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
idea/tests/testData/refactoring/inline/lambdaExpression/lambdaWithReceiverAsParameter3.kt
JetBrains
278,369,660
false
null
// WITH_RUNTIME class Chain fun complicate(chain: Chain) { val vra = ((<caret>{ chain: Chain, fn: Chain.() -> Chain -> chain.fn() }))(chain){ this.also { println(it) } } }
1
null
30
82
cc81d7505bc3e9ad503d706998ae8026c067e838
188
intellij-kotlin
Apache License 2.0
android/src/com/android/tools/idea/run/configuration/AndroidWatchFaceConfiguration.kt
JetBrains
60,701,247
false
{"Kotlin": 53054415, "Java": 43443054, "Starlark": 1332164, "HTML": 1218044, "C++": 507658, "Python": 191041, "C": 71660, "Lex": 70302, "NSIS": 58238, "AIDL": 35382, "Shell": 29838, "CMake": 27103, "JavaScript": 18437, "Smali": 7580, "Batchfile": 7357, "RenderScript": 4411, "Clean": 3522, "Makefile": 2495, "IDL": 19}
/* * Copyright (C) 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.idea.run.configuration import com.android.tools.idea.run.ApkProvider import com.android.tools.idea.run.ApplicationIdProvider import com.android.tools.idea.run.configuration.execution.AndroidWatchFaceConfigurationExecutor import com.android.tools.idea.run.configuration.execution.WatchFaceLaunchOptions import com.android.tools.idea.run.editor.DeployTarget import com.intellij.execution.configurations.ConfigurationFactory import com.intellij.execution.configurations.ConfigurationTypeBase import com.intellij.execution.runners.ExecutionEnvironment import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.Project import icons.StudioIcons import org.jetbrains.android.util.AndroidBundle class AndroidWatchFaceConfigurationType : ConfigurationTypeBase( ID, AndroidBundle.message("android.watchface.configuration.type.name"), AndroidBundle.message("android.run.configuration.type.description"), StudioIcons.Wear.WATCH_FACE_RUN_CONFIG ), DumbAware { companion object { const val ID = "AndroidWatchFaceConfigurationType" } init { addFactory(object : ConfigurationFactory(this) { override fun getId() = "AndroidWatchFaceConfigurationFactory" override fun createTemplateConfiguration(project: Project) = AndroidWatchFaceConfiguration(project, this) }) } } class AndroidWatchFaceConfiguration(project: Project, factory: ConfigurationFactory) : AndroidWearConfiguration(project, factory) { override val componentLaunchOptions = WatchFaceLaunchOptions() override fun getExecutor( environment: ExecutionEnvironment, deployTarget: DeployTarget, appRunSettings: AppRunSettings, applicationIdProvider: ApplicationIdProvider, apkProvider: ApkProvider ) = AndroidWatchFaceConfigurationExecutor(environment, deployTarget, appRunSettings, applicationIdProvider, apkProvider) }
5
Kotlin
230
948
10110983c7e784122d94c7467e9d243aba943bf4
2,514
android
Apache License 2.0
brd-android/registration/src/main/java/com/fabriik/registration/ui/views/EnterCodeView.kt
fabriik
489,117,365
false
null
package com.fabriik.registration.ui.views import android.content.Context import android.graphics.* import android.text.InputFilter import android.text.InputType import android.util.AttributeSet import android.view.inputmethod.EditorInfo import androidx.appcompat.widget.AppCompatEditText import androidx.core.content.ContextCompat import androidx.core.content.res.ResourcesCompat import androidx.core.view.setPadding import com.fabriik.common.utils.dp import com.fabriik.common.utils.sp import com.fabriik.registration.R class EnterCodeView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null ) : AppCompatEditText(context, attrs) { private val pinLength = 6 private val boxRadius = 12.dp.toFloat() private val strokeWidth = 1.dp.toFloat() private val marginBetweenBoxes = 8.dp.toFloat() private val paintText = Paint().apply { color = ContextCompat.getColor(context, R.color.light_text_01) textSize = 16.sp.toFloat() typeface = ResourcesCompat.getFont(context, R.font.roboto_medium) } private val paintBackgroundDefault = Paint().apply { strokeWidth = [email protected] style = Paint.Style.STROKE color = ContextCompat.getColor(context, R.color.light_outline_01) } private val paintBackgroundError = Paint().apply { strokeWidth = [email protected] style = Paint.Style.STROKE color = ContextCompat.getColor(context, R.color.light_error) } private val textBounds = Rect() private var boxes = arrayOf<RectF>() private var showErrorState: Boolean = false init { setPadding(2.dp) setBackgroundResource(0) isCursorVisible = false imeOptions = EditorInfo.IME_ACTION_DONE filters = arrayOf(InputFilter.LengthFilter(pinLength)) inputType = InputType.TYPE_CLASS_NUMBER } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) val availableWidth = measuredWidth - paddingEnd - paddingStart val boxSize = (availableWidth - marginBetweenBoxes * (pinLength - 1)) / pinLength val newHeight = boxSize + paddingTop + paddingBottom // change height to create square rectangles setMeasuredDimension( measuredWidth, newHeight.toInt() ) initBoxes(boxSize) } private fun initBoxes(boxSize: Float) { boxes = IntRange(0, pinLength) .map { val startX = paddingStart + (boxSize + marginBetweenBoxes) * it RectF( startX, paddingTop.toFloat(), startX + boxSize, paddingTop + boxSize ) } .toTypedArray() } override fun onDraw(canvas: Canvas) { // draw boxes for (box in boxes) { canvas.drawRoundRect( box, boxRadius, boxRadius, if (showErrorState) paintBackgroundError else paintBackgroundDefault ) } // draw text for (index in 0 until length()) { val letter = getPin()[index].toString() val boxBounds = boxes[index] paintText.getTextBounds(letter, 0, 1, textBounds) canvas.drawText( letter, 0, 1, boxBounds.centerX() - textBounds.width() / 2, boxBounds.centerY() + textBounds.height() / 2, paintText ) } } fun getPin() = text.toString() fun setErrorState(error: Boolean) { showErrorState = error invalidate() } }
2
null
1
1
8894f5c38203c64e48242dae9ae9344ed4b2a61f
3,692
wallet-android
MIT License
src/test/kotlin/io/github/tobi/laa/spring/boot/embedded/redis/server/CustomCustomizerTest.kt
tobias-laa
755,903,685
false
{"Kotlin": 73970}
package io.github.tobi.laa.spring.boot.embedded.redis.server import io.github.tobi.laa.spring.boot.embedded.redis.IntegrationTest import io.github.tobi.laa.spring.boot.embedded.redis.RedisTests import io.github.tobi.laa.spring.boot.embedded.redis.server.CustomCustomizerTest.* import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import redis.embedded.core.RedisServerBuilder private const val TEST_PORT = 10000 @IntegrationTest @EmbeddedRedisServer( customizer = [ WillBeIgnored::class, SetsPortToTestPort::class, SetsBindToLoopbackIpv4::class, SetsProtectedMode::class] ) @DisplayName("Using @EmbeddedRedisServer with several customizers") internal open class CustomCustomizerTest { @Autowired private lateinit var given: RedisTests @Test @DisplayName("RedisProperties should have the customized values") fun redisPropertiesShouldHaveCustomizedValues() { given.nothing() .whenDoingNothing() .then().redisProperties() .shouldBeStandalone().and() .shouldHaveHost("127.0.0.1").and() .shouldHavePort(TEST_PORT) } @Test @DisplayName("It should be possible to write to Redis and the data should be available afterwards") fun givenRandomTestdata_writingToRedis_dataShouldBeAvailable() { given.randomTestdata() .whenRedis().isBeingWrittenTo() .then().redis().shouldContainTheTestdata() } @Test @DisplayName("Settings from customizer should have been applied to the embedded Redis server") fun settingsFromCustomizerShouldHaveBeenApplied() { given.nothing() .whenDoingNothing() .then().embeddedRedis() .shouldHaveConfig().thatContainsDirective("protected-mode", "yes") } class WillBeIgnored : RedisServerCustomizer { override fun accept(builder: RedisServerBuilder, config: EmbeddedRedisServer) { builder.port(1) builder.bind("zombo.com") } } class SetsPortToTestPort : RedisServerCustomizer { override fun accept(builder: RedisServerBuilder, config: EmbeddedRedisServer) { builder.port(TEST_PORT) } } class SetsBindToLoopbackIpv4 : RedisServerCustomizer { override fun accept(builder: RedisServerBuilder, config: EmbeddedRedisServer) { builder.bind("127.0.0.1") } } class SetsProtectedMode : RedisServerCustomizer { override fun accept(builder: RedisServerBuilder, config: EmbeddedRedisServer) { builder.setting("protected-mode yes") } } }
4
Kotlin
0
2
caa06dbdeee5d21a6a45c4826138ebc14a53c61c
2,720
spring-boot-embedded-redis
Apache License 2.0
app/src/main/java/com/vitor238/popcorn/data/model/NowPlaying.kt
Vitor238
308,182,063
false
null
package com.vitor238.cartalog.data.model import com.squareup.moshi.Json import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class NowPlaying( val id: Int, @Json(name = "poster_path") val posterPath: String?, @Json(name = "release_date") val releaseDate: String?, val title: String?, )
0
Kotlin
1
1
9207416012652d6093b9f741af71e8017781d7cd
335
Popcorn
Apache License 2.0
InkBetterAndroidViews/src/main/java/com/inlacou/inkbetterandroidviews/listenerstoflow/OnLongTouchIncrementFiringSpeedFlow.kt
inlacou
400,138,100
false
null
package com.inlacou.inkbetterandroidviews.listenerstoflow import android.view.MotionEvent import android.view.View import io.reactivex.rxjava3.core.ObservableEmitter import io.reactivex.rxjava3.core.ObservableOnSubscribe import kotlinx.coroutines.channels.ProducerScope import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.flow.callbackFlow import kotlinx.coroutines.flow.flow import timber.log.Timber import java.util.concurrent.Flow class OnLongTouchIncrementFiringSpeedFlow constructor(private val view: View, breakpoints: List<Pair<Int, Int>>? = null) { private var breakpointsFinal = breakpoints ?: listOf(Pair(1200, 400), Pair(3000, 200), Pair(6000, 100), Pair(12000, 50), Pair(18000, 25)) private var subscriber: ProducerScope<Long>? = null private var downTimeStamp = 0L private var currentIndex = 0 var thread = newIntervalThread() private fun newIntervalThread() = IntervalThread(breakpointsFinal[0].first.toLong()) { thread, counter, elapsedTime -> subscriber.let { if(it!=null){ it.trySend(counter) if(breakpointsFinal.size>currentIndex+1 && elapsedTime>=breakpointsFinal[currentIndex+1].first) { currentIndex += 1 thread.periodicity = breakpointsFinal[currentIndex].second.toLong() } true }else{ false } } } fun create() = callbackFlow<Long> { subscriber = this view.setOnTouchListener { v, event -> when (event.actionMasked) { MotionEvent.ACTION_DOWN -> { Timber.d("$view ACTION DOWN | isPressed: ${view.isPressed}") downTimeStamp = System.currentTimeMillis() thread.stop() currentIndex = 0 thread = newIntervalThread() thread.start() if(!view.isPressed) view.isPressed = true true //hold the event } MotionEvent.ACTION_UP -> { Timber.d("$view ACTION UP") thread.stop() currentIndex = 0 view.isPressed = false false //release the event } MotionEvent.ACTION_CANCEL -> { Timber.w("$view ACTION CANCEL") false } else -> { false } /*release the event*/ } } awaitClose { view.setOnTouchListener(null) } } } class IntervalThread(startingPeriodicity: Long, val callback: (thread: IntervalThread, counter: Long, elapsedTime: Long) -> Boolean) { private var counter = 1L private var accumulator = 0L var periodicity = startingPeriodicity private var running = false private var thread: Thread = Thread { Timber.d("begin") while(running) { Timber.d("iteration $counter") accumulator += periodicity if(callback.invoke(this, counter, accumulator)) counter++ else running = false Thread.sleep(periodicity) } Timber.d("end") } fun start() { Timber.d("start") running = true thread.start() } fun stop() { Timber.d("stop") running = false } }
0
Kotlin
0
0
6fc908d6963f07e0c5d3d2836fcc28143fe58674
2,803
InkCommons
MIT License
tools/resource-cli/src/commonMain/kotlin/io/matthewnelson/resource/cli/Main.kt
05nelsonm
734,754,650
false
{"Kotlin": 322914, "Shell": 1152, "Java": 1086, "JavaScript": 14}
/* * Copyright (c) 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ package io.matthewnelson.resource.cli import io.matthewnelson.cli.core.CLIRuntime import io.matthewnelson.cli.core.OptQuiet import io.matthewnelson.cli.core.OptQuiet.Companion.quietOption import io.matthewnelson.resource.cli.internal.ResourceWriter import io.matthewnelson.resource.cli.internal.write import kotlinx.cli.ArgParser import kotlinx.cli.ArgType public fun main(args: Array<String>) { val runtime = KMPResourceCLIRuntime() runtime.run(args) val resourcePath = ResourceWriter( packageName = runtime.packageName, pathSourceSet = runtime.pathSourceSet, pathFile = runtime.pathFile ).write() if (runtime.quietOpt) return println("transformed '${runtime.pathFile}' -> '$resourcePath'") } private class KMPResourceCLIRuntime: CLIRuntime(parser = ArgParser(PROGRAM_NAME.lowercase())), OptQuiet { private companion object { private const val PROGRAM_NAME = "Resource-CLI" } val packageName by parser.argument( type = ArgType.String, fullName = "package-name", description = "The package name for the resource (e.g. io.matthewnelson.kmp.tor.binary)" ) val pathSourceSet by parser.argument( type = ArgType.String, fullName = "path-source-set", description = "The absolute path to the target source set to place the resource_{name}.kt file" ) val pathFile by parser.argument( type = ArgType.String, fullName = "path-file", description = "The absolute path of the file to transform into a resource_{name}.kt file" ) override val quietOpt: Boolean by parser.quietOption() override fun printHeader() { val versionName = "0.1.0" val url = "https://github.com/05nelsonm/kmp-tor-binary/tree/master/tools/kmp-resource-cli" println(""" $PROGRAM_NAME v$versionName Copyright (C) 2023 <NAME> Apache License, Version 2.0 Utility for converting files to resource_{name}.kt files since non-jvm Kotlin Multiplatform source sets do not have a way to package and distribute resources. Project: $url """.trimIndent()) } }
13
Kotlin
0
1
54b305c97e9b5c8a959a65d4d1ee378afb3dd8f6
2,820
kmp-tor-resource
Apache License 2.0
src/main/kotlin/com/bsuir/hrm/dataanalyzer/service/impl/StatisticsServiceImpl.kt
herman2lv
640,611,590
false
{"Kotlin": 44194, "JavaScript": 21655, "HTML": 3170, "CSS": 1844, "Dockerfile": 847, "PowerShell": 136}
package com.bsuir.hrm.dataanalyzer.service.impl import com.bsuir.hrm.dataanalyzer.service.dto.DataSeries import com.bsuir.hrm.dataanalyzer.service.dto.Dataset import com.bsuir.hrm.dataanalyzer.data.entity.Product import com.bsuir.hrm.dataanalyzer.service.StatisticsService import com.bsuir.hrm.dataanalyzer.service.dto.ChartPropertiesDto import org.slf4j.Logger import org.slf4j.LoggerFactory import org.springframework.stereotype.Service import java.math.BigDecimal import java.time.LocalDate private val log: Logger = LoggerFactory.getLogger(StatisticsServiceImpl::class.java) @Service class StatisticsServiceImpl : StatisticsService { override fun getInflationRateByMonths(products: List<Product>, properties: ChartPropertiesDto): Map<String, Dataset> { val sumByMonth: MutableMap<LocalDate, Sum> = groupSumByDates(products) val labels: MutableList<String> = mutableListOf() val seriesAverage = getSeriesAverage(properties, sumByMonth, labels) val seriesInflation = getSeriesInflation(seriesAverage) val datasetInflation = Dataset(labels) datasetInflation.addDataSeries(seriesInflation) val datasetAverage = Dataset(labels) if (!properties.group) { val mapByCategory: MutableMap<String, MutableList<Product>> = mapByCategory(products) mapByCategory.forEach { entry -> val sumByMonthCategory: MutableMap<LocalDate, Sum> = groupSumByDates(entry.value) val seriesAverageCategory = getSeriesAverage(properties, sumByMonthCategory) datasetAverage.addDataSeries(seriesAverageCategory) } } else { datasetAverage.addDataSeries(seriesAverage) } log.debug("Datasets to be returned: {}, {}", datasetAverage, datasetInflation) return mapOf(Pair("inflation", datasetInflation), Pair("average", datasetAverage)) } private fun mapByCategory(products: List<Product>): MutableMap<String, MutableList<Product>> { val mapByCategory: MutableMap<String, MutableList<Product>> = mutableMapOf() products.forEach { product -> mapByCategory.merge(product.category, mutableListOf(product)) { old, new -> old.addAll(new) old } } return mapByCategory } private fun getSeriesInflation(seriesAverage: DataSeries): DataSeries { val seriesInflation = DataSeries("Inflation Rate") var prevAverage = seriesAverage.getValues()[0] for (average in seriesAverage.getValues()) { val inflationRate = (average - prevAverage) / prevAverage seriesInflation.addValue(inflationRate) prevAverage = average } return seriesInflation } private fun getSeriesAverage( properties: ChartPropertiesDto, sumByMonth: MutableMap<LocalDate, Sum>, labels: MutableList<String>? = null ): DataSeries { val seriesAverage = DataSeries("AveragePrice") var date = properties.start.withDayOfMonth(1) while (date.isBefore(properties.end) || date.isEqual(properties.end)) { val key = date.withDayOfMonth(1) date = date.plusMonths(1) val monthSum = sumByMonth[key] ?: continue val monthAverage = monthSum.amount / monthSum.count.toBigDecimal() labels?.add("${key.month.toString().substring(0..2)}-${key.year}") seriesAverage.addValue(monthAverage) } return seriesAverage } private fun groupSumByDates(products: List<Product>): MutableMap<LocalDate, Sum> { val monthly: MutableMap<LocalDate, Sum> = mutableMapOf() products.forEach { product -> product.prices.forEach { priceEntry -> monthly.merge(priceEntry.date.withDayOfMonth(1), Sum(1, priceEntry.price.amount)) { old, new -> Sum(old.count + new.count, old.amount + new.amount) } } } return monthly } private data class Sum(val count: Int, val amount: BigDecimal) }
0
Kotlin
0
1
8f0a94f9124edbfb1309e589dae4bc24ec3a9537
4,113
market-analyzer-lab
Apache License 2.0
domain/src/main/java/com/example/domain/entity/pharmacySendRequest/FindNearstPharmacy.kt
YoussefmSaber
595,215,406
false
null
package com.example.domain.entity.pharmacySendRequest import android.os.Parcelable import kotlinx.parcelize.Parcelize @Parcelize data class FindNearestPharmacy( val products: List<String> ): Parcelable
0
Kotlin
1
4
a4931c0edcc76e9b8b5876cb272beadcfcbd1165
207
Eshfeeny
MIT License
domain/src/main/java/com/example/domain/entity/pharmacySendRequest/FindNearstPharmacy.kt
YoussefmSaber
595,215,406
false
null
package com.example.domain.entity.pharmacySendRequest import android.os.Parcelable import kotlinx.parcelize.Parcelize @Parcelize data class FindNearestPharmacy( val products: List<String> ): Parcelable
0
Kotlin
1
4
a4931c0edcc76e9b8b5876cb272beadcfcbd1165
207
Eshfeeny
MIT License
src/main/kotlin/io/opencui/sessionmanager/SessionManager.kt
opencui
550,521,089
false
{"Kotlin": 1001003, "Shell": 44}
package io.opencui.sessionmanager import io.opencui.core.* import io.opencui.core.da.DialogAct import io.opencui.core.da.UserDefinedInform import io.opencui.core.user.IUserIdentifier import io.opencui.kvstore.IKVStore import io.opencui.logging.ILogger import org.slf4j.Logger import org.slf4j.LoggerFactory /** * We assume that at no circumstances that user will access more than one language at the same time. */ interface ISessionStore { fun getSession(channel: String, id:String, botInfo: BotInfo): UserSession? fun deleteSession(channel: String, id:String, botInfo: BotInfo) fun updateSession(channel: String, id: String, botInfo: BotInfo, session: UserSession) fun saveSession(channel: String, id: String, botInfo: BotInfo, session: UserSession) companion object { fun key(channel: String, id:String, botInfo: BotInfo): String { // We do not use language as part of key so that multiple language support is easier. return "${botInfo.fullName}:s:${channel}:${id}" } } } // Some time, we need to save the bot related information across different versions for all users. interface IBotStore: IKVStore { val botInfo: BotInfo } /** * The conversion state need to be saved in UserSession so that the same customer can be served * by different instances if we need to. Consider this as short term memory for the conversation, * we can have long term memory about what user have consumed (but may not include how user got * these services). * * So we need two different interfaces: at dispatcher level, we manage the support channel as * well, at session manager level, we simply respond to user query. Of course, we can reply * with messages that goes to support as well. * * SessionManager provide interface that wraps a particular version of agent, so that it is easy * for both generic and channel specific rest controller to connect user with bot. * This is useful so that different restful api (for different channel) can reuse the same * session manager. * * To support try it now, we need to return response from all channels. We add targetChannels * if it is null, we use the source channels, if it is empty list, we return all channels, * otherwise, we return the response for every channel specified. * * For now, bot takes in raw text as query, and returns the raw string that contains the structured * messages. * */ class SessionManager(private val sessionStore: ISessionStore, val botStore: IBotStore? = null) { private val dm: DialogManager = DialogManager() fun getUserSession(channel: IUserIdentifier, botInfo: BotInfo): UserSession? { // We try to deserialize the saved session, but if we can not, return null as if we // did not see this user before. return try { sessionStore.getSession(channel.channelId(), channel.userId!!, botInfo) } catch (e: Exception) { sessionStore.deleteSession(channel.channelId(), channel.userId!!, botInfo) null } } fun createUserSession(rawUser: IUserIdentifier, botInfo: BotInfo): UserSession { sessionStore.deleteSession(rawUser.channelId(), rawUser.userId!!, botInfo) val bot = ChatbotLoader.findChatbot(botInfo) val createdSession = bot.createUserSession(rawUser.channelType!!, rawUser.userId!!, channelLabel = rawUser.channelLabel) // Try to use the info from message. createdSession.isVerfied = rawUser.isVerfied // If the channel had extra way to get user identifier, use that. val lchannel = if (rawUser.channelLabel != null) bot.getChannel(rawUser.channelLabel!!) else null val identifier = if (lchannel != null && rawUser.userId != null) lchannel!!.getIdentifier(botInfo, rawUser.userId!!) else null if (identifier != null) { createdSession.name = identifier.name createdSession.phone = identifier.phone createdSession.email = identifier.email } else { createdSession.name = rawUser.name createdSession.phone = rawUser.phone createdSession.email = rawUser.email } sessionStore.saveSession(rawUser.channelId(), rawUser.userId!!, botInfo, createdSession) logger.info("create session with bot version: ${createdSession.chatbot?.agentBranch}") return createdSession } /** * This deletes the corresponding user session so that next conversation starts from scratch. * Of course the user history (services enjoyed) should be saved somehow. */ fun deleteUserSession(channel: IUserIdentifier, botInfo: BotInfo) { sessionStore.deleteSession(channel.channelId(), channel.userId!!, botInfo) } fun updateUserSession(channel: IUserIdentifier, botInfo: BotInfo, session: UserSession) { sessionStore.updateSession(channel.channelId(), channel.userId!!, botInfo, session) } /** * This method will be called when contact submit an query along with events (should we allow this?) * And we need to come up with reply to move the conversation forward. * * event: the extra signal encoded. * * session: if the bot can handle it, we should keep botOwn as true, if bot can not, it should * set the botOwn as false, and inform support. * * channel: the format that is expected. */ fun getReply( session: UserSession, query: String, targetChannels: List<String>, events: List<FrameEvent> = emptyList() ): Map<String, List<String>> { assert(targetChannels.isNotEmpty()) session.targetChannel = targetChannels val turnAndActs = dm.response(query, events, session) val responses = turnAndActs.second val logger = session.chatbot!!.getExtension<ILogger>() if (logger != null) { // first update the turn so that we know who this user is talking too val turn = turnAndActs.first turn.channelType = session.channelType!! turn.channelLabel = session.channelLabel!! turn.userId = session.userId!! // we then log the turn logger.log(turn) } updateUserSession(session.userIdentifier, session.botInfo, session) return convertDialogActsToText(session, responses, session.targetChannel) } /** * This the place where we can remove extra prompt if we need to. */ private fun convertDialogActsToText(session: UserSession, responses: List<DialogAct>, targetChannels: List<String>): Map<String, List<String>> { val rewrittenResponses = session.rewriteDialogAct(responses) val dialogActPairs = rewrittenResponses.partition { it is UserDefinedInform<*> && it.frameType == "io.opencui.core.System1"} val dialogActs = replaceWithSystem1(dialogActPairs.second, dialogActPairs.first) return targetChannels.associateWith { k -> dialogActs.map {"""${if (k == SideEffect.RESTFUL) "[${it::class.simpleName}]" else ""}${it.templates.pick(k)}"""} } } private fun isDonotUnderstand(it: DialogAct): Boolean { return it is UserDefinedInform<*> && it.frameType == "io.opencui.core.IDonotGetIt" } private fun replaceWithSystem1(orig: List<DialogAct>, system1: List<DialogAct>) : List<DialogAct> { if (system1.isEmpty()) return orig val deduped = orig.removeDuplicate { isDonotUnderstand(it) } val res = mutableListOf<DialogAct>() for (it in deduped) { if (isDonotUnderstand(it)) { res.addAll(system1) } else { res.add(it) } } return res } /** * Return the best implementation for given agentId. */ fun getAgent(botInfo: BotInfo): IChatbot { return ChatbotLoader.findChatbot(botInfo) } companion object { private val master = "master" private val logger: Logger = LoggerFactory.getLogger(SessionManager::class.java) } }
1
Kotlin
1
0
f046fd91f38e6bcb7330e441d996e122fac9f18a
8,082
structi
Apache License 2.0
app/src/main/java/app/tivi/home/discover/DiscoverViewState.kt
qwertyfinger
157,608,523
true
{"Kotlin": 616309, "Shell": 2252, "Java": 737}
/* * Copyright 2017 Google, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package app.tivi.home.discover import app.tivi.data.entities.SearchResults import app.tivi.data.entities.TraktUser import app.tivi.data.resultentities.PopularEntryWithShow import app.tivi.data.resultentities.TrendingEntryWithShow import app.tivi.tmdb.TmdbImageUrlProvider import app.tivi.trakt.TraktAuthState import com.airbnb.mvrx.MvRxState data class DiscoverViewState( val isSearchOpen: Boolean = false, val searchResults: SearchResults? = null, val trendingItems: List<TrendingEntryWithShow> = emptyList(), val popularItems: List<PopularEntryWithShow> = emptyList(), val tmdbImageUrlProvider: TmdbImageUrlProvider = TmdbImageUrlProvider(), val isLoading: Boolean = false, val user: TraktUser? = null, val authState: TraktAuthState = TraktAuthState.LOGGED_OUT ) : MvRxState
0
Kotlin
1
0
f7a618119947cf52fff478809ad3d183c2ae1112
1,407
tivi
Apache License 2.0
app/src/androidTest/java/com/team28/thehiker/LanguageIntegrationTest.kt
sw21-tug
350,774,901
false
null
package com.team28.thehiker import androidx.test.core.app.ActivityScenario import androidx.test.espresso.Espresso.onView import androidx.test.espresso.action.ViewActions import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.contrib.DrawerActions import androidx.test.espresso.matcher.RootMatchers import androidx.test.espresso.matcher.ViewMatchers.* import androidx.test.ext.junit.rules.ActivityScenarioRule import androidx.test.ext.junit.runners.AndroidJUnit4 import com.team28.thehiker.sharedpreferencehandler.SharedPreferenceHandler import com.team28.thehiker.language.LanguageSelector import org.junit.Assert import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class LanguageIntegrationTest { @get:Rule var activityRule = ActivityScenarioRule(MainActivity::class.java) @Test fun switchLanguageToRU() { switchLanguage(R.string.russian, "ru", "ru-RU") } @Test fun switchLanguageToEN() { switchLanguage(R.string.english, "en", "en-EN") } @Test fun checkLanguageSwitchPersistsAppRestart(){ //ensure app is in russian language switchLanguage(R.string.russian, "ru", "ru-RU") //close the app activityRule.scenario.onActivity { //mocking an app reset this way since we didn't find a better way to fully kill the app during testing //this just updates the current configuration but not the shared preferences we want to test LanguageSelector.setLocaleToEnglish(it) } activityRule.scenario.close() // In the SplashscreenActivity the app should reload the shared preferences and update the locale config val scenario = ActivityScenario.launch(SplashscreenActivity::class.java) scenario.onActivity { val sharedPreferenceHandler = SharedPreferenceHandler() Assert.assertEquals("ru", sharedPreferenceHandler.getLocalizationString(it)) Assert.assertEquals("ru-RU", it.resources.configuration.locales[0].toLanguageTag()) } } private fun switchLanguage(languageStringID : Int, sharedPreferenceTag : String, languageTag : String) { onView(withId(R.id.drawerLayout)).perform(DrawerActions.open()) onView(withId(R.id.language)).perform(ViewActions.click()) onView(withText(languageStringID)).inRoot(RootMatchers.isPlatformPopup()).perform(ViewActions.click()) //wait for the ui to update Thread.sleep(2000) lateinit var altitudeLabel : String lateinit var findMeLabel : String activityRule.scenario.onActivity { val sharedPreferenceHandler = SharedPreferenceHandler() Assert.assertEquals(sharedPreferenceTag, sharedPreferenceHandler.getLocalizationString(it)) Assert.assertEquals(languageTag, it.resources.configuration.locales[0].toLanguageTag()) altitudeLabel = it.resources.getString(R.string.altitude) findMeLabel = it.resources.getString(R.string.find_me) } onView(withId(R.id.btn_altitude)).check(matches(withText(altitudeLabel))) onView(withId(R.id.btn_position_on_map)).check(matches(withText(findMeLabel))) } }
1
Kotlin
9
7
eb1bdb8844c55538cac867b4cc987c9d313a081b
3,280
Team_28
MIT License
build-logic/src/main/kotlin/VersionTuple.kt
projectnessie
254,450,741
false
null
/* * Copyright (C) 2023 Dremio * * 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. */ import java.nio.file.Files import java.nio.file.Path import java.util.regex.Pattern /** Represents a version tuple with mandatory major, minor and patch numbers and snapshot-flag. */ data class VersionTuple(val major: Int, val minor: Int, val patch: Int, val snapshot: Boolean) : Comparable<VersionTuple> { companion object Factory { val pattern = Pattern.compile( "^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?\$" ) fun fromFile(file: Path): VersionTuple = create(Files.readString(file).trim()) @JvmStatic fun create(string: String): VersionTuple { val matcher = pattern.matcher(string) if (!matcher.matches()) { throw IllegalArgumentException("'$string' is not a valid version string") } val major = matcher.group(1) val minor = matcher.group(2) val patch = matcher.group(3) val prerelease = matcher.group(4) val buildmetadata = matcher.group(5) if (buildmetadata != null) { throw IllegalArgumentException("Build metadata not supported") } val snapshot = "SNAPSHOT" == prerelease if (prerelease != null && !snapshot) { throw IllegalArgumentException( "Only SNAPSHOT prerelease supported, but $prerelease != SNAPSHOT" ) } return VersionTuple(major.toInt(), minor.toInt(), patch.toInt(), snapshot) } } fun bumpMajor(): VersionTuple = VersionTuple(major + 1, 0, 0, false) fun bumpMinor(): VersionTuple = VersionTuple(major, minor + 1, 0, false) fun bumpPatch(): VersionTuple = VersionTuple(major, minor, patch + 1, false) fun asSnapshot(): VersionTuple = VersionTuple(major, minor, patch, true) fun asRelease(): VersionTuple = VersionTuple(major, minor, patch, false) fun writeToFile(file: Path) = Files.writeString(file, toString()) override fun compareTo(other: VersionTuple): Int { var cmp: Int cmp = major.compareTo(other.major) if (cmp != 0) { return cmp } cmp = minor.compareTo(other.minor) if (cmp != 0) { return cmp } cmp = patch.compareTo(other.patch) if (cmp != 0) { return cmp } if (snapshot == other.snapshot) { return 0 } return if (snapshot) -1 else 1 } override fun toString(): String { return "$major.$minor.$patch${if (snapshot) "-SNAPSHOT" else ""}" } }
14
null
13
820
91f251bb9e9721bd6e30f1bb568c904660506212
3,100
nessie
Apache License 2.0
build-logic/src/main/kotlin/VersionTuple.kt
projectnessie
254,450,741
false
null
/* * Copyright (C) 2023 Dremio * * 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. */ import java.nio.file.Files import java.nio.file.Path import java.util.regex.Pattern /** Represents a version tuple with mandatory major, minor and patch numbers and snapshot-flag. */ data class VersionTuple(val major: Int, val minor: Int, val patch: Int, val snapshot: Boolean) : Comparable<VersionTuple> { companion object Factory { val pattern = Pattern.compile( "^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?\$" ) fun fromFile(file: Path): VersionTuple = create(Files.readString(file).trim()) @JvmStatic fun create(string: String): VersionTuple { val matcher = pattern.matcher(string) if (!matcher.matches()) { throw IllegalArgumentException("'$string' is not a valid version string") } val major = matcher.group(1) val minor = matcher.group(2) val patch = matcher.group(3) val prerelease = matcher.group(4) val buildmetadata = matcher.group(5) if (buildmetadata != null) { throw IllegalArgumentException("Build metadata not supported") } val snapshot = "SNAPSHOT" == prerelease if (prerelease != null && !snapshot) { throw IllegalArgumentException( "Only SNAPSHOT prerelease supported, but $prerelease != SNAPSHOT" ) } return VersionTuple(major.toInt(), minor.toInt(), patch.toInt(), snapshot) } } fun bumpMajor(): VersionTuple = VersionTuple(major + 1, 0, 0, false) fun bumpMinor(): VersionTuple = VersionTuple(major, minor + 1, 0, false) fun bumpPatch(): VersionTuple = VersionTuple(major, minor, patch + 1, false) fun asSnapshot(): VersionTuple = VersionTuple(major, minor, patch, true) fun asRelease(): VersionTuple = VersionTuple(major, minor, patch, false) fun writeToFile(file: Path) = Files.writeString(file, toString()) override fun compareTo(other: VersionTuple): Int { var cmp: Int cmp = major.compareTo(other.major) if (cmp != 0) { return cmp } cmp = minor.compareTo(other.minor) if (cmp != 0) { return cmp } cmp = patch.compareTo(other.patch) if (cmp != 0) { return cmp } if (snapshot == other.snapshot) { return 0 } return if (snapshot) -1 else 1 } override fun toString(): String { return "$major.$minor.$patch${if (snapshot) "-SNAPSHOT" else ""}" } }
14
null
13
820
91f251bb9e9721bd6e30f1bb568c904660506212
3,100
nessie
Apache License 2.0
app/src/main/java/dev/twelveoclock/riverhacks/MainActivity.kt
camdenorrb
494,633,525
false
null
package dev.twelveoclock.riverhacks import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.MaterialTheme import androidx.compose.material.Surface import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import dev.twelveoclock.riverhacks.ui.theme.RiverHacksTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { RiverHacksTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colors.background ) { Greeting("Android") } } } } } @Composable fun Greeting(name: String) { Column(Modifier.verticalScroll(rememberScrollState())) { repeat(100) { Row { Text(text = "Hello $name!") } } } } @Preview(showBackground = true) @Composable fun DefaultPreview() { RiverHacksTheme { Greeting("Android") } }
0
Kotlin
0
0
f43746294bf851f6c3e13159e9d228190b777b9a
1,591
RiverHacksApp
MIT License
app/src/main/kotlin/com/absinthe/libchecker/view/detail/LibDetailBottomSheetView.kt
zhaobozhen
248,400,799
false
null
package com.absinthe.libchecker.view.detail import android.content.Context import android.content.res.ColorStateList import android.text.method.LinkMovementMethod import android.util.TypedValue import android.view.ContextThemeWrapper import android.view.Gravity import android.view.ViewGroup import android.widget.FrameLayout import android.widget.ViewFlipper import androidx.appcompat.widget.AppCompatImageView import androidx.appcompat.widget.AppCompatTextView import androidx.core.text.HtmlCompat import androidx.core.view.marginStart import androidx.core.view.marginTop import com.absinthe.libchecker.R import com.absinthe.libchecker.api.ApiManager import com.absinthe.libchecker.utils.extensions.getColorByAttr import com.absinthe.libchecker.utils.extensions.getResourceIdByAttr import com.absinthe.libchecker.view.AViewGroup import com.absinthe.libchecker.view.app.BottomSheetHeaderView import com.absinthe.libchecker.view.app.IHeaderView import com.airbnb.lottie.LottieAnimationView import com.airbnb.lottie.LottieDrawable const val VF_LOADING = 0 const val VF_CONTENT = 1 const val VF_NOT_FOUND = 2 class LibDetailBottomSheetView(context: Context) : AViewGroup(context), IHeaderView { private val header = BottomSheetHeaderView(context).apply { layoutParams = LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) title.text = context.getString(R.string.lib_detail_dialog_title) } val icon = AppCompatImageView(context).apply { val iconSize = 48.dp layoutParams = LayoutParams(iconSize, iconSize).also { it.topMargin = 4.dp } setBackgroundResource(R.drawable.bg_gray_circle) } val title = AppCompatTextView( ContextThemeWrapper( context, R.style.TextView_SansSerifCondensedMedium ) ).apply { layoutParams = LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT ).also { it.topMargin = 4.dp } gravity = Gravity.CENTER setTextSize(TypedValue.COMPLEX_UNIT_SP, 14f) } val viewFlipper = ViewFlipper(context).apply { layoutParams = LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) setInAnimation(context, R.anim.anim_fade_in) setOutAnimation(context, R.anim.anim_fade_out) } private val loading = LottieAnimationView(context).apply { layoutParams = FrameLayout.LayoutParams(200.dp, 200.dp).also { it.gravity = Gravity.CENTER } imageAssetsFolder = "/" repeatCount = LottieDrawable.INFINITE setAnimation("lib_detail_rocket.json") } private val notFoundView = NotFoundView(context).apply { layoutParams = FrameLayout.LayoutParams( FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT ).also { it.gravity = Gravity.CENTER } } val libDetailContentView = LibDetailContentView(context).apply { layoutParams = FrameLayout.LayoutParams( FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT ) } init { val padding = 24.dp setPadding(padding, 16.dp, padding, padding) addView(header) addView(icon) addView(title) addView(viewFlipper) viewFlipper.addView(loading) viewFlipper.addView(libDetailContentView) viewFlipper.addView(notFoundView) } override fun onAttachedToWindow() { super.onAttachedToWindow() loading.playAnimation() } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) header.measure( (measuredWidth - paddingStart - paddingEnd).toExactlyMeasureSpec(), header.defaultHeightMeasureSpec(this) ) icon.autoMeasure() title.measure( (measuredWidth - paddingStart - paddingEnd).toExactlyMeasureSpec(), title.defaultHeightMeasureSpec(this) ) viewFlipper.measure( (measuredWidth - paddingStart - paddingEnd).toExactlyMeasureSpec(), viewFlipper.defaultHeightMeasureSpec(this) ) setMeasuredDimension( measuredWidth, paddingTop + paddingBottom + header.measuredHeight + title.measuredHeight + icon.measuredHeight + title.marginTop + icon.marginTop + viewFlipper.measuredHeight + 16.dp ) } override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) { header.layout(paddingStart, paddingTop) icon.layout(icon.toHorizontalCenter(this), header.bottom + icon.marginTop) title.layout(title.toHorizontalCenter(this), icon.bottom + title.marginTop) viewFlipper.layout(paddingStart, title.bottom.coerceAtLeast(icon.bottom) + 16.dp) } override fun getHeaderView(): BottomSheetHeaderView { return header } class LibDetailItemView(context: Context) : AViewGroup(context) { val icon = AppCompatImageView(context).apply { layoutParams = LayoutParams(24.dp, 24.dp) } val text = AppCompatTextView(context).apply { layoutParams = LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT ).also { it.marginStart = 8.dp } } init { setPadding(8.dp, 8.dp, 8.dp, 8.dp) setBackgroundResource(R.drawable.bg_lib_detail_item) addView(icon) addView(text) } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) icon.autoMeasure() text.measure( (measuredWidth - paddingStart - paddingEnd - icon.measuredWidth - text.marginStart).toExactlyMeasureSpec(), text.defaultHeightMeasureSpec(this) ) setMeasuredDimension( measuredWidth, text.measuredHeight.coerceAtLeast(icon.measuredHeight) + paddingTop + paddingBottom ) } override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) { icon.layout(paddingStart, icon.toVerticalCenter(this)) text.layout(icon.right + text.marginStart, text.toVerticalCenter(this)) } } class NotFoundView(context: Context) : AViewGroup(context) { private val icon = AppCompatImageView(context).apply { layoutParams = LayoutParams(64.dp, 64.dp) setImageResource(R.drawable.ic_failed) } private val notFoundText = AppCompatTextView(context).apply { layoutParams = LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT ) text = context.getString(R.string.not_found) setTextAppearance(context.getResourceIdByAttr(com.google.android.material.R.attr.textAppearanceBody2)) } private val createNewIssueText = AppCompatTextView(context).apply { layoutParams = LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT ) text = context.getString(R.string.create_an_issue) setLinkTextColor(context.getColor(R.color.colorPrimary)) gravity = Gravity.CENTER_VERTICAL setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_github, 0, 0, 0) compoundDrawablePadding = 4.dp compoundDrawableTintList = ColorStateList.valueOf(context.getColorByAttr(android.R.attr.colorControlNormal)) isClickable = true movementMethod = LinkMovementMethod.getInstance() text = HtmlCompat.fromHtml( "<a href='${ApiManager.GITHUB_NEW_ISSUE_URL}'> ${resources.getText(R.string.create_an_issue)} </a>", HtmlCompat.FROM_HTML_MODE_LEGACY ) } init { addView(icon) addView(notFoundText) addView(createNewIssueText) } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) icon.autoMeasure() notFoundText.autoMeasure() createNewIssueText.autoMeasure() setMeasuredDimension( measuredWidth, icon.measuredHeight + notFoundText.measuredHeight + createNewIssueText.marginTop + createNewIssueText.measuredHeight ) } override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) { icon.layout(icon.toHorizontalCenter(this), 0) notFoundText.layout(notFoundText.toHorizontalCenter(this), icon.bottom) createNewIssueText.layout( createNewIssueText.toHorizontalCenter(this), notFoundText.bottom + createNewIssueText.marginTop ) } } class LibDetailContentView(context: Context) : AViewGroup(context) { val label = LibDetailItemView(context).apply { layoutParams = LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT ) icon.setImageResource(R.drawable.ic_label) text.setTextAppearance(context.getResourceIdByAttr(com.google.android.material.R.attr.textAppearanceSubtitle2)) } val team = LibDetailItemView(context).apply { layoutParams = LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT ) icon.setImageResource(R.drawable.ic_team) text.setTextAppearance(context.getResourceIdByAttr(com.google.android.material.R.attr.textAppearanceSubtitle2)) } val contributor = LibDetailItemView(context).apply { layoutParams = LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT ) icon.setImageResource(R.drawable.ic_github) text.setTextAppearance(context.getResourceIdByAttr(com.google.android.material.R.attr.textAppearanceSubtitle2)) } val description = LibDetailItemView(context).apply { layoutParams = LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT ) icon.setImageResource(R.drawable.ic_content) text.setTextAppearance(context.getResourceIdByAttr(com.google.android.material.R.attr.textAppearanceBody2)) } val relativeLink = LibDetailItemView(context).apply { layoutParams = LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT ) icon.setImageResource(R.drawable.ic_url) text.setTextAppearance(context.getResourceIdByAttr(com.google.android.material.R.attr.textAppearanceBody2)) } init { addView(label) addView(team) addView(contributor) addView(description) addView(relativeLink) } private val marginVertical = 8.dp override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) label.measure( (measuredWidth - paddingStart - paddingEnd).toExactlyMeasureSpec(), label.defaultHeightMeasureSpec(this) ) team.measure( (measuredWidth - paddingStart - paddingEnd).toExactlyMeasureSpec(), team.defaultHeightMeasureSpec(this) ) contributor.measure( (measuredWidth - paddingStart - paddingEnd).toExactlyMeasureSpec(), contributor.defaultHeightMeasureSpec(this) ) description.measure( (measuredWidth - paddingStart - paddingEnd).toExactlyMeasureSpec(), description.defaultHeightMeasureSpec(this) ) relativeLink.measure( (measuredWidth - paddingStart - paddingEnd).toExactlyMeasureSpec(), relativeLink.defaultHeightMeasureSpec(this) ) setMeasuredDimension( measuredWidth, label.measuredHeight + team.measuredHeight + contributor.measuredHeight + description.measuredHeight + relativeLink.measuredHeight + marginVertical * 4 ) } override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) { label.layout(0, 0) team.layout(0, label.bottom + marginVertical) contributor.layout(0, team.bottom + marginVertical) description.layout(0, contributor.bottom + marginVertical) relativeLink.layout(0, description.bottom + marginVertical) } } }
24
null
83
987
bbfdf8353172281af5ae08694305c32e837cb497
11,946
LibChecker
Apache License 2.0
simple-icons/src/commonMain/kotlin/compose/icons/simpleicons/Cloud66.kt
DevSrSouza
311,134,756
false
{"Kotlin": 36756847}
package compose.icons.simpleicons 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 compose.icons.SimpleIcons public val SimpleIcons.Cloud66: ImageVector get() { if (_cloud66 != null) { return _cloud66!! } _cloud66 = Builder(name = "Cloud66", 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) { moveTo(11.985f, 0.317f) curveTo(7.0865f, 2.716f, 2.9666f, 0.4233f, 2.9666f, 0.4233f) curveTo(1.1064f, 3.486f, 0.216f, 6.1747f, 0.0f, 8.5272f) horizontalLineToRelative(23.9992f) curveToRelative(-0.2165f, -2.3514f, -1.1074f, -5.0365f, -2.9665f, -8.0966f) curveToRelative(0.0f, 0.0f, -4.119f, 2.2905f, -9.0185f, -0.1073f) close() moveTo(5.2196f, 3.5273f) curveToRelative(0.424f, 0.0f, 0.7456f, 0.0853f, 0.8906f, 0.1594f) lineToRelative(-0.1666f, 0.6417f) arcToRelative(1.7877f, 1.7877f, 0.0f, false, false, -0.6865f, -0.1334f) curveToRelative(-0.6485f, 0.0f, -1.152f, 0.3871f, -1.152f, 1.1823f) curveToRelative(0.0f, 0.7157f, 0.4282f, 1.1666f, 1.1572f, 1.1666f) curveToRelative(0.2464f, 0.0f, 0.5202f, -0.0537f, 0.6813f, -0.1166f) lineToRelative(0.124f, 0.6312f) curveToRelative(-0.1505f, 0.0747f, -0.4882f, 0.1594f, -0.9282f, 0.1594f) curveToRelative(-1.248f, 0.0f, -1.8916f, -0.7751f, -1.8916f, -1.7927f) curveToRelative(0.0f, -1.2197f, 0.879f, -1.8979f, 1.9718f, -1.8979f) close() moveTo(11.534f, 3.5273f) curveToRelative(1.1093f, 0.0f, 1.7145f, 0.8217f, 1.7145f, 1.8083f) curveToRelative(0.0f, 1.1717f, -0.7179f, 1.8823f, -1.7739f, 1.8823f) curveToRelative(-1.072f, 0.0f, -1.6989f, -0.8006f, -1.6989f, -1.8187f) curveToRelative(0.0f, -1.071f, 0.6917f, -1.8719f, 1.7583f, -1.8719f) close() moveTo(19.3431f, 3.5596f) curveToRelative(0.6859f, 0.0f, 1.131f, 0.1226f, 1.4792f, 0.3823f) curveToRelative(0.3754f, 0.2757f, 0.6114f, 0.7149f, 0.6114f, 1.3458f) curveToRelative(0.0f, 0.6837f, -0.2517f, 1.1562f, -0.6f, 1.4479f) curveToRelative(-0.3808f, 0.3125f, -0.9594f, 0.4604f, -1.6666f, 0.4604f) curveToRelative(-0.424f, 0.0f, -0.7244f, -0.026f, -0.928f, -0.0521f) lineTo(18.2391f, 3.6336f) curveToRelative(0.2996f, -0.048f, 0.6913f, -0.074f, 1.104f, -0.074f) close() moveTo(7.003f, 3.5867f) horizontalLineToRelative(0.8198f) verticalLineToRelative(2.8947f) lineTo(9.258f, 6.4814f) verticalLineToRelative(0.6781f) lineTo(7.003f, 7.1595f) close() moveTo(14.1809f, 3.5867f) horizontalLineToRelative(0.8208f) lineTo(15.0017f, 5.643f) curveToRelative(0.0f, 0.615f, 0.235f, 0.9281f, 0.6531f, 0.9281f) curveToRelative(0.4293f, 0.0f, 0.6646f, -0.2972f, 0.6646f, -0.928f) lineTo(16.3194f, 3.5866f) horizontalLineToRelative(0.8156f) verticalLineToRelative(2.003f) curveToRelative(0.0f, 1.103f, -0.5638f, 1.6282f, -1.5073f, 1.6282f) curveToRelative(-0.9109f, 0.0f, -1.4468f, -0.4988f, -1.4468f, -1.6385f) close() moveTo(11.5091f, 4.169f) curveToRelative(-0.5504f, 0.0f, -0.8708f, 0.5212f, -0.8708f, 1.2166f) curveToRelative(0.0f, 0.7013f, 0.332f, 1.1958f, 0.877f, 1.1958f) curveToRelative(0.55f, 0.0f, 0.8646f, -0.5212f, 0.8646f, -1.2166f) curveToRelative(0.0f, -0.6432f, -0.3097f, -1.1958f, -0.8708f, -1.1958f) close() moveTo(19.4297f, 4.1794f) curveToRelative(-0.1824f, 0.0f, -0.301f, 0.0163f, -0.3708f, 0.0323f) verticalLineToRelative(2.3437f) curveToRelative(0.0698f, 0.016f, 0.1825f, 0.0156f, 0.2843f, 0.0156f) curveToRelative(0.7398f, 0.0053f, 1.2219f, -0.3987f, 1.2219f, -1.2541f) curveToRelative(0.0053f, -0.744f, -0.4336f, -1.1375f, -1.1354f, -1.1375f) close() moveTo(0.0052f, 9.7886f) curveToRelative(-0.281f, 10.276f, 11.9798f, 13.8881f, 11.9798f, 13.8881f) lineToRelative(0.0292f, 0.0063f) reflectiveCurveTo(24.281f, 20.0688f, 23.9951f, 9.7886f) horizontalLineToRelative(-0.001f) close() moveTo(10.7736f, 11.0688f) arcToRelative(5.5849f, 5.5849f, 0.0f, false, true, 0.326f, 0.0083f) verticalLineToRelative(1.4125f) curveToRelative(-0.2117f, 0.0f, -0.4367f, 0.0f, -0.7364f, 0.024f) curveToRelative(-1.6853f, 0.1333f, -2.434f, 0.967f, -2.6457f, 1.8842f) horizontalLineToRelative(0.0375f) curveToRelative(0.3989f, -0.3983f, 0.9613f, -0.628f, 1.7228f, -0.628f) curveToRelative(1.36f, 0.0f, 2.5083f, 0.93f, 2.5083f, 2.5603f) curveToRelative(0.0f, 1.5583f, -1.2358f, 2.8384f, -2.9958f, 2.8384f) curveToRelative(-2.1588f, 0.0f, -3.2196f, -1.557f, -3.2196f, -3.429f) curveToRelative(0.0f, -1.4736f, 0.5618f, -2.706f, 1.4353f, -3.4916f) curveToRelative(0.8112f, -0.7125f, 1.8592f, -1.099f, 3.1322f, -1.1593f) arcToRelative(5.5849f, 5.5849f, 0.0f, false, true, 0.4354f, -0.0198f) close() moveTo(17.7005f, 11.0688f) arcToRelative(5.5849f, 5.5849f, 0.0f, false, true, 0.327f, 0.0083f) verticalLineToRelative(1.4125f) curveToRelative(-0.2117f, 0.0f, -0.4367f, 0.0f, -0.7364f, 0.024f) curveToRelative(-1.6853f, 0.1333f, -2.434f, 0.967f, -2.6457f, 1.8842f) horizontalLineToRelative(0.0375f) curveToRelative(0.3989f, -0.3983f, 0.9613f, -0.628f, 1.7228f, -0.628f) curveToRelative(1.36f, 0.0f, 2.5072f, 0.93f, 2.5072f, 2.5603f) curveToRelative(0.0f, 1.5583f, -1.2352f, 2.8384f, -2.9947f, 2.8384f) curveToRelative(-2.1593f, 0.0f, -3.2196f, -1.557f, -3.2196f, -3.429f) curveToRelative(0.0f, -1.4736f, 0.5618f, -2.706f, 1.4353f, -3.4916f) curveToRelative(0.8112f, -0.7125f, 1.8592f, -1.099f, 3.1322f, -1.1593f) arcToRelative(5.5849f, 5.5849f, 0.0f, false, true, 0.4344f, -0.0198f) close() moveTo(8.8528f, 15.0749f) curveToRelative(-0.512f, 0.0f, -0.9356f, 0.301f, -1.1228f, 0.7f) curveToRelative(-0.0496f, 0.096f, -0.075f, 0.2423f, -0.075f, 0.4593f) curveToRelative(0.0373f, 0.8336f, 0.449f, 1.5823f, 1.3103f, 1.5823f) horizontalLineToRelative(0.0125f) curveToRelative(0.6614f, 0.0f, 1.0854f, -0.5928f, 1.0854f, -1.3896f) curveToRelative(0.0f, -0.7253f, -0.3992f, -1.352f, -1.2104f, -1.352f) close() moveTo(15.7808f, 15.0749f) curveToRelative(-0.512f, 0.0f, -0.9357f, 0.301f, -1.123f, 0.7f) curveToRelative(-0.0495f, 0.096f, -0.075f, 0.2423f, -0.075f, 0.4593f) curveToRelative(0.0374f, 0.8336f, 0.4491f, 1.5823f, 1.3105f, 1.5823f) horizontalLineToRelative(0.0125f) curveToRelative(0.6613f, 0.0f, 1.0853f, -0.5928f, 1.0853f, -1.3896f) curveToRelative(0.0f, -0.7253f, -0.3992f, -1.352f, -1.2103f, -1.352f) close() } } .build() return _cloud66!! } private var _cloud66: ImageVector? = null
15
Kotlin
20
460
651badc4ace0137c5541f859f61ffa91e5242b83
8,717
compose-icons
MIT License
core/src/main/java/io/github/crow_misia/libyuv/Nv21Buffer.kt
crow-misia
128,540,372
false
{"C++": 4781231, "Kotlin": 254193, "C": 145869, "Python": 134916, "Starlark": 11104, "CMake": 8822, "Makefile": 7653, "Shell": 4346}
package io.github.crow_misia.libyuv import java.nio.ByteBuffer import kotlin.math.min /** * NV21 YUV Format. 4:2:0 12bpp */ class Nv21Buffer private constructor( buffer: ByteBuffer?, override val planeY: Plane, val planeVU: Plane, override val width: Int, override val height: Int, releaseCallback: Runnable?, ) : AbstractBuffer(buffer, arrayOf(planeY, planeVU), releaseCallback), BufferY<I400Buffer> { fun convertTo(dst: I420Buffer) { Yuv.convertNV21ToI420( srcY = planeY.buffer, srcStrideY = planeY.rowStride, srcVU = planeVU.buffer, srcStrideVU = planeVU.rowStride, dstY = dst.planeY.buffer, dstStrideY = dst.planeY.rowStride, dstU = dst.planeU.buffer, dstStrideU = dst.planeU.rowStride, dstV = dst.planeV.buffer, dstStrideV = dst.planeV.rowStride, width = min(width, dst.width), height = min(height, dst.height), ) } fun convertTo(dst: Nv12Buffer) { Yuv.planerNV21ToNV12( srcY = planeY.buffer, srcStrideY = planeY.rowStride, srcVU = planeVU.buffer, srcStrideVU = planeVU.rowStride, dstY = dst.planeY.buffer, dstStrideY = dst.planeY.rowStride, dstUV = dst.planeUV.buffer, dstStrideUV = dst.planeUV.rowStride, width = min(width, dst.width), height = min(height, dst.height), ) } fun convertTo(dst: Nv21Buffer) { Yuv.planerNV12Copy( srcY = planeY.buffer, srcStrideY = planeY.rowStride, srcVU = planeVU.buffer, srcStrideVU = planeVU.rowStride, dstY = dst.planeY.buffer, dstStrideY = dst.planeY.rowStride, dstUV = dst.planeVU.buffer, dstStrideUV = dst.planeVU.rowStride, width = min(width, dst.width), height = min(height, dst.height), ) } fun convertTo(dst: ArgbBuffer) { Yuv.convertNV21ToARGB( srcY = planeY.buffer, srcStrideY = planeY.rowStride, srcVU = planeVU.buffer, srcStrideVU = planeVU.rowStride, dstARGB = dst.plane.buffer, dstStrideARGB = dst.plane.rowStride, width = min(width, dst.width), height = min(height, dst.height), ) } fun convertTo(dst: AbgrBuffer) { Yuv.convertNV21ToABGR( srcY = planeY.buffer, srcStrideY = planeY.rowStride, srcVU = planeVU.buffer, srcStrideVU = planeVU.rowStride, dstABGR = dst.plane.buffer, dstStrideABGR = dst.plane.rowStride, width = min(width, dst.width), height = min(height, dst.height), ) } fun convertTo(dst: Rgb24Buffer) { Yuv.convertNV21ToRGB24( srcY = planeY.buffer, srcStrideY = planeY.rowStride, srcVU = planeVU.buffer, srcStrideVU = planeVU.rowStride, dstRGB24 = dst.plane.buffer, dstStrideRGB24 = dst.plane.rowStride, width = min(width, dst.width), height = min(height, dst.height), ) } fun convertTo(dst: Yuv24Buffer) { Yuv.convertNV21ToYUV24( srcY = planeY.buffer, srcStrideY = planeY.rowStride, srcVU = planeVU.buffer, srcStrideVU = planeVU.rowStride, dstYUV24 = dst.plane.buffer, dstStrideYUV24 = dst.plane.rowStride, width = min(width, dst.width), height = min(height, dst.height), ) } fun convertTo(dst: RawBuffer) { Yuv.convertNV21ToRAW( srcY = planeY.buffer, srcStrideY = planeY.rowStride, srcVU = planeVU.buffer, srcStrideVU = planeVU.rowStride, dstRAW = dst.plane.buffer, dstStrideRAW = dst.plane.rowStride, width = min(width, dst.width), height = min(height, dst.height), ) } fun mirrorTo(dst: Nv21Buffer) { Yuv.planerNV12Mirror( srcY = planeY.buffer, srcStrideY = planeY.rowStride, srcUV = planeVU.buffer, srcStrideUV = planeVU.rowStride, dstY = dst.planeY.buffer, dstStrideY = dst.planeY.rowStride, dstUV = dst.planeVU.buffer, dstStrideUV = dst.planeVU.rowStride, width = min(width, dst.width), height = min(height, dst.height), ) } fun rotate(dst: I420Buffer, rotateMode: RotateMode) { Yuv.rotateNV12ToI420Rotate( srcY = planeY.buffer, srcStrideY = planeY.rowStride, srcUV = planeVU.buffer, srcStrideUV = planeVU.rowStride, dstY = dst.planeY.buffer, dstStrideY = dst.planeY.rowStride, dstU = dst.planeV.buffer, dstStrideU = dst.planeV.rowStride, dstV = dst.planeU.buffer, dstStrideV = dst.planeU.rowStride, width = rotateMode.calculateWidth(this, dst), height = rotateMode.calculateHeight(this, dst), rotateMode = rotateMode.degrees, ) } fun rotate(dst: Nv12Buffer, rotateMode: RotateMode) { Yuv.rotateNV12ToNV21Rotate( srcY = planeY.buffer, srcStrideY = planeY.rowStride, srcUV = planeVU.buffer, srcStrideUV = planeVU.rowStride, dstY = dst.planeY.buffer, dstStrideY = dst.planeY.rowStride, dstVU = dst.planeUV.buffer, dstStrideVU = dst.planeUV.rowStride, width = rotateMode.calculateWidth(this, dst), height = rotateMode.calculateHeight(this, dst), rotateMode = rotateMode.degrees, ) } fun rotate(dst: Nv21Buffer, rotateMode: RotateMode) { Yuv.rotateNV21Rotate( srcY = planeY.buffer, srcStrideY = planeY.rowStride, srcVU = planeVU.buffer, srcStrideVU = planeVU.rowStride, dstY = dst.planeY.buffer, dstStrideY = dst.planeY.rowStride, dstVU = dst.planeVU.buffer, dstStrideVU = dst.planeVU.rowStride, width = rotateMode.calculateWidth(this, dst), height = rotateMode.calculateHeight(this, dst), rotateMode = rotateMode.degrees, ) } fun scale(dst: Nv21Buffer, filterMode: FilterMode) { Yuv.scaleNV12Scale( srcY = planeY.buffer, srcStrideY = planeY.rowStride, srcUV = planeVU.buffer, srcStrideUV = planeVU.rowStride, srcWidth = width, srcHeight = height, dstY = dst.planeY.buffer, dstStrideY = dst.planeY.rowStride, dstUV = dst.planeVU.buffer, dstStrideUV = dst.planeVU.rowStride, dstWidth = dst.width, dstHeight = dst.height, filterMode = filterMode.mode, ) } companion object Factory : BufferFactory<Nv21Buffer> { private fun getStrideWithCapacity(width: Int, height: Int): IntArray { val capacityY = width * height val capacityVU = (width + 1).shr(1) * height return intArrayOf(width, capacityY, width, capacityVU) } override fun allocate(width: Int, height: Int): Nv21Buffer { val (strideY, capacityY, strideVU, capacityVU) = getStrideWithCapacity(width, height) val buffer = createByteBuffer(capacityY + capacityVU) val (bufferY, bufferVU) = buffer.slice(capacityY, capacityVU) return Nv21Buffer( buffer = buffer, planeY = PlanePrimitive(strideY, bufferY), planeVU = PlanePrimitive(strideVU, bufferVU), width = width, height = height, ) { Yuv.freeNativeBuffer(buffer) } } override fun wrap(buffer: ByteBuffer, width: Int, height: Int): Nv21Buffer { check(buffer.isDirect) { "Unsupported non-direct ByteBuffer." } val (strideY, capacityY, strideVU, capacityVU) = getStrideWithCapacity(width, height) val (bufferY, bufferVU) = buffer.slice(capacityY, capacityVU) return Nv21Buffer( buffer = buffer, planeY = PlanePrimitive(strideY, bufferY), planeVU = PlanePrimitive(strideVU, bufferVU), width = width, height = height, releaseCallback = null, ) } fun wrap(planeY: Plane, planeVU: Plane, width: Int, height: Int): Nv21Buffer { return Nv21Buffer( buffer = null, planeY = planeY, planeVU = planeVU, width = width, height = height, releaseCallback = null, ) } } }
3
C++
18
79
89a93f053eb7fa5f4c1d7c9f023a80d3c630e9e0
8,379
libyuv-android
Apache License 2.0
src/main/kotlin/com/yapp/weekand/domain/schedule/exception/ScheduleInvalidSkipDateException.kt
YAPP-Github
475,727,764
false
null
package com.yapp.weekand.domain.schedule.exception import com.yapp.weekand.common.error.ErrorCode import com.yapp.weekand.common.error.graphql.AbstractBaseGraphQLException class ScheduleInvalidSkipDateException : AbstractBaseGraphQLException(ErrorCode.SCHEDULE_INVALID_SKIP_DATE)
3
Kotlin
0
4
382c212a6af89c6009a776be8eb4de96c5c3d147
282
20th-ALL-Rounder-Team-1-BE
Apache License 2.0
server-endpoint/src/main/kotlin/com/jacknie/sample/firebase/ksns/config/WebSecurityConfiguration.kt
jacknie84
334,155,766
false
null
package com.jacknie.sample.firebase.ksns.config import com.google.firebase.FirebaseApp import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.core.Ordered import org.springframework.core.annotation.Order import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter import org.springframework.security.config.http.SessionCreationPolicy import org.springframework.web.cors.CorsConfiguration import org.springframework.web.cors.CorsConfigurationSource import org.springframework.web.cors.UrlBasedCorsConfigurationSource @Configuration @Order(Ordered.HIGHEST_PRECEDENCE) class WebSecurityConfiguration1 : WebSecurityConfigurerAdapter(true) { override fun configure(http: HttpSecurity) { http .oauth2Client().and() .requestMatchers().antMatchers("/oauth2/authorization/**", "/login/oauth2/code/**") } } @Configuration @Order(1) class WebSecurityConfiguration2 : WebSecurityConfigurerAdapter(true) { override fun configure(http: HttpSecurity) { http .authenticationProvider(basicAuthenticationProvider()) .cors().and() .sessionManagement().and() .securityContext().and() .httpBasic().and() .requestMatchers().antMatchers("/firebase/*/custom-token").and() .authorizeRequests().antMatchers("/firebase/*/custom-token").authenticated() } @Bean fun basicAuthenticationProvider() = BasicAuthenticationProvider() } @Configuration @Order(Ordered.LOWEST_PRECEDENCE) class WebSecurityConfiguration3(private val firebaseApp: FirebaseApp) : WebSecurityConfigurerAdapter() { override fun configure(http: HttpSecurity) { http .csrf().disable() .cors().and() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and() .headers().frameOptions().sameOrigin().and() .oauth2ResourceServer().jwt().decoder(FirebaseJwtDecoder(firebaseApp)).and().and() .requestMatchers().antMatchers("/resources").and() .authorizeRequests().anyRequest().authenticated() } } @Configuration class CorsConfiguration { @Bean fun corsConfigurationSource(): CorsConfigurationSource { val corsConfigurationSource = UrlBasedCorsConfigurationSource() val config = CorsConfiguration() config.addAllowedOrigin("http://localhost:3000") config.addAllowedMethod("*") config.addAllowedHeader("*") config.allowCredentials = true corsConfigurationSource.registerCorsConfiguration("/**", config) return corsConfigurationSource } }
0
Kotlin
0
3
a35348f4b4ea0fda92f5413a49b8f3c066699177
2,832
firebase-korea-sns
MIT License
Quiz/app/src/main/java/com/example/quiz/model/repository/ResultRepository.kt
KamilDonda
321,666,752
false
null
package com.example.quiz.model.repository import androidx.lifecycle.LiveData import com.example.quiz.model.dao.ResultDao import com.example.quiz.model.entities.Result class ResultRepository(private val dao: ResultDao) { val getAllResult: LiveData<List<Result>> = dao.getAllResults() suspend fun insert(result: Result) = dao.insert(result) fun getResultsWithCategories(categories: List<Int>) = dao.getResultsWithCategories(categories) fun getResultsWithFilters(categories: List<Int>, levels: List<String>) = dao.getResultsWithFilters(categories, levels) fun getResultsWithLevels(levels: List<String>) = dao.getResultsWithLevels(levels) }
0
Kotlin
0
1
755580ba0eefe3e44ed12096a60b15bcd0a3b826
670
QuizzzyMobile
MIT License
amazon/dynamodb/client/src/main/kotlin/org/http4k/connect/amazon/dynamodb/action/Scan.kt
http4k
295,641,058
false
{"Kotlin": 1624429, "Handlebars": 10370, "CSS": 5434, "Shell": 3178, "JavaScript": 2076, "Python": 1834, "HTML": 675}
package org.http4k.connect.amazon.dynamodb.action import org.http4k.connect.Http4kConnectAction import org.http4k.connect.Paged import org.http4k.connect.amazon.dynamodb.model.ConsumedCapacity import org.http4k.connect.amazon.dynamodb.model.IndexName import org.http4k.connect.amazon.dynamodb.model.Item import org.http4k.connect.amazon.dynamodb.model.ItemResult import org.http4k.connect.amazon.dynamodb.model.Key import org.http4k.connect.amazon.dynamodb.model.ReturnConsumedCapacity import org.http4k.connect.amazon.dynamodb.model.Select import org.http4k.connect.amazon.dynamodb.model.TableName import org.http4k.connect.amazon.dynamodb.model.TokensToNames import org.http4k.connect.amazon.dynamodb.model.TokensToValues import org.http4k.connect.amazon.dynamodb.model.toItem import org.http4k.connect.kClass import se.ansman.kotshi.JsonSerializable @Http4kConnectAction @JsonSerializable data class Query( val TableName: TableName, val KeyConditionExpression: String? = null, val FilterExpression: String? = null, val ProjectionExpression: String? = null, val ExpressionAttributeNames: TokensToNames? = null, val ExpressionAttributeValues: TokensToValues? = null, val IndexName: IndexName? = null, val Select: Select? = null, val ConsistentRead: Boolean? = null, val ExclusiveStartKey: Key? = null, override val Limit: Int? = null, val ReturnConsumedCapacity: ReturnConsumedCapacity? = null, val ScanIndexForward: Boolean? = null, ) : DynamoDbPagedAction<QueryResponse, Query>(kClass()) { override fun next(token: Key) = copy(ExclusiveStartKey = token) } @JsonSerializable data class QueryResponse( internal val Items: List<ItemResult>? = null, val ConsumedCapacity: ConsumedCapacity? = null, val Count: Int = 0, val LastEvaluatedKey: Key? = null, val ScannedCount: Int = 0 ) : Paged<Key, Item> { override val items = Items?.map(ItemResult::toItem) ?: emptyList() override fun token() = LastEvaluatedKey }
7
Kotlin
17
37
94e71e6bba87d9c79ac29f7ba23bdacd0fdf354c
1,997
http4k-connect
Apache License 2.0
newm-server/src/main/kotlin/io/newm/server/features/distribution/model/OutletStatusCode.kt
projectNEWM
447,979,150
false
null
package io.newm.server.features.distribution.model import kotlinx.serialization.Serializable @Serializable enum class OutletStatusCode(val code: Int) { DRAFT(1021), READY_TO_DISTRIBUTE(1022), READY_TO_SUBMIT(1208), DISTRIBUTE_INITIATED(1201), DISTRIBUTED(1202), TAKEDOWN_INITIATED(1203), UPDATE_INITIATED(1205), UPDATED(1206), REVIEW_PENDING(1207), DISAPPROVED(1034), }
1
Kotlin
3
7
3335108d0d87a8b2aca3b4aeaeac834faeb1d2d9
412
newm-server
Apache License 2.0
android/src/main/java/com/swmansion/gesturehandler/react/RNGestureHandlerRootHelper.kt
software-mansion
72,087,685
false
null
package abi46_0_0.host.exp.exponent.modules.api.components.gesturehandler.react import android.os.SystemClock import android.util.Log import android.view.MotionEvent import android.view.ViewGroup import android.view.ViewParent import abi46_0_0.com.facebook.react.bridge.ReactContext import abi46_0_0.com.facebook.react.bridge.UiThreadUtil import abi46_0_0.com.facebook.react.common.ReactConstants import abi46_0_0.com.facebook.react.uimanager.RootView import abi46_0_0.host.exp.exponent.modules.api.components.gesturehandler.GestureHandler import abi46_0_0.host.exp.exponent.modules.api.components.gesturehandler.GestureHandlerOrchestrator class RNGestureHandlerRootHelper(private val context: ReactContext, wrappedView: ViewGroup) { private val orchestrator: GestureHandlerOrchestrator? private val jsGestureHandler: GestureHandler<*>? val rootView: ViewGroup private var shouldIntercept = false private var passingTouch = false init { UiThreadUtil.assertOnUiThread() val wrappedViewTag = wrappedView.id check(wrappedViewTag >= 1) { "Expect view tag to be set for $wrappedView" } val module = context.getNativeModule(RNGestureHandlerModule::class.java)!! val registry = module.registry rootView = findRootViewTag(wrappedView) Log.i( ReactConstants.TAG, "[GESTURE HANDLER] Initialize gesture handler for root view $rootView" ) orchestrator = GestureHandlerOrchestrator( wrappedView, registry, RNViewConfigurationHelper() ).apply { minimumAlphaForTraversal = MIN_ALPHA_FOR_TOUCH } jsGestureHandler = RootViewGestureHandler().apply { tag = -wrappedViewTag } with(registry) { registerHandler(jsGestureHandler) attachHandlerToView(jsGestureHandler.tag, wrappedViewTag, GestureHandler.ACTION_TYPE_JS_FUNCTION_OLD_API) } module.registerRootHelper(this) } fun tearDown() { Log.i( ReactConstants.TAG, "[GESTURE HANDLER] Tearing down gesture handler registered for root view $rootView" ) val module = context.getNativeModule(RNGestureHandlerModule::class.java)!! with(module) { registry.dropHandler(jsGestureHandler!!.tag) unregisterRootHelper(this@RNGestureHandlerRootHelper) } } private inner class RootViewGestureHandler : GestureHandler<RootViewGestureHandler>() { override fun onHandle(event: MotionEvent) { val currentState = state if (currentState == STATE_UNDETERMINED) { begin() shouldIntercept = false } if (event.actionMasked == MotionEvent.ACTION_UP) { end() } } override fun onCancel() { shouldIntercept = true val time = SystemClock.uptimeMillis() val event = MotionEvent.obtain(time, time, MotionEvent.ACTION_CANCEL, 0f, 0f, 0).apply { action = MotionEvent.ACTION_CANCEL } if (rootView is RootView) { rootView.onChildStartedNativeGesture(event) } } } fun requestDisallowInterceptTouchEvent(disallowIntercept: Boolean) { // If this method gets called it means that some native view is attempting to grab lock for // touch event delivery. In that case we cancel all gesture recognizers if (orchestrator != null && !passingTouch) { // if we are in the process of delivering touch events via GH orchestrator, we don't want to // treat it as a native gesture capturing the lock tryCancelAllHandlers() } } fun dispatchTouchEvent(ev: MotionEvent): Boolean { // We mark `mPassingTouch` before we get into `mOrchestrator.onTouchEvent` so that we can tell // if `requestDisallow` has been called as a result of a normal gesture handling process or // as a result of one of the gesture handlers activating passingTouch = true orchestrator!!.onTouchEvent(ev) passingTouch = false return shouldIntercept } private fun tryCancelAllHandlers() { // In order to cancel handlers we activate handler that is hooked to the root view jsGestureHandler?.apply { if (state == GestureHandler.STATE_BEGAN) { // Try activate main JS handler activate() end() } } } /*package*/ fun handleSetJSResponder(viewTag: Int, blockNativeResponder: Boolean) { if (blockNativeResponder) { UiThreadUtil.runOnUiThread { tryCancelAllHandlers() } } } companion object { private const val MIN_ALPHA_FOR_TOUCH = 0.1f private fun findRootViewTag(viewGroup: ViewGroup): ViewGroup { UiThreadUtil.assertOnUiThread() var parent: ViewParent? = viewGroup while (parent != null && parent !is RootView) { parent = parent.parent } checkNotNull(parent) { "View $viewGroup has not been mounted under ReactRootView" } return parent as ViewGroup } } }
97
null
980
6,098
da9eed867ff09633c506fc9ad08634eaf707cbdb
4,809
react-native-gesture-handler
MIT License
core/src/main/java/com/aba/core/callback/ErrorSuccessCallback.kt
amircoder
247,642,230
false
{"Gradle": 19, "INI": 3, "Java Properties": 2, "Shell": 1, "Ignore List": 8, "Batchfile": 1, "Groovy": 1, "Markdown": 1, "Kotlin": 105, "XML": 64, "Java": 8, "Proguard": 3, "PureBasic": 1}
package com.alphacoder.core.callback.view interface ErrorSuccessCallback { fun showLoadingSpinner() fun hideLoadingSpinner() fun displayGenericErrorMessage() fun displayNetworkErrorMessage() fun displayCustomError(title: String, msg: String) }
0
Kotlin
0
2
d48bbf066eadd135a45a415c0f1babeac3aee539
265
CleanMVVMCoroutine
Apache License 2.0
src/main/java/at/petrak/hexcasting/api/PatternRegistry.kt
Noobulus
513,991,947
false
null
package at.petrak.hexcasting.api import at.petrak.hexcasting.common.casting.CastException import at.petrak.hexcasting.hexmath.EulerPathFinder import at.petrak.hexcasting.hexmath.HexDir import at.petrak.hexcasting.hexmath.HexPattern import net.minecraft.nbt.CompoundTag import net.minecraft.resources.ResourceLocation import net.minecraft.server.level.ServerLevel import net.minecraft.world.level.saveddata.SavedData import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.ConcurrentLinkedDeque import java.util.concurrent.ConcurrentMap /** * Register your patterns and associate them with spells here. * * Most patterns are matches to their operators solely by their *angle signature*. * This is a record of all the angles in the pattern, independent of the direction the player started drawing in. * It's written in shorthand, where `w` is straight ahead, `q` is left, `a` is left-back, `d` is right-back, * and `e` is right. * * For example, the signature for a straight line of 3 segments is `"ww"`. The signatures for the "get caster" * operator (the diamond) are `"qaq"` and `"ede"`. */ object PatternRegistry { private val operatorLookup = ConcurrentHashMap<ResourceLocation, Operator>() private val specialHandlers: ConcurrentLinkedDeque<SpecialHandler> = ConcurrentLinkedDeque() // Map signatures to the "preferred" direction they start in and their operator ID. private val regularPatternLookup: ConcurrentMap<String, RegularEntry> = ConcurrentHashMap() private val perWorldPatternLookup: ConcurrentMap<ResourceLocation, PerWorldEntry> = ConcurrentHashMap() /** * Associate a given angle signature with a SpellOperator. */ @JvmStatic @JvmOverloads @Throws(RegisterPatternException::class) fun mapPattern(pattern: HexPattern, id: ResourceLocation, operator: Operator, isPerWorld: Boolean = false) { this.operatorLookup[id]?.let { throw RegisterPatternException("The operator with id `$id` was already registered to: $it") } this.operatorLookup[id] = operator if (isPerWorld) { this.perWorldPatternLookup[id] = PerWorldEntry(pattern, id) } else { this.regularPatternLookup[pattern.anglesSignature()] = RegularEntry(pattern.startDir, id) } } /** * Add a special handler, to take an arbitrary pattern and return whatever kind of operator you like. */ @JvmStatic fun addSpecialHandler(handler: SpecialHandler) { this.specialHandlers.add(handler) } /** * Internal use only. */ @JvmStatic fun matchPattern(pat: HexPattern, overworld: ServerLevel): Operator { // Pipeline: // patterns are registered here every time the game boots // when we try to look for (handler in specialHandlers) { val op = handler.handlePattern(pat) if (op != null) return op } // Is it global? val sig = pat.anglesSignature() this.regularPatternLookup[sig]?.let { return this.operatorLookup[it.opId] ?: throw CastException(CastException.Reason.INVALID_PATTERN, pat) } // Look it up in the world? val ds = overworld.dataStorage val perWorldPatterns: Save = ds.computeIfAbsent(Save.Companion::load, { Save.create(overworld.seed) }, TAG_SAVED_DATA) perWorldPatterns.lookup[sig]?.let { return this.operatorLookup[it.first]!! } throw CastException(CastException.Reason.INVALID_PATTERN, pat) } /** * Internal use only. */ @JvmStatic fun getPerWorldPatterns(overworld: ServerLevel): Map<String, Pair<ResourceLocation, HexDir>> { val ds = overworld.dataStorage val perWorldPatterns: Save = ds.computeIfAbsent(Save.Companion::load, { Save.create(overworld.seed) }, TAG_SAVED_DATA) return perWorldPatterns.lookup } /** * Internal use only. */ @JvmStatic fun lookupPattern(opId: ResourceLocation): PatternEntry { this.perWorldPatternLookup[opId]?.let { return PatternEntry(it.prototype, this.operatorLookup[it.opId]!!, true) } for ((sig, entry) in this.regularPatternLookup) { if (entry.opId == opId) { val pattern = HexPattern.FromAnglesSig(sig, entry.preferredStart) return PatternEntry(pattern, this.operatorLookup[entry.opId]!!, false) } } throw IllegalArgumentException("could not find a pattern for $opId") } /** * Special handling of a pattern. Before checking any of the normal angle-signature based patterns, * a given pattern is run by all of these special handlers patterns. If none of them return non-null, * then its signature is checked. * * In the base mod, this is used for number patterns. */ fun interface SpecialHandler { fun handlePattern(pattern: HexPattern): Operator? } class RegisterPatternException(msg: String) : java.lang.Exception(msg) private data class RegularEntry(val preferredStart: HexDir, val opId: ResourceLocation) private data class PerWorldEntry(val prototype: HexPattern, val opId: ResourceLocation) // Fake class we pretend to use internally data class PatternEntry(val prototype: HexPattern, val operator: Operator, val isPerWorld: Boolean) /** * Maps angle sigs to resource locations and their preferred start dir so we can look them up in the main registry */ class Save(val lookup: MutableMap<String, Pair<ResourceLocation, HexDir>>) : SavedData() { override fun save(tag: CompoundTag): CompoundTag { for ((sig, rhs) in this.lookup) { val (id, startDir) = rhs val entry = CompoundTag() entry.putString(TAG_OP_ID, id.toString()) entry.putInt(TAG_START_DIR, startDir.ordinal) tag.put(sig, entry) } return tag } companion object { fun load(tag: CompoundTag): Save { val map = HashMap<String, Pair<ResourceLocation, HexDir>>() for (sig in tag.allKeys) { val entry = tag.getCompound(sig) val opId = ResourceLocation.tryParse(entry.getString(TAG_OP_ID))!! val startDir = HexDir.values()[entry.getInt(TAG_START_DIR)] map[sig] = Pair(opId, startDir) } return Save(map) } @JvmStatic fun create(seed: Long): Save { val map = mutableMapOf<String, Pair<ResourceLocation, HexDir>>() for ((opId, entry) in PatternRegistry.perWorldPatternLookup) { // waugh why doesn't kotlin recursively destructure things val scrungled = EulerPathFinder.findAltDrawing(entry.prototype, seed) map[scrungled.anglesSignature()] = Pair(opId, scrungled.startDir) } val save = Save(map) save.setDirty() return save } } } const val TAG_SAVED_DATA = "hex.per-world-patterns" private const val TAG_OP_ID = "op_id" private const val TAG_START_DIR = "start_dir" }
1
null
1
1
fd206287f685261aa257957f6a4eb634db46630f
7,367
HexMod
MIT License
ktfx-layouts/src/test/kotlin/javafx/scene/layout/StackPaneTest.kt
hanggrian
102,934,147
false
{"Kotlin": 1103986, "CSS": 1653}
package ktfx.layouts import com.hanggrian.ktfx.test.LayoutsStyledTest import javafx.scene.layout.StackPane class StackPaneTest : LayoutsStyledTest<KtfxPane, StackPane>() { override fun manager() = KtfxPane() override fun KtfxPane.childCount() = children.size override fun child1() = stackPane {} override fun KtfxPane.child2() = stackPane() override fun child3() = styledStackPane(styleClass = arrayOf("style")) override fun KtfxPane.child4() = styledStackPane(styleClass = arrayOf("style")) }
1
Kotlin
2
18
8ab17659146dc9c402a6bcb9f5148c70b2cd9ed1
525
ktfx
Apache License 2.0
work/workmanager-ktx/src/androidTest/java/androidx/work/DataTest.kt
RikkaW
389,105,112
false
null
/* * Copyright 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.work import android.support.test.filters.SmallTest import android.support.test.runner.AndroidJUnit4 import org.junit.Assert.assertEquals import org.junit.Assert.assertNotNull import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) @SmallTest class DataTest { @Test fun testMapToData() { val map = mapOf("one" to 1, "two" to 2L, "three" to "Three", "four" to longArrayOf(1L, 2L)) val data = map.toWorkData() assertEquals(data.getInt("one", 0), 1) assertEquals(data.getLong("two", 0L), 2L) assertEquals(data.getString("three"), "Three") val longArray = data.getLongArray("four") assertNotNull(longArray) assertEquals(longArray!!.size, 2) assertEquals(longArray[0], 1L) assertEquals(longArray[1], 2L) } }
8
null
657
7
6d53f95e5d979366cf7935ad7f4f14f76a951ea5
1,458
androidx
Apache License 2.0
androidApp/src/main/java/io/github/lazyengineer/castaway/androidApp/view/podcast/PodcastViewModel.kt
lazy-engineer
321,396,462
false
{"Kotlin": 262426, "Swift": 86110, "Ruby": 1720}
package io.github.lazyengineer.castaway.androidApp.view.podcast import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import io.github.lazyengineer.castaway.androidApp.player.PlayPauseUseCase import io.github.lazyengineer.castaway.androidApp.player.PlayerState import io.github.lazyengineer.castaway.androidApp.player.PlayerStateUseCase import io.github.lazyengineer.castaway.androidApp.player.PreparePlayerUseCase import io.github.lazyengineer.castaway.androidApp.player.SubscribeToPlayerUseCase import io.github.lazyengineer.castaway.androidApp.view.podcast.PodcastEpisode.Companion.toEpisode import io.github.lazyengineer.castaway.androidApp.view.podcast.PodcastEpisode.Companion.toPodcastEpisode import io.github.lazyengineer.castaway.androidApp.view.podcast.PodcastEvent.EpisodeRowEvent.PlayPause import io.github.lazyengineer.castaway.androidApp.view.podcast.PodcastEvent.EpisodeRowEvent.PlaybackPosition import io.github.lazyengineer.castaway.androidApp.view.podcast.PodcastEvent.EpisodeRowEvent.Playing import io.github.lazyengineer.castaway.androidApp.view.podcast.PodcastEvent.EpisodeRowEvent.ShowDetails import io.github.lazyengineer.castaway.androidApp.view.podcast.PodcastEvent.FeedEvent.DetailsShowed import io.github.lazyengineer.castaway.androidApp.view.podcast.PodcastEvent.FeedEvent.FetchError import io.github.lazyengineer.castaway.androidApp.view.podcast.PodcastEvent.FeedEvent.Load import io.github.lazyengineer.castaway.androidApp.view.podcast.PodcastEvent.FeedEvent.Loaded import io.github.lazyengineer.castaway.domain.common.stateReducerFlow import io.github.lazyengineer.castaway.domain.entity.common.DataResult.Error import io.github.lazyengineer.castaway.domain.entity.common.DataResult.Success import io.github.lazyengineer.castaway.domain.usecase.GetStoredFeedUseCase import io.github.lazyengineer.castaway.domain.usecase.StoreAndGetFeedUseCase import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch class PodcastViewModel( initialState: PodcastViewState = PodcastViewState.Initial, playerStateUseCase: PlayerStateUseCase, private val getStoredFeedUseCase: GetStoredFeedUseCase, private val storeAndGetFeedUseCase: StoreAndGetFeedUseCase, private val subscribeToPlayerUseCase: SubscribeToPlayerUseCase, private val preparePlayerUseCase: PreparePlayerUseCase, private val playPauseUseCase: PlayPauseUseCase, ) : ViewModel() { val podcastState = stateReducerFlow( initialState = initialState, reduceState = ::reduceState, ) private fun reduceState( currentState: PodcastViewState, event: PodcastEvent ): PodcastViewState { return when (event) { is Loaded -> { val episodes = event.feed.episodes.map { it.toPodcastEpisode() } preparePlayer(episodes) currentState.copy( loading = false, imageUrl = event.feed.info.imageUrl.orEmpty(), episodes = EpisodesList(items = episodes) ) } is Load -> { if (currentState.episodes.items.isEmpty() || event.forceUpdate) { if (event.forceUpdate) { viewModelScope.launch { fetchFeed(event.id) } } else { viewModelScope.launch { loadFeed(event.id) } } currentState.copy(loading = true) } else { currentState } } is ShowDetails -> currentState.copy(showDetails = event.item) is Playing -> { currentState.copy(episodes = EpisodesList(currentState.episodes.items.map { episode -> if (event.itemId == episode.id) { episode.copy(buffering = false, playing = !episode.playing) } else { episode.copy(playing = false) } })) } is PlayPause -> { playOrPause(event.itemId) currentState.copy(episodes = EpisodesList(currentState.episodes.items.map { if (event.itemId == it.id) { it.copy(buffering = true) } else { it.copy(buffering = false) } })) } is PlaybackPosition -> { currentState.copy(episodes = currentState.episodes.copy( items = currentState.episodes.items.map { episode -> if (event.itemId == episode.id) { episode.copy( playbackPosition = event.positionMillis, playbackDuration = event.durationMillis, playbackProgress = event.positionMillis.toFloat() / event.durationMillis ) } else { episode } } )) } DetailsShowed -> { currentState.copy(showDetails = null) } is FetchError -> currentState.copy(error = event.error.message, loading = false) } } private val playerState: StateFlow<PlayerState> = playerStateUseCase() .stateIn(viewModelScope, SharingStarted.Lazily, PlayerState.Initial) init { subscribeToPlayer() collectPlayerState() } private fun subscribeToPlayer() { viewModelScope.launch { subscribeToPlayerUseCase() } } private fun collectPlayerState() { viewModelScope.launch { playerState.collect { state -> if (state.prepared) { state.mediaData?.mediaId?.let { mediaId -> val episode = podcastState.value.episodes.items.firstOrNull { it.id == mediaId } if (state.playing != episode?.playing) { podcastState.handleEvent(Playing(mediaId)) } if (state.mediaData.playbackPosition != episode?.playbackPosition) { podcastState.handleEvent( PlaybackPosition( itemId = mediaId, positionMillis = state.mediaData.playbackPosition, durationMillis = state.mediaData.duration ?: 0 ) ) } } } else { preparePlayer(podcastState.value.episodes.items) } } } } private fun playOrPause(itemId: String) { viewModelScope.launch { playPauseUseCase(itemId) } } private fun preparePlayer(episodes: List<PodcastEpisode>) { preparePlayerUseCase(episodes.map { it.toEpisode() }) } private suspend fun loadFeed(url: String) { when (val result = getStoredFeedUseCase(url)) { is Error -> { fetchFeed(url) } is Success -> { podcastState.handleEvent(Loaded(result.data)) } } } private fun fetchFeed(url: String) { viewModelScope.launch { fetchFeedFromUrl(url) } } private suspend fun fetchFeedFromUrl(url: String) { when (val result = storeAndGetFeedUseCase(url)) { is Success -> { podcastState.handleEvent(Loaded(result.data)) } is Error -> { podcastState.handleEvent(FetchError(result.exception)) } } } companion object { const val TEST_URL = "https://atp.fm/rss" } }
0
Kotlin
0
2
78a206c53d8f4b613a0283c03aa30236fc4858d7
6,373
castaway
MIT License
app/movies/src/main/java/io/github/kunal26das/yify/movies/compose/Movies.kt
kunal26das
283,553,926
false
{"Kotlin": 116060, "Swift": 614}
package io.github.kunal26das.yify.movies.compose import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.grid.rememberLazyGridState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowDownward import androidx.compose.material.icons.filled.ArrowUpward import androidx.compose.material.icons.filled.Clear import androidx.compose.material3.DismissibleNavigationDrawer import androidx.compose.material3.DrawerValue import androidx.compose.material3.ElevatedCard import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedButton import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Slider import androidx.compose.material3.Text import androidx.compose.material3.rememberDrawerState import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalFocusManager import androidx.compose.ui.platform.LocalSoftwareKeyboardController import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.hilt.navigation.compose.hiltViewModel import androidx.paging.compose.collectAsLazyPagingItems import io.github.kunal26das.common.compose.Dropdown import io.github.kunal26das.common.compose.LocalNavigationBarHeight import io.github.kunal26das.common.compose.LocalStatusBarHeight import io.github.kunal26das.yify.movies.R import io.github.kunal26das.yify.movies.domain.model.Genre import io.github.kunal26das.yify.movies.domain.model.OrderBy import io.github.kunal26das.yify.movies.domain.model.Quality import io.github.kunal26das.yify.movies.domain.model.SortBy import io.github.kunal26das.yify.movies.presentation.MoviesViewModel @Composable fun Movies( modifier: Modifier = Modifier, viewModel: MoviesViewModel = hiltViewModel(), ) { val state = rememberLazyGridState() val drawerState = rememberDrawerState(DrawerValue.Closed) val moviesCount by viewModel.moviesCount.collectAsState() val moviePreference by viewModel.moviePreference.collectAsState() val uncategorizedMovies = viewModel.uncategorizedMovies.collectAsLazyPagingItems() val firstVisibleItemIndex by remember { derivedStateOf { state.firstVisibleItemIndex } } val visibleItemsCount by remember { derivedStateOf { state.layoutInfo.visibleItemsInfo.size } } LaunchedEffect(moviePreference) { try { state.scrollToItem(0) } catch (_: IndexOutOfBoundsException) { } } DismissibleNavigationDrawer( modifier = modifier, drawerState = drawerState, drawerContent = { ElevatedCard( modifier = Modifier .width(360.dp) .fillMaxHeight(), shape = RoundedCornerShape( bottomEnd = 16.dp, topEnd = 16.dp, ) ) { DrawerContent() } }, ) { Box(modifier = Modifier.fillMaxSize()) { VerticalGridMovies( modifier = Modifier.fillMaxSize(), contentPadding = PaddingValues( vertical = LocalStatusBarHeight.current, horizontal = 5.dp, ), moviePadding = PaddingValues(5.dp), movies = uncategorizedMovies, state = state, ) AnimatedVisibility( modifier = Modifier .padding(bottom = LocalNavigationBarHeight.current + 24.dp) .align(Alignment.BottomCenter), visible = moviesCount > 0 && firstVisibleItemIndex > 0, enter = fadeIn(), exit = fadeOut(), ) { Text( modifier = Modifier .background( shape = RoundedCornerShape(32.dp), color = MaterialTheme.colorScheme.background, ) .padding( horizontal = 10.dp, vertical = 2.dp, ), text = "${firstVisibleItemIndex + visibleItemsCount}/${moviesCount}", color = MaterialTheme.colorScheme.onSurface, textAlign = TextAlign.Center, fontSize = 12.sp, ) } } } } @Composable private fun DrawerContent( modifier: Modifier = Modifier, ) { val contentModifier = Modifier.fillMaxWidth() Column( modifier = modifier.padding( vertical = LocalStatusBarHeight.current, horizontal = 16.dp, ), verticalArrangement = Arrangement.spacedBy(12.dp), ) { SearchTextField(modifier = contentModifier) GenreDropdown(modifier = contentModifier) QualityDropdown(modifier = contentModifier) SortByDropdown(modifier = contentModifier) MinimumRating(modifier = contentModifier) ClearButton(modifier = contentModifier) } } @Composable private fun SearchTextField( modifier: Modifier = Modifier, viewModel: MoviesViewModel = hiltViewModel(), ) { val focusManager = LocalFocusManager.current val searchQuery by viewModel.searchQuery.collectAsState() val keyboardController = LocalSoftwareKeyboardController.current OutlinedTextField( modifier = modifier, readOnly = false, label = { Text(stringResource(R.string.search)) }, trailingIcon = { IconButton( onClick = { viewModel.search(null) focusManager.clearFocus() } ) { Icon( imageVector = Icons.Filled.Clear, contentDescription = null, ) } }, value = searchQuery, onValueChange = { viewModel.search(it) }, keyboardOptions = KeyboardOptions( imeAction = ImeAction.Search, autoCorrectEnabled = false, ), keyboardActions = KeyboardActions( onSearch = { // onBackPressedCallback.handleOnBackPressed() keyboardController?.hide() } ) ) } @Composable private fun GenreDropdown( modifier: Modifier = Modifier, viewModel: MoviesViewModel = hiltViewModel() ) { val moviePreference by viewModel.moviePreference.collectAsState() Dropdown( modifier2 = modifier, label = stringResource(R.string.genre), selection = moviePreference.genre, items = Genre.entries, name = { it.name }, onSelect = { viewModel.setGenre(it) } ) } @Composable private fun QualityDropdown( modifier: Modifier = Modifier, viewModel: MoviesViewModel = hiltViewModel(), ) { val context = LocalContext.current val moviePreference by viewModel.moviePreference.collectAsState() Dropdown( modifier2 = modifier, label = stringResource(R.string.quality), selection = moviePreference.quality, items = Quality.entries.reversed(), showTrailingIcon = false, name = { when (it) { Quality.Low -> context.getString(R.string.low) Quality.Medium -> context.getString(R.string.medium) Quality.High -> context.getString(R.string.high) else -> "" } }, onSelect = { viewModel.setQuality(it) } ) } @Composable private fun MinimumRating( modifier: Modifier = Modifier, viewModel: MoviesViewModel = hiltViewModel(), ) { val moviePreference by viewModel.moviePreference.collectAsState() Row( modifier = modifier, verticalAlignment = Alignment.CenterVertically, ) { Text(text = stringResource(R.string.rating)) Slider( modifier = Modifier .weight(1f) .padding(horizontal = 12.dp), steps = 10, valueRange = 0f..9f, value = moviePreference.minimumRating.toFloat(), onValueChange = { viewModel.setMinimumRating(it.toInt()) } ) Text(text = moviePreference.minimumRating.toString()) } } @Composable private fun SortByDropdown( modifier: Modifier = Modifier, viewModel: MoviesViewModel = hiltViewModel(), ) { val context = LocalContext.current val moviePreference by viewModel.moviePreference.collectAsState() Dropdown( modifier = modifier, modifier2 = Modifier.fillMaxWidth(), label = stringResource(R.string.sort_by), selection = moviePreference.sortBy, items = listOf(SortBy.DateAdded, SortBy.Title, SortBy.Year, SortBy.Rating), name = { when (it) { SortBy.DateAdded -> context.getString(R.string.date_added) SortBy.Peers -> context.getString(R.string.peers) SortBy.Rating -> context.getString(R.string.rating) SortBy.Seeds -> context.getString(R.string.seeds) SortBy.Title -> context.getString(R.string.title) SortBy.Year -> context.getString(R.string.year) } }, onSelect = { viewModel.setSortBy(it) }, trailingIcon = { IconButton( onClick = { viewModel.setOrderBy( when (moviePreference.orderBy) { OrderBy.Ascending -> OrderBy.Descending OrderBy.Descending -> OrderBy.Ascending } ) } ) { Icon( imageVector = when (moviePreference.orderBy) { OrderBy.Descending -> Icons.Filled.ArrowDownward OrderBy.Ascending -> Icons.Filled.ArrowUpward }, contentDescription = null, ) } } ) } @Composable private fun ClearButton( modifier: Modifier = Modifier, viewModel: MoviesViewModel = hiltViewModel() ) { OutlinedButton( modifier = modifier, onClick = { viewModel.clear() }, contentPadding = PaddingValues(12.dp), content = { Text(text = stringResource(R.string.reset)) } ) }
0
Kotlin
1
1
c88d5cdf4d6ce291377254466e779878ad9c7562
12,014
yify
Apache License 2.0
data/src/main/java/com/jjswigut/data/local/CardAction.kt
JJSwigut
360,247,838
false
null
package com.jjswigut.data.local import com.jjswigut.data.local.entities.ListEntity import com.jjswigut.data.local.entities.TaskEntity sealed class CardAction { data class ListCardClicked(val list: ListEntity) : CardAction() data class TaskCardChecked(val task: TaskEntity) : CardAction() data class AddCardClicked(val type: AddType) : CardAction() }
0
Kotlin
0
0
0151363bc0d0e3ff0d8ffa9f8ca6fcac7fb20e3c
363
DoitToit
The Unlicense
example-app/src/main/java/foo/bar/example/OG.kt
erdo
364,914,424
false
{"Kotlin": 43364}
package foo.bar.example import android.app.Application import co.early.fore.kt.core.logging.AndroidLogger import co.early.fore.kt.core.logging.Logger import co.early.persista.PerSista import foo.bar.example.feature.wallet.Wallet import java.util.HashMap /** * OG - Object Graph, pure DI implementation * * Copyright © 2015-2021 early.co. All rights reserved. */ @Suppress("UNUSED_PARAMETER") object OG { private var initialized = false private val dependencies = HashMap<Class<*>, Any>() fun setApplication(application: Application) { // create dependency graph val logger = AndroidLogger("persista_") val perSista = PerSista( dataDirectory = application.filesDir, logger = logger, ) val wallet = Wallet( perSista, logger ) // add models to the dependencies map if you will need them later dependencies[Wallet::class.java] = wallet dependencies[Logger::class.java] = logger } fun init() { if (!initialized) { initialized = true // run any necessary initialization code once object graph has been created here } } /** * This is how dependencies get injected, typically an Activity/Fragment/View will call this * during the onCreate()/onCreateView()/onFinishInflate() method respectively for each of the * dependencies it needs. * * Can use a DI library for similar behaviour using annotations * * Will return mocks if they have been set previously in putMock() * * * Call it like this: * * <code> * yourModel = OG[YourModel::class.java] * </code> * * If you want to more tightly scoped object, one way is to pass a factory class here and create * an instance where you need it * */ @Suppress("UNCHECKED_CAST") operator fun <T> get(model: Class<T>): T = dependencies[model] as T fun <T> putMock(clazz: Class<T>, instance: T) { dependencies[clazz] = instance as Any } }
0
Kotlin
0
7
38b3d1fb5e70143e589ebf7b8f96afe32f229142
2,096
persista
Apache License 2.0
kotlinx-datetime-wasm/src/commonMain/kotlin/kotlinx/datetime/ZonedDateTime.kt
sdeleuze
586,987,800
false
null
/* * Copyright 2019-2020 JetBrains s.r.o. * Use of this source code is governed by the Apache 2.0 License that can be found in the LICENSE.txt file. */ /* Based on the ThreeTenBp project. * Copyright (c) 2007-present, Stephen Colebourne & Michael Nascimento Santos */ package kotlinx.datetime internal class ZonedDateTime(val dateTime: LocalDateTime, private val zone: TimeZone, val offset: ZoneOffset) { /** * @throws IllegalArgumentException if the result exceeds the boundaries * @throws ArithmeticException if arithmetic overflow occurs */ internal fun plus(value: Int, unit: DateTimeUnit.DateBased): ZonedDateTime = dateTime.plus(value, unit).resolve() // Never throws in practice private fun LocalDateTime.resolve(): ZonedDateTime = with(zone) { atZone(offset) } override fun equals(other: Any?): Boolean = this === other || other is ZonedDateTime && dateTime == other.dateTime && offset == other.offset && zone == other.zone @OptIn(ExperimentalStdlibApi::class) override fun hashCode(): Int { return dateTime.hashCode() xor offset.hashCode() xor zone.hashCode().rotateLeft(3) } override fun toString(): String { var str = dateTime.toString() + offset.toString() if (offset !== zone) { str += "[$zone]" } return str } } internal fun ZonedDateTime.toInstant(): Instant = Instant(dateTime.toEpochSecond(offset), dateTime.nanosecond) // org.threeten.bp.LocalDateTime#ofEpochSecond + org.threeten.bp.ZonedDateTime#create /** * @throws IllegalArgumentException if the [Instant] exceeds the boundaries of [LocalDateTime] */ internal fun Instant.toZonedLocalDateTime(zone: TimeZone): ZonedDateTime { val currentOffset = offsetIn(zone) val localSecond: Long = epochSeconds + currentOffset.totalSeconds // overflow caught later val localEpochDay = floorDiv(localSecond, SECONDS_PER_DAY.toLong()).toInt() val secsOfDay = floorMod(localSecond, SECONDS_PER_DAY.toLong()).toInt() val date: LocalDate = LocalDate.ofEpochDay(localEpochDay) // may throw val time: LocalTime = LocalTime.ofSecondOfDay(secsOfDay, nanosecondsOfSecond) return ZonedDateTime(LocalDateTime(date, time), zone, currentOffset) } // org.threeten.bp.ZonedDateTime#until // This version is simplified and to be used ONLY in case you know the timezones are equal! /** * @throws ArithmeticException on arithmetic overflow * @throws DateTimeArithmeticException if setting [other] to the offset of [this] leads to exceeding boundaries of * [LocalDateTime]. */ internal fun ZonedDateTime.until(other: ZonedDateTime, unit: DateTimeUnit): Long = when (unit) { // if the time unit is date-based, the offsets are disregarded and only the dates and times are compared. is DateTimeUnit.DateBased -> dateTime.until(other.dateTime, unit).toLong() // if the time unit is not date-based, we need to make sure that [other] is at the same offset as [this]. is DateTimeUnit.TimeBased -> { val offsetDiff = offset.totalSeconds - other.offset.totalSeconds val otherLdtAdjusted = try { other.dateTime.plusSeconds(offsetDiff) } catch (e: IllegalArgumentException) { throw DateTimeArithmeticException( "Unable to find difference between date-times, as one of them overflowed") } dateTime.until(otherLdtAdjusted, unit) } }
78
null
91
81
b1cbeb9f537a618570f13f1d1538fd27f94fd45e
3,500
kowasm
Apache License 2.0
plugins/maven/src/main/java/org/jetbrains/idea/maven/dsl/MavenDependencyModificator.kt
ingokegel
72,937,917
false
null
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.idea.maven.dsl import com.intellij.buildsystem.model.unified.UnifiedCoordinates import com.intellij.buildsystem.model.unified.UnifiedDependency import com.intellij.buildsystem.model.unified.UnifiedDependencyRepository import com.intellij.externalSystem.ExternalDependencyModificator import com.intellij.openapi.application.ReadAction import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.psi.PsiDocumentManager import com.intellij.psi.xml.XmlFile import com.intellij.psi.xml.XmlTag import com.intellij.util.xml.DomUtil import com.intellij.util.xml.GenericDomValue import org.jetbrains.annotations.NotNull import org.jetbrains.idea.maven.dom.MavenDomElement import org.jetbrains.idea.maven.dom.MavenDomUtil import org.jetbrains.idea.maven.dom.converters.MavenDependencyCompletionUtil import org.jetbrains.idea.maven.dom.model.MavenDomDependency import org.jetbrains.idea.maven.dom.model.MavenDomProjectModel import org.jetbrains.idea.maven.dom.model.MavenDomRepository import org.jetbrains.idea.maven.model.MavenConstants.SCOPE_COMPILE import org.jetbrains.idea.maven.model.MavenId import org.jetbrains.idea.maven.project.MavenProject import org.jetbrains.idea.maven.project.MavenProjectBundle import org.jetbrains.idea.maven.project.MavenProjectsManager val mavenTopLevelElementsOrder = listOf( "modelVersion", "parent", "groupId", "artifactId", "version", "packaging", "properties", "name", "description", "url", "inceptionYear", "licenses", "organization", "developers", "contributors", "modules", "dependencyManagement", "dependencies", "build", "reporting", "issueManagement", "ciManagement", "mailingLists", "scm", "prerequisites", "repositories", "pluginRepositories", "distributionManagement", "profiles" ) val elementsBeforeDependencies = elementsBefore("dependencies") val elementsBeforeRepositories = elementsBefore("repositories") fun elementsBefore(s: String): Set<String> { return mavenTopLevelElementsOrder.takeWhile { it != s } .toSet() } class MavenDependencyModificator(private val myProject: Project) : ExternalDependencyModificator { private val myProjectsManager: MavenProjectsManager = MavenProjectsManager.getInstance(myProject) private val myDocumentManager: PsiDocumentManager = PsiDocumentManager.getInstance(myProject) private fun addDependenciesTagIfNotExists(psiFile: XmlFile, model: MavenDomProjectModel) { addTagIfNotExists(psiFile, model.dependencies, elementsBeforeDependencies) } private fun addRepositoriesTagIfNotExists(psiFile: XmlFile, model: MavenDomProjectModel) { addTagIfNotExists(psiFile, model.repositories, elementsBeforeRepositories) } private fun addTagIfNotExists(psiFile: XmlFile, element: MavenDomElement, elementsBefore: Set<String>) { if (element.exists()) { return } val rootTag = psiFile.rootTag; if (rootTag == null) { element.ensureTagExists(); return } val children = rootTag.children if (children == null || children.isEmpty()) { element.ensureTagExists() return } val lastOrNull = children .mapNotNull { it as? XmlTag } .lastOrNull { elementsBefore.contains(it.name) } val child = rootTag.createChildTag(element.xmlElementName, rootTag.namespace, null, false) rootTag.addAfter(child, lastOrNull) } private fun getDependenciesModel(module: Module, groupId: String, artifactId: String): Pair<MavenDomProjectModel, MavenDomDependency?> { val project: MavenProject = myProjectsManager.findProject(module) ?: throw IllegalArgumentException(MavenProjectBundle.message( "maven.project.not.found.for", module.name)) return ReadAction.compute<Pair<MavenDomProjectModel, MavenDomDependency?>, Throwable> { val model = MavenDomUtil.getMavenDomProjectModel(myProject, project.getFile()) ?: throw IllegalStateException( MavenProjectBundle.message("maven.model.error", module.name)) val managedDependency = MavenDependencyCompletionUtil.findManagedDependency(model, myProject, groupId, artifactId) return@compute Pair(model, managedDependency) } } override fun supports(module: Module): Boolean { return myProjectsManager.isMavenizedModule(module) } override fun addDependency(module: Module, descriptor: UnifiedDependency) { requireNotNull(descriptor.coordinates.groupId) requireNotNull(descriptor.coordinates.version) requireNotNull(descriptor.coordinates.artifactId) val mavenId = descriptor.coordinates.toMavenId() val (model, managedDependency) = getDependenciesModel(module, mavenId.groupId!!, mavenId.artifactId!!) val psiFile = DomUtil.getFile(model) WriteCommandAction.writeCommandAction(myProject, psiFile).compute<Unit, Throwable> { addDependenciesTagIfNotExists(psiFile, model); val dependency = MavenDomUtil.createDomDependency(model, null) dependency.groupId.stringValue = mavenId.groupId dependency.artifactId.stringValue = mavenId.artifactId val scope = toMavenScope(descriptor.scope, managedDependency?.scope?.stringValue); scope?.let { dependency.scope.stringValue = it } if (managedDependency == null || managedDependency.version.stringValue != mavenId.version) { dependency.version.stringValue = mavenId.version } saveFile(psiFile) } } override fun updateDependency(module: Module, oldDescriptor: UnifiedDependency, newDescriptor: UnifiedDependency) { requireNotNull(newDescriptor.coordinates.groupId) requireNotNull(newDescriptor.coordinates.version) requireNotNull(newDescriptor.coordinates.artifactId) val oldMavenId = oldDescriptor.coordinates.toMavenId() val newMavenId = newDescriptor.coordinates.toMavenId() val (model, managedDependency) = ReadAction.compute<Pair<MavenDomProjectModel, MavenDomDependency?>, Throwable> { getDependenciesModel(module, oldMavenId.groupId!!, oldMavenId.artifactId!!) } val psiFile = managedDependency?.let(DomUtil::getFile) ?: DomUtil.getFile(model) WriteCommandAction.writeCommandAction(myProject, psiFile).compute<Unit, Throwable> { if (managedDependency != null) { val parentModel = managedDependency.getParentOfType(MavenDomProjectModel::class.java, true) if (parentModel != null) { updateVariableOrValue(parentModel, managedDependency.version, newMavenId.version!!) } else { managedDependency.version.stringValue = newDescriptor.coordinates.version } } else { for (dep in model.dependencies.dependencies) { if (dep.artifactId.stringValue == oldMavenId.artifactId && dep.groupId.stringValue == oldMavenId.groupId) { updateVariableOrValue(model, dep.artifactId, newMavenId.artifactId!!) updateVariableOrValue(model, dep.groupId, newMavenId.groupId!!) updateVariableOrValue(model, dep.version, newMavenId.version!!) } } } saveFile(psiFile) } } override fun removeDependency(module: Module, descriptor: UnifiedDependency) { requireNotNull(descriptor.coordinates.groupId) requireNotNull(descriptor.coordinates.version) val mavenId = descriptor.coordinates.toMavenId() val (model, _) = getDependenciesModel(module, mavenId.groupId!!, mavenId.artifactId!!) val psiFile = DomUtil.getFile(model) WriteCommandAction.writeCommandAction(myProject, psiFile).compute<Unit, Throwable> { for (dep in model.dependencies.dependencies) { if (dep.artifactId.stringValue == mavenId.artifactId && dep.groupId.stringValue == mavenId.groupId) { dep.xmlTag?.delete() } } if (model.dependencies.dependencies.isEmpty()) { model.dependencies.xmlTag?.delete(); } saveFile(psiFile) } } override fun addRepository(module: Module, repository: UnifiedDependencyRepository) { val project: MavenProject = myProjectsManager.findProject(module) ?: throw IllegalArgumentException(MavenProjectBundle.message( "maven.project.not.found.for", module.name)) val model = ReadAction.compute<MavenDomProjectModel, Throwable> { MavenDomUtil.getMavenDomProjectModel(myProject, project.getFile()) ?: throw IllegalStateException( MavenProjectBundle.message("maven.model.error", module.name)) } for (repo in model.repositories.repositories) { if (repo.url.stringValue?.trimLastSlash() == repository.url.trimLastSlash()) { return; } } val psiFile = DomUtil.getFile(model) WriteCommandAction.writeCommandAction(myProject, psiFile).compute<Unit, Throwable> { addRepositoriesTagIfNotExists(psiFile, model) val repoTag = model.repositories.addRepository() repository.id?.let { repoTag.id.stringValue = it } repository.name?.let { repoTag.name.stringValue = it } repository.url.let { repoTag.url.stringValue = it } saveFile(psiFile) } } override fun deleteRepository(module: Module, repository: UnifiedDependencyRepository) { val project: MavenProject = myProjectsManager.findProject(module) ?: throw IllegalArgumentException(MavenProjectBundle.message( "maven.project.not.found.for", module.name)) val (model, repo) = ReadAction.compute<Pair<MavenDomProjectModel, MavenDomRepository?>, Throwable> { val model = MavenDomUtil.getMavenDomProjectModel(myProject, project.getFile()) ?: throw IllegalStateException( MavenProjectBundle.message("maven.model.error", module.name)) for (repo in model.repositories.repositories) { if (repo.url.stringValue?.trimLastSlash() == repository.url.trimLastSlash()) { return@compute Pair(model, repo) } } return@compute null; } if (repo == null) return; val psiFile = DomUtil.getFile(repo) WriteCommandAction.writeCommandAction(myProject, psiFile).compute<Unit, Throwable> { repo.xmlTag?.delete() if(model.repositories.repositories.isEmpty()) { model.repositories.xmlTag?.delete() } saveFile(psiFile) } } private fun saveFile(psiFile: @NotNull XmlFile) { val document = myDocumentManager.getDocument(psiFile) ?: throw IllegalStateException(MavenProjectBundle.message( "maven.model.error", psiFile)); myDocumentManager.doPostponedOperationsAndUnblockDocument(document) FileDocumentManager.getInstance().saveDocument(document) } private fun updateVariableOrValue(model: MavenDomProjectModel, domValue: GenericDomValue<String>, newValue: String) { val rawText = domValue.rawText?.trim() if (rawText != null && rawText.startsWith("${'$'}{") && rawText.endsWith("}")) { val propertyName = rawText.substring(2, rawText.length - 1); val subTags = model.properties.xmlTag?.subTags ?: emptyArray() for (subTag in subTags) { if (subTag.name == propertyName) { //TODO: recursive property declaration subTag.value.text = newValue return } } } else { domValue.stringValue = newValue } } private fun toMavenScope(scope: String?, managedScope: String?): String? { if (managedScope == null) { if (scope == null || scope == SCOPE_COMPILE) return null return scope; } if (scope == managedScope) return null return scope } override fun declaredDependencies(module: Module): List<UnifiedDependency> { val project = MavenProjectsManager.getInstance(module.project).findProject(module) ?: return emptyList() return ReadAction.compute<List<UnifiedDependency>, Throwable> { val model = MavenDomUtil.getMavenDomProjectModel(myProject, project.getFile()) ?: throw IllegalStateException( MavenProjectBundle.message("maven.model.error", module.name)) model.dependencies.dependencies.map { var scope = it.scope.stringValue; if (scope == SCOPE_COMPILE) scope = null UnifiedDependency(it.groupId.stringValue, it.artifactId.stringValue, it.version.rawText, scope) } } } override fun declaredRepositories(module: Module): List<UnifiedDependencyRepository> { val project = MavenProjectsManager.getInstance(module.project).findProject(module) ?: return emptyList() return ReadAction.compute<List<UnifiedDependencyRepository>, Throwable> { val model = MavenDomUtil.getMavenDomProjectModel(myProject, project.getFile()) ?: throw IllegalStateException( MavenProjectBundle.message("maven.model.error", module.name)) model.repositories.repositories.map { UnifiedDependencyRepository(it.id.stringValue, it.name.stringValue, it.url.stringValue ?: "") } } } } private fun String.trimLastSlash(): String { return trimEnd('/'); } private fun UnifiedCoordinates.toMavenId(): MavenId { return MavenId(groupId, artifactId, version) }
284
null
5162
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
13,295
intellij-community
Apache License 2.0
coroutine-cancellation/app/src/main/java/com/example/coroutine_cancellation/homework/assignmenttwo/MoneyTransferState.kt
mygomii
855,464,049
false
{"Kotlin": 84679}
package com.example.coroutine_cancellation.homework.assignmenttwo import androidx.compose.foundation.text.input.TextFieldState data class MoneyTransferState( val savingsBalance: Double = 1000.0, val checkingBalance: Double = 500.0, val transferAmount: TextFieldState = TextFieldState(), val isTransferring: Boolean = false, val resultMessage: String? = null, val processingState: ProcessingState? = null, )
0
Kotlin
0
0
c48746cd9ffe561089787c9c233689bceebd01e1
434
coroutines-flow-study
Apache License 2.0
matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/verification/qrcode/DefaultQrCodeVerificationTransaction.kt
matrix-org
287,466,066
false
null
/* * Copyright 2020 New Vector Ltd * Copyright 2020 The Matrix.org Foundation C.I.C. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.matrix.android.sdk.internal.crypto.verification.qrcode import org.matrix.android.sdk.api.session.crypto.crosssigning.CrossSigningService import org.matrix.android.sdk.api.session.crypto.verification.CancelCode import org.matrix.android.sdk.api.session.crypto.verification.QrCodeVerificationTransaction import org.matrix.android.sdk.api.session.crypto.verification.VerificationTxState import org.matrix.android.sdk.api.session.events.model.EventType import org.matrix.android.sdk.internal.crypto.IncomingGossipingRequestManager import org.matrix.android.sdk.internal.crypto.OutgoingGossipingRequestManager import org.matrix.android.sdk.internal.crypto.actions.SetDeviceVerificationAction import org.matrix.android.sdk.internal.crypto.crosssigning.fromBase64 import org.matrix.android.sdk.internal.crypto.crosssigning.fromBase64Safe import org.matrix.android.sdk.internal.crypto.store.IMXCryptoStore import org.matrix.android.sdk.internal.crypto.verification.DefaultVerificationTransaction import org.matrix.android.sdk.internal.crypto.verification.ValidVerificationInfoStart import org.matrix.android.sdk.internal.util.exhaustive import timber.log.Timber internal class DefaultQrCodeVerificationTransaction( setDeviceVerificationAction: SetDeviceVerificationAction, override val transactionId: String, override val otherUserId: String, override var otherDeviceId: String?, private val crossSigningService: CrossSigningService, outgoingGossipingRequestManager: OutgoingGossipingRequestManager, incomingGossipingRequestManager: IncomingGossipingRequestManager, private val cryptoStore: IMXCryptoStore, // Not null only if other user is able to scan QR code private val qrCodeData: QrCodeData?, val userId: String, val deviceId: String, override val isIncoming: Boolean ) : DefaultVerificationTransaction( setDeviceVerificationAction, crossSigningService, outgoingGossipingRequestManager, incomingGossipingRequestManager, userId, transactionId, otherUserId, otherDeviceId, isIncoming), QrCodeVerificationTransaction { override val qrCodeText: String? get() = qrCodeData?.toEncodedString() override var state: VerificationTxState = VerificationTxState.None set(newState) { field = newState listeners.forEach { try { it.transactionUpdated(this) } catch (e: Throwable) { Timber.e(e, "## Error while notifying listeners") } } } override fun userHasScannedOtherQrCode(otherQrCodeText: String) { val otherQrCodeData = otherQrCodeText.toQrCodeData() ?: run { Timber.d("## Verification QR: Invalid QR Code Data") cancel(CancelCode.QrCodeInvalid) return } // Perform some checks if (otherQrCodeData.transactionId != transactionId) { Timber.d("## Verification QR: Invalid transaction actual ${otherQrCodeData.transactionId} expected:$transactionId") cancel(CancelCode.QrCodeInvalid) return } // check master key val myMasterKey = crossSigningService.getUserCrossSigningKeys(userId)?.masterKey()?.unpaddedBase64PublicKey var canTrustOtherUserMasterKey = false // Check the other device view of my MSK when (otherQrCodeData) { is QrCodeData.VerifyingAnotherUser -> { // key2 (aka otherUserMasterCrossSigningPublicKey) is what the one displaying the QR code (other user) think my MSK is. // Let's check that it's correct // If not -> Cancel if (otherQrCodeData.otherUserMasterCrossSigningPublicKey != myMasterKey) { Timber.d("## Verification QR: Invalid other master key ${otherQrCodeData.otherUserMasterCrossSigningPublicKey}") cancel(CancelCode.MismatchedKeys) return } else Unit } is QrCodeData.SelfVerifyingMasterKeyTrusted -> { // key1 (aka userMasterCrossSigningPublicKey) is the session displaying the QR code view of our MSK. // Let's check that I see the same MSK // If not -> Cancel if (otherQrCodeData.userMasterCrossSigningPublicKey != myMasterKey) { Timber.d("## Verification QR: Invalid other master key ${otherQrCodeData.userMasterCrossSigningPublicKey}") cancel(CancelCode.MismatchedKeys) return } else { // I can trust the MSK then (i see the same one, and other session tell me it's trusted by him) canTrustOtherUserMasterKey = true } } is QrCodeData.SelfVerifyingMasterKeyNotTrusted -> { // key2 (aka userMasterCrossSigningPublicKey) is the session displaying the QR code view of our MSK. // Let's check that it's the good one // If not -> Cancel if (otherQrCodeData.userMasterCrossSigningPublicKey != myMasterKey) { Timber.d("## Verification QR: Invalid other master key ${otherQrCodeData.userMasterCrossSigningPublicKey}") cancel(CancelCode.MismatchedKeys) return } else { // Nothing special here, we will send a reciprocate start event, and then the other session will trust it's view of the MSK } } }.exhaustive val toVerifyDeviceIds = mutableListOf<String>() // Let's now check the other user/device key material when (otherQrCodeData) { is QrCodeData.VerifyingAnotherUser -> { // key1(aka userMasterCrossSigningPublicKey) is the MSK of the one displaying the QR code (i.e other user) // Let's check that it matches what I think it should be if (otherQrCodeData.userMasterCrossSigningPublicKey != crossSigningService.getUserCrossSigningKeys(otherUserId)?.masterKey()?.unpaddedBase64PublicKey) { Timber.d("## Verification QR: Invalid user master key ${otherQrCodeData.userMasterCrossSigningPublicKey}") cancel(CancelCode.MismatchedKeys) return } else { // It does so i should mark it as trusted canTrustOtherUserMasterKey = true Unit } } is QrCodeData.SelfVerifyingMasterKeyTrusted -> { // key2 (aka otherDeviceKey) is my current device key in POV of the one displaying the QR code (i.e other device) // Let's check that it's correct if (otherQrCodeData.otherDeviceKey != cryptoStore.getUserDevice(userId, deviceId)?.fingerprint()) { Timber.d("## Verification QR: Invalid other device key ${otherQrCodeData.otherDeviceKey}") cancel(CancelCode.MismatchedKeys) return } else Unit // Nothing special here, we will send a reciprocate start event, and then the other session will trust my device // and thus allow me to request SSSS secret } is QrCodeData.SelfVerifyingMasterKeyNotTrusted -> { // key1 (aka otherDeviceKey) is the device key of the one displaying the QR code (i.e other device) // Let's check that it matches what I have locally if (otherQrCodeData.deviceKey != cryptoStore.getUserDevice(otherUserId, otherDeviceId ?: "")?.fingerprint()) { Timber.d("## Verification QR: Invalid device key ${otherQrCodeData.deviceKey}") cancel(CancelCode.MismatchedKeys) return } else { // Yes it does -> i should trust it and sign then upload the signature toVerifyDeviceIds.add(otherDeviceId ?: "") Unit } } }.exhaustive if (!canTrustOtherUserMasterKey && toVerifyDeviceIds.isEmpty()) { // Nothing to verify cancel(CancelCode.MismatchedKeys) return } // All checks are correct // Send the shared secret so that sender can trust me // qrCodeData.sharedSecret will be used to send the start request start(otherQrCodeData.sharedSecret) trust( canTrustOtherUserMasterKey = canTrustOtherUserMasterKey, toVerifyDeviceIds = toVerifyDeviceIds.distinct(), eventuallyMarkMyMasterKeyAsTrusted = true, autoDone = false ) } private fun start(remoteSecret: String, onDone: (() -> Unit)? = null) { if (state != VerificationTxState.None) { Timber.e("## Verification QR: start verification from invalid state") // should I cancel?? throw IllegalStateException("Interactive Key verification already started") } state = VerificationTxState.Started val startMessage = transport.createStartForQrCode( deviceId, transactionId, remoteSecret ) transport.sendToOther( EventType.KEY_VERIFICATION_START, startMessage, VerificationTxState.WaitingOtherReciprocateConfirm, CancelCode.User, onDone ) } override fun cancel() { cancel(CancelCode.User) } override fun cancel(code: CancelCode) { state = VerificationTxState.Cancelled(code, true) transport.cancelTransaction(transactionId, otherUserId, otherDeviceId ?: "", code) } override fun isToDeviceTransport() = false // Other user has scanned our QR code. check that the secret matched, so we can trust him fun onStartReceived(startReq: ValidVerificationInfoStart.ReciprocateVerificationInfoStart) { if (qrCodeData == null) { // Should not happen cancel(CancelCode.UnexpectedMessage) return } if (startReq.sharedSecret.fromBase64Safe()?.contentEquals(qrCodeData.sharedSecret.fromBase64()) == true) { // Ok, we can trust the other user // We can only trust the master key in this case // But first, ask the user for a confirmation state = VerificationTxState.QrScannedByOther } else { // Display a warning cancel(CancelCode.MismatchedKeys) } } fun onDoneReceived() { if (state != VerificationTxState.WaitingOtherReciprocateConfirm) { cancel(CancelCode.UnexpectedMessage) return } state = VerificationTxState.Verified transport.done(transactionId) {} } override fun otherUserScannedMyQrCode() { when (qrCodeData) { is QrCodeData.VerifyingAnotherUser -> { // Alice telling Bob that the code was scanned successfully is sufficient for Bob to trust Alice's key, trust(true, emptyList(), false) } is QrCodeData.SelfVerifyingMasterKeyTrusted -> { // I now know that I have the correct device key for other session, // and can sign it with the self-signing key and upload the signature trust(false, listOf(otherDeviceId ?: ""), false) } is QrCodeData.SelfVerifyingMasterKeyNotTrusted -> { // I now know that i can trust my MSK trust(true, emptyList(), true) } } } override fun otherUserDidNotScannedMyQrCode() { // What can I do then? // At least remove the transaction... cancel(CancelCode.MismatchedKeys) } }
75
null
418
97
55cc7362de34a840c67b4bbb3a14267bc8fd3b9c
12,867
matrix-android-sdk2
Apache License 2.0
core/src/game/robotm/gamesys/ItemType.kt
yichen0831
51,819,854
false
null
package game.robotm.gamesys import com.badlogic.gdx.math.MathUtils enum class ItemType { HardSkin, QuickHealing, FastFeet, LowGravity; companion object { val typeArray = arrayOf(HardSkin, QuickHealing, FastFeet, LowGravity) fun randomType(): ItemType { return typeArray[MathUtils.random(typeArray.size - 1)] } } }
0
Kotlin
2
1
eb85ca306b5e055cf83fad34468ce33382351c63
379
RobotM
Apache License 2.0
plugin-dotnet-server/src/main/kotlin/jetbrains/buildServer/dotnet/commands/TestCommandType.kt
JetBrains
49,584,664
false
null
/* * Copyright 2000-2021 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jetbrains.buildServer.dotnet.commands import jetbrains.buildServer.dotnet.DotnetCommandType import jetbrains.buildServer.dotnet.RequirementFactory /** * Provides parameters for dotnet restore command. */ class RestoreCommandType( private val _requirementFactory: RequirementFactory) : DotnetType(_requirementFactory) { override val name: String = DotnetCommandType.Restore.id override val editPage: String = "editRestoreParameters.jsp" override val viewPage: String = "viewRestoreParameters.jsp" }
3
null
25
91
68c95408c1d39158312573573591b8efa4d78cab
1,138
teamcity-dotnet-plugin
Apache License 2.0
tabler/src/commonMain/kotlin/com/woowla/compose/icon/collections/tabler/tabler/outline/Layout.kt
walter-juan
868,046,028
false
{"Kotlin": 20416825}
package com.woowla.compose.icon.collections.tabler.tabler.outline import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import com.woowla.compose.icon.collections.tabler.tabler.OutlineGroup import androidx.compose.ui.graphics.StrokeCap.Companion.Round as strokeCapRound import androidx.compose.ui.graphics.StrokeJoin.Companion.Round as strokeJoinRound public val OutlineGroup.Layout: ImageVector get() { if (_layout != null) { return _layout!! } _layout = Builder(name = "Layout", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin = strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(4.0f, 4.0f) moveToRelative(0.0f, 2.0f) arcToRelative(2.0f, 2.0f, 0.0f, false, true, 2.0f, -2.0f) horizontalLineToRelative(2.0f) arcToRelative(2.0f, 2.0f, 0.0f, false, true, 2.0f, 2.0f) verticalLineToRelative(1.0f) arcToRelative(2.0f, 2.0f, 0.0f, false, true, -2.0f, 2.0f) horizontalLineToRelative(-2.0f) arcToRelative(2.0f, 2.0f, 0.0f, false, true, -2.0f, -2.0f) close() } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin = strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(4.0f, 13.0f) moveToRelative(0.0f, 2.0f) arcToRelative(2.0f, 2.0f, 0.0f, false, true, 2.0f, -2.0f) horizontalLineToRelative(2.0f) arcToRelative(2.0f, 2.0f, 0.0f, false, true, 2.0f, 2.0f) verticalLineToRelative(3.0f) arcToRelative(2.0f, 2.0f, 0.0f, false, true, -2.0f, 2.0f) horizontalLineToRelative(-2.0f) arcToRelative(2.0f, 2.0f, 0.0f, false, true, -2.0f, -2.0f) close() } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin = strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(14.0f, 4.0f) moveToRelative(0.0f, 2.0f) arcToRelative(2.0f, 2.0f, 0.0f, false, true, 2.0f, -2.0f) horizontalLineToRelative(2.0f) arcToRelative(2.0f, 2.0f, 0.0f, false, true, 2.0f, 2.0f) verticalLineToRelative(12.0f) arcToRelative(2.0f, 2.0f, 0.0f, false, true, -2.0f, 2.0f) horizontalLineToRelative(-2.0f) arcToRelative(2.0f, 2.0f, 0.0f, false, true, -2.0f, -2.0f) close() } } .build() return _layout!! } private var _layout: ImageVector? = null
0
Kotlin
0
1
b037895588c2f62d069c724abe624b67c0889bf9
3,530
compose-icon-collections
MIT License
maestro-ios-driver/src/main/kotlin/hierarchy/Error.kt
mobile-dev-inc
476,427,476
false
null
package hierarchy import com.fasterxml.jackson.annotation.JsonProperty data class Error( @JsonProperty("errorMessage") val errorMessage: String, @JsonProperty("errorCode") val errorCode: String, )
236
Kotlin
160
4,242
6d369c39c7e9735d58311d0e3c83dc6ff862ac66
206
maestro
Apache License 2.0
apollo-ast/src/main/kotlin/com/apollographql/apollo3/ast/gqldocument.kt
wavemm
111,576,468
false
null
package com.apollographql.apollo3.ast import com.apollographql.apollo3.annotations.ApolloDeprecatedSince import okio.buffer import okio.source fun GQLDocument.withBuiltinDefinitions(): GQLDocument { return withDefinitions(builtinDefinitions()) } fun GQLDocument.withoutBuiltinDefinitions(): GQLDocument { return withoutDefinitions(builtinDefinitions()) } @ApolloDeprecatedSince(ApolloDeprecatedSince.Version.v3_3_1) @Deprecated("This method is deprecated and will be removed in a future version") fun GQLDocument.withBuiltinDirectives(): GQLDocument { return withDefinitions(builtinDefinitions().filterIsInstance<GQLDirectiveDefinition>()) } @ApolloDeprecatedSince(ApolloDeprecatedSince.Version.v3_3_1) @Deprecated("This method is deprecated and will be removed in a future version") fun GQLDocument.withoutBuiltinDirectives(): GQLDocument { return withoutDefinitions(builtinDefinitions().filterIsInstance<GQLDirectiveDefinition>()) } @ApolloDeprecatedSince(ApolloDeprecatedSince.Version.v3_3_1) @Deprecated("This method is deprecated and will be removed in a future version") fun GQLDocument.withApolloDefinitions(): GQLDocument { @Suppress("DEPRECATION") return withDefinitions(apolloDefinitions()) } /** * Definitions from the spec */ fun builtinDefinitions() = definitionsFromResources("builtins.graphqls") /** * The @link definition for bootstrapping * * https://specs.apollo.dev/link/v1.0/ */ fun linkDefinitions() = definitionsFromResources("link.graphqls") @Deprecated("Use apolloDefinitions(version) instead", ReplaceWith("apolloDefinitions(\"v0.1\")")) fun apolloDefinitions() = apolloDefinitions("v0.1") /** * Extra apollo specific definitions from https://specs.apollo.dev/kotlin_labs/<[version]> */ fun apolloDefinitions(version: String) = definitionsFromResources("apollo-$version.graphqls") private fun definitionsFromResources(name: String): List<GQLDefinition> { return GQLDocument::class.java.getResourceAsStream("/$name")!! .source() .buffer() .parseAsGQLDocument("($name)") .valueAssertNoErrors() .definitions } private fun GQLDocument.withoutDefinitions(definitions: List<GQLDefinition>): GQLDocument { val excludedNames = definitions.map { check(it is GQLNamed) it.name }.toSet() return copy( definitions = this.definitions.filter { if (it !is GQLNamed) { // GQLSchemaDefinition is not a GQLNamed return@filter true } !excludedNames.contains(it.name) } ) } internal enum class ConflictResolution { /** * If a definition exists in both left and right, throw an error */ Error, //MergeIfSameDefinition, /** * If a definition exists in both left and right, use left always */ TakeLeft } internal fun combineDefinitions(left: List<GQLDefinition>, right: List<GQLDefinition>, conflictResolution: ConflictResolution): List<GQLDefinition> { val mergedDefinitions = left.toMutableList() right.forEach { builtInTypeDefinition -> check(builtInTypeDefinition is GQLNamed) { "only extra named definitions are supported" } val existingDefinition = mergedDefinitions.firstOrNull { (it as? GQLNamed)?.name == builtInTypeDefinition.name } if (existingDefinition != null) { if (conflictResolution == ConflictResolution.Error) { error("Apollo: definition '${builtInTypeDefinition.name}' is already in the schema at " + "'${existingDefinition.sourceLocation.filePath}:${existingDefinition.sourceLocation}'") } } else { mergedDefinitions.add(builtInTypeDefinition) } } return mergedDefinitions } /** * Adds [definitions] to the [GQLDocument] * * If a definition already exists, it is kept as is and a warning is logged * See https://spec.graphql.org/draft/#sel-FAHnBPLCAACCcooU * * A better implementation might verify that the definitions match or are compatible */ private fun GQLDocument.withDefinitions(definitions: List<GQLDefinition>): GQLDocument { return copy( definitions = combineDefinitions(this.definitions, definitions, ConflictResolution.TakeLeft) ) }
1
null
1
1
95bf818206e70fbb6f84dff5b960b9c1cf18c7db
4,126
apollo-android
MIT License
serialization-djvm/deserializers/src/main/kotlin/net/corda/serialization/djvm/deserializers/PublicKeyDecoder.kt
corda
70,137,417
false
null
package net.corda.serialization.djvm.deserializers import net.corda.core.crypto.Crypto import java.security.PublicKey import java.util.function.Function class PublicKeyDecoder : Function<ByteArray, PublicKey> { override fun apply(encoded: ByteArray): PublicKey { return Crypto.decodePublicKey(encoded) } }
58
null
1089
3,952
6ec8855c6e36f81cf8cfc8ef011e5ca23d95d757
324
corda
Apache License 2.0
auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/FirebaseUIActivity.kt
SagarBChauhan
216,040,454
false
null
package com.google.firebase.quickstart.auth.kotlin import android.app.Activity import android.content.Intent import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.view.View import android.widget.Toast import com.firebase.ui.auth.AuthUI import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.FirebaseUser import com.google.firebase.quickstart.auth.BuildConfig import com.google.firebase.quickstart.auth.R import kotlinx.android.synthetic.main.activity_firebase_ui.* /** * Demonstrate authentication using the FirebaseUI-Android library. This activity demonstrates * using FirebaseUI for basic email/password sign in. * * For more information, visit https://github.com/firebase/firebaseui-android */ class FirebaseUIActivity : AppCompatActivity(), View.OnClickListener { private lateinit var mAuth: FirebaseAuth override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_firebase_ui) mAuth = FirebaseAuth.getInstance() signInButton.setOnClickListener(this) signOutButton.setOnClickListener(this) } override fun onStart() { super.onStart() updateUI(mAuth.currentUser) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == RC_SIGN_IN) { if (resultCode == Activity.RESULT_OK) { // Sign in succeeded updateUI(mAuth.currentUser) } else { // Sign in failed Toast.makeText(this, "Sign In Failed", Toast.LENGTH_SHORT).show() updateUI(null) } } } private fun startSignIn() { // Build FirebaseUI sign in intent. For documentation on this operation and all // possible customization see: https://github.com/firebase/firebaseui-android val intent = AuthUI.getInstance().createSignInIntentBuilder() .setIsSmartLockEnabled(!BuildConfig.DEBUG) .setAvailableProviders(listOf(AuthUI.IdpConfig.EmailBuilder().build())) .setLogo(R.mipmap.ic_launcher) .build() startActivityForResult(intent, RC_SIGN_IN) } private fun updateUI(user: FirebaseUser?) { if (user != null) { // Signed in status.text = getString(R.string.firebaseui_status_fmt, user.email) detail.text = getString(R.string.id_fmt, user.uid) signInButton.visibility = View.GONE signOutButton.visibility = View.VISIBLE } else { // Signed out status.setText(R.string.signed_out) detail.text = null signInButton.visibility = View.VISIBLE signOutButton.visibility = View.GONE } } private fun signOut() { AuthUI.getInstance().signOut(this) updateUI(null) } override fun onClick(view: View) { when (view.id) { R.id.signInButton -> startSignIn() R.id.signOutButton -> signOut() } } companion object { private val RC_SIGN_IN = 9001 } }
4
null
0
5
d886d348a681f41f02e78d720cb74fb8c162e339
3,279
quickstart-android
Creative Commons Attribution 4.0 International
web-regresjonstest/src/test/kotlin/no/nav/su/se/bakover/web/LocalTestDataRoutes.kt
navikt
227,366,088
false
{"Kotlin": 8916291, "Shell": 3838, "TSQL": 1233, "Dockerfile": 800}
package no.nav.su.se.bakover.web import io.ktor.client.HttpClient import io.ktor.client.engine.java.Java import io.ktor.client.plugins.defaultRequest import io.ktor.http.HttpStatusCode import io.ktor.server.application.call import io.ktor.server.routing.Route import io.ktor.server.routing.post import no.nav.su.se.bakover.common.extensions.endOfMonth import no.nav.su.se.bakover.common.extensions.startOfMonth import no.nav.su.se.bakover.common.infrastructure.web.Resultat import no.nav.su.se.bakover.common.infrastructure.web.svar import no.nav.su.se.bakover.common.infrastructure.web.withBody import no.nav.su.se.bakover.common.person.Fnr import no.nav.su.se.bakover.test.fixedLocalDate import no.nav.su.se.bakover.test.generer import no.nav.su.se.bakover.web.routes.søknad.SØKNAD_PATH import no.nav.su.se.bakover.web.søknad.ny.nyDigitalSøknad import no.nav.su.se.bakover.web.søknadsbehandling.opprettAvslåttSøknadsbehandlingPgaVilkår import no.nav.su.se.bakover.web.søknadsbehandling.opprettInnvilgetSøknadsbehandling val localClient = HttpClient(Java) { defaultRequest { url("http://localhost:8080") } } internal fun Route.testDataRoutes() { data class NySøknadBody( val fnr: String?, ) post("$SØKNAD_PATH/dev/ny/uføre") { call.withBody<NySøknadBody> { val res = nyDigitalSøknad( fnr = it.fnr ?: Fnr.generer().toString(), client = localClient, ) call.svar(Resultat.json(HttpStatusCode.OK, res)) } } data class NySøknadsbehandlingBody( val fnr: String?, val resultat: String?, val fraOgMed: String?, val tilOgMed: String?, ) post("søknadsbehandling/dev/ny/iverksatt") { call.withBody<NySøknadsbehandlingBody> { call.svar( Resultat.json( HttpStatusCode.OK, if (it.resultat == "innvilget") { opprettInnvilgetSøknadsbehandling( fnr = it.fnr ?: Fnr.generer().toString(), fraOgMed = it.fraOgMed ?: fixedLocalDate.startOfMonth().toString(), tilOgMed = it.tilOgMed ?: fixedLocalDate.startOfMonth().plusMonths(11).endOfMonth().toString(), client = localClient, appComponents = null, ) } else { opprettAvslåttSøknadsbehandlingPgaVilkår( fnr = it.fnr ?: Fnr.generer().toString(), fraOgMed = it.fraOgMed ?: fixedLocalDate.startOfMonth().toString(), tilOgMed = it.tilOgMed ?: fixedLocalDate.startOfMonth().plusMonths(11).endOfMonth().toString(), client = localClient, ) }, ), ) } } }
6
Kotlin
1
1
f187a366e1b4ec73bf18f4ebc6a68109494f1c1b
2,952
su-se-bakover
MIT License
app/src/main/java/com/techbeloved/hymnbook/utils/workers/UnzipArchiveWorker.kt
techbeloved
133,724,406
false
null
package com.techbeloved.hymnbook.utils.workers import android.content.Context import androidx.hilt.Assisted import androidx.hilt.work.WorkerInject import androidx.work.Data import androidx.work.RxWorker import androidx.work.WorkerParameters import com.techbeloved.hymnbook.R import com.techbeloved.hymnbook.data.FileManager import io.reactivex.Single import timber.log.Timber import java.io.File /** * Takes care of unzipping a single archive. Input data should be supplied with the key [KEY_DOWNLOADED_ARCHIVE] * for the archive path and [KEY_UNZIP_FILES_DIRECTORY] for the location where the files will be unzipped */ class UnzipArchiveWorker @WorkerInject constructor(@Assisted context: Context, @Assisted params: WorkerParameters, private val fileManager: FileManager) : RxWorker(context, params) { override fun createWork(): Single<Result> { Timber.i("Unzip work: onGoing") makeStatusNotification("Unzipping midi archive", applicationContext) val archivePath = inputData.getString(KEY_DOWNLOADED_ARCHIVE) val unzipDirPath = inputData.getString(KEY_UNZIP_FILES_DIRECTORY) ?: File(applicationContext.getExternalFilesDir(null), applicationContext.getString(R.string.file_path_artifacts)).absolutePath if (archivePath == null) return Single.just(Result.failure()) return fileManager.unzipFile(archivePath, unzipDirPath) .map { unzippedFilesLocation -> val outputData = Data.Builder() .putString(KEY_UNZIP_FILES_DIRECTORY, unzippedFilesLocation) Result.success(outputData.build()) } } } const val KEY_UNZIP_FILES_DIRECTORY = "unzipFilesDirectory"
4
Kotlin
7
7
9252d0cab23f1c29a99c296dde8cf501d047bcaa
1,728
hymnbook
MIT License
app/src/main/java/mx/itesm/ag/covid19/model/PaisDatos.kt
gggandre
555,611,346
false
{"Kotlin": 14118}
package mx.itesm.ag.covid19.model import com.google.gson.annotations.SerializedName /** * @author <NAME> * datos de pais */ data class PaisDatos( @SerializedName("country") val name: String, val timeline: Map<String, Map<String, String>> = mapOf(), )
0
Kotlin
0
0
a3b06c71307eff1f3ce6c263b3fd43507e39ac25
269
Covid19
MIT License
room/integration-tests/kotlintestapp/src/androidTest/java/androidx/room/integration/kotlintestapp/migration/MigrationKotlinTest.kt
RikkaW
389,105,112
false
null
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.arch.persistence.room.integration.kotlintestapp.migration import android.arch.persistence.db.SupportSQLiteDatabase import android.arch.persistence.db.framework.FrameworkSQLiteOpenHelperFactory import android.arch.persistence.room.Room import android.arch.persistence.room.migration.Migration import android.arch.persistence.room.testing.MigrationTestHelper import android.arch.persistence.room.util.TableInfo import android.support.test.InstrumentationRegistry import org.hamcrest.CoreMatchers.`is` import org.hamcrest.CoreMatchers.containsString import org.hamcrest.CoreMatchers.instanceOf import org.hamcrest.CoreMatchers.nullValue import org.hamcrest.MatcherAssert.assertThat import org.junit.Rule import org.junit.Test import java.io.FileNotFoundException import java.io.IOException class MigrationKotlinTest { @get:Rule var helper: MigrationTestHelper = MigrationTestHelper( InstrumentationRegistry.getInstrumentation(), MigrationDbKotlin::class.java.canonicalName, FrameworkSQLiteOpenHelperFactory()) companion object { val TEST_DB = "migration-test" } @Test @Throws(IOException::class) fun giveBadResource() { val helper = MigrationTestHelper( InstrumentationRegistry.getInstrumentation(), "foo", FrameworkSQLiteOpenHelperFactory()) try { helper.createDatabase(TEST_DB, 1) throw AssertionError("must have failed with missing file exception") } catch (exception: FileNotFoundException) { assertThat<String>(exception.message, containsString("Cannot find")) } } @Test @Throws(IOException::class) fun startInCurrentVersion() { val db = helper.createDatabase(TEST_DB, MigrationDbKotlin.LATEST_VERSION) val dao = MigrationDbKotlin.Dao_V1(db) dao.insertIntoEntity1(2, "x") db.close() val migrationDb = getLatestDb() val items = migrationDb.dao().loadAllEntity1s() helper.closeWhenFinished(migrationDb) assertThat<Int>(items.size, `is`<Int>(1)) } @Test @Throws(IOException::class) fun addTable() { var db = helper.createDatabase(TEST_DB, 1) val dao = MigrationDbKotlin.Dao_V1(db) dao.insertIntoEntity1(2, "foo") dao.insertIntoEntity1(3, "bar") db.close() db = helper.runMigrationsAndValidate(TEST_DB, 2, true, MIGRATION_1_2) MigrationDbKotlin.Dao_V2(db).insertIntoEntity2(3, "blah") db.close() val migrationDb = getLatestDb() val entity1s = migrationDb.dao().loadAllEntity1s() assertThat(entity1s.size, `is`(2)) val entity2 = MigrationDbKotlin.Entity2(2, null, "bar") // assert no error happens migrationDb.dao().insert(entity2) val entity2s = migrationDb.dao().loadAllEntity2s() assertThat(entity2s.size, `is`(2)) } private fun getLatestDb(): MigrationDbKotlin { val db = Room.databaseBuilder( InstrumentationRegistry.getInstrumentation().targetContext, MigrationDbKotlin::class.java, TEST_DB).addMigrations(*ALL_MIGRATIONS).build() // trigger open db.beginTransaction() db.endTransaction() helper.closeWhenFinished(db) return db } @Test @Throws(IOException::class) fun addTableFailure() { testFailure(1, 2) } @Test @Throws(IOException::class) fun addColumnFailure() { val db = helper.createDatabase(TEST_DB, 2) db.close() var caught: IllegalStateException? = null try { helper.runMigrationsAndValidate(TEST_DB, 3, true, EmptyMigration(2, 3)) } catch (ex: IllegalStateException) { caught = ex } assertThat<IllegalStateException>(caught, instanceOf<IllegalStateException>(IllegalStateException::class.java)) } @Test @Throws(IOException::class) fun addColumn() { val db = helper.createDatabase(TEST_DB, 2) val v2Dao = MigrationDbKotlin.Dao_V2(db) v2Dao.insertIntoEntity2(7, "blah") db.close() helper.runMigrationsAndValidate(TEST_DB, 3, true, MIGRATION_2_3) // trigger open. val migrationDb = getLatestDb() val entity2s = migrationDb.dao().loadAllEntity2s() assertThat(entity2s.size, `is`(1)) assertThat<String>(entity2s[0].name, `is`("blah")) assertThat<String>(entity2s[0].addedInV3, `is`<Any>(nullValue())) val entity2Pojos = migrationDb.dao().loadAllEntity2sAsPojo() assertThat(entity2Pojos.size, `is`(1)) assertThat<String>(entity2Pojos[0].name, `is`("blah")) assertThat<String>(entity2Pojos[0].addedInV3, `is`<Any>(nullValue())) } @Test @Throws(IOException::class) fun failedToRemoveColumn() { testFailure(4, 5) } @Test @Throws(IOException::class) fun removeColumn() { helper.createDatabase(TEST_DB, 4) val db = helper.runMigrationsAndValidate(TEST_DB, 5, true, MIGRATION_4_5) val info = TableInfo.read(db, MigrationDbKotlin.Entity3.TABLE_NAME) assertThat(info.columns.size, `is`(2)) } @Test @Throws(IOException::class) fun dropTable() { helper.createDatabase(TEST_DB, 5) val db = helper.runMigrationsAndValidate(TEST_DB, 6, true, MIGRATION_5_6) val info = TableInfo.read(db, MigrationDbKotlin.Entity3.TABLE_NAME) assertThat(info.columns.size, `is`(0)) } @Test @Throws(IOException::class) fun failedToDropTable() { testFailure(5, 6) } @Test @Throws(IOException::class) fun failedToDropTableDontVerify() { helper.createDatabase(TEST_DB, 5) val db = helper.runMigrationsAndValidate(TEST_DB, 6, false, EmptyMigration(5, 6)) val info = TableInfo.read(db, MigrationDbKotlin.Entity3.TABLE_NAME) assertThat(info.columns.size, `is`(2)) } @Test @Throws(IOException::class) fun failedForeignKey() { val db = helper.createDatabase(TEST_DB, 6) db.close() var throwable: Throwable? = null try { helper.runMigrationsAndValidate(TEST_DB, 7, false, object : Migration(6, 7) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("CREATE TABLE Entity4 (`id` INTEGER, `name` TEXT," + " PRIMARY KEY(`id`))") } }) } catch (t: Throwable) { throwable = t } assertThat<Throwable>(throwable, instanceOf<Throwable>(IllegalStateException::class.java)) assertThat<String>(throwable!!.message, containsString("Migration failed")) } @Test @Throws(IOException::class) fun newTableWithForeignKey() { helper.createDatabase(TEST_DB, 6) val db = helper.runMigrationsAndValidate(TEST_DB, 7, false, MIGRATION_6_7) val info = TableInfo.read(db, MigrationDbKotlin.Entity4.TABLE_NAME) assertThat(info.foreignKeys.size, `is`(1)) } @Throws(IOException::class) private fun testFailure(startVersion: Int, endVersion: Int) { val db = helper.createDatabase(TEST_DB, startVersion) db.close() var throwable: Throwable? = null try { helper.runMigrationsAndValidate(TEST_DB, endVersion, true, EmptyMigration(startVersion, endVersion)) } catch (t: Throwable) { throwable = t } assertThat<Throwable>(throwable, instanceOf<Throwable>(IllegalStateException::class.java)) assertThat<String>(throwable!!.message, containsString("Migration failed")) } internal val MIGRATION_1_2: Migration = object : Migration(1, 2) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("CREATE TABLE IF NOT EXISTS `Entity2` (`id` INTEGER NOT NULL," + " `name` TEXT, PRIMARY KEY(`id`))") } } internal val MIGRATION_2_3: Migration = object : Migration(2, 3) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("ALTER TABLE " + MigrationDbKotlin.Entity2.TABLE_NAME + " ADD COLUMN addedInV3 TEXT") } } internal val MIGRATION_3_4: Migration = object : Migration(3, 4) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("CREATE TABLE IF NOT EXISTS `Entity3` (`id` INTEGER NOT NULL," + " `removedInV5` TEXT, `name` TEXT, PRIMARY KEY(`id`))") } } internal val MIGRATION_4_5: Migration = object : Migration(4, 5) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("CREATE TABLE IF NOT EXISTS `Entity3_New` (`id` INTEGER NOT NULL," + " `name` TEXT, PRIMARY KEY(`id`))") database.execSQL("INSERT INTO Entity3_New(`id`, `name`) " + "SELECT `id`, `name` FROM Entity3") database.execSQL("DROP TABLE Entity3") database.execSQL("ALTER TABLE Entity3_New RENAME TO Entity3") } } internal val MIGRATION_5_6: Migration = object : Migration(5, 6) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("DROP TABLE " + MigrationDbKotlin.Entity3.TABLE_NAME) } } internal val MIGRATION_6_7: Migration = object : Migration(6, 7) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("CREATE TABLE IF NOT EXISTS " + MigrationDbKotlin.Entity4.TABLE_NAME + " (`id` INTEGER NOT NULL, `name` TEXT, PRIMARY KEY(`id`)," + " FOREIGN KEY(`name`) REFERENCES `Entity1`(`name`)" + " ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED)") } } private val ALL_MIGRATIONS = arrayOf(MIGRATION_1_2, MIGRATION_2_3, MIGRATION_3_4, MIGRATION_4_5, MIGRATION_5_6, MIGRATION_6_7) internal class EmptyMigration(startVersion: Int, endVersion: Int) : Migration(startVersion, endVersion) { override fun migrate(database: SupportSQLiteDatabase) { // do nothing } } }
8
null
937
7
6d53f95e5d979366cf7935ad7f4f14f76a951ea5
11,137
androidx
Apache License 2.0
educational-core/src/com/jetbrains/edu/learning/coursera/CourseraOptions.kt
JetBrains
43,696,115
false
null
package com.jetbrains.edu.learning.coursera import com.intellij.ui.IdeBorderFactory import com.intellij.ui.components.JBTextField import com.intellij.ui.layout.* import com.jetbrains.edu.learning.settings.OptionsProvider import javax.swing.JComponent class CourseraOptions : OptionsProvider { private val emailField = JBTextField() private val loginPanel = panel { row("Email:") { emailField(growPolicy = GrowPolicy.MEDIUM_TEXT) } } init { loginPanel.border = IdeBorderFactory.createTitledBorder(CourseraNames.COURSERA) } override fun isModified() = CourseraSettings.getInstance().email != emailField.text override fun getDisplayName() = CourseraNames.COURSERA override fun apply() { CourseraSettings.getInstance().email = emailField.text } override fun reset() { emailField.text = CourseraSettings.getInstance().email } override fun createComponent(): JComponent = loginPanel }
1
Kotlin
40
99
cfc24fe13318de446b8adf6e05d1a7c15d9511b5
927
educational-plugin
Apache License 2.0
tmp/arrays/youTrackTests/912.kt
DaniilStepanov
228,623,440
false
{"Git Config": 1, "Gradle": 6, "Text": 3, "INI": 5, "Shell": 2, "Ignore List": 3, "Batchfile": 2, "Markdown": 2, "Kotlin": 15942, "JavaScript": 4, "ANTLR": 2, "XML": 12, "Java": 4}
// Original bug: KT-44745 val strings = arrayOf("1a", "1b", "2", "3") fun main() { for (s in strings) { if (s == "1a" || s == "1b") { continue } if (s == "2") { continue } println(s) } }
1
null
1
1
602285ec60b01eee473dcb0b08ce497b1c254983
261
bbfgradle
Apache License 2.0
app/src/main/java/cn/wthee/pcrtool/ui/components/Other.kt
wthee
277,015,110
false
{"Kotlin": 1316423}
package cn.wthee.pcrtool.ui.components import androidx.annotation.StringRes import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxScope import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.ExperimentalLayoutApi import androidx.compose.foundation.layout.FlowRow import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.imePadding import androidx.compose.foundation.layout.isImeVisible import androidx.compose.foundation.layout.navigationBarsPadding import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyListState import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.pager.PagerState import androidx.compose.foundation.pager.rememberPagerState import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.CutCornerShape import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.LinearProgressIndicator import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.MutableState import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Alignment import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha import androidx.compose.ui.draw.clip import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalInspectionMode import androidx.compose.ui.platform.LocalSoftwareKeyboardController import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import cn.wthee.pcrtool.R import cn.wthee.pcrtool.data.db.view.CharacterInfo import cn.wthee.pcrtool.data.enums.MainIconType import cn.wthee.pcrtool.data.enums.PositionType import cn.wthee.pcrtool.data.model.KeywordData import cn.wthee.pcrtool.data.model.ResponseData import cn.wthee.pcrtool.data.network.isResultError import cn.wthee.pcrtool.ui.MainActivity.Companion.navViewModel import cn.wthee.pcrtool.ui.character.getAtkColor import cn.wthee.pcrtool.ui.character.getAtkText import cn.wthee.pcrtool.ui.character.getLimitTypeColor import cn.wthee.pcrtool.ui.character.getLimitTypeText import cn.wthee.pcrtool.ui.theme.CombinedPreviews import cn.wthee.pcrtool.ui.theme.Dimen import cn.wthee.pcrtool.ui.theme.ExpandAnimation import cn.wthee.pcrtool.ui.theme.FadeAnimation import cn.wthee.pcrtool.ui.theme.PreviewLayout import cn.wthee.pcrtool.ui.theme.colorBlue import cn.wthee.pcrtool.ui.theme.colorCopper import cn.wthee.pcrtool.ui.theme.colorCyan import cn.wthee.pcrtool.ui.theme.colorGold import cn.wthee.pcrtool.ui.theme.colorGray import cn.wthee.pcrtool.ui.theme.colorGreen import cn.wthee.pcrtool.ui.theme.colorOrange import cn.wthee.pcrtool.ui.theme.colorPurple import cn.wthee.pcrtool.ui.theme.colorRed import cn.wthee.pcrtool.ui.theme.colorSilver import cn.wthee.pcrtool.ui.theme.colorWhite import cn.wthee.pcrtool.utils.Constants import cn.wthee.pcrtool.utils.dates import cn.wthee.pcrtool.utils.days import cn.wthee.pcrtool.utils.deleteSpace import cn.wthee.pcrtool.utils.fixJpTime import cn.wthee.pcrtool.utils.getToday import cn.wthee.pcrtool.utils.isComingSoon import cn.wthee.pcrtool.utils.isInProgress import com.google.accompanist.pager.HorizontalPagerIndicator import kotlinx.coroutines.launch /** * 底部空白占位 */ @Composable fun CommonSpacer() { Spacer( modifier = Modifier .navigationBarsPadding() .height(Dimen.fabSize + Dimen.fabMargin + Dimen.mediumPadding) ) } /** * 位置颜色 * @param position 角色占位 */ @Composable fun getPositionColor(position: Int) = when (PositionType.getPositionType(position)) { PositionType.POSITION_0_299 -> colorRed PositionType.POSITION_300_599 -> colorGold PositionType.POSITION_600_999 -> colorCyan PositionType.UNKNOWN -> MaterialTheme.colorScheme.primary } /** * rank 颜色 * @param rank rank数值 */ @Composable fun getRankColor(rank: Int): Color { return when (rank) { 1 -> colorBlue in 2..3 -> colorCopper in 4..6 -> colorSilver in 7..10 -> colorGold in 11..17 -> colorPurple in 18..20 -> colorRed in 21..23 -> colorGreen in 24..27 -> colorOrange in 28..99 -> colorCyan else -> colorGray } } /** * 带指示器图标 * @param urls 最大5个 */ @OptIn(ExperimentalFoundationApi::class) @Composable fun IconHorizontalPagerIndicator(pagerState: PagerState, urls: List<String>) { val scope = rememberCoroutineScope() Box( modifier = Modifier.fillMaxWidth(urls.size * 0.2f), contentAlignment = Alignment.Center ) { //显示指示器 Row { urls.forEachIndexed { index, url -> val modifier = if (pagerState.currentPage == index) { Modifier .padding(horizontal = Dimen.mediumPadding) .border( width = Dimen.border, color = MaterialTheme.colorScheme.primary, shape = MaterialTheme.shapes.extraSmall ) } else { Modifier.padding(horizontal = Dimen.mediumPadding) } Box(modifier = Modifier.weight(1f), contentAlignment = Alignment.Center) { MainIcon( modifier = modifier, data = url, ) { scope.launch { pagerState.scrollToPage(index) } } } } } } } /** * 指示器 */ @OptIn(ExperimentalFoundationApi::class) @Composable fun MainHorizontalPagerIndicator( modifier: Modifier = Modifier, pagerState: PagerState, pageCount: Int ) { HorizontalPagerIndicator( modifier = modifier, pagerState = pagerState, pageCount = pageCount, indicatorWidth = 6.dp, activeColor = MaterialTheme.colorScheme.primary, indicatorShape = CutCornerShape(50), spacing = 0.dp ) } /** * 加载中-圆形 */ @Composable fun CircularProgressCompose( modifier: Modifier = Modifier, size: Dp = Dimen.menuIconSize, color: Color = MaterialTheme.colorScheme.primary ) { CircularProgressIndicator( modifier = modifier .size(size) .padding(Dimen.exSmallPadding), color = color, strokeWidth = Dimen.strokeWidth ) } /** * 加载中-圆形 */ @Composable fun CircularProgressCompose( progress: Float, modifier: Modifier = Modifier, size: Dp = Dimen.menuIconSize, color: Color = MaterialTheme.colorScheme.primary ) { Box(contentAlignment = Alignment.Center) { CircularProgressIndicator( progress = progress, modifier = modifier .size(size) .padding(Dimen.exSmallPadding), color = color, strokeWidth = Dimen.strokeWidth, ) Text( text = (progress * 100).toInt().toString(), color = MaterialTheme.colorScheme.primary, style = MaterialTheme.typography.labelSmall ) } } /** * 加载中-直线 */ @Composable fun LinearProgressCompose( modifier: Modifier = Modifier, color: Color = MaterialTheme.colorScheme.primary ) { LinearProgressIndicator( modifier = modifier .height(Dimen.linearProgressHeight) .clip(MaterialTheme.shapes.medium), color = color ) } /** * 加载中进度-直线 */ @Composable fun LinearProgressCompose( progress: Float, modifier: Modifier = Modifier, color: Color = MaterialTheme.colorScheme.primary ) { LinearProgressIndicator( progress = progress, modifier = modifier .height(Dimen.linearProgressHeight) .clip(MaterialTheme.shapes.medium), color = color ) } /** * 底部搜索栏 * * @param keywordState 关键词,用于查询 * @param keywordInputState 输入框内文本,不实时更新 [keywordState] ,仅在输入确认后更新 * @param defaultKeywordList 默认关键词列表 * @param fabText 不为空时,fab将显示该文本 */ @OptIn( ExperimentalComposeUiApi::class, ExperimentalLayoutApi::class ) @Composable fun BottomSearchBar( modifier: Modifier = Modifier, fabText: String? = null, @StringRes labelStringId: Int, keywordInputState: MutableState<String>, keywordState: MutableState<String>, leadingIcon: MainIconType, scrollState: LazyListState? = null, defaultKeywordList: List<KeywordData>? = null, onResetClick: (() -> Unit)? = null, ) { val keyboardController = LocalSoftwareKeyboardController.current val coroutineScope = rememberCoroutineScope() //获取焦点 val focusRequester = remember { FocusRequester() } //键盘是否可见 val isImeVisible = WindowInsets.isImeVisible val openDialog = remember { mutableStateOf(false) } if (!isImeVisible) { Row( modifier = modifier .padding(end = Dimen.fabMarginEnd, bottom = Dimen.fabMargin), horizontalArrangement = Arrangement.End ) { //回到顶部 scrollState?.let { MainSmallFab( iconType = MainIconType.TOP ) { coroutineScope.launch { scrollState.scrollToItem(0) } } } //重置 if (keywordState.value != "") { MainSmallFab( iconType = MainIconType.RESET ) { keywordState.value = "" keywordInputState.value = "" if (onResetClick != null) { onResetClick() } } } //搜索 MainSmallFab( iconType = if (fabText != null) leadingIcon else MainIconType.SEARCH, text = fabText ?: keywordState.value ) { keyboardController?.show() openDialog.value = true focusRequester.requestFocus() //如有日期弹窗,则关闭日期弹窗 navViewModel.fabCloseClick.postValue(true) } } } Column( modifier = modifier .fillMaxWidth() .padding(Dimen.mediumPadding) .imePadding() ) { //关键词列表,搜索时显示 ExpandAnimation( visible = openDialog.value && isImeVisible && defaultKeywordList?.isNotEmpty() == true, modifier = Modifier.padding(bottom = Dimen.mediumPadding) ) { MainCard( modifier = Modifier.padding(bottom = Dimen.mediumPadding), elevation = Dimen.popupMenuElevation ) { Column( modifier = Modifier.padding(Dimen.mediumPadding) ) { MainText(text = stringResource(id = R.string.search_suggestion)) SuggestionChipGroup( defaultKeywordList ?: arrayListOf(), modifier = Modifier.padding(top = Dimen.mediumPadding) ) { keyword -> keywordInputState.value = keyword keywordState.value = keyword keyboardController?.hide() focusRequester.freeFocus() openDialog.value = false } } } } //focusRequester MainCard( elevation = Dimen.popupMenuElevation ) { OutlinedTextField( modifier = Modifier .fillMaxWidth() .heightIn(max = if (openDialog.value && isImeVisible) Dp.Unspecified else 0.dp) .padding(Dimen.smallPadding) .focusRequester(focusRequester) .alpha(if (openDialog.value && isImeVisible) 1f else 0f), value = keywordInputState.value, shape = MaterialTheme.shapes.medium, onValueChange = { keywordInputState.value = it.deleteSpace }, textStyle = MaterialTheme.typography.labelLarge, leadingIcon = { MainIcon( data = leadingIcon, size = Dimen.fabIconSize ) }, trailingIcon = { MainIcon( data = MainIconType.SEARCH, size = Dimen.fabIconSize ) { keyboardController?.hide() keywordState.value = keywordInputState.value focusRequester.freeFocus() openDialog.value = false } }, keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done), keyboardActions = KeyboardActions( onDone = { keyboardController?.hide() keywordState.value = keywordInputState.value focusRequester.freeFocus() openDialog.value = false } ), label = { Text( text = stringResource(id = labelStringId), style = MaterialTheme.typography.labelLarge ) }, maxLines = 1, singleLine = true, ) } } } @Composable fun <T> CommonResponseBox( responseData: ResponseData<T>?, fabContent: @Composable (BoxScope.(T) -> Unit)? = null, content: @Composable (BoxScope.(T) -> Unit), ) { Box( modifier = Modifier .fillMaxSize() .background(MaterialTheme.colorScheme.surface) ) { FadeAnimation(visible = isResultError(responseData)) { CenterTipText(text = stringResource(id = R.string.response_error)) } FadeAnimation(visible = responseData?.data != null) { content(responseData!!.data!!) } if (responseData == null) { CircularProgressCompose( modifier = Modifier .padding(vertical = Dimen.largePadding) .align(Alignment.Center) ) } if (responseData?.data != null && fabContent != null) { fabContent(responseData.data!!) } } } /** * 日程标题 * @param showDays 显示天数 * @param showOverdueColor 过期日程颜色变灰色 */ @Composable fun EventTitle( startTime: String, endTime: String, showDays: Boolean = true, showOverdueColor: Boolean = false ) { val today = getToday() val sd = startTime.fixJpTime val ed = endTime.fixJpTime val inProgress = isInProgress(today, startTime, endTime) val comingSoon = isComingSoon(today, startTime) val color = when { inProgress -> { MaterialTheme.colorScheme.primary } comingSoon -> { colorPurple } else -> { if (showOverdueColor) { MaterialTheme.colorScheme.outline } else { MaterialTheme.colorScheme.primary } } } //日期 MainTitleText( text = sd.substring(0, 10), modifier = Modifier.padding(end = Dimen.smallPadding), backgroundColor = color ) //天数,预览时不显示 if (showDays && !LocalInspectionMode.current) { val days = ed.days(sd) MainTitleText( text = days, modifier = Modifier.padding(end = Dimen.smallPadding), backgroundColor = color ) } //计时 EventTitleCountdown(today, sd, ed, inProgress, comingSoon) } /** * 日程倒计时 */ @Composable fun EventTitleCountdown( today: String, sd: String, ed: String, inProgress: Boolean, comingSoon: Boolean ) { Row( verticalAlignment = Alignment.CenterVertically ) { if (inProgress) { MainIcon( data = MainIconType.TIME_LEFT, size = Dimen.smallIconSize, ) MainContentText( text = ed.dates(today), modifier = Modifier.padding(start = Dimen.smallPadding), textAlign = TextAlign.Start, color = MaterialTheme.colorScheme.primary ) } if (comingSoon) { MainIcon( data = MainIconType.COUNTDOWN, size = Dimen.smallIconSize, tint = colorPurple ) MainContentText( text = sd.dates(today), modifier = Modifier.padding(start = Dimen.smallPadding), textAlign = TextAlign.Start, color = colorPurple ) } } } /** * 装备适用角色 */ @Composable fun UnitList(unitIds: List<Int>) { LazyColumn( modifier = Modifier .fillMaxWidth() .padding(horizontal = Dimen.mediumPadding), state = rememberLazyListState() ) { //标题 item { MainText( text = stringResource(R.string.extra_equip_unit), modifier = Modifier .padding(Dimen.largePadding) .fillMaxWidth() ) } //角色图标 item { GridIconList(unitIds, isSubLayout = false) {} } item { CommonSpacer() } } } /** * 角色标签行 * */ @OptIn(ExperimentalLayoutApi::class) @Composable fun CharacterTagRow( modifier: Modifier = Modifier, unknown: Boolean = false, basicInfo: CharacterInfo?, tipText: String? = null, endText: String? = null, endTextColor: Color? = null, horizontalArrangement: Arrangement.Horizontal = Arrangement.Start ) { FlowRow( modifier = modifier, horizontalArrangement = horizontalArrangement, verticalArrangement = Arrangement.Center ) { if (!unknown) { //位置 CharacterPositionTag( modifier = Modifier .padding( start = Dimen.smallPadding ) .align(Alignment.CenterVertically), position = basicInfo!!.position ) Row { //获取方式 CharacterTag( modifier = Modifier.padding(Dimen.smallPadding), text = getLimitTypeText(limitType = basicInfo.limitType), backgroundColor = getLimitTypeColor(limitType = basicInfo.limitType) ) //攻击 CharacterTag( modifier = Modifier.padding( bottom = Dimen.smallPadding, top = Dimen.smallPadding ), text = getAtkText(atkType = basicInfo.atkType), backgroundColor = getAtkColor(atkType = basicInfo.atkType) ) } //日期 if (endText != null && endTextColor != null) { CharacterTag( text = endText, backgroundColor = Color.Transparent, textColor = endTextColor, fontWeight = FontWeight.Light, modifier = Modifier .weight(1f) .align(Alignment.CenterVertically), endAlignment = true ) } } else { Row(modifier = Modifier.padding(bottom = Dimen.smallPadding)) { if (tipText != null) { //提示 CharacterTag( modifier = Modifier.padding(start = Dimen.smallPadding), text = tipText, backgroundColor = Color.Transparent, textColor = colorGray, fontWeight = FontWeight.Light ) } //日期 if (endText != null && endTextColor != null) { CharacterTag( text = endText, backgroundColor = Color.Transparent, textColor = endTextColor, fontWeight = FontWeight.Light, modifier = Modifier.weight(1f), endAlignment = true ) } } } } } /** * 位置信息 * */ @Composable fun CharacterPositionTag( modifier: Modifier = Modifier, position: Int ) { val positionText = getPositionText(position) Row(modifier = modifier, verticalAlignment = Alignment.CenterVertically) { //位置图标 PositionIcon( position = position ) //位置 CharacterTag( modifier = Modifier.padding(start = Dimen.smallPadding), text = positionText, backgroundColor = getPositionColor(position) ) } } /** * 获取位置描述 */ @Composable private fun getPositionText(position: Int): String { var positionText = "" val pos = when (PositionType.getPositionType(position)) { PositionType.POSITION_0_299 -> stringResource(id = R.string.position_0) PositionType.POSITION_300_599 -> stringResource(id = R.string.position_1) PositionType.POSITION_600_999 -> stringResource(id = R.string.position_2) PositionType.UNKNOWN -> Constants.UNKNOWN } if (pos != Constants.UNKNOWN) { positionText = "$pos $position" } return positionText } /** * 角色属性标签 * * @param leadingContent 开头内容 */ @Composable fun CharacterTag( modifier: Modifier = Modifier, text: String, backgroundColor: Color = MaterialTheme.colorScheme.primary, textColor: Color = colorWhite, fontWeight: FontWeight = FontWeight.ExtraBold, style: TextStyle = MaterialTheme.typography.bodyMedium, endAlignment: Boolean = false, leadingContent: @Composable (() -> Unit)? = null ) { Box( modifier = modifier .clip(CircleShape) .background(color = backgroundColor, shape = CircleShape) .padding(horizontal = Dimen.mediumPadding), contentAlignment = if (endAlignment) Alignment.CenterEnd else Alignment.Center ) { Row(verticalAlignment = Alignment.CenterVertically) { leadingContent?.let { it() Spacer(modifier = Modifier.padding(start = Dimen.smallPadding)) } Text( text = text, color = textColor, style = style, fontWeight = fontWeight, maxLines = 1, overflow = TextOverflow.Ellipsis ) } } } @OptIn(ExperimentalFoundationApi::class) @CombinedPreviews @Composable private fun AllPreview() { val text = stringResource(id = R.string.debug_short_text) PreviewLayout { MainTitleText(text = text) MainButton(text = text) {} SubButton(text = text) {} RankText(rank = 21) SelectText(text = text, selected = true) IconTextButton(icon = MainIconType.MORE, text = text) CommonTitleContentText(title = text, content = text) MainTabRow( pagerState = rememberPagerState { 2 }, tabs = arrayListOf(text, text) ) } } @CombinedPreviews @Composable private fun CharacterTagPreview() { PreviewLayout { CharacterTag( text = getLimitTypeText(limitType = 1), backgroundColor = getLimitTypeColor(limitType = 1) ) } }
0
Kotlin
2
53
73b9331c3e15e9718177c64ef6725eea8582abe6
25,333
pcr-tool
Apache License 2.0
src/entity/Youkai.kt
Crystal1921
793,632,316
false
{"Kotlin": 21787}
package entity import data.DoublePoint import data.Player import data.Power import utils.Entity import utils.Image import java.awt.image.BufferedImage import kotlin.math.atan2 class Youkai (override var health: Int, override var pos: DoublePoint, override val image: BufferedImage?, private val target : Player) : AbstractEntity() { constructor(health: Int,pos: DoublePoint,target: Player) : this(health,pos, Image.images["reimu_mouse.png"],target) override fun tick() { if (health <= 0) { Entity.items.add(ItemEntity(pos, Power.Big)) return } lifeTime ++ pos.x ++ if (lifeTime % 50 == 0) { val x = target.pos.x - pos.x val y = target.pos.y - pos.y val angle = atan2(y,x) Entity.danmaku.add(LittleDanmaku(pos.copy(),angle)) } } }
0
Kotlin
0
0
ea0608fc793b1264bb260f45483c322b3ad0e8c0
864
kotlin-test-stg
MIT License
vector/src/main/java/im/vector/app/features/roomprofile/RoomProfileFragment.kt
tchapgouv
340,329,238
false
null
/* * Copyright 2019 New Vector Ltd * * 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 im.vector.app.features.roomprofile import android.os.Bundle import android.os.Parcelable import android.view.LayoutInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import androidx.core.content.pm.ShortcutManagerCompat import androidx.core.view.isVisible import androidx.fragment.app.setFragmentResultListener import com.airbnb.mvrx.args import com.airbnb.mvrx.fragmentViewModel import com.airbnb.mvrx.withState import com.google.android.material.dialog.MaterialAlertDialogBuilder import im.vector.app.BuildConfig import im.vector.app.R import im.vector.app.core.animations.AppBarStateChangeListener import im.vector.app.core.animations.MatrixItemAppBarStateChangeListener import im.vector.app.core.extensions.cleanup import im.vector.app.core.extensions.configureWith import im.vector.app.core.extensions.copyOnLongClick import im.vector.app.core.extensions.exhaustive import im.vector.app.core.extensions.setTextOrHide import im.vector.app.core.platform.VectorBaseFragment import im.vector.app.core.utils.copyToClipboard import im.vector.app.core.utils.startSharePlainTextIntent import im.vector.app.databinding.FragmentMatrixProfileBinding import im.vector.app.databinding.ViewStubRoomProfileHeaderBinding import im.vector.app.features.home.AvatarRenderer import im.vector.app.features.home.room.detail.RoomDetailPendingAction import im.vector.app.features.home.room.detail.RoomDetailPendingActionStore import im.vector.app.features.home.room.detail.upgrade.MigrateRoomBottomSheet import im.vector.app.features.home.room.list.actions.RoomListActionsArgs import im.vector.app.features.home.room.list.actions.RoomListQuickActionsBottomSheet import im.vector.app.features.home.room.list.actions.RoomListQuickActionsSharedAction import im.vector.app.features.home.room.list.actions.RoomListQuickActionsSharedActionViewModel import kotlinx.parcelize.Parcelize import org.matrix.android.sdk.api.session.room.notification.RoomNotificationState import org.matrix.android.sdk.api.util.toMatrixItem import timber.log.Timber import javax.inject.Inject @Parcelize data class RoomProfileArgs( val roomId: String ) : Parcelable class RoomProfileFragment @Inject constructor( private val roomProfileController: RoomProfileController, private val avatarRenderer: AvatarRenderer, private val roomDetailPendingActionStore: RoomDetailPendingActionStore, ) : VectorBaseFragment<FragmentMatrixProfileBinding>(), RoomProfileController.Callback { private lateinit var headerViews: ViewStubRoomProfileHeaderBinding private val roomProfileArgs: RoomProfileArgs by args() private lateinit var roomListQuickActionsSharedActionViewModel: RoomListQuickActionsSharedActionViewModel private lateinit var roomProfileSharedActionViewModel: RoomProfileSharedActionViewModel private val roomProfileViewModel: RoomProfileViewModel by fragmentViewModel() private var appBarStateChangeListener: AppBarStateChangeListener? = null override fun getBinding(inflater: LayoutInflater, container: ViewGroup?): FragmentMatrixProfileBinding { return FragmentMatrixProfileBinding.inflate(inflater, container, false) } override fun getMenuRes() = R.menu.vector_room_profile override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setFragmentResultListener(MigrateRoomBottomSheet.REQUEST_KEY) { _, bundle -> bundle.getString(MigrateRoomBottomSheet.BUNDLE_KEY_REPLACEMENT_ROOM)?.let { replacementRoomId -> roomDetailPendingActionStore.data = RoomDetailPendingAction.OpenRoom(replacementRoomId, closeCurrentRoom = true) vectorBaseActivity.finish() } } } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) roomListQuickActionsSharedActionViewModel = activityViewModelProvider.get(RoomListQuickActionsSharedActionViewModel::class.java) roomProfileSharedActionViewModel = activityViewModelProvider.get(RoomProfileSharedActionViewModel::class.java) val headerView = views.matrixProfileHeaderView.let { it.layoutResource = R.layout.view_stub_room_profile_header it.inflate() } headerViews = ViewStubRoomProfileHeaderBinding.bind(headerView) setupWaitingView() setupToolbar(views.matrixProfileToolbar) setupRecyclerView() appBarStateChangeListener = MatrixItemAppBarStateChangeListener( headerView, listOf(views.matrixProfileToolbarAvatarImageView, views.matrixProfileToolbarTitleView, views.matrixProfileDecorationToolbarAvatarImageView) ) views.matrixProfileAppBarLayout.addOnOffsetChangedListener(appBarStateChangeListener) roomProfileViewModel.observeViewEvents { when (it) { is RoomProfileViewEvents.Loading -> showLoading(it.message) is RoomProfileViewEvents.Failure -> showFailure(it.throwable) is RoomProfileViewEvents.ShareRoomProfile -> onShareRoomProfile(it.permalink) is RoomProfileViewEvents.OnShortcutReady -> addShortcut(it) }.exhaustive } roomListQuickActionsSharedActionViewModel .observe() .subscribe { handleQuickActions(it) } .disposeOnDestroyView() setupClicks() setupLongClicks() } private fun setupWaitingView() { views.waitingView.waitingStatusText.setText(R.string.please_wait) views.waitingView.waitingStatusText.isVisible = true } private fun setupClicks() { // Shortcut to room settings setOf( headerViews.roomProfileNameView, views.matrixProfileToolbarTitleView ).forEach { it.setOnClickListener { roomProfileSharedActionViewModel.post(RoomProfileSharedAction.OpenRoomSettings) } } // Shortcut to room alias headerViews.roomProfileAliasView.setOnClickListener { roomProfileSharedActionViewModel.post(RoomProfileSharedAction.OpenRoomAliasesSettings) } // Open Avatar setOf( headerViews.roomProfileAvatarView, views.matrixProfileToolbarAvatarImageView ).forEach { view -> view.setOnClickListener { onAvatarClicked(view) } } } private fun setupLongClicks() { headerViews.roomProfileNameView.copyOnLongClick() headerViews.roomProfileAliasView.copyOnLongClick() } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.roomProfileShareAction -> { roomProfileViewModel.handle(RoomProfileAction.ShareRoomProfile) return true } } return super.onOptionsItemSelected(item) } private fun handleQuickActions(action: RoomListQuickActionsSharedAction) = when (action) { is RoomListQuickActionsSharedAction.NotificationsAllNoisy -> { roomProfileViewModel.handle(RoomProfileAction.ChangeRoomNotificationState(RoomNotificationState.ALL_MESSAGES_NOISY)) } is RoomListQuickActionsSharedAction.NotificationsAll -> { roomProfileViewModel.handle(RoomProfileAction.ChangeRoomNotificationState(RoomNotificationState.ALL_MESSAGES)) } is RoomListQuickActionsSharedAction.NotificationsMentionsOnly -> { roomProfileViewModel.handle(RoomProfileAction.ChangeRoomNotificationState(RoomNotificationState.MENTIONS_ONLY)) } is RoomListQuickActionsSharedAction.NotificationsMute -> { roomProfileViewModel.handle(RoomProfileAction.ChangeRoomNotificationState(RoomNotificationState.MUTE)) } else -> Timber.v("$action not handled") } private fun setupRecyclerView() { roomProfileController.callback = this views.matrixProfileRecyclerView.configureWith(roomProfileController, hasFixedSize = true, disableItemAnimation = true) } override fun onDestroyView() { views.matrixProfileAppBarLayout.removeOnOffsetChangedListener(appBarStateChangeListener) views.matrixProfileRecyclerView.cleanup() appBarStateChangeListener = null super.onDestroyView() } override fun invalidate() = withState(roomProfileViewModel) { state -> views.waitingView.root.isVisible = state.isLoading state.roomSummary()?.let { if (it.membership.isLeft()) { Timber.w("The room has been left") activity?.finish() } else { headerViews.roomProfileNameView.text = it.displayName views.matrixProfileToolbarTitleView.text = it.displayName headerViews.roomProfileAliasView.setTextOrHide(it.canonicalAlias) val matrixItem = it.toMatrixItem() avatarRenderer.render(matrixItem, headerViews.roomProfileAvatarView) avatarRenderer.render(matrixItem, views.matrixProfileToolbarAvatarImageView) headerViews.roomProfileDecorationImageView.render(it.roomEncryptionTrustLevel) views.matrixProfileDecorationToolbarAvatarImageView.render(it.roomEncryptionTrustLevel) headerViews.roomProfilePresenceImageView.render(it.isDirect, it.directUserPresence) headerViews.roomProfilePublicImageView.isVisible = it.isPublic && !it.isDirect } } roomProfileController.setData(state) } // RoomProfileController.Callback override fun onLearnMoreClicked() { vectorBaseActivity.notImplemented() } override fun onEnableEncryptionClicked() { MaterialAlertDialogBuilder(requireActivity()) .setTitle(R.string.room_settings_enable_encryption_dialog_title) .setMessage(R.string.room_settings_enable_encryption_dialog_content) .setNegativeButton(R.string.cancel, null) .setPositiveButton(R.string.room_settings_enable_encryption_dialog_submit) { _, _ -> roomProfileViewModel.handle(RoomProfileAction.EnableEncryption) } .show() } override fun onMemberListClicked() { roomProfileSharedActionViewModel.post(RoomProfileSharedAction.OpenRoomMembers) } override fun onBannedMemberListClicked() { roomProfileSharedActionViewModel.post(RoomProfileSharedAction.OpenBannedRoomMembers) } override fun onSettingsClicked() { roomProfileSharedActionViewModel.post(RoomProfileSharedAction.OpenRoomSettings) } override fun onNotificationsClicked() { if (BuildConfig.USE_NOTIFICATION_SETTINGS_V2) { roomProfileSharedActionViewModel.post(RoomProfileSharedAction.OpenRoomNotificationSettings) } else { RoomListQuickActionsBottomSheet .newInstance(roomProfileArgs.roomId, RoomListActionsArgs.Mode.NOTIFICATIONS) .show(childFragmentManager, "ROOM_PROFILE_NOTIFICATIONS") } } override fun onUploadsClicked() { roomProfileSharedActionViewModel.post(RoomProfileSharedAction.OpenRoomUploads) } override fun createShortcut() { // Ask the view model to prepare it... roomProfileViewModel.handle(RoomProfileAction.CreateShortcut) } private fun addShortcut(onShortcutReady: RoomProfileViewEvents.OnShortcutReady) { // ... and propose the user to add it ShortcutManagerCompat.requestPinShortcut(requireContext(), onShortcutReady.shortcutInfo, null) } override fun onLeaveRoomClicked() { val isPublicRoom = roomProfileViewModel.isPublicRoom() val message = buildString { append(getString(R.string.room_participants_leave_prompt_msg)) if (!isPublicRoom) { append("\n\n") append(getString(R.string.room_participants_leave_private_warning)) } } MaterialAlertDialogBuilder(requireContext(), if (isPublicRoom) 0 else R.style.ThemeOverlay_Vector_MaterialAlertDialog_Destructive) .setTitle(R.string.room_participants_leave_prompt_title) .setMessage(message) .setPositiveButton(R.string.leave) { _, _ -> roomProfileViewModel.handle(RoomProfileAction.LeaveRoom) } .setNegativeButton(R.string.cancel, null) .show() } override fun onRoomAliasesClicked() { roomProfileSharedActionViewModel.post(RoomProfileSharedAction.OpenRoomAliasesSettings) } override fun onRoomPermissionsClicked() { roomProfileSharedActionViewModel.post(RoomProfileSharedAction.OpenRoomPermissionsSettings) } override fun onRoomIdClicked() { copyToClipboard(requireContext(), roomProfileArgs.roomId) } override fun onRoomDevToolsClicked() { navigator.openDevTools(requireContext(), roomProfileArgs.roomId) } override fun onUrlInTopicLongClicked(url: String) { copyToClipboard(requireContext(), url, true) } override fun doMigrateToVersion(newVersion: String) { MigrateRoomBottomSheet.newInstance(roomProfileArgs.roomId, newVersion) .show(parentFragmentManager, "migrate") } private fun onShareRoomProfile(permalink: String) { startSharePlainTextIntent( fragment = this, activityResultLauncher = null, chooserTitle = null, text = permalink ) } private fun onAvatarClicked(view: View) = withState(roomProfileViewModel) { state -> state.roomSummary()?.toMatrixItem()?.let { matrixItem -> navigator.openBigImageViewer(requireActivity(), view, matrixItem) } } }
96
null
7
9
a2c060c687b0aa69af681138c5788d6933d19860
14,765
tchap-android
Apache License 2.0
src/main/kotlin/io/github/kryszak/gwatlin/api/gamemechanics/model/facts/Radius.kt
Kryszak
214,791,260
false
{"Kotlin": 443350, "Shell": 654}
package io.github.kryszak.gwatlin.api.gamemechanics.model.facts import io.github.kryszak.gwatlin.http.serializers.SerialNameDelegate.Companion.serialNameDelegate import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable /** * Data model for skill/trait facts with type Radius */ @Serializable @SerialName("Radius") data class Radius( override val text: String? = null, override val icon: String? = null, val distance: Int, ) : Fact { override val type by serialNameDelegate }
1
Kotlin
1
6
657798c9ca17dfcdbca6e45196dfd15443d63751
520
gwatlin
MIT License
modules/nbt/src/commonTest/kotlin/com/handtruth/mc/nbt/test/TagBuilderTest.kt
handtruth
282,440,433
false
null
package com.handtruth.mc.nbt.test import com.handtruth.mc.nbt.NBT import com.handtruth.mc.nbt.NBTBinaryConfig import com.handtruth.mc.nbt.tags.* import com.handtruth.mc.nbt.writeText import com.handtruth.mc.types.Dynamic import com.handtruth.mc.types.buildDynamic import com.handtruth.mc.types.dynamic import io.ktor.utils.io.core.* import kotlin.test.Test import kotlin.test.assertTrue class TagBuilderTest { val javaNBT = NBT(binary = NBTBinaryConfig.Java) @Test fun buildRootTag() { val tag = buildDynamic { "group" assign "Them" "id" assign 568 "members" assign buildList { dynamic { "name" assign "Ktlo" "id" assign 398.toShort() } dynamic { "name" assign "Xydgiz" "id" assign (-3).toShort() } } "metadata" assign intArrayOf(3, 5, 8, 9, 16, -15) "byteArray" assign byteArrayOf(-3, 5, 76, 81) "intArray" assign intArrayOf(58, -98, 334) "longArray" assign longArrayOf(4842, -6496462, 24554679784123) } println(javaNBT.writeText(tag)) buildPacket { javaNBT.writeNamedBinary(this, "", tag) }.use { input -> val actual = javaNBT.readNamedBinary(input) assertDynamicEquals(tag, actual.second as Dynamic) } } @Test fun printAllTags() { val tags = listOf( BooleanArrayTag, BooleanTag, ByteArrayTag, BytesTag, ByteTag, CharTag, CompoundTag, DoubleTag, EndTag, FloatTag, InstantTag, IntArrayTag, IntTag, ListTag, LongArrayTag, LongTag, ShortArrayTag, ShortTag, StringTag, UByteTag, UIntTag, ULongTag, UShortTag, UUIDTag ) for (tag in tags) { assertTrue { tag.toString().startsWith("TAG_") } } } }
0
Kotlin
0
0
fa6d230dc1f7e62cd75b91ad4798a763ca7e78f1
1,941
mc-tools
MIT License
src/me/anno/remsstudio/Rendering.kt
AntonioNoack
266,471,164
false
null
package me.anno.remsstudio import me.anno.engine.EngineBase.Companion.workspace import me.anno.gpu.GFX import me.anno.gpu.GFXBase import me.anno.io.MediaMetadata.Companion.getMeta import me.anno.io.files.FileReference import me.anno.io.files.InvalidRef import me.anno.language.translation.NameDesc import me.anno.remsstudio.RemsStudio.motionBlurSteps import me.anno.remsstudio.RemsStudio.project import me.anno.remsstudio.RemsStudio.root import me.anno.remsstudio.RemsStudio.shutterPercentage import me.anno.remsstudio.RemsStudio.targetOutputFile import me.anno.remsstudio.RemsStudio.targetTransparency import me.anno.remsstudio.audio.AudioCreatorV2 import me.anno.remsstudio.objects.Audio import me.anno.remsstudio.objects.Camera import me.anno.remsstudio.objects.Transform import me.anno.remsstudio.video.FrameTaskV2 import me.anno.remsstudio.video.videoAudioCreatorV2 import me.anno.ui.base.menu.Menu.ask import me.anno.ui.base.menu.Menu.msg import me.anno.ui.base.progress.ProgressBar import me.anno.utils.files.FileChooser import me.anno.utils.types.Strings.defaultImportType import me.anno.utils.types.Strings.getImportType import me.anno.video.VideoCreator import me.anno.video.VideoCreator.Companion.defaultQuality import me.anno.video.ffmpeg.FFMPEGEncodingBalance import me.anno.video.ffmpeg.FFMPEGEncodingType import org.apache.logging.log4j.LogManager import kotlin.concurrent.thread import kotlin.math.max import kotlin.math.roundToInt @Suppress("MemberVisibilityCanBePrivate") object Rendering { var isRendering = false set(value) { GFXBase.mayIdle = !value field = value } const val minimumDivider = 4 private val LOGGER = LogManager.getLogger(Rendering::class) fun renderPart(size: Int, ask: Boolean, callback: () -> Unit) { renderVideo(RemsStudio.targetWidth / size, RemsStudio.targetHeight / size, ask, callback) } fun renderSetPercent(ask: Boolean, callback: () -> Unit) { val project = project ?: throw IllegalStateException("Missing project") renderVideo( max(minimumDivider, (project.targetWidth * project.targetSizePercentage / 100).roundToInt()), max(minimumDivider, (project.targetHeight * project.targetSizePercentage / 100).roundToInt()), ask, callback ) } fun filterAudio(scene: Transform): List<Audio> { return scene.listOfAll .filterIsInstance<Audio>() .filter { it.forcedMeta?.hasAudio == true && (it.amplitude.isAnimated || it.amplitude[0.0] * 32e3f > 1f) }.toList() } fun renderVideo(width: Int, height: Int, ask: Boolean, callback: () -> Unit) { val divW = width % minimumDivider val divH = height % minimumDivider if (divW != 0 || divH != 0) return renderVideo( width - divW, height - divH, ask, callback ) if (isRendering) return onAlreadyRendering() val targetOutputFile = findTargetOutputFile(RenderType.VIDEO) if (targetOutputFile.exists && ask) { return askOverridingIsAllowed(targetOutputFile) { renderVideo(width, height, false, callback) } } val isGif = targetOutputFile.lcExtension == "gif" isRendering = true LOGGER.info("Rendering video at $width x $height") val duration = RemsStudio.targetDuration val tmpFile = getTmpFile(targetOutputFile) val fps = RemsStudio.targetFPS val totalFrameCount = max(1, (fps * duration).toInt() + 1) val sampleRate = max(1, RemsStudio.targetSampleRate) val samples = RemsStudio.targetSamples val project = project val scene = root.clone() val audioSources = if (isGif) emptyList() else filterAudio(scene) val balance = project?.ffmpegBalance ?: FFMPEGEncodingBalance.M0 val type = project?.ffmpegFlags ?: FFMPEGEncodingType.DEFAULT val videoCreator = VideoCreator( width, height, RemsStudio.targetFPS, totalFrameCount, balance, type, project?.targetVideoQuality ?: defaultQuality, targetTransparency, if (audioSources.isEmpty()) targetOutputFile else tmpFile ) val progress = GFX.someWindow.addProgressBar( object : ProgressBar( "Rendering", "Frames", totalFrameCount.toDouble() ) { override fun formatProgress(): String { val progress = progress.toInt() val total = total.toInt() return "$name: $progress / $total $unit" } } ) val videoAudioCreator = videoAudioCreatorV2( videoCreator, samples, scene, findCamera(scene), duration, sampleRate, audioSources, motionBlurSteps, shutterPercentage, targetOutputFile, progress ) videoAudioCreator.onFinished = { // todo sometimes the "pipe fails", and that is reported as a green bar -> needs to be red (cancelled) // this happens after something has been cancelled :/ -> FFMPEG not closed down? isRendering = false progress.finish() callback() tmpFile.invalidate() targetOutputFile.invalidate() } videoCreator.init() videoAudioCreator.start() } private fun getTmpFile(file: FileReference) = file.getSibling(file.nameWithoutExtension + ".tmp." + targetOutputFile.extension) fun renderFrame(width: Int, height: Int, time: Double, ask: Boolean, callback: () -> Unit) { val targetOutputFile = findTargetOutputFile(RenderType.FRAME) if (targetOutputFile.exists && ask) { return askOverridingIsAllowed(targetOutputFile) { renderFrame(width, height, time, false, callback) } } LOGGER.info("Rendering frame at $time, $width x $height") val scene = root.clone() // so that changed don't influence the result val camera = findCamera(scene) FrameTaskV2( width, height, RemsStudio.targetFPS, scene, camera, motionBlurSteps[time], shutterPercentage[time], time, targetOutputFile ).start(callback) } private fun findCamera(scene: Transform): Camera { val cameras = scene.listOfAll.filterIsInstance<Camera>() return cameras.firstOrNull() ?: RemsStudio.nullCamera ?: Camera() } fun overrideAudio(callback: () -> Unit) { if (isRendering) return onAlreadyRendering() FileChooser.selectFiles( NameDesc("Choose source file"), allowFiles = true, allowFolders = false, allowMultiples = false, toSave = false, startFolder = project?.scenes ?: workspace, filters = emptyList() // todo video filter ) { if (it.size == 1) { val video = it.first() if (video != project?.targetOutputFile) { overrideAudio(video, callback) } else LOGGER.warn("Files must not be the same") } } } fun overrideAudio(video: FileReference, callback: () -> Unit) { val meta = getMeta(video, false)!! isRendering = true LOGGER.info("Rendering audio onto video") val duration = meta.duration val sampleRate = max(1, RemsStudio.targetSampleRate) val scene = root.clone() val audioSources = filterAudio(scene) // if empty, skip? LOGGER.info("Found ${audioSources.size} audio sources") // todo progress bar didn't show up :/, why? val progress = GFX.someWindow.addProgressBar(object : ProgressBar("Audio Override", "Samples", duration * sampleRate) { override fun formatProgress(): String { return "$name: ${progress.toLong()} / ${total.toLong()} $unit" } }) AudioCreatorV2(scene, findCamera(scene), audioSources, duration, sampleRate, progress).apply { onFinished = { isRendering = false progress.finish() callback() targetOutputFile.invalidate() } thread(name = "Rendering::renderAudio()") { createOrAppendAudio(targetOutputFile, video, false) } } } fun renderAudio(ask: Boolean, callback: () -> Unit) { if (isRendering) return onAlreadyRendering() val targetOutputFile = findTargetOutputFile(RenderType.AUDIO) if (targetOutputFile.exists && ask) { return askOverridingIsAllowed(targetOutputFile) { renderAudio(false, callback) } } isRendering = true LOGGER.info("Rendering audio") val duration = RemsStudio.targetDuration val sampleRate = max(1, RemsStudio.targetSampleRate) val scene = root.clone() val audioSources = filterAudio(scene) // todo if is empty, send a warning instead of doing something fun createProgressBar(): ProgressBar { return object : ProgressBar("Audio Export", "Samples", duration * sampleRate) { override fun formatProgress(): String { return "$name: ${progress.toLong()} / ${total.toLong()} $unit" } } } val progress = GFX.someWindow.addProgressBar(createProgressBar()) AudioCreatorV2(scene, findCamera(scene), audioSources, duration, sampleRate, progress).apply { onFinished = { isRendering = false progress.finish() callback() targetOutputFile.invalidate() } thread(name = "Rendering::renderAudio()") { createOrAppendAudio(targetOutputFile, InvalidRef, false) } } } private fun onAlreadyRendering() { val windowStack = GFX.someWindow.windowStack msg( windowStack, NameDesc( "Rendering already in progress!", "If you think, this is an error, please restart!", "ui.warn.renderingInProgress" ) ) } private fun askOverridingIsAllowed(targetOutputFile: FileReference, callback: () -> Unit) { val windowStack = GFX.someWindow.windowStack ask(windowStack, NameDesc("Override %1?").with("%1", targetOutputFile.name), callback) } enum class RenderType( val importType: String, val extension: String, val defaultName: String = "output.$extension" ) { VIDEO("Video", ".mp4"), AUDIO("Audio", ".mp3"), FRAME("Image", ".png") } fun findTargetOutputFile(type: RenderType): FileReference { var targetOutputFile = targetOutputFile val defaultExtension = type.extension val defaultName = type.defaultName do { val file0 = targetOutputFile if (targetOutputFile.exists && targetOutputFile.isDirectory) { targetOutputFile = targetOutputFile.getChild(defaultName) } else if (!targetOutputFile.name.contains('.')) { targetOutputFile = targetOutputFile.getSiblingWithExtension(defaultExtension) } } while (file0 !== targetOutputFile) val importType = targetOutputFile.extension.getImportType() if (importType == defaultImportType && RenderType.entries.none { importType == it.importType }) { LOGGER.warn("The file extension .${targetOutputFile.extension} is unknown! Your export may fail!") return targetOutputFile } val targetType = type.importType if (importType != targetType) { // wrong extension -> place it automatically val fileName = targetOutputFile.nameWithoutExtension + defaultExtension return targetOutputFile.getSibling(fileName) } return targetOutputFile } }
2
null
3
19
c9c0d366d1f2d08a57da72f7315bb161579852f2
12,208
RemsStudio
Apache License 2.0
modern-treasury-java-core/src/test/kotlin/com/moderntreasury/api/models/LedgerTransactionUpdateParamsTest.kt
Modern-Treasury
665,761,562
false
null
package com.moderntreasury.api.models import com.moderntreasury.api.models.* import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test class LedgerTransactionUpdateParamsTest { @Test fun createLedgerTransactionUpdateParams() { LedgerTransactionUpdateParams.builder() .id("string") .description("string") .status(LedgerTransactionUpdateParams.Status.ARCHIVED) .metadata(LedgerTransactionUpdateParams.Metadata.builder().build()) .ledgerEntries( listOf( LedgerTransactionUpdateParams.LedgerEntryCreateRequest.builder() .amount(123L) .direction( LedgerTransactionUpdateParams.LedgerEntryCreateRequest.Direction.CREDIT ) .ledgerAccountId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .availableBalanceAmount( LedgerTransactionUpdateParams.LedgerEntryCreateRequest .AvailableBalanceAmount .builder() .build() ) .lockVersion(123L) .pendingBalanceAmount( LedgerTransactionUpdateParams.LedgerEntryCreateRequest .PendingBalanceAmount .builder() .build() ) .postedBalanceAmount( LedgerTransactionUpdateParams.LedgerEntryCreateRequest .PostedBalanceAmount .builder() .build() ) .showResultingLedgerAccountBalances(true) .build() ) ) .build() } @Test fun getBody() { val params = LedgerTransactionUpdateParams.builder() .id("string") .description("string") .status(LedgerTransactionUpdateParams.Status.ARCHIVED) .metadata(LedgerTransactionUpdateParams.Metadata.builder().build()) .ledgerEntries( listOf( LedgerTransactionUpdateParams.LedgerEntryCreateRequest.builder() .amount(123L) .direction( LedgerTransactionUpdateParams.LedgerEntryCreateRequest.Direction .CREDIT ) .ledgerAccountId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .availableBalanceAmount( LedgerTransactionUpdateParams.LedgerEntryCreateRequest .AvailableBalanceAmount .builder() .build() ) .lockVersion(123L) .pendingBalanceAmount( LedgerTransactionUpdateParams.LedgerEntryCreateRequest .PendingBalanceAmount .builder() .build() ) .postedBalanceAmount( LedgerTransactionUpdateParams.LedgerEntryCreateRequest .PostedBalanceAmount .builder() .build() ) .showResultingLedgerAccountBalances(true) .build() ) ) .build() val body = params.getBody() assertThat(body).isNotNull assertThat(body.description()).isEqualTo("string") assertThat(body.status()).isEqualTo(LedgerTransactionUpdateParams.Status.ARCHIVED) assertThat(body.metadata()) .isEqualTo(LedgerTransactionUpdateParams.Metadata.builder().build()) assertThat(body.ledgerEntries()) .isEqualTo( listOf( LedgerTransactionUpdateParams.LedgerEntryCreateRequest.builder() .amount(123L) .direction( LedgerTransactionUpdateParams.LedgerEntryCreateRequest.Direction.CREDIT ) .ledgerAccountId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .availableBalanceAmount( LedgerTransactionUpdateParams.LedgerEntryCreateRequest .AvailableBalanceAmount .builder() .build() ) .lockVersion(123L) .pendingBalanceAmount( LedgerTransactionUpdateParams.LedgerEntryCreateRequest .PendingBalanceAmount .builder() .build() ) .postedBalanceAmount( LedgerTransactionUpdateParams.LedgerEntryCreateRequest .PostedBalanceAmount .builder() .build() ) .showResultingLedgerAccountBalances(true) .build() ) ) } @Test fun getBodyWithoutOptionalFields() { val params = LedgerTransactionUpdateParams.builder().id("string").build() val body = params.getBody() assertThat(body).isNotNull } @Test fun getPathParam() { val params = LedgerTransactionUpdateParams.builder().id("string").build() assertThat(params).isNotNull // path param "id" assertThat(params.getPathParam(0)).isEqualTo("string") // out-of-bound path param assertThat(params.getPathParam(1)).isEqualTo("") } }
2
Kotlin
1
0
c5719b232bfb411d426e5c4de888ad167ef4acce
6,426
modern-treasury-java
MIT License
app/src/main/java/com/yangdai/opennote/ui/component/DrawerItem.kt
YangDai2003
774,993,540
false
{"Kotlin": 218210}
package com.yangdai.opennote.ui.component import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.NavigationDrawerItem import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp @Composable fun DrawerItem( icon: ImageVector, iconTint: Color = MaterialTheme.colorScheme.onSurface, label: String, badge: String = "", selected: Boolean, onClick: () -> Unit ) = NavigationDrawerItem( modifier = Modifier.padding(horizontal = 8.dp), icon = { Icon( modifier = Modifier.padding(horizontal = 12.dp), imageVector = icon, tint = iconTint, contentDescription = "Leading Icon" ) }, label = { Text( text = label, color = MaterialTheme.colorScheme.onSurface, fontWeight = FontWeight.Bold, maxLines = 1, overflow = TextOverflow.Ellipsis ) }, badge = { Text( text = badge, style = MaterialTheme.typography.labelMedium ) }, shape = RoundedCornerShape(16.dp), selected = selected, onClick = onClick )
0
Kotlin
0
0
7e727f427cd812759a517db20420357005bafd92
1,593
OpenNote-Compose
Apache License 2.0
app/src/main/kotlin/app/newproj/lbrytv/data/datasource/VideoLocalDataSource.kt
linimin
434,503,024
false
null
/* * MIT License * * Copyright (c) 2022 <NAME> * * 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 app.newproj.lbrytv.data.datasource import androidx.paging.PagingSource import androidx.room.withTransaction import app.newproj.lbrytv.data.AppDatabase import app.newproj.lbrytv.data.dto.ClaimSearchResult import app.newproj.lbrytv.data.dto.Video import app.newproj.lbrytv.data.entity.ClaimLookup import kotlinx.coroutines.flow.Flow import javax.inject.Inject class VideoLocalDataSource @Inject constructor( private val db: AppDatabase, ) { fun video(id: String): Flow<Video> = db.videoDao().video(id) suspend fun upsert(claim: ClaimSearchResult.Item) { db.claimSearchResultDao().upsert(claim) } fun featuredVideoPagingSource(): PagingSource<Int, Video> = db.videoDao().featuredVideosPagingSource() fun subscriptionVideoPagingSource(): PagingSource<Int, Video> = db.videoDao().subscriptionVideos() fun channelVideoPagingSource(channelId: String): PagingSource<Int, Video> = db.videoDao().videos(channelId) suspend fun replaceRecommendedVideos(claims: List<ClaimSearchResult.Item>): List<Video> { return db.withTransaction { db.claimSearchResultDao().upsert(claims) db.claimLookupDao().deleteAll("RECOMMENDED_VIDEOS") val claimLookups = claims.mapIndexed { index, claim -> ClaimLookup("RECOMMENDED_VIDEOS", claim.claimId, index) } db.claimLookupDao().upsert(claimLookups) db.videoDao().recommendedVideos() } } }
7
Kotlin
3
23
75bed7e7bae0b1ddaa2b5356b82dbec62c25776e
2,626
lbry-androidtv
MIT License
logging/src/commonMain/kotlin/Pool.kt
JuulLabs
261,866,344
false
null
package com.juul.tuulbox.logging import kotlinx.atomicfu.locks.reentrantLock import kotlinx.atomicfu.locks.withLock /** While a [Pool] is logically thread safe, Kotlin/Native's memory model requires @ThreadLocal on instances of this. */ internal class Pool<T>( private val factory: () -> T, private val refurbish: (T) -> Unit, ) { private val lock = reentrantLock() private val cache = ArrayDeque<T>() fun borrow(): T = lock.withLock { cache.removeLastOrNull() } ?: factory() fun recycle(value: T) { refurbish(value) lock.withLock { cache.addLast(value) } } }
9
null
2
7
85d8a11cc66b04f5461de7d66c06eca341269570
608
tuulbox
Apache License 2.0
platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/EditorComposite.kt
ingokegel
72,937,917
false
null
// Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("ReplaceGetOrSet", "ReplacePutWithAssignment") package com.intellij.openapi.fileEditor.impl import com.intellij.codeWithMe.ClientId import com.intellij.codeWithMe.ClientId.Companion.isLocal import com.intellij.ide.impl.DataValidators import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.actionSystem.DataProvider import com.intellij.openapi.actionSystem.IdeActions import com.intellij.openapi.actionSystem.PlatformCoreDataKeys import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.editor.colors.EditorColors import com.intellij.openapi.editor.colors.EditorColorsManager import com.intellij.openapi.fileEditor.* import com.intellij.openapi.fileEditor.ClientFileEditorManager.Companion.assignClientId import com.intellij.openapi.fileEditor.ex.FileEditorWithProvider import com.intellij.openapi.project.DumbService import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.Pair import com.intellij.openapi.util.Weighted import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.wm.FocusWatcher import com.intellij.openapi.wm.IdeFocusManager import com.intellij.ui.* import com.intellij.ui.components.panels.NonOpaquePanel import com.intellij.ui.components.panels.Wrapper import com.intellij.ui.tabs.JBTabs import com.intellij.ui.tabs.impl.JBTabsImpl import com.intellij.util.EventDispatcher import com.intellij.util.ui.EDT import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import java.awt.BorderLayout import java.awt.Color import java.awt.Component import java.util.concurrent.CopyOnWriteArrayList import javax.swing.BoxLayout import javax.swing.JComponent import javax.swing.JPanel import javax.swing.SwingConstants /** * An abstraction over one or several file editors opened in the same tab (e.g. designer and code-behind). * It's a composite that can be pinned in the tab list or opened as a preview, not concrete file editors. * It also manages the internal UI structure: bottom and top components, panels, labels, actions for navigating between editors it owns. */ @Suppress("LeakingThis") open class EditorComposite internal constructor( val file: VirtualFile, editorsWithProviders: List<FileEditorWithProvider>, internal val project: Project, ) : FileEditorComposite, Disposable { private val clientId: ClientId private var tabbedPaneWrapper: TabbedPaneWrapper? = null private var compositePanel: EditorCompositePanel private val focusWatcher: FocusWatcher? /** * Currently selected editor */ protected val selectedEditorWithProviderMutable: MutableStateFlow<FileEditorWithProvider?> = MutableStateFlow(null) internal val selectedEditorWithProvider: StateFlow<FileEditorWithProvider?> = selectedEditorWithProviderMutable.asStateFlow() private val topComponents = HashMap<FileEditor, JComponent>() private val bottomComponents = HashMap<FileEditor, JComponent>() private val displayNames = HashMap<FileEditor, String>() /** * Editors opened in the composite */ private val editorsWithProviders = CopyOnWriteArrayList(editorsWithProviders) private val dispatcher = EventDispatcher.create(EditorCompositeListener::class.java) private var selfBorder = false init { EDT.assertIsEdt() clientId = ClientId.current for (editorWithProvider in editorsWithProviders) { val editor = editorWithProvider.fileEditor FileEditor.FILE_KEY.set(editor, file) if (!clientId.isLocal) { assignClientId(editor, clientId) } } when { editorsWithProviders.size > 1 -> { tabbedPaneWrapper = createTabbedPaneWrapper(component = null) val component = tabbedPaneWrapper!!.component compositePanel = EditorCompositePanel(realComponent = component, composite = this, focusComponent = { component }) } editorsWithProviders.size == 1 -> { tabbedPaneWrapper = null val editor = editorsWithProviders[0].fileEditor compositePanel = EditorCompositePanel(realComponent = createEditorComponent(editor), composite = this, focusComponent = { editor.preferredFocusedComponent }) } else -> throw IllegalArgumentException("editor array cannot be empty") } selectedEditorWithProviderMutable.value = editorsWithProviders[0] focusWatcher = FocusWatcher() focusWatcher.install(compositePanel) } companion object { private val LOG = logger<EditorComposite>() private fun calcComponentInsertionIndex(newComponent: JComponent, container: JComponent): Int { var i = 0 val max = container.componentCount while (i < max) { val childWrapper = container.getComponent(i) val childComponent = if (childWrapper is Wrapper) childWrapper.targetComponent else childWrapper val weighted1 = newComponent is Weighted val weighted2 = childComponent is Weighted if (!weighted2) { i++ continue } if (!weighted1) return i val w1 = (newComponent as Weighted).weight val w2 = (childComponent as Weighted).weight if (w1 < w2) return i i++ } return -1 } @JvmStatic fun isEditorComposite(component: Component): Boolean = component is EditorCompositePanel private fun createTopBottomSideBorder(top: Boolean, borderColor: Color?): SideBorder { return object : SideBorder(null, if (top) BOTTOM else TOP) { override fun getLineColor(): Color { if (borderColor != null) { return borderColor } val scheme = EditorColorsManager.getInstance().globalScheme if (ExperimentalUI.isNewUI()) { return scheme.defaultBackground } else { return scheme.getColor(EditorColors.TEARLINE_COLOR) ?: JBColor.BLACK } } } } /** * A mapper for old API with arrays and pairs */ fun retrofit(composite: FileEditorComposite?): Pair<Array<FileEditor>, Array<FileEditorProvider>> { if (composite == null) { return Pair(FileEditor.EMPTY_ARRAY, FileEditorProvider.EMPTY_ARRAY) } else { return Pair(composite.allEditors.toTypedArray(), composite.allProviders.toTypedArray()) } } } @get:Deprecated("use {@link #getAllEditorsWithProviders()}", ReplaceWith("allProviders"), level = DeprecationLevel.ERROR) val providers: Array<FileEditorProvider> get() = allProviders.toTypedArray() override val allProviders: List<FileEditorProvider> get() = providerSequence.toList() internal val providerSequence: Sequence<FileEditorProvider> get() = editorsWithProviders.asSequence().map { it.provider } private fun createTabbedPaneWrapper(component: EditorCompositePanel?): TabbedPaneWrapper { val descriptor = PrevNextActionsDescriptor(IdeActions.ACTION_NEXT_EDITOR_TAB, IdeActions.ACTION_PREVIOUS_EDITOR_TAB) val wrapper = TabbedPaneWrapper.createJbTabs(project, SwingConstants.BOTTOM, descriptor, this) var firstEditor = true for (editorWithProvider in editorsWithProviders) { val editor = editorWithProvider.fileEditor wrapper.addTab( getDisplayName(editor), if (firstEditor && component != null) component.getComponent(0) as JComponent else createEditorComponent(editor), ) firstEditor = false } // handles changes of selected editor wrapper.addChangeListener { val selectedIndex = tabbedPaneWrapper!!.selectedIndex require(selectedIndex != -1) selectedEditorWithProviderMutable.value = editorsWithProviders.get(selectedIndex) } return wrapper } private fun createEditorComponent(editor: FileEditor): JComponent { val component = JPanel(BorderLayout()) var editorComponent = editor.component if (!FileEditorManagerImpl.isDumbAware(editor)) { editorComponent = DumbService.getInstance(project).wrapGently(editorComponent, editor) } component.add(editorComponent, BorderLayout.CENTER) val topPanel = TopBottomPanel() topComponents.put(editor, topPanel) component.add(topPanel, BorderLayout.NORTH) val bottomPanel = TopBottomPanel() bottomComponents.put(editor, bottomPanel) component.add(bottomPanel, BorderLayout.SOUTH) return component } /** * @return whether myEditor composite is pinned */ var isPinned: Boolean = false /** * Sets new "pinned" state */ set(pinned) { val oldPinned = field field = pinned (compositePanel.parent as? JComponent)?.let { ClientProperty.put(it, JBTabsImpl.PINNED, if (field) true else null) } if (pinned != oldPinned) { dispatcher.multicaster.isPinnedChanged(this, pinned) } } /** * Whether the composite is opened as a preview tab or not */ override var isPreview: Boolean = false set(preview) { if (preview != field) { field = preview dispatcher.multicaster.isPreviewChanged(this, preview) } } fun addListener(listener: EditorCompositeListener, disposable: Disposable?) { dispatcher.addListener(listener, disposable!!) } /** * @return preferred focused component inside myEditor composite. Composite uses FocusWatcher to track focus movement inside the editor. */ open val preferredFocusedComponent: JComponent? get() { if (selectedEditorWithProvider.value == null) { return null } val component = focusWatcher!!.focusedComponent if (component !is JComponent || !component.isShowing() || !component.isEnabled() || !component.isFocusable()) { return selectedEditor?.preferredFocusedComponent } else { return component } } @Deprecated(message = "Use FileEditorManager.getInstance()", replaceWith = ReplaceWith("FileEditorManager.getInstance()"), level = DeprecationLevel.ERROR) val fileEditorManager: FileEditorManager get() = FileEditorManager.getInstance(project) @get:Deprecated("use {@link #getAllEditors()}", ReplaceWith("allEditors"), level = DeprecationLevel.ERROR) val editors: Array<FileEditor> get() = allEditors.toTypedArray() final override val allEditors: List<FileEditor> get() = editorsWithProviders.map { it.fileEditor } val allEditorsWithProviders: List<FileEditorWithProvider> get() = java.util.List.copyOf(editorsWithProviders) fun getTopComponents(editor: FileEditor): List<JComponent> { return topComponents.get(editor)!!.components.mapNotNull { (it as? NonOpaquePanel)?.targetComponent } } internal fun containsFileEditor(editor: FileEditor): Boolean { return editorsWithProviders.any { it.fileEditor === editor } } open val tabs: JBTabs? get() = tabbedPaneWrapper?.let { (it.tabbedPane as JBTabsPaneImpl).tabs } fun addTopComponent(editor: FileEditor, component: JComponent) { manageTopOrBottomComponent(editor = editor, component = component, top = true, remove = false) } fun removeTopComponent(editor: FileEditor, component: JComponent) { manageTopOrBottomComponent(editor = editor, component = component, top = true, remove = true) } fun addBottomComponent(editor: FileEditor, component: JComponent) { manageTopOrBottomComponent(editor = editor, component = component, top = false, remove = false) } fun removeBottomComponent(editor: FileEditor, component: JComponent) { manageTopOrBottomComponent(editor = editor, component = component, top = false, remove = true) } private fun manageTopOrBottomComponent(editor: FileEditor, component: JComponent, top: Boolean, remove: Boolean) { ApplicationManager.getApplication().assertIsDispatchThread() val container = (if (top) topComponents.get(editor) else bottomComponents.get(editor))!! selfBorder = false if (remove) { container.remove(component.parent) val multicaster = dispatcher.multicaster if (top) { multicaster.topComponentRemoved(editor, component) } else { multicaster.bottomComponentRemoved(editor, component) } } else { val wrapper = NonOpaquePanel(component) if (component.getClientProperty(FileEditorManager.SEPARATOR_DISABLED) != true) { val border = ClientProperty.get(component, FileEditorManager.SEPARATOR_BORDER) selfBorder = border != null wrapper.border = border ?: createTopBottomSideBorder(top = top, borderColor = ClientProperty.get(component, FileEditorManager.SEPARATOR_COLOR)) } val index = calcComponentInsertionIndex(component, container) container.add(wrapper, index) val multicaster = dispatcher.multicaster if (top) { multicaster.topComponentAdded(editor, index, component) } else { multicaster.bottomComponentAdded(editor, index, component) } } container.revalidate() } fun selfBorder(): Boolean = selfBorder fun setDisplayName(editor: FileEditor, name: @NlsContexts.TabTitle String) { val index = editorsWithProviders.indexOfFirst { it.fileEditor == editor } assert(index != -1) displayNames.set(editor, name) tabbedPaneWrapper?.setTitleAt(index, name) dispatcher.multicaster.displayNameChanged(editor, name) } @Suppress("HardCodedStringLiteral") protected fun getDisplayName(editor: FileEditor): @NlsContexts.TabTitle String = displayNames.get(editor) ?: editor.name internal fun deselectNotify() { val selected = selectedEditorWithProvider.value ?: return selectedEditorWithProviderMutable.value = null selected.fileEditor.deselectNotify() } val selectedEditor: FileEditor? get() = selectedWithProvider?.fileEditor val selectedWithProvider: FileEditorWithProvider? get() = selectedEditorWithProvider.value fun setSelectedEditor(providerId: String) { val fileEditorWithProvider = editorsWithProviders.firstOrNull { it.provider.editorTypeId == providerId } ?: return setSelectedEditor(fileEditorWithProvider) } fun setSelectedEditor(editor: FileEditor) { val newSelection = editorsWithProviders.firstOrNull { it.fileEditor == editor } LOG.assertTrue(newSelection != null, "Unable to find editor=$editor") setSelectedEditor(newSelection!!) } open fun setSelectedEditor(editorWithProvider: FileEditorWithProvider) { if (editorsWithProviders.size == 1) { LOG.assertTrue(tabbedPaneWrapper == null) LOG.assertTrue(editorWithProvider == editorsWithProviders[0]) return } val index = editorsWithProviders.indexOf(editorWithProvider) LOG.assertTrue(index != -1) LOG.assertTrue(tabbedPaneWrapper != null) tabbedPaneWrapper!!.selectedIndex = index } open val component: JComponent /** * @return component which represents a set of file editors in the UI */ get() = compositePanel open val focusComponent: JComponent? /** * @return component which represents the component that is supposed to be focusable */ get() = compositePanel.focusComponent() val isModified: Boolean /** * @return `true` if the composite contains at least one modified myEditor */ get() = allEditors.any { it.isModified } override fun dispose() { selectedEditorWithProviderMutable.value = null for (editor in editorsWithProviders) { @Suppress("DEPRECATION") if (!Disposer.isDisposed(editor.fileEditor)) { Disposer.dispose(editor.fileEditor) } } focusWatcher?.deinstall(focusWatcher.topComponent) } fun addEditor(editor: FileEditor, provider: FileEditorProvider) { ApplicationManager.getApplication().assertIsDispatchThread() val editorWithProvider = FileEditorWithProvider(editor, provider) editorsWithProviders.add(editorWithProvider) FileEditor.FILE_KEY.set(editor, file) if (!clientId.isLocal) { assignClientId(editor, clientId) } if (tabbedPaneWrapper == null) { tabbedPaneWrapper = createTabbedPaneWrapper(compositePanel) compositePanel.setComponent(tabbedPaneWrapper!!.component) } else { val component = createEditorComponent(editor) tabbedPaneWrapper!!.addTab(getDisplayName(editor), component) } focusWatcher!!.deinstall(focusWatcher.topComponent) focusWatcher.install(compositePanel) dispatcher.multicaster.editorAdded(editorWithProvider) } fun currentStateAsHistoryEntry(): HistoryEntry { val editors = allEditors val states = editors.map { it.getState(FileEditorStateLevel.FULL) } val selectedProviderIndex = editors.indexOf(selectedEditorWithProvider.value?.fileEditor) LOG.assertTrue(selectedProviderIndex != -1) val providers = allProviders return HistoryEntry.createLight(file, providers, states, providers.get(selectedProviderIndex), isPreview) } } private class EditorCompositePanel(realComponent: JComponent, private val composite: EditorComposite, var focusComponent: () -> JComponent?) : JPanel(BorderLayout()), DataProvider { init { isFocusable = false add(realComponent, BorderLayout.CENTER) } fun setComponent(newComponent: JComponent) { add(newComponent, BorderLayout.CENTER) focusComponent = { newComponent } } override fun requestFocusInWindow(): Boolean = focusComponent()?.requestFocusInWindow() ?: false override fun requestFocus() { val focusComponent = focusComponent() ?: return val focusManager = IdeFocusManager.getGlobalInstance() focusManager.doWhenFocusSettlesDown { focusManager.requestFocus(focusComponent, true) } } @Suppress("OVERRIDE_DEPRECATION", "DEPRECATION") override fun requestDefaultFocus(): Boolean = focusComponent()?.requestDefaultFocus() ?: false override fun getData(dataId: String): Any? { return when { CommonDataKeys.PROJECT.`is`(dataId) -> composite.project PlatformCoreDataKeys.FILE_EDITOR.`is`(dataId) -> composite.selectedEditor CommonDataKeys.VIRTUAL_FILE.`is`(dataId) -> composite.file CommonDataKeys.VIRTUAL_FILE_ARRAY.`is`(dataId) -> arrayOf(composite.file) else -> { val component = composite.preferredFocusedComponent if (component is DataProvider && component !== this) { val data = component.getData(dataId) if (data == null) null else DataValidators.validOrNull(data, dataId, component) } else { null } } } } } private class TopBottomPanel : JPanel() { init { layout = BoxLayout(this, BoxLayout.Y_AXIS) } override fun getBackground(): Color { val globalScheme = EditorColorsManager.getInstance().globalScheme if (ExperimentalUI.isNewUI()) { return globalScheme.defaultBackground } else { return globalScheme.getColor(EditorColors.GUTTER_BACKGROUND) ?: EditorColors.GUTTER_BACKGROUND.defaultColor } } }
284
null
5162
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
19,462
intellij-community
Apache License 2.0
app/src/androidTestScenarios/java/uk/nhs/nhsx/covid19/android/app/qrcode/riskyvenues/DownloadAndProcessRiskyVenuesFlowTest.kt
coderus-ltd
369,240,870
true
{"Kotlin": 3133494, "Shell": 1098, "Ruby": 847, "Batchfile": 197}
package uk.nhs.nhsx.covid19.android.app.qrcode.riskyvenues import java.time.Instant import kotlin.test.assertEquals import kotlin.test.assertNull import kotlinx.coroutines.runBlocking import org.junit.After import org.junit.Test import uk.nhs.nhsx.covid19.android.app.notifications.AddableUserInboxItem import uk.nhs.nhsx.covid19.android.app.notifications.AddableUserInboxItem.ShowVenueAlert import uk.nhs.nhsx.covid19.android.app.qrcode.Venue import uk.nhs.nhsx.covid19.android.app.remote.data.MessageType.BOOK_TEST import uk.nhs.nhsx.covid19.android.app.remote.data.MessageType.INFORM import uk.nhs.nhsx.covid19.android.app.remote.data.RiskyVenue import uk.nhs.nhsx.covid19.android.app.remote.data.RiskyVenuesResponse import uk.nhs.nhsx.covid19.android.app.remote.data.RiskyWindow import uk.nhs.nhsx.covid19.android.app.report.notReported import uk.nhs.nhsx.covid19.android.app.testhelpers.base.EspressoTest import java.time.LocalDate class DownloadAndProcessRiskyVenuesFlowTest : EspressoTest() { private val venue1 = Venue( id = "3KR9JX59", organizationPartName = "Venue1" ) private val venue2 = Venue( id = "2V542M5J", organizationPartName = "Venue2" ) private val venue3 = Venue( id = "MX5X235W", organizationPartName = "Venue3" ) private val venue4 = Venue( id = "94RK34RY", organizationPartName = "Venue4" ) private val venue1Instant = Instant.parse("2020-08-02T00:00:00Z") private val venue2Instant = Instant.parse("2020-08-02T02:00:00Z") private val venue3Instant = Instant.parse("2020-08-02T04:00:00Z") private val venue4Instant = Instant.parse("2020-08-02T06:00:00Z") private val riskyVenues1to2 = listOf( RiskyVenue( venue1.id, RiskyWindow( from = Instant.parse("2020-08-01T00:00:00Z"), to = Instant.parse("2020-08-30T23:59:59Z") ), messageType = INFORM ), RiskyVenue( venue2.id, RiskyWindow( from = Instant.parse("2020-08-01T00:00:00Z"), to = Instant.parse("2020-08-30T23:59:59Z") ), messageType = BOOK_TEST ) ) private val riskyVenues3 = riskyVenues1to2 + listOf( RiskyVenue( venue3.id, RiskyWindow( from = Instant.parse("2020-08-01T00:00:00Z"), to = Instant.parse("2020-08-30T23:59:59Z") ), messageType = INFORM ) ) private val riskyVenues4 = riskyVenues3 + listOf( RiskyVenue( venue4.id, RiskyWindow( from = Instant.parse("2020-08-01T00:00:00Z"), to = Instant.parse("2020-08-30T23:59:59Z") ), messageType = INFORM ) ) @After fun tearDown() { testAppContext.clock.reset() } @Test fun visitAndMarkRiskyMultipleVenues() = notReported { runBlocking { val visitedVenuesStorage = testAppContext.getVisitedVenuesStorage() val downloadAndProcessRiskyVenues = testAppContext.getDownloadAndProcessRiskyVenues() val userInbox = testAppContext.getUserInbox() visitedVenuesStorage.removeAllVenueVisits() testAppContext.clock.currentInstant = venue1Instant visitedVenuesStorage .finishLastVisitAndAddNewVenue(venue1) testAppContext.clock.currentInstant = venue2Instant visitedVenuesStorage .finishLastVisitAndAddNewVenue(venue2) testAppContext.clock.currentInstant = venue3Instant visitedVenuesStorage .finishLastVisitAndAddNewVenue(venue3) testAppContext.clock.currentInstant = venue4Instant visitedVenuesStorage .finishLastVisitAndAddNewVenue(venue4) testAppContext.riskyVenuesApi.riskyVenuesResponse = RiskyVenuesResponse(venues = riskyVenues1to2) downloadAndProcessRiskyVenues.invoke(clearOutdatedVisits = false) val alert1 = userInbox.fetchInbox() as AddableUserInboxItem assertEquals(ShowVenueAlert(venue2.id, BOOK_TEST), alert1) userInbox.clearItem(alert1) testAppContext.riskyVenuesApi.riskyVenuesResponse = RiskyVenuesResponse(venues = riskyVenues3) downloadAndProcessRiskyVenues.invoke(clearOutdatedVisits = false) val alert2 = userInbox.fetchInbox() as AddableUserInboxItem assertEquals(ShowVenueAlert(venue3.id, INFORM), alert2) userInbox.clearItem(alert2) testAppContext.riskyVenuesApi.riskyVenuesResponse = RiskyVenuesResponse(venues = riskyVenues4) downloadAndProcessRiskyVenues.invoke(clearOutdatedVisits = false) val alert3 = userInbox.fetchInbox() as AddableUserInboxItem assertEquals(ShowVenueAlert(venue4.id, INFORM), alert3) userInbox.clearItem(alert3) downloadAndProcessRiskyVenues.invoke(clearOutdatedVisits = false) assertNull(userInbox.fetchInbox()) } } @Test fun visitBookTestTypeRiskyVenue() = notReported { runBlocking { val visitedVenuesStorage = testAppContext.getVisitedVenuesStorage() val downloadAndProcessRiskyVenues = testAppContext.getDownloadAndProcessRiskyVenues() val lastVisitedBookTestTypeVenueDate = testAppContext.getLastVisitedBookTestTypeVenueDateProvider() visitedVenuesStorage.removeAllVenueVisits() val venue = Venue( id = "74ZK34RY", organizationPartName = "Venue" ) val bookTestTypeRiskyVenue = RiskyVenue( venue.id, RiskyWindow( from = Instant.parse("2020-08-01T15:00:00Z"), to = Instant.parse("2020-08-02T00:00:00Z") ), messageType = BOOK_TEST ) testAppContext.clock.currentInstant = Instant.parse("2020-08-01T20:00:00Z") val initialLatestDate = lastVisitedBookTestTypeVenueDate.lastVisitedVenue?.latestDate assertNull(initialLatestDate) visitedVenuesStorage.finishLastVisitAndAddNewVenue(venue) testAppContext.riskyVenuesApi.riskyVenuesResponse = RiskyVenuesResponse(venues = listOf(bookTestTypeRiskyVenue)) downloadAndProcessRiskyVenues.invoke(clearOutdatedVisits = false) val latestDate = lastVisitedBookTestTypeVenueDate.lastVisitedVenue?.latestDate assertEquals(LocalDate.parse("2020-08-01"), latestDate) } } }
0
null
0
0
b74358684b9dbc0174890db896b93b0f7c6660a4
6,812
covid-19-app-android-ag-public
MIT License
desktop/src/main/kotlin/io/kanro/mediator/desktop/ui/MessageView.kt
ButterCam
365,499,735
false
null
package io.kanro.mediator.desktop.ui import androidx.compose.foundation.ContextMenuItem import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.VerticalScrollbar import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.rememberScrollbarAdapter import androidx.compose.foundation.verticalScroll import androidx.compose.runtime.Composable import androidx.compose.runtime.MutableState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import com.bybutter.sisyphus.jackson.toJson import com.bybutter.sisyphus.protobuf.Message import com.bybutter.sisyphus.protobuf.ProtoEnum import com.bybutter.sisyphus.protobuf.ProtoReflection import com.bybutter.sisyphus.protobuf.findMapEntryDescriptor import com.bybutter.sisyphus.protobuf.invoke import com.bybutter.sisyphus.protobuf.primitives.Duration import com.bybutter.sisyphus.protobuf.primitives.FieldDescriptorProto import com.bybutter.sisyphus.protobuf.primitives.Timestamp import com.bybutter.sisyphus.protobuf.primitives.string import com.bybutter.sisyphus.security.base64 import com.bybutter.sisyphus.string.toCamelCase import io.kanro.compose.jetbrains.JBTheme import io.kanro.compose.jetbrains.control.ContextMenuArea import io.kanro.compose.jetbrains.control.JBTreeItem import io.kanro.compose.jetbrains.control.JBTreeList import java.awt.Toolkit import java.awt.datatransfer.StringSelection import java.util.UUID @Composable @OptIn(ExperimentalFoundationApi::class) fun MessageView(reflection: ProtoReflection, message: Message<*, *>) { Box(Modifier.background(JBTheme.panelColors.bgContent).fillMaxSize()) { val vState = rememberScrollState() JBTreeList( Modifier.verticalScroll(vState) ) { val selectedItem = remember { mutableStateOf("") } val fields = reflection { val fields = mutableMapOf<FieldDescriptorProto, Any?>() for ((field, value) in message) { if (message.has(field.number)) { fields[field] = value } } fields } for ((field, value) in fields) { FieldView(selectedItem, reflection, field, value) } } VerticalScrollbar( adapter = rememberScrollbarAdapter(vState), Modifier.align(Alignment.CenterEnd) ) } } @Composable fun FieldView( selectedItem: MutableState<String>, reflection: ProtoReflection, field: FieldDescriptorProto, value: Any? ) { if (field.label == FieldDescriptorProto.Label.REPEATED) { RepeatedFieldView(Modifier, selectedItem, reflection, field, value) } else { SimpleFieldView(Modifier, selectedItem, reflection, field, null, value) } } @Composable internal fun RepeatedFieldView( modifier: Modifier, selectedItem: MutableState<String>, reflection: ProtoReflection, field: FieldDescriptorProto, value: Any?, ) { var expanded by remember { mutableStateOf(false) } val key = remember { UUID.randomUUID().toString() } val selected = key == selectedItem.value FieldContextMenu(reflection, field, value) { JBTreeItem( modifier = modifier.fillMaxSize(), expanded = expanded, expanding = { expanded = it }, selected = selected, onClick = { selectedItem.value = key }, content = { Row(Modifier.fillMaxSize(), verticalAlignment = Alignment.CenterVertically) { Label(field.name) when (value) { is List<*> -> { val type = field.typeName.substringAfterLast('.').takeIf { it.isNotEmpty() } ?: field.type.toString() .toCamelCase() Label(": $type[]", color = JBTheme.textColors.infoInput) } is Map<*, *> -> { val entry = reflection.findMapEntryDescriptor(field.typeName) val keyField = entry?.field?.firstOrNull { it.number == 1 } val valueField = entry?.field?.firstOrNull { it.number == 2 } val keyType = keyField?.typeName?.substringAfterLast('.')?.takeIf { it.isNotEmpty() } ?: keyField?.type?.toString()?.toCamelCase() val valueType = valueField?.typeName?.substringAfterLast('.')?.takeIf { it.isNotEmpty() } ?: valueField?.type?.toString()?.toCamelCase() Label( ": map<${keyType ?: "?"}, ${valueType ?: "?"}>", color = JBTheme.textColors.infoInput ) } } } } ) { when (value) { is List<*> -> { value.forEachIndexed { index, any -> SimpleFieldView(Modifier, selectedItem, reflection, field, index.toString(), any) } } is Map<*, *> -> { val valueField = reflection.findMapEntryDescriptor(field.typeName)?.field?.firstOrNull { it.number == 2 } if (valueField != null) { value.forEach { (key, any) -> SimpleFieldView(Modifier, selectedItem, reflection, valueField, key.toString(), any) } } else { JBTreeItem( selected = false, onClick = { selectedItem.value = "" } ) { Label("Unknown Map Field") } } } } } } } @Composable internal fun SimpleFieldView( modifier: Modifier, selectedItem: MutableState<String>, reflection: ProtoReflection, field: FieldDescriptorProto, prefix: String?, value: Any? ) { val key = remember { UUID.randomUUID().toString() } val selected = key == selectedItem.value when (field.type) { FieldDescriptorProto.Type.MESSAGE -> { MessageFieldView(modifier, selectedItem, reflection, field, prefix, value as Message<*, *>) } FieldDescriptorProto.Type.ENUM -> FieldContextMenu(reflection, field, value) { JBTreeItem( modifier.fillMaxSize(), selected = selected, onClick = { selectedItem.value = key } ) { Row(Modifier.fillMaxSize(), verticalAlignment = Alignment.CenterVertically) { Label(prefix ?: field.name) Label(": ${field.typeName.substringAfterLast('.')}", color = JBTheme.textColors.infoInput) Label(" = $value") Label("(${(value as ProtoEnum<*>).number})", color = JBTheme.textColors.infoInput) } } } FieldDescriptorProto.Type.BYTES -> FieldContextMenu(reflection, field, value) { JBTreeItem( modifier.fillMaxSize(), selected = selected, onClick = { selectedItem.value = key } ) { Row(Modifier.fillMaxSize(), verticalAlignment = Alignment.CenterVertically) { Label(prefix ?: field.name) Label(": bytes", color = JBTheme.textColors.infoInput) Label(" = ${(value as ByteArray).base64()}") } } } FieldDescriptorProto.Type.STRING -> FieldContextMenu(reflection, field, value) { JBTreeItem( modifier.fillMaxSize(), selected = selected, onClick = { selectedItem.value = key } ) { Row(Modifier.fillMaxSize(), verticalAlignment = Alignment.CenterVertically) { Label(prefix ?: field.name) Label(": string", color = JBTheme.textColors.infoInput) Label(" = ${value?.toJson()}") } } } else -> FieldContextMenu(reflection, field, value) { JBTreeItem( modifier.fillMaxSize(), selected = selected, onClick = { selectedItem.value = key } ) { Row(Modifier.fillMaxSize(), verticalAlignment = Alignment.CenterVertically) { Label(prefix ?: field.name) Label(": ${field.type.toString().toCamelCase()}", color = JBTheme.textColors.infoInput) Label(" = $value") } } } } } @Composable @OptIn(ExperimentalFoundationApi::class) internal fun FieldContextMenu( reflection: ProtoReflection, field: FieldDescriptorProto, value: Any?, content: @Composable () -> Unit ) { ContextMenuArea( { val result = mutableListOf<ContextMenuItem>() result += ContextMenuItem("Copy Field Name") { Toolkit.getDefaultToolkit().systemClipboard.setContents(StringSelection(field.name), null) } result += ContextMenuItem("Copy Field JSON Name") { Toolkit.getDefaultToolkit().systemClipboard.setContents(StringSelection(field.jsonName), null) } val json = reflection { value?.toJson() ?: "" } result += ContextMenuItem("Copy Value as JSON") { Toolkit.getDefaultToolkit().systemClipboard.setContents(StringSelection(json), null) } val stringValue = when (value) { is String -> value is Timestamp -> value.string() is Duration -> value.string() else -> null } if (stringValue != null) { result += ContextMenuItem("Copy Value") { Toolkit.getDefaultToolkit().systemClipboard.setContents(StringSelection(stringValue), null) } } result }, content = content ) } @Composable internal fun MessageFieldView( modifier: Modifier, selectedItem: MutableState<String>, reflection: ProtoReflection, field: FieldDescriptorProto, prefix: String?, message: Message<*, *> ) { var expanded by remember { mutableStateOf(false) } val key = remember { UUID.randomUUID().toString() } val selected = key == selectedItem.value FieldContextMenu(reflection, field, message) { JBTreeItem( modifier = modifier.fillMaxSize(), expanded = expanded, expanding = { expanded = it }, selected = selected, onClick = { selectedItem.value = key }, content = { Row(Modifier.fillMaxSize(), verticalAlignment = Alignment.CenterVertically) { Label(prefix ?: field.name) Label(": ${message.type().substringAfterLast('.')}", color = JBTheme.textColors.infoInput) when (message) { is Timestamp -> Label(" = ${message.string()}", color = JBTheme.textColors.infoInput) is Duration -> Label(" = ${message.string()}", color = JBTheme.textColors.infoInput) } } } ) { val fields = reflection { val fields = mutableMapOf<FieldDescriptorProto, Any?>() for ((field, value) in message) { if (message.has(field.number)) { fields[field] = value } } fields } for ((field, value) in fields) { FieldView(selectedItem, reflection, field, value) } } } }
1
null
4
98
3ad28dc886f1cfb6eee0a7c88536781d1ec8d7a9
13,171
Mediator
Apache License 2.0
felles/src/main/kotlin/no/nav/familie/kontrakter/felles/klage/FagsystemVedtak.kt
navikt
206,793,193
false
null
package no.nav.tilleggsstonader.kontrakter.klage import java.time.LocalDateTime data class FagsystemVedtak( val eksternBehandlingId: String, val behandlingstype: String, val resultat: String, val vedtakstidspunkt: LocalDateTime, val fagsystemType: FagsystemType, val regelverk: Regelverk?, ) enum class FagsystemType { ORDNIÆR, // brukes for behandlinger fra ef-sak/ba-sak TILBAKEKREVING, SANKSJON_1_MND, UTESTENGELSE, }
1
Kotlin
0
2
7f218f3c15be62cd438c690c6d4a670afe73fd65
464
familie-kontrakter
MIT License
src/zh/manhuagui/src/eu/kanade/tachiyomi/extension/zh/manhuagui/Comic.kt
komikku-app
720,497,299
false
null
package eu.kanade.tachiyomi.extension.zh.manhuagui import kotlinx.serialization.Serializable @Serializable data class Comic( val bid: Int? = 0, val block_cc: String? = "", val bname: String? = "", val bpic: String? = "", val cid: Int? = 0, val cname: String? = "", val files: List<String?>? = listOf(), val finished: Boolean? = false, val len: Int? = 0, val nextId: Int? = 0, val path: String? = "", val prevId: Int? = 0, val sl: Sl? = Sl(), val status: Int? = 0 )
9
null
99
97
7fc1d11ee314376fe0daa87755a7590a03bc11c0
523
komikku-extensions
Apache License 2.0
save-cloud-common/src/jvmMain/kotlin/com/saveourtool/save/entities/OriginalLogin.kt
saveourtool
300,279,336
false
null
package com.saveourtool.save.entities import com.saveourtool.save.spring.entity.BaseEntity import com.fasterxml.jackson.annotation.JsonBackReference import javax.persistence.Entity import javax.persistence.JoinColumn import javax.persistence.ManyToOne import javax.persistence.Table /** * @property name * @property user * @property source */ @Entity @Table(schema = "save_cloud", name = "original_login") class OriginalLogin( var name: String, @ManyToOne @JoinColumn(name = "user_id") @JsonBackReference var user: User, var source: String, ) : BaseEntity()
201
null
3
38
e101105f8e449253d5fbe81ece2668654d08639f
590
save-cloud
MIT License
app/src/main/java/com/miguelangelboti/stocks/entities/Stock.kt
miguelangelboti
274,739,267
false
null
package com.miguelangelboti.stocks.entities import com.miguelangelboti.stocks.utils.extensions.sumByFloat data class Stock( val id: Int = 0, val symbol: String, val name: String, val region: String, val marketOpen: String, val marketClose: String, val timeZone: String, val currency: String, val price: Float, val priceOpen: Float, val priceDate: String, val icon: String, val orders: List<Order> = emptyList() ) fun Stock.getProfitability(): Float { return orders.sumByFloat { it.getProfitability(price) } }
0
Kotlin
0
0
42fe19b191ac48e7a55ffda78caee6d52f32f27f
568
stocks
Apache License 2.0
idea/testData/copyPaste/imports/Extension.expected.kt
JakeWharton
99,388,807
true
null
package to import a.f import a.g import a.p fun foo() { 3.f() 2.p 3.g = 5 }
0
Kotlin
28
83
4383335168338df9bbbe2a63cb213a68d0858104
89
kotlin
Apache License 2.0
core/src/main/kotlin/midgard/World.kt
mfursov
131,506,842
false
null
package midgard class World( /** All active places in the world. */ val rooms: MutableMap<RoomId, Room>, /** Online characters map. */ val characters: MutableMap<CharacterId, Character>, /** Offline characters map. */ val offlineCharacters: MutableMap<CharacterId, Character>, /** Removed characters. They live here for some period of time. */ val removedCharacters: MutableMap<CharacterId, Character>, /** All objects by ID */ val objects: MutableMap<ObjId, Obj>, /** List of all pending events. */ val events: MutableList<Event>, /** List of all pending actions. */ val actions: MutableList<Action>, val random: Random, val eventIdGenerator: IdGenerator<EventId>, val actionIdGenerator: IdGenerator<ActionId>, val characterIdGenerator: IdGenerator<CharacterId>, val objectIdGenerator: IdGenerator<ObjId>, var tick: Long )
0
Kotlin
0
0
c8daa04809f40a1c0bb42de54ad7817dab7c62b4
1,000
midgard
Apache License 2.0
dynamic-shortcuts/complete/app/src/main/java/com/example/android/architecture/blueprints/todoapp/tasks/TasksFilterType.kt
android
577,929,339
false
null
/* * Copyright (C) 2020 Google LLC * * 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.example.android.architecture.blueprints.todoapp.tasks /** * Const values are coming from Assistants intent extras */ const val COMPLETED_TASK_VALUE = "completed_tasks" const val ACTIVE_TASK_VALUE = "active_tasks" const val ALL_TASK_VALUE = "all_tasks" /** * Used with the filter spinner in the tasks list. * @param value Id injected with the corresponding Android resource from res folder. */ enum class TasksFilterType(val value: String) { /** * Filters only the active (not completed yet) tasks. */ ACTIVE_TASKS(ACTIVE_TASK_VALUE), /** * Filters only the completed tasks. */ COMPLETED_TASKS(COMPLETED_TASK_VALUE), /** * Do not filter tasks. */ ALL_TASKS(ALL_TASK_VALUE); companion object { /** * @param type of task used to filter tasks from the model view and displayed by the * task list. * @return a TasksFilterType.Type that matches the given name */ fun find(type: String?): TasksFilterType { return values().find { it.value.equals(other = type, ignoreCase = true) } ?: ALL_TASKS } } }
5
null
33
54
fea0f48a6d7f1c43d47c3ad14bfd11ace4b5629c
1,748
app-actions-samples
Apache License 2.0
libraries/tools/kotlin-gradle-plugin/src/common/kotlin/org/jetbrains/kotlin/gradle/plugin/mpp/pm20/GradleKpmModule.kt
JetBrains
3,432,266
false
null
/* * Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.gradle.plugin.mpp.pm20 import groovy.lang.Closure import org.gradle.api.ExtensiblePolymorphicDomainObjectContainer import org.gradle.api.Named import org.gradle.api.NamedDomainObjectSet import org.gradle.api.Project import org.jetbrains.kotlin.gradle.plugin.HasKotlinDependencies import org.jetbrains.kotlin.gradle.plugin.KotlinDependencyHandler import org.jetbrains.kotlin.project.model.KotlinModule import org.jetbrains.kotlin.project.model.KpmCompilerPlugin interface KotlinGradleModule : KotlinModule, Named, HasKotlinDependencies { val project: Project val moduleClassifier: String? override val fragments: ExtensiblePolymorphicDomainObjectContainer<KotlinGradleFragment> // TODO DSL & build script model: find a way to create a flexible typed view on fragments? override val variants: NamedDomainObjectSet<KotlinGradleVariant> override val plugins: Set<KpmCompilerPlugin> val isPublic: Boolean fun ifMadePublic(action: () -> Unit) fun makePublic() companion object { const val MAIN_MODULE_NAME = "main" const val TEST_MODULE_NAME = "test" } override fun getName(): String = when (val classifier = moduleClassifier) { null -> MAIN_MODULE_NAME else -> classifier } // DSL val common: KotlinGradleFragment get() = fragments.getByName(KotlinGradleFragment.COMMON_FRAGMENT_NAME) fun common(configure: KotlinGradleFragment.() -> Unit) = common.configure() override fun dependencies(configure: KotlinDependencyHandler.() -> Unit) = common.dependencies(configure) override fun dependencies(configureClosure: Closure<Any?>) = common.dependencies(configureClosure) override val apiConfigurationName: String get() = common.apiConfigurationName override val implementationConfigurationName: String get() = common.implementationConfigurationName override val compileOnlyConfigurationName: String get() = common.compileOnlyConfigurationName override val runtimeOnlyConfigurationName: String get() = common.runtimeOnlyConfigurationName }
155
null
5608
45,423
2db8f31966862388df4eba2702b2f92487e1d401
2,371
kotlin
Apache License 2.0
app/src/main/java/org/sil/storyproducer/controller/MultiRecordFrag.kt
sillsdev
93,890,166
false
null
package org.sil.storyproducer.controller import android.app.Activity import android.app.AlertDialog import android.content.Intent import android.os.Bundle import android.os.Environment import android.provider.MediaStore import androidx.core.content.FileProvider import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.EditText import android.widget.ImageView import android.widget.Toast import com.google.firebase.crashlytics.FirebaseCrashlytics import org.sil.storyproducer.BuildConfig import org.sil.storyproducer.R import org.sil.storyproducer.model.PROJECT_DIR import org.sil.storyproducer.model.SLIDE_NUM import org.sil.storyproducer.model.SlideType import org.sil.storyproducer.model.Workspace import org.sil.storyproducer.tools.file.copyToWorkspacePath import org.sil.storyproducer.tools.toolbar.MultiRecordRecordingToolbar import org.sil.storyproducer.tools.toolbar.PlayBackRecordingToolbar import org.sil.storyproducer.tools.toolbar.RecordingToolbar import java.io.File /** * The fragment for the Draft view. This is where a user can draft out the story slide by slide */ abstract class MultiRecordFrag : SlidePhaseFrag(), PlayBackRecordingToolbar.ToolbarMediaListener { protected open var recordingToolbar: RecordingToolbar = MultiRecordRecordingToolbar() private var tempPicFile: File? = null override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { super.onCreateView(inflater, container, savedInstanceState) setToolbar() setupCameraAndEditButton() return rootView } /** * Setup camera button for updating background image * and edit button for renaming text and local credits */ fun setupCameraAndEditButton() { // display the image selection button, if on the title slide if(Workspace.activeStory.slides[slideNum].slideType in arrayOf(SlideType.FRONTCOVER,SlideType.LOCALSONG)) { val imageFab: ImageView = rootView!!.findViewById<View>(R.id.insert_image_view) as ImageView imageFab.visibility = View.VISIBLE imageFab.setOnClickListener { val chooser = Intent(Intent.ACTION_CHOOSER) chooser.putExtra(Intent.EXTRA_TITLE, "Select From:") val galleryIntent = Intent(Intent.ACTION_GET_CONTENT) galleryIntent.type = "image/*" chooser.putExtra(Intent.EXTRA_INTENT, galleryIntent) val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE) cameraIntent.resolveActivity(activity!!.packageManager).also { tempPicFile = File.createTempFile("temp", ".jpg", activity?.getExternalFilesDir(Environment.DIRECTORY_PICTURES)) cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, FileProvider.getUriForFile(activity!!, "${BuildConfig.APPLICATION_ID}.fileprovider", tempPicFile!!)) } chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, arrayOf(cameraIntent)) startActivityForResult(chooser, ACTIVITY_SELECT_IMAGE) } } // display the image selection button, if on the title slide val slideType : SlideType = Workspace.activeStory.slides[slideNum].slideType if(slideType in arrayOf(SlideType.FRONTCOVER)) { //for these, use the edit text button instead of the text in the lower half. //In the phases that these are not there, do nothing. val editBox = rootView?.findViewById<View>(R.id.fragment_dramatization_edit_text) as EditText? editBox?.visibility = View.INVISIBLE val editFab = rootView!!.findViewById<View>(R.id.edit_text_view) as ImageView? editFab?.visibility = View.VISIBLE editFab?.setOnClickListener { val editText = EditText(context) editText.id = R.id.edit_text_input // Programmatically set layout properties for edit text field val params = ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT) // Apply layout properties editText.layoutParams = params editText.minLines = 5 editText.text.insert(0, Workspace.activeSlide!!.translatedContent) val dialog = AlertDialog.Builder(context) .setTitle(getString(R.string.enter_text)) .setView(editText) .setNegativeButton(getString(R.string.cancel), null) .setPositiveButton(getString(R.string.save)) { _, _ -> Workspace.activeSlide!!.translatedContent = editText.text.toString() setPic(rootView!!.findViewById(R.id.fragment_image_view) as ImageView) }.create() dialog.show() } } } /** * Change the picture behind the screen. */ override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { try { if (resultCode == Activity.RESULT_OK && requestCode == ACTIVITY_SELECT_IMAGE) { //copy image into workspace var uri = data?.data if (uri == null) uri = FileProvider.getUriForFile(context!!, "${BuildConfig.APPLICATION_ID}.fileprovider", tempPicFile!!) //it was a camera intent Workspace.activeStory.slides[slideNum].imageFile = "$PROJECT_DIR/${slideNum}_Local.png" copyToWorkspacePath(context!!, uri!!, "${Workspace.activeStory.title}/${Workspace.activeStory.slides[slideNum].imageFile}") tempPicFile?.delete() setPic(rootView!!.findViewById(R.id.fragment_image_view) as ImageView) } }catch (e:Exception){ Toast.makeText(context,"Error",Toast.LENGTH_SHORT).show() FirebaseCrashlytics.getInstance().recordException(e) } } /** * This function serves to handle page changes and stops the audio streams from * continuing. * * @param isVisibleToUser whether fragment is currently visible to user */ override fun setUserVisibleHint(isVisibleToUser: Boolean) { super.setUserVisibleHint(isVisibleToUser) // Make sure that we are currently visible if (this.isVisible) { // If we are becoming invisible, then... if (!isVisibleToUser) { recordingToolbar.stopToolbarMedia() } } } protected open fun setToolbar() { val bundle = Bundle() bundle.putInt(SLIDE_NUM, slideNum) recordingToolbar.arguments = bundle childFragmentManager.beginTransaction().replace(R.id.toolbar_for_recording_toolbar, recordingToolbar).commit() recordingToolbar.keepToolbarVisible() } override fun onStartedToolbarMedia() { super.onStartedToolbarMedia() stopSlidePlayBack() } override fun onStartedSlidePlayBack() { super.onStartedSlidePlayBack() recordingToolbar.stopToolbarMedia() } companion object { private const val ACTIVITY_SELECT_IMAGE = 53 } }
95
null
9
3
98d4ef056f74c0b6e6667220a84c7c9304f5a739
7,430
StoryProducer
MIT License
src/main/kotlin/sapala/s2sauthservice/api/entity/PublicKey.kt
MateuszSapala
762,630,819
false
{"Kotlin": 13742}
package sapala.s2sauthservice.api.entity data class PublicKey(val type: String, val publicKey: String)
0
Kotlin
0
0
89645f9efd19071cc40f3ba146f10ead064d74e6
104
s2s-auth-service-api
Apache License 2.0
tabler/src/commonMain/kotlin/com/woowla/compose/icon/collections/tabler/tabler/outline/ChargingPile.kt
walter-juan
868,046,028
false
{"Kotlin": 34345428}
package com.woowla.compose.icon.collections.tabler.tabler.outline import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.StrokeCap.Companion.Round import androidx.compose.ui.graphics.StrokeJoin 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 com.woowla.compose.icon.collections.tabler.tabler.OutlineGroup public val OutlineGroup.ChargingPile: ImageVector get() { if (_chargingPile != null) { return _chargingPile!! } _chargingPile = Builder(name = "ChargingPile", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(18.0f, 7.0f) lineToRelative(-1.0f, 1.0f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(14.0f, 11.0f) horizontalLineToRelative(1.0f) arcToRelative(2.0f, 2.0f, 0.0f, false, true, 2.0f, 2.0f) verticalLineToRelative(3.0f) arcToRelative(1.5f, 1.5f, 0.0f, false, false, 3.0f, 0.0f) verticalLineToRelative(-7.0f) lineToRelative(-3.0f, -3.0f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(4.0f, 20.0f) verticalLineToRelative(-14.0f) arcToRelative(2.0f, 2.0f, 0.0f, false, true, 2.0f, -2.0f) horizontalLineToRelative(6.0f) arcToRelative(2.0f, 2.0f, 0.0f, false, true, 2.0f, 2.0f) verticalLineToRelative(14.0f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(9.0f, 11.5f) lineToRelative(-1.5f, 2.5f) horizontalLineToRelative(3.0f) lineToRelative(-1.5f, 2.5f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(3.0f, 20.0f) lineToRelative(12.0f, 0.0f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(4.0f, 8.0f) lineToRelative(10.0f, 0.0f) } } .build() return _chargingPile!! } private var _chargingPile: ImageVector? = null
0
Kotlin
0
3
eca6c73337093fbbfbb88546a88d4546482cfffc
3,976
compose-icon-collections
MIT License
src/main/kotlin/dev/shtanko/patterns/structural/proxy/WizardTowerProxy.kt
ashtanko
203,993,092
false
null
/* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.patterns.structural.proxy import org.slf4j.LoggerFactory class WizardTowerProxy(private val tower: WizardTower) : WizardTower { companion object { private val LOGGER = LoggerFactory.getLogger(WizardTowerProxy::class.java) private const val NUM_WIZARDS_ALLOWED = 3 } private var numWizards: Int = 0 override fun enter(wizard: Wizard) { if (numWizards < NUM_WIZARDS_ALLOWED) { tower.enter(wizard) numWizards++ } else { LOGGER.info("{} is not allowed to enter!", wizard) } } }
4
null
0
19
5bfa4b0dd30d515117d112b5d061e9235e444d13
1,187
kotlab
Apache License 2.0
alice-ktx/src/main/kotlin/com/github/alice/ktx/models/request/Session.kt
danbeldev
833,612,985
false
{"Kotlin": 68779}
package com.github.alice.ktx.models.request import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class Session( @SerialName("message_id") val messageId: Int, @SerialName("session_id") val sessionId: String, @SerialName("skill_id") val skillId: String, @SerialName("user_id") val userId: String, val user: User? = null, val application: Application, val new: Boolean )
0
Kotlin
0
3
2e2cb34b3bc4de208917e007d1bea2c827fcfbf4
462
alice-ktx
MIT License
compose-annotation/src/androidMain/kotlin/app/meetacy/vm/compose/Immutable.kt
meetacy
685,180,414
false
{"Kotlin": 23707}
package app.meetacy.vm.compose import androidx.compose.runtime.StableMarker @androidx.compose.runtime.Immutable @StableMarker public actual annotation class Immutable
0
Kotlin
0
6
a0eb75501368a48b269c74cd3bd77391ecca1aff
168
vm
Apache License 2.0
compiler/testData/codegen/box/initializers/files/globalNotInitedAfterAccessingClassInternals.kt
JetBrains
3,432,266
false
null
/* * Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ // FILE: lib.kt var z = false // FILE: lib2.kt import kotlin.test.* val x = foo() private fun foo(): Int { z = true return 42 } class C { fun bar() = 117 } // FILE: main.kt import kotlin.test.* fun main() { C().bar() assertFalse(z) }
181
null
5771
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
470
kotlin
Apache License 2.0
src/test/kotlin/com/cultureshock/madeleine/rest/controller/UserControllerTest.kt
DDD-Community
401,593,410
false
null
package com.cultureshock.madeleine.rest.controller import com.cultureshock.madeleine.MadeleineApplication import com.cultureshock.madeleine.domain.user.UserRepository import com.cultureshock.madeleine.service.user.KakaoAuthService import com.cultureshock.madeleine.service.user.UserService import com.ninjasquad.springmockk.MockkBean import io.mockk.every import org.junit.jupiter.api.Test import org.slf4j.Logger import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.context.SpringBootTest import org.springframework.boot.test.mock.mockito.MockBean import org.springframework.http.ResponseEntity.ok import org.springframework.test.web.servlet.get import org.springframework.test.web.servlet.result.MockMvcResultMatchers import org.springframework.web.context.WebApplicationContext import support.createUser import support.createUserResponse private const val VALID_TOKEN = "SOME_VALID_TOKEN" private const val RANDOM_PASSWORD = "<PASSWORD>" private const val PASSWORD = "<PASSWORD>" private const val INVALID_PASSWORD = "<PASSWORD>" @SpringBootTest(classes = [MadeleineApplication::class], webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) internal class UserControllerTest( ): RestControllerTest() { @MockkBean private lateinit var kakaoAuthService: KakaoAuthService @MockkBean private lateinit var userService: UserService @MockkBean private lateinit var userRepository: UserRepository @Autowired private val wac: WebApplicationContext? = null companion object { private val log: Logger = LoggerFactory.getLogger(UserController::class.java) } private val userResponse = createUserResponse() @Test fun `기존 사용자 정보와 일치하는 사용자 검증 요청에 응답으로 Authorized를 반환한다`() { every { userService.getUserInfo(any()) } returns userResponse every { userRepository.getById(any()) } returns createUser() mockMvc.get("/api/v1/user") { header("user_id",1) }.andExpect { status { ok() } content { MockMvcResultMatchers.jsonPath("code").value("401") MockMvcResultMatchers.jsonPath("message").value("권한이 없는 사용자입니다.") } } } @Test fun `기존 사용자 정보와 일치하지 않는 사용자 검증 요청에 응답으로 unAuthorized를 반환한다`() { every { userService.getUserInfo(any()) } returns userResponse mockMvc.get("/api/v1/user") { header("user_id",2) }.andExpect { status { ok() } content { MockMvcResultMatchers.jsonPath("code").value("401") MockMvcResultMatchers.jsonPath("message").value("권한이 없는 사용자입니다.") } } } }
2
Kotlin
1
4
fc07b03adafd42f7c9c11c8e135c197f24182df8
2,752
CultureShock-Server
MIT License
src/test/kotlin/com/example/marketo/MarketoApplicationTests.kt
ani404
733,952,883
false
{"Kotlin": 4510}
package com.example.marketo import org.junit.jupiter.api.Test import org.springframework.boot.test.context.SpringBootTest @SpringBootTest class MarketoApplicationTests { @Test fun contextLoads() { } }
0
Kotlin
0
1
d3e6cacc904353507753bb35194df53fd6e47053
208
marketo
Apache License 2.0
compiler/frontend/src/org/jetbrains/kotlin/cfg/ControlFlowInfo.kt
JakeWharton
99,388,807
false
null
/* * Copyright 2010-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.cfg import javaslang.Tuple2 import org.jetbrains.kotlin.descriptors.VariableDescriptor typealias ImmutableMap<K, V> = javaslang.collection.Map<K, V> typealias ImmutableHashMap<K, V> = javaslang.collection.HashMap<K, V> abstract class ControlFlowInfo<S : ControlFlowInfo<S, D>, D : Any> internal constructor( protected val map: ImmutableMap<VariableDescriptor, D> = ImmutableHashMap.empty() ) : ImmutableMap<VariableDescriptor, D> by map, ReadOnlyControlFlowInfo<D> { abstract protected fun copy(newMap: ImmutableMap<VariableDescriptor, D>): S override fun put(key: VariableDescriptor, value: D): S = put(key, value, this[key].getOrElse(null as D?)) /** * This overload exists just for sake of optimizations: in some cases we've just retrieved the old value, * so we don't need to scan through the peristent hashmap again */ fun put(key: VariableDescriptor, value: D, oldValue: D?): S { @Suppress("UNCHECKED_CAST") // Avoid a copy instance creation if new value is the same if (value == oldValue) return this as S return copy(map.put(key, value)) } override fun getOrNull(variableDescriptor: VariableDescriptor): D? = this[variableDescriptor].getOrElse(null as D?) override fun asMap() = this fun retainAll(predicate: (VariableDescriptor) -> Boolean): S = copy(map.removeAll(map.keySet().filterNot(predicate))) override fun equals(other: Any?) = map == (other as? ControlFlowInfo<*, *>)?.map override fun hashCode() = map.hashCode() override fun toString() = map.toString() } operator fun <T> Tuple2<T, *>.component1(): T = _1() operator fun <T> Tuple2<*, T>.component2(): T = _2() interface ReadOnlyControlFlowInfo<D : Any> { fun getOrNull(variableDescriptor: VariableDescriptor): D? // Only used in tests fun asMap(): ImmutableMap<VariableDescriptor, D> } interface ReadOnlyInitControlFlowInfo : ReadOnlyControlFlowInfo<VariableControlFlowState> { fun checkDefiniteInitializationInWhen(merge: ReadOnlyInitControlFlowInfo): Boolean } typealias ReadOnlyUseControlFlowInfo = ReadOnlyControlFlowInfo<VariableUseState> class InitControlFlowInfo(map: ImmutableMap<VariableDescriptor, VariableControlFlowState> = ImmutableHashMap.empty()) : ControlFlowInfo<InitControlFlowInfo, VariableControlFlowState>(map), ReadOnlyInitControlFlowInfo { override fun copy(newMap: ImmutableMap<VariableDescriptor, VariableControlFlowState>) = InitControlFlowInfo(newMap) // this = output of EXHAUSTIVE_WHEN_ELSE instruction // merge = input of MergeInstruction // returns true if definite initialization in when happens here override fun checkDefiniteInitializationInWhen(merge: ReadOnlyInitControlFlowInfo): Boolean { for ((key, value) in iterator()) { if (value.initState == InitState.INITIALIZED_EXHAUSTIVELY && merge.getOrNull(key)?.initState == InitState.INITIALIZED) { return true } } return false } } class UseControlFlowInfo(map: ImmutableMap<VariableDescriptor, VariableUseState> = ImmutableHashMap.empty()) : ControlFlowInfo<UseControlFlowInfo, VariableUseState>(map), ReadOnlyUseControlFlowInfo { override fun copy(newMap: ImmutableMap<VariableDescriptor, VariableUseState>) = UseControlFlowInfo(newMap) } enum class InitState(private val s: String) { // Definitely initialized INITIALIZED("I"), // Fake initializer in else branch of "exhaustive when without else", see MagicKind.EXHAUSTIVE_WHEN_ELSE INITIALIZED_EXHAUSTIVELY("IE"), // Initialized in some branches, not initialized in other branches UNKNOWN("I?"), // Definitely not initialized NOT_INITIALIZED(""); fun merge(other: InitState): InitState { // X merge X = X // X merge IE = IE merge X = X // else X merge Y = I? if (this == other || other == INITIALIZED_EXHAUSTIVELY) return this if (this == INITIALIZED_EXHAUSTIVELY) return other return UNKNOWN } override fun toString() = s } class VariableControlFlowState private constructor(val initState: InitState, val isDeclared: Boolean) { fun definitelyInitialized(): Boolean = initState == InitState.INITIALIZED fun mayBeInitialized(): Boolean = initState != InitState.NOT_INITIALIZED override fun toString(): String { if (initState == InitState.NOT_INITIALIZED && !isDeclared) return "-" return "$initState${if (isDeclared) "D" else ""}" } companion object { private val VS_IT = VariableControlFlowState(InitState.INITIALIZED, true) private val VS_IF = VariableControlFlowState(InitState.INITIALIZED, false) private val VS_ET = VariableControlFlowState(InitState.INITIALIZED_EXHAUSTIVELY, true) private val VS_EF = VariableControlFlowState(InitState.INITIALIZED_EXHAUSTIVELY, false) private val VS_UT = VariableControlFlowState(InitState.UNKNOWN, true) private val VS_UF = VariableControlFlowState(InitState.UNKNOWN, false) private val VS_NT = VariableControlFlowState(InitState.NOT_INITIALIZED, true) private val VS_NF = VariableControlFlowState(InitState.NOT_INITIALIZED, false) fun create(initState: InitState, isDeclared: Boolean): VariableControlFlowState = when (initState) { InitState.INITIALIZED -> if (isDeclared) VS_IT else VS_IF InitState.INITIALIZED_EXHAUSTIVELY -> if (isDeclared) VS_ET else VS_EF InitState.UNKNOWN -> if (isDeclared) VS_UT else VS_UF InitState.NOT_INITIALIZED -> if (isDeclared) VS_NT else VS_NF } fun createInitializedExhaustively(isDeclared: Boolean): VariableControlFlowState = create(InitState.INITIALIZED_EXHAUSTIVELY, isDeclared) fun create(isInitialized: Boolean, isDeclared: Boolean = false): VariableControlFlowState = create(if (isInitialized) InitState.INITIALIZED else InitState.NOT_INITIALIZED, isDeclared) fun create(isDeclaredHere: Boolean, mergedEdgesData: VariableControlFlowState?): VariableControlFlowState = create(true, isDeclaredHere || mergedEdgesData != null && mergedEdgesData.isDeclared) } } enum class VariableUseState(private val priority: Int) { READ(3), WRITTEN_AFTER_READ(2), ONLY_WRITTEN_NEVER_READ(1), UNUSED(0); fun merge(variableUseState: VariableUseState?): VariableUseState { if (variableUseState == null || priority > variableUseState.priority) return this return variableUseState } companion object { @JvmStatic fun isUsed(variableUseState: VariableUseState?): Boolean = variableUseState != null && variableUseState != UNUSED } }
12
null
4
83
4383335168338df9bbbe2a63cb213a68d0858104
7,410
kotlin
Apache License 2.0
dragswipe/src/test/java/com/programmersbox/dragswipe/ExampleUnitTest.kt
jakepurple13
243,099,864
false
null
package com.programmersbox.dragswipe import org.junit.Assert.assertEquals import org.junit.Test /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) Direction.DOWN or Direction.UP or Direction.START } }
10
null
1
8
904eb4dc9d6ca3024df1096a4a8ccadaca566a4c
420
HelpfulTools
Apache License 2.0
platform/build-scripts/src/org/jetbrains/intellij/build/impl/productInfo/ProductInfoValidator.kt
ingokegel
72,937,917
false
null
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.intellij.build.impl.productInfo import com.fasterxml.jackson.databind.ObjectMapper import com.intellij.openapi.util.io.FileUtilRt import com.intellij.util.lang.ImmutableZipFile import com.networknt.schema.JsonSchemaFactory import com.networknt.schema.SpecVersion import kotlinx.serialization.decodeFromString import org.apache.commons.compress.archivers.tar.TarArchiveInputStream import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream import org.jetbrains.intellij.build.BuildContext import org.jetbrains.intellij.build.BuildMessages import org.jetbrains.intellij.build.CompilationContext import org.jetbrains.intellij.build.OsFamily import java.nio.file.Files import java.nio.file.Path /** * Checks that product-info.json file located in `archivePath` archive in `pathInArchive` subdirectory is correct */ internal fun checkInArchive(archiveFile: Path, pathInArchive: String, context: BuildContext) { val productJsonPath = joinPaths(pathInArchive, PRODUCT_INFO_FILE_NAME) val entryData = loadEntry(archiveFile, productJsonPath) ?: throw RuntimeException("Failed to validate product-info.json: cannot find \'$productJsonPath\' in $archiveFile") validateProductJson(jsonText = entryData.decodeToString(), relativePathToProductJson = "", installationDirectories = emptyList(), installationArchives = listOf(Pair(archiveFile, pathInArchive)), context = context) } /** * Checks that product-info.json file is correct. * * @param installationDirectories directories which will be included into product installation * @param installationArchives archives which will be unpacked and included into product installation (the first part specified path to archive, * the second part specifies path inside archive) */ internal fun validateProductJson(jsonText: String, relativePathToProductJson: String, installationDirectories: List<Path>, installationArchives: List<Pair<Path, String>>, context: CompilationContext) { val schemaPath = context.paths.communityHomeDir.communityRoot .resolve("platform/build-scripts/groovy/org/jetbrains/intellij/build/product-info.schema.json") val messages = context.messages verifyJsonBySchema(jsonText, schemaPath, messages) val productJson = jsonEncoder.decodeFromString<ProductInfoData>(jsonText) checkFileExists(path = productJson.svgIconPath, description = "svg icon", relativePathToProductJson = relativePathToProductJson, installationDirectories = installationDirectories, installationArchives = installationArchives) for ((os, launcherPath, javaExecutablePath, vmOptionsFilePath) in productJson.launch) { if (OsFamily.ALL.none { it.osName == os }) { messages.error("Incorrect os name \'$os\' in $relativePathToProductJson/product-info.json") } checkFileExists(launcherPath, "$os launcher", relativePathToProductJson, installationDirectories, installationArchives) checkFileExists(javaExecutablePath, "$os java executable", relativePathToProductJson, installationDirectories, installationArchives) checkFileExists(vmOptionsFilePath, "$os VM options file", relativePathToProductJson, installationDirectories, installationArchives) } } private fun verifyJsonBySchema(jsonData: String, jsonSchemaFile: Path, messages: BuildMessages) { val schema = JsonSchemaFactory.getInstance(SpecVersion.VersionFlag.V7).getSchema(Files.readString(jsonSchemaFile)) val errors = schema.validate(ObjectMapper().readTree(jsonData)) if (!errors.isEmpty()) { messages.error("Unable to validate JSON against $jsonSchemaFile:" + "\n${errors.joinToString(separator = "\n")}\njson file content:\n$jsonData") } } private fun checkFileExists(path: String?, description: String, relativePathToProductJson: String, installationDirectories: List<Path>, installationArchives: List<Pair<Path, String>>) { if (path == null) { return } val pathFromProductJson = relativePathToProductJson + path if (installationDirectories.none { Files.exists(it.resolve(pathFromProductJson)) } && installationArchives.none { archiveContainsEntry(it.first, joinPaths(it.second, pathFromProductJson)) }) { throw RuntimeException("Incorrect path to $description '$path' in $relativePathToProductJson/product-info.json: " + "the specified file doesn't exist in directories $installationDirectories " + "and archives ${installationArchives.map { "${it.first}/${it.second}" }}") } } private fun joinPaths(parent: String, child: String): String { return FileUtilRt.toCanonicalPath(/* path = */ "$parent/$child", /* separatorChar = */ '/', /* removeLastSlash = */ true) .dropWhile { it == '/' } } private fun archiveContainsEntry(archiveFile: Path, entryPath: String): Boolean { val fileName = archiveFile.fileName.toString() if (fileName.endsWith(".zip") || fileName.endsWith(".jar")) { ImmutableZipFile.load(archiveFile).use { return it.getResource(entryPath) != null } } else if (fileName.endsWith(".tar.gz")) { Files.newInputStream(archiveFile).use { val inputStream = TarArchiveInputStream(GzipCompressorInputStream(it)) val altEntryPath = "./$entryPath" while (true) { val entry = inputStream.nextEntry ?: break if (entry.name == entryPath || entry.name == altEntryPath) { return true } } } } return false } private fun loadEntry(archiveFile: Path, entryPath: String): ByteArray? { val fileName = archiveFile.fileName.toString() if (fileName.endsWith(".zip") || fileName.endsWith(".jar")) { ImmutableZipFile.load(archiveFile).use { return it.getResource(entryPath)?.data } } else if (fileName.endsWith(".tar.gz")) { TarArchiveInputStream(GzipCompressorInputStream(Files.newInputStream(archiveFile))).use { inputStream -> val altEntryPath = "./$entryPath" while (true) { val entry = inputStream.nextEntry ?: break if (entry.name == entryPath || entry.name == altEntryPath) { return inputStream.readAllBytes() } } } } return null }
233
null
4912
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
6,698
intellij-community
Apache License 2.0
app/src/main/java/com/app/tugaypamuk/movieapp/peresention/ui/BaseFragmentFactory.kt
fortysevennn
495,296,580
false
{"Kotlin": 21382}
package com.app.tugaypamuk.movieapp.peresention.ui import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentFactory import com.app.tugaypamuk.movieapp.peresention.ui.home.HomeAdapter import com.app.tugaypamuk.movieapp.peresention.ui.home.HomeFragment import javax.inject.Inject /* class BaseFragmentFactory @Inject constructor( private val homeAdapter: HomeAdapter ) : FragmentFactory(){ override fun instantiate(classLoader: ClassLoader, className: String): Fragment { return when(className){ //HomeFragment::class.java.name -> HomeFragment(homeAdapter) else -> super.instantiate(classLoader, className) } } } */
0
Kotlin
0
0
16cb8b115d55ed8625b374eabc98798ddb04e15a
687
MovieApp
The Unlicense
mobile_app1/module72/src/main/java/module72packageKt0/Foo145.kt
uber-common
294,831,672
false
null
package module692packageKt0; annotation class Foo145Fancy @Foo145Fancy class Foo145 { fun foo0(){ module692packageKt0.Foo144().foo4() } fun foo1(){ foo0() } fun foo2(){ foo1() } fun foo3(){ foo2() } fun foo4(){ foo3() } }
6
null
6
72
9cc83148c1ca37d0f2b2fcb08c71ac04b3749e5e
267
android-build-eval
Apache License 2.0
src/main/kotlin/no/nav/arbeidsplassen/importapi/adoutbox/AdOutboxRepository.kt
navikt
236,483,368
false
{"Kotlin": 198918, "Shell": 3062, "Dockerfile": 157}
package no.nav.arbeidsplassen.importapi.adoutbox import io.micronaut.data.jdbc.annotation.JdbcRepository import io.micronaut.data.model.query.builder.sql.Dialect import io.micronaut.data.repository.CrudRepository import no.nav.arbeidsplassen.importapi.provider.toTimeStamp import java.sql.Connection import java.sql.ResultSet import java.time.LocalDateTime import javax.transaction.Transactional @JdbcRepository(dialect = Dialect.POSTGRES) abstract class AdOutboxRepository(val connection: Connection) : CrudRepository<AdOutbox, Long> { fun ResultSet.toAdOutbox() = AdOutbox( id = this.getLong("id"), uuid = this.getString("uuid"), payload = this.getString("payload"), opprettetDato = this.getObject("opprettet_dato", LocalDateTime::class.java), harFeilet = this.getBoolean("har_feilet"), antallForsøk = this.getInt("antall_forsok"), sisteForsøkDato = this.getObject("siste_forsok_dato", LocalDateTime::class.java), prosessertDato = this.getObject("prosessert_dato", LocalDateTime::class.java) ) @Transactional fun lagre(entity: AdOutbox): Int { val sql = """ INSERT INTO ad_outbox (uuid, payload, opprettet_dato, har_feilet, antall_forsok, siste_forsok_dato, prosessert_dato) VALUES (?, ?, ?, ?, ?, ?, ?) """.trimIndent() return connection.prepareStatement(sql).apply { setString(1, entity.uuid) setString(2, entity.payload) setTimestamp(3, entity.opprettetDato.toTimeStamp()) setBoolean(4, entity.harFeilet) setInt(5, entity.antallForsøk) setTimestamp(6, entity.sisteForsøkDato?.toTimeStamp()) setTimestamp(7, entity.prosessertDato?.toTimeStamp()) }.executeUpdate() } @Transactional fun hentUprosesserteMeldinger(batchSize: Int = 1000, outboxDelay: Long = 30): List<AdOutbox> { val sql = """ SELECT id, uuid, payload, opprettet_dato, har_feilet, antall_forsok, siste_forsok_dato, prosessert_dato FROM ad_outbox WHERE prosessert_dato is null AND opprettet_dato <= ? ORDER BY opprettet_dato ASC LIMIT ? """.trimIndent() val resultSet = connection .prepareStatement(sql) .apply { setTimestamp(1, LocalDateTime.now().minusSeconds(outboxDelay).toTimeStamp()) setInt(2, batchSize) }.executeQuery() return resultSet.use { generateSequence { if (it.next()) it.toAdOutbox() else null }.toList() } } @Transactional fun lagreFlere(entities: Iterable<AdOutbox>) = entities.sumOf { lagre(it) } @Transactional fun markerSomProsessert(adOutbox: AdOutbox): Boolean { val sql = """UPDATE ad_outbox SET prosessert_dato = ? WHERE id = ?""" return connection.prepareStatement(sql).apply { setTimestamp(1, adOutbox.prosessertDato?.toTimeStamp()) setLong(2, adOutbox.id!!) }.executeUpdate() > 0 } @Transactional fun markerSomFeilet(adOutbox: AdOutbox): Boolean { val sql = """UPDATE ad_outbox SET har_feilet = ?, antall_forsok = ?, siste_forsok_dato = ? WHERE id = ?""" return connection.prepareStatement(sql).apply { setBoolean(1, adOutbox.harFeilet) setInt(2, adOutbox.antallForsøk) setTimestamp(3, adOutbox.sisteForsøkDato?.toTimeStamp()) setLong(4, adOutbox.id!!) }.executeUpdate() > 0 } }
0
Kotlin
0
4
77e6a9673a51631bc60c60959f9c4223f4d76e5a
3,535
pam-import-api
MIT License
android/libs/mvi/src/main/kotlin/io/chefbook/libs/mvi/MviState.kt
mephistolie
379,951,682
false
{"Kotlin": 1334117, "Ruby": 16819, "Swift": 352}
package io.chefbook.libs.mvi interface MviState
0
Kotlin
0
12
ddaf82ee3142f30aee8920d226a8f07873cdcffe
49
chefbook-mobile
Apache License 2.0
src/main/kotlin/pwr/aiir/Application.kt
tomasouza
498,934,453
false
null
package com.giacom import io.micronaut.runtime.Micronaut.* import io.swagger.v3.oas.annotations.* import io.swagger.v3.oas.annotations.info.* @OpenAPIDefinition( info = Info( title = "demo-testcontainers", version = "0.0" ) ) object Api { } fun main(args: Array<String>) { build() .args(*args) .packages("com.giacom") .start() }
1
Kotlin
0
0
9911007bc866d66f7fe011bf9cf511546ea5fcfb
374
web
MIT License
src/commonMain/kotlin/org/daiv/tick/FileDataCreator.kt
henry1986
625,890,395
false
null
package org.daiv.tick interface Intervalable { val interval: Long } interface FileDataFactory : Intervalable { fun <R : DataCollection> fileData(time: Long, fileData: (Long, Long) -> R): R { val fileStart = time / interval * interval val fileEnd = fileStart + interval return fileData(fileStart, fileEnd) } fun startTime(time: Long) = time / interval * interval fun stopTime(time: Long): Long { val fileStart = startTime(time) return fileStart + interval - 1L } fun fileName(start: Long, end: Long) = "$start-$end" } interface FileDataCreator<T : DataCollection> : FileDataFactory { fun build(start: Long, end: Long, isCurrent:Boolean, fileName: String = fileName(start, end)): T fun defaultFileData(time: Long): T = fileData(time) { start, end -> build(start, end, false) } fun currentFileData(time: Long): T = fileData(time) { start, end -> build(start, end, true) } }
0
Kotlin
0
0
2d78ac69fe3ddc6cc4774d05baca2136cffe2940
960
timebased-datacompress
Apache License 2.0
modules/domain/src/main/java/eu/automateeverything/domain/automation/blocks/ChangeStateBlockFactory.kt
tomaszbabiuk
488,678,209
false
{"Kotlin": 498866, "Vue": 138384, "JavaScript": 51377, "HTML": 795}
/* * Copyright (c) 2019-2022 Tomasz Babiuk * * 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 eu.automateeverything.domain.automation.blocks import eu.automateeverything.data.automation.State import eu.automateeverything.data.blocks.RawJson import eu.automateeverything.domain.automation.* import eu.automateeverything.domain.configurable.StateDeviceConfigurable class ChangeStateBlockFactory(private val state: State) : StatementBlockFactory { override val category = CommonBlockCategories.ThisObject override val type: String = "change_state_${state.id}" override fun buildBlock(): RawJson { return RawJson { """ { "type": "$type", "colour": ${category.color}, "tooltip": null, "helpUrl": null, "message0": "${state.action!!.getValue(it)}", "previousStatement": null, "nextStatement": null } """ .trimIndent() } } override fun transform( block: Block, next: StatementNode?, context: AutomationContext, transformer: BlocklyTransformer, ): StatementNode { if (context.thisDevice is StateDeviceConfigurable) { val evaluator = context.automationUnitsCache[context.thisInstance.id] if (evaluator is StateDeviceAutomationUnitBase) { return ChangeStateAutomationNode(state.id, evaluator, next) } else { throw MalformedBlockException(block.type, "should point only to a state device") } } throw MalformedBlockException( block.type, "it's impossible to connect this block with correct ${StateDeviceConfigurable::class.java}" ) } }
0
Kotlin
1
0
f1163bb95b9497c70ed48db0bcaf4e7050218e7a
2,354
automate-everything
Apache License 2.0
z2-service-kotlin-plugin/src/hu/simplexion/z2/service/kotlin/ir/util/IrBuilder.kt
spxbhuhb
667,868,480
false
null
package hu.simplexion.z2.service.kotlin.ir.util import hu.simplexion.z2.service.kotlin.ir.ServicePluginContext import hu.simplexion.z2.service.kotlin.ir.proto.ProtoEnum import org.jetbrains.kotlin.backend.common.ir.addDispatchReceiver import org.jetbrains.kotlin.backend.common.lower.DeclarationIrBuilder import org.jetbrains.kotlin.descriptors.DescriptorVisibilities import org.jetbrains.kotlin.descriptors.Modality import org.jetbrains.kotlin.ir.UNDEFINED_OFFSET import org.jetbrains.kotlin.ir.builders.declarations.* import org.jetbrains.kotlin.ir.builders.irBlockBody import org.jetbrains.kotlin.ir.builders.irGet import org.jetbrains.kotlin.ir.builders.irReturn import org.jetbrains.kotlin.ir.builders.irSetField import org.jetbrains.kotlin.ir.declarations.* import org.jetbrains.kotlin.ir.expressions.* import org.jetbrains.kotlin.ir.expressions.impl.* import org.jetbrains.kotlin.ir.symbols.* import org.jetbrains.kotlin.ir.types.IrType import org.jetbrains.kotlin.ir.types.getPrimitiveType import org.jetbrains.kotlin.ir.types.impl.IrSimpleTypeImpl import org.jetbrains.kotlin.ir.types.isBoolean import org.jetbrains.kotlin.ir.types.isSubtypeOfClass import org.jetbrains.kotlin.ir.util.SYNTHETIC_OFFSET import org.jetbrains.kotlin.ir.util.defaultType import org.jetbrains.kotlin.ir.util.getPrimitiveArrayElementType import org.jetbrains.kotlin.ir.util.parentAsClass import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.util.OperatorNameConventions interface IrBuilder { val pluginContext: ServicePluginContext val irContext get() = pluginContext.irContext val irFactory get() = irContext.irFactory val irBuiltIns get() = irContext.irBuiltIns // -------------------------------------------------------------------------------------------------------- // Properties // -------------------------------------------------------------------------------------------------------- fun IrClass.addIrProperty( inName: Name, inType: IrType, inIsVar: Boolean, inInitializer: IrExpression? = null, overridden: List<IrPropertySymbol>? = null ): IrProperty { val irClass = this val irField = irFactory.buildField { name = inName type = inType origin = IrDeclarationOrigin.PROPERTY_BACKING_FIELD visibility = DescriptorVisibilities.PRIVATE }.apply { parent = irClass initializer = inInitializer?.let { irFactory.createExpressionBody(it) } } val irProperty = irClass.addProperty { name = inName isVar = inIsVar }.apply { parent = irClass backingField = irField overridden?.let { overriddenSymbols = it } addDefaultGetter(irClass, irBuiltIns) } if (inIsVar) { irProperty.addDefaultSetter(irField) } return irProperty } fun IrProperty.addDefaultSetter(irField: IrField) { setter = irFactory.buildFun { origin = IrDeclarationOrigin.DEFAULT_PROPERTY_ACCESSOR name = Name.identifier("set-" + irField.name.identifier) visibility = DescriptorVisibilities.PUBLIC modality = Modality.FINAL returnType = irBuiltIns.unitType }.also { it.parent = parent it.correspondingPropertySymbol = symbol val receiver = it.addDispatchReceiver { type = parentAsClass.defaultType } val value = it.addValueParameter { name = Name.identifier("set-?") type = irField.type } it.body = DeclarationIrBuilder(irContext, this.symbol).irBlockBody { + irSetField( receiver = irGet(receiver), field = irField, value = irGet(value) ) } } } fun transformGetter(irClass : IrClass, getter: IrSimpleFunction, field: IrField) { getter.origin = IrDeclarationOrigin.DEFAULT_PROPERTY_ACCESSOR getter.isFakeOverride = false getter.addDispatchReceiver { type = irClass.defaultType } getter.body = DeclarationIrBuilder(irContext, getter.symbol).irBlockBody { + irReturn( IrGetFieldImpl( UNDEFINED_OFFSET, UNDEFINED_OFFSET, field.symbol, field.type, IrGetValueImpl( UNDEFINED_OFFSET, UNDEFINED_OFFSET, getter.dispatchReceiverParameter !!.type, getter.dispatchReceiverParameter !!.symbol ) ) ) } } fun IrProperty.irSetField(value: IrExpression, receiver: IrExpression): IrSetFieldImpl { return IrSetFieldImpl( SYNTHETIC_OFFSET, SYNTHETIC_OFFSET, backingField !!.symbol, receiver, value, irBuiltIns.unitType ) } fun irGetValue(irProperty: IrProperty, receiver: IrExpression?): IrCall = IrCallImpl( SYNTHETIC_OFFSET, SYNTHETIC_OFFSET, irProperty.backingField !!.type, irProperty.getter !!.symbol, 0, 0, origin = IrStatementOrigin.GET_PROPERTY ).apply { dispatchReceiver = receiver } fun irSetValue(irProperty: IrProperty, value: IrExpression, receiver: IrExpression?): IrCall = IrCallImpl( SYNTHETIC_OFFSET, SYNTHETIC_OFFSET, irProperty.backingField !!.type, irProperty.setter !!.symbol, 0, 1 ).apply { dispatchReceiver = receiver putValueArgument(0, value) } // -------------------------------------------------------------------------------------------------------- // IR Basics // -------------------------------------------------------------------------------------------------------- fun irConst(value: Long): IrConst<Long> = IrConstImpl( UNDEFINED_OFFSET, UNDEFINED_OFFSET, irContext.irBuiltIns.longType, IrConstKind.Long, value ) fun irConst(value: Int): IrConst<Int> = IrConstImpl( UNDEFINED_OFFSET, UNDEFINED_OFFSET, irContext.irBuiltIns.intType, IrConstKind.Int, value ) fun irConst(value: String): IrConst<String> = IrConstImpl( UNDEFINED_OFFSET, UNDEFINED_OFFSET, irContext.irBuiltIns.stringType, IrConstKind.String, value ) fun irConst(value: Boolean) = IrConstImpl( UNDEFINED_OFFSET, UNDEFINED_OFFSET, irContext.irBuiltIns.booleanType, IrConstKind.Boolean, value ) fun irNull() = IrConstImpl( UNDEFINED_OFFSET, UNDEFINED_OFFSET, irContext.irBuiltIns.anyNType, IrConstKind.Null, null ) fun irGet(type: IrType, symbol: IrValueSymbol, origin: IrStatementOrigin?): IrExpression { return IrGetValueImpl( UNDEFINED_OFFSET, UNDEFINED_OFFSET, type, symbol, origin ) } fun irGet(variable: IrValueDeclaration, origin: IrStatementOrigin? = null): IrExpression { return irGet(variable.type, variable.symbol, origin) } fun irGetObject(symbol: IrClassSymbol) = IrGetObjectValueImpl( SYNTHETIC_OFFSET, SYNTHETIC_OFFSET, IrSimpleTypeImpl(symbol, false, emptyList(), emptyList()), symbol ) fun irIf(condition: IrExpression, body: IrExpression): IrExpression { return IrIfThenElseImpl( UNDEFINED_OFFSET, UNDEFINED_OFFSET, irContext.irBuiltIns.unitType, origin = IrStatementOrigin.IF ).also { it.branches.add( IrBranchImpl(condition, body) ) } } fun irImplicitAs(toType: IrType, argument: IrExpression): IrTypeOperatorCallImpl { return IrTypeOperatorCallImpl( SYNTHETIC_OFFSET, SYNTHETIC_OFFSET, toType, IrTypeOperator.IMPLICIT_CAST, toType, argument ) } // -------------------------------------------------------------------------------------------------------- // Logic // -------------------------------------------------------------------------------------------------------- fun irAnd(lhs: IrExpression, rhs: IrExpression): IrCallImpl { return irCall( lhs.type.binaryOperator(OperatorNameConventions.AND, rhs.type), null, lhs, null, rhs ) } fun irOr(lhs: IrExpression, rhs: IrExpression): IrCallImpl { val int = irContext.irBuiltIns.intType return irCall( int.binaryOperator(OperatorNameConventions.OR, int), null, lhs, null, rhs ) } fun irEqual(lhs: IrExpression, rhs: IrExpression): IrExpression { return irCall( this.irContext.irBuiltIns.eqeqSymbol, null, null, null, lhs, rhs ) } fun irNot(value: IrExpression): IrExpression { return irCall( irContext.irBuiltIns.booleanNotSymbol, dispatchReceiver = value ) } fun irNotEqual(lhs: IrExpression, rhs: IrExpression): IrExpression { return irNot(irEqual(lhs, rhs)) } fun irOrOr(lhs: IrExpression, rhs: IrExpression): IrExpression { return IrWhenImpl( UNDEFINED_OFFSET, UNDEFINED_OFFSET, origin = IrStatementOrigin.OROR, type = irContext.irBuiltIns.booleanType, branches = listOf( IrBranchImpl( UNDEFINED_OFFSET, UNDEFINED_OFFSET, condition = lhs, result = irConst(true) ), IrElseBranchImpl( UNDEFINED_OFFSET, UNDEFINED_OFFSET, condition = irConst(true), result = rhs ) ) ) } // -------------------------------------------------------------------------------------------------------- // Operators // -------------------------------------------------------------------------------------------------------- fun IrType.binaryOperator(name: Name, paramType: IrType): IrFunctionSymbol = irContext.symbols.getBinaryOperator(name, this, paramType) // -------------------------------------------------------------------------------------------------------- // Calls // -------------------------------------------------------------------------------------------------------- fun irCall( symbol: IrFunctionSymbol, origin: IrStatementOrigin? = null, dispatchReceiver: IrExpression? = null, extensionReceiver: IrExpression? = null, vararg args: IrExpression ): IrCallImpl { return IrCallImpl( UNDEFINED_OFFSET, UNDEFINED_OFFSET, symbol.owner.returnType, symbol as IrSimpleFunctionSymbol, symbol.owner.typeParameters.size, symbol.owner.valueParameters.size, origin ).also { if (dispatchReceiver != null) it.dispatchReceiver = dispatchReceiver if (extensionReceiver != null) it.extensionReceiver = extensionReceiver args.forEachIndexed { index, arg -> it.putValueArgument(index, arg) } } } // -------------------------------------------------------------------------------------------------------- // Misc // -------------------------------------------------------------------------------------------------------- val String.name: Name get() = Name.identifier(this) val IrType.isList get() = isSubtypeOfClass(pluginContext.listClass) fun IrType.enumListType(protoEnum: ProtoEnum): IrType? { if (! this.isList) return null val itemType = (this as IrSimpleTypeImpl).arguments.first() as IrType if (!itemType.isSubtypeOfClass(protoEnum.enumClass)) return null return itemType } fun <T> IrType.ifBoolean(result: () -> T): T? = if (isBoolean()) result() else null fun <T> IrType.ifByteArray(result: () -> T): T? { return if (getPrimitiveArrayElementType() == irBuiltIns.byteType.getPrimitiveType()) { result() } else { null } } fun <T> IrType.ifUuid(result: () -> T): T? { return if (this.isSubtypeOfClass(pluginContext.uuidType)) { result() } else { null } } }
6
null
1
8
2421ce21026088e255d0b975a194a66c2f3a2b84
13,069
z2-service
Apache License 2.0
codebase/android/core/testing/src/main/java/com/makeappssimple/abhimanyu/financemanager/android/core/testing/alarmkit/TestAlarmKit.kt
Abhimanyu14
429,663,688
false
{"Kotlin": 1908017}
package com.makeappssimple.abhimanyu.financemanager.android.core.testing.alarmkit import com.makeappssimple.abhimanyu.financemanager.android.core.alarmkit.AlarmKit public class TestAlarmKit : AlarmKit { override suspend fun cancelReminderAlarm(): Boolean { return true } override suspend fun setReminderAlarm(): Boolean { return true } }
11
Kotlin
0
3
a9e7570d854c7738d0ad5bcf139fa9874fa83b21
373
finance-manager
Apache License 2.0
android-uitests/testData/CatchUp/app/src/main/kotlin/io/sweers/catchup/ui/fragments/service/ImageAdapter.kt
JetBrains
60,701,247
false
null
/* * Copyright (c) 2018 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.sweers.catchup.ui.controllers.service import android.animation.ObjectAnimator import android.annotation.SuppressLint import android.annotation.TargetApi import android.content.Context import android.graphics.ColorMatrixColorFilter import android.graphics.drawable.ColorDrawable import android.graphics.drawable.Drawable import android.graphics.drawable.TransitionDrawable import android.os.Build import android.view.LayoutInflater import android.view.MotionEvent import android.view.View import android.view.ViewGroup import androidx.annotation.ArrayRes import androidx.annotation.ColorInt import androidx.core.animation.doOnEnd import androidx.interpolator.view.animation.FastOutSlowInInterpolator import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView.ViewHolder import androidx.recyclerview.widget.RxViewHolder import com.bumptech.glide.ListPreloader.PreloadModelProvider import com.bumptech.glide.RequestBuilder import com.bumptech.glide.load.DataSource import com.bumptech.glide.load.engine.DiskCacheStrategy import com.bumptech.glide.load.engine.GlideException import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions import com.bumptech.glide.load.resource.gif.GifDrawable import com.bumptech.glide.request.RequestListener import com.bumptech.glide.request.RequestOptions import com.bumptech.glide.request.target.Target import com.jakewharton.rxbinding2.view.clicks import io.sweers.catchup.GlideApp import io.sweers.catchup.R import io.sweers.catchup.R.layout import io.sweers.catchup.service.api.BindableCatchUpItemViewHolder import io.sweers.catchup.service.api.CatchUpItem import io.sweers.catchup.service.api.LinkHandler import io.sweers.catchup.ui.base.DataLoadingSubject import io.sweers.catchup.ui.widget.BadgedFourThreeImageView import io.sweers.catchup.util.ObservableColorMatrix import io.sweers.catchup.util.UiUtil import io.sweers.catchup.util.glide.CatchUpTarget import io.sweers.catchup.util.isInNightMode internal class ImageAdapter(private val context: Context, private val bindDelegate: (ImageItem, ImageHolder) -> Unit) : DisplayableItemAdapter<ImageItem, ViewHolder>(columnCount = 2), DataLoadingSubject.DataLoadingCallbacks, PreloadModelProvider<ImageItem> { companion object { const val PRELOAD_AHEAD_ITEMS = 6 @ColorInt private const val INITIAL_GIF_BADGE_COLOR = 0x40ffffff } private val loadingPlaceholders: Array<ColorDrawable> private var showLoadingMore = false init { setHasStableIds(true) @ArrayRes val loadingColorArrayId = if (context.isInNightMode()) { R.array.loading_placeholders_dark } else { R.array.loading_placeholders_light } loadingPlaceholders = context.resources.getIntArray(loadingColorArrayId) .iterator() .asSequence() .map(::ColorDrawable) .toList() .toTypedArray() } override fun getPreloadItems(position: Int) = data.subList(position, minOf(data.size, position + 5)) override fun getPreloadRequestBuilder(item: ImageItem): RequestBuilder<Drawable> { val (x, y) = item.imageInfo.bestSize ?: Pair(0, 0) return GlideApp.with(context) .asDrawable() .apply(RequestOptions() .diskCacheStrategy(DiskCacheStrategy.DATA) .fitCenter() .override(x, y)) .load(item.realItem()) } override fun getItemId(position: Int): Long { if (getItemViewType(position) == TYPE_LOADING_MORE) { return RecyclerView.NO_ID } return data[position].realItem().id } @TargetApi(Build.VERSION_CODES.M) override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { val layoutInflater = LayoutInflater.from(parent.context) return when (viewType) { TYPE_ITEM -> { ImageHolder(LayoutInflater.from(parent.context) .inflate(R.layout.image_item, parent, false), loadingPlaceholders) .apply { image.setBadgeColor( INITIAL_GIF_BADGE_COLOR) image.foreground = UiUtil.createColorSelector(0x40808080, null) // play animated GIFs whilst touched image.setOnTouchListener { _, event -> // check if it's an event we care about, else bail fast val action = event.action if (!(action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL)) { return@setOnTouchListener false } // get the image and check if it's an animated GIF val drawable = image.drawable ?: return@setOnTouchListener false val gif: GifDrawable = when (drawable) { is GifDrawable -> drawable is TransitionDrawable -> (0 until drawable.numberOfLayers).asSequence() .map(drawable::getDrawable) .filterIsInstance<GifDrawable>() .firstOrNull() else -> null } ?: return@setOnTouchListener false // GIF found, start/stop it on press/lift when (action) { MotionEvent.ACTION_DOWN -> gif.start() MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> gif.stop() } false } } } TYPE_LOADING_MORE -> LoadingMoreHolder( layoutInflater.inflate(layout.infinite_loading, parent, false)) else -> TODO("Unknown type") } } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { when (getItemViewType(position)) { TYPE_ITEM -> { val imageItem = data[position] val imageHolder = holder as ImageHolder if (imageHolder.backingImageItem?.stableId() == imageItem.stableId()) { // This is the same item, no need to reset. Possible from a refresh. return } // TODO This is kind of ugly but not sure what else to do. Holder can't be an inner class to avoid mem leaks imageHolder.backingImageItem = imageItem bindDelegate(imageItem, holder) .also { holder.backingImageItem = null } } TYPE_LOADING_MORE -> (holder as LoadingMoreHolder).progress.visibility = if (position > 0) View.VISIBLE else View.INVISIBLE } } @SuppressLint("NewApi") override fun onViewRecycled(holder: RecyclerView.ViewHolder) { if (holder is ImageHolder) { // reset the badge & ripple which are dynamically determined GlideApp.with(holder.itemView).clear(holder.image) holder.image.setBadgeColor( INITIAL_GIF_BADGE_COLOR) holder.image.showBadge(false) holder.image.foreground = UiUtil.createColorSelector(0x40808080, null) } } override fun getItemCount() = dataItemCount + if (showLoadingMore) 1 else 0 private val dataItemCount: Int get() = data.size private val loadingMoreItemPosition: Int get() = if (showLoadingMore) itemCount - 1 else RecyclerView.NO_POSITION override fun getItemViewType(position: Int): Int { if (position < dataItemCount && dataItemCount > 0) { return TYPE_ITEM } return TYPE_LOADING_MORE } override fun dataStartedLoading() { if (showLoadingMore) { return } showLoadingMore = true notifyItemInserted(loadingMoreItemPosition) } override fun dataFinishedLoading() { if (!showLoadingMore) { return } val loadingPos = loadingMoreItemPosition showLoadingMore = false notifyItemRemoved(loadingPos) } internal class ImageHolder(itemView: View, private val loadingPlaceholders: Array<ColorDrawable>) : RxViewHolder(itemView), BindableCatchUpItemViewHolder { internal var backingImageItem: ImageItem? = null internal val image: BadgedFourThreeImageView = itemView as BadgedFourThreeImageView override fun itemView(): View = itemView override fun bind(item: CatchUpItem, linkHandler: LinkHandler, itemClickHandler: ((String) -> Any)?, markClickHandler: ((String) -> Any)?) { backingImageItem?.let { imageItem -> item.itemClickUrl?.let { itemClickHandler?.invoke(it) } val (x, y) = imageItem.imageInfo.bestSize ?: Pair(image.measuredWidth, image.measuredHeight) GlideApp.with(itemView.context) .load(imageItem.imageInfo.url) .apply(RequestOptions() .placeholder(loadingPlaceholders[adapterPosition % loadingPlaceholders.size]) .diskCacheStrategy(DiskCacheStrategy.DATA) .centerCrop() .override(x, y)) .transition(DrawableTransitionOptions.withCrossFade()) .listener(object : RequestListener<Drawable> { override fun onResourceReady(resource: Drawable, model: Any, target: Target<Drawable>, dataSource: DataSource, isFirstResource: Boolean): Boolean { if (!imageItem.hasFadedIn) { image.setHasTransientState(true) val cm = ObservableColorMatrix() // Saturation ObjectAnimator.ofFloat(cm, ObservableColorMatrix.SATURATION, 0f, 1f) .apply { addUpdateListener { _ -> // just animating the color matrix does not invalidate the // drawable so need this update listener. Also have to create a // new CMCF as the matrix is immutable :( image.colorFilter = ColorMatrixColorFilter(cm) } duration = 2000L interpolator = FastOutSlowInInterpolator() doOnEnd { image.clearColorFilter() image.setHasTransientState(false) } start() imageItem.hasFadedIn = true } } return false } override fun onLoadFailed(e: GlideException?, model: Any, target: Target<Drawable>, isFirstResource: Boolean) = false }) .into(CatchUpTarget(image, false)) // need both placeholder & background to prevent seeing through image as it fades in image.background = loadingPlaceholders[adapterPosition % loadingPlaceholders.size] image.showBadge(imageItem.imageInfo.animatable) } } override fun itemClicks() = itemView().clicks() } }
5
null
227
948
10110983c7e784122d94c7467e9d243aba943bf4
11,531
android
Apache License 2.0
app/src/main/java/org/wikipedia/dataclient/mwapi/media/MediaHelper.kt
dbrant
28,157,306
false
null
package org.wikipedia.dataclient.mwapi.media import org.wikipedia.dataclient.Service import org.wikipedia.dataclient.ServiceFactory import org.wikipedia.dataclient.WikiSite import java.util.HashMap import io.reactivex.Observable object MediaHelper { private const val COMMONS_DB_NAME = "commonswiki" /** * Returns a map of "language":"caption" combinations for a particular file on Commons. */ fun getImageCaptions(fileName: String): Observable<Map<String, String>> { return ServiceFactory.get(WikiSite(Service.COMMONS_URL)).getEntitiesByTitle(fileName, COMMONS_DB_NAME) .map { entities -> val captions = HashMap<String, String>() for (label in entities.first!!.labels().values) { captions[label.language()] = label.value() } captions } } }
1
null
0
2
33d4c162b0847ef4814d9ae7a6229d4877d8eb80
917
apps-android-wikipedia
Apache License 2.0
vuesaxicons/src/commonMain/kotlin/moe/tlaster/icons/vuesax/vuesaxicons/bulk/Languagesquare.kt
Tlaster
560,394,734
false
{"Kotlin": 25133302}
package moe.tlaster.icons.vuesax.vuesaxicons.bulk import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin 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 moe.tlaster.icons.vuesax.vuesaxicons.BulkGroup public val BulkGroup.Languagesquare: ImageVector get() { if (_languagesquare != null) { return _languagesquare!! } _languagesquare = Builder(name = "Languagesquare", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF292D32)), stroke = null, fillAlpha = 0.4f, strokeAlpha = 0.4f, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(16.1898f, 2.0f) horizontalLineTo(7.8198f) curveTo(4.1798f, 2.0f, 2.0098f, 4.17f, 2.0098f, 7.81f) verticalLineTo(16.18f) curveTo(2.0098f, 19.82f, 4.1798f, 21.99f, 7.8198f, 21.99f) horizontalLineTo(16.1898f) curveTo(19.8298f, 21.99f, 21.9998f, 19.82f, 21.9998f, 16.18f) verticalLineTo(7.81f) curveTo(21.9998f, 4.17f, 19.8298f, 2.0f, 16.1898f, 2.0f) close() } path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(17.0002f, 15.97f) curveTo(15.6902f, 15.97f, 14.4402f, 15.37f, 13.4402f, 14.26f) curveTo(14.4302f, 12.99f, 15.0702f, 11.42f, 15.2102f, 9.7f) horizontalLineTo(16.9902f) curveTo(17.4002f, 9.7f, 17.7402f, 9.36f, 17.7402f, 8.95f) curveTo(17.7402f, 8.54f, 17.4002f, 8.2f, 16.9902f, 8.2f) horizontalLineTo(14.5602f) curveTo(14.5402f, 8.2f, 14.5202f, 8.19f, 14.5002f, 8.19f) curveTo(14.4802f, 8.19f, 14.4602f, 8.2f, 14.4402f, 8.2f) horizontalLineTo(12.7502f) verticalLineTo(7.27f) curveTo(12.7502f, 6.86f, 12.4102f, 6.52f, 12.0002f, 6.52f) curveTo(11.5902f, 6.52f, 11.2502f, 6.86f, 11.2502f, 7.27f) verticalLineTo(8.2f) horizontalLineTo(7.0103f) curveTo(6.6002f, 8.2f, 6.2603f, 8.54f, 6.2603f, 8.95f) curveTo(6.2603f, 9.36f, 6.6002f, 9.7f, 7.0103f, 9.7f) horizontalLineTo(12.0002f) horizontalLineTo(13.7003f) curveTo(13.3303f, 13.22f, 10.4702f, 15.97f, 6.9902f, 15.97f) curveTo(6.5802f, 15.97f, 6.2402f, 16.31f, 6.2402f, 16.72f) curveTo(6.2402f, 17.13f, 6.5802f, 17.47f, 6.9902f, 17.47f) curveTo(9.0602f, 17.47f, 10.9502f, 16.67f, 12.4002f, 15.36f) curveTo(13.6702f, 16.72f, 15.2802f, 17.47f, 16.9902f, 17.47f) curveTo(17.4002f, 17.47f, 17.7402f, 17.13f, 17.7402f, 16.72f) curveTo(17.7402f, 16.31f, 17.4102f, 15.97f, 17.0002f, 15.97f) close() } } .build() return _languagesquare!! } private var _languagesquare: ImageVector? = null
0
Kotlin
0
2
b8a8231e6637c2008f675ae76a3423b82ee53950
3,893
VuesaxIcons
MIT License
kotest-framework/kotest-framework-api/src/commonMain/kotlin/io/kotest/core/spec/style/scopes/DescribeSpecContainerContext.kt
nicorichard
399,195,014
true
{"Kotlin": 2834461, "CSS": 352, "Java": 145}
package io.kotest.core.spec.style.scopes import io.kotest.common.ExperimentalKotest import io.kotest.core.spec.resolvedDefaultConfig import io.kotest.core.test.DescriptionName import io.kotest.core.test.NestedTest import io.kotest.core.test.TestCase import io.kotest.core.test.TestContext import io.kotest.core.test.TestType import io.kotest.core.test.createNestedTest import io.kotest.core.test.createTestName import kotlin.coroutines.CoroutineContext @Deprecated("This interface has been renamed to DescribeSpecContainerContext. This alias will be removed in 4.8") typealias DescribeScope = DescribeSpecContainerContext /** * A scope that allows tests to be registered using the syntax: * * describe("some test") * * or * * xdescribe("some disabled test") * * and * * it("some test") * it("some test").config(...) * xit("some test") * xit("some test").config(...) */ class DescribeSpecContainerContext( val testContext: TestContext, ) : ContainerContext { override val testCase: TestCase = testContext.testCase override val coroutineContext: CoroutineContext = testContext.coroutineContext override suspend fun registerTestCase(nested: NestedTest) = testContext.registerTestCase(nested) override suspend fun addTest(name: String, type: TestType, test: suspend TestContext.() -> Unit) { when (type) { TestType.Container -> describe(name, test) TestType.Test -> it(name, test) } } suspend fun context(name: String, test: suspend DescribeSpecContainerContext.() -> Unit) { val testName = createTestName("Context: ", name, false) containerTest(testName, false, test) } @ExperimentalKotest fun context(name: String) = ContainerContextConfigBuilder(createTestName(name), this, false) { DescribeSpecContainerContext(it) } suspend fun xcontext(name: String, test: suspend DescribeSpecContainerContext.() -> Unit) { val testName = createTestName("Context: ", name, false) containerTest(testName, true, test) } @ExperimentalKotest fun xcontext(name: String) = ContainerContextConfigBuilder(createTestName("Context: ", name, false), this, true) { DescribeSpecContainerContext(it) } suspend fun describe(name: String, test: suspend DescribeSpecContainerContext.() -> Unit) { val testName = createTestName("Describe: ", name, false) containerTest(testName, false, test) } @ExperimentalKotest fun describe(name: String) = ContainerContextConfigBuilder(createTestName("Describe: ", name, false), this, false) { DescribeSpecContainerContext(it) } suspend fun xdescribe(name: String, test: suspend DescribeSpecContainerContext.() -> Unit) { val testName = createTestName("Describe: ", name, false) containerTest(testName, true, test) } @ExperimentalKotest fun xdescribe(name: String) = ContainerContextConfigBuilder(createTestName("Describe: ", name, false), this, true) { DescribeSpecContainerContext(it) } private suspend fun containerTest( testName: DescriptionName.TestName, xdisabled: Boolean, test: suspend DescribeSpecContainerContext.() -> Unit, ) { registerTestCase( createNestedTest( name = testName, xdisabled = xdisabled, config = testCase.spec.resolvedDefaultConfig(), type = TestType.Container, descriptor = null, factoryId = testCase.factoryId ) { DescribeSpecContainerContext(this).test() } ) } suspend fun it(name: String): TestWithConfigBuilder { TestDslState.startTest(testContext.testCase.description.appendTest(name)) return TestWithConfigBuilder( createTestName("It: ", name, false), testContext, testCase.spec.resolvedDefaultConfig(), xdisabled = false, ) } suspend fun xit(name: String): TestWithConfigBuilder { TestDslState.startTest(testContext.testCase.description.appendTest(name)) return TestWithConfigBuilder( createTestName("It: ", name, false), testContext, testCase.spec.resolvedDefaultConfig(), xdisabled = true, ) } suspend fun it(name: String, test: suspend TestContext.() -> Unit) = registerTestCase( createNestedTest( name = createTestName(name), xdisabled = false, config = testCase.spec.resolvedDefaultConfig(), type = TestType.Test, descriptor = null, factoryId = testCase.factoryId ) { DescribeSpecContainerContext(this).test() } ) suspend fun xit(name: String, test: suspend TestContext.() -> Unit) = registerTestCase( createNestedTest( name = createTestName(name), xdisabled = true, config = testCase.spec.resolvedDefaultConfig(), type = TestType.Test, descriptor = null, factoryId = testCase.factoryId ) { DescribeSpecContainerContext(this).test() } ) }
0
Kotlin
0
0
a1ea844df42befeb66199f3eec5b95ae9df9669f
5,044
kotest
Apache License 2.0
app/src/main/java/com/mita/todolistcomposeapp/ui/theme/Theme.kt
AHm1ta
844,129,873
false
{"Kotlin": 21596}
package com.mita.todolistcomposeapp.ui.theme import android.app.Activity import android.os.Build import android.view.View import android.view.Window import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat import androidx.core.view.WindowInsetsControllerCompat private val DarkColorScheme = darkColorScheme( primary = Purple80, secondary = PurpleGrey80, tertiary = Pink80 ) private val LightColorScheme = lightColorScheme( primary = Purple40, secondary = PurpleGrey40, tertiary = Pink40 /* Other default colors to override background = Color(0xFFFFFBFE), surface = Color(0xFFFFFBFE), onPrimary = Color.White, onSecondary = Color.White, onTertiary = Color.White, onBackground = Color(0xFF1C1B1F), onSurface = Color(0xFF1C1B1F), */ ) @Composable fun ToDoListComposeAppTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ dynamicColor: Boolean = true, content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> DarkColorScheme else -> LightColorScheme } val view: View= LocalView.current //val isLightTheme = MaterialTheme.colorScheme. if (!view.isInEditMode){ SideEffect { val window: Window= (view.context as Activity).window window.statusBarColor= Color.Transparent.toArgb() WindowCompat.setDecorFitsSystemWindows(window, false) // Set light or dark status bar icons depending on the theme val insetsController = WindowInsetsControllerCompat(window, view) // insetsController.isAppearanceLightStatusBars = isLightTheme } } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
0
Kotlin
0
0
393320f8dad595cf6d6260e59d705685375de017
2,612
ToDoListComposeApp
MIT License
core-kotlin-modules/core-kotlin-numbers-2/src/main/kotlin/com/baeldung/evenodd/EvenOdd.kt
Baeldung
260,481,121
false
{"Kotlin": 1855665, "Java": 48276, "HTML": 4883, "Dockerfile": 292}
package com.baeldung.evenodd fun isEven(value: Int) = value % 2 == 0 fun isOdd(value: Int) = value % 2 == 1
14
Kotlin
294
465
f1ef5d5ded3f7ddc647f1b6119f211068f704577
108
kotlin-tutorials
MIT License
order-api/src/main/kotlin/ru/romanow/inst/services/order/model/PaymentStatus.kt
Romanow
304,987,654
false
{"Kotlin": 117029, "JavaScript": 2720, "Dockerfile": 2127, "HCL": 1533, "Shell": 1444}
package ru.romanow.inst.services.order.model enum class PaymentStatus { PAID, CANCELED, WAITING }
5
Kotlin
4
3
fd7c37f495511382a26109c1f634e1aaf6001bb9
111
micro-services-v2
MIT License
samples/src/test/kotlin/type/P256PublicKey.kt
airgap-it
460,351,851
false
null
package type import _utils.SamplesBase import _utils.hexToBytes import it.airgap.tezos.core.Tezos import it.airgap.tezos.core.coder.encoded.decodeFromBytes import it.airgap.tezos.core.coder.encoded.encodeToBytes import it.airgap.tezos.core.type.encoded.P256PublicKey import it.airgap.tezos.crypto.bouncycastle.BouncyCastleCryptoProvider import org.junit.Test import org.junit.experimental.runners.Enclosed import org.junit.runner.RunWith import kotlin.test.assertContentEquals import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertTrue @RunWith(Enclosed::class) class P256PublicKeySamples { class Usage : SamplesBase() { @Test fun isValid() { val publicKey = "<KEY>" assertTrue(P256PublicKey.isValid(publicKey)) val unknownKey = "<KEY>" assertFalse(P256PublicKey.isValid(unknownKey)) } } class Coding : SamplesBase() { @Test fun toBytes() { Tezos { isDefault = true cryptoProvider = BouncyCastleCryptoProvider() } val publicKey = P256PublicKey("<KEY>") assertContentEquals(hexToBytes("91be4ebfb33637848b7f0f89020afed820c19f4753803761d3ed8d6e03976eeb2b"), publicKey.encodeToBytes()) } @Test fun fromBytes() { Tezos { isDefault = true cryptoProvider = BouncyCastleCryptoProvider() } val publicKey = hexToBytes("91be4ebfb33637848b7f0f89020afed820c19f4753803761d3ed8d6e03976eeb2b") assertEquals(P256PublicKey("<KEY>"), P256PublicKey.decodeFromBytes(publicKey)) } } }
0
Kotlin
2
1
c5af5ffdd4940670bd66842580d82c2b9d682d84
1,719
tezos-kotlin-sdk
MIT License