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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
analysis/low-level-api-fir/testData/lazyAnnotations/annotations/deprecation_class.kt
|
JetBrains
| 3,432,266
| false
|
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
|
// QUERY: annotations
package one
@Deprecated("deprecated class", ReplaceWith("1" + "2"))
class F<caret>oo
| 181
|
Kotlin
|
5748
| 49,172
|
33eb9cef3d146062c103f9853d772f0a1da0450e
| 107
|
kotlin
|
Apache License 2.0
|
composeUi/src/commonMain/kotlin/com/darkrockstudios/apps/hammer/common/projecteditor/scenelist/scenetree/ItemUi.kt
|
Wavesonics
| 499,367,913
| false
| null |
package com.darkrockstudios.apps.hammer.common.projecteditor.scenelist.scenetree
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import com.darkrockstudios.apps.hammer.common.data.SceneItem
import com.darkrockstudios.apps.hammer.common.tree.TreeValue
typealias ItemUi = @Composable (
node: TreeValue<SceneItem>,
toggleExpanded: (nodeId: Int) -> Unit,
collapsed: Boolean,
draggable: Modifier,
) -> Unit
| 0
|
Kotlin
|
1
| 8
|
37fa39e536151ba2b15eb81feddfd8435bf8a1d7
| 450
|
hammer-editor
|
MIT License
|
compiler/testData/diagnostics/tests/controlFlowAnalysis/deadCode/deadCallInInvokeCall.kt
|
JakeWharton
| 99,388,807
| false
| null |
fun testInvoke() {
operator fun Nothing.invoke() = this
todo()<!UNREACHABLE_CODE!>()<!>
}
fun testInvokeWithLambda() {
operator fun Nothing.invoke(<!UNUSED_PARAMETER!>i<!>: Int, f: () -> Int) = f
todo()<!UNREACHABLE_CODE!>(1){ 42 }<!>
}
fun todo() = throw Exception()
| 179
| null |
5640
| 83
|
4383335168338df9bbbe2a63cb213a68d0858104
| 285
|
kotlin
|
Apache License 2.0
|
codegen/smithy-aws-kotlin-codegen/src/main/kotlin/aws/sdk/kotlin/codegen/protocols/eventstream/EventStreamParserGenerator.kt
|
awslabs
| 121,333,316
| false
| null |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
package aws.sdk.kotlin.codegen.protocols.eventstream
import aws.sdk.kotlin.codegen.AwsRuntimeTypes
import software.amazon.smithy.codegen.core.CodegenException
import software.amazon.smithy.codegen.core.Symbol
import software.amazon.smithy.kotlin.codegen.core.*
import software.amazon.smithy.kotlin.codegen.model.*
import software.amazon.smithy.kotlin.codegen.rendering.ExceptionBaseClassGenerator
import software.amazon.smithy.kotlin.codegen.rendering.protocol.ProtocolGenerator
import software.amazon.smithy.kotlin.codegen.rendering.serde.StructuredDataParserGenerator
import software.amazon.smithy.kotlin.codegen.rendering.serde.bodyDeserializer
import software.amazon.smithy.kotlin.codegen.rendering.serde.bodyDeserializerName
import software.amazon.smithy.model.shapes.*
import software.amazon.smithy.model.traits.EventHeaderTrait
import software.amazon.smithy.model.traits.EventPayloadTrait
/**
* Implements rendering deserialize implementation for event streams implemented using the
* `vnd.amazon.event-stream` content-type
*
* @param sdg the structured data parser generator
*/
class EventStreamParserGenerator(
private val ctx: ProtocolGenerator.GenerationContext,
private val sdg: StructuredDataParserGenerator,
) {
/**
* Return the function responsible for deserializing an operation output that targets an event stream
*
* ```
* private suspend fun deserializeFooOperationBody(builder: Foo.Builder, body: HttpBody) { ... }
* ```
*/
fun responseHandler(ctx: ProtocolGenerator.GenerationContext, op: OperationShape): Symbol =
op.bodyDeserializer(ctx.settings) { writer ->
val outputSymbol = ctx.symbolProvider.toSymbol(ctx.model.expectShape<StructureShape>(op.output.get()))
// we have access to the builder for the output type and the full HttpBody
// members bound via HTTP bindings (e.g. httpHeader, statusCode, etc) are already deserialized via HttpDeserialize impl
// we just need to deserialize the event stream member (and/or the initial response)
writer.withBlock(
// FIXME - revert to private, exposed as internal temporarily while we figure out integration tests
"internal suspend fun #L(builder: #T.Builder, body: #T) {",
"}",
op.bodyDeserializerName(),
outputSymbol,
RuntimeTypes.Http.HttpBody,
) {
renderDeserializeEventStream(ctx, op, writer)
}
}
private fun renderDeserializeEventStream(ctx: ProtocolGenerator.GenerationContext, op: OperationShape, writer: KotlinWriter) {
val output = ctx.model.expectShape<StructureShape>(op.output.get())
val streamingMember = output.findStreamingMember(ctx.model) ?: error("expected a streaming member for $output")
val streamShape = ctx.model.expectShape<UnionShape>(streamingMember.target)
val streamSymbol = ctx.symbolProvider.toSymbol(streamShape)
// TODO - handle RPC bound protocol bindings where the initial response is bound to an event stream document
// possibly by decoding the first Message
val messageTypeSymbol = RuntimeTypes.AwsEventStream.MessageType
val baseExceptionSymbol = ExceptionBaseClassGenerator.baseExceptionSymbol(ctx.settings)
writer.write("val chan = body.#T() ?: return", RuntimeTypes.Http.toSdkByteReadChannel)
writer.write("val events = #T(chan)", RuntimeTypes.AwsEventStream.decodeFrames)
.indent()
.withBlock(".#T { message ->", "}", RuntimeTypes.KotlinxCoroutines.Flow.map) {
withBlock("when(val mt = message.#T()) {", "}", RuntimeTypes.AwsEventStream.MessageTypeExt) {
withBlock("is #T.Event -> when(mt.shapeType) {", "}", messageTypeSymbol) {
streamShape.filterEventStreamErrors(ctx.model).forEach { member ->
withBlock("#S -> {", "}", member.memberName) {
renderDeserializeEventVariant(ctx, streamSymbol, member, writer)
}
}
write("else -> #T.SdkUnknown", streamSymbol)
}
withBlock("is #T.Exception -> when(mt.shapeType){", "}", messageTypeSymbol) {
// errors are completely bound to payload (at least according to design docs)
val errorMembers = streamShape.members().filter {
val target = ctx.model.expectShape(it.target)
target.isError
}
errorMembers.forEach { member ->
withBlock("#S -> {", "}", member.memberName) {
val payloadDeserializeFn = sdg.payloadDeserializer(ctx, member)
write("val err = #T(message.payload)", payloadDeserializeFn)
write("throw err")
}
}
write("else -> throw #T(#S)", baseExceptionSymbol, "error processing event stream, unrecognized errorType: \${mt.shapeType}")
}
// this is a service exception still, just un-modeled
write("is #T.Error -> throw #T(\"error processing event stream: errorCode=\${mt.errorCode}; message=\${mt.message}\")", messageTypeSymbol, baseExceptionSymbol)
// this is a client exception because we failed to parse it
write("is #T.SdkUnknown -> throw #T(\"unrecognized event stream message `:message-type`: \${mt.messageType}\")", messageTypeSymbol, AwsRuntimeTypes.Core.ClientException)
}
}
.dedent()
.write("builder.#L = events", streamingMember.defaultName())
}
private fun renderDeserializeEventVariant(ctx: ProtocolGenerator.GenerationContext, unionSymbol: Symbol, member: MemberShape, writer: KotlinWriter) {
val variant = ctx.model.expectShape(member.target)
val eventHeaderBindings = variant.members().filter { it.hasTrait<EventHeaderTrait>() }
val eventPayloadBinding = variant.members().firstOrNull { it.hasTrait<EventPayloadTrait>() }
val unbound = variant.members().filterNot { it.hasTrait<EventHeaderTrait>() || it.hasTrait<EventPayloadTrait>() }
if (eventHeaderBindings.isEmpty() && eventPayloadBinding == null) {
// the entire variant can be deserialized from the payload
val payloadDeserializeFn = sdg.payloadDeserializer(ctx, member)
writer.write("val e = #T(message.payload)", payloadDeserializeFn)
} else {
val variantSymbol = ctx.symbolProvider.toSymbol(variant)
writer.write("val eb = #T.Builder()", variantSymbol)
// render members bound to header
eventHeaderBindings.forEach { hdrBinding ->
val target = ctx.model.expectShape(hdrBinding.target)
val targetSymbol = ctx.symbolProvider.toSymbol(target)
// :test(boolean, byte, short, integer, long, blob, string, timestamp))
val conversionFn = when (target.type) {
ShapeType.BOOLEAN -> RuntimeTypes.AwsEventStream.expectBool
ShapeType.BYTE -> RuntimeTypes.AwsEventStream.expectByte
ShapeType.SHORT -> RuntimeTypes.AwsEventStream.expectInt16
ShapeType.INTEGER -> RuntimeTypes.AwsEventStream.expectInt32
ShapeType.LONG -> RuntimeTypes.AwsEventStream.expectInt64
ShapeType.BLOB -> RuntimeTypes.AwsEventStream.expectByteArray
ShapeType.STRING -> RuntimeTypes.AwsEventStream.expectString
ShapeType.TIMESTAMP -> RuntimeTypes.AwsEventStream.expectTimestamp
else -> throw CodegenException("unsupported eventHeader shape: member=$hdrBinding; targetShape=$target")
}
val defaultValuePostfix = if (targetSymbol.isNotBoxed && targetSymbol.defaultValue() != null) {
" ?: ${targetSymbol.defaultValue()}"
} else {
""
}
writer.write("eb.#L = message.headers.find { it.name == #S }?.value?.#T()$defaultValuePostfix", hdrBinding.defaultName(), hdrBinding.memberName, conversionFn)
}
if (eventPayloadBinding != null) {
renderDeserializeExplicitEventPayloadMember(ctx, eventPayloadBinding, writer)
} else {
if (unbound.isNotEmpty()) {
// all remaining members are bound to payload (but not explicitly bound via @eventPayload)
// generate a payload deserializer specific to the unbound members (note this will be a deserializer
// for the overall event shape but only payload members will be considered for deserialization),
// and then assign each deserialized payload member to the current builder instance
val payloadDeserializeFn = sdg.payloadDeserializer(ctx, member, unbound)
writer.write("val tmp = #T(message.payload)", payloadDeserializeFn)
unbound.forEach {
writer.write("eb.#1L = tmp.#1L", it.defaultName())
}
}
}
writer.write("val e = eb.build()")
}
writer.write("#T.#L(e)", unionSymbol, member.unionVariantName())
}
private fun renderDeserializeExplicitEventPayloadMember(
ctx: ProtocolGenerator.GenerationContext,
member: MemberShape,
writer: KotlinWriter,
) {
// TODO - check content type for blob and string
// structure > :test(member > :test(blob, string, structure, union))
val target = ctx.model.expectShape(member.target)
when (target.type) {
ShapeType.BLOB -> writer.write("eb.#L = message.payload", member.defaultName())
ShapeType.STRING -> writer.write("eb.#L = message.payload.decodeToString()", member.defaultName())
ShapeType.STRUCTURE, ShapeType.UNION -> {
val payloadDeserializeFn = sdg.payloadDeserializer(ctx, member)
writer.write("eb.#L = #T(message.payload)", member.defaultName(), payloadDeserializeFn)
}
else -> throw CodegenException("unsupported shape type `${target.type}` for target: $target; expected blob, string, structure, or union for eventPayload member: $member")
}
}
}
| 92
| null |
34
| 293
|
7e01857598b2b91ea964e9fd4a45b2ffd17cd13e
| 10,853
|
aws-sdk-kotlin
|
Apache License 2.0
|
3D Clock With Dark and Light Theme/android/app/src/main/kotlin/com/example/image_view_3d/MainActivity.kt
|
SatYu26
| 331,404,021
| false
|
{"Dart": 64987, "Swift": 6464, "Kotlin": 2067, "Objective-C": 608}
|
package com.example.image_view_3d
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 0
|
Dart
|
0
| 0
|
a4dc0e3ae58e04288d5927e1d92371178b5a2249
| 130
|
Flutter-Practice-Projects
|
MIT License
|
src/main/kotlin/no/skatteetaten/aurora/mokey/extensions/JsonNode.kt
|
Skatteetaten
| 104,215,122
| false
| null |
package no.skatteetaten.aurora.mokey.extensions
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.node.MissingNode
import com.fasterxml.jackson.databind.node.MissingNode.getInstance
fun JsonNode.extract(vararg pathAlternatives: String): JsonNode? {
var valueNode: JsonNode = getInstance()
for (alt in pathAlternatives) {
valueNode = this.at(alt)
if (valueNode !is MissingNode) break
valueNode = this.getExact(alt)
if (valueNode !is MissingNode) break
}
return if (valueNode !is MissingNode) valueNode else null
}
/**
* This is for fields that contains slash in key. Ex: "commit.time/v1"
* @return value for key if key exists or MissingNode if not.
*/
fun JsonNode.getExact(path: String): JsonNode {
val value = try {
this.fields().asSequence().first { "/${it.key}" == path }?.value
} catch (ex: Exception) {
null
}
return value ?: getInstance()
}
| 1
|
Kotlin
|
0
| 2
|
56fbffee28560a722ab5ae19d92f4baed0aaf059
| 974
|
mokey
|
Apache License 2.0
|
app/src/main/java/com/junjun/sunnyweather/android/logic/model/DailyResponse.kt
|
wangchuan-long
| 282,352,282
| false
| null |
package com.junjun.sunnyweather.android.logic.model
import com.google.gson.annotations.SerializedName
import java.util.*
/**
* 定义未来天气查询返回的数据类型
*/
// status:请求状态 result:关于结果的数组
data class DailyResponse(val status: String, val result: Result) {
// daily:未来天气信息
data class Result(val daily: Daily)
// temperature:温度 skycon:天气情况 lifeIndex:其他状况
data class Daily(val temperature: List<Temperature>, val skycon: List<Skycon>, @SerializedName("life_index") val lifeIndex: LifeIndex)
// max:最高温度 min:最低温度
data class Temperature(val max: Float, val min: Float)
// value:状况 date:时间
data class Skycon(val value: String, val date: Date)
// coldRisk: 寒冷风险 carWashing:洗车 ultraviolet:紫外线 dressing:穿衣
data class LifeIndex(val coldRisk: List<LifeDescription>, val carWashing: List<LifeDescription>, val ultraviolet: List<LifeDescription>, val dressing: List<LifeDescription>)
// desc:说明
data class LifeDescription(val desc: String)
}
| 0
|
Kotlin
|
0
| 0
|
408f44fac5aeb252327191482ad550d5f675084c
| 968
|
SunnyWeather
|
Apache License 2.0
|
app/src/main/java/github/sukieva/hhu/data/local/dao/FavDao.kt
|
SukiEva
| 338,038,935
| false
| null |
package github.sukieva.hhu.data.local.dao
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
import androidx.room.Update
import github.sukieva.hhu.data.entity.Website
@Dao
interface FavDao {
@Insert
suspend fun insertWeb(website: Website): Long
@Query("select * from Website")
suspend fun loadAllWebs(): List<Website>
@Query("delete from Website")
suspend fun deleteAllWebs()
@Query("delete from Website where site_name = :siteName")
suspend fun deleteWebBySiteName(siteName: String): Int
}
| 0
|
Kotlin
|
1
| 9
|
fb62706e96602a18b90f2ebf05808918dc1b0358
| 558
|
Myhhu
|
Apache License 2.0
|
app/src/main/java/net/mm2d/orientation/view/widget/CustomWidgetProvider.kt
|
ohmae
| 30,814,736
| false
|
{"Kotlin": 285967}
|
/*
* Copyright (c) 2023 大前良介 (<NAME>)
*
* This software is released under the MIT License.
* http://opensource.org/licenses/MIT
*/
package net.mm2d.orientation.view.widget
import android.appwidget.AppWidgetManager
import android.appwidget.AppWidgetProvider
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.res.Configuration
import android.os.Bundle
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.shareIn
import kotlinx.coroutines.launch
import net.mm2d.orientation.control.Orientation
import net.mm2d.orientation.settings.DesignPreference
import net.mm2d.orientation.settings.OrientationPreference
import net.mm2d.orientation.settings.PreferenceRepository
import net.mm2d.orientation.settings.WidgetSettingsRepository
import javax.inject.Inject
@AndroidEntryPoint
class CustomWidgetProvider : AppWidgetProvider() {
@Inject
lateinit var preference: PreferenceRepository
@Inject
lateinit var widgetSettings: WidgetSettingsRepository
private val exceptionHandler = CoroutineExceptionHandler { _, _ -> }
private val job = SupervisorJob()
private val scope: CoroutineScope = CoroutineScope(Dispatchers.Main + job + exceptionHandler)
private val orientationFlow: Flow<OrientationPreference> by lazy {
preference.orientationPreferenceFlow
.map {
val o = if (it.enabled) it.orientation else Orientation.INVALID
it.copy(orientation = o)
}
.shareIn(scope, SharingStarted.Eagerly, 1)
}
private val designFlow: Flow<DesignPreference> by lazy {
preference.designPreferenceFlow.shareIn(scope, SharingStarted.Eagerly, 1)
}
override fun onReceive(context: Context, intent: Intent) {
super.onReceive(context, intent)
if (intent.action == Intent.ACTION_CONFIGURATION_CHANGED) {
scope.launch {
delay(500)
val manager: AppWidgetManager = AppWidgetManager.getInstance(context)
val orientation = orientationFlow.first()
manager.getAppWidgetIds(ComponentName(context, CustomWidgetProvider::class.java)).forEach {
launch { update(context, manager, it, orientation) }
}
}
}
}
override fun onUpdate(context: Context, manager: AppWidgetManager, ids: IntArray) {
scope.launch {
val (orientation, design) = combine(orientationFlow, designFlow, ::Pair).first()
ids.forEach { launch { update(context, manager, it, orientation, design) } }
}
}
override fun onAppWidgetOptionsChanged(
context: Context,
manager: AppWidgetManager,
id: Int,
newOptions: Bundle?
) {
scope.launch {
val (orientation, design) = combine(orientationFlow, designFlow, ::Pair).first()
update(context, manager, id, orientation, design, newOptions)
}
}
override fun onDeleted(context: Context, appWidgetIds: IntArray) {
scope.launch {
appWidgetIds.forEach {
widgetSettings.dao().delete(it)
}
}
}
override fun onRestored(context: Context, oldWidgetIds: IntArray, newWidgetIds: IntArray) {
scope.launch {
val newSettings = oldWidgetIds.indices.mapNotNull {
val oldId = oldWidgetIds[it]
val newId = newWidgetIds[it]
if (oldId == newId) return@mapNotNull null
widgetSettings.dao().get(oldId)?.copy(id = newId)
}
oldWidgetIds.forEach { widgetSettings.dao().delete(it) }
newSettings.forEach { widgetSettings.dao().insert(it) }
}
}
companion object {
private lateinit var preferenceRepository: PreferenceRepository
private lateinit var widgetSettingsRepository: WidgetSettingsRepository
private lateinit var orientationFlow: Flow<OrientationPreference>
fun initialize(
context: Context,
preference: PreferenceRepository,
widgetSettings: WidgetSettingsRepository,
) {
preferenceRepository = preference
widgetSettingsRepository = widgetSettings
orientationFlow = preference.orientationPreferenceFlow
.map {
val o = if (it.enabled) it.orientation else Orientation.INVALID
it.copy(orientation = o)
}
.shareIn(preference.scope, SharingStarted.Eagerly, 1)
val manager: AppWidgetManager = AppWidgetManager.getInstance(context)
preference.scope.launch {
orientationFlow.collect { orientation ->
manager.getAppWidgetIds(ComponentName(context, CustomWidgetProvider::class.java)).forEach {
launch { update(context, manager, it, orientation) }
}
}
}
context.registerReceiver(CustomWidgetProvider(), IntentFilter(Intent.ACTION_CONFIGURATION_CHANGED))
}
private suspend fun update(
context: Context,
manager: AppWidgetManager,
id: Int,
orientation: OrientationPreference,
design: DesignPreference,
options: Bundle? = null
) {
val setting = widgetSettingsRepository.getOrDefault(id, design)
val (width, height) = extractSize(context, manager, id, options)
val views = CustomWidgetRemoteViewsCreator(context, width, height, setting, orientation).create()
manager.updateAppWidget(id, views)
}
private suspend fun update(
context: Context,
manager: AppWidgetManager,
id: Int,
orientation: OrientationPreference,
) {
val setting = widgetSettingsRepository.dao().get(id) ?: return
val (width, height) = extractSize(context, manager, id)
val views = CustomWidgetRemoteViewsCreator(context, width, height, setting, orientation).create()
manager.updateAppWidget(id, views)
}
fun update(
context: Context,
id: Int,
) {
preferenceRepository.scope.launch {
val setting = widgetSettingsRepository.dao().get(id) ?: return@launch
val orientation = orientationFlow.first()
val manager: AppWidgetManager = AppWidgetManager.getInstance(context)
val (width, height) = extractSize(context, manager, id)
val views = CustomWidgetRemoteViewsCreator(context, width, height, setting, orientation).create()
manager.updateAppWidget(id, views)
}
}
private fun extractSize(
context: Context,
manager: AppWidgetManager,
id: Int,
options: Bundle? = null
): Pair<Int, Int> = (options ?: manager.getAppWidgetOptions(id)).let {
if (context.resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE) {
it.getInt(AppWidgetManager.OPTION_APPWIDGET_MAX_WIDTH) to
it.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT)
} else {
it.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH) to
it.getInt(AppWidgetManager.OPTION_APPWIDGET_MAX_HEIGHT)
}
}
}
}
| 6
|
Kotlin
|
21
| 70
|
b8384573e09be1c07abf31beb6ad19a62e974536
| 7,991
|
orientation-faker
|
MIT License
|
core/mobile/src/main/kotlin/com/boswelja/smartwatchextensions/core/CommonDI.kt
|
boswelja
| 103,805,743
| false
| null |
package com.boswelja.smartwatchextensions.core
import com.boswelja.smartwatchextensions.core.devicemanagement.WatchDbRepository
import com.boswelja.smartwatchextensions.core.devicemanagement.WatchRepository
import com.boswelja.smartwatchextensions.core.devicemanagement.database.RegisteredWatchDatabase
import com.boswelja.smartwatchextensions.core.settings.WatchSettingsDbRepository
import com.boswelja.smartwatchextensions.core.settings.WatchSettingsRepository
import com.boswelja.smartwatchextensions.core.settings.database.WatchSettingsDatabase
import org.koin.core.parameter.parametersOf
import org.koin.core.qualifier.named
import org.koin.dsl.module
/**
* A Koin module for providing core dependencies.
*/
val coreCommonModule = module {
// Settings repository
single {
WatchSettingsDatabase(
get {
parametersOf(WatchSettingsDatabase.Schema, "watchsettings.db")
}
)
}
single<WatchSettingsRepository> { WatchSettingsDbRepository(get(), get(named("database"))) }
// Registered watch repository
single {
RegisteredWatchDatabase(
get {
parametersOf(RegisteredWatchDatabase.Schema, "registeredwatches.db")
}
)
}
single<WatchRepository> {
WatchDbRepository(get(), get(), get(named("database")))
}
}
| 15
|
Kotlin
|
0
| 12
|
8bcbb19bd153a60a71aec6abade94ae3ac6f71d4
| 1,361
|
SmartwatchExtensions
|
Apache License 2.0
|
app/src/test/java/com/waryozh/simplestepcounter/WalkViewModelTest.kt
|
Waryozh
| 202,525,623
| false
| null |
package com.waryozh.simplestepcounter
import android.view.View
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.lifecycle.MutableLiveData
import com.waryozh.simplestepcounter.database.WalkDay
import com.waryozh.simplestepcounter.repositories.Repository
import com.waryozh.simplestepcounter.testing.getOrAwaitValue
import com.waryozh.simplestepcounter.viewmodels.WalkViewModel
import io.mockk.every
import io.mockk.mockkClass
import org.junit.Assert.assertEquals
import org.junit.Rule
import org.junit.Test
class WalkViewModelTest {
@Rule
@JvmField
val instantExecutorRule = InstantTaskExecutorRule()
private lateinit var viewModel: WalkViewModel
private val repository = mockkClass(Repository::class, relaxed = true)
@Test
fun stepsAndDistance_todayIsNull() {
every { repository.today } returns MutableLiveData<WalkDay>(null)
viewModel = WalkViewModel(repository)
assertEquals(0, viewModel.stepsTaken.getOrAwaitValue())
assertEquals(0, viewModel.distanceWalked.getOrAwaitValue())
}
@Test
fun stepsAndDistance_todayNotNull() {
val steps = 1000
val distance = 650
val today = WalkDay(steps = steps, distance = distance)
every { repository.today } returns MutableLiveData<WalkDay>(today)
viewModel = WalkViewModel(repository)
assertEquals(steps, viewModel.stepsTaken.getOrAwaitValue())
assertEquals(distance, viewModel.distanceWalked.getOrAwaitValue())
}
@Test
fun stepLength() {
val stepLength = 70
every { repository.getStepLength() } returns stepLength
viewModel = WalkViewModel(repository)
assertEquals(stepLength, viewModel.stepLength.value)
}
@Test
fun stepCounterNotAvailableVisibility() {
viewModel = WalkViewModel(repository)
assertEquals(View.GONE, viewModel.stepCounterNotAvailableVisibility.value)
}
@Test
fun shouldStartService_serviceIsRunningAndShouldRun() {
every { repository.getServiceRunning() } returns true
every { repository.getServiceShouldRun() } returns true
viewModel = WalkViewModel(repository)
assertEquals(false, viewModel.shouldStartService.value)
}
@Test
fun shouldStartService_serviceIsRunningAndShouldNotRun() {
every { repository.getServiceRunning() } returns true
every { repository.getServiceShouldRun() } returns false
viewModel = WalkViewModel(repository)
assertEquals(false, viewModel.shouldStartService.value)
}
@Test
fun shouldStartService_serviceNotRunningAndShouldRun() {
every { repository.getServiceRunning() } returns false
every { repository.getServiceShouldRun() } returns true
viewModel = WalkViewModel(repository)
assertEquals(true, viewModel.shouldStartService.value)
}
@Test
fun shouldStartService_serviceNotRunningAndShouldNotRun() {
every { repository.getServiceRunning() } returns false
every { repository.getServiceShouldRun() } returns false
viewModel = WalkViewModel(repository)
assertEquals(false, viewModel.shouldStartService.value)
}
@Test
fun buttonsState_serviceIsRunning() {
every { repository.getServiceRunning() } returns true
viewModel = WalkViewModel(repository)
assertEquals(false, viewModel.startButtonEnabled.value)
assertEquals(true, viewModel.stopButtonEnabled.value)
}
@Test
fun buttonsState_serviceNotRunning() {
every { repository.getServiceRunning() } returns false
viewModel = WalkViewModel(repository)
assertEquals(true, viewModel.startButtonEnabled.value)
assertEquals(false, viewModel.stopButtonEnabled.value)
}
}
| 0
|
Kotlin
|
0
| 0
|
9c1d619d51c2fcdc5f041ea3a84a6ed36771a4d1
| 3,826
|
simple-step-counter
|
MIT License
|
frontend/app/src/main/java/com/kasiry/app/screen/LoginScreen.kt
|
alfianandinugraha
| 585,695,566
| false
| null |
package com.kasiry.app.screen
import android.app.Application
import android.util.Log
import android.widget.Toast
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.Email
import androidx.compose.material.icons.rounded.Lock
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import com.kasiry.app.compose.Button
import com.kasiry.app.compose.TextField
import com.kasiry.app.repositories.AuthRepository
import com.kasiry.app.repositories.ProfileRepository
import com.kasiry.app.rules.minLength
import com.kasiry.app.rules.required
import com.kasiry.app.theme.*
import com.kasiry.app.utils.Field
import com.kasiry.app.utils.FormStore
import com.kasiry.app.utils.http.HttpState
import com.kasiry.app.viewmodel.LoginViewModel
import com.kasiry.app.viewmodel.ProfileViewModel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.koin.androidx.compose.get
@Composable
fun LoginScreen(
navController: NavController,
application: Application,
profileViewModel: ProfileViewModel
) {
val profileRepository: ProfileRepository = get()
val context = LocalContext.current
val loginService = remember {
LoginViewModel(
application,
profileRepository = profileRepository,
authRepository = AuthRepository(application.applicationContext)
)
}
val loginResponse by loginService.login.collectAsState()
val isLoading = loginResponse is HttpState.Loading
val form = remember {
FormStore(
fields = mutableStateMapOf(
"email" to Field(
initialValue = "<EMAIL>",
),
"password" to Field(
initialValue = "<PASSWORD>",
),
)
)
}
val focusManager = LocalFocusManager.current
Box(
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight(),
) {
Column(
modifier = Modifier
.padding(horizontal = 32.dp)
.padding(top = 128.dp)
) {
Text(
text = "Masuk",
style = Typo.body,
fontWeight = FontWeight.Bold,
fontSize = 32.sp,
modifier = Modifier
.fillMaxWidth()
.padding(bottom = 2.dp)
)
Text(
text = "Harap masuk untuk melanjutkan",
modifier = Modifier
.fillMaxWidth()
.padding(bottom = 16.dp),
style = Typo.body,
fontSize = 14.sp,
color = Color.gray(500),
)
TextField(
label = "Email",
disabled = isLoading,
modifier = remember {
Modifier.padding(bottom = 12.dp)
},
control = form,
name = "email",
startIcon = Icons.Rounded.Email,
rules = remember {
listOf(
required()
)
},
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Email
)
)
TextField(
label = "Password",
disabled = isLoading,
modifier = Modifier.padding(bottom = 16.dp),
control = form,
name = "password",
startIcon = Icons.Rounded.Lock,
rules = remember {
listOf(
required(),
minLength(8),
)
},
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Password
),
visualTransformation = PasswordVisualTransformation()
)
Button(
disabled = isLoading,
onClick = remember(form, loginService, navController, focusManager) {
{
form.handleSubmit { it ->
form.clearFocus()
focusManager.clearFocus()
val email = it["email"]?.value as String
val password = it["password"]?.value as String
CoroutineScope(Dispatchers.IO).launch {
loginService.login(
body = AuthRepository.LoginBody(
email = email,
password = <PASSWORD>
)
) {
onSuccess {
profileViewModel
.setProfile(it.data)
}
onError {
Toast
.makeText(
context,
"Gagal saat login harap cek kembali email dan password",
Toast.LENGTH_LONG
)
.show()
}
}
}
}
}
},
modifier = Modifier
.fillMaxWidth()
) {
Text(
text = "Masuk",
color = Color.White,
style = Typo.body
)
}
Text(
text = remember {
buildAnnotatedString {
append("Belum punya akun? ")
withStyle(style = SpanStyle(color = Color.blue(500), fontWeight = FontWeight.Bold)) {
append("Daftar")
}
}
},
style = Typo.body,
textAlign = TextAlign.Center,
modifier = remember(navController) {
Modifier
.fillMaxWidth()
.padding(top = 10.dp)
.clickable {
navController.navigate("register")
}
}
)
}
}
}
| 0
|
Kotlin
|
0
| 1
|
6dc3a367acc255e7c2b1fe75543311b4bbb38b17
| 7,570
|
kasiry
|
MIT License
|
src/commonMain/kotlin/data/items/GauntletsOfTheRighteous.kt
|
marisa-ashkandi
| 332,658,265
| false
| null |
package `data`.items
import `data`.Constants
import `data`.buffs.Buffs
import `data`.itemsets.ItemSets
import `data`.model.Item
import `data`.model.ItemSet
import `data`.model.Socket
import `data`.model.SocketBonus
import character.Buff
import character.Stats
import kotlin.Array
import kotlin.Boolean
import kotlin.Double
import kotlin.Int
import kotlin.String
import kotlin.collections.List
import kotlin.js.JsExport
@JsExport
public class GauntletsOfTheRighteous : Item() {
public override var isAutoGenerated: Boolean = true
public override var id: Int = 27535
public override var name: String = "Gauntlets of the Righteous"
public override var itemLevel: Int = 115
public override var quality: Int = 3
public override var icon: String = "inv_gauntlets_29.jpg"
public override var inventorySlot: Int = 10
public override var itemSet: ItemSet? = ItemSets.byId(623)
public override var itemClass: Constants.ItemClass? = Constants.ItemClass.ARMOR
public override var itemSubclass: Constants.ItemSubclass? = Constants.ItemSubclass.PLATE
public override var allowableClasses: Array<Constants.AllowableClass>? = null
public override var minDmg: Double = 0.0
public override var maxDmg: Double = 0.0
public override var speed: Double = 0.0
public override var stats: Stats = Stats(
stamina = 22,
intellect = 20,
armor = 728,
defenseRating = 19.0
)
public override var sockets: Array<Socket> = arrayOf()
public override var socketBonus: SocketBonus? = null
public override var phase: Int = 1
public override val buffs: List<Buff> by lazy {
listOfNotNull(
Buffs.byIdOrName(14248, "Increase Spell Dam 21", this),
Buffs.byIdOrName(21628, "Increased Mana Regen", this)
)}
}
| 21
|
Kotlin
|
11
| 25
|
9cb6a0e51a650b5d04c63883cb9bf3f64057ce73
| 1,787
|
tbcsim
|
MIT License
|
node/src/test/kotlin/net/corda/node/utilities/certsigning/CertificateSignerTest.kt
|
evisoft
| 75,185,334
| true
|
{"Kotlin": 1706445, "Java": 130061, "Groovy": 16432, "Shell": 1653, "CSS": 636, "Batchfile": 84}
|
package net.corda.node.utilities.certsigning
import com.nhaarman.mockito_kotlin.any
import com.nhaarman.mockito_kotlin.eq
import com.nhaarman.mockito_kotlin.mock
import net.corda.core.crypto.SecureHash
import net.corda.core.crypto.X509Utilities
import net.corda.core.div
import net.corda.core.exists
import net.corda.core.readLines
import net.corda.node.services.config.NodeConfiguration
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import java.nio.file.Path
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
class CertificateSignerTest {
@Rule
@JvmField
val tempFolder: TemporaryFolder = TemporaryFolder()
@Test
fun buildKeyStore() {
val id = SecureHash.randomSHA256().toString()
val certs = arrayOf(X509Utilities.createSelfSignedCACert("CORDA_CLIENT_CA").certificate,
X509Utilities.createSelfSignedCACert("CORDA_INTERMEDIATE_CA").certificate,
X509Utilities.createSelfSignedCACert("CORDA_ROOT_CA").certificate)
val certService: CertificateSigningService = mock {
on { submitRequest(any()) }.then { id }
on { retrieveCertificates(eq(id)) }.then { certs }
}
val config = object : NodeConfiguration {
override val basedir: Path = tempFolder.root.toPath()
override val myLegalName: String = "me"
override val nearestCity: String = "London"
override val emailAddress: String = ""
override val devMode: Boolean = true
override val exportJMXto: String = ""
override val keyStorePassword: String = "<PASSWORD>"
override val trustStorePassword: String = "<PASSWORD>"
}
assertFalse(config.keyStorePath.exists())
assertFalse(config.trustStorePath.exists())
CertificateSigner(config, certService).buildKeyStore()
assertTrue(config.keyStorePath.exists())
assertTrue(config.trustStorePath.exists())
X509Utilities.loadKeyStore(config.keyStorePath, config.keyStorePassword).run {
assertTrue(containsAlias(X509Utilities.CORDA_CLIENT_CA_PRIVATE_KEY))
assertTrue(containsAlias(X509Utilities.CORDA_CLIENT_CA))
assertFalse(containsAlias(X509Utilities.CORDA_INTERMEDIATE_CA))
assertFalse(containsAlias(X509Utilities.CORDA_INTERMEDIATE_CA_PRIVATE_KEY))
assertFalse(containsAlias(X509Utilities.CORDA_ROOT_CA))
assertFalse(containsAlias(X509Utilities.CORDA_ROOT_CA_PRIVATE_KEY))
}
X509Utilities.loadKeyStore(config.trustStorePath, config.trustStorePassword).run {
assertFalse(containsAlias(X509Utilities.CORDA_CLIENT_CA_PRIVATE_KEY))
assertFalse(containsAlias(X509Utilities.CORDA_CLIENT_CA))
assertFalse(containsAlias(X509Utilities.CORDA_INTERMEDIATE_CA))
assertFalse(containsAlias(X509Utilities.CORDA_INTERMEDIATE_CA_PRIVATE_KEY))
assertTrue(containsAlias(X509Utilities.CORDA_ROOT_CA))
assertFalse(containsAlias(X509Utilities.CORDA_ROOT_CA_PRIVATE_KEY))
}
assertEquals(id, (config.certificatesPath / "certificate-request-id.txt").readLines { it.findFirst().get() })
}
}
| 1
|
Kotlin
|
1
| 1
|
4a9f5cafc1f2f09e8f612a09f30f9dfffd985a6c
| 3,291
|
corda
|
Apache License 2.0
|
app/src/main/kotlin/net/euse/calendar/services/SnoozeService.kt
|
saleo
| 123,436,418
| true
|
{"Kotlin": 816075, "Java": 66798}
|
package net.euse.calendar.services
import android.app.IntentService
import android.content.Intent
import net.euse.calendar.extensions.config
import net.euse.calendar.extensions.dbHelper
import net.euse.calendar.extensions.rescheduleReminder
import net.euse.calendar.helpers.EVENT_ID
class SnoozeService : IntentService("Snooze") {
override fun onHandleIntent(intent: Intent) {
val eventId = intent.getIntExtra(EVENT_ID, 0)
val event = dbHelper.getEventWithId(eventId)
rescheduleReminder(event, config.snoozeDelay)
}
}
| 26
|
Kotlin
|
0
| 0
|
9622eaa8afac50645b7de71689b82bb183917081
| 552
|
skcal
|
Apache License 2.0
|
zircon.core/src/jvmTest/kotlin/org/hexworks/zircon/integration/ButtonIntegrationTest.kt
|
mstaack
| 217,368,179
| true
|
{"Kotlin": 1445120, "Java": 79475}
|
package org.hexworks.zircon.integration
import org.hexworks.zircon.api.Components
import org.hexworks.zircon.api.Positions
import org.hexworks.zircon.api.Sizes
import org.hexworks.zircon.api.extensions.box
import org.hexworks.zircon.api.extensions.halfBlock
import org.hexworks.zircon.api.extensions.positionalAlignment
import org.hexworks.zircon.api.extensions.shadow
import org.hexworks.zircon.api.extensions.side
import org.hexworks.zircon.api.graphics.BoxType
import org.hexworks.zircon.api.screen.Screen
class ButtonIntegrationTest : ComponentIntegrationTestBase() {
override fun buildScreenContent(screen: Screen) {
val panel = Components.panel()
.withDecorations(box(title = "Buttons on panel"), shadow())
.withSize(Sizes.create(30, 28))
.withAlignment(positionalAlignment(29, 1))
.build()
screen.addComponent(panel)
val simpleBtn = Components.button()
.withText("Button")
.withDecorations(side())
.withAlignment(positionalAlignment(1, 3))
val boxedBtn = Components.button()
.withText("Boxed Button")
.withDecorations(box())
.withAlignment(positionalAlignment(1, 5))
val tooLongBtn = Components.button()
.withText("Too long name for button")
.withDecorations(box(), shadow())
.withAlignment(positionalAlignment(1, 9))
.withSize(Sizes.create(10, 4))
val overTheTopBtn = Components.button()
.withText("Over the top button")
.withDecorations(box(boxType = BoxType.DOUBLE), halfBlock(), shadow())
.withAlignment(positionalAlignment(1, 14))
val halfBlockBtn = Components.button()
.withText("Half block button")
.withDecorations(halfBlock(), shadow())
.withAlignment(positionalAlignment(Positions.create(1, 23)))
screen.addComponent(simpleBtn)
panel.addComponent(simpleBtn.withPosition(Positions.create(1, 1)).build())
screen.addComponent(boxedBtn)
panel.addComponent(boxedBtn.withPosition(Positions.create(1, 3)).build())
screen.addComponent(tooLongBtn)
panel.addComponent(tooLongBtn.withPosition(Positions.create(1, 7)).build())
screen.addComponent(overTheTopBtn)
panel.addComponent(overTheTopBtn.withPosition(Positions.create(1, 12)).build())
screen.addComponent(halfBlockBtn)
panel.addComponent(halfBlockBtn.withPosition(Positions.create(1, 21)).build())
}
}
| 0
| null |
0
| 0
|
81e071352eb5f1f601a692d8dc9e013c98a17a02
| 2,639
|
zircon
|
MIT License
|
src/main/kotlin/com/bloock/sdk/record/entity/RecordReceipt.kt
|
bloock
| 305,086,190
| false
| null |
package com.bloock.sdk.record.entity
class RecordReceipt(
val anchor: Int,
val client: String,
val record: String,
val status: String
)
| 0
|
Kotlin
|
0
| 0
|
80e7f0b2872cde532715ee4824815d0db76e32d5
| 153
|
bloock-sdk-kotlin
|
MIT License
|
idea-plugin/src/main/java/org/jetbrains/bunches/idea/vcs/SimpleCheckToolWindow.kt
|
JetBrains
| 126,407,654
| false
| null |
package org.jetbrains.bunches.idea.vcs
import com.intellij.icons.AllIcons
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.SimpleToolWindowPanel
import com.intellij.openapi.vcs.CheckinProjectPanel
import com.intellij.openapi.vcs.changes.Change
import com.intellij.openapi.vcs.changes.ChangeListChange
import com.intellij.openapi.vcs.changes.ChangeListManagerImpl
import com.intellij.openapi.vcs.changes.LocalChangeListImpl
import com.intellij.openapi.vcs.changes.ui.CommitChangeListDialog
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.wm.ToolWindow
import com.intellij.openapi.wm.ToolWindowContentUiType
import com.intellij.psi.PsiFile
import com.intellij.ui.PopupHandler
import com.intellij.ui.components.JBScrollPane
import org.jetbrains.bunches.idea.actions.ApplyChangesAction
import org.jetbrains.bunches.idea.actions.BunchCompareFilesAction
import org.jetbrains.bunches.idea.util.BunchFileUtils
import org.jetbrains.bunches.idea.util.BunchFileUtils.isBunchFile
import java.awt.GridLayout
import java.io.File
import javax.swing.JComponent
import javax.swing.JPanel
import javax.swing.JToolBar
import javax.swing.tree.DefaultMutableTreeNode
class SimpleCheckToolWindow(
private val toolWindow: ToolWindow,
forgottenFiles: Set<VirtualFile>,
all: Map<PsiFile, List<PsiFile>>,
private val checkInProjectPanel: CheckinProjectPanel
) {
private val allFiles = checkInProjectPanel.virtualFiles
private val project = checkInProjectPanel.project
private val mainChanges = checkInProjectPanel.selectedChanges.toList()
private val panel: SimpleToolWindowPanel = SimpleToolWindowPanel(false)
private val filesTree: ForgottenFilesTree = ForgottenFilesTree(
DefaultMutableTreeNode("root"),
forgottenFiles, all
)
val content: JComponent
get() = panel
init {
panel.apply {
toolbar = JToolBar()
setContent(JBScrollPane(filesTree).apply {
border = null
})
}
setToolBar()
setPopupMenu()
toolWindow.apply {
setDefaultContentUiType(ToolWindowContentUiType.TABBED)
setToHideOnEmptyContent(true)
}
}
private fun closeTab() {
val content = toolWindow.contentManager.getContent(panel) ?: return
toolWindow.contentManager.removeContent(content, true)
}
private fun setToolBar() {
val actionGroup = DefaultActionGroup()
actionGroup.addAction(CommitWithoutCheck()).setAsSecondary(false)
panel.toolbar = JPanel(GridLayout()).apply {
add(
ActionManager.getInstance()
.createActionToolbar(ActionPlaces.TOOLBAR, actionGroup, false).component
)
}
}
private fun inCommit(file: PsiFile): Boolean {
return file.virtualFile in allFiles
}
private fun isSelected(file: PsiFile): Boolean {
return file.virtualFile in filesTree.getSelected()
}
private fun setPopupMenu() {
val actionGroup = DefaultActionGroup().apply {
add(SetCheckedAction())
add(SetUncheckedAction())
addSeparator()
add(ActionManager.getInstance().getAction(IdeActions.ACTION_EDIT_SOURCE))
addSeparator()
add(CreateAndApplyAction())
add(DiffAction())
}
PopupHandler.installPopupHandler(filesTree, actionGroup, ActionPlaces.POPUP, ActionManager.getInstance())
}
private inner class CommitWithoutCheck :
AnAction("Commit", "Commit previously chosen and added files", AllIcons.Actions.Commit) {
init {
registerCustomShortcutSet(CustomShortcutSet.fromString("ctrl shift K"), panel)
}
override fun actionPerformed(e: AnActionEvent) {
val changeListManager = ChangeListManagerImpl.getInstanceImpl(project)
val changes = mainChanges.toMutableList()
val firstChange = (changes.firstOrNull() ?: return) as ChangeListChange
changes.addAll(filesTree.getSelected().mapNotNull { changeListManager.getChange(it) }.map {
ChangeListChange(
it,
firstChange.changeListName,
firstChange.changeListId
)
})
project.bunchFileCheckEnabled = false
if (CommitChangeListDialog.commitChanges(
project,
changes,
LocalChangeListImpl.Builder(project, firstChange.changeListName).setChanges(changes).build(),
null,
checkInProjectPanel.commitMessage
)
) {
closeTab()
BunchFileUtils.updateGitLog(project)
}
project.bunchFileCheckEnabled = true
}
}
private inner class SetCheckedAction :
AnAction("Add to commit", "Add all current changes to commit", AllIcons.Actions.Redo) {
init {
registerCustomShortcutSet(CommonShortcuts.ENTER, panel)
}
override fun actionPerformed(e: AnActionEvent) {
filesTree.getAllChosenFiles().forEach { filesTree.addSelected(it.virtualFile) }
}
private fun isAvailable(file: PsiFile): Boolean {
return !isSelected(file)
&& isBunchFile(file.virtualFile, project)
&& !inCommit(file)
}
override fun update(e: AnActionEvent) {
e.presentation.isEnabledAndVisible = filesTree.getAllChosenFiles().all { isAvailable(it) }
}
}
private inner class SetUncheckedAction :
AnAction("Remove from commit", "Remove all current changes from commit", AllIcons.Actions.Undo) {
init {
registerCustomShortcutSet(CommonShortcuts.ENTER, panel)
}
override fun actionPerformed(e: AnActionEvent) {
filesTree.getAllChosenFiles().forEach { filesTree.removeSelected(it.virtualFile) }
}
private fun isAvailable(file: PsiFile): Boolean {
return isSelected(file)
&& isBunchFile(file.virtualFile, project)
&& !inCommit(file)
}
override fun update(e: AnActionEvent) {
e.presentation.isEnabledAndVisible = filesTree.getAllChosenFiles().all { isAvailable(it) }
}
}
private inner class DiffAction : BunchCompareFilesAction() {
init {
val diffShortcutSet = ActionManager.getInstance()
.getAction("BunchCompareFilesActions").shortcutSet
registerCustomShortcutSet(diffShortcutSet, panel)
}
override fun getFile(e: AnActionEvent): VirtualFile? {
return filesTree.psiFile?.virtualFile
}
}
inner class CreateAndApplyAction : ApplyChangesAction() {
init {
registerCustomShortcutSet(CommonShortcuts.ALT_ENTER, panel)
}
override fun update(e: AnActionEvent) {
val file = filesTree.psiFile?.virtualFile ?: return
e.presentation.isEnabled = !(getChanges(file, project) == null || isBunchFile(file, project))
}
override fun getChanges(file: VirtualFile, project: Project): Change? {
return mainChanges.firstOrNull { it.affectsFile(File(file.path)) }
?: super.getChanges(file, project)
}
override fun actionPerformed(e: AnActionEvent) {
val file = filesTree.psiFile ?: return
val affected = applyMainToAll(file.virtualFile, project)
affected.forEach { filesTree.addSelected(it) }
showInfoBalloon(affected.mapNotNull { it.extension }, file.virtualFile, project)
}
}
}
| 12
|
Kotlin
|
19
| 20
|
c19456770115994092b796fa177113abb096bb14
| 7,871
|
bunches
|
Apache License 2.0
|
src/ar/mangarose/src/eu/kanade/tachiyomi/extension/ar/mangarose/MangaRose.kt
|
komikku-app
| 720,497,299
| false
|
{"Kotlin": 6775539, "JavaScript": 2160}
|
package eu.kanade.tachiyomi.extension.ar.mangarose
import eu.kanade.tachiyomi.multisrc.madara.Madara
import java.text.SimpleDateFormat
import java.util.Locale
class MangaRose : Madara(
"Manga Rose",
"https://mangarose.net",
"ar",
dateFormat = SimpleDateFormat("MMMM dd, yyyy", Locale("ar")),
)
| 22
|
Kotlin
|
8
| 97
|
7fc1d11ee314376fe0daa87755a7590a03bc11c0
| 312
|
komikku-extensions
|
Apache License 2.0
|
api/src/main/java/com/vk/sdk/api/media/dto/MediaPopupDto.kt
|
VKCOM
| 16,025,583
| false
| null |
/**
* The MIT License (MIT)
*
* Copyright (c) 2019 vk.com
*
* 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.
*/
// *********************************************************************
// THIS FILE IS AUTO GENERATED!
// DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING.
// *********************************************************************
package com.vk.sdk.api.media.dto
import com.google.gson.annotations.SerializedName
import com.vk.sdk.api.base.dto.BaseImageDto
import com.vk.sdk.api.base.dto.BaseLinkButtonDto
import kotlin.String
import kotlin.collections.List
/**
* @param title - Restriction title
* @param id - Popup id
* @param button - Restriction button
* @param buttons - Restriction button
* @param icons - Restriction icon
* @param musicSubscriptionEvent - Stats param
* @param text - Restriction text
* @param imageMode
* @param emojiIcons
*/
data class MediaPopupDto(
@SerializedName("title")
val title: String,
@SerializedName("id")
val id: String? = null,
@SerializedName("button")
val button: BaseLinkButtonDto? = null,
@SerializedName("buttons")
val buttons: List<BaseLinkButtonDto>? = null,
@SerializedName("icons")
val icons: List<BaseImageDto>? = null,
@SerializedName("music_subscription_event")
val musicSubscriptionEvent: String? = null,
@SerializedName("text")
val text: String? = null,
@SerializedName("image_mode")
val imageMode: MediaPopupDto.ImageModeDto? = null,
@SerializedName("emoji_icons")
val emojiIcons: String? = null
) {
enum class ImageModeDto(
val value: String
) {
@SerializedName("round")
ROUND("round"),
@SerializedName("small")
SMALL("small"),
@SerializedName("big")
BIG("big"),
@SerializedName("emoji")
EMOJI("emoji");
}
}
| 69
|
Kotlin
|
233
| 440
|
3dd6d9e3bc10ce9e77c3ea9331cc753f704f8f79
| 2,889
|
vk-android-sdk
|
MIT License
|
intellij-plugin/educational-core/src/com/jetbrains/edu/learning/ui/utils.kt
|
JetBrains
| 43,696,115
| false
|
{"Kotlin": 5014435, "Java": 42267, "Python": 19649, "HTML": 14893, "CSS": 10327, "JavaScript": 302, "Shell": 71}
|
package com.jetbrains.edu.learning.ui
import com.intellij.ide.ui.laf.darcula.ui.DarculaButtonUI
import com.intellij.ui.ClientProperty
import javax.swing.JButton
/**
* Makes the button blue like a default button in dialogs
*/
var JButton.isDefault: Boolean
get() = ClientProperty.isTrue(this, DarculaButtonUI.DEFAULT_STYLE_KEY)
set(value) {
if (value) {
ClientProperty.put(this, DarculaButtonUI.DEFAULT_STYLE_KEY, true)
}
else {
ClientProperty.remove(this, DarculaButtonUI.DEFAULT_STYLE_KEY)
}
}
| 7
|
Kotlin
|
49
| 150
|
9cec6c97d896f4485e76cf9a2a95f8a8dd21c982
| 533
|
educational-plugin
|
Apache License 2.0
|
common/src/main/kotlin/net/spaceeye/vsource/items/BaseTool.kt
|
SuperSpaceEye
| 751,999,893
| false
|
{"Kotlin": 78653, "Java": 7131}
|
package net.spaceeye.vsource.items
import net.minecraft.server.level.ServerLevel
import net.minecraft.world.InteractionHand
import net.minecraft.world.InteractionResultHolder
import net.minecraft.world.entity.player.Player
import net.minecraft.world.item.Item
import net.minecraft.world.item.ItemStack
import net.minecraft.world.level.ClipContext
import net.minecraft.world.level.Level
import net.minecraft.world.phys.BlockHitResult
import net.spaceeye.vsource.VSItems
import net.spaceeye.vsource.utils.Vector3d
//TODO find a way to detect if player it's a singular click or a button press
abstract class BaseTool: Item(Properties().tab(VSItems.TAB).stacksTo(1)) {
abstract fun activatePrimaryFunction(level: Level, player: Player, clipResult: BlockHitResult)
abstract fun resetState()
override fun use(
level: Level,
player: Player,
usedHand: InteractionHand
): InteractionResultHolder<ItemStack> {
if (player.isShiftKeyDown) { resetState() }
val clipResult = level.clip(
ClipContext(
player.eyePosition,
(Vector3d(player.eyePosition)
+ Vector3d(player.lookAngle).snormalize() * 100).toMCVec3(),
ClipContext.Block.COLLIDER,
ClipContext.Fluid.NONE,
null
)
)
activatePrimaryFunction(level, player, clipResult)
return super.use(level, player, usedHand)
}
}
| 0
|
Kotlin
|
0
| 0
|
f873ddc802e7360c96a4e7b5ea584cca0db7a94a
| 1,474
|
VSource
|
MIT License
|
services/csm.cloud.project.statistics/src/main/kotlin/com/bosch/pt/csm/cloud/projectmanagement/statistics/facade/listener/ProjectEventListenerImpl.kt
|
boschglobal
| 805,348,245
| false
|
{"Kotlin": 13156190, "HTML": 274761, "Go": 184388, "HCL": 158560, "Shell": 117666, "Java": 52634, "Python": 51306, "Dockerfile": 10348, "Vim Snippet": 3969, "CSS": 344}
|
/*
* ************************************************************************
*
* Copyright: Robert Bosch Power Tools GmbH, 2018 - 2021
*
* ************************************************************************
*/
package com.bosch.pt.csm.cloud.projectmanagement.statistics.facade.listener
import com.bosch.pt.csm.cloud.common.ExcludeFromCodeCoverage
import com.bosch.pt.csm.cloud.common.kafka.logConsumption
import com.bosch.pt.csm.cloud.common.model.key.EventMessageKey
import com.bosch.pt.csm.cloud.projectmanagement.project.event.listener.ProjectEventListener
import datadog.trace.api.Trace
import org.apache.avro.specific.SpecificRecordBase
import org.apache.kafka.clients.consumer.ConsumerRecord
import org.slf4j.LoggerFactory
import org.springframework.context.annotation.Profile
import org.springframework.kafka.annotation.KafkaListener
import org.springframework.kafka.support.Acknowledgment
import org.springframework.stereotype.Component
@Profile("!kafka-project-listener-disabled")
@Component
class ProjectEventListenerImpl(
private val projectEventToStateProcessor: ProjectEventToStateProcessor
) : ProjectEventListener {
@Trace
@KafkaListener(topics = ["#{kafkaTopicConfiguration.getTopicForChannel('project')}"])
override fun listenToProjectEvents(
record: ConsumerRecord<EventMessageKey, SpecificRecordBase?>,
ack: Acknowledgment
) {
LOGGER.logConsumption(record)
val message = record.value()
projectEventToStateProcessor.updateStateFromProjectEvent(message)
ack.acknowledge()
}
/*
* workaround to avoid illegal reflection access warning
* by spring proxies (due to java 11)
*/
@ExcludeFromCodeCoverage
override fun toString() = this.javaClass.name + "@" + Integer.toHexString(this.hashCode())
companion object {
private val LOGGER = LoggerFactory.getLogger(ProjectEventListenerImpl::class.java)
}
}
| 0
|
Kotlin
|
3
| 9
|
9f3e7c4b53821bdfc876531727e21961d2a4513d
| 1,902
|
bosch-pt-refinemysite-backend
|
Apache License 2.0
|
app/src/main/java/droiddevelopers254/droidconke/repository/SpeakersRepo.kt
|
droidconKE
| 132,411,780
| false
| null |
package droiddevelopers254.droidconke.repository
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.FirebaseFirestoreException
import com.google.firebase.firestore.ktx.toObjects
import droiddevelopers254.droidconke.datastates.Result
import droiddevelopers254.droidconke.models.SpeakersModel
import droiddevelopers254.droidconke.utils.await
class SpeakersRepo(private val firestore: FirebaseFirestore) {
suspend fun getSpeakersInfo(speakerId: Int): Result<List<SpeakersModel>> {
return try {
val snapshot = firestore.collection("speakers")
.whereEqualTo("id", speakerId)
.get()
.await()
Result.Success(snapshot.toObjects<SpeakersModel>())
} catch (e: FirebaseFirestoreException) {
Result.Error(e.message)
}
}
}
| 3
| null |
25
| 21
|
1c82965bf1fb0737ad1420ef4e4f0c96681f18a0
| 818
|
droidconKE
|
MIT License
|
android/src/main/kotlin/vn/com/extremevn/flutter_amplify_sdk/AmplifyMethodChannelHandler.kt
|
extremevn
| 348,202,216
| false
|
{"Dart": 56458, "Kotlin": 39814, "Swift": 37106, "Ruby": 4327, "Objective-C": 2930}
|
/*
MIT License
Copyright (c) [2020] Extreme Viet Nam
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 vn.com.extremevn.flutter_amplify_sdk
import android.app.Activity
import android.content.Context
import android.net.ConnectivityManager
import android.util.Log
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
class AmplifyMethodChannelHandler(private val context: Context, private val activity: Activity) : MethodChannel.MethodCallHandler {
companion object {
private const val NETWORK_ERROR_CODE = "NetworkException"
private const val NETWORK_ERROR_TAG = "Amplify Network"
private const val NETWORK_ERROR_MESSAGE = "Error checking network connection"
}
override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
if (!isNetworkConnected(context)) {
Log.e(NETWORK_ERROR_TAG, NETWORK_ERROR_MESSAGE)
result.error(NETWORK_ERROR_CODE, NETWORK_ERROR_MESSAGE, "")
return
}
when (call.method) {
"getPlatformVersion" -> result.success("Android ${android.os.Build.VERSION.RELEASE}")
"initialize" -> AmplifyImplement.initialize(context, result)
"signUp" -> AmplifyImplement.signUp(result, call.argument<String>("username")!!,
call.argument<String>("password")!!,
call.argument<Map<String, String>>("userAttributes")!!)
"confirmSignUp" -> AmplifyImplement.confirmSignUp(
result,
call.argument<String>("username")!!,
call.argument<String>("code")!!
)
"signIn" -> AmplifyImplement.signIn(
result,
call.argument<String>("username")!!,
call.argument<String>("password")!!
)
"resendSignUpCode" -> AmplifyImplement.resendSignUpCode(
result,
call.argument<String>("username")!!
)
"resetPassword" -> AmplifyImplement.resetPassword(
result,
call.argument<String>("username")!!
)
"confirmResetPassword" -> AmplifyImplement.confirmResetPassword(
result,
call.argument<String>("newPassword")!!,
call.argument<String>("confirmationCode")!!
)
"changePassword" -> AmplifyImplement.changePassword(
result,
call.argument<String>("oldPassword")!!,
call.argument<String>("newPassword")!!
)
"signOut" -> AmplifyImplement.signOut(result)
"signOutGlobally" -> AmplifyImplement.signOutGlobally(result)
"getTokens" -> AmplifyImplement.getTokens(result)
"getCredentials" -> AmplifyImplement.getCredentials(result)
"getIdentityId" -> AmplifyImplement.getIdentityId(result)
"isSignedIn" -> AmplifyImplement.isSignedIn(result)
"getUsername" -> AmplifyImplement.getUsername(result)
"postApi" -> AmplifyImplement.postApi(
result,
call.argument<String>("apiName")!!,
call.argument<String>("tokenUser")!!,
call.argument<String>("path")!!,
call.argument<Map<String, Any>>("body")!!
)
"putApi" -> AmplifyImplement.putApi(
result,
call.argument<String>("apiName")!!,
call.argument<String>("tokenUser")!!,
call.argument<String>("path")!!,
call.argument<Map<String, Any>>("body")!!
)
"getApi" -> AmplifyImplement.getApi(
result,
call.argument<String>("apiName")!!,
call.argument<String>("tokenUser")!!,
call.argument<String>("path")!!,
call.argument<Map<String, Any>>("body")!!
)
"deleteApi" -> AmplifyImplement.deleteApi(
result,
call.argument<String>("apiName")!!,
call.argument<String>("tokenUser")!!,
call.argument<String>("path")!!,
call.argument<Map<String, Any>>("body")!!
)
"authenWithSocialNetwork" -> AmplifyImplement.authenWithSocialNetwork(result, activity, call.argument<String>("type")!!)
"updateUserPhone" -> AmplifyImplement.updateUserPhone(
result,
call.argument<String>("userPhone")!!
)
"confirmUpdateUserPhone" -> AmplifyImplement.confirmUpdateUserPhone(
result,
call.argument<String>("confirmCode")!!
)
"resendConfirmCodeUpdateUserPhone" -> AmplifyImplement.resendConfirmCodeUpdateUserPhone(
result
)
else -> result.notImplemented()
}
}
private fun isNetworkConnected(context: Context): Boolean {
val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?
return cm!!.activeNetworkInfo != null && cm.activeNetworkInfo.isConnected
}
}
| 0
|
Dart
|
2
| 7
|
4beb8bddca117610e02c73733a9805457bf9cf5c
| 6,332
|
famplify
|
MIT License
|
common/components/screen-editor/src/commonMain/kotlin/io/stardewvalleydesigner/component/editor/modules/toolkit/tools/Drag.kt
|
AzimMuradov
| 377,785,069
| false
|
{"Kotlin": 1064148, "HTML": 1659, "JavaScript": 461}
|
/*
* Copyright 2021-2024 Azim Muradov
*
* 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.stardewvalleydesigner.component.editor.modules.toolkit.tools
import io.stardewvalleydesigner.component.editor.modules.toolkit.*
import io.stardewvalleydesigner.engine.*
import io.stardewvalleydesigner.engine.entity.Entity
import io.stardewvalleydesigner.engine.geometry.*
import io.stardewvalleydesigner.engine.layer.*
import io.stardewvalleydesigner.engine.layers.flatten
import io.stardewvalleydesigner.engine.layout.respects
import kotlin.properties.Delegates
class Drag(private val engine: EditorEngine) : Tool {
private lateinit var initMovedEntities: List<PlacedEntity<*>>
private var start: Coordinate by Delegates.notNull()
private var isSelected: Boolean by Delegates.notNull()
private lateinit var heldEntities: List<PlacedEntity<*>>
override fun start(
coordinate: Coordinate,
currentEntity: Entity<*>?,
selectedEntities: List<PlacedEntity<*>>,
visLayers: Set<LayerType<*>>,
): ActionReturn? {
start = coordinate
isSelected = coordinate in selectedEntities.coordinates
initMovedEntities = if (isSelected) {
engine.removeAll(selectedEntities)
} else {
engine.remove(coordinate, visLayers).flatten()
}
heldEntities = initMovedEntities
return if (heldEntities.isNotEmpty()) {
ActionReturn(
toolkit = ToolkitState.Drag.Point.Acting(heldEntities),
currentEntity = currentEntity,
selectedEntities = heldEntities
)
} else {
null
}
}
override fun keep(
coordinate: Coordinate,
currentEntity: Entity<*>?,
selectedEntities: List<PlacedEntity<*>>,
visLayers: Set<LayerType<*>>,
): ActionReturn {
heldEntities = initMovedEntities
.asSequence()
.map { it.copy(place = it.place + (coordinate - start)) }
.filter { it respects engine.layout }
.toList()
return ActionReturn(
toolkit = ToolkitState.Drag.Point.Acting(heldEntities),
currentEntity = currentEntity,
selectedEntities = heldEntities
)
}
override fun end(
currentEntity: Entity<*>?,
selectedEntities: List<PlacedEntity<*>>,
visLayers: Set<LayerType<*>>,
): ActionReturn {
engine.putAll(heldEntities)
return ActionReturn(
toolkit = ToolkitState.Drag.Point.Idle,
currentEntity = currentEntity,
selectedEntities = if (isSelected) heldEntities else emptyList()
)
}
override fun dispose() {
initMovedEntities = emptyList()
start = Coordinate.ZERO
isSelected = false
heldEntities = emptyList()
}
}
| 23
|
Kotlin
|
1
| 5
|
21e1fe7d4d5aa472e7aeb321b943b991d4fb58b9
| 3,403
|
stardew-valley-designer
|
Apache License 2.0
|
src/org/jetbrains/r/console/jobs/RRunJobDialog.kt
|
JetBrains
| 214,212,060
| 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.r.console.jobs
import com.intellij.openapi.application.invokeLater
import com.intellij.openapi.ui.DialogPanel
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.ui.TextFieldWithBrowseButton
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.ui.DocumentAdapter
import com.intellij.ui.layout.*
import org.jetbrains.concurrency.runAsync
import org.jetbrains.r.RBundle
import org.jetbrains.r.interpreter.RInterpreter
import org.jetbrains.r.interpreter.isLocal
import javax.swing.DefaultComboBoxModel
import javax.swing.JComponent
import javax.swing.event.DocumentEvent
import kotlin.reflect.KMutableProperty0
class RRunJobDialog(private val interpreter: RInterpreter, private val defaultScript: VirtualFile?,
private val defaultWorkingDirectory: String) :
DialogWrapper(interpreter.project, null, true, IdeModalityType.IDE) {
private val project = interpreter.project
private val panel: DialogPanel
enum class PathType {
LOCAL {
override fun toString() = "Local R Script"
},
REMOTE {
override fun toString() = "Remote R Script"
}
}
private var scriptPathType = PathType.LOCAL
private var scriptPathLocal: String = ""
private var scriptPathRemote: String = ""
private var workingDirectory: String = defaultWorkingDirectory
private var runWithGlobalEnvironment: Boolean = false
private var exportGlobalEnvPolicy: ExportGlobalEnvPolicy = ExportGlobalEnvPolicy.DO_NO_EXPORT
init {
if (defaultScript?.isInLocalFileSystem == true) {
scriptPathLocal = defaultScript.path
} else if (!interpreter.isLocal() && defaultScript != null) {
interpreter.getFilePathAtHost(defaultScript)?.let {
scriptPathType = PathType.REMOTE
scriptPathRemote = it
}
}
panel = createDialogPanel()
setTitle(RBundle.message("jobs.dialog.title"))
setOKButtonText(RBundle.message("jobs.dialog.ok.button.text"))
init()
}
override fun createCenterPanel(): JComponent = panel.also { updateOkAction() }
private fun createDialogPanel(): DialogPanel =
panel {
row { label(RBundle.message("jobs.dialog.label.script.path")) }
row {
cell {
if (interpreter.isLocal()) {
label(RBundle.message("jobs.dialog.label.r.script")).withLargeLeftGap()
textFieldWithBrowseButton().addTextChangedListener(::scriptPathLocal)
} else {
val comboBox = comboBox(DefaultComboBoxModel(arrayOf(PathType.LOCAL, PathType.REMOTE)), ::scriptPathType).component
val localField = textFieldWithBrowseButton().addTextChangedListener(::scriptPathLocal).component
val remoteField = component(interpreter.createFileChooserForHost()).addTextChangedListener(::scriptPathRemote)
.withLeftGap(0).component
val listener = {
localField.isVisible = comboBox.item == PathType.LOCAL
remoteField.isVisible = comboBox.item == PathType.REMOTE
}
comboBox.addActionListener {
listener()
updateOkAction()
}
listener()
}
}
}
row {
cell {
label(RBundle.message("jobs.dialog.label.working.directory")).withLargeLeftGap()
component(interpreter.createFileChooserForHost(defaultWorkingDirectory, true)).addTextChangedListener(::workingDirectory)
}
}
row { label(RBundle.message("jobs.dialog.label.environments")) }
row {
checkBox(RBundle.message("jobs.dialog.checkbox.copy.global.env"), ::runWithGlobalEnvironment).withLargeLeftGap()
}
row {
cell {
label(RBundle.message("jobs.dialog.label.upon.completion")).withLargeLeftGap()
comboBox(DefaultComboBoxModel<ExportGlobalEnvPolicy>(
arrayOf(ExportGlobalEnvPolicy.DO_NO_EXPORT, ExportGlobalEnvPolicy.EXPORT_TO_GLOBAL_ENV,
ExportGlobalEnvPolicy.EXPORT_TO_VARIABLE)),
::exportGlobalEnvPolicy)
}
}
}
private fun CellBuilder<TextFieldWithBrowseButton>.addTextChangedListener(prop: KMutableProperty0<String>? = null):
CellBuilder<TextFieldWithBrowseButton> {
if (prop != null) {
component.text = prop.get()
}
component.textField.document.addDocumentListener(object : DocumentAdapter() {
override fun textChanged(e: DocumentEvent) {
prop?.set(component.text)
updateOkAction()
}
})
return this
}
override fun doOKAction() {
panel.apply()
runAsync {
val (script, scriptPath) = when (scriptPathType) {
PathType.LOCAL -> LocalFileSystem.getInstance().findFileByPath(scriptPathLocal) to scriptPathLocal
PathType.REMOTE -> interpreter.findFileByPathAtHost(scriptPathRemote) to scriptPathRemote
}
if (script == null) {
invokeLater {
Messages.showErrorDialog(project, RBundle.message("jobs.dialog.file.not.found.message", scriptPath),
RBundle.message("jobs.dialog.file.not.found.title"))
}
} else {
val task = RJobTask(script, workingDirectory, runWithGlobalEnvironment, exportGlobalEnvPolicy)
RJobRunner.getInstance(project).runRJob(task)
}
}
super.doOKAction()
}
private fun updateOkAction() {
panel.apply()
isOKActionEnabled = workingDirectory.isNotBlank() && when (scriptPathType) {
PathType.LOCAL -> scriptPathLocal.isNotBlank()
PathType.REMOTE -> scriptPathRemote.isNotBlank()
}
}
}
| 1
|
Kotlin
|
9
| 49
|
ab1d4fae83d1621533d14c6870f590d90039967a
| 5,833
|
Rplugin
|
Apache License 2.0
|
scribe/src/main/java/dev/aspirasoft/scribe/Pen.kt
|
aspirasoft
| 330,161,229
| false
| null |
package dev.aspirasoft.scribe
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.PointF
import android.text.TextPaint
import dev.aspirasoft.scribe.text.FontStyle
import dev.aspirasoft.scribe.text.ParagraphStyle
/**
* @author saifkhichi96
* @since 1.0.0
*/
internal class Pen(private val ix: Float, private val iy: Float) : TextPaint() {
private var breakDirty = false
private var cursor = PointF(ix, iy)
val x get() = cursor.x
val y get() = cursor.y
var currentStyle: ParagraphStyle = ParagraphStyle()
set(value) {
field = value
typeface = value.font
textSize = value.fontSize
isFakeBoldText = value.fontStyle == FontStyle.BOLD || value.fontStyle == FontStyle.BOLD_ITALIC
if (value.fontStyle == FontStyle.ITALIC || value.fontStyle == FontStyle.BOLD_ITALIC) {
textSkewX = -0.25f
} else {
textSkewX = 0f
}
}
init {
this.color = Color.BLACK
}
fun writeOnCanvas(text: String, canvas: Canvas) {
canvas.drawText(text, cursor.x, cursor.y, this)
}
fun moveToNextLine() {
moveTo(ix, y + (textSize + 2f) * currentStyle.lineSpacing)
breakDirty = true
}
fun moveToNextParagraph() {
if (breakDirty) {
moveTo(ix, y + currentStyle.paragraphSpacing)
} else {
moveTo(ix, y + textSize + currentStyle.paragraphSpacing)
}
breakDirty = false
}
fun move(dx: Float, dy: Float) {
cursor.x += dx
cursor.y += dy
}
fun resetPosition() {
moveTo(ix, iy)
}
private fun moveTo(x: Float, y: Float) {
cursor.x = x
cursor.y = y
}
}
| 0
|
Kotlin
|
0
| 0
|
53f62ebc40515228090a04d6123fd599132360dc
| 1,784
|
scribe
|
MIT License
|
src/commonMain/kotlin/data/items/TouchOfInspiration.kt
|
marisa-ashkandi
| 332,658,265
| false
| null |
package `data`.items
import `data`.Constants
import `data`.buffs.Buffs
import `data`.model.Item
import `data`.model.ItemSet
import `data`.model.Socket
import `data`.model.SocketBonus
import character.Buff
import character.Stats
import kotlin.Array
import kotlin.Boolean
import kotlin.Double
import kotlin.Int
import kotlin.String
import kotlin.collections.List
import kotlin.js.JsExport
@JsExport
public class TouchOfInspiration : Item() {
public override var isAutoGenerated: Boolean = true
public override var id: Int = 32350
public override var name: String = "Touch of Inspiration"
public override var itemLevel: Int = 141
public override var quality: Int = 4
public override var icon: String = "inv_misc_gem_ebondraenite_02.jpg"
public override var inventorySlot: Int = 23
public override var itemSet: ItemSet? = null
public override var itemClass: Constants.ItemClass? = Constants.ItemClass.ARMOR
public override var itemSubclass: Constants.ItemSubclass? = Constants.ItemSubclass.MISC
public override var allowableClasses: Array<Constants.AllowableClass>? = null
public override var minDmg: Double = 0.0
public override var maxDmg: Double = 0.0
public override var speed: Double = 0.0
public override var stats: Stats = Stats(
stamina = 24,
intellect = 21
)
public override var sockets: Array<Socket> = arrayOf()
public override var socketBonus: SocketBonus? = null
public override val buffs: List<Buff> by lazy {
listOfNotNull(
Buffs.byIdOrName(18040, "Increase Healing 64", this),
Buffs.byIdOrName(21635, "Increased Mana Regen", this)
)}
}
| 21
| null |
11
| 25
|
9cb6a0e51a650b5d04c63883cb9bf3f64057ce73
| 1,654
|
tbcsim
|
MIT License
|
jetbrains-core/src/software/aws/toolkits/jetbrains/services/telemetry/ClientMetadata.kt
|
JetBrains
| 223,485,227
| false
| null |
// Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.aws.toolkits.jetbrains.services.telemetry
import com.intellij.openapi.application.ApplicationInfo
import com.intellij.openapi.application.ApplicationNamesInfo
import com.intellij.openapi.util.SystemInfo
import software.amazon.awssdk.services.toolkittelemetry.model.AWSProduct
import software.aws.toolkits.jetbrains.AwsToolkit
import software.aws.toolkits.jetbrains.settings.AwsSettings
data class ClientMetadata(
val productName: AWSProduct = AWSProduct.AWS_TOOLKIT_FOR_JET_BRAINS,
val productVersion: String = AwsToolkit.PLUGIN_VERSION,
val clientId: String = AwsSettings.getInstance().clientId.toString(),
val parentProduct: String = ApplicationNamesInfo.getInstance().fullProductNameWithEdition,
val parentProductVersion: String = ApplicationInfo.getInstance().build.baselineVersion.toString(),
val os: String = SystemInfo.OS_NAME,
val osVersion: String = SystemInfo.OS_VERSION
) {
companion object {
val DEFAULT_METADATA = ClientMetadata()
}
}
| 6
| null |
4
| 9
|
ccee3307fe58ad48f93cd780d4378c336ee20548
| 1,126
|
aws-toolkit-jetbrains
|
Apache License 2.0
|
src/main/kotlin/schemact/domain/StaticWebsite.kt
|
typedpath
| 839,785,725
| false
|
{"Kotlin": 95991, "Shell": 131}
|
package schemact.domain
class StaticWebsite(val name: String, val description: String, val functionClients: List<FunctionClient> = mutableListOf(),
init: StaticWebsite.() -> Unit = {}) {
class BucketName : StringType(maxLength = 100) {
init {
isFromInfrastructure = true
}
}
init {
init()
}
fun client(function: Function, language: Language) {
(functionClients as MutableList).add(FunctionClient(function, language))
}
}
| 0
|
Kotlin
|
0
| 0
|
3a11a52204b6d4cecd83029a216a2d01837c5359
| 518
|
schemact4
|
Apache License 2.0
|
apzkr-pzpi-21-11-kokhanevych-pavlo/Task4-MobileClient/src/main/java/com/animal/hotel/presentation/ui/fragments/user/current_list/feeding_list/ListFeedingFragment.kt
|
NureKokhanevychPavlo
| 810,819,177
| false
|
{"Kotlin": 196074, "Java": 178994, "C++": 2061}
|
package com.animal.hotel.presentation.ui.fragments.user.current_list.feeding_list
import android.os.Bundle
import android.view.View
import androidx.fragment.app.viewModels
import androidx.lifecycle.flowWithLifecycle
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import androidx.recyclerview.widget.LinearLayoutManager
import com.animal.hotel.databinding.FragmentListFeedingBinding
import com.animal.hotel.domain.models.user.ScheduleFeedResponse
import com.animal.hotel.presentation.ui.base.BaseFragment
import com.animal.hotel.presentation.ui.fragments.user.current_list.feeding_list.adapter.FeedingAdapter
import com.animal.hotel.presentation.ui.interfaces.FeedingAdapterListener
import com.animal.hotel.presentation.ui.models.ScheduleFeedResponseUI
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
@AndroidEntryPoint
class ListFeedingFragment: BaseFragment<FragmentListFeedingBinding>(FragmentListFeedingBinding::inflate) {
private val viewModel: ListFeedingViewModel by viewModels()
private val args: ListFeedingFragmentArgs by navArgs()
private val feedingAdapter by lazy {
FeedingAdapter(
listener = object : FeedingAdapterListener {
override fun onItemClick(scheduleFeedResponse: ScheduleFeedResponse) {
val direction =
ListFeedingFragmentDirections.actionListFeedingFragmentToEditFeedingFragmentDialog(ScheduleFeedResponseUI.toScheduleFeedResponseUI(scheduleFeedResponse))
findNavController().navigate(direction)
}
}
)
}
override fun onStart() {
super.onStart()
viewModel.scheduleFeeding.flowWithLifecycle(viewLifecycleOwner.lifecycle)
.onEach { data ->
feedingAdapter.submitList(data)
}
.launchIn(viewLifecycleOwner.lifecycleScope)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewModel.getScheduleFeeding(args.rentId)
setupRecyclerView()
}
private fun setupRecyclerView() {
binding.recyclerFoodSchedule.adapter = feedingAdapter
binding.recyclerFoodSchedule.layoutManager = LinearLayoutManager(requireContext())
}
override fun setListeners() {
super.setListeners()
binding.buttonBack.setOnClickListener{findNavController().navigateUp()}
}
}
| 0
|
Kotlin
|
0
| 0
|
7ccf454ca73913ea72011b5322558e130f6b525f
| 2,604
|
apzkr-pzpi-21-11-kokhanevych-pavlo
|
Apache License 2.0
|
kotlinx-coroutines-core/common/src/flow/Migration.kt
|
hitherejoe
| 258,154,989
| true
|
{"Kotlin": 2640560, "Java": 30547, "CSS": 8215, "Shell": 3332, "JavaScript": 2529, "Ruby": 1932, "HTML": 1675, "Prolog": 422}
|
/*
* Copyright 2016-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
@file:JvmMultifileClass
@file:JvmName("FlowKt")
@file:Suppress("unused", "DeprecatedCallableAddReplaceWith", "UNUSED_PARAMETER")
package kotlinx.coroutines.flow
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.internal.*
import kotlinx.coroutines.flow.internal.unsafeFlow
import kotlin.coroutines.*
import kotlin.jvm.*
/**
* **GENERAL NOTE**
*
* These deprecations are added to improve user experience when they will start to
* search for their favourite operators and/or patterns that are missing or renamed in Flow.
* Deprecated functions also are moved here when they renamed. The difference is that they have
* a body with their implementation while pure stubs have [noImpl].
*/
private fun noImpl(): Nothing =
throw UnsupportedOperationException("Not implemented, should not be called")
/**
* `observeOn` has no direct match in [Flow] API because all terminal flow operators are suspending and
* thus use the context of the caller.
*
* For example, the following code:
* ```
* flowable
* .observeOn(Schedulers.io())
* .doOnEach { value -> println("Received $value") }
* .subscribe()
* ```
*
* has the following Flow equivalent:
* ```
* withContext(Dispatchers.IO) {
* flow.collect { value -> println("Received $value") }
* }
*
* ```
* @suppress
*/
@Deprecated(message = "Collect flow in the desired context instead", level = DeprecationLevel.ERROR)
public fun <T> Flow<T>.observeOn(context: CoroutineContext): Flow<T> = noImpl()
/**
* `publishOn` has no direct match in [Flow] API because all terminal flow operators are suspending and
* thus use the context of the caller.
*
* For example, the following code:
* ```
* flux
* .publishOn(Schedulers.io())
* .doOnEach { value -> println("Received $value") }
* .subscribe()
* ```
*
* has the following Flow equivalent:
* ```
* withContext(Dispatchers.IO) {
* flow.collect { value -> println("Received $value") }
* }
*
* ```
* @suppress
*/
@Deprecated(message = "Collect flow in the desired context instead", level = DeprecationLevel.ERROR)
public fun <T> Flow<T>.publishOn(context: CoroutineContext): Flow<T> = noImpl()
/**
* `subscribeOn` has no direct match in [Flow] API because [Flow] preserves its context and does not leak it.
*
* For example, the following code:
* ```
* flowable
* .map { value -> println("Doing map in IO"); value }
* .subscribeOn(Schedulers.io())
* .observeOn(Schedulers.computation())
* .doOnEach { value -> println("Processing $value in computation")
* .subscribe()
* ```
* has the following Flow equivalent:
* ```
* withContext(Dispatchers.Default) {
* flow
* .map { value -> println("Doing map in IO"); value }
* .flowOn(Dispatchers.IO) // Works upstream, doesn't change downstream
* .collect { value ->
* println("Processing $value in computation")
* }
* }
* ```
* Opposed to subscribeOn, it it **possible** to use multiple `flowOn` operators in the one flow
* @suppress
*/
@Deprecated(message = "Use flowOn instead", level = DeprecationLevel.ERROR)
public fun <T> Flow<T>.subscribeOn(context: CoroutineContext): Flow<T> = noImpl()
/**
* Flow analogue of `onErrorXxx` is [catch].
* Use `catch { emitAll(fallback) }`.
* @suppress
*/
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogue of 'onErrorXxx' is 'catch'. Use 'catch { emitAll(fallback) }'",
replaceWith = ReplaceWith("catch { emitAll(fallback) }")
)
public fun <T> Flow<T>.onErrorResume(fallback: Flow<T>): Flow<T> = noImpl()
/**
* Flow analogue of `onErrorXxx` is [catch].
* Use `catch { emitAll(fallback) }`.
* @suppress
*/
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogue of 'onErrorXxx' is 'catch'. Use 'catch { emitAll(fallback) }'",
replaceWith = ReplaceWith("catch { emitAll(fallback) }")
)
public fun <T> Flow<T>.onErrorResumeNext(fallback: Flow<T>): Flow<T> = noImpl()
/**
* `subscribe` is Rx-specific API that has no direct match in flows.
* One can use [launchIn] instead, for example the following:
* ```
* flowable
* .observeOn(Schedulers.io())
* .subscribe({ println("Received $it") }, { println("Exception $it happened") }, { println("Flowable is completed successfully") }
* ```
*
* has the following Flow equivalent:
* ```
* flow
* .onEach { value -> println("Received $value") }
* .onCompletion { cause -> if (cause == null) println("Flow is completed successfully") }
* .catch { cause -> println("Exception $cause happened") }
* .flowOn(Dispatchers.IO)
* .launchIn(myScope)
* ```
*
* Note that resulting value of [launchIn] is not used because the provided scope takes care of cancellation.
*
* Or terminal operators like [single] can be used from suspend functions.
* @suppress
*/
@Deprecated(
message = "Use launchIn with onEach, onCompletion and catch operators instead",
level = DeprecationLevel.ERROR
)
public fun <T> Flow<T>.subscribe(): Unit = noImpl()
/**
* Use [launchIn] with [onEach], [onCompletion] and [catch] operators instead.
* @suppress
*/
@Deprecated(
message = "Use launchIn with onEach, onCompletion and catch operators instead",
level = DeprecationLevel.ERROR
)public fun <T> Flow<T>.subscribe(onEach: suspend (T) -> Unit): Unit = noImpl()
/**
* Use [launchIn] with [onEach], [onCompletion] and [catch] operators instead.
* @suppress
*/
@Deprecated(
message = "Use launchIn with onEach, onCompletion and catch operators instead",
level = DeprecationLevel.ERROR
)public fun <T> Flow<T>.subscribe(onEach: suspend (T) -> Unit, onError: suspend (Throwable) -> Unit): Unit = noImpl()
/**
* Note that this replacement is sequential (`concat`) by default.
* For concurrent flatMap [flatMapMerge] can be used instead.
* @suppress
*/
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogue is named flatMapConcat",
replaceWith = ReplaceWith("flatMapConcat(mapper)")
)
public fun <T, R> Flow<T>.flatMap(mapper: suspend (T) -> Flow<R>): Flow<R> = noImpl()
/**
* Flow analogue of `concatMap` is [flatMapConcat].
* @suppress
*/
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogue of 'concatMap' is 'flatMapConcat'",
replaceWith = ReplaceWith("flatMapConcat(mapper)")
)
public fun <T, R> Flow<T>.concatMap(mapper: (T) -> Flow<R>): Flow<R> = noImpl()
/**
* Note that this replacement is sequential (`concat`) by default.
* For concurrent flatMap [flattenMerge] can be used instead.
* @suppress
*/
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogue of 'merge' is 'flattenConcat'",
replaceWith = ReplaceWith("flattenConcat()")
)
public fun <T> Flow<Flow<T>>.merge(): Flow<T> = noImpl()
/**
* Flow analogue of `flatten` is [flattenConcat].
* @suppress
*/
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogue of 'flatten' is 'flattenConcat'",
replaceWith = ReplaceWith("flattenConcat()")
)
public fun <T> Flow<Flow<T>>.flatten(): Flow<T> = noImpl()
/**
* Kotlin has a built-in generic mechanism for making chained calls.
* If you wish to write something like
* ```
* myFlow.compose(MyFlowExtensions.ignoreErrors()).collect { ... }
* ```
* you can replace it with
*
* ```
* myFlow.let(MyFlowExtensions.ignoreErrors()).collect { ... }
* ```
* @suppress
*/
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogue of 'compose' is 'let'",
replaceWith = ReplaceWith("let(transformer)")
)
public fun <T, R> Flow<T>.compose(transformer: Flow<T>.() -> Flow<R>): Flow<R> = noImpl()
/**
* Flow analogue of `skip` is [drop].
* @suppress
*/
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogue of 'skip' is 'drop'",
replaceWith = ReplaceWith("drop(count)")
)
public fun <T> Flow<T>.skip(count: Int): Flow<T> = noImpl()
/**
* Flow extension to iterate over elements is [collect].
* Foreach wasn't introduced deliberately to avoid confusion.
* Flow is not a collection, iteration over it may be not idempotent
* and can *launch* computations with side-effects.
* This behaviour is not reflected in [forEach] name.
* @suppress
*/
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogue of 'forEach' is 'collect'",
replaceWith = ReplaceWith("collect(block)")
)
public fun <T> Flow<T>.forEach(action: suspend (value: T) -> Unit): Unit = noImpl()
/**
* Flow has less verbose [scan] shortcut.
* @suppress
*/
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow has less verbose 'scan' shortcut",
replaceWith = ReplaceWith("scan(initial, operation)")
)
public fun <T, R> Flow<T>.scanFold(initial: R, @BuilderInference operation: suspend (accumulator: R, value: T) -> R): Flow<R> =
noImpl()
/**
* Flow analogue of `onErrorXxx` is [catch].
* Use `catch { emit(fallback) }`.
* @suppress
*/
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogue of 'onErrorXxx' is 'catch'. Use 'catch { emit(fallback) }'",
replaceWith = ReplaceWith("catch { emit(fallback) }")
)
// Note: this version without predicate gives better "replaceWith" action
public fun <T> Flow<T>.onErrorReturn(fallback: T): Flow<T> = noImpl()
/**
* Flow analogue of `onErrorXxx` is [catch].
* Use `catch { e -> if (predicate(e)) emit(fallback) else throw e }`.
* @suppress
*/
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogue of 'onErrorXxx' is 'catch'. Use 'catch { e -> if (predicate(e)) emit(fallback) else throw e }'",
replaceWith = ReplaceWith("catch { e -> if (predicate(e)) emit(fallback) else throw e }")
)
public fun <T> Flow<T>.onErrorReturn(fallback: T, predicate: (Throwable) -> Boolean = { true }): Flow<T> =
catch { e ->
// Note: default value is for binary compatibility with preview version, that is why it has body
if (!predicate(e)) throw e
emit(fallback)
}
/**
* Flow analogue of `startWith` is [onStart].
* Use `onStart { emit(value) }`.
* @suppress
*/
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogue of 'startWith' is 'onStart'. Use 'onStart { emit(value) }'",
replaceWith = ReplaceWith("onStart { emit(value) }")
)
public fun <T> Flow<T>.startWith(value: T): Flow<T> = noImpl()
/**
* Flow analogue of `startWith` is [onStart].
* Use `onStart { emitAll(other) }`.
* @suppress
*/
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogue of 'startWith' is 'onStart'. Use 'onStart { emitAll(other) }'",
replaceWith = ReplaceWith("onStart { emitAll(other) }")
)
public fun <T> Flow<T>.startWith(other: Flow<T>): Flow<T> = noImpl()
/**
* Flow analogue of `concatWith` is [onCompletion].
* Use `onCompletion { emit(value) }`.
* @suppress
*/
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogue of 'concatWith' is 'onCompletion'. Use 'onCompletion { emit(value) }'",
replaceWith = ReplaceWith("onCompletion { emit(value) }")
)
public fun <T> Flow<T>.concatWith(value: T): Flow<T> = noImpl()
/**
* Flow analogue of `concatWith` is [onCompletion].
* Use `onCompletion { emitAll(other) }`.
* @suppress
*/
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogue of 'concatWith' is 'onCompletion'. Use 'onCompletion { emitAll(other) }'",
replaceWith = ReplaceWith("onCompletion { emitAll(other) }")
)
public fun <T> Flow<T>.concatWith(other: Flow<T>): Flow<T> = noImpl()
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogue of 'combineLatest' is 'combine'",
replaceWith = ReplaceWith("this.combine(other, transform)")
)
public fun <T1, T2, R> Flow<T1>.combineLatest(other: Flow<T2>, transform: suspend (T1, T2) -> R): Flow<R> =
combine(this, other, transform)
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogue of 'combineLatest' is 'combine'",
replaceWith = ReplaceWith("combine(this, other, other2, transform)")
)
public inline fun <T1, T2, T3, R> Flow<T1>.combineLatest(
other: Flow<T2>,
other2: Flow<T3>,
crossinline transform: suspend (T1, T2, T3) -> R
) = combine(this, other, other2, transform)
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogue of 'combineLatest' is 'combine'",
replaceWith = ReplaceWith("combine(this, other, other2, other3, transform)")
)
public inline fun <T1, T2, T3, T4, R> Flow<T1>.combineLatest(
other: Flow<T2>,
other2: Flow<T3>,
other3: Flow<T4>,
crossinline transform: suspend (T1, T2, T3, T4) -> R
) = combine(this, other, other2, other3, transform)
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogue of 'combineLatest' is 'combine'",
replaceWith = ReplaceWith("combine(this, other, other2, other3, transform)")
)
public inline fun <T1, T2, T3, T4, T5, R> Flow<T1>.combineLatest(
other: Flow<T2>,
other2: Flow<T3>,
other3: Flow<T4>,
other4: Flow<T5>,
crossinline transform: suspend (T1, T2, T3, T4, T5) -> R
): Flow<R> = combine(this, other, other2, other3, other4, transform)
/**
* Delays the emission of values from this flow for the given [timeMillis].
* Use `onStart { delay(timeMillis) }`.
* @suppress
*/
@Deprecated(
level = DeprecationLevel.WARNING, // since 1.3.0, error in 1.4.0
message = "Use 'onStart { delay(timeMillis) }'",
replaceWith = ReplaceWith("onStart { delay(timeMillis) }")
)
public fun <T> Flow<T>.delayFlow(timeMillis: Long): Flow<T> = onStart { delay(timeMillis) }
/**
* Delays each element emitted by the given flow for the given [timeMillis].
* Use `onEach { delay(timeMillis) }`.
* @suppress
*/
@Deprecated(
level = DeprecationLevel.WARNING, // since 1.3.0, error in 1.4.0
message = "Use 'onEach { delay(timeMillis) }'",
replaceWith = ReplaceWith("onEach { delay(timeMillis) }")
)
public fun <T> Flow<T>.delayEach(timeMillis: Long): Flow<T> = onEach { delay(timeMillis) }
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Flow analogues of 'switchMap' are 'transformLatest', 'flatMapLatest' and 'mapLatest'",
replaceWith = ReplaceWith("this.flatMapLatest(transform)")
)
public fun <T, R> Flow<T>.switchMap(transform: suspend (value: T) -> Flow<R>): Flow<R> = flatMapLatest(transform)
| 0
|
Kotlin
|
0
| 1
|
d13087241e75a357d89f67f8f34476fd122eb56b
| 14,449
|
kotlinx.coroutines
|
Apache License 2.0
|
tmp/results/JS/BACKEND_tatno.kt
|
mandelshtamd
| 249,374,670
| 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}
|
fun foo(x: Int
) {
when (x) {
1, when (x) {
else -> 1
}
-> 1
}
}
| 1
| null |
1
| 1
|
da010bdc91c159492ae74456ad14d93bdb5fdd0a
| 78
|
bbfgradle
|
Apache License 2.0
|
library/src/main/java/com/chuckerteam/chucker/internal/support/AndroidCacheFileFactory.kt
|
CuriousNikhil
| 245,493,073
| true
|
{"Kotlin": 182841, "Shell": 799}
|
package com.chuckerteam.chucker.internal.support
import android.content.Context
import java.io.File
import java.util.concurrent.atomic.AtomicLong
internal class AndroidCacheFileFactory(
context: Context
) : FileFactory {
private val fileDir = context.cacheDir
private val uniqueIdGenerator = AtomicLong()
override fun create(): File {
return File(fileDir, "chucker-${uniqueIdGenerator.getAndIncrement()}")
}
}
| 0
|
Kotlin
|
0
| 1
|
d34919abd63fd28700141f3ad809d2e5c941a78c
| 441
|
chucker
|
Apache License 2.0
|
imagepicker/src/main/java/com/nguyenhoanglam/imagepicker/helper/LayoutManagerHelper.kt
|
nguyenhoanglam
| 64,893,333
| false
| null |
/*
* Copyright (C) 2023 Image Picker
* Author: <NAME> <<EMAIL>>
*/
package com.nguyenhoanglam.imagepicker.helper
import android.content.Context
import android.content.res.Configuration
import androidx.recyclerview.widget.GridLayoutManager
import com.nguyenhoanglam.imagepicker.model.GridCount
object LayoutManagerHelper {
fun newInstance(context: Context, gridCount: GridCount): GridLayoutManager {
val spanCount = getSpanCountForCurrentConfiguration(context, gridCount)
return GridLayoutManager(context, spanCount)
}
fun getSpanCountForCurrentConfiguration(context: Context, gridCount: GridCount): Int {
val isPortrait =
context.resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT
return if (isPortrait) gridCount.portrait else gridCount.landscape
}
}
| 21
|
Kotlin
|
154
| 550
|
7f1b1cc7254bb4d4c11af00f4a17aee782a8a3ef
| 842
|
ImagePicker
|
Apache License 2.0
|
spring-boot-oauth2-extended-authorization-server/authorization-server/src/main/kotlin/com/onlyteo/sandbox/service/JwkService.kt
|
onlyteo
| 692,402,826
| false
|
{"Kotlin": 148668, "TypeScript": 58482, "HTML": 40643, "CSS": 9955, "Shell": 627}
|
package com.onlyteo.sandbox.service
import com.nimbusds.jose.jwk.JWK
import com.nimbusds.jose.jwk.JWKSelector
import com.nimbusds.jose.jwk.source.JWKSource
import com.nimbusds.jose.proc.SecurityContext
import com.onlyteo.sandbox.properties.ApplicationProperties
class JwkService(
private val properties: ApplicationProperties,
private val keyService: KeyService
) : JWKSource<SecurityContext> {
override fun get(selector: JWKSelector, context: SecurityContext): MutableList<JWK> {
val jwkList = ArrayList<JWK>()
properties.security.keys.stream()
.map { key ->
keyService.readPrivateRsaKey(
key.keyId,
key.publicKeyLocation,
key.privateKeyLocation
)
}
.filter { key ->
selector.matcher.matches(key)
}
.forEach { key -> jwkList.add(key) }
return jwkList
}
}
| 0
|
Kotlin
|
0
| 0
|
433851708c6baa51ae39e947df704824820db3e6
| 966
|
spring-boot-sandbox
|
Apache License 2.0
|
sundowner-service/logic/src/main/kotlin/de/tkoeppel/sundowner/module/spotreviews/SpotReviewEndpoint.kt
|
tkoeppel
| 849,831,922
| false
|
{"Kotlin": 10633, "TypeScript": 3993, "Nix": 1580, "HTML": 753, "SCSS": 153}
|
package de.tkoeppel.sundowner.module.spotreviews
import de.tkoeppel.sundowner.api.SpotReviewsApi
class SpotReviewEndpoint : SpotReviewsApi {
// TODO
}
| 5
|
Kotlin
|
0
| 0
|
f28be88e170b01b0b4e16f73dafdbe25b07560e2
| 153
|
sundowner
|
Boost Software License 1.0
|
app/src/main/java/com/heyanle/easybangumi4/preferences/Preference.kt
|
easybangumiorg
| 413,723,669
| false
| null |
package com.heyanle.easybangumi4.preferences
import com.heyanle.okkv2.core.okkv
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
/**
* Created by HeYanLe on 2023/3/22 15:58.
* https://github.com/heyanLE
*/
// 无痕模式
object InPrivatePreferences: Preference<Boolean>("inPrivate", false)
// 平板模式
// 0 自动
// 1 关闭
// 2 开启
object PadModePreferences: Preference<Int>("padMode", 0)
// 兼容模式
object WebViewCompatiblePreferences: Preference<Boolean>("webViewCompatible", false)
open class Preference <T: Any> (
key: String,
def: T,
) {
private var okkv by okkv(key, def)
private val _stateFlow = MutableStateFlow<T>(okkv)
val stateFlow = _stateFlow.asStateFlow()
suspend fun set(value: T){
okkv = value
_stateFlow.emit(value)
}
}
| 7
|
Kotlin
|
21
| 924
|
3f0079d90e24d6a2a4d3fb358b1bc421ee4a9904
| 818
|
EasyBangumi
|
Apache License 2.0
|
reposilite-backend/src/main/kotlin/com/reposilite/statistics/DateIntervalProvider.kt
|
dzikoysk
| 96,474,388
| false
| null |
/*
* Copyright (c) 2022 dzikoysk
*
* 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.reposilite.statistics
import java.time.LocalDate
import java.time.temporal.TemporalAdjusters
import java.time.temporal.WeekFields
import java.util.Locale
fun createDateIntervalProvider(mode: String): DateIntervalProvider =
when (mode) {
"daily" -> DailyDateIntervalProvider
"weekly" -> WeeklyDateIntervalProvider
"monthly" -> MonthlyDateIntervalProvider
"yearly" -> YearlyDateIntervalProvider
else -> throw IllegalStateException("Unsupported date interval provided: $mode")
}
sealed interface DateIntervalProvider {
fun createDate(): LocalDate
}
internal object DailyDateIntervalProvider : DateIntervalProvider {
override fun createDate(): LocalDate =
LocalDate.now()
}
internal object WeeklyDateIntervalProvider : DateIntervalProvider {
private val firstDayOfWeek = WeekFields.of(Locale.getDefault()).firstDayOfWeek
override fun createDate(): LocalDate =
LocalDate.now().with(TemporalAdjusters.previousOrSame(firstDayOfWeek))
}
internal object MonthlyDateIntervalProvider : DateIntervalProvider {
override fun createDate(): LocalDate =
LocalDate.now().with(TemporalAdjusters.firstDayOfMonth())
}
internal object YearlyDateIntervalProvider : DateIntervalProvider {
override fun createDate(): LocalDate =
LocalDate.now().with(TemporalAdjusters.firstDayOfYear())
}
| 13
|
Kotlin
|
85
| 541
|
2d116b595c64c6b5a71b694ba6d044c40ef16b6a
| 1,993
|
reposilite
|
Apache License 2.0
|
colorpicker/src/main/java/com/jrummyapps/android/colorpicker/Compat.kt
|
tateisu
| 89,120,200
| false
|
{"Kotlin": 4306902, "Java": 324536, "Perl": 34567}
|
package com.jrummyapps.android.colorpicker
import android.os.Build
import android.os.Bundle
import android.os.Parcelable
inline fun <reified T : Parcelable> Bundle.getParcelableCompat(key: String) =
if (Build.VERSION.SDK_INT >= 33) {
getParcelable(key, T::class.java)
} else {
@Suppress("DEPRECATION")
getParcelable(key)
}
| 29
|
Kotlin
|
24
| 226
|
e57568a5b4e1657292831474b1a18b45784111ce
| 361
|
SubwayTooter
|
Apache License 2.0
|
core/src/commonMain/kotlin/work/socialhub/kslack/entity/event/StarRemovedEvent.kt
|
uakihir0
| 794,979,552
| false
|
{"Kotlin": 945304, "Ruby": 2164, "Shell": 2095, "Makefile": 316}
|
package work.socialhub.kslack.entity.event
import com.github.seratch.jslack.api.model.Attachment
/**
* When an item is starred, the star_added event is sent to all connected clients for the authenticated user who starred the item.
*
*
* See the stars.list method for details of the structure of the item property.
*
*
* https://api.slack.com/events/star_added
*/
class StarAddedEvent : Event {
override val type: String = TYPE_NAME
var user: String? = null
var item: Item? = null
var eventTs: String? = null
class Item {
var type: String? = null
var channel: String? = null
var createdBy: String? = null // user id
var created: Int? = null
var message: Message? = null
var file: File? = null // TODO: correct definition
var comment: FileComment? = null // TODO: correct definition
}
class Message {
var clientMsgId: String? = null
var type: String? = null
var user: String? = null
var text: String? = null
var blocks: Array<LayoutBlock>? = null
var attachments: Array<Attachment>? = null
var ts: String? = null
var pinnedTo: Array<String>? = null
var permalink: String? = null
}
companion object {
const val TYPE_NAME: String = "star_added"
}
}
| 5
|
Kotlin
|
0
| 0
|
4d7fe4d7658ebe5e7daac29f727db96a09deaead
| 1,334
|
kslack
|
MIT License
|
infra/micrometer/src/test/kotlin/io/bluetape4k/micrometer/instrument/AbstractMicrometerTest.kt
|
debop
| 625,161,599
| false
|
{"Kotlin": 7504333, "HTML": 502995, "Java": 2273, "JavaScript": 1351, "Shell": 1301, "CSS": 444, "Dockerfile": 121, "Mustache": 82}
|
package io.bluetape4k.micrometer.instrument
import io.bluetape4k.junit5.faker.Fakers
import io.bluetape4k.logging.KLogging
abstract class AbstractMicrometerTest {
companion object: KLogging() {
@JvmStatic
protected val faker = Fakers.faker
}
}
| 0
|
Kotlin
|
0
| 1
|
ce3da5b6bddadd29271303840d334b71db7766d2
| 271
|
bluetape4k
|
MIT License
|
src/jvmTest/kotlin/doc/HelloWorld.kt
|
natanfudge
| 193,679,632
| false
|
{"Kotlin": 45035, "HTML": 1548, "Python": 587}
|
package doc
import kotplot.builders.KotPlot
import kotplot.constructables.Point
//import kotplot.jvmExtensions.show
//TODO: change README to html so I can have tabs for jvm/js/native, and kotlin-dsl/groovy-dsl
fun main() {
val points = listOf(
Point(0, 0),
Point(1, 1),
Point(2, 2)
)
val plot = KotPlot.plot {
scatterTrace(points)
}
// plot.show()
}
| 0
|
Kotlin
|
0
| 0
|
f243a55ec47def424e18a0f30c71f877a038c3b4
| 405
|
kotplot
|
Apache License 2.0
|
src/main/kotlin/com/deflatedpickle/popenchanttags/PopEnchantTagsResuscitated.kt
|
DeflatedPickle
| 440,869,318
| true
|
{"Kotlin": 4988, "Java": 1949}
|
/* Copyright (c) 2021-2022 DeflatedPickle under the MIT license */
package com.deflatedpickle.popenchanttags
import net.minecraft.client.MinecraftClient
import net.minecraft.client.util.math.MatrixStack
import net.minecraft.entity.effect.StatusEffectUtil
import net.minecraft.inventory.Inventories
import net.minecraft.item.BlockItem
import net.minecraft.item.EnchantedBookItem
import net.minecraft.item.ItemStack
import net.minecraft.item.Items
import net.minecraft.item.PotionItem
import net.minecraft.item.TippedArrowItem
import net.minecraft.potion.PotionUtil
import net.minecraft.text.MutableText
import net.minecraft.text.Text
import net.minecraft.text.Text.literal
import net.minecraft.text.Text.translatable
import net.minecraft.util.Formatting
import net.minecraft.util.collection.DefaultedList
import org.quiltmc.loader.api.ModContainer
import org.quiltmc.qsl.base.api.entrypoint.client.ClientModInitializer
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo
@Suppress("UNUSED")
object PopEnchantTagsResuscitated : ClientModInitializer {
private const val MOD_ID = "$[id]"
private const val NAME = "$[name]"
private const val GROUP = "$[group]"
private const val AUTHOR = "$[author]"
private const val VERSION = "$[version]"
const val DISTANCE = 10
override fun onInitializeClient(mod: ModContainer) {
println(listOf(MOD_ID, NAME, GROUP, AUTHOR, VERSION))
}
fun moveItemTitle(matrixStack: MatrixStack, info: CallbackInfo) {
val mc = MinecraftClient.getInstance()
val currentStack = mc.player!!.mainHandStack
if (!currentStack.hasNbt()) return
if (MinecraftClient.getInstance().interactionManager?.hasStatusBars() == false) return
if (info.id == "move:head") {
matrixStack.push()
matrixStack.translate(0.0, -DISTANCE.toDouble(), 0.0)
} else matrixStack.pop()
}
fun drawExtraText(
matrices: MatrixStack,
width: Int,
x: Int,
y: Int,
opacity: Int
) {
val mc = MinecraftClient.getInstance()
val textRenderer = mc.textRenderer
val currentStack = mc.player!!.mainHandStack
val textList = mutableListOf<Text>()
if (currentStack.item == Items.SHULKER_BOX) {
BlockItem.getBlockEntityNbtFromStack(currentStack)?.let { nbtCompound ->
if (nbtCompound.contains("Items")) {
val defaultedList = DefaultedList.ofSize(27, ItemStack.EMPTY)
Inventories.readNbt(nbtCompound, defaultedList)
for (i in defaultedList) {
if (i.isEmpty) continue
val text = i.name.copyContentOnly()
text.append(" x").append(i.count.toString())
textList.add(text)
}
}
}
} else if (currentStack.item is PotionItem || currentStack.item is TippedArrowItem) {
val effects = PotionUtil.getPotionEffects(currentStack)
if (effects.isEmpty()) {
textList.add(translatable("effect.none"))
} else {
for (i in effects) {
var text = translatable(i.translationKey)
if (i.duration > 20) {
text = translatable(
"potion.withDuration",
text,
StatusEffectUtil.durationToString(
i,
when (currentStack.item) {
is PotionItem -> 1.0f
is TippedArrowItem -> 0.125f
else -> 0.0f
}
)
)
}
textList.add(text)
}
}
} else if (currentStack.item == Items.ENCHANTED_BOOK || currentStack.hasEnchantments()) {
ItemStack.appendEnchantments(
textList,
when (currentStack.item) {
is EnchantedBookItem -> EnchantedBookItem.getEnchantmentNbt(currentStack)
else -> currentStack.enchantments
}
)
}
val text = literal("").apply {
for ((i, s) in textList.take(4).withIndex()) {
append(s)
if (i < textList.size - 1) {
append(", ")
}
}
if (textList.size > 4) {
append("...")
}
}.formatted(Formatting.ITALIC, Formatting.GRAY)
val textWidth = textRenderer.getWidth(text)
textRenderer.drawWithShadow(
matrices,
text,
(x + (width - textWidth) / 2).toFloat(),
y.toFloat() + DISTANCE,
0xFFFFFF + (opacity shl 24)
)
}
}
| 0
|
Kotlin
|
0
| 1
|
16c6efc4f5f674e4e79ba057704fbdbb6b2e1375
| 5,016
|
PopEnchantTagsResuscitated
|
MIT License
|
daemon/src/main/kotlin/net/bytemc/bytecloud/daemon/commands/impl/ServiceCommand.kt
|
bytemcnetzwerk
| 684,494,766
| false
|
{"Kotlin": 147393}
|
package net.bytemc.bytecloud.daemon.commands.impl
import net.bytemc.bytecloud.api.CloudAPI
import net.bytemc.bytecloud.api.commands.SenderType
import net.bytemc.bytecloud.api.commands.annotations.Command
import net.bytemc.bytecloud.api.commands.annotations.DefaultExecution
import net.bytemc.bytecloud.api.commands.annotations.SubCommand
import net.bytemc.bytecloud.api.services.CloudServiceState
import net.bytemc.bytecloud.daemon.Daemon
import net.bytemc.bytecloud.daemon.services.CloudServiceProviderImpl
@Command("service", "Manage all services", SenderType.CONSOLE_AND_IN_GAME, ["ser", "services"])
class ServiceCommand {
val logger = Daemon.getInstance().logger
@SubCommand(["list"])
fun create() {
val services = CloudAPI.getInstance().getCloudServiceProvider().getServices()
logger.emptySpace()
logger.info("Currently run Services &8(&7${services.stream().filter { it.getState() == CloudServiceState.ONLINE }.count()} online&8 / &3${services.size}&8)")
services.forEach {
logger.info("&8- &3${it.getName()} &7with status ${it.getState()}")
}
}
@SubCommand(["shutdown", "<serviceId>"])
fun create(serviceId: String) {
val cloudService = Daemon.getInstance().getCloudServiceProvider().getService(serviceId)
if (cloudService == null) {
logger.info("Service&3 $serviceId&7 does not exist&8.")
return
}
cloudService.shutdown()
}
@SubCommand(["screen", "<serviceId>"])
fun screen(serviceId: String) {
Daemon.getInstance().terminal.clear()
val cloudService = Daemon.getInstance().getCloudServiceProvider().getService(serviceId)
if(cloudService == null) {
logger.info("Service&3 $serviceId&7 does not exist&8.")
return
}
cloudService.getOutput().forEach {
logger.empty(it)
}
Daemon.getInstance().logger.info("If you want to exit the screen, type &8'&3cancel&8'.")
Daemon.getInstance().terminal.setPrompt("&b${serviceId}&8@&fscreen &8> &7")
(Daemon.getInstance().getCloudServiceProvider() as CloudServiceProviderImpl).serviceScreenProvider.setScreen(cloudService)
//TODO update screen
}
@SubCommand(["info", "<serviceId>"])
fun info(serviceId: String) {
val service = Daemon.getInstance().getCloudServiceProvider().getService(serviceId)
if (service == null) {
logger.info("Service&3 $serviceId&7 does not exist&8.")
return
}
logger.info("Information about service ${service.getName()}")
logger.info("&8- &7Name&8: &3${service.getName()}")
logger.info("&8- &7Group&8: &3${service.getGroupName()}")
logger.info("&8- &7State&8: &3${service.getState()}")
}
@DefaultExecution
fun handle() {
logger.info("service shutdown &8[&bname&8] - &7Stops a service")
logger.info("service info &8[&bname&8] - &7Get information about a service")
logger.info("service screen &8[&bname&8] - &7See the screen of a service")
logger.info("service list - &7List all Services and their status")
}
}
| 1
|
Kotlin
|
3
| 5
|
71a52f1a41d3dcd3c656090549e25e13b846539b
| 3,183
|
bytecloud
|
Apache License 2.0
|
app/src/main/kotlin/net/primal/android/nostr/utils/Nip19TLV.kt
|
PrimalHQ
| 639,579,258
| false
| null |
package com.vitorpamplona.amethyst.service.nip19
import java.nio.ByteBuffer
import java.nio.ByteOrder
object Tlv {
enum class Type(val id: Byte) {
SPECIAL(0),
RELAY(1),
AUTHOR(2),
KIND(3);
}
fun toInt32(bytes: ByteArray): Int {
require(bytes.size == 4) { "length must be 4, got: ${bytes.size}" }
return ByteBuffer.wrap(bytes, 0, 4).order(ByteOrder.BIG_ENDIAN).int
}
fun parse(data: ByteArray): Map<Byte, List<ByteArray>> {
val result = mutableMapOf<Byte, MutableList<ByteArray>>()
var rest = data
while (rest.isNotEmpty()) {
val t = rest[0]
val l = rest[1]
val v = rest.sliceArray(IntRange(2, (2 + l) - 1))
rest = rest.sliceArray(IntRange(2 + l, rest.size - 1))
if (v.size < l) continue
if (!result.containsKey(t)) {
result[t] = mutableListOf()
}
result[t]?.add(v)
}
return result
}
}
| 56
| null |
4
| 98
|
438072af7f67762c71c5dceffa0c83dedd8e2e85
| 1,014
|
primal-android-app
|
MIT License
|
app/src/main/java/com/example/nasa_mars_api_service/ui/fragment/image_of_day_description/ImageOfDayFragment.kt
|
Ferum-bot
| 321,743,211
| false
| null |
package com.example.nasa_mars_api_service.ui.fragment.image_of_day_description
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions.withCrossFade
import com.example.nasa_mars_api_service.R
import com.example.nasa_mars_api_service.core.enums.PhotoTypes
import com.example.nasa_mars_api_service.core.getBaseRequestOptions
import com.example.nasa_mars_api_service.core.models.PictureOfDayPhoto
import com.example.nasa_mars_api_service.database.db.MainDatabase
import com.example.nasa_mars_api_service.databinding.FragmentImageOfDayDescriptionBinding
import com.example.nasa_mars_api_service.network.api.MarsPhotosApi
import com.example.nasa_mars_api_service.preferences.implementations.AppPreferences
import com.example.nasa_mars_api_service.preferences.interfaces.BaseApplicationPreferences
import com.example.nasa_mars_api_service.repository.implementations.MainRepository
import com.example.nasa_mars_api_service.repository.interfaces.BaseRepository
/**
* Created by <NAME>.
* Date: 31.12.2020
* Time: 20:24
* Project: NASA-Mars-API-Service
*/
class ImageOfDayFragment: Fragment() {
private lateinit var binding: FragmentImageOfDayDescriptionBinding
private lateinit var viewModel: ImageOfDayViewModel
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_image_of_day_description, container, false)
getViewModel()
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setAllClickListeners()
setAllObservers()
getImageOfDay()
}
private fun getViewModel() {
val context = requireContext()
val preferences: BaseApplicationPreferences = AppPreferences.getInstance(context)
val dataBase = MainDatabase.getInstance(context)
val remoteSource = MarsPhotosApi.marsPhotosService
val repository: BaseRepository = MainRepository.getInstance(
dataBase.marsPhotoDao,
dataBase.favoritePhotoDao,
dataBase.pictureOfDayDao,
remoteSource,
preferences
)
val factory = ImageOfDayViewModelFactory(repository)
viewModel = ViewModelProvider(this, factory).get(ImageOfDayViewModel::class.java)
}
private fun setAllClickListeners() {
binding.appBar.setNavigationOnClickListener {
findNavController().popBackStack()
}
binding.imageView.setOnClickListener {
val args = ImageOfDayFragmentArgs.fromBundle(requireArguments())
val id = args.id
findNavController().navigate(ImageOfDayFragmentDirections.actionImageOfDayFragmentToPhotoViewFragment(id, PhotoTypes.PICTURE_OF_DAY))
}
binding.appBar.setOnMenuItemClickListener {
when(viewModel.imageOfDay.value?.isFavourite) {
true -> {
viewModel.removeImageOfDayFromFavourites()
true
}
false -> {
viewModel.addImageOfDayToFavourites()
true
}
else -> {
false
}
}
}
}
private fun setAllObservers() {
viewModel.errorMessage.observe(viewLifecycleOwner, Observer { newMessage ->
if (newMessage != null) {
showErrorMessage(newMessage)
}
})
viewModel.imageOfDay.observe(viewLifecycleOwner, Observer { image ->
startLoadingImage(image)
setAllFields(image)
})
}
private fun startLoadingImage(image: PictureOfDayPhoto) {
val src = image.imageSrc
val options = getBaseRequestOptions()
Glide.with(binding.imageView)
.applyDefaultRequestOptions(options)
.load(src)
.transition(withCrossFade())
.into(binding.imageView)
}
private fun setAllFields(image: PictureOfDayPhoto) {
binding.authorTextView.text = image.author
binding.dateTextView.text = image.date
binding.titleTextView.text = image.title
binding.descriptionTextView.text = image.description
when(image.isFavourite) {
true -> binding.appBar.menu.getItem(0).setIcon(R.drawable.ic_star__filled)
false -> binding.appBar.menu.getItem(0).setIcon(R.drawable.ic_star)
}
}
private fun showErrorMessage(message: String) {
val context = requireContext()
Toast.makeText(context, "Something went wrong: $message", Toast.LENGTH_SHORT).show()
}
private fun getImageOfDay() {
val args = ImageOfDayFragmentArgs.fromBundle(requireArguments())
val id = args.id
viewModel.getImageOfDay(id)
}
}
| 0
|
Kotlin
|
0
| 1
|
65b8c42e08ff3fffdacf09b0796a327f27f52418
| 5,367
|
NASA-Mars-Api-Service
|
MIT License
|
app/src/main/java/top/z7workbench/butterfly/playback/ButterflyMediaService.kt
|
z7workbench
| 431,685,741
| false
|
{"Kotlin": 28502}
|
package top.z7workbench.butterfly.playback
import androidx.media3.common.AudioAttributes
import androidx.media3.common.MediaItem
import androidx.media3.common.Player
import androidx.media3.common.util.UnstableApi
import androidx.media3.exoplayer.DefaultRenderersFactory
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.session.MediaLibraryService
import androidx.media3.session.MediaSession
import androidx.media3.ui.PlayerNotificationManager
import com.google.common.util.concurrent.Futures
import com.google.common.util.concurrent.ListenableFuture
@UnstableApi
class ButterflyMediaService : MediaLibraryService() {
private val player: Player by lazy {
ExoPlayer.Builder(applicationContext)
.setAudioAttributes(AudioAttributes.DEFAULT, true)
.setHandleAudioBecomingNoisy(true)
.setRenderersFactory(
DefaultRenderersFactory(this).apply {
this.setExtensionRendererMode(DefaultRenderersFactory.EXTENSION_RENDERER_MODE_PREFER);
}
)
.build()
}
private lateinit var notification: PlayerNotificationManager
private lateinit var session: MediaLibrarySession
override fun onCreate() {
super.onCreate()
session = MediaLibrarySession.Builder(this, player,
object: MediaLibrarySession.Callback {
override fun onAddMediaItems(
mediaSession: MediaSession,
controller: MediaSession.ControllerInfo,
mediaItems: MutableList<MediaItem>
): ListenableFuture<MutableList<MediaItem>> {
val updatedMediaItems = mediaItems.map { it.buildUpon().setUri(it.mediaId).build() }.toMutableList()
return Futures.immediateFuture(updatedMediaItems)
}
}).build()
notification = PlayerNotificationManager.Builder(this, NOTIFICATION_ID, CHANNEL)
.build()
notification.setPlayer(player)
}
override fun onGetSession(controllerInfo: MediaSession.ControllerInfo) = session
override fun onDestroy() {
session.release()
notification.setPlayer(null)
player.release()
super.onDestroy()
}
companion object {
const val CHANNEL = "playback_service"
const val NOTIFICATION_ID = 1
}
}
| 5
|
Kotlin
|
0
| 1
|
d3755061ecd8c17acdf6d645fe22cbe9eb001c34
| 2,388
|
Butterfly
|
MIT License
|
Corona-Warn-App/src/main/java/de/rki/coronawarnapp/bugreporting/debuglog/ui/upload/history/HistoryItemAdapter.kt
|
corona-warn-app
| 268,027,139
| false
| null |
package de.rki.coronawarnapp.bugreporting.debuglog.ui.upload.history
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.view.ViewGroup
import de.rki.coronawarnapp.R
import de.rki.coronawarnapp.bugreporting.debuglog.upload.history.model.LogUpload
import de.rki.coronawarnapp.databinding.BugreportingUploadHistoryItemBinding
import de.rki.coronawarnapp.ui.lists.BaseAdapter
import de.rki.coronawarnapp.util.lists.BindableVH
import de.rki.coronawarnapp.util.toLocalDateTimeUserTz
import java.time.format.DateTimeFormatter
import timber.log.Timber
class HistoryItemAdapter : BaseAdapter<HistoryItemAdapter.CachedKeyViewHolder>() {
val data = mutableListOf<LogUpload>()
override fun getItemCount(): Int = data.size
override fun onCreateBaseVH(parent: ViewGroup, viewType: Int): CachedKeyViewHolder = CachedKeyViewHolder(parent)
override fun onBindBaseVH(holder: CachedKeyViewHolder, position: Int, payloads: MutableList<Any>) {
data[position].let {
holder.bind(it)
}
}
class CachedKeyViewHolder(
val parent: ViewGroup
) : VH(R.layout.bugreporting_upload_history_item, parent),
BindableVH<LogUpload, BugreportingUploadHistoryItemBinding> {
override val viewBinding = lazy { BugreportingUploadHistoryItemBinding.bind(itemView) }
override val onBindData: BugreportingUploadHistoryItemBinding.(
item: LogUpload,
payloads: List<Any>
) -> Unit = { item, _ ->
title.text = item.uploadedAt.toLocalDateTimeUserTz().format(FORMATTER)
description.text = "ID ${item.id}"
itemView.setOnClickListener {
try {
val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
clipboard.setPrimaryClip(
ClipData.newPlainText(
context.getString(R.string.debugging_debuglog_share_log_title),
"""
${context.getString(R.string.debugging_debuglog_share_log_title)}
${title.text}
${description.text}
""".trimIndent()
)
)
} catch (e: Throwable) {
Timber.e(e, "Failed to copy ID to clipboard.")
}
}
}
}
companion object {
private val FORMATTER = DateTimeFormatter.ofPattern("dd.MM.yyyy - HH:mm:ss")
}
}
| 6
| null |
516
| 2,495
|
d3833a212bd4c84e38a1fad23b282836d70ab8d5
| 2,626
|
cwa-app-android
|
Apache License 2.0
|
KotlinMultiplatform/XFullStack/shared/src/commonMain/kotlin/core/models/request/Content.kt
|
pradyotprksh
| 385,586,594
| false
|
{"Kotlin": 2932498, "Dart": 1066884, "Python": 319755, "Rust": 180589, "Swift": 149003, "C++": 113494, "JavaScript": 103891, "CMake": 94132, "HTML": 57188, "Go": 45704, "CSS": 18615, "SCSS": 17864, "Less": 17245, "Ruby": 13609, "Dockerfile": 9772, "C": 8043, "Shell": 7657, "PowerShell": 3045, "Nix": 2616, "Makefile": 1480, "PHP": 1241, "Objective-C": 380, "Handlebars": 354}
|
package core.models.request
import kotlinx.serialization.Serializable
@Serializable
data class Content(
val parts: List<Part>,
)
| 0
|
Kotlin
|
11
| 24
|
a31e612a63e1dc42ed4cf2f50db90b8613fb5177
| 134
|
development_learning
|
MIT License
|
data/src/main/java/com/foobarust/data/models/seller/SellerItemDetailDto.kt
|
foobar-UST
| 285,792,732
| false
| null |
package com.foobarust.data.models.seller
import com.foobarust.data.constants.Constants.SELLER_ITEM_AVAILABLE_FIELD
import com.foobarust.data.constants.Constants.SELLER_ITEM_CATALOG_ID_FIELD
import com.foobarust.data.constants.Constants.SELLER_ITEM_COUNT_FIELD
import com.foobarust.data.constants.Constants.SELLER_ITEM_DESCRIPTION_FIELD
import com.foobarust.data.constants.Constants.SELLER_ITEM_DESCRIPTION_ZH_FIELD
import com.foobarust.data.constants.Constants.SELLER_ITEM_ID_FIELD
import com.foobarust.data.constants.Constants.SELLER_ITEM_IMAGE_URL_FIELD
import com.foobarust.data.constants.Constants.SELLER_ITEM_PRICE_FIELD
import com.foobarust.data.constants.Constants.SELLER_ITEM_SELLER_ID_FIELD
import com.foobarust.data.constants.Constants.SELLER_ITEM_TITLE_FIELD
import com.foobarust.data.constants.Constants.SELLER_ITEM_TITLE_ZH_FIELD
import com.foobarust.data.constants.Constants.SELLER_ITEM_UPDATED_AT_FIELD
import com.google.firebase.Timestamp
import com.google.firebase.firestore.PropertyName
import com.google.firebase.firestore.ServerTimestamp
/**
* Created by kevin on 10/5/20
*/
data class SellerItemDetailDto(
@JvmField
@PropertyName(SELLER_ITEM_ID_FIELD)
val id: String? = null,
@JvmField
@PropertyName(SELLER_ITEM_TITLE_FIELD)
val title: String? = null,
@JvmField
@PropertyName(SELLER_ITEM_TITLE_ZH_FIELD)
val titleZh: String? = null,
@JvmField
@PropertyName(SELLER_ITEM_DESCRIPTION_FIELD)
val description: String? = null,
@JvmField
@PropertyName(SELLER_ITEM_DESCRIPTION_ZH_FIELD)
val descriptionZh: String? = null,
@JvmField
@PropertyName(SELLER_ITEM_CATALOG_ID_FIELD)
val catalogId: String? = null,
@JvmField
@PropertyName(SELLER_ITEM_SELLER_ID_FIELD)
val sellerId: String? = null,
@JvmField
@PropertyName(SELLER_ITEM_PRICE_FIELD)
val price: Double? = null,
@JvmField
@PropertyName(SELLER_ITEM_IMAGE_URL_FIELD)
val imageUrl: String? = null,
@JvmField
@PropertyName(SELLER_ITEM_COUNT_FIELD)
val count: Int? = null,
@JvmField
@PropertyName(SELLER_ITEM_AVAILABLE_FIELD)
val available: Boolean? = null,
@JvmField
@ServerTimestamp
@PropertyName(SELLER_ITEM_UPDATED_AT_FIELD)
val updatedAt: Timestamp? = null
)
| 0
|
Kotlin
|
2
| 2
|
b4358ef0323a0b7a95483223496164e616a01da5
| 2,289
|
foobar-android
|
MIT License
|
recyclerview/src/main/java/com/tunjid/androidx/recyclerview/SwipeDragOptions.kt
|
tunjid
| 89,848,117
| false
|
{"Kotlin": 436389, "Java": 77823}
|
package com.tunjid.androidx.recyclerview
import android.view.View
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
internal class SwipeDragOptions<VH : RecyclerView.ViewHolder>(
internal val itemViewSwipeSupplier: () -> Boolean,
internal val longPressDragSupplier: () -> Boolean,
internal val dragConsumer: (VH, VH) -> Unit,
internal val swipeConsumer: (VH, Int) -> Unit,
internal val swipeDragStartConsumer: (VH, Int) -> Unit,
internal val swipeDragEndConsumer: (VH, Int) -> Unit,
internal val movementFlagFunction: (VH) -> Int,
internal val dragHandleFunction: (VH) -> View
)
val SWIPE_DRAG_ALL_DIRECTIONS = ItemTouchHelper.Callback.makeMovementFlags(
ItemTouchHelper.UP or ItemTouchHelper.DOWN,
ItemTouchHelper.START or ItemTouchHelper.END
)
| 5
|
Kotlin
|
60
| 595
|
efdc0dcf5559984a36a8bed4cff6257f20e6e07d
| 839
|
Android-Extensions
|
MIT License
|
app/src/main/java/com/example/mymvvmsample/di/RepositoryModule.kt
|
EdyWDev
| 532,205,085
| false
| null |
package com.example.mymvvmsample.di
import com.example.mymvvmsample.service.CatFactRepository
import com.example.mymvvmsample.service.CatFactService
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object RepositoryModule {
@Singleton
@Provides
fun provideCatFactRepository(
catFactService: CatFactService
): CatFactRepository =
CatFactRepository(catFactService)
}
| 0
|
Kotlin
|
0
| 0
|
c10791fe6d9946e90e2e8587ee87fc0fde047d00
| 548
|
SampleMVVM
|
Apache License 2.0
|
lavaplayer/src/main/java/com/sedmelluq/discord/lavaplayer/source/soundcloud/SoundCloudSegmentDecoder.kt
|
mixtape-bot
| 397,835,411
| true
|
{"Kotlin": 781109, "Java": 315803}
|
package com.sedmelluq.discord.lavaplayer.source.soundcloud
import com.sedmelluq.discord.lavaplayer.tools.io.SeekableInputStream
import com.sedmelluq.discord.lavaplayer.track.playback.AudioProcessingContext
import java.io.IOException
interface SoundCloudSegmentDecoder : AutoCloseable {
@Throws(IOException::class)
fun prepareStream(beginning: Boolean)
@Throws(IOException::class)
fun resetStream()
@Throws(InterruptedException::class, IOException::class)
fun playStream(context: AudioProcessingContext, startPosition: Long, desiredPosition: Long)
fun interface Factory {
fun create(nextStreamProvider: () -> SeekableInputStream): SoundCloudSegmentDecoder
}
}
| 0
|
Kotlin
|
0
| 6
|
06b02d8e711930c52d8ca67ad6347a17ca352ba2
| 704
|
lavaplayer
|
Apache License 2.0
|
src/main/kotlin/com/skillw/pouvoir/api/feature/trigger/BukkitTrigger.kt
|
Glom-c
| 396,683,163
| false
| null |
package com.skillw.pouvoir.api.feature.trigger
/**
* Pou trigger
*
* 主要是将Bukkit事件名字格式化
*
* 如果Bukkit事件类上没有此注解或没有指定name
*
* 则其事件名称将会像这样格式化为触发器id:
*
* "PlayerMoveEvent" -> "player move"
*
* @constructor Create empty Pou trigger
* @property name
*/
annotation class BukkitTrigger(val name: String = "")
| 1
|
Kotlin
|
0
| 9
|
35b93485f5f4c2d5c534a2765ff7cfb8f34dd737
| 313
|
Pouvoir
|
MIT License
|
app/src/main/java/br/com/compasso/markup/ui/fragments/LocationFragment.kt
|
jotavier
| 330,055,469
| false
| null |
package br.com.compasso.markup.ui.fragments
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import br.com.compasso.markup.R
import br.com.compasso.markup.databinding.FragmentEventLocationBinding
import br.com.compasso.markup.ui.viewmodels.EventViewModel
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.MarkerOptions
import org.koin.android.viewmodel.ext.android.sharedViewModel
class LocationFragment : BaseFragment(), OnMapReadyCallback {
private val binding by lazy { FragmentEventLocationBinding.inflate(layoutInflater) }
private val eventDetailsViewModel by sharedViewModel<EventViewModel>()
private val map by lazy { childFragmentManager.findFragmentByTag(getString(R.string.map_fragment_tag)) as SupportMapFragment }
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
return binding.root
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
map.getMapAsync(this@LocationFragment)
}
override fun onMapReady(googleMap: GoogleMap?) {
eventDetailsViewModel.event.observe(viewLifecycleOwner, { event ->
event?.let {
binding.event = event
val eventLocation = LatLng(event.latitude, event.longitude)
googleMap?.addMarker(MarkerOptions().position(eventLocation).title(event.title))
googleMap?.moveCamera(CameraUpdateFactory.newLatLng(eventLocation))
googleMap?.animateCamera(CameraUpdateFactory.newLatLngZoom(eventLocation, 16f))
}
})
}
}
| 0
|
Kotlin
|
0
| 1
|
fc9a47ca44cdb4e50916dbc450f99bb51e58c9c9
| 1,983
|
markup
|
MIT License
|
mediapicker/src/main/kotlin/ca/allanwang/kau/mediapicker/MediaModel.kt
|
pranavlathigara
| 109,946,503
| true
|
{"Kotlin": 371986, "Java": 118232, "HTML": 3366, "Shell": 1054, "Ruby": 25}
|
package ca.allanwang.kau.mediapicker
import android.database.Cursor
import android.database.SQLException
import android.net.Uri
import android.os.Parcel
import android.os.Parcelable
import android.provider.MediaStore
import android.support.annotation.NonNull
import java.io.File
/**
* Created by <NAME> on 2017-07-14.
*/
data class MediaModel(
val data: String, val mimeType: String, val size: Long, val dateModified: Long, val displayName: String?
) : Parcelable {
@Throws(SQLException::class)
constructor(@NonNull cursor: Cursor) : this(
cursor.getString(0),
cursor.getString(1) ?: "",
cursor.getLong(2),
cursor.getLong(3),
cursor.getString(4)
)
constructor(f: File) : this(
f.absolutePath,
f.extension, // this isn't a mime type, but it does give some info
f.length(),
f.lastModified(),
f.nameWithoutExtension
)
constructor(parcel: Parcel) : this(
parcel.readString(),
parcel.readString(),
parcel.readLong(),
parcel.readLong(),
parcel.readString())
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeString(this.data)
parcel.writeString(this.mimeType)
parcel.writeLong(this.size)
parcel.writeLong(this.dateModified)
parcel.writeString(this.displayName)
}
val isGif
get() = mimeType.endsWith("gif")
val isImage
get() = mimeType.endsWith("image")
val isVideo
get() = mimeType.endsWith("video")
val uri: Uri by lazy { Uri.fromFile(File(data)) }
override fun describeContents(): Int {
return 0
}
companion object CREATOR : Parcelable.Creator<MediaModel> {
val projection = arrayOf(
MediaStore.MediaColumns.DATA,
MediaStore.MediaColumns.MIME_TYPE,
MediaStore.MediaColumns.SIZE,
MediaStore.MediaColumns.DATE_MODIFIED,
MediaStore.MediaColumns.DISPLAY_NAME
)
override fun createFromParcel(parcel: Parcel): MediaModel {
return MediaModel(parcel)
}
override fun newArray(size: Int): Array<MediaModel?> {
return arrayOfNulls(size)
}
}
}
| 1
|
Kotlin
|
1
| 1
|
a0587e8877f35ac2dc149a64e06665dff424b469
| 2,341
|
KAU
|
Apache License 2.0
|
src/main/java/unofficial/html_generator.kt
|
MHordecki
| 64,960,736
| false
|
{"HTML": 1918577, "Kotlin": 39700, "JavaScript": 994, "CSS": 475}
|
/**
* This file contains HTML generating routines.
*
* It uses Freemarker as its templating engine. Boy, does it suck. Sadly, all other engines for the JVM suck even more.
*/
package unofficial
import freemarker.ext.beans.StringModel
import freemarker.template.Configuration
import freemarker.template.SimpleScalar
import freemarker.template.TemplateMethodModelEx
import org.threeten.bp.Duration
import org.threeten.bp.Instant
import org.threeten.bp.ZoneId
import org.threeten.bp.ZonedDateTime
import org.threeten.bp.format.DateTimeFormatter
import java.io.StringWriter
import java.util.*
// An override map for needlessly long league names
val LEAGUE_NAME_OVERRIDES = mapOf(
"Captains Draft 3.0 Presented by DotaCinema & MoonduckTV".to("Captains Draft 3.0")
)
// Used to pass arguments to the template in a typesafe way.
data class TemplateContext(
// Prefix to put before each URL. This is needed because files for each run are put in a subdirectory,
// but the HTTP server is using index.html from the root to serve.
val urlBase: String,
// Run ID displayed in the footer.
val now: Instant,
// Self-explanatory
val history: List<Match>,
val teamLeaderboard: List<TeamLeaderboard.Item>,
val regionLeaderboard: List<RegionLeaderboard.Item>,
// Champion is the winner of this match
val champion: Match,
val includeAnalytics: Boolean
) {
private fun templateMethod(fn: (Any) -> Any): TemplateMethodModelEx =
object : TemplateMethodModelEx {
override fun exec(args: MutableList<Any?>?): Any? {
val arg = args!![0]!!
// I have no idea what the conceptual model behind Freemarker is and frankly I don't care
return when (arg) {
is StringModel -> fn(arg.wrappedObject)
is SimpleScalar -> fn(arg.asString)
else -> fn(arg)
}
}
}
val unbreakable = templateMethod { (it as String).replace(" ", " ") }
val getMatchUrl = templateMethod { "http://www.dotabuff.com/matches/${(it as MatchId).id}" }
val getLeagueUrl = templateMethod { "http://www.dotabuff.com/esports/leagues/${(it as LeagueId).id}" }
val getTeamUrl = templateMethod { "http://www.dotabuff.com/esports/teams/${(it as TeamId).id}" }
val displayLeagueName = templateMethod { LEAGUE_NAME_OVERRIDES[it as String] ?: it }
val displayDuration = templateMethod {
it as Duration
listOf(
if (it.toDays() != 0L) "${it.toDays()}d" else null,
if (it.toHours() % 24 != 0L) "${it.toHours() % 24}h" else null)
.filterNotNull()
.joinToString(" ")
}
val displayDate = templateMethod {
DateTimeFormatter.ofPattern("MMM d, yyyy").format(ZonedDateTime.ofInstant(it as Instant, ZoneId.of("UTC")))
}
val displayShortDate = templateMethod {
DateTimeFormatter.ofPattern("MMM yyyy").format(ZonedDateTime.ofInstant(it as Instant, ZoneId.of("UTC")))
}
val displayRegion = templateMethod {
when (it as RegionId) {
RegionId.EUROPE -> "Europe"
RegionId.AMERICA -> "America"
RegionId.SEA -> "SEA"
RegionId.ANTARCTICA -> "Antarctica"
RegionId.CHINA -> "China"
}
}
}
object HtmlGenerator {
fun generate(
now: Instant,
urlBase: String,
result: Unofficial.Result,
includeAnalytics: Boolean = false
): String {
val context = TemplateContext(
urlBase = "$urlBase",
now = now,
history = result.championshipMatches,
teamLeaderboard = result.teamLeaderboard,
regionLeaderboard = result.regionLeaderboard,
champion = result.championshipMatches.last(),
includeAnalytics = includeAnalytics
)
val cfg = Configuration(Configuration.VERSION_2_3_24)
cfg.setClassForTemplateLoading(javaClass, "")
cfg.defaultEncoding = "UTF-8"
cfg.templateExceptionHandler = freemarker.template.TemplateExceptionHandler.RETHROW_HANDLER
cfg.logTemplateExceptions = true
val writer = StringWriter()
cfg.getTemplate("template.html").process(context, writer)
return writer.toString()
}
}
| 0
|
HTML
|
0
| 0
|
215953bf22e05fe40a5c0de57db2a4f09d6f74f2
| 4,098
|
unofficial
|
MIT License
|
src/serverMain/kotlin/mce/pass/backend/Stage.kt
|
mcenv
| 435,848,712
| false
| null |
package mce.pass.backend
import mce.Id
import mce.ast.core.Item
import mce.ast.core.Term
import mce.ast.core.VTerm
import mce.pass.*
import mce.pass.frontend.Zonk
import mce.util.Store
/**
* Performs staging.
*/
@Suppress("NAME_SHADOWING")
class Stage private constructor(
private val normalizer: Normalizer,
) : Transform() {
// TODO: do not normalize runtime code
override fun transformTerm(term: Term): Term = when (term) {
is Term.Hole -> throw Error()
is Term.Meta -> throw Error()
is Term.Command -> {
val body = Store(normalizer).normTerm(term.body)
Term.Command(body, term.id)
}
is Term.CodeOf -> throw Error()
is Term.Splice -> {
val staged = Store(normalizer).normTerm(term)
transformTermInternal(staged)
}
is Term.Code -> throw Error()
else -> transformTermInternal(term)
}
data class Result(
val item: Item,
val types: Map<Id, VTerm>,
)
companion object : Pass<Zonk.Result, Result> {
override operator fun invoke(config: Config, input: Zonk.Result): Result = Stage(input.normalizer).run {
Result(transformItem(input.item), input.types)
}
}
}
| 79
|
Kotlin
|
0
| 15
|
f63905729320733d3cae95c3b51b492e94339fca
| 1,256
|
mce
|
MIT License
|
app/src/main/java/com/rogertalk/roger/ui/adapters/listener/ContactPicker.kt
|
rogertalk
| 207,123,525
| false
|
{"Gradle": 4, "Java Properties": 3, "Markdown": 7, "Text": 6, "Shell": 1, "Ignore List": 3, "Batchfile": 1, "XML": 157, "Proguard": 2, "Kotlin": 408, "Java": 2, "JSON": 1, "Makefile": 2, "C": 105, "C++": 11}
|
package com.rogertalk.roger.ui.adapters.listener
import com.rogertalk.roger.models.data.DeviceContactInfo
interface ContactPicker {
fun selectionBegun()
fun selectionCleared()
fun pressedRequestPermission()
fun selectedContact(contact: DeviceContactInfo)
fun unSelectedContact(contact: DeviceContactInfo)
}
| 0
|
C
|
0
| 1
|
55c9922947311d9d8a1e930463b9ac2a1332e006
| 331
|
roger-android
|
MIT License
|
cli/src/main/java/io/boxtape/cli/commands/ShellCommand.kt
|
martypitt
| 40,046,986
| false
|
{"Maven POM": 4, "Text": 2, "Ignore List": 1, "EditorConfig": 1, "YAML": 3, "Markdown": 1, "Java": 13, "Kotlin": 25, "XML": 1}
|
package io.boxtape.cli.commands
import io.boxtape.core.Project
public interface ShellCommand {
fun name():String
fun run(project: Project)
}
| 1
| null |
1
| 1
|
4fd8ea2995dd467bc93f5f512da891f88a3dc8d7
| 151
|
boxtape
|
Apache License 2.0
|
app/src/main/java/com/softwarehut/mvpplayground/domain/home/HomePresenter.kt
|
softwarehutpl
| 139,710,457
| false
|
{"Kotlin": 49242}
|
package com.softwarehut.mvpplayground.domain.home
import com.softwarehut.mvp.domain.paramless.Presenter
interface HomePresenter : Presenter
| 0
|
Kotlin
|
0
| 0
|
fe91f41fad6413a8dabd3b3e9e1e0826e8cd7553
| 141
|
MvpPlayground
|
Apache License 2.0
|
src/main/kotlin/com/github/gamefixxer/phpstormconstantmanagerplugin/utils/ContextUtils.kt
|
GameFixxer
| 819,920,091
| false
|
{"Kotlin": 36578, "HTML": 2865}
|
package com.github.gamefixxer.phpstormconstantmanagerplugin.utils
import com.intellij.psi.PsiElement
import com.jetbrains.php.lang.psi.elements.*
object ContextUtils {
fun getContextName(element: PsiElement): String? {
var contextElement = element.parent
while (contextElement != null && contextElement !is PhpClass) {
contextElement = contextElement.parent
}
return if (contextElement is PhpClass) {
contextElement.name
} else {
null
}
}
fun isArrayKey(element: PsiElement): Boolean {
val parent = element.parent
return parent is ArrayAccessExpression && parent.index == element
}
fun isArrayValue(element: PsiElement): Boolean {
val parent = element.parent
if (parent is PhpPsiElement) {
return parent is ArrayHashElement && parent.value == element
}
return false
}
fun isMethodParameter(element: PsiElement): Boolean {
val parent = element.parent
return parent is Parameter && parent.defaultValue == element
}
fun getArrayKeyName(element: PsiElement): String? {
val parent = element.parent
return if (parent is ArrayAccessExpression && parent.index == element) {
(parent.firstChild as? PhpNamedElement)?.name
} else {
null
}
}
fun getArrayValueName(element: PsiElement): String? {
val parent = element.parent
return if (parent is ArrayHashElement && parent.value == element) {
(parent.key as? PhpNamedElement)?.name
} else {
null
}
}
fun getParamName(element: PsiElement): String? {
val parent = element.parent
return if (parent is Parameter && parent.defaultValue == element) {
parent.name
} else {
null
}
}
}
| 1
|
Kotlin
|
0
| 1
|
2ad81d5ab5091ee8f0b538196ae2bbb97129e4b7
| 1,908
|
php-constant-manager
|
MIT License
|
modules/LoadingView/src/main/java/com/loading/view/space/SpaceWorld.kt
|
siarheisinelnikau
| 337,195,832
| false
| null |
package com.loading.view.space
import com.badlogic.ashley.core.Engine
import com.loading.view.ecs.util.FPS
import com.loading.view.ecs.util.VectorFloat
import com.loading.view.space.component.*
import com.loading.view.space.component.renderer.DotRenderer
import com.loading.view.space.component.renderer.GradientRenderer
import com.loading.view.space.component.renderer.LineRenderer
import com.loading.view.space.system.LinesSystem
import com.loading.view.space.system.PositionSystem
import com.loading.view.space.system.RenderSystem
import com.loading.view.space.system.RotationSystem
import kotlin.random.Random
class SpaceWorld private constructor(private val engine: Engine) {
companion object {
fun create(
width: Float,
height: Float,
widthDp: Float,
heightDp: Float,
configuration: Configuration
): SpaceWorld {
val engine = Engine()
// Fill with systems
engine.addSystem(PositionSystem(width, height))
engine.addSystem(LinesSystem(configuration.backgroundProximity))
engine.addSystem(LinesSystem(configuration.foregroundProximity))
engine.addSystem(
RotationSystem(
configuration.backgroundMinSpeed,
configuration.backgroundMaxSpeed,
configuration.foregroundMinSpeed,
configuration.foregroundMaxSpeed
)
)
engine.addSystem(RenderSystem())
// make renderers
// TODO hardcoded values
val bgDotRenderer = DotRenderer(
configuration.backgroundMaxRadius,
configuration.backgroundMinRadius,
170f,
50f
)
val bgLineRenderer = LineRenderer(
configuration.backgroundLineAlpha
)
// TODO hardcoded values
val fgDotRenderer = DotRenderer(
configuration.foregroundMaxRadius,
configuration.foregroundMinRadius,
128f,
128f
)
val fgLineRenderer = LineRenderer(
configuration.foregroundLineAlpha
)
val gradientRenderer = GradientRenderer(
width,
height,
configuration.gradientStart,
configuration.gradientEnd
)
// Fill with entities
val entity = engine.createEntity()
entity.add(RenderComponent(gradientRenderer::render))
engine.addEntity(entity)
engine.initializeLayer(
width,
height,
widthDp,
heightDp,
configuration.backgroundDensity,
configuration.backgroundMinRadius,
configuration.backgroundMaxRadius,
configuration.backgroundMinSpeed,
configuration.backgroundMaxSpeed,
false,
renderer = {
RenderComponent { entity, canvas ->
bgLineRenderer.render(entity, canvas)
bgDotRenderer.render(entity, canvas)
}
}
)
engine.initializeLayer(
width,
height,
widthDp,
heightDp,
configuration.foregroundDensity,
configuration.foregroundMinRadius,
configuration.foregroundMaxRadius,
configuration.foregroundMinSpeed,
configuration.foregroundMaxSpeed,
true,
renderer = {
RenderComponent { entity, canvas ->
fgLineRenderer.render(entity, canvas)
fgDotRenderer.render(entity, canvas)
}
}
)
return SpaceWorld(engine)
}
private fun Engine.initializeLayer(
width: Float,
height: Float,
widthDp: Float,
heightDp: Float,
density: Int,
minRadius: Float,
maxRadius: Float,
minSpeed: Float,
maxSpeed: Float,
foreground: Boolean,
renderer: () -> RenderComponent
) {
val count = (widthDp * heightDp / density).toInt()
(0 until count).forEach { _ ->
val entity = createEntity()
entity.add(
MovementComponent(
VectorFloat(
VectorFloat.random360(minSpeed, maxSpeed),
VectorFloat.random360(minSpeed, maxSpeed)
)
)
)
entity.add(
SizeComponent(VectorFloat.random(minRadius, maxRadius), foreground)
)
entity.add(
TransformComponent(
VectorFloat(
Random.nextInt(1, width.toInt() - 1).toFloat(),
Random.nextInt(1, height.toInt() - 1).toFloat()
)
)
)
entity.add(LineComponent(VectorFloat()))
entity.add(renderer.invoke())
addEntity(entity)
}
}
}
private val fps = FPS()
private val rotationSystem: RotationSystem get() = engine.getSystem(RotationSystem::class.java)
val renderSystem: RenderSystem get() = engine.getSystem(RenderSystem::class.java)
fun update() {
fps.onFrame()
val delta = fps.getDelta()
engine.update(delta)
}
fun rotate() {
rotationSystem.rotationRequested = true
}
}
| 0
|
Kotlin
|
0
| 0
|
ed59d1e4c1f67c1e70cadd8e37a52882fe879912
| 5,947
|
LoadingView
|
Apache License 2.0
|
models/src/main/java/com/serma/models/model/WebAppUpdateUserRequestDto.kt
|
asuka1211
| 350,113,092
| false
| null |
/**
* Party maker API
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* The version of the OpenAPI document: v1
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapi.example.model
import com.google.gson.annotations.SerializedName
import java.io.Serializable
/**
*
* @param id
* @param email
* @param name
* @param imageId
* @param phone
*/
data class WebAppUpdateUserRequestDto (
@SerializedName("id")
val id: java.util.UUID? = null,
@SerializedName("email")
val email: kotlin.String? = null,
@SerializedName("name")
val name: kotlin.String? = null,
@SerializedName("imageId")
val imageId: java.util.UUID? = null,
@SerializedName("phone")
val phone: kotlin.String? = null
) : Serializable {
companion object {
private const val serialVersionUID: Long = 123
}
}
| 0
|
Kotlin
|
0
| 0
|
92c1a65d5b52e4d14907f32a3d7d10028aca783e
| 1,032
|
DionysusProject
|
Apache License 2.0
|
app/src/main/java/com/nick_sib/popularlibraries/di/repository/RepositorySubComponent.kt
|
Nick-sib
| 309,776,675
| false
| null |
package com.nick_sib.popularlibraries.di.repository
import com.nick_sib.popularlibraries.di.repository.module.RepositoryModule
import com.nick_sib.popularlibraries.mvp.presenters.ReposPresenter
import dagger.Subcomponent
@RepositoryScope
@Subcomponent(
modules = [
RepositoryModule::class
]
)
interface RepositorySubComponent {
fun inject(reposPresenter: ReposPresenter)
}
| 0
|
Kotlin
|
0
| 0
|
2be9c427a3881bf9774c72471505c69f1e08f74f
| 396
|
Popular-libraries
|
The Unlicense
|
src/commonMain/kotlin/wizard/files/composeApp/IosProject.kt
|
terrakok
| 618,540,934
| false
| null |
package wizard.files.app
import wizard.ProjectFile
import wizard.ProjectInfo
class IosAppIcon : ProjectFile {
override val path = "iosApp/iosApp/Assets.xcassets/AppIcon.appiconset/Contents.json"
override val content = """
{
"images" : [
{
"idiom" : "universal",
"platform" : "ios",
"size" : "1024x1024"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
""".trimIndent()
}
class IosAccentColor : ProjectFile {
override val path = "iosApp/iosApp/Assets.xcassets/AccentColor.colorset/Contents.json"
override val content = """
{
"colors" : [
{
"idiom" : "universal"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
""".trimIndent()
}
class IosAssets : ProjectFile {
override val path = "iosApp/iosApp/Assets.xcassets/Contents.json"
override val content = """
{
"info" : {
"author" : "xcode",
"version" : 1
}
}
""".trimIndent()
}
class IosPreviewAssets : ProjectFile {
override val path = "iosApp/iosApp/Preview Content/Preview Assets.xcassets/Contents.json"
override val content = """
{
"info" : {
"author" : "xcode",
"version" : 1
}
}
""".trimIndent()
}
class IosAppSwift : ProjectFile {
override val path = "iosApp/iosApp/iosApp.swift"
override val content = """
import UIKit
import SwiftUI
import ComposeApp
@main
struct iosApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
struct ContentView: View {
@State private var colorScheme: ColorScheme = .dark
var body: some View {
ComposeView(setScheme: { scheme in colorScheme = scheme })
.ignoresSafeArea(.all)
.preferredColorScheme(colorScheme)
}
}
struct ComposeView: UIViewControllerRepresentable {
var setScheme: (ColorScheme) -> Void
init(setScheme: @escaping (ColorScheme) -> Void) {
self.setScheme = setScheme
}
func makeUIViewController(context: Context) -> UIViewController {
MainKt.MainViewController { isLight in
setScheme(isLight.boolValue ? .light : .dark)
}
}
func updateUIViewController(_ uiViewController: UIViewController, context: Context) {}
}
""".trimIndent()
}
class IosXcworkspace : ProjectFile {
override val path = "iosApp/iosApp.xcodeproj/project.xcworkspace/contents.xcworkspacedata"
override val content = """
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "self:">
</FileRef>
</Workspace>
""".trimIndent()
}
class IosPbxproj(info: ProjectInfo) : ProjectFile {
override val path = "iosApp/iosApp.xcodeproj/project.pbxproj"
override val content = """
// !${'$'}*UTF8*${'$'}!
{
archiveVersion = 1;
classes = {
};
objectVersion = 50;
objects = {
/* Begin PBXBuildFile section */
A93A953B29CC810C00F8E227 /* iosApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = A93A953A29CC810C00F8E227 /* iosApp.swift */; };
A93A953F29CC810D00F8E227 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = A93A953E29CC810D00F8E227 /* Assets.xcassets */; };
A93A954229CC810D00F8E227 /* Preview Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = A93A954129CC810D00F8E227 /* Preview Assets.xcassets */; };
/* End PBXBuildFile section */
/* Begin PBXFileReference section */
A93A953729CC810C00F8E227 /* ${info.name}.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "${info.name}.app"; sourceTree = BUILT_PRODUCTS_DIR; };
A93A953A29CC810C00F8E227 /* iosApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = iosApp.swift; sourceTree = "<group>"; };
A93A953E29CC810D00F8E227 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
A93A954129CC810D00F8E227 /* Preview Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = "Preview Assets.xcassets"; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
A93A953429CC810C00F8E227 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
A93A952E29CC810C00F8E227 = {
isa = PBXGroup;
children = (
A93A953929CC810C00F8E227 /* iosApp */,
A93A953829CC810C00F8E227 /* Products */,
C4127409AE3703430489E7BC /* Frameworks */,
);
sourceTree = "<group>";
};
A93A953829CC810C00F8E227 /* Products */ = {
isa = PBXGroup;
children = (
A93A953729CC810C00F8E227 /* ${info.name}.app */,
);
name = Products;
sourceTree = "<group>";
};
A93A953929CC810C00F8E227 /* iosApp */ = {
isa = PBXGroup;
children = (
A93A953A29CC810C00F8E227 /* iosApp.swift */,
A93A953E29CC810D00F8E227 /* Assets.xcassets */,
A93A954029CC810D00F8E227 /* Preview Content */,
);
path = iosApp;
sourceTree = "<group>";
};
A93A954029CC810D00F8E227 /* Preview Content */ = {
isa = PBXGroup;
children = (
A93A954129CC810D00F8E227 /* Preview Assets.xcassets */,
);
path = "Preview Content";
sourceTree = "<group>";
};
C4127409AE3703430489E7BC /* Frameworks */ = {
isa = PBXGroup;
children = (
);
name = Frameworks;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
A93A953629CC810C00F8E227 /* iosApp */ = {
isa = PBXNativeTarget;
buildConfigurationList = A93A954529CC810D00F8E227 /* Build configuration list for PBXNativeTarget "iosApp" */;
buildPhases = (
A9D80A052AAB5CDE006C8738 /* ShellScript */,
A93A953329CC810C00F8E227 /* Sources */,
A93A953429CC810C00F8E227 /* Frameworks */,
A93A953529CC810C00F8E227 /* Resources */,
);
buildRules = (
);
dependencies = (
);
name = iosApp;
productName = iosApp;
productReference = A93A953729CC810C00F8E227 /* ${info.name}.app */;
productType = "com.apple.product-type.application";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
A93A952F29CC810C00F8E227 /* Project object */ = {
isa = PBXProject;
attributes = {
LastSwiftUpdateCheck = 1420;
LastUpgradeCheck = 1420;
TargetAttributes = {
A93A953629CC810C00F8E227 = {
CreatedOnToolsVersion = 14.2;
};
};
};
buildConfigurationList = A93A953229CC810C00F8E227 /* Build configuration list for PBXProject "iosApp" */;
compatibilityVersion = "Xcode 14.0";
developmentRegion = en;
hasScannedForEncodings = 0;
knownRegions = (
en,
Base,
);
mainGroup = A93A952E29CC810C00F8E227;
productRefGroup = A93A953829CC810C00F8E227 /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
A93A953629CC810C00F8E227 /* iosApp */,
);
};
/* End PBXProject section */
/* Begin PBXResourcesBuildPhase section */
A93A953529CC810C00F8E227 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
A93A954229CC810D00F8E227 /* Preview Assets.xcassets in Resources */,
A93A953F29CC810D00F8E227 /* Assets.xcassets in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXShellScriptBuildPhase section */
A9D80A052AAB5CDE006C8738 /* ShellScript */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
);
inputPaths = (
);
outputFileListPaths = (
);
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "cd \"${'$'}SRCROOT/..\"\n./gradlew :composeApp:embedAndSignAppleFrameworkForXcode\n";
};
/* End PBXShellScriptBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
A93A953329CC810C00F8E227 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
A93A953B29CC810C00F8E227 /* iosApp.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin XCBuildConfiguration section */
A93A954329CC810D00F8E227 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
GCC_C_LANGUAGE_STANDARD = gnu11;
GCC_DYNAMIC_NO_PIC = NO;
GCC_NO_COMMON_BLOCKS = YES;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"${'$'}(inherited)",
);
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 16.2;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = iphoneos;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
};
name = Debug;
};
A93A954429CC810D00F8E227 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
GCC_C_LANGUAGE_STANDARD = gnu11;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 16.2;
MTL_ENABLE_DEBUG_INFO = NO;
MTL_FAST_MATH = YES;
SDKROOT = iphoneos;
SWIFT_COMPILATION_MODE = wholemodule;
SWIFT_OPTIMIZATION_LEVEL = "-O";
VALIDATE_PRODUCT = YES;
};
name = Release;
};
A93A954629CC810D00F8E227 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
DEVELOPMENT_ASSET_PATHS = "\"iosApp/Preview Content\"";
ENABLE_PREVIEWS = YES;
FRAMEWORK_SEARCH_PATHS = (
"${'$'}{inherited}",
"${'$'}(SRCROOT)/../composeApp/build/xcode-frameworks/${'$'}(CONFIGURATION)/${'$'}(SDK_NAME)",
);
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES;
INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES;
INFOPLIST_KEY_UILaunchScreen_Generation = YES;
INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";
INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";
LD_RUNPATH_SEARCH_PATHS = (
"${'$'}(inherited)",
"@executable_path/Frameworks",
);
MARKETING_VERSION = 1.0;
OTHER_LDFLAGS = (
"${'$'}{inherited}",
"-framework",
ComposeApp,
);
PRODUCT_BUNDLE_IDENTIFIER = ${info.packageId}.iosApp;
PRODUCT_NAME = "${info.name}";
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Debug;
};
A93A954729CC810D00F8E227 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
DEVELOPMENT_ASSET_PATHS = "\"iosApp/Preview Content\"";
ENABLE_PREVIEWS = YES;
FRAMEWORK_SEARCH_PATHS = (
"${'$'}{inherited}",
"${'$'}(SRCROOT)/../composeApp/build/xcode-frameworks/${'$'}(CONFIGURATION)/${'$'}(SDK_NAME)",
);
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES;
INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES;
INFOPLIST_KEY_UILaunchScreen_Generation = YES;
INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";
INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";
LD_RUNPATH_SEARCH_PATHS = (
"${'$'}(inherited)",
"@executable_path/Frameworks",
);
MARKETING_VERSION = 1.0;
OTHER_LDFLAGS = (
"${'$'}{inherited}",
"-framework",
ComposeApp,
);
PRODUCT_BUNDLE_IDENTIFIER = ${info.packageId}.iosApp;
PRODUCT_NAME = "${info.name}";
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
A93A953229CC810C00F8E227 /* Build configuration list for PBXProject "iosApp" */ = {
isa = XCConfigurationList;
buildConfigurations = (
A93A954329CC810D00F8E227 /* Debug */,
A93A954429CC810D00F8E227 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
A93A954529CC810D00F8E227 /* Build configuration list for PBXNativeTarget "iosApp" */ = {
isa = XCConfigurationList;
buildConfigurations = (
A93A954629CC810D00F8E227 /* Debug */,
A93A954729CC810D00F8E227 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
};
rootObject = A93A952F29CC810C00F8E227 /* Project object */;
}
""".trimIndent()
}
| 9
| null |
30
| 439
|
d61bd739f0443940441eec1986c5b58fa40f5f89
| 21,880
|
Compose-Multiplatform-Wizard
|
MIT License
|
recycler/src/main/java/com/elpassion/android/commons/recycler/adapters/Adapters.kt
|
mg6maciej
| 90,137,933
| true
|
{"Kotlin": 155349, "Shell": 3364}
|
@file:JvmName("Adapters")
package com.elpassion.android.commons.recycler.adapters
import android.support.v7.widget.RecyclerView
import android.view.View
import android.view.ViewGroup
import com.elpassion.android.commons.recycler.RecyclerViewCompositeAdapter
import com.elpassion.android.commons.recycler.basic.BasicAdapter
import com.elpassion.android.commons.recycler.basic.BasicList
import com.elpassion.android.commons.recycler.basic.BasicViewHolder
import com.elpassion.android.commons.recycler.components.ItemsStrategy
import com.elpassion.android.commons.recycler.components.base.ItemAdapter
import com.elpassion.android.commons.recycler.components.base.ListItemsStrategy
import com.elpassion.android.commons.recycler.components.base.MutableListItemsStrategy
import com.elpassion.android.commons.recycler.components.group.SectionedItemsStrategy
import com.elpassion.android.commons.recycler.components.stable.StableItemAdapter
import com.elpassion.android.commons.recycler.components.stable.createStableIdInitialization
import com.elpassion.android.commons.recycler.components.stable.getStableItemIdentifier
import com.elpassion.android.view.inflate
import java.util.*
fun recyclerViewAdapter(
adapters: List<ItemAdapter<*>>
) = RecyclerViewCompositeAdapter(ListItemsStrategy(adapters))
fun mutableRecyclerViewAdapter(
adapters: MutableList<ItemAdapter<*>> = mutableListOf()
) = RecyclerViewCompositeAdapter(MutableListItemsStrategy(adapters))
fun stableRecyclerViewAdapter(
itemsStrategy: ItemsStrategy<StableItemAdapter<out RecyclerView.ViewHolder>>
) = RecyclerViewCompositeAdapter(
itemsStrategy = itemsStrategy,
getItemIdentifier = getStableItemIdentifier(itemsStrategy),
init = createStableIdInitialization()
)
fun <Section, Item : StableItemAdapter<out RecyclerView.ViewHolder>> stableSectionedRecyclerViewAdapter(
itemsStrategy: SectionedItemsStrategy<Section, Item>
) = RecyclerViewCompositeAdapter(
itemsStrategy = itemsStrategy,
getItemIdentifier = getStableItemIdentifier(itemsStrategy),
init = createStableIdInitialization()
)
fun <Item> basicAdapterWithHolder(items: BasicList<Item>, createHolder: (parent: ViewGroup) -> BasicViewHolder<Item>) =
object : BasicAdapter<Item>(items) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = createHolder(parent)
}
fun <Item> basicAdapterWithLayoutAndBinder(
items: BasicList<Item>,
layout: Int,
binder: (holder: BasicViewHolder<Item>, item: Item) -> Unit
) = basicAdapterWithHolder(items) { parent ->
object : BasicViewHolder<Item>(parent.inflate(layout)) {
override fun bind(item: Item) = binder(this, item)
}
}
fun <Item> basicAdapterWithCreator(
items: BasicList<Item>,
getTypeAndCreator: (position: Int) -> Pair<Int, (parent: ViewGroup) -> BasicViewHolder<Item>>
) = object : BasicAdapter<Item>(items) {
private val creators = HashMap<Int, (parent: ViewGroup) -> BasicViewHolder<Item>>()
override fun getItemViewType(position: Int): Int {
val (type, creator) = getTypeAndCreator(position)
creators[type] = creator
return type
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = creators[viewType]!!(parent)
}
fun <Item> basicAdapterWithConstructors(
items: BasicList<Item>,
getLayoutAndConstructor: (position: Int) -> Pair<Int, (itemView: View) -> BasicViewHolder<Item>>
) = basicAdapterWithCreator(items) { position ->
val (layout, constructor) = getLayoutAndConstructor(position)
layout to { parent: ViewGroup -> constructor(parent.inflate(layout)) }
}
| 0
|
Kotlin
|
1
| 0
|
e6c09cf0da2ae9e847fd733018b2b7d1864626de
| 3,699
|
el-android-commons
|
Apache License 2.0
|
spring/src/test/kotlin/de/codecentric/hikaku/converters/spring/httpmethod/SpringConverterHttpMethodTest.kt
|
codecentric
| 167,929,609
| false
|
{"Kotlin": 731151, "RAML": 5024, "Shell": 1492}
|
package de.codecentric.hikaku.converters.spring.httpmethod
import de.codecentric.hikaku.converters.spring.SpringConverter
import de.codecentric.hikaku.endpoints.Endpoint
import de.codecentric.hikaku.endpoints.HttpMethod.*
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
import org.springframework.context.ConfigurableApplicationContext
import org.springframework.http.MediaType.APPLICATION_JSON_VALUE
import org.springframework.http.MediaType.TEXT_HTML_VALUE
class HttpMethodTestController {
@Nested
inner class RequestMappingTests {
@Nested
inner class ClassLevelTests {
@Nested
@WebMvcTest(RequestMappingDefinedOnClassWithExplicitGetMethodController::class, excludeAutoConfiguration = [ErrorMvcAutoConfiguration::class])
inner class DefinedOnClassWithExplicitGetMethodTest {
@Autowired
lateinit var context: ConfigurableApplicationContext
@Test
fun `endpoint defined on class having explicit GET method definition is extracted correctly`() {
//given
val specification: Set<Endpoint> = setOf(
Endpoint("/todos", GET),
Endpoint("/todos", OPTIONS),
Endpoint("/todos", HEAD)
)
//when
val implementation = SpringConverter(context)
//then
assertThat(implementation.conversionResult).containsExactlyInAnyOrderElementsOf(specification)
}
}
@Nested
@WebMvcTest(RequestMappingDefinedOnClassWithExplicitPostMethodController::class, excludeAutoConfiguration = [ErrorMvcAutoConfiguration::class])
inner class DefinedOnClassWithExplicitPostMethodTest {
@Autowired
lateinit var context: ConfigurableApplicationContext
@Test
fun `endpoint defined on class having explicit POST method definition is extracted correctly`() {
//given
val specification: Set<Endpoint> = setOf(
Endpoint("/todos", POST),
Endpoint("/todos", OPTIONS),
Endpoint("/todos", HEAD)
)
//when
val implementation = SpringConverter(context)
//then
assertThat(implementation.conversionResult).containsExactlyInAnyOrderElementsOf(specification)
}
}
@Nested
@WebMvcTest(RequestMappingDefinedOnClassWithExplicitHeadMethodController::class, excludeAutoConfiguration = [ErrorMvcAutoConfiguration::class])
inner class DefinedOnClassWithExplicitHeadMethodTest {
@Autowired
lateinit var context: ConfigurableApplicationContext
@Test
fun `endpoint defined on class having explicit HEAD method definition is extracted correctly`() {
//given
val specification: Set<Endpoint> = setOf(
Endpoint("/todos", OPTIONS),
Endpoint("/todos", HEAD)
)
//when
val implementation = SpringConverter(context)
//then
assertThat(implementation.conversionResult).containsExactlyInAnyOrderElementsOf(specification)
}
}
@Nested
@WebMvcTest(RequestMappingDefinedOnClassWithExplicitPutMethodController::class, excludeAutoConfiguration = [ErrorMvcAutoConfiguration::class])
inner class DefinedOnClassWithExplicitPutMethodTest {
@Autowired
lateinit var context: ConfigurableApplicationContext
@Test
fun `endpoint defined on class having explicit PUT method definition is extracted correctly`() {
//given
val specification: Set<Endpoint> = setOf(
Endpoint("/todos", PUT),
Endpoint("/todos", OPTIONS),
Endpoint("/todos", HEAD)
)
//when
val implementation = SpringConverter(context)
//then
assertThat(implementation.conversionResult).containsExactlyInAnyOrderElementsOf(specification)
}
}
@Nested
@WebMvcTest(RequestMappingDefinedOnClassWithExplicitPatchMethodController::class, excludeAutoConfiguration = [ErrorMvcAutoConfiguration::class])
inner class DefinedOnClassWithExplicitPatchMethodTest {
@Autowired
lateinit var context: ConfigurableApplicationContext
@Test
fun `endpoint defined on class having explicit PATCH method definition is extracted correctly`() {
//given
val specification: Set<Endpoint> = setOf(
Endpoint("/todos", PATCH),
Endpoint("/todos", OPTIONS),
Endpoint("/todos", HEAD)
)
//when
val implementation = SpringConverter(context)
//then
assertThat(implementation.conversionResult).containsExactlyInAnyOrderElementsOf(specification)
}
}
@Nested
@WebMvcTest(RequestMappingDefinedOnClassWithExplicitDeleteMethodController::class, excludeAutoConfiguration = [ErrorMvcAutoConfiguration::class])
inner class DefinedOnClassWithExplicitDeleteMethodTest {
@Autowired
lateinit var context: ConfigurableApplicationContext
@Test
fun `endpoint defined on class having explicit DELETE method definition is extracted correctly`() {
//given
val specification: Set<Endpoint> = setOf(
Endpoint("/todos", DELETE),
Endpoint("/todos", OPTIONS),
Endpoint("/todos", HEAD)
)
//when
val implementation = SpringConverter(context)
//then
assertThat(implementation.conversionResult).containsExactlyInAnyOrderElementsOf(specification)
}
}
@Nested
@WebMvcTest(RequestMappingDefinedOnClassWithExplicitTraceMethodController::class, excludeAutoConfiguration = [ErrorMvcAutoConfiguration::class])
inner class DefinedOnClassWithExplicitTraceMethodTest {
@Autowired
lateinit var context: ConfigurableApplicationContext
@Test
fun `endpoint defined on class having explicit TRACE method definition is extracted correctly`() {
//given
val specification: Set<Endpoint> = setOf(
Endpoint("/todos", TRACE),
Endpoint("/todos", OPTIONS),
Endpoint("/todos", HEAD)
)
//when
val implementation = SpringConverter(context)
//then
assertThat(implementation.conversionResult).containsExactlyInAnyOrderElementsOf(specification)
}
}
@Nested
@WebMvcTest(RequestMappingDefinedOnClassWithExplicitOptionsMethodController::class, excludeAutoConfiguration = [ErrorMvcAutoConfiguration::class])
inner class DefinedOnClassWithExplicitOptionsMethodTest {
@Autowired
lateinit var context: ConfigurableApplicationContext
@Test
fun `endpoint defined on class having explicit OPTIONS method definition is extracted correctly`() {
//given
val specification: Set<Endpoint> = setOf(
Endpoint("/todos", OPTIONS),
Endpoint("/todos", HEAD)
)
//when
val implementation = SpringConverter(context)
//then
assertThat(implementation.conversionResult).containsExactlyInAnyOrderElementsOf(specification)
}
}
@Nested
@WebMvcTest(RequestMappingDefinedOnClassNoHttpMethodDefinedController::class, excludeAutoConfiguration = [ErrorMvcAutoConfiguration::class])
inner class NoHttpMethodDefinedTest {
@Autowired
lateinit var context: ConfigurableApplicationContext
@Test
fun `no http method defined means that spring supports all http methods except for trace`() {
//given
val specification: Set<Endpoint> = setOf(
Endpoint("/todos", GET),
Endpoint("/todos", PUT),
Endpoint("/todos", POST),
Endpoint("/todos", DELETE),
Endpoint("/todos", PATCH),
Endpoint("/todos", HEAD),
Endpoint("/todos", OPTIONS)
)
//when
val implementation = SpringConverter(context)
//then
assertThat(implementation.conversionResult).containsExactlyInAnyOrderElementsOf(specification)
}
}
@Nested
@WebMvcTest(RequestMappingDefinedOnClassWithMultipleMethodsController::class, excludeAutoConfiguration = [ErrorMvcAutoConfiguration::class])
inner class DefinedOnClassWithMultipleMethodsTest {
@Autowired
lateinit var context: ConfigurableApplicationContext
@Test
fun `endpoint providing multiple http methods`() {
//given
val specification: Set<Endpoint> = setOf(
Endpoint("/todos", PUT),
Endpoint("/todos", PATCH),
Endpoint("/todos", TRACE),
Endpoint("/todos", OPTIONS),
Endpoint("/todos", HEAD)
)
//when
val implementation = SpringConverter(context)
//then
assertThat(implementation.conversionResult).containsExactlyInAnyOrderElementsOf(specification)
}
}
}
@Nested
inner class FunctionLevelTests {
@Nested
@WebMvcTest(RequestMappingDefinedOnFunctionWithExplicitGetMethodController::class, excludeAutoConfiguration = [ErrorMvcAutoConfiguration::class])
inner class DefinedOnFunctionWithExplicitGetMethodTest {
@Autowired
lateinit var context: ConfigurableApplicationContext
@Test
fun `endpoint defined on class having explicit GET method definition is extracted correctly`() {
//given
val specification: Set<Endpoint> = setOf(
Endpoint("/todos", GET),
Endpoint("/todos", OPTIONS),
Endpoint("/todos", HEAD)
)
//when
val implementation = SpringConverter(context)
//then
assertThat(implementation.conversionResult).containsExactlyInAnyOrderElementsOf(specification)
}
}
@Nested
@WebMvcTest(RequestMappingDefinedOnFunctionWithExplicitPostMethodController::class, excludeAutoConfiguration = [ErrorMvcAutoConfiguration::class])
inner class DefinedOnFunctionWithExplicitPostMethodTest {
@Autowired
lateinit var context: ConfigurableApplicationContext
@Test
fun `endpoint defined on class having explicit POST method definition is extracted correctly`() {
//given
val specification: Set<Endpoint> = setOf(
Endpoint("/todos", POST),
Endpoint("/todos", OPTIONS),
Endpoint("/todos", HEAD)
)
//when
val implementation = SpringConverter(context)
//then
assertThat(implementation.conversionResult).containsExactlyInAnyOrderElementsOf(specification)
}
}
@Nested
@WebMvcTest(RequestMappingDefinedOnFunctionWithExplicitHeadMethodController::class, excludeAutoConfiguration = [ErrorMvcAutoConfiguration::class])
inner class DefinedOnFunctionWithExplicitHeadMethodTest {
@Autowired
lateinit var context: ConfigurableApplicationContext
@Test
fun `endpoint defined on class having explicit HEAD method definition is extracted correctly`() {
//given
val specification: Set<Endpoint> = setOf(
Endpoint("/todos", OPTIONS),
Endpoint("/todos", HEAD)
)
//when
val implementation = SpringConverter(context)
//then
assertThat(implementation.conversionResult).containsExactlyInAnyOrderElementsOf(specification)
}
}
@Nested
@WebMvcTest(RequestMappingDefinedOnFunctionWithExplicitPutMethodController::class, excludeAutoConfiguration = [ErrorMvcAutoConfiguration::class])
inner class DefinedOnFunctionWithExplicitPutMethodTest {
@Autowired
lateinit var context: ConfigurableApplicationContext
@Test
fun `endpoint defined on class having explicit PUT method definition is extracted correctly`() {
//given
val specification: Set<Endpoint> = setOf(
Endpoint("/todos", PUT),
Endpoint("/todos", OPTIONS),
Endpoint("/todos", HEAD)
)
//when
val implementation = SpringConverter(context)
//then
assertThat(implementation.conversionResult).containsExactlyInAnyOrderElementsOf(specification)
}
}
@Nested
@WebMvcTest(RequestMappingDefinedOnFunctionWithExplicitPatchMethodController::class, excludeAutoConfiguration = [ErrorMvcAutoConfiguration::class])
inner class DefinedOnFunctionWithExplicitPatchMethodTest {
@Autowired
lateinit var context: ConfigurableApplicationContext
@Test
fun `endpoint defined on class having explicit PATCH method definition is extracted correctly`() {
//given
val specification: Set<Endpoint> = setOf(
Endpoint("/todos", PATCH),
Endpoint("/todos", OPTIONS),
Endpoint("/todos", HEAD)
)
//when
val implementation = SpringConverter(context)
//then
assertThat(implementation.conversionResult).containsExactlyInAnyOrderElementsOf(specification)
}
}
@Nested
@WebMvcTest(RequestMappingDefinedOnFunctionWithExplicitDeleteMethodController::class, excludeAutoConfiguration = [ErrorMvcAutoConfiguration::class])
inner class DefinedOnFunctionWithExplicitDeleteMethodTest {
@Autowired
lateinit var context: ConfigurableApplicationContext
@Test
fun `endpoint defined on class having explicit DELETE method definition is extracted correctly`() {
//given
val specification: Set<Endpoint> = setOf(
Endpoint("/todos", DELETE),
Endpoint("/todos", OPTIONS),
Endpoint("/todos", HEAD)
)
//when
val implementation = SpringConverter(context)
//then
assertThat(implementation.conversionResult).containsExactlyInAnyOrderElementsOf(specification)
}
}
@Nested
@WebMvcTest(RequestMappingDefinedOnFunctionWithExplicitTraceMethodController::class, excludeAutoConfiguration = [ErrorMvcAutoConfiguration::class])
inner class DefinedOnFunctionWithExplicitTraceMethodTest {
@Autowired
lateinit var context: ConfigurableApplicationContext
@Test
fun `endpoint defined on class having explicit TRACE method definition is extracted correctly`() {
//given
val specification: Set<Endpoint> = setOf(
Endpoint("/todos", TRACE),
Endpoint("/todos", OPTIONS),
Endpoint("/todos", HEAD)
)
//when
val implementation = SpringConverter(context)
//then
assertThat(implementation.conversionResult).containsExactlyInAnyOrderElementsOf(specification)
}
}
@Nested
@WebMvcTest(RequestMappingDefinedOnFunctionWithExplicitOptionsMethodController::class, excludeAutoConfiguration = [ErrorMvcAutoConfiguration::class])
inner class DefinedOnFunctionWithExplicitOptionsMethodTest {
@Autowired
lateinit var context: ConfigurableApplicationContext
@Test
fun `endpoint defined on class having explicit OPTIONS method definition is extracted correctly`() {
//given
val specification: Set<Endpoint> = setOf(
Endpoint("/todos", OPTIONS),
Endpoint("/todos", HEAD)
)
//when
val implementation = SpringConverter(context)
//then
assertThat(implementation.conversionResult).containsExactlyInAnyOrderElementsOf(specification)
}
}
@Nested
@WebMvcTest(RequestMappingDefinedOnFunctionNoHttpMethodDefinedController::class, excludeAutoConfiguration = [ErrorMvcAutoConfiguration::class])
inner class NoHttpMethodDefinedTest {
@Autowired
lateinit var context: ConfigurableApplicationContext
@Test
fun `no http method defined means that spring supports all http methods except for trace`() {
//given
val specification: Set<Endpoint> = setOf(
Endpoint("/todos", GET),
Endpoint("/todos", PUT),
Endpoint("/todos", POST),
Endpoint("/todos", DELETE),
Endpoint("/todos", PATCH),
Endpoint("/todos", HEAD),
Endpoint("/todos", OPTIONS)
)
//when
val implementation = SpringConverter(context)
//then
assertThat(implementation.conversionResult).containsExactlyInAnyOrderElementsOf(specification)
}
}
@Nested
@WebMvcTest(RequestMappingDefinedOnFunctionWithMultipleMethodsController::class, excludeAutoConfiguration = [ErrorMvcAutoConfiguration::class])
inner class DefinedOnClassWithMultipleMethodsTest {
@Autowired
lateinit var context: ConfigurableApplicationContext
@Test
fun `endpoint providing multiple http methods`() {
//given
val specification: Set<Endpoint> = setOf(
Endpoint("/todos", PUT),
Endpoint("/todos", PATCH),
Endpoint("/todos", TRACE),
Endpoint("/todos", OPTIONS),
Endpoint("/todos", HEAD)
)
//when
val implementation = SpringConverter(context)
//then
assertThat(implementation.conversionResult).containsExactlyInAnyOrderElementsOf(specification)
}
}
}
}
@Nested
inner class HttpMethodMappingAnnotationTests {
@Nested
@WebMvcTest(GetMappingController::class, excludeAutoConfiguration = [ErrorMvcAutoConfiguration::class])
inner class GetMappingControllerTest {
@Autowired
lateinit var context: ConfigurableApplicationContext
@Test
fun `endpoint defined on function using GetMapping anbnotation is extracted correctly`() {
//given
val specification: Set<Endpoint> = setOf(
Endpoint("/todos", GET),
Endpoint("/todos", OPTIONS),
Endpoint("/todos", HEAD)
)
//when
val implementation = SpringConverter(context)
//then
assertThat(implementation.conversionResult).containsExactlyInAnyOrderElementsOf(specification)
}
}
@Nested
@WebMvcTest(DeleteMappingController::class, excludeAutoConfiguration = [ErrorMvcAutoConfiguration::class])
inner class DeleteMappingControllerTest {
@Autowired
lateinit var context: ConfigurableApplicationContext
@Test
fun `endpoint defined on function using DeleteMapping anbnotation is extracted correctly`() {
//given
val specification: Set<Endpoint> = setOf(
Endpoint("/todos", DELETE),
Endpoint("/todos", OPTIONS),
Endpoint("/todos", HEAD)
)
//when
val implementation = SpringConverter(context)
//then
assertThat(implementation.conversionResult).containsExactlyInAnyOrderElementsOf(specification)
}
}
@Nested
@WebMvcTest(PatchMappingController::class, excludeAutoConfiguration = [ErrorMvcAutoConfiguration::class])
inner class PatchMappingControllerTest {
@Autowired
lateinit var context: ConfigurableApplicationContext
@Test
fun `endpoint defined on function using PatchMapping anbnotation is extracted correctly`() {
//given
val specification: Set<Endpoint> = setOf(
Endpoint("/todos", PATCH),
Endpoint("/todos", OPTIONS),
Endpoint("/todos", HEAD)
)
//when
val implementation = SpringConverter(context)
//then
assertThat(implementation.conversionResult).containsExactlyInAnyOrderElementsOf(specification)
}
}
@Nested
@WebMvcTest(PostMappingController::class, excludeAutoConfiguration = [ErrorMvcAutoConfiguration::class])
inner class PostMappingControllerTest {
@Autowired
lateinit var context: ConfigurableApplicationContext
@Test
fun `endpoint defined on function using PostMapping anbnotation is extracted correctly`() {
//given
val specification: Set<Endpoint> = setOf(
Endpoint("/todos", POST),
Endpoint("/todos", OPTIONS),
Endpoint("/todos", HEAD)
)
//when
val implementation = SpringConverter(context)
//then
assertThat(implementation.conversionResult).containsExactlyInAnyOrderElementsOf(specification)
}
}
@Nested
@WebMvcTest(PutMappingController::class, excludeAutoConfiguration = [ErrorMvcAutoConfiguration::class])
inner class PutMappingControllerTest {
@Autowired
lateinit var context: ConfigurableApplicationContext
@Test
fun `endpoint defined on function using PutMapping anbnotation is extracted correctly`() {
//given
val specification: Set<Endpoint> = setOf(
Endpoint("/todos", PUT),
Endpoint("/todos", OPTIONS),
Endpoint("/todos", HEAD)
)
//when
val implementation = SpringConverter(context)
//then
assertThat(implementation.conversionResult).containsExactlyInAnyOrderElementsOf(specification)
}
}
@Nested
inner class HttpMethodMappingAnnotationTests {
@Nested
@WebMvcTest(MultipleHttpMethodMappingAnnotationsController::class, excludeAutoConfiguration = [ErrorMvcAutoConfiguration::class])
inner class MultipleHttpMethodMappingAnnotationsTest {
@Autowired
lateinit var context: ConfigurableApplicationContext
@Test
fun `multiple HttpMethodMapping annotations are not supported by spring - most outer annotation wins`() {
//given
val specification: Set<Endpoint> = setOf(
Endpoint("/todos", GET),
Endpoint("/todos", OPTIONS),
Endpoint("/todos", HEAD)
)
//when
val implementation = SpringConverter(context)
//then
assertThat(implementation.conversionResult).containsExactlyInAnyOrderElementsOf(specification)
}
}
}
}
@Nested
inner class ConjunctionTests {
@Nested
@WebMvcTest(RequestMappingDefinedOnClassAndFunctionWithDifferentHttpMethodsController::class, excludeAutoConfiguration = [ErrorMvcAutoConfiguration::class])
inner class DefinedOnClassAndFunctionWithDifferentHttpMethodsTest {
@Autowired
lateinit var context: ConfigurableApplicationContext
@Test
fun `No overwrite for RequestMapping defined on class and function for the same path with different http methods - instead both http methods will be supported`() {
//given
val specification: Set<Endpoint> = setOf(
Endpoint("/todos", PUT),
Endpoint("/todos", PATCH),
Endpoint("/todos", OPTIONS),
Endpoint("/todos", HEAD)
)
//when
val implementation = SpringConverter(context)
//then
assertThat(implementation.conversionResult).containsExactlyInAnyOrderElementsOf(specification)
}
}
@Nested
@WebMvcTest(RequestMappingDefinedOnClassAndFunctionWithDifferentHttpMethodsAndDifferentPathsController::class, excludeAutoConfiguration = [ErrorMvcAutoConfiguration::class])
inner class DefinedOnClassAndFunctionWithDifferentHttpMethodsAndDifferentPathsTest {
@Autowired
lateinit var context: ConfigurableApplicationContext
@Test
fun `RequestMapping defined on class and function for the different paths with different http methods will create two endpoints with combined http methods for the nested path`() {
//given
val specification: Set<Endpoint> = setOf(
Endpoint("/todos", GET),
Endpoint("/todos", OPTIONS),
Endpoint("/todos", HEAD),
Endpoint("/todos/{id}", GET),
Endpoint("/todos/{id}", PUT),
Endpoint("/todos/{id}", OPTIONS),
Endpoint("/todos/{id}", HEAD)
)
//when
val implementation = SpringConverter(context)
//then
assertThat(implementation.conversionResult).containsExactlyInAnyOrderElementsOf(specification)
}
}
@Nested
@WebMvcTest(RequestMappingWithPostAndGetMappingInCombinationController::class, excludeAutoConfiguration = [ErrorMvcAutoConfiguration::class])
inner class RequestMappingWithPostAndGetMappingInCombinationTest {
@Autowired
lateinit var context: ConfigurableApplicationContext
@Test
fun `RequestMapping providing POST defined on class and GetMapping on function`() {
//given
val specification: Set<Endpoint> = setOf(
Endpoint("/todos", GET),
Endpoint("/todos", POST),
Endpoint("/todos", OPTIONS),
Endpoint("/todos", HEAD)
)
//when
val implementation = SpringConverter(context)
//then
assertThat(implementation.conversionResult).containsExactlyInAnyOrderElementsOf(specification)
}
}
@Nested
@WebMvcTest(RequestMappingWithPostAndDeleteMappingInCombinationController::class, excludeAutoConfiguration = [ErrorMvcAutoConfiguration::class])
inner class RequestMappingWithPostAndDeleteMappingInCombinationTest {
@Autowired
lateinit var context: ConfigurableApplicationContext
@Test
fun `RequestMapping providing POST defined on class and DeleteMapping on function`() {
//given
val specification: Set<Endpoint> = setOf(
Endpoint("/todos", DELETE),
Endpoint("/todos", POST),
Endpoint("/todos", OPTIONS),
Endpoint("/todos", HEAD)
)
//when
val implementation = SpringConverter(context)
//then
assertThat(implementation.conversionResult).containsExactlyInAnyOrderElementsOf(specification)
}
}
@Nested
@WebMvcTest(RequestMappingWithPostAndPatchMappingInCombinationController::class, excludeAutoConfiguration = [ErrorMvcAutoConfiguration::class])
inner class RequestMappingWithPostAndPatchMappingInCombinationTest {
@Autowired
lateinit var context: ConfigurableApplicationContext
@Test
fun `RequestMapping providing POST defined on class and PatchMapping on function`() {
//given
val specification: Set<Endpoint> = setOf(
Endpoint("/todos", PATCH),
Endpoint("/todos", POST),
Endpoint("/todos", OPTIONS),
Endpoint("/todos", HEAD)
)
//when
val implementation = SpringConverter(context)
//then
assertThat(implementation.conversionResult).containsExactlyInAnyOrderElementsOf(specification)
}
}
@Nested
@WebMvcTest(RequestMappingWithTraceAndPostMappingInCombinationController::class, excludeAutoConfiguration = [ErrorMvcAutoConfiguration::class])
inner class RequestMappingWithTraceAndPostMappingInCombinationTest {
@Autowired
lateinit var context: ConfigurableApplicationContext
@Test
fun `RequestMapping providing TRACE defined on class and PostMapping on function`() {
//given
val specification: Set<Endpoint> = setOf(
Endpoint("/todos", POST),
Endpoint("/todos", TRACE),
Endpoint("/todos", OPTIONS),
Endpoint("/todos", HEAD)
)
//when
val implementation = SpringConverter(context)
//then
assertThat(implementation.conversionResult).containsExactlyInAnyOrderElementsOf(specification)
}
}
@Nested
@WebMvcTest(RequestMappingWithPostAndPutMappingInCombinationController::class, excludeAutoConfiguration = [ErrorMvcAutoConfiguration::class])
inner class RequestMappingWithPostAndPutMappingInCombinationTest {
@Autowired
lateinit var context: ConfigurableApplicationContext
@Test
fun `RequestMapping providing POST defined on class and PutMapping on function`() {
//given
val specification: Set<Endpoint> = setOf(
Endpoint("/todos", PUT),
Endpoint("/todos", POST),
Endpoint("/todos", OPTIONS),
Endpoint("/todos", HEAD)
)
//when
val implementation = SpringConverter(context)
//then
assertThat(implementation.conversionResult).containsExactlyInAnyOrderElementsOf(specification)
}
}
@Nested
@WebMvcTest(EmptyRequestMappingAndGetMappingInCombinationController::class, excludeAutoConfiguration = [ErrorMvcAutoConfiguration::class])
inner class EmptyRequestMappingAndGetMappingInCombinationTest {
@Autowired
lateinit var context: ConfigurableApplicationContext
@Test
fun `RequestMapping without http method defined on class and GetMapping on function`() {
//given
val specification: Set<Endpoint> = setOf(
Endpoint("/todos", GET),
Endpoint("/todos", OPTIONS),
Endpoint("/todos", HEAD)
)
//when
val implementation = SpringConverter(context)
//then
assertThat(implementation.conversionResult).containsExactlyInAnyOrderElementsOf(specification)
}
}
@Nested
@WebMvcTest(EmptyRequestMappingAndDeleteMappingInCombinationController::class, excludeAutoConfiguration = [ErrorMvcAutoConfiguration::class])
inner class EmptyRequestMappingAndDeleteMappingInCombinationTest {
@Autowired
lateinit var context: ConfigurableApplicationContext
@Test
fun `RequestMapping without http method defined on class and DeleteMapping on function`() {
//given
val specification: Set<Endpoint> = setOf(
Endpoint("/todos", DELETE),
Endpoint("/todos", OPTIONS),
Endpoint("/todos", HEAD)
)
//when
val implementation = SpringConverter(context)
//then
assertThat(implementation.conversionResult).containsExactlyInAnyOrderElementsOf(specification)
}
}
@Nested
@WebMvcTest(EmptyRequestMappingAndPatchMappingInCombinationController::class, excludeAutoConfiguration = [ErrorMvcAutoConfiguration::class])
inner class EmptyRequestMappingAndPatchMappingInCombinationTest {
@Autowired
lateinit var context: ConfigurableApplicationContext
@Test
fun `RequestMapping without http method defined on class and PatchMapping on function`() {
//given
val specification: Set<Endpoint> = setOf(
Endpoint("/todos", PATCH),
Endpoint("/todos", OPTIONS),
Endpoint("/todos", HEAD)
)
//when
val implementation = SpringConverter(context)
//then
assertThat(implementation.conversionResult).containsExactlyInAnyOrderElementsOf(specification)
}
}
@Nested
@WebMvcTest(EmptyRequestMappingAndPostMappingInCombinationController::class, excludeAutoConfiguration = [ErrorMvcAutoConfiguration::class])
inner class EmptyRequestMappingAndPostMappingInCombinationTest {
@Autowired
lateinit var context: ConfigurableApplicationContext
@Test
fun `RequestMapping without http method defined on class and PostMapping on function`() {
//given
val specification: Set<Endpoint> = setOf(
Endpoint("/todos", POST),
Endpoint("/todos", OPTIONS),
Endpoint("/todos", HEAD)
)
//when
val implementation = SpringConverter(context)
//then
assertThat(implementation.conversionResult).containsExactlyInAnyOrderElementsOf(specification)
}
}
@Nested
@WebMvcTest(EmptyRequestMappingAndPutMappingInCombinationController::class, excludeAutoConfiguration = [ErrorMvcAutoConfiguration::class])
inner class EmptyRequestMappingAndPutMappingInCombinationTest {
@Autowired
lateinit var context: ConfigurableApplicationContext
@Test
fun `RequestMapping without http method defined on class and PutMapping on function`() {
//given
val specification: Set<Endpoint> = setOf(
Endpoint("/todos", PUT),
Endpoint("/todos", OPTIONS),
Endpoint("/todos", HEAD)
)
//when
val implementation = SpringConverter(context)
//then
assertThat(implementation.conversionResult).containsExactlyInAnyOrderElementsOf(specification)
}
}
}
@Nested
inner class OverwriteTests {
@Nested
@WebMvcTest(RequestMappingFirstAndGetMappingBothOnFunctionController::class, excludeAutoConfiguration = [ErrorMvcAutoConfiguration::class])
inner class RequestMappingFirstAndGetMappingBothOnFunctionTest {
@Autowired
lateinit var context: ConfigurableApplicationContext
@Test
fun `RequestMapping and GetMapping both on function, but behaves like RequestMapping without http methods`() {
//given
val specification: Set<Endpoint> = setOf(
Endpoint("/todos", GET),
Endpoint("/todos", PUT),
Endpoint("/todos", POST),
Endpoint("/todos", DELETE),
Endpoint("/todos", PATCH),
Endpoint("/todos", HEAD),
Endpoint("/todos", OPTIONS)
)
//when
val implementation = SpringConverter(context)
//then
assertThat(implementation.conversionResult).containsExactlyInAnyOrderElementsOf(specification)
}
}
@Nested
@WebMvcTest(GetMappingFirstAndRequestMappingBothOnFunctionController::class, excludeAutoConfiguration = [ErrorMvcAutoConfiguration::class])
inner class GetMappingFirstAndRequestMappingBothOnFunctionTest {
@Autowired
lateinit var context: ConfigurableApplicationContext
@Test
fun `RequestMapping and GetMapping both on function, but behaves like RequestMapping without http methods`() {
//given
val specification: Set<Endpoint> = setOf(
Endpoint("/todos", GET),
Endpoint("/todos", PUT),
Endpoint("/todos", POST),
Endpoint("/todos", DELETE),
Endpoint("/todos", PATCH),
Endpoint("/todos", HEAD),
Endpoint("/todos", OPTIONS)
)
//when
val implementation = SpringConverter(context)
//then
assertThat(implementation.conversionResult).containsExactlyInAnyOrderElementsOf(specification)
}
}
@Nested
@WebMvcTest(RequestMappingFirstAndDeleteMappingBothOnFunctionController::class, excludeAutoConfiguration = [ErrorMvcAutoConfiguration::class])
inner class RequestMappingFirstAndDeleteMappingBothOnFunctionTest {
@Autowired
lateinit var context: ConfigurableApplicationContext
@Test
fun `RequestMapping and DeleteMapping both on function, but behaves like RequestMapping without http methods`() {
//given
val specification: Set<Endpoint> = setOf(
Endpoint("/todos", GET),
Endpoint("/todos", PUT),
Endpoint("/todos", POST),
Endpoint("/todos", DELETE),
Endpoint("/todos", PATCH),
Endpoint("/todos", HEAD),
Endpoint("/todos", OPTIONS)
)
//when
val implementation = SpringConverter(context)
//then
assertThat(implementation.conversionResult).containsExactlyInAnyOrderElementsOf(specification)
}
}
@Nested
@WebMvcTest(DeleteMappingFirstAndRequestMappingBothOnFunctionController::class, excludeAutoConfiguration = [ErrorMvcAutoConfiguration::class])
inner class DeleteMappingFirstAndRequestMappingBothOnFunctionTest {
@Autowired
lateinit var context: ConfigurableApplicationContext
@Test
fun `RequestMapping and DeleteMapping both on function, but behaves like RequestMapping without http methods`() {
//given
val specification: Set<Endpoint> = setOf(
Endpoint("/todos", GET),
Endpoint("/todos", PUT),
Endpoint("/todos", POST),
Endpoint("/todos", DELETE),
Endpoint("/todos", PATCH),
Endpoint("/todos", HEAD),
Endpoint("/todos", OPTIONS)
)
//when
val implementation = SpringConverter(context)
//then
assertThat(implementation.conversionResult).containsExactlyInAnyOrderElementsOf(specification)
}
}
@Nested
@WebMvcTest(RequestMappingFirstAndPatchMappingBothOnFunctionController::class, excludeAutoConfiguration = [ErrorMvcAutoConfiguration::class])
inner class RequestMappingFirstAndPatchMappingBothOnFunctionTest {
@Autowired
lateinit var context: ConfigurableApplicationContext
@Test
fun `RequestMapping and PatchMapping both on function, but behaves like RequestMapping without http methods`() {
//given
val specification: Set<Endpoint> = setOf(
Endpoint("/todos", GET),
Endpoint("/todos", PUT),
Endpoint("/todos", POST),
Endpoint("/todos", DELETE),
Endpoint("/todos", PATCH),
Endpoint("/todos", HEAD),
Endpoint("/todos", OPTIONS)
)
//when
val implementation = SpringConverter(context)
//then
assertThat(implementation.conversionResult).containsExactlyInAnyOrderElementsOf(specification)
}
}
@Nested
@WebMvcTest(PatchMappingFirstAndRequestMappingBothOnFunctionController::class, excludeAutoConfiguration = [ErrorMvcAutoConfiguration::class])
inner class PatchMappingFirstAndRequestMappingBothOnFunctionTest {
@Autowired
lateinit var context: ConfigurableApplicationContext
@Test
fun `RequestMapping and PatchMapping both on function, but behaves like RequestMapping without http methods`() {
//given
val specification: Set<Endpoint> = setOf(
Endpoint("/todos", GET),
Endpoint("/todos", PUT),
Endpoint("/todos", POST),
Endpoint("/todos", DELETE),
Endpoint("/todos", PATCH),
Endpoint("/todos", HEAD),
Endpoint("/todos", OPTIONS)
)
//when
val implementation = SpringConverter(context)
//then
assertThat(implementation.conversionResult).containsExactlyInAnyOrderElementsOf(specification)
}
}
@Nested
@WebMvcTest(RequestMappingFirstAndPostMappingBothOnFunctionController::class, excludeAutoConfiguration = [ErrorMvcAutoConfiguration::class])
inner class RequestMappingFirstAndPostMappingBothOnFunctionTest {
@Autowired
lateinit var context: ConfigurableApplicationContext
@Test
fun `RequestMapping and PostMapping both on function, but behaves like RequestMapping without http methods`() {
//given
val specification: Set<Endpoint> = setOf(
Endpoint("/todos", GET),
Endpoint("/todos", PUT),
Endpoint("/todos", POST),
Endpoint("/todos", DELETE),
Endpoint("/todos", PATCH),
Endpoint("/todos", HEAD),
Endpoint("/todos", OPTIONS)
)
//when
val implementation = SpringConverter(context)
//then
assertThat(implementation.conversionResult).containsExactlyInAnyOrderElementsOf(specification)
}
}
@Nested
@WebMvcTest(PostMappingFirstAndRequestMappingBothOnFunctionController::class, excludeAutoConfiguration = [ErrorMvcAutoConfiguration::class])
inner class PostMappingFirstAndRequestMappingBothOnFunctionTest {
@Autowired
lateinit var context: ConfigurableApplicationContext
@Test
fun `RequestMapping and PostMapping both on function, but behaves like RequestMapping without http methods`() {
//given
val specification: Set<Endpoint> = setOf(
Endpoint("/todos", GET),
Endpoint("/todos", PUT),
Endpoint("/todos", POST),
Endpoint("/todos", DELETE),
Endpoint("/todos", PATCH),
Endpoint("/todos", HEAD),
Endpoint("/todos", OPTIONS)
)
//when
val implementation = SpringConverter(context)
//then
assertThat(implementation.conversionResult).containsExactlyInAnyOrderElementsOf(specification)
}
}
@Nested
@WebMvcTest(RequestMappingFirstAndPutMappingBothOnFunctionController::class, excludeAutoConfiguration = [ErrorMvcAutoConfiguration::class])
inner class RequestMappingFirstAndPutMappingBothOnFunctionTest {
@Autowired
lateinit var context: ConfigurableApplicationContext
@Test
fun `RequestMapping and PutMapping both on function, but behaves like RequestMapping without http methods`() {
//given
val specification: Set<Endpoint> = setOf(
Endpoint("/todos", GET),
Endpoint("/todos", PUT),
Endpoint("/todos", POST),
Endpoint("/todos", DELETE),
Endpoint("/todos", PATCH),
Endpoint("/todos", HEAD),
Endpoint("/todos", OPTIONS)
)
//when
val implementation = SpringConverter(context)
//then
assertThat(implementation.conversionResult).containsExactlyInAnyOrderElementsOf(specification)
}
}
@Nested
@WebMvcTest(PutMappingFirstAndRequestMappingBothOnFunctionController::class, excludeAutoConfiguration = [ErrorMvcAutoConfiguration::class])
inner class PutMappingFirstAndRequestMappingBothOnFunctionTest {
@Autowired
lateinit var context: ConfigurableApplicationContext
@Test
fun `RequestMapping and PutMapping both on function, but behaves like RequestMapping without http methods`() {
//given
val specification: Set<Endpoint> = setOf(
Endpoint("/todos", GET),
Endpoint("/todos", PUT),
Endpoint("/todos", POST),
Endpoint("/todos", DELETE),
Endpoint("/todos", PATCH),
Endpoint("/todos", HEAD),
Endpoint("/todos", OPTIONS)
)
//when
val implementation = SpringConverter(context)
//then
assertThat(implementation.conversionResult).containsExactlyInAnyOrderElementsOf(specification)
}
}
}
@Nested
@WebMvcTest(HttpMethodsForDefaultErrorEndpointController::class)
inner class HttpMethodsForDefaultErrorEndpointTest {
@Autowired
lateinit var context: ConfigurableApplicationContext
@Test
fun `all http methods are provided by the default error endpoint`() {
//given
val specification: Set<Endpoint> = setOf(
Endpoint("/todos", GET),
Endpoint("/todos", OPTIONS),
Endpoint("/todos", HEAD),
Endpoint(
path = "/error",
httpMethod = GET,
produces = setOf(APPLICATION_JSON_VALUE)
),
Endpoint(
path = "/error",
httpMethod = POST,
produces = setOf(APPLICATION_JSON_VALUE)
),
Endpoint(
path = "/error",
httpMethod = HEAD,
produces = setOf(APPLICATION_JSON_VALUE)
),
Endpoint(
path = "/error",
httpMethod = PUT,
produces = setOf(APPLICATION_JSON_VALUE)
),
Endpoint(
path = "/error",
httpMethod = PATCH,
produces = setOf(APPLICATION_JSON_VALUE)
),
Endpoint(
path = "/error",
httpMethod = DELETE,
produces = setOf(APPLICATION_JSON_VALUE)
),
Endpoint("/error", OPTIONS),
Endpoint(
path = "/error",
httpMethod = GET,
produces = setOf(TEXT_HTML_VALUE)
),
Endpoint(
path = "/error",
httpMethod = POST,
produces = setOf(TEXT_HTML_VALUE)
),
Endpoint(
path = "/error",
httpMethod = HEAD,
produces = setOf(TEXT_HTML_VALUE)
),
Endpoint(
path = "/error",
httpMethod = PUT,
produces = setOf(TEXT_HTML_VALUE)
),
Endpoint(
path = "/error",
httpMethod = PATCH,
produces = setOf(TEXT_HTML_VALUE)
),
Endpoint(
path = "/error",
httpMethod = DELETE,
produces = setOf(TEXT_HTML_VALUE)
),
Endpoint("/error", OPTIONS)
)
//when
val implementation = SpringConverter(context)
//then
assertThat(implementation.conversionResult).containsExactlyInAnyOrderElementsOf(specification)
}
}
}
| 2
|
Kotlin
|
19
| 193
|
b8a754f91b524b53a464167bf0abd6044caa25a4
| 54,687
|
hikaku
|
Apache License 2.0
|
demos/paint/src/main/java/com/guru/composecookbook/paint/DrawingCanvas.kt
|
Gurupreet
| 293,227,683
| false
| null |
package com.example.fa_android.feature.main
import android.view.MotionEvent
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.input.pointer.pointerInteropFilter
import androidx.compose.ui.unit.dp
@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun DrawingCanvas(
drawColor: MutableState<Color>,
drawBrush: MutableState<Float>,
usedColors: MutableState<MutableSet<Color>>,
paths: MutableList<PathState>
) {
val currentPath = paths.last().path
val movePath = remember { mutableStateOf<Offset?>(null) }
Canvas(
modifier = Modifier
.fillMaxSize()
.padding(top = 100.dp)
.pointerInteropFilter {
when (it.action) {
MotionEvent.ACTION_DOWN -> {
currentPath.moveTo(it.x, it.y)
usedColors.value.add(drawColor.value)
}
MotionEvent.ACTION_MOVE -> {
movePath.value = Offset(it.x, it.y)
}
else -> {
movePath.value = null
}
}
true
},
) {
movePath.value?.let {
currentPath.lineTo(it.x, it.y)
drawPath(
path = currentPath,
color = drawColor.value,
style = Stroke(drawBrush.value)
)
}
paths.forEach {
drawPath(
path = it.path,
color = it.color,
style = Stroke(it.stroke)
)
}
}
}
| 2
| null |
774
| 6,057
|
1b82b0b990648b2ece5c890fef622d9bdb00e4d8
| 2,139
|
ComposeCookBook
|
MIT License
|
pacote-download/listadecompras/app/src/main/java/br/com/alexandre/listadecompras/Produto.kt
|
alexandreluizdasilva
| 267,085,819
| false
| null |
package br.com.alexandre.listadecompras
import android.graphics.Bitmap
data class Produto(val nome:String, val quantidade:Int, val valor:Double, val foto:Bitmap? = null)
| 0
|
Kotlin
|
0
| 0
|
c76f3ec8416e7ea9ff533fb592f9b0c7df322aa2
| 171
|
Android
|
MIT License
|
src/main/kotlin/com/fortify/fod/parser/BsiToken.kt
|
4est
| 108,306,501
| true
|
{"Kotlin": 14498}
|
package com.fortify.fod.parser
/**
* A Build Server (Continuous) Integration Token for integrating with Fortify on Demand
*/
class BsiToken {
var tenantId: Int = 0
var tenantCode: String = ""
var projectVersionId: Int = 0
var assessmentTypeId: Int = 0
var payloadType: String = "ANALYSIS_PAYLOAD"
var scanPreferenceId: Int = 1
var scanPreference: String = "Standard"
var auditPreferenceId: Int = 1
var auditPreference: String = "Manual"
var includeThirdParty: Boolean = false
var includeOpenSourceAnalysis: Boolean = false
var portalUri: String = "https://ams.fortify.com"
var apiUri: String = "https://api.ams.fortify.com"
var technologyTypeId: Int = 0
var technologyType: String? = null
var technologyVersion: String? = null
var technologyVersionId: Int? = null
/**
* Legacy alias for Technology Type
*/
var technologyStack: String?
get() {
return technologyType
}
set(value) {
this.technologyType = value
}
/**
* Legacy alias for Technology Version
*/
var languageLevel: String?
get() {
return technologyVersion
}
set(value) {
this.technologyVersion = value
}
}
| 0
|
Kotlin
|
0
| 0
|
d93ae4050e1eb38318ddbbc9aefb23232f94f795
| 1,295
|
bsi-token-parser
|
MIT License
|
src/main/kotlin/com/sourcegraph/cody/agent/protocol_generated/CurrentUserCodySubscription.kt
|
sourcegraph
| 702,947,607
| false
|
{"Kotlin": 914689, "Java": 201176, "Shell": 4636, "TypeScript": 2153, "Nix": 1122, "JavaScript": 436, "HTML": 294}
|
@file:Suppress("FunctionName", "ClassName", "unused", "EnumEntryName", "UnusedImport")
package com.sourcegraph.cody.agent.protocol_generated;
data class CurrentUserCodySubscription(
val status: String,
val plan: String,
val applyProRateLimits: Boolean,
val currentPeriodStartAt: Date,
val currentPeriodEndAt: Date,
)
| 230
|
Kotlin
|
16
| 55
|
1eb25809c3e51b64f08e851c8da09778000540c6
| 329
|
jetbrains
|
Apache License 2.0
|
src/jvmMain/kotlin/blue/starry/stella/server/endpoints/GetMedia.kt
|
SlashNephy
| 279,921,971
| false
|
{"Kotlin": 112668, "Go": 7724, "Dockerfile": 878, "Makefile": 360}
|
package blue.starry.stella.server.endpoints
import blue.starry.stella.Env
import blue.starry.stella.Stella
import io.ktor.application.call
import io.ktor.http.HttpHeaders
import io.ktor.http.HttpStatusCode
import io.ktor.http.Url
import io.ktor.locations.Location
import io.ktor.locations.get
import io.ktor.request.header
import io.ktor.response.respond
import io.ktor.response.respondFile
import io.ktor.routing.Route
@Location("/media/{filename}")
data class GetMedia(val filename: String)
fun Route.getMediaByFilename() {
get<GetMedia> { (filename) ->
if (Env.CORS_HOSTS.isNotEmpty()) {
val referer = call.request.header(HttpHeaders.Referrer) ?: return@get call.respond(HttpStatusCode.BadRequest)
val refererUrl = Url(referer)
if (refererUrl.host !in Env.CORS_HOSTS) {
return@get call.respond(HttpStatusCode.Forbidden)
}
}
call.respondFile(Stella.MediaDirectory.toFile(), filename)
}
}
| 27
|
Kotlin
|
0
| 8
|
a120352416eb7630fe5cb52743815435164840c9
| 990
|
stella
|
MIT License
|
YouKonCMP/composeApp/src/commonMain/kotlin/view/BackgroundBox.kt
|
radcli14
| 652,278,622
| false
|
{"Kotlin": 132950, "Swift": 37362}
|
package view
import androidx.compose.foundation.Image
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.graphics.ColorMatrix
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.dp
import getPlatform
import org.jetbrains.compose.resources.ExperimentalResourceApi
import org.jetbrains.compose.resources.painterResource
import youkon.composeapp.generated.resources.Res
import youkon.composeapp.generated.resources.background
/// Holds the background image, content overlaid on top of it
@OptIn(ExperimentalResourceApi::class)
@Composable
fun BackgroundBox(content: @Composable () -> Unit) {
val isIphone = "iOS" in getPlatform().name
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.TopCenter
) {
Image(
painter = painterResource(Res.drawable.background),
contentDescription = "Background image of mountains",
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.Crop,
colorFilter = ColorFilter.colorMatrix(
colorMatrix(if (isSystemInDarkTheme()) -80f else 80f)
)
)
Box(
modifier = Modifier
.padding(
top = if (isIphone) 36.dp else 0.dp,
bottom = if (isIphone) 12.dp else 0.dp
)
) {
content()
}
}
}
fun colorMatrix(brightness: Float): ColorMatrix {
val matrixAsArray = floatArrayOf(
1f, 0f, 0f, 0f, brightness,
0f, 1f, 0f, 0f, brightness,
0f, 0f, 1f, 0f, brightness,
0f, 0f, 0f, 1f, 0f
)
return ColorMatrix(matrixAsArray)
}
| 6
|
Kotlin
|
0
| 1
|
88bf47faa923c43d04a03fccb7a64609f968ba0d
| 2,026
|
youkon
|
MIT License
|
SharedCode/src/androidMain/kotlin/com/surrus/galwaybus/common/di/KoinAndroid.kt
|
joreilly
| 96,469,751
| false
| null |
package com.surrus.galwaybus.common.di
import android.content.Context
import com.russhwolf.settings.AndroidSettings
import com.russhwolf.settings.ExperimentalSettingsApi
import com.russhwolf.settings.ObservableSettings
import com.squareup.sqldelight.android.AndroidSqliteDriver
import com.surrus.galwaybus.db.MyDatabase
import org.koin.dsl.module
@OptIn(ExperimentalSettingsApi::class)
actual fun platformModule() = module {
single { createObservableSettings(get()) }
single { createDb(get()) }
}
@OptIn(ExperimentalSettingsApi::class)
private fun createObservableSettings(context: Context): ObservableSettings {
return AndroidSettings(context.getSharedPreferences("AppSettings", Context.MODE_PRIVATE))
}
fun createDb(context: Context): MyDatabase {
val driver = AndroidSqliteDriver(MyDatabase.Schema, context, "galwaybus.db")
return MyDatabase(driver)
}
| 5
|
Kotlin
|
37
| 424
|
d94da5ae243cf9cf1037e08ec53f55993288f920
| 879
|
GalwayBus
|
MIT License
|
va_code/app/src/main/java/com/mvrc/viewapp/domain/event/ValidationEvent.kt
|
MarcoBendinelli
| 789,851,376
| false
|
{"Kotlin": 547994}
|
package com.mvrc.viewapp.domain.event
/**
* Sealed class representing events that can occur during a validation process.
*/
sealed class ValidationEvent {
/**
* Object representing a successful validation event.
*/
object Success : ValidationEvent()
/**
* Object representing an error in the validation process.
*/
object Failure : ValidationEvent()
}
| 0
|
Kotlin
|
0
| 0
|
1c570950bd1d8e122e83414c1b0ff6d731a2d3fb
| 392
|
View-Android-Mobile-App
|
MIT License
|
beagle/src/test/kotlin/br/com/zup/beagle/android/cache/LruCacheStoreTest.kt
|
mabcl
| 400,229,216
| true
|
{"Kotlin": 1942093, "Java": 29122, "Shell": 7802, "Ruby": 5586, "HTML": 927}
|
/*
* Copyright 2020 ZUP IT SERVICOS EM TECNOLOGIA E INOVACAO SA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package br.com.zup.beagle.android.cache
import android.util.LruCache
import br.com.zup.beagle.android.BaseTest
import br.com.zup.beagle.android.testutil.RandomData
import io.mockk.every
import io.mockk.mockk
import io.mockk.slot
import io.mockk.verify
import org.junit.Assert.assertEquals
import org.junit.jupiter.api.BeforeAll
import org.junit.jupiter.api.Test
private val CACHE_KEY = RandomData.string()
class LruCacheStoreTest : BaseTest() {
private val cachedData: LruCache<String, BeagleCache> = mockk()
private lateinit var cacheStore: LruCacheStore
private val beagleCache: BeagleCache = mockk()
@BeforeAll
override fun setUp() {
super.setUp()
cacheStore = LruCacheStore(cache = cachedData)
}
@Test
fun save_should_add_new_beagleHashKey_to_cache() {
// Given
val timerCacheSlot = slot<BeagleCache>()
every { cachedData.put(any(), capture(timerCacheSlot)) } returns null
// When
cacheStore.save(CACHE_KEY, beagleCache)
// Then
verify(exactly = 1) { cachedData.put(CACHE_KEY, timerCacheSlot.captured) }
assertEquals(timerCacheSlot.captured, beagleCache)
}
@Test
fun restore_should_return_cached_timerCache() {
// Given
every { cachedData[CACHE_KEY] } returns beagleCache
// When
val actualTimerCache = cacheStore.restore(CACHE_KEY)
// Then
assertEquals(beagleCache, actualTimerCache)
}
}
| 0
| null |
0
| 0
|
5ae9258bd6316e97633bc73a84ad03dd4d9de0dc
| 2,110
|
beagle-android
|
Apache License 2.0
|
desktop/src/jvmMain/kotlin/main.kt
|
alexmaryin
| 419,989,861
| false
| null |
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material.MaterialTheme
import androidx.compose.ui.window.Window
import androidx.compose.ui.window.application
import com.arkivanov.decompose.DefaultComponentContext
import com.arkivanov.essenty.lifecycle.LifecycleRegistry
import decompose.Root
import di.apiModule
import di.dbModule
import org.koin.core.context.startKoin
fun main() = application {
startKoin {
modules(dbModule, apiModule)
}
val root = Root(DefaultComponentContext(LifecycleRegistry()))
Window(
title = "Sims checklists",
onCloseRequest = ::exitApplication) {
val isDark = isSystemInDarkTheme()
MaterialTheme(colors = if (isDark) Themes.dark else Themes.light) {
App(root)
}
}
}
| 3
|
Kotlin
|
1
| 4
|
c186ee8a179bed5cb903bfc5179e9e7198aad369
| 810
|
sims_checklist
|
Apache License 2.0
|
app/src/main/java/com/test/tribal/App.kt
|
israis007
| 399,584,600
| false
| null |
package com.test.tribal
import androidx.multidex.MultiDex
import androidx.multidex.MultiDexApplication
class App: MultiDexApplication() {
private var isConnected = false
companion object {
lateinit var instance: App
private set
}
init {
instance = this
}
override fun onCreate() {
super.onCreate()
MultiDex.install(this)
}
fun setIsConnected(isConnected : Boolean){
this@App.isConnected = isConnected
}
fun isConnected() = this@App.isConnected
}
| 0
|
Kotlin
|
0
| 0
|
07b5e3b685164446b9f38f51eec114d15a324324
| 546
|
pruebaTribal
|
Apache License 2.0
|
core/src/main/java/com/loitp/views/layout/heart/PathAnimator.kt
|
tplloi
| 126,578,283
| false
| null |
package com.views.layout.heartlayout
import android.graphics.Path
import android.graphics.PathMeasure
import android.os.Handler
import android.os.Looper
import android.view.View
import android.view.ViewGroup
import android.view.animation.Animation
import android.view.animation.LinearInterpolator
import android.view.animation.Transformation
import java.util.concurrent.atomic.AtomicInteger
class PathAnimator(config: Config) : AbstractPathAnimator(config) {
companion object {
private fun scale(a: Double, b: Double, c: Double, d: Double, e: Double): Float {
return ((a - b) / (c - b) * (e - d) + d).toFloat()
}
}
private val atomicInteger = AtomicInteger(0)
private val mHandler: Handler = Handler(Looper.getMainLooper())
override fun start(child: View, parent: ViewGroup) {
parent.addView(child, ViewGroup.LayoutParams(mConfig.heartWidth, mConfig.heartHeight))
val anim = FloatAnimation(
path = createPath(
counter = atomicInteger,
view = parent,
factor = 2),
rotation = randomRotation(),
parent = parent,
child = child
)
anim.duration = mConfig.animDuration.toLong()
anim.interpolator = LinearInterpolator()
anim.setAnimationListener(object : Animation.AnimationListener {
override fun onAnimationEnd(animation: Animation) {
mHandler.post {
parent.removeView(child)
}
atomicInteger.decrementAndGet()
}
override fun onAnimationRepeat(animation: Animation) {}
override fun onAnimationStart(animation: Animation) {
atomicInteger.incrementAndGet()
}
})
anim.interpolator = LinearInterpolator()
child.startAnimation(anim)
}
internal class FloatAnimation(path: Path?, rotation: Float, parent: View?, child: View?) : Animation() {
private val pathMeasure: PathMeasure = PathMeasure(path, false)
private val mView: View?
private val mDistance: Float
private val mRotation: Float
override fun applyTransformation(factor: Float, transformation: Transformation) {
val matrix = transformation.matrix
pathMeasure.getMatrix(mDistance * factor, matrix, PathMeasure.POSITION_MATRIX_FLAG)
mView?.rotation = mRotation * factor
var scale = 1f
if (3000.0f * factor < 200.0f) {
scale = scale(factor.toDouble(), 0.0, 0.06666667014360428, 0.20000000298023224, 1.100000023841858)
} else if (3000.0f * factor < 300.0f) {
scale = scale(factor.toDouble(), 0.06666667014360428, 0.10000000149011612, 1.100000023841858, 1.0)
}
mView?.scaleX = scale
mView?.scaleY = scale
transformation.alpha = 1.0f - factor
}
init {
mDistance = pathMeasure.length
mView = child
mRotation = rotation
parent?.setLayerType(View.LAYER_TYPE_HARDWARE, null)
}
}
}
| 1
| null |
1
| 9
|
1bf1d6c0099ae80c5f223065a2bf606a7542c2b9
| 3,204
|
base
|
Apache License 2.0
|
feature/employee_payment/src/main/java/com/niyaj/feature/employee_payment/components/EmployeePayments.kt
|
skniyajali
| 579,613,644
| false
|
{"Kotlin": 2202790}
|
package com.niyaj.feature.employee_payment.components
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Card
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.MaterialTheme
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.KeyboardArrowDown
import androidx.compose.material.icons.filled.Person
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.unit.dp
import com.niyaj.designsystem.theme.SpaceMini
import com.niyaj.designsystem.theme.SpaceSmall
import com.niyaj.model.Employee
import com.niyaj.model.Payment
import com.niyaj.ui.components.IconBox
import com.niyaj.ui.components.StandardExpandable
import com.niyaj.ui.components.TextWithIcon
/**
*
*/
@OptIn(ExperimentalMaterialApi::class)
@Composable
fun EmployeePayments(
employee: Employee,
employeeSalaries: List<Payment>,
onSelectEmployee: (String) -> Unit,
doesSelected: (String) -> Boolean,
onClick: (String) -> Unit,
onLongClick: (String) -> Unit,
isExpanded: Boolean = false,
onExpandChanged: (String) -> Unit,
onClickAddSalaryBtn: (String) -> Unit
) {
Card(
onClick = {
onSelectEmployee(employee.employeeId)
},
modifier = Modifier
.testTag(employee.employeeName.plus("Tag"))
.fillMaxWidth()
.padding(SpaceSmall),
shape = RoundedCornerShape(4.dp),
elevation = SpaceMini
) {
StandardExpandable(
modifier = Modifier
.fillMaxWidth()
.padding(SpaceSmall),
expanded = isExpanded,
onExpandChanged = {
onExpandChanged(employee.employeeId)
},
title = {
TextWithIcon(
text = employee.employeeName,
icon = Icons.Default.Person,
isTitle = true
)
},
trailing = {
IconBox(
text = "Add Entry",
icon = Icons.Default.Add,
onClick = {
onClickAddSalaryBtn(employee.employeeId)
}
)
},
rowClickable = true,
expand = { modifier: Modifier ->
IconButton(
modifier = modifier,
onClick = {
onSelectEmployee(employee.employeeId)
}
) {
Icon(
imageVector = Icons.Filled.KeyboardArrowDown,
contentDescription = "Expand More",
tint = MaterialTheme.colors.secondary
)
}
},
content = {
EmployeePaymentsData(
employeeSalaries = employeeSalaries,
doesSelected = doesSelected,
onClick = onClick,
onLongClick = onLongClick
)
}
)
}
}
| 25
|
Kotlin
|
0
| 1
|
8067efcc5dc377f7161fee2f372c5be35e98e678
| 3,460
|
POS-Application
|
MIT License
|
app/app/src/main/java/com/example/posture/Sensors.kt
|
metaflow
| 199,304,130
| false
|
{"Jupyter Notebook": 11469268, "Kotlin": 34379, "C++": 29182, "Python": 3764}
|
package com.example.posture
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothManager
import android.bluetooth.le.ScanCallback
import android.bluetooth.le.ScanFilter
import android.bluetooth.le.ScanResult
import android.bluetooth.le.ScanSettings
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.os.ParcelUuid
import android.util.Log
import java.lang.ref.WeakReference
import java.util.*
private val TAG: String = Sensors::class.java.simpleName
interface SensorsObserver {
fun onMeasurement(measurement: SensorMeasurement) {}
fun onScanStatus(on: Boolean, aggressive: Boolean) {}
fun onDisconnected(address: String) {}
}
class Sensors private constructor() {
private var disconnected = false
private val observers = LinkedList<WeakReference<SensorsObserver>>()
private val activeDevices = HashMap<String, GattCallback>()
var scanning = false
set(value) {
val notify = field != value
field = value
if (notify) notifyScanStatus()
}
private var aggressiveScan = false
set(value) {
val notify = field != value
field = value
if (notify) notifyScanStatus()
}
var context: Context? = null
private lateinit var bluetoothAdapter: BluetoothAdapter
private val scan = object : ScanCallback() {
override fun onScanFailed(errorCode: Int) {
Log.i(TAG, "onScanFailed $errorCode")
}
override fun onScanResult(callbackType: Int, result: ScanResult?) {
if (result == null) return
Log.v(TAG, "onScanResult($callbackType, $result)")
if (result.scanRecord?.serviceUuids?.contains(ParcelUuid(serviceUUID)) == true) {
Log.i(TAG, "found IMU sensor")
connect(result.device)
}
}
override fun onBatchScanResults(results: MutableList<ScanResult>?) {
Log.i(TAG, "onBatchScanResults($results)")
}
}
// TODO: make flow interface
fun addObserver(o: SensorsObserver) {
observers.push(WeakReference(o))
o.onScanStatus(scanning, aggressiveScan)
}
companion object {
@Volatile
private var INSTANCE: Sensors? = null
fun getInstance(context: Context): Sensors {
val tempInstance = INSTANCE
if (tempInstance != null) {
return tempInstance
}
synchronized(this) {
val instance = Sensors()
INSTANCE = instance
instance.context = context
val bluetoothManager =
context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
instance.bluetoothAdapter = bluetoothManager.adapter
return instance
}
}
}
fun connect() {
disconnected = false
startScan(true)
}
private fun startScan(aggressive: Boolean) {
if (disconnected) return
Log.i(TAG, "startScan")
bluetoothAdapter.takeIf { it.isEnabled }?.apply {
val s = bluetoothAdapter.bluetoothLeScanner
s.stopScan(scan)
Log.i(TAG, "BLE is enabled, starting scan $s aggressive=$aggressive")
Mediator.getInstance()
.addStatusMessage("scanning ${if (aggressive) "aggresive" else ""}")
val scanSettings = ScanSettings.Builder()
scanSettings.setScanMode(if (aggressive) ScanSettings.SCAN_MODE_LOW_LATENCY else ScanSettings.SCAN_MODE_LOW_POWER)
scanSettings.setMatchMode(ScanSettings.MATCH_MODE_STICKY)
scanSettings.setReportDelay(0)
s?.startScan(Vector<ScanFilter>(0), scanSettings.build(), scan)
scanning = true
aggressiveScan = aggressive
if (aggressive) {
Handler(Looper.getMainLooper()).postDelayed({ startScan(false) }, 20_000)
Handler(Looper.getMainLooper()).postDelayed({ stopScan() }, 80_000)
}
}
}
private fun notifyScanStatus() {
observers.forEach { o -> o.get()?.onScanStatus(scanning, aggressiveScan) }
}
private fun connect(device: BluetoothDevice?) {
val address = device?.address
if (device == null || address == null) return
if (activeDevices.contains(address)) {
Log.d(TAG, "device $address already active")
return
}
Log.i(TAG, "connecting to $device")
val gattCallback = GattCallback(stateConnected = {
Log.i(TAG, "$address connected, ${activeDevices.size} active devices")
}, stateDisconnected = { add: String ->
activeDevices.remove(add)
Log.i(TAG, "$add, disconnected ${activeDevices.size} active devices")
Mediator.getInstance()
.addStatusMessage("$address disconnected, ${activeDevices.size} active sensors")
if (activeDevices.size < 3) {
Handler(Looper.getMainLooper()).postDelayed({ startScan(true) }, 60_000)
}
observers.forEach { o -> o.get()?.onDisconnected(add) }
}, onValue = { _, value ->
observers.forEach { o -> o.get()?.onMeasurement(value) }
})
activeDevices[address] = gattCallback
device.connectGatt(context, false, gattCallback)
}
private fun stopScan() {
if (!scanning) return
if (activeDevices.size < 3) Handler(Looper.getMainLooper()).postDelayed(
{ startScan(true) },
5 * 60_000
)
Mediator.getInstance().addStatusMessage("not scanning")
bluetoothAdapter.bluetoothLeScanner?.stopScan(scan)
scanning = false
}
fun disconnect() {
disconnected = true
stopScan()
activeDevices.forEach { (_, u) -> u.disconnect() }
}
}
| 0
|
Jupyter Notebook
|
0
| 0
|
ee01b134d31bf2c24fd41c97d5b810c6c18ed07c
| 5,992
|
posture
|
MIT License
|
framework/src/main/kotlin/dev/alpas/auth/HandlesUserLogin.kt
|
alpas
| 222,342,832
| false
| null |
package dev.alpas.auth
import dev.alpas.exceptions.ValidationException
import dev.alpas.http.HttpCall
import dev.alpas.http.RequestError
import dev.alpas.orAbort
import dev.alpas.validation.ErrorBag
import dev.alpas.validation.Required
import dev.alpas.validation.Rule
interface HandlesUserLogin {
fun afterLoginRedirectTo(call: HttpCall) = "/home"
fun afterLogoutRedirectTo(call: HttpCall) = "/"
fun username() = "email"
@Suppress("unused")
fun showLoginForm(call: HttpCall) {
call.render("auth.login")
}
@Suppress("unused")
fun login(call: HttpCall) {
validate(call)
if (attemptLogin(call)) {
onLoginSuccess(call)
} else {
onLoginFail(call)
}
}
@Suppress("unused")
fun logout(call: HttpCall) {
call.authChannel.logout()
call.redirect().to(afterLogoutRedirectTo(call))
}
fun onLoginFail(call: HttpCall) {
val errorBag = ErrorBag(RequestError(username(), message = "Credentials don't match"))
throw ValidationException(errorBag = errorBag)
}
fun onLoginSuccess(call: HttpCall) {
call.session.regenerate()
call.redirect().intended(default = afterLoginRedirectTo(call))
}
fun attemptLogin(call: HttpCall): Boolean {
return call.authChannel.attempt(
call.string(username()),
call.string("password"),
call.filled("remember")
)
}
fun validate(call: HttpCall) {
call.applyRules(validationRules())
}
fun validationRules(): Map<String, Iterable<Rule>> {
return mapOf(
username() to listOf(Required()),
"password" to listOf(Required())
)
}
}
| 8
| null |
7
| 180
|
1006b1e6aa2a97f2e122162b7d90444515b43cc5
| 1,743
|
alpas
|
MIT License
|
app/src/main/java/com/project/messagingapp/ui/main/viewmodel/NearbyUsersViewModel.kt
|
RavanSA
| 451,967,284
| false
|
{"Kotlin": 218193, "Jupyter Notebook": 75834, "Java": 2313, "JavaScript": 1816, "HTML": 372, "CSS": 272}
|
package com.project.messagingapp.ui.main.viewmodel
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.project.messagingapp.data.ChatDatabase
import com.project.messagingapp.data.model.UserModel
import com.project.messagingapp.data.repository.remote.AppRepo
class NearbyUsersViewModel(application: Application): AndroidViewModel(application) {
private var appRepo: AppRepo
var nearbyUserLiveData: LiveData<MutableList<UserModel>>
init {
val contactListDao = ChatDatabase.getLocalDatabase(application).getContactListDao()
appRepo = AppRepo.SingletonStatic.getInstance(contactListDao)
nearbyUserLiveData = appRepo.findNearbyUsersUsingHarvesineDistance()
}
fun getNearbyUsersList(): LiveData<MutableList<UserModel>> {
return nearbyUserLiveData
}
}
| 0
|
Kotlin
|
0
| 1
|
015ec8ad25fc9e3152e4b47011ba37079fdb38c5
| 953
|
MessagingApp
|
MIT License
|
openmrs-client/src/main/java/edu/upc/openmrs/activities/logs/LogsViewModel.kt
|
BLOPUP-UPC
| 536,613,762
| false
| null |
package edu.upc.openmrs.activities.logs
import edu.upc.sdk.library.OpenMRSLogger
import edu.upc.sdk.library.OpenmrsAndroid
import dagger.hilt.android.lifecycle.HiltViewModel
import java.io.BufferedReader
import java.io.File
import java.io.FileInputStream
import java.io.InputStreamReader
import javax.inject.Inject
@HiltViewModel
class LogsViewModel @Inject constructor(private val openMRSLogger: OpenMRSLogger) : edu.upc.openmrs.activities.BaseViewModel<Unit>() {
val logs: String = readLogsFromFile()
private fun readLogsFromFile(): String {
var textLogs = ""
try {
val filename = OpenmrsAndroid.getOpenMRSDir() + File.separator + openMRSLogger.logFilename
val stream = FileInputStream(File(filename))
val reader = BufferedReader(InputStreamReader(stream))
while (reader.readLine() != null) textLogs += reader.readLine()
reader.close()
} catch (e: Exception) {
e.printStackTrace()
openMRSLogger.e(e.message)
}
return textLogs
}
}
| 0
|
Kotlin
|
1
| 3
|
a043c8647db54a8c3fef1018829af227b320b9df
| 1,073
|
blopup-android-app
|
Naumen Public License
|
app/src/main/java/net/tnose/app/trisquel/FilmRollViewModel.kt
|
plus7
| 117,273,066
| false
|
{"Kotlin": 564939, "Java": 1153}
|
package net.tnose.app.trisquel
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.switchMap
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch
class FilmRollViewModel(application: Application?) : AndroidViewModel(
application!!
) {
private val mRepository: TrisquelRepo
init {
mRepository = TrisquelRepo(application)
}
val viewRule = MutableLiveData<Pair<Int, Pair<Int, String>>>(Pair(0, Pair(0, "")))
val allFilmRollAndRels: LiveData<List<FilmRollAndRels>> = viewRule.switchMap {
val sortBy = it.first
val filterByKind = it.second.first
val filterByValue = it.second.second
mRepository.getAllFilmRolls(sortBy, filterByKind, filterByValue)
}
fun insert(entity: FilmRollEntity) = viewModelScope.launch {
mRepository.upsertFilmRoll(entity)
}
// 意味ないけどViewModelの段階ではなんとなく分けておく
fun update(entity: FilmRollEntity) = viewModelScope.launch {
mRepository.upsertFilmRoll(entity)
}
fun refresh(id: Int) = viewModelScope.launch {
val entity = mRepository.getFilmRoll(id)
mRepository.upsertFilmRoll(entity.value!!)
}
fun delete(id : Int) = viewModelScope.launch {
mRepository.deleteFilmRoll(id)
}
}
| 14
|
Kotlin
|
0
| 2
|
7655d354f8bcee9d0de19a4038871e6400fcc6d9
| 1,389
|
Trisquel
|
Apache License 2.0
|
collector/src/androidTest/java/com/bitmovin/analytics/data/LongtermRetryOnFailureTest.kt
|
bitmovin
| 120,633,749
| false
| null |
package com.bitmovin.analytics.data
import android.os.Handler
import android.os.Looper
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import com.bitmovin.analytics.BitmovinAnalytics
import com.bitmovin.analytics.adapters.PlayerAdapter
import com.bitmovin.analytics.adapters.PlayerContext
import com.bitmovin.analytics.api.AnalyticsConfig
import com.bitmovin.analytics.api.DefaultMetadata
import com.bitmovin.analytics.api.RetryPolicy
import com.bitmovin.analytics.api.SourceMetadata
import com.bitmovin.analytics.data.persistence.EventDatabase
import com.bitmovin.analytics.data.persistence.PersistentAnalyticsEventQueue
import com.bitmovin.analytics.data.testutils.TestFactory
import com.bitmovin.analytics.enums.PlayerType
import com.bitmovin.analytics.features.Feature
import com.bitmovin.analytics.license.FeatureConfigContainer
import com.bitmovin.analytics.persistence.EventQueueConfig
import com.bitmovin.analytics.persistence.EventQueueFactory
import com.bitmovin.analytics.persistence.queue.AnalyticsEventQueue
import com.bitmovin.analytics.stateMachines.PlayerStateMachine
import com.bitmovin.analytics.systemtest.utils.Impression
import com.bitmovin.analytics.systemtest.utils.MockedIngress
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import org.assertj.core.api.Assertions.assertThat
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import java.util.UUID
import kotlin.time.Duration.Companion.days
import kotlin.time.Duration.Companion.hours
import kotlin.time.Duration.Companion.milliseconds
@RunWith(AndroidJUnit4::class)
class LongtermRetryOnFailureTest {
private val mainScope = MainScope()
private val appContext = InstrumentationRegistry.getInstrumentation().targetContext
private lateinit var dummyPlayerAdapter: PlayerAdapter
private lateinit var config: AnalyticsConfig
private lateinit var bitmovinAnalytics: BitmovinAnalytics
private lateinit var eventQueue: AnalyticsEventQueue
@Before
fun setup() {
val mockedIngressUrl = MockedIngress.startServer()
config = AnalyticsConfig(licenseKey = "<KEY>", retryPolicy = RetryPolicy.LONG_TERM, backendUrl = mockedIngressUrl)
eventQueue = EventQueueFactory.createPersistentEventQueue(
EventQueueConfig(),
EventDatabase.getInstance(appContext),
)
bitmovinAnalytics = BitmovinAnalytics(
config = config,
context = appContext,
eventQueue = eventQueue,
)
dummyPlayerAdapter = createDummyPlayerAdapter()
}
private fun createDummyPlayerAdapter(): DummyPlayerAdapter = runBlocking {
withContext(mainScope.coroutineContext) {
// Can not be created on the test thread
DummyPlayerAdapter(
bitmovinAnalytics,
DummyPlayerContext(),
)
}
}
@After
fun tearDown() {
MockedIngress.stopServer()
bitmovinAnalytics.detachPlayer()
EventDatabase.getInstance(appContext).purge()
}
@Test
fun test_sending_eventdata_sends_the_events() {
bitmovinAnalytics.attach(dummyPlayerAdapter)
val sessionId = createTestImpressionId()
val eventData = MutableList(5) {
TestFactory.createEventData(impressionId = sessionId)
}
eventData.forEach {
bitmovinAnalytics.sendEventData(it)
// waiting a bit here after each call, to make it more likely that the license
// authentication call is already done
Thread.sleep(400)
}
Thread.sleep(500)
val impressionList = MockedIngress.extractImpressions().combineByImpressionId()
assertThat(impressionList).hasSize(1)
assertThat(impressionList.values.first().eventDataList)
.hasSize(5)
.isEqualTo(eventData)
}
@Test
fun test_online_offline_online_sends_all_eventdata() {
// this test uses a hardcoded port, since we cannot go online/offline/online due to
// the fact that the server socket cannot be reused if port 0 is used (if there is traffic as it seems)
val mockedIngressUrl = MockedIngress.startServer(61123)
config = AnalyticsConfig(licenseKey = "<KEY>", retryPolicy = RetryPolicy.LONG_TERM, backendUrl = mockedIngressUrl)
bitmovinAnalytics = BitmovinAnalytics(
config = config,
context = appContext,
eventQueue = eventQueue,
)
dummyPlayerAdapter = createDummyPlayerAdapter()
bitmovinAnalytics.attach(dummyPlayerAdapter)
val sessionId = createTestImpressionId()
val eventData = MutableList(2) {
TestFactory.createEventData(impressionId = sessionId)
}
eventData.forEach {
bitmovinAnalytics.sendEventData(it)
// waiting a bit here after each call, to make it more likely that the license
// authentication call is already done
Thread.sleep(400)
}
Thread.sleep(500)
val impressionsBeforeOffline = MockedIngress.extractImpressions().combineByImpressionId()
assertThat(impressionsBeforeOffline).hasSize(1)
assertThat(impressionsBeforeOffline.values.first().eventDataList)
.hasSize(2)
MockedIngress.setServerOffline()
eventData.forEach {
bitmovinAnalytics.sendEventData(it)
// waiting a bit here after each call, to make it more likely that the license
// authentication call is already done
Thread.sleep(400)
}
Thread.sleep(500)
// server didn't receive any new requests since it is offline
assertThat(MockedIngress.requestCount()).isEqualTo(3)
MockedIngress.setServerOnline()
eventData.forEach {
bitmovinAnalytics.sendEventData(it)
// waiting a bit here after each call, to make it more likely that the license
// authentication call is already done
Thread.sleep(400)
}
// all samples in queue are sent together with the new samples
val impressionsAfterOffline = MockedIngress.extractImpressions().combineByImpressionId()
assertThat(impressionsAfterOffline).hasSize(1)
assertThat(impressionsAfterOffline.values.first().eventDataList)
.hasSize(4)
}
@Test
fun test_sending_ad_eventdata_sends_the_adevents() {
bitmovinAnalytics.attach(dummyPlayerAdapter)
val sessionId = createTestImpressionId()
val eventData: List<AdEventData> = MutableList(5) {
TestFactory.createAdEventData(
adImpressionId = sessionId,
videoImpressionId = sessionId,
)
}
eventData.forEach {
bitmovinAnalytics.sendAdEventData(it)
// waiting a bit here after each call, to make it more likely that the license
// authentication call is already done
Thread.sleep(400)
}
Thread.sleep(500)
val impressions = MockedIngress.extractImpressions().combineByImpressionId()
assertThat(impressions).hasSize(1)
assertThat(impressions.values.first().adEventDataList)
.hasSize(5)
.isEqualTo(eventData)
}
@Test
fun test_failed_ad_and_eventdata_sending_they_are_send_with_the_next_successful_one() {
MockedIngress.setServerOffline()
val cachedSessionId = createTestImpressionId()
val sessionId = createTestImpressionId(2)
bitmovinAnalytics.attach(dummyPlayerAdapter)
val eventData = MutableList(5) {
TestFactory.createEventData(impressionId = cachedSessionId)
}
val adEventData: List<AdEventData> = MutableList(5) {
TestFactory.createAdEventData(
adImpressionId = cachedSessionId,
videoImpressionId = cachedSessionId,
)
}
eventData.forEach { bitmovinAnalytics.sendEventData(it) }
adEventData.forEach { bitmovinAnalytics.sendAdEventData(it) }
Thread.sleep(1000)
assertThat(MockedIngress.hasNoSamplesReceived()).isTrue
// activate ingress backend again
MockedIngress.setServerOnline()
bitmovinAnalytics.attach(dummyPlayerAdapter)
// Trigger sending of cached data
bitmovinAnalytics.sendEventData(TestFactory.createEventData(impressionId = sessionId))
Thread.sleep(5000)
val impressions = MockedIngress.extractImpressions().combineByImpressionId()
assertThat(impressions).hasSize(2)
assertThat(impressions[cachedSessionId]!!.eventDataList)
.hasSize(5)
assertThat(impressions[cachedSessionId]!!.adEventDataList)
.hasSize(5)
}
@Test
fun test_failed_ad_and_eventdata_sending_are_send_by_another_bitmovin_analytics_instance() {
val cachedSessionId = createTestImpressionId()
val sessionId = createTestImpressionId(2)
val offlineConfig = config.copy(backendUrl = "https://doesnotwork")
bitmovinAnalytics = BitmovinAnalytics(
config = offlineConfig,
context = appContext,
eventQueue = eventQueue,
)
bitmovinAnalytics.attach(dummyPlayerAdapter)
val eventData = MutableList(5) {
TestFactory.createEventData(impressionId = cachedSessionId)
}
val adEventData: List<AdEventData> = MutableList(5) {
TestFactory.createAdEventData(
adImpressionId = cachedSessionId,
videoImpressionId = cachedSessionId,
)
}
eventData.forEach { bitmovinAnalytics.sendEventData(it) }
adEventData.forEach { bitmovinAnalytics.sendAdEventData(it) }
Thread.sleep(1000)
bitmovinAnalytics.detachPlayer()
val secondInstance = BitmovinAnalytics(
config = config,
context = appContext,
eventQueue = eventQueue,
)
dummyPlayerAdapter = createDummyPlayerAdapter()
secondInstance.attach(dummyPlayerAdapter)
// Trigger sending of cached data
secondInstance.sendEventData(TestFactory.createEventData(impressionId = sessionId))
Thread.sleep(5000)
val impressions = MockedIngress.extractImpressions().combineByImpressionId()
assertThat(impressions).hasSize(2)
val cachedImpression = impressions[cachedSessionId]
val triggerImpression = impressions[sessionId]
assertThat(cachedImpression!!.eventDataList).hasSize(5)
assertThat(cachedImpression.adEventDataList).hasSize(5)
assertThat(triggerImpression!!.eventDataList).hasSize(1)
}
@Test
fun test_having_multiple_bitmovin_analytics_instance_events_are_send_once() {
val offlineConfig = AnalyticsConfig(licenseKey = "<KEY>", retryPolicy = RetryPolicy.LONG_TERM, backendUrl = "https://doesnotwork")
val firstSession = createTestImpressionId()
val secondSession = createTestImpressionId(2)
val firstBitmovinAnalytics = BitmovinAnalytics(
config = offlineConfig,
context = appContext,
eventQueue = eventQueue,
)
val secondBitmovinAnalytics = BitmovinAnalytics(
config = offlineConfig,
context = appContext,
eventQueue = eventQueue,
)
val firstDummyPlayerAdapter = createDummyPlayerAdapter()
firstBitmovinAnalytics.attach(firstDummyPlayerAdapter)
val secondDummyPlayerAdapter = createDummyPlayerAdapter()
secondBitmovinAnalytics.attach(secondDummyPlayerAdapter)
val eventDataFirstCollector = MutableList(100) {
TestFactory.createEventData(impressionId = firstSession)
}
val eventDataSecondCollector = MutableList(100) {
TestFactory.createEventData(impressionId = secondSession)
}
val firstJob = mainScope.launch {
eventDataFirstCollector.forEach { firstBitmovinAnalytics.sendEventData(it) }
}
val secondJob = mainScope.launch {
eventDataSecondCollector.forEach { secondBitmovinAnalytics.sendEventData(it) }
}
runBlocking {
firstJob.join()
secondJob.join()
}
Thread.sleep(1000)
val onlineConfig = AnalyticsConfig(licenseKey = "<KEY>", retryPolicy = RetryPolicy.LONG_TERM)
val thirdBitmovinAnalytics = BitmovinAnalytics(
config = onlineConfig,
context = appContext,
eventQueue = eventQueue,
)
val forthBitmovinAnalytics = BitmovinAnalytics(
config = onlineConfig,
context = appContext,
eventQueue = eventQueue,
)
thirdBitmovinAnalytics.attach(firstDummyPlayerAdapter)
forthBitmovinAnalytics.attach(secondDummyPlayerAdapter)
// Trigger sending of cached data
thirdBitmovinAnalytics.sendEventData(TestFactory.createEventData(impressionId = firstSession))
forthBitmovinAnalytics.sendEventData(TestFactory.createEventData(impressionId = secondSession))
Thread.sleep(40000)
val impressions = MockedIngress.extractImpressions().combineByImpressionId()
impressions.values.forEach {
assertThat(it.eventDataList).hasSize(101)
}
}
@Test
fun test_having_more_than_14_days_old_events_in_the_event_queue_they_are_not_send_later() {
bitmovinAnalytics.attach(dummyPlayerAdapter)
val oldSession1 = createTestImpressionId(1)
val oldSession2 = createTestImpressionId(2)
val newSession = createTestImpressionId(1337)
val oldTimestamp = (System.currentTimeMillis().milliseconds - 15.days).inWholeMilliseconds
val oldEventData = MutableList(5) {
TestFactory.createEventData(
impressionId = oldSession1,
time = oldTimestamp + it,
)
}.apply {
TestFactory.createEventData(
impressionId = oldSession1,
time = System.currentTimeMillis(),
)
repeat(5) {
add(
TestFactory.createEventData(
impressionId = oldSession2,
time = oldTimestamp + it,
),
)
}
}
val oldAdEventData = MutableList(5) {
TestFactory.createAdEventData(
videoImpressionId = oldSession1,
adImpressionId = oldSession1,
time = oldTimestamp + it,
)
}.apply {
repeat(5) {
add(
TestFactory.createAdEventData(
videoImpressionId = oldSession2,
adImpressionId = oldSession2,
time = oldTimestamp + it,
),
)
}
}
PersistentAnalyticsEventQueue(
EventQueueConfig(),
EventDatabase.getInstance(appContext),
).run {
oldAdEventData.forEach(::push)
oldEventData.forEach(::push)
}
// Trigger sending of cached data
bitmovinAnalytics.sendEventData(TestFactory.createEventData(impressionId = newSession))
Thread.sleep(1000)
val impressions = MockedIngress.extractImpressions().combineByImpressionId()
assertThat(impressions.values).hasSize(1)
assertThat(impressions.values.first().eventDataList).hasSize(1)
}
@Test
fun test_reaching_the_overall_count_limit_deletes_the_oldest_session() {
config = config.copy(backendUrl = "https://doesnotwork")
bitmovinAnalytics = BitmovinAnalytics(
config = config,
context = appContext,
eventQueue = eventQueue,
)
bitmovinAnalytics.attach(dummyPlayerAdapter)
val newSession = createTestImpressionId()
val persistentQueue = PersistentAnalyticsEventQueue(
EventQueueConfig(),
EventDatabase.getInstance(appContext),
)
val sessionIds = persistentQueue.almostFillDatabaseToCountLimit()
assertThat(persistentQueue.popEvent()!!.impressionId).isEqualTo(sessionIds.first())
repeat(150) {
bitmovinAnalytics.sendEventData(TestFactory.createEventData(impressionId = newSession))
}
Thread.sleep(2000)
val secondSessionId = sessionIds[1]
assertThat(persistentQueue.popEvent()!!.impressionId).isEqualTo(secondSessionId)
assertThat(persistentQueue.popAdEvent()!!.videoImpressionId).isEqualTo(secondSessionId)
}
@Test
fun test_events_with_sequencenumber_higher_than_500_are_not_stored() {
val offlineConfig = config.copy(backendUrl = "https://doesnotwork")
bitmovinAnalytics = BitmovinAnalytics(
config = offlineConfig,
context = appContext,
eventQueue = eventQueue,
)
dummyPlayerAdapter = createDummyPlayerAdapter()
val persistentQueue = PersistentAnalyticsEventQueue(
EventQueueConfig(),
EventDatabase.getInstance(appContext),
)
val sessionId = UUID.randomUUID().toString()
repeat(300) {
bitmovinAnalytics.sendEventData(TestFactory.createEventData(impressionId = sessionId))
bitmovinAnalytics.sendAdEventData(
TestFactory.createAdEventData(
videoImpressionId = sessionId,
adImpressionId = sessionId,
),
)
}
// go beyond the sequence number limit
repeat(300) {
bitmovinAnalytics.sendEventData(TestFactory.createEventData(impressionId = sessionId))
}
// try to send/store more ad event data
repeat(300) {
bitmovinAnalytics.sendAdEventData(
TestFactory.createAdEventData(
videoImpressionId = sessionId,
adImpressionId = sessionId,
),
)
}
bitmovinAnalytics.detachPlayer()
var eventCount = 0
var element = persistentQueue.popEvent()
while (element != null) {
eventCount++
assertThat(element.sequenceNumber).isLessThan(501)
element = persistentQueue.popEvent()
}
assertThat(eventCount).isEqualTo(501)
var adEventCount = 0
var adElement = persistentQueue.popAdEvent()
while (adElement != null) {
adEventCount++
adElement = persistentQueue.popAdEvent()
}
assertThat(adEventCount).isEqualTo(300)
}
}
private fun List<Impression>.combineByImpressionId(): Map<String, Impression> {
val events = flatMap { it.eventDataList }.groupBy { it.impressionId }
val adEvents = flatMap { it.adEventDataList }.groupBy { it.videoImpressionId }
return (events.keys + adEvents.keys).associateWith {
Impression(
events[it]?.toMutableList() ?: mutableListOf(),
adEvents[it]?.toMutableList() ?: mutableListOf(),
)
}
}
private fun createTestImpressionId(
numberOfImpression: Int = 1,
) = UUID(0xB177E57, numberOfImpression.toLong()).toString()
private fun PersistentAnalyticsEventQueue.almostFillDatabaseToCountLimit(): List<String> {
val startTime = (System.currentTimeMillis().milliseconds - 10.hours).inWholeMilliseconds
val sessionIds = MutableList(10) { createTestImpressionId(it + 1) }
sessionIds.take(9).forEachIndexed { index, sessionId ->
repeat(500) {
push(
TestFactory.createEventData(
impressionId = sessionId,
sequenceNumber = it,
time = startTime + 500 * index + it,
),
)
}
repeat(100) {
push(
TestFactory.createAdEventData(
videoImpressionId = sessionId,
adImpressionId = sessionId,
time = startTime + 500 * index + it,
),
)
}
}
val lastSessionId = sessionIds.last()
repeat(400) {
push(
TestFactory.createEventData(
impressionId = lastSessionId,
sequenceNumber = it,
time = startTime + 500 * 10 + it,
),
)
}
return sessionIds
}
private class DummyPlayerAdapter(
analytics: BitmovinAnalytics,
playerContext: PlayerContext,
) : PlayerAdapter {
override val stateMachine: PlayerStateMachine = PlayerStateMachine.Factory.create(
analytics,
playerContext,
Handler(Looper.getMainLooper()),
)
override val position: Long
get() = 0
override val drmDownloadTime: Long?
get() = 0
override var defaultMetadata: DefaultMetadata = DefaultMetadata()
override val playerInfo: PlayerInfo
get() = PlayerInfo("Android:Testing", PlayerType.EXOPLAYER)
override fun init(): Collection<Feature<FeatureConfigContainer, *>> {
return emptyList()
}
override fun getCurrentSourceMetadata(): SourceMetadata = SourceMetadata()
override fun release() {
}
override fun resetSourceRelatedState() {
}
override fun clearValuesAfterSendingOfSample() {
}
override fun createEventData(): EventData {
return TestFactory.createEventData(createTestImpressionId(1001))
}
override fun createEventDataForCustomDataEvent(sourceMetadata: SourceMetadata): EventData {
return TestFactory.createEventData(createTestImpressionId(1))
}
}
private class DummyPlayerContext : PlayerContext {
override fun isPlaying(): Boolean {
return false
}
override val position: Long
get() = 0
}
| 1
| null |
6
| 9
|
ffde2585194bf468b00c409f32b68c76d1e7f0bb
| 22,202
|
bitmovin-analytics-collector-android
|
Amazon Digital Services License
|
sphinx/screens/onboard/onboard-message/src/main/java/chat/sphinx/onboard/ui/OnBoardMessageSideEffect.kt
|
stakwork
| 340,103,148
| false
| null |
package chat.sphinx.onboard.ui
import android.app.AlertDialog
import android.content.Context
import chat.sphinx.onboard.R
import chat.sphinx.wrapper_relay.RelayUrl
import io.matthewnelson.concept_views.sideeffect.SideEffect
internal sealed class OnBoardSideEffect: SideEffect<Context>() {
class RelayUrlHttpConfirmation(
private val relayUrl: RelayUrl,
private val callback: (RelayUrl?) -> Unit,
): OnBoardSideEffect() {
override suspend fun execute(value: Context) {
val builder = AlertDialog.Builder(value)
builder.setTitle(relayUrl.value)
builder.setMessage(value.getString(R.string.relay_url_http_message))
builder.setPositiveButton(R.string.relay_url_http_positive_change_to_https) { _, _ ->
callback.invoke(RelayUrl(relayUrl.value.replaceFirst("http://", "https://")))
}
builder.setNegativeButton(R.string.relay_url_http_negative_keep_http) { _, _ ->
callback.invoke(relayUrl)
}
builder.setOnCancelListener {
callback.invoke(null)
}
builder.show()
}
}
}
| 96
| null |
8
| 18
|
4fd9556a4a34f14126681535558fe1e39747b323
| 1,177
|
sphinx-kotlin
|
MIT License
|
lib/src/integrationTest/kotlin/com/lemonappdev/konsist/core/declaration/kosetter/KoSetterDeclarationForKoContainingFileProviderTest.kt
|
LemonAppDev
| 621,181,534
| false
| null |
package com.lemonappdev.konsist.core.declaration.kosetter
import com.lemonappdev.konsist.TestSnippetProvider.getSnippetKoScope
import org.amshove.kluent.shouldBeEqualTo
import org.junit.jupiter.api.Test
class KoSetterDeclarationForKoContainingFileProviderTest {
@Test
fun `setter-containing-file`() {
// given
val sut =
getSnippetFile("setter-containing-file")
.properties()
.first()
.setter
// then
sut
?.containingFile
?.nameWithExtension
?.endsWith("file.kt")
?.shouldBeEqualTo(true)
}
private fun getSnippetFile(fileName: String) =
getSnippetKoScope("core/declaration/kosetter/snippet/forkocontainingfileprovider/", fileName)
}
| 5
| null |
26
| 995
|
603d19e179f59445c5f4707c1528a438e4595136
| 800
|
konsist
|
Apache License 2.0
|
library/src/main/kotlin/com/daniloaraujosilva/mathemagika/library/common/mathematica/functions/FillingTransform.kt
|
Danilo-Araujo-Silva
| 271,904,885
| false
| null |
package com.daniloaraujosilva.mathemagika.library.common.mathematica.functions
import com.daniloaraujosilva.mathemagika.library.common.mathematica.MathematicaFunction
/**
*````
*
* Name: FillingTransform
*
* Full name: System`FillingTransform
*
* FillingTransform[image] gives a version of image with all extended minima filled.
* FillingTransform[image, marker] fills extended minima in regions where at least one corresponding element of marker is nonzero.
* Usage: FillingTransform[image, h] fills only extended minima of depth h or less.
*
* CornerNeighbors -> True
* Options: Padding -> 0
*
* Protected
* Attributes: ReadProtected
*
* local: paclet:ref/FillingTransform
* Documentation: web: http://reference.wolfram.com/language/ref/FillingTransform.html
*
* Definitions: None
*
* Own values: None
*
* Down values: None
*
* Up values: None
*
* Sub values: None
*
* Default value: None
*
* Numeric values: None
*/
fun fillingTransform(vararg arguments: Any?, options: MutableMap<String, Any?> = mutableMapOf()): MathematicaFunction {
return MathematicaFunction("FillingTransform", arguments.toMutableList(), options)
}
| 2
|
Kotlin
|
0
| 3
|
4fcf68af14f55b8634132d34f61dae8bb2ee2942
| 1,332
|
mathemagika
|
Apache License 2.0
|
kimhyebeen/Mission05/CustomBurger/app/src/main/java/com/khb/customburger/viewmodel/DecoRepository.kt
|
Yapp-17th
| 285,854,858
| false
|
{"Swift": 256086, "Kotlin": 116710, "JavaScript": 26300, "Ruby": 3960, "Objective-C": 1731, "HTML": 1196}
|
package com.khb.customburger.viewmodel
import com.khb.customburger.BasicBurger
import com.khb.customburger.Burger
import com.khb.customburger.concretedecorator.*
import java.lang.Exception
class DecoRepository {
fun makeBurger(materials: List<String>): Burger {
var burger: Burger = BasicBurger()
materials.map {
burger = getDecoBurger(burger, it)
}
return burger
}
private fun getDecoBurger(burger: Burger, str: String): Burger {
return when (str) {
"cabbage" -> Cabbage(burger)
"cheese" -> Cheese(burger)
"shrimp" -> Shrimp(burger)
"tomato" -> Tomato(burger)
"patty01" -> PorkPatty(burger)
"patty02" -> ChickenPatty(burger)
else -> throw Exception("DecoRepository-getDecoBurger : type is wrong")
}
}
}
| 20
|
Swift
|
1
| 5
|
572983a00913bbc110ce062f26fd2cb35475186b
| 867
|
Study_DesignPattern
|
MIT License
|
app/src/main/java/lt/vilnius/tvarkau/data/GsonSerializer.kt
|
vilnius
| 45,076,585
| false
| null |
package lt.vilnius.tvarkau.data
import java.lang.reflect.Type
interface GsonSerializer {
fun <T> toJson(value: T): String
fun <T> fromJson(json: String?, clazz: Class<T>): T
fun <T> fromJsonType(json: String, type: Type): T
}
| 7
| null |
15
| 24
|
3d546e1e70b5b05514f47e7cb6c1c2e03a7da093
| 241
|
tvarkau-vilniu
|
MIT License
|
kommons-core/src/commonTest/kotlin/com/bkahlert/kommons/RangesKtTest.kt
|
bkahlert
| 323,048,013
| false
| null |
package com.bkahlert.kommons
import com.bkahlert.kommons.test.testAll
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.matchers.collections.shouldBeEmpty
import io.kotest.matchers.collections.shouldContainExactly
import io.kotest.matchers.doubles.shouldBeBetween
import io.kotest.matchers.nulls.shouldBeNull
import io.kotest.matchers.nulls.shouldNotBeNull
import io.kotest.matchers.should
import io.kotest.matchers.shouldBe
import kotlin.random.Random
import kotlin.test.Test
class RangesKtTest {
@Test fun map() = testAll {
0.0.map(0.0..5.0, 0.0..1.0) shouldBe 0.0
0.4.map(0.0..5.0, 0.0..1.0) shouldBe 2.0
0.5.map(0.0..5.0, 0.0..1.0) shouldBe 2.5
0.75.map(0.0..5.0, 0.0..1.0) shouldBe 3.75
1.0.map(0.0..5.0, 0.0..1.0) shouldBe 5.0
shouldThrow<IllegalArgumentException> { (-0.1).map(0.0..5.0, 0.0..1.0) }
shouldThrow<IllegalArgumentException> { (1.1).map(0.0..5.0, 0.0..1.0) }
0.4.map(5.0) shouldBe 2.0
0.4.map(10.0) shouldBe 4.0
0.4.map(5.0..10.00) shouldBe 7.0
0.4.map((-5.0)..5.00) shouldBe -1.0
0.4.map((-15.0)..(-10.00)) shouldBe (-13.0)
}
@Test fun normalize() = testAll {
0.0.normalize(0.0..5.0) shouldBe 0.0
2.0.normalize(0.0..5.0) shouldBe 0.4
2.5.normalize(0.0..5.0) shouldBe 0.5
3.75.normalize(0.0..5.0) shouldBe 0.75
5.0.normalize(0.0..5.0) shouldBe 1.0
shouldThrow<IllegalArgumentException> { (-0.1).normalize(0.0..5.0) }
shouldThrow<IllegalArgumentException> { (5.1).normalize(0.0..5.0) }
2.0.normalize(5.0) shouldBe 0.4
4.0.normalize(10.0) shouldBe 0.4
7.0.normalize(5.0..10.00) shouldBe 0.4
(-1.0).normalize((-5.0)..5.00) shouldBe 0.4
(-13.0).normalize((-15.0)..(-10.00)) shouldBe 0.4
}
@Test fun scale() = testAll {
0.0.scale(-1.0, -1.0..4.0) shouldBe -1.0
0.0.scale(-0.8, -1.0..4.0) shouldBe -0.8
0.0.scale(0.0, -1.0..4.0) shouldBe 0.0
0.0.scale(0.8, -1.0..4.0) shouldBe 3.2
0.0.scale(1.0, -1.0..4.0) shouldBe 4.0
shouldThrow<IllegalArgumentException> { 0.0.scale(-1.1, -1.0..4.0) }
shouldThrow<IllegalArgumentException> { 0.0.scale(+1.1, -1.0..4.0) }
2.0.scale(-1.0, -1.0..4.0) - 1.0
2.0.scale(-0.8, -1.0..4.0).round(0.1) shouldBe -0.4
2.0.scale(0.0, -1.0..4.0) shouldBe 2.0
2.0.scale(0.8, -1.0..4.0) shouldBe 3.6
2.0.scale(1.0, -1.0..4.0) shouldBe 4.0
(-1.0).scale(0.8, -1.0..5.0).round(0.1) shouldBe 3.8
2.0.scale(0.8, 5.0) shouldBe 4.4
0.4.scale(0.8) shouldBe 0.88
shouldThrow<IllegalArgumentException> { 10.0.scale(0.0, -1.0..5.0) }
}
@Test fun end() = testAll {
(0..10).end shouldBe 11
shouldThrow<IllegalStateException> { (0..Int.MAX_VALUE).end }.message shouldBe "The exclusive end of 0..2147483647 is greater than Int.MAX_VALUE."
}
@Test fun random() = testAll {
(-4.2..42.0) should { range ->
repeat(100) { range.random().shouldBeBetween(-4.2, 42.0, 0.1) }
repeat(100) { range.random(Random(123)).shouldBeBetween(-4.2, 42.0, 0.1) }
}
@Suppress("EmptyRange")
(42.0..-4.2) should { range ->
shouldThrow<NoSuchElementException> { range.random().shouldBeNull() }
shouldThrow<NoSuchElementException> { range.random(Random(123)).shouldBeNull() }
}
}
@Test fun random_or_null() = testAll {
(-4.2..42.0) should { range ->
repeat(100) { range.randomOrNull().shouldNotBeNull().shouldBeBetween(-4.2, 42.0, 0.1) }
repeat(100) { range.randomOrNull(Random(123)).shouldNotBeNull().shouldBeBetween(-4.2, 42.0, 0.1) }
}
@Suppress("EmptyRange")
(42.0..-4.2) should { range ->
range.randomOrNull().shouldBeNull()
range.randomOrNull(Random(123)).shouldBeNull()
}
}
@Test fun as_iterable() = testAll {
(-4..42).asIterable { it + 9 }.map { it }.shouldContainExactly(-4, 5, 14, 23, 32, 41)
(-4.2..42.0).asIterable { it + 9 }.map { it.toInt() }.shouldContainExactly(-4, 4, 13, 22, 31, 40)
@Suppress("EmptyRange")
(42.0..-4.2).asIterable { it + 9 }.map { it.toInt() }.shouldBeEmpty()
}
}
| 5
| null |
0
| 18
|
747cb51cf6e6b729d574396a4938eabafbdac1fe
| 4,323
|
kommons
|
MIT License
|
html-parser/src/main/kotlin/it/skrape/selects/html5/FormSelectors.kt
|
skrapeit
| 165,720,614
| false
| null |
package it.skrape.selects.html5
import it.skrape.selects.CssSelectable
import it.skrape.selects.CssSelector
/**
* Will define a <button>-tags css query selector.
* By default it will just be the specific tag-name.
* It is possible to define a more concrete selector by using the provided fields of the CssSelector object or
* by passing a raw css query selector as parameter.
* If a selector is passed as parameter as well as be defined via CssSelector fields, they will be merged.
* @see CssSelector
* @param cssSelector
* @return T
*/
fun <T> CssSelectable.button(cssSelector: String = "", init: CssSelector.() -> T) =
selection("button$cssSelector", init)
/**
* Will define a <datalist>-tags css query selector.
* By default it will just be the specific tag-name.
* It is possible to define a more concrete selector by using the provided fields of the CssSelector object or
* by passing a raw css query selector as parameter.
* If a selector is passed as parameter as well as be defined via CssSelector fields, they will be merged.
* @see CssSelector
* @param cssSelector
* @return T
*/
fun <T> CssSelectable.datalist(cssSelector: String = "", init: CssSelector.() -> T) =
selection("datalist$cssSelector", init)
/**
* Will define a <fieldset>-tags css query selector.
* By default it will just be the specific tag-name.
* It is possible to define a more concrete selector by using the provided fields of the CssSelector object or
* by passing a raw css query selector as parameter.
* If a selector is passed as parameter as well as be defined via CssSelector fields, they will be merged.
* @see CssSelector
* @param cssSelector
* @return T
*/
fun <T> CssSelectable.fieldset(cssSelector: String = "", init: CssSelector.() -> T) =
selection("fieldset$cssSelector", init)
/**
* Will define a <form>-tags css query selector.
* By default it will just be the specific tag-name.
* It is possible to define a more concrete selector by using the provided fields of the CssSelector object or
* by passing a raw css query selector as parameter.
* If a selector is passed as parameter as well as be defined via CssSelector fields, they will be merged.
* @see CssSelector
* @param cssSelector
* @return T
*/
fun <T> CssSelectable.form(cssSelector: String = "", init: CssSelector.() -> T) =
selection("form$cssSelector", init)
/**
* Will define a <input>-tags css query selector.
* By default it will just be the specific tag-name.
* It is possible to define a more concrete selector by using the provided fields of the CssSelector object or
* by passing a raw css query selector as parameter.
* If a selector is passed as parameter as well as be defined via CssSelector fields, they will be merged.
* @see CssSelector
* @param cssSelector
* @return T
*/
fun <T> CssSelectable.input(cssSelector: String = "", init: CssSelector.() -> T) =
selection("input$cssSelector", init)
/**
* Will define a <label>-tags css query selector.
* By default it will just be the specific tag-name.
* It is possible to define a more concrete selector by using the provided fields of the CssSelector object or
* by passing a raw css query selector as parameter.
* If a selector is passed as parameter as well as be defined via CssSelector fields, they will be merged.
* @see CssSelector
* @param cssSelector
* @return T
*/
fun <T> CssSelectable.label(cssSelector: String = "", init: CssSelector.() -> T) =
selection("label$cssSelector", init)
/**
* Will define a <legend>-tags css query selector.
* By default it will just be the specific tag-name.
* It is possible to define a more concrete selector by using the provided fields of the CssSelector object or
* by passing a raw css query selector as parameter.
* If a selector is passed as parameter as well as be defined via CssSelector fields, they will be merged.
* @see CssSelector
* @param cssSelector
* @return T
*/
fun <T> CssSelectable.legend(cssSelector: String = "", init: CssSelector.() -> T) =
selection("legend$cssSelector", init)
/**
* Will define a <meter>-tags css query selector.
* By default it will just be the specific tag-name.
* It is possible to define a more concrete selector by using the provided fields of the CssSelector object or
* by passing a raw css query selector as parameter.
* If a selector is passed as parameter as well as be defined via CssSelector fields, they will be merged.
* @see CssSelector
* @param cssSelector
* @return T
*/
fun <T> CssSelectable.meter(cssSelector: String = "", init: CssSelector.() -> T) =
selection("meter$cssSelector", init)
/**
* Will define a <optgroup>-tags css query selector.
* By default it will just be the specific tag-name.
* It is possible to define a more concrete selector by using the provided fields of the CssSelector object or
* by passing a raw css query selector as parameter.
* If a selector is passed as parameter as well as be defined via CssSelector fields, they will be merged.
* @see CssSelector
* @param cssSelector
* @return T
*/
fun <T> CssSelectable.optgroup(cssSelector: String = "", init: CssSelector.() -> T) =
selection("optgroup$cssSelector", init)
/**
* Will define a <option>-tags css query selector.
* By default it will just be the specific tag-name.
* It is possible to define a more concrete selector by using the provided fields of the CssSelector object or
* by passing a raw css query selector as parameter.
* If a selector is passed as parameter as well as be defined via CssSelector fields, they will be merged.
* @see CssSelector
* @param cssSelector
* @return T
*/
fun <T> CssSelectable.option(cssSelector: String = "", init: CssSelector.() -> T) =
selection("option$cssSelector", init)
/**
* Will define a <output>-tags css query selector.
* By default it will just be the specific tag-name.
* It is possible to define a more concrete selector by using the provided fields of the CssSelector object or
* by passing a raw css query selector as parameter.
* If a selector is passed as parameter as well as be defined via CssSelector fields, they will be merged.
* @see CssSelector
* @param cssSelector
* @return T
*/
fun <T> CssSelectable.output(cssSelector: String = "", init: CssSelector.() -> T) =
selection("output$cssSelector", init)
/**
* Will define a <progress>-tags css query selector.
* By default it will just be the specific tag-name.
* It is possible to define a more concrete selector by using the provided fields of the CssSelector object or
* by passing a raw css query selector as parameter.
* If a selector is passed as parameter as well as be defined via CssSelector fields, they will be merged.
* @see CssSelector
* @param cssSelector
* @return T
*/
fun <T> CssSelectable.progress(cssSelector: String = "", init: CssSelector.() -> T) =
selection("progress$cssSelector", init)
/**
* Will define a <isPresent>-tags css query selector.
* By default it will just be the specific tag-name.
* It is possible to define a more concrete selector by using the provided fields of the CssSelector object or
* by passing a raw css query selector as parameter.
* If a selector is passed as parameter as well as be defined via CssSelector fields, they will be merged.
* @see CssSelector
* @param cssSelector
* @return T
*/
fun <T> CssSelectable.select(cssSelector: String = "", init: CssSelector.() -> T) =
selection("isPresent$cssSelector", init)
/**
* Will define a <textarea>-tags css query selector.
* By default it will just be the specific tag-name.
* It is possible to define a more concrete selector by using the provided fields of the CssSelector object or
* by passing a raw css query selector as parameter.
* If a selector is passed as parameter as well as be defined via CssSelector fields, they will be merged.
* @see CssSelector
* @param cssSelector
* @return T
*/
fun <T> CssSelectable.textarea(cssSelector: String = "", init: CssSelector.() -> T) =
selection("textarea$cssSelector", init)
| 30
| null |
58
| 793
|
0cf3e5c2f5322deabf28c5872624d2f876d321c7
| 8,096
|
skrape.it
|
MIT License
|
core/src/main/java/com/github/windsekirun/naraeaudiorecorder/extensions/RxExtensions.kt
|
WindSekirun
| 164,206,852
| false
| null |
package com.github.windsekirun.naraeaudiorecorder.extensions
import com.github.windsekirun.naraeaudiorecorder.model.DebugState
import io.reactivex.Observable
import io.reactivex.annotations.CheckReturnValue
import io.reactivex.disposables.Disposable
/**
* internal extensions to handle onNext, onError, onComplete event
*/
@CheckReturnValue
fun <T> Observable<T>.subscribe(callback: (T?, Throwable?, Boolean) -> Unit): Disposable {
return this.subscribe({
callback.invoke(it, null, false)
}, {
DebugState.error("error", it)
callback.invoke(null, it, false)
}, {
callback.invoke(null, null, true)
})
}
/**
* internal extensions to handle dispose Disposable
*/
fun Disposable?.safeDispose() {
if (this != null && !this.isDisposed) this.dispose()
}
| 9
|
Kotlin
|
19
| 85
|
dd59377b2a41db32b4244e4d0135d0c7e82bdad6
| 804
|
NaraeAudioRecorder
|
Apache License 2.0
|
app/src/main/java/com/example/noteapp/Model/Note.kt
|
ahmedsamir9
| 256,301,731
| false
| null |
package com.example.noteapp.Model
import android.os.Parcelable
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.Ignore
import androidx.room.PrimaryKey
import kotlinx.android.parcel.Parcelize
@Parcelize
@Entity
data class Note(
@PrimaryKey(autoGenerate = true)
var id:Int,
@ColumnInfo
var title:String,
@ColumnInfo
var description:String,
@ColumnInfo
var importance:Int
):Parcelable{
}
| 0
|
Kotlin
|
0
| 1
|
ad3ebc4079377ba48f5a84521d3935b1df2524b1
| 451
|
Note-app-kotlin
|
MIT License
|
src/opennlp-conll/main/opennlp/ext/conll/treebank/features/lexical/PronType.kt
|
rhdunn
| 418,266,921
| false
| null |
// Copyright (C) 2021 <NAME>. SPDX-License-Identifier: Apache-2.0
package opennlp.ext.conll.treebank.features.lexical
import opennlp.ext.conll.treebank.Feature
import opennlp.ext.conll.treebank.FeatureSet
import opennlp.ext.conll.treebank.features.UnknownFeatureValue
// Reference: [PronType](https://universaldependencies.org/u/feat/PronType.html)
enum class PronType : Feature {
Art, Dem, Emp, Exc, Ind, Int, Neg, Prs, Rcp, Rel, Tot;
override val type: String = "PronType"
override val value: String = name
override fun toString(): String = "$type=$value"
companion object : FeatureSet {
override val type: String = "PronType"
override fun create(value: String): Feature {
return values().find { it.value == value } ?: UnknownFeatureValue(type, value)
}
}
}
| 0
|
Kotlin
|
0
| 3
|
3b0f35236af1773bf28a5ccec8c2e8bf7a3de9b2
| 826
|
opennlp-extensions
|
Apache License 2.0
|
src-test-split/nyab/util/QStringAlign.kt
|
nyabkun
| 643,495,669
| false
| null |
/*
* Copyright 2023. nyabkun
*
* 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 nyab.util
import kotlin.math.abs
// qq-shell-color is a self-contained single-file library created by nyabkun.
// This is a split-file version of the library, this file is not self-contained.
// CallChain[size=5] = QAlign <-[Ref]- qSeparatorWithLabel() <-[Call]- qTestMethods() <-[Call]- qTest() <-[Call]- main()[Root]
internal enum class QAlign {
// CallChain[size=5] = QAlign.LEFT <-[Call]- qSeparatorWithLabel() <-[Call]- qTestMethods() <-[Call]- qTest() <-[Call]- main()[Root]
LEFT,
// CallChain[size=6] = QAlign.RIGHT <-[Propag]- QAlign.LEFT <-[Call]- qSeparatorWithLabel() <-[Call]- qTestMethods() <-[Call]- qTest() <-[Call]- main()[Root]
RIGHT,
// CallChain[size=6] = QAlign.CENTER <-[Propag]- QAlign.LEFT <-[Call]- qSeparatorWithLabel() <-[Call]- qTestMethods() <-[Call]- qTest() <-[Call]- main()[Root]
CENTER
}
// CallChain[size=9] = QLineMatchResult <-[Call]- String.qAlign() <-[Call]- String.qAlignCenter() <- ... <-[Call]- qSeparatorWithLabel() <-[Call]- qTestMethods() <-[Call]- qTest() <-[Call]- main()[Root]
internal class QLineMatchResult(
val regex: Regex,
val text: String,
val onlyFirstMatch: Boolean = false,
val groupIdx: QGroupIdx
) {
// CallChain[size=10] = QLineMatchResult.curText <-[Call]- QLineMatchResult.align() <-[Call]- String ... <-[Call]- qSeparatorWithLabel() <-[Call]- qTestMethods() <-[Call]- qTest() <-[Call]- main()[Root]
var curText: String = text
// CallChain[size=10] = QLineMatchResult.updateResult() <-[Call]- QLineMatchResult.align() <-[Call]- ... <-[Call]- qSeparatorWithLabel() <-[Call]- qTestMethods() <-[Call]- qTest() <-[Call]- main()[Root]
private fun updateResult(align: QAlign) {
updateRowResult()
updateColResult()
updateColDestPos(align)
}
// CallChain[size=11] = QLineMatchResult.rowResults <-[Call]- QLineMatchResult.matchedRange() <-[Cal ... <-[Call]- qSeparatorWithLabel() <-[Call]- qTestMethods() <-[Call]- qTest() <-[Call]- main()[Root]
// line index -> match index
lateinit var rowResults: List<List<MatchResult>>
// CallChain[size=12] = QLineMatchResult.colResults <-[Call]- QLineMatchResult.updateColDestPos() <- ... <-[Call]- qSeparatorWithLabel() <-[Call]- qTestMethods() <-[Call]- qTest() <-[Call]- main()[Root]
// col index -> match index
lateinit var colResults: List<List<MatchResult>>
// CallChain[size=10] = QLineMatchResult.colDestPos <-[Call]- QLineMatchResult.align() <-[Call]- Str ... <-[Call]- qSeparatorWithLabel() <-[Call]- qTestMethods() <-[Call]- qTest() <-[Call]- main()[Root]
// col index -> max left index / right index of matched region
lateinit var colDestPos: List<QLeftRight>
// CallChain[size=11] = QLineMatchResult.updateRowResult() <-[Call]- QLineMatchResult.updateResult() ... <-[Call]- qSeparatorWithLabel() <-[Call]- qTestMethods() <-[Call]- qTest() <-[Call]- main()[Root]
private fun updateRowResult() {
rowResults = if (onlyFirstMatch) {
curText.lineSequence().map { regex.find(it, 0) }.map {
if (it == null) {
emptyList()
} else {
listOf(it)
}
}.toList()
} else {
curText.lineSequence().map { regex.findAll(it, 0).toList() }.toList()
}
}
// CallChain[size=11] = QLineMatchResult.updateColResult() <-[Call]- QLineMatchResult.updateResult() ... <-[Call]- qSeparatorWithLabel() <-[Call]- qTestMethods() <-[Call]- qTest() <-[Call]- main()[Root]
private fun updateColResult() {
colResults = mutableListOf<List<MatchResult>>().also { list ->
val maximumRowMatchCount = rowResults.maxOfOrNull { it.size } ?: -1
for (iColumn in 0 until maximumRowMatchCount) {
list += rowResults.mapNotNull { result ->
result.getOrNull(iColumn)
}
}
}
}
// CallChain[size=11] = QLineMatchResult.updateColDestPos() <-[Call]- QLineMatchResult.updateResult( ... <-[Call]- qSeparatorWithLabel() <-[Call]- qTestMethods() <-[Call]- qTest() <-[Call]- main()[Root]
private fun updateColDestPos(align: QAlign) {
colDestPos = if (align == QAlign.RIGHT) {
colResults.map { it.qMinOrMaxIndexLR(groupIdx, QMinOrMax.MAX) }
} else {
colResults.map { it.qMinOrMaxIndexLR(groupIdx, QMinOrMax.MIN) }
}
}
// CallChain[size=10] = QLineMatchResult.matchedRange() <-[Call]- QLineMatchResult.align() <-[Call]- ... <-[Call]- qSeparatorWithLabel() <-[Call]- qTestMethods() <-[Call]- qTest() <-[Call]- main()[Root]
private fun matchedRange(rowIdx: Int, colIdx: Int): IntRange? {
val groups = rowResults.getOrNull(rowIdx)?.getOrNull(colIdx)?.groups ?: return null
return if (groupIdx.idx < groups.size) {
groups[groupIdx.idx]?.range
} else {
null
}
}
// CallChain[size=12] = QLineMatchResult.QMinOrMax <-[Ref]- QLineMatchResult.updateColDestPos() <-[C ... <-[Call]- qSeparatorWithLabel() <-[Call]- qTestMethods() <-[Call]- qTest() <-[Call]- main()[Root]
enum class QMinOrMax {
MIN, MAX
}
// CallChain[size=12] = QLineMatchResult.List<MatchResult>.qMinOrMaxIndexLR() <-[Call]- QLineMatchRe ... <-[Call]- qSeparatorWithLabel() <-[Call]- qTestMethods() <-[Call]- qTest() <-[Call]- main()[Root]
private fun List<MatchResult>.qMinOrMaxIndexLR(
groupIdx: QGroupIdx,
minOrMax: QMinOrMax
): QLeftRight {
val leftList = mapNotNull {
if (groupIdx.idx < it.groups.size) {
it.groups[groupIdx.idx]?.range?.first
} else {
-1
}
}
val left =
if (minOrMax == QMinOrMax.MIN) {
leftList.minOrNull() ?: -1
} else {
leftList.maxOrNull() ?: -1
}
val rightList = mapNotNull {
if (groupIdx.idx < it.groups.size) {
it.groups[groupIdx.idx]?.range?.last
} else {
-1
}
}
val right =
if (minOrMax == QMinOrMax.MIN) {
rightList.minOrNull() ?: -1
} else {
rightList.maxOrNull() ?: -1
}
return QLeftRight(left, right)
}
// CallChain[size=9] = QLineMatchResult.align() <-[Call]- String.qAlign() <-[Call]- String.qAlignCen ... <-[Call]- qSeparatorWithLabel() <-[Call]- qTestMethods() <-[Call]- qTest() <-[Call]- main()[Root]
fun align(align: QAlign = QAlign.RIGHT, keepLength: Boolean = false, oddLengthTuning: QLR): String {
updateResult(align)
var colIdx = 0
while (colIdx < colDestPos.size) {
val lines = curText.lineSequence().mapIndexed { rowIdx, line ->
val range = matchedRange(rowIdx, colIdx) ?: return@mapIndexed line
if (align == QAlign.CENTER) {
line.qMoveCenter(range, oddLengthTuning)
} else {
val maxLR = colDestPos[colIdx]
val destLeft = when (align) {
QAlign.RIGHT -> maxLR.right - range.qSize + 1
QAlign.LEFT -> maxLR.left
else -> qUnreachable()
}
if (range.first < destLeft) {
line.qMoveRight(range, destLeft, keepLength)
} else {
line.qMoveLeft(range, destLeft, keepLength)
}
}
}
curText = lines.joinToString("\n")
if (!keepLength && align != QAlign.CENTER) {
updateResult(align)
}
colIdx++
}
return curText
}
}
// CallChain[size=10] = qSize <-[Call]- QLineMatchResult.align() <-[Call]- String.qAlign() <-[Call]- ... <-[Call]- qSeparatorWithLabel() <-[Call]- qTestMethods() <-[Call]- qTest() <-[Call]- main()[Root]
private val IntRange.qSize: Int
get() = abs(last - first) + 1
// CallChain[size=8] = String.qIsNumber() <-[Call]- String.qAlignCenter() <-[Call]- String.qWithMinL ... <-[Call]- qSeparatorWithLabel() <-[Call]- qTestMethods() <-[Call]- qTest() <-[Call]- main()[Root]
internal fun String.qIsNumber(): Boolean {
return this.trim().matches("""[\d./eE+-]+""".re)
}
// CallChain[size=7] = String.qAlignCenter() <-[Call]- String.qWithMinLength() <-[Call]- String.qWit ... <-[Call]- qSeparatorWithLabel() <-[Call]- qTestMethods() <-[Call]- qTest() <-[Call]- main()[Root]
internal fun String.qAlignCenter(
vararg places: Regex = arrayOf("(.*)".re),
onlyFirstMatch: Boolean = true,
oddLengthTuning: QLR = if (qIsNumber()) QLR.RIGHT else QLR.LEFT,
groupIdx: QGroupIdx = QGroupIdx.FIRST
): String {
return qAlign(QAlign.CENTER, *places, onlyFirstMatch = onlyFirstMatch, oddLengthTuning = oddLengthTuning, groupIdx = groupIdx)
}
// CallChain[size=8] = String.qAlign() <-[Call]- String.qAlignCenter() <-[Call]- String.qWithMinLeng ... <-[Call]- qSeparatorWithLabel() <-[Call]- qTestMethods() <-[Call]- qTest() <-[Call]- main()[Root]
private fun String.qAlign(
align: QAlign = QAlign.RIGHT,
vararg places: Regex,
onlyFirstMatch: Boolean = true,
keepLength: Boolean = false,
oddLengthTuning: QLR = if (qIsNumber()) QLR.RIGHT else QLR.LEFT,
groupIdx: QGroupIdx = QGroupIdx.ENTIRE_MATCH
): String {
var text = this
for (p in places) {
text = QLineMatchResult(p, text, onlyFirstMatch, groupIdx).align(align, keepLength, oddLengthTuning)
}
return text
}
// CallChain[size=11] = QLeftRight <-[Ref]- QLineMatchResult.colDestPos <-[Call]- QLineMatchResult.a ... <-[Call]- qSeparatorWithLabel() <-[Call]- qTestMethods() <-[Call]- qTest() <-[Call]- main()[Root]
internal data class QLeftRight(val left: Int, val right: Int)
// CallChain[size=8] = QGroupIdx <-[Ref]- String.qAlignCenter() <-[Call]- String.qWithMinLength() <- ... <-[Call]- qSeparatorWithLabel() <-[Call]- qTestMethods() <-[Call]- qTest() <-[Call]- main()[Root]
internal enum class QGroupIdx(val idx: Int) {
// CallChain[size=9] = QGroupIdx.ENTIRE_MATCH <-[Call]- String.qAlign() <-[Call]- String.qAlignCente ... <-[Call]- qSeparatorWithLabel() <-[Call]- qTestMethods() <-[Call]- qTest() <-[Call]- main()[Root]
ENTIRE_MATCH(0),
// CallChain[size=8] = QGroupIdx.FIRST <-[Call]- String.qAlignCenter() <-[Call]- String.qWithMinLeng ... <-[Call]- qSeparatorWithLabel() <-[Call]- qTestMethods() <-[Call]- qTest() <-[Call]- main()[Root]
FIRST(1),
// CallChain[size=12] = QGroupIdx.SECOND <-[Propag]- QGroupIdx.QGroupIdx() <-[Call]- QLineMatchResul ... <-[Call]- qSeparatorWithLabel() <-[Call]- qTestMethods() <-[Call]- qTest() <-[Call]- main()[Root]
SECOND(2),
// CallChain[size=12] = QGroupIdx.THIRD <-[Propag]- QGroupIdx.QGroupIdx() <-[Call]- QLineMatchResult ... <-[Call]- qSeparatorWithLabel() <-[Call]- qTestMethods() <-[Call]- qTest() <-[Call]- main()[Root]
THIRD(3),
// CallChain[size=12] = QGroupIdx.FOURTH <-[Propag]- QGroupIdx.QGroupIdx() <-[Call]- QLineMatchResul ... <-[Call]- qSeparatorWithLabel() <-[Call]- qTestMethods() <-[Call]- qTest() <-[Call]- main()[Root]
FOURTH(4),
// CallChain[size=12] = QGroupIdx.FIFTH <-[Propag]- QGroupIdx.QGroupIdx() <-[Call]- QLineMatchResult ... <-[Call]- qSeparatorWithLabel() <-[Call]- qTestMethods() <-[Call]- qTest() <-[Call]- main()[Root]
FIFTH(5),
// CallChain[size=12] = QGroupIdx.SIXTH <-[Propag]- QGroupIdx.QGroupIdx() <-[Call]- QLineMatchResult ... <-[Call]- qSeparatorWithLabel() <-[Call]- qTestMethods() <-[Call]- qTest() <-[Call]- main()[Root]
SIXTH(6),
// CallChain[size=12] = QGroupIdx.SEVENTH <-[Propag]- QGroupIdx.QGroupIdx() <-[Call]- QLineMatchResu ... <-[Call]- qSeparatorWithLabel() <-[Call]- qTestMethods() <-[Call]- qTest() <-[Call]- main()[Root]
SEVENTH(7),
// CallChain[size=12] = QGroupIdx.EIGHTH <-[Propag]- QGroupIdx.QGroupIdx() <-[Call]- QLineMatchResul ... <-[Call]- qSeparatorWithLabel() <-[Call]- qTestMethods() <-[Call]- qTest() <-[Call]- main()[Root]
EIGHTH(8),
// CallChain[size=12] = QGroupIdx.NINTH <-[Propag]- QGroupIdx.QGroupIdx() <-[Call]- QLineMatchResult ... <-[Call]- qSeparatorWithLabel() <-[Call]- qTestMethods() <-[Call]- qTest() <-[Call]- main()[Root]
NINTH(9),
// CallChain[size=12] = QGroupIdx.TENTH <-[Propag]- QGroupIdx.QGroupIdx() <-[Call]- QLineMatchResult ... <-[Call]- qSeparatorWithLabel() <-[Call]- qTestMethods() <-[Call]- qTest() <-[Call]- main()[Root]
TENTH(10);
}
// CallChain[size=10] = String.qMoveCenter() <-[Call]- QLineMatchResult.align() <-[Call]- String.qAl ... <-[Call]- qSeparatorWithLabel() <-[Call]- qTestMethods() <-[Call]- qTest() <-[Call]- main()[Root]
// always keep length
private fun String.qMoveCenter(range: IntRange, oddLengthTuning: QLR): String {
val regionText = qSubstring(range) // includes spaces
val nLeftSpace = regionText.qCountLeftSpace()
val nRightSpace = regionText.qCountRightSpace()
val nonSpaceChars = regionText.substring(nLeftSpace, regionText.length - nRightSpace)
val nLeftSpaceTarget =
if (oddLengthTuning == QLR.LEFT || (nLeftSpace + nRightSpace) % 2 == 0) {
abs(nLeftSpace + nRightSpace) / 2
} else {
abs(nLeftSpace + nRightSpace) / 2 + 1
}
val nRightSpaceTarget = (nLeftSpace + nRightSpace) - nLeftSpaceTarget
return replaceRange(range, " ".repeat(nLeftSpaceTarget) + nonSpaceChars + " ".repeat(nRightSpaceTarget))
// return substring(
// 0, range.first
// ) + " ".repeat(nLeftSpaceTarget) + nonSpaceChars + " ".repeat(nRightSpaceTarget) + substring(range.last + 1, length)
}
// CallChain[size=10] = String.qMoveLeft() <-[Call]- QLineMatchResult.align() <-[Call]- String.qAlig ... <-[Call]- qSeparatorWithLabel() <-[Call]- qTestMethods() <-[Call]- qTest() <-[Call]- main()[Root]
private fun String.qMoveLeft(range: IntRange, destRangeLeft: Int, keepLength: Boolean): String {
if (destRangeLeft >= range.first) {
return this
}
if (substring(destRangeLeft, range.first).isNotBlank()) {
// can't move. already has some contents.
return this
}
val regionText = qSubstring(range)
val nSpaces = range.first - destRangeLeft
if (nSpaces <= 0) return this
// when keepLength is true, add as many spaces to the right as removed
val rightSpaces = if (keepLength) " ".repeat(nSpaces) else ""
// cut left spaces
val first = substring(0, range.first - nSpaces) + regionText
// add spaces to the right
return first + rightSpaces + substring(range.last + 1, length)
}
// CallChain[size=10] = String.qMoveRight() <-[Call]- QLineMatchResult.align() <-[Call]- String.qAli ... <-[Call]- qSeparatorWithLabel() <-[Call]- qTestMethods() <-[Call]- qTest() <-[Call]- main()[Root]
private fun String.qMoveRight(range: IntRange, destRangeLeft: Int, keepLength: Boolean): String {
val regionText = qSubstring(range)
val nSpaces = destRangeLeft - range.first
if (nSpaces <= 0) return this
val spaces = " ".repeat(nSpaces)
return if (keepLength) {
if (range.last + 1 > length) return this
if (range.last + 1 + nSpaces > length) return this
if (substring(range.last + 1, range.last + 1 + nSpaces).isNotBlank()) return this
replaceRange(IntRange(range.first, range.last - nSpaces), spaces + regionText)
} else {
replaceRange(range, spaces + regionText)
}
}
| 0
|
Kotlin
|
0
| 1
|
c9da5932027900b6b2ac9881f387590b112d7ff0
| 16,687
|
qq-tree
|
MIT License
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.