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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
batterysync/mobile/src/androidMain/kotlin/com/boswelja/smartwatchextensions/batterysync/ui/BatterySlider.kt | boswelja | 103,805,743 | false | null | package com.boswelja.smartwatchextensions.batterysync.ui
import androidx.compose.foundation.layout.Column
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.ListItem
import androidx.compose.material.Slider
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import com.boswelja.smartwatchextensions.batterysync.R
import com.boswelja.smartwatchextensions.batterysync.ui.BatterySliderDefaults.PROGRESS_FACTOR
import com.boswelja.smartwatchextensions.batterysync.ui.BatterySliderDefaults.STEP_SIZE
import kotlin.math.roundToInt
/**
* A [ListItem] containing some text and a slider. This allows the user to pick a battery percent value.
* @param valueRange The possible selectable range. Start and end values should be set in
* [BatterySliderDefaults.STEP_SIZE] increments. The start value should be at or above 0f and the end value should be at
* or below 1f.
* @param value The current value.
* @param onValueChanged Called when the user has finished adjusting the slider value.
* @param text The text to display. This should describe the slider's purpose.
* @param modifier [Modifier].
*/
@OptIn(ExperimentalMaterialApi::class)
@Composable
fun BatterySliderSetting(
valueRange: ClosedFloatingPointRange<Float>,
value: Float,
onValueChanged: (Float) -> Unit,
text: @Composable () -> Unit,
enabled: Boolean,
modifier: Modifier = Modifier
) {
var currentValue by remember(value) { mutableStateOf(value) }
val steps = remember(valueRange) {
((valueRange.endInclusive - valueRange.start) / STEP_SIZE).roundToInt() - 1
}
ListItem(
modifier = modifier,
text = text,
secondaryText = {
Column {
Text(stringResource(R.string.battery_percent, (currentValue * PROGRESS_FACTOR).roundToInt()))
Slider(
value = currentValue,
valueRange = valueRange,
steps = steps,
onValueChange = { currentValue = it },
onValueChangeFinished = {
onValueChanged(currentValue)
},
enabled = enabled
)
}
}
)
}
/**
* Contains default values for Battery Sliders.
*/
object BatterySliderDefaults {
/**
* The factor used to convert between integer and floating point percentages.
*/
const val PROGRESS_FACTOR = 100f
/**
* The default step size for battery sliders.
*/
const val STEP_SIZE = 0.05f
}
| 14 | Kotlin | 0 | 12 | c716630794b1a34aa7f0d27c51b2094029967834 | 2,850 | SmartwatchExtensions | Apache License 2.0 |
browser-kotlin/src/jsMain/kotlin/web/history/PageTransitionEvent.types.deprecated.kt | karakum-team | 393,199,102 | false | {"Kotlin": 6328455} | // Automatically generated - do not modify!
package web.history
import seskar.js.JsValue
import web.events.EventType
sealed external class PageTransitionEventTypes_deprecated {
@Deprecated(
message = "Legacy event type declaration. Use type constant instead!",
replaceWith = ReplaceWith("PageTransitionEvent.PAGE_HIDE"),
)
@JsValue("pagehide")
fun pageHide(): EventType<PageTransitionEvent>
@Deprecated(
message = "Legacy event type declaration. Use type constant instead!",
replaceWith = ReplaceWith("PageTransitionEvent.PAGE_SHOW"),
)
@JsValue("pageshow")
fun pageShow(): EventType<PageTransitionEvent>
}
| 1 | Kotlin | 8 | 35 | 6c553c67c6cbf77a802c137d010b143895c7da60 | 676 | types-kotlin | Apache License 2.0 |
src/main/kotlin/common/init/ItemGroups.kt | Cosmic-Goat | 356,115,770 | true | {"Kotlin": 25981, "Shell": 1929} | package net.dblsaiko.rswires.common.init
import net.dblsaiko.hctm.common.util.ext.makeStack
import net.dblsaiko.rswires.MOD_ID
import net.fabricmc.fabric.api.client.itemgroup.FabricItemGroupBuilder
import net.minecraft.item.ItemGroup
import net.minecraft.util.Identifier
object ItemGroups {
val ALL: ItemGroup = FabricItemGroupBuilder.create(Identifier(MOD_ID, "all"))
.icon { Items.RED_ALLOY_WIRE.makeStack() }
.build()
} | 0 | null | 0 | 0 | 9e73f148745b25fea9b0c6b729dcb93f348ab4b8 | 436 | rswires | MIT License |
model/src/commonMain/kotlin/io/github/droidkaigi/feeder/NotificationContents.kt | DroidKaigi | 448,507,544 | false | null | package io.github.droidkaigi.feeder
import kotlinx.datetime.LocalDateTime
import kotlinx.datetime.TimeZone
import kotlinx.datetime.toInstant
data class NotificationContents(
val notificationItems: List<NotificationItem> = listOf(),
)
fun fakeNotificationContents(): NotificationContents = NotificationContents(
notificationItems = listOf(
NotificationItem(
id = "1",
title = "title 1",
content = "content 1",
type = NotificationItem.Type.ALERT,
publishedAt = LocalDateTime
.parse("2022-03-30T00:00:00")
.toInstant(TimeZone.of("UTC+9")),
deletedAt = null,
language = NotificationItem.Language.JAPANESE,
),
NotificationItem(
id = "2",
title = "title 2 the title of this content is very very very long.",
content = "content 2",
type = NotificationItem.Type.NOTIFICATION,
publishedAt = LocalDateTime
.parse("2022-03-20T00:00:00")
.toInstant(TimeZone.of("UTC+9")),
deletedAt = null,
language = NotificationItem.Language.ENGLISH,
),
NotificationItem(
id = "3",
title = "title 3",
content = "content 3 is long content. it is too long. it is very very long.",
type = NotificationItem.Type.FEEDBACK,
publishedAt = LocalDateTime
.parse("2022-03-10T00:00:00")
.toInstant(TimeZone.of("UTC+9")),
deletedAt = null,
language = NotificationItem.Language.JAPANESE,
),
NotificationItem(
id = "4",
title = "title 4",
content = "content 4",
type = NotificationItem.Type.FEEDBACK,
publishedAt = LocalDateTime
.parse("2022-02-20T00:00:00")
.toInstant(TimeZone.of("UTC+9")),
deletedAt = null,
language = NotificationItem.Language.JAPANESE,
),
NotificationItem(
id = "5",
title = "title 5",
content = "content 5",
type = NotificationItem.Type.FEEDBACK,
publishedAt = LocalDateTime
.parse("2022-02-10T00:00:00")
.toInstant(TimeZone.of("UTC+9")),
deletedAt = null,
language = NotificationItem.Language.JAPANESE,
),
NotificationItem(
id = "6",
title = "title 6",
content = "content 6",
type = NotificationItem.Type.FEEDBACK,
publishedAt = LocalDateTime
.parse("2022-01-30T00:00:00")
.toInstant(TimeZone.of("UTC+9")),
deletedAt = LocalDateTime
.parse("2022-02-28T00:00:00")
.toInstant(TimeZone.of("UTC+9")),
language = NotificationItem.Language.JAPANESE,
),
)
)
| 3 | Kotlin | 3 | 18 | 8d58e41b4bf4fbc0559fc32921a856f71f6b049e | 2,973 | droidkaigi-feed-reader-app | Apache License 2.0 |
examples/src/main/kotlin/com/decentstudio/adapters/ExamplesAdapter.kt | DecentPit | 170,007,879 | false | null | package com.decentstudio.adapters
import android.view.ViewGroup
import com.decentstudio.BR
import com.decentstudio.R
import com.decentstudio.core.adapters.BaseAdapter
import com.decentstudio.core.adapters.BaseHolder
import com.decentstudio.core.adapters.BaseItemCallBack
import com.decentstudio.models.Example
class ExamplesAdapter : BaseAdapter<Example>(create()) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = BaseHolder<Example>(parent, R.layout.item_example, BR.example)
companion object : BaseItemCallBack<Example>
} | 0 | Kotlin | 0 | 0 | 2109fde8349646fd763f258d75a30ad27b26f296 | 549 | Android-Examples | Apache License 2.0 |
ospf-kotlin-framework/src/main/fuookami/ospf/kotlin/framework/log/LogContext.kt | fuookami | 359,831,793 | false | {"Kotlin": 1433872, "Vue": 46326, "Rust": 23739, "Python": 6611, "JavaScript": 5100, "HTML": 1369, "CSS": 1302} | package fuookami.ospf.kotlin.framework.log
import java.util.*
import kotlin.time.*
import kotlin.time.Duration.Companion.days
import kotlinx.coroutines.*
import kotlinx.serialization.*
import org.http4k.core.*
import org.apache.logging.log4j.kotlin.*
import fuookami.ospf.kotlin.utils.context.*
import fuookami.ospf.kotlin.framework.persistence.*
interface Pushing {
operator fun <T> invoke(serializer: KSerializer<T>, value: T): Response
}
data class LogContextBuilder(
var app: String = "",
var version: String = "",
var requestId: String = "",
var pushing: Pushing? = null
) {
operator fun invoke(): LogContext {
return LogContext(
app = app,
version = version,
requestId = requestId,
pushing = pushing
)
}
}
class LogContext private constructor(
val app: String,
val version: String,
val serviceId: String,
val pushing: Pushing? = null
): Cloneable {
private val logger = logger()
companion object {
operator fun invoke(app: String = "", version: String, requestId: String, pushing: Pushing? = null): LogContext {
val uuid = UUID.nameUUIDFromBytes("${app}${version}${requestId}".toByteArray(charset("UTF-8")))
return LogContext(
app = app,
version = version,
serviceId = uuid.toString(),
pushing = pushing
)
}
fun Build(builder: LogContextBuilder.() -> Unit): LogContext {
val context = LogContextBuilder()
builder(context)
return context()
}
}
@OptIn(DelicateCoroutinesApi::class)
fun <T: RequestDTO<T>> pushRequest(
step: String,
requester: String,
serializer: KSerializer<T>,
request: T,
availableTime: Duration = 90.days
) {
if (pushing != null) {
val pushing = this.pushing
GlobalScope.launch(Dispatchers.IO) {
val record = RequestLogRecordPO(
app = app,
version = version,
serviceId = serviceId,
step = step,
request = RequestRecordPO(
requester = requester,
version = version,
request = request
),
availableTime = availableTime
)
val ret = pushing(
serializer = RequestLogRecordPO.serializer(serializer),
value = record
)
if (ret.status.successful) {
logger.info { "pushing log success" }
} else {
logger.info { "pushing log failed" }
}
}
}
}
@OptIn(DelicateCoroutinesApi::class)
fun <T: ResponseDTO<T>> pushResponse(
step: String,
serializer: KSerializer<T>,
response: T,
availableTime: Duration = 90.days
) {
if (pushing != null) {
val pushing = this.pushing
GlobalScope.launch(Dispatchers.IO) {
val record = ResponseLogRecordPO(
app = app,
version = version,
serviceId = serviceId,
step = step,
response = ResponseRecordPO(
version = version,
response = response
),
availableTime = availableTime
)
val ret = pushing(
serializer = ResponseLogRecordPO.serializer(serializer),
value = record
)
if (ret.status.successful) {
logger.info { "pushing log success" }
} else {
logger.info { "pushing log failed" }
}
}
}
}
@OptIn(DelicateCoroutinesApi::class)
fun <T> push(
step: String,
serializer: KSerializer<T>,
value: T,
availableTime: Duration = 90.days
) {
if (pushing != null) {
val pushing = this.pushing
GlobalScope.launch(Dispatchers.IO) {
val record = NormalLogRecordPO(
app = app,
version = version,
serviceId = serviceId,
step = step,
value = value,
availableTime = availableTime
)
val ret = pushing(
serializer = NormalLogRecordPO.serializer(serializer),
value = record
)
if (ret.status.successful) {
logger.info { "pushing log success" }
} else {
logger.info { "pushing log failed" }
}
}
}
}
}
val logContext = ContextVar(LogContext(app = "", version = "", requestId = ""))
| 0 | Kotlin | 0 | 1 | fdeeb1e4bf3bd4ec486beb69840f881123a2a628 | 5,098 | ospf-kotlin | Apache License 2.0 |
features/content/people/people-implementation/src/main/java/com/odogwudev/example/people_implementation/PeopleNetworkService.kt | odogwudev | 592,877,753 | false | null | package com.odogwudev.example.people_implementation
import com.odogwudev.example.people.dto.PeopleListResponse
import retrofit2.http.GET
import retrofit2.http.Query
interface PeopleNetworkService {
@GET("person/popular")
suspend fun getPopularPeople(@Query("page") page: Int) : PeopleListResponse
} | 0 | Kotlin | 0 | 4 | 82791abdcf1554d2a2cd498a19cd93952f90e53e | 309 | CinephilesCompanion | MIT License |
features/content/people/people-implementation/src/main/java/com/odogwudev/example/people_implementation/PeopleNetworkService.kt | odogwudev | 592,877,753 | false | null | package com.odogwudev.example.people_implementation
import com.odogwudev.example.people.dto.PeopleListResponse
import retrofit2.http.GET
import retrofit2.http.Query
interface PeopleNetworkService {
@GET("person/popular")
suspend fun getPopularPeople(@Query("page") page: Int) : PeopleListResponse
} | 0 | Kotlin | 0 | 4 | 82791abdcf1554d2a2cd498a19cd93952f90e53e | 309 | CinephilesCompanion | MIT License |
base-android-library/src/main/kotlin/network/xyo/base/Helpers.kt | XYOracleNetwork | 144,196,520 | false | {"Gradle": 3, "XML": 4, "YAML": 7, "INI": 1, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 4, "Java Properties": 2, "Proguard": 1, "Kotlin": 4, "JSON": 1} | package network.xyo.base
import android.os.Debug
import com.jaredrummler.android.device.DeviceName
val currentThreadName : String
get() = Thread.currentThread().name
val deviceName: String
get() = DeviceName.getDeviceName()
val hasDebugger: Boolean
get() = Debug.isDebuggerConnected()
fun classNameFromObject(objectToCheck: Any): String {
val parts = objectToCheck.javaClass.kotlin.simpleName?.split('.') ?: return "Unknown"
return parts[parts.lastIndex]
} | 1 | null | 1 | 1 | 235c3e4d9b9394abf3c13e82ebceafff1d4ccdd4 | 481 | sdk-core-android | Info-ZIP License |
kexp-kotlin-plugin/src/main/kotlin/hu/simplexion/kotlin/kexp/KeOptions.kt | spxbhuhb | 634,056,804 | false | null | /*
* Copyright ยฉ 2022-2023, Simplexion, Hungary and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package hu.simplexion.kotlin.kexp
class KeOptions(
val dumpPoints: List<KeDumpPoint>,
val withTrace: Boolean
)
| 0 | Kotlin | 0 | 0 | 7ca91217fe19a7692adc7bc14ffcb857cbc8809a | 254 | kexp | Apache License 2.0 |
src/main/kotlin/com/mukatalab/jumpy/settings/JumpyTableModel.kt | mukatalab | 502,393,398 | false | null | package com.mukatalab.jumpy.settings
import javax.swing.table.AbstractTableModel
class JumpyTableModel(val uiState: JumpyUiState) : AbstractTableModel() {
private val _columnNames = arrayOf("Name", "Relative Path", "Action ID")
private val _columnClasses = arrayOf(String::class.java, String::class.java, String::class.java)
override fun getRowCount(): Int {
return uiState.testSrcRoots.size
}
override fun getColumnCount(): Int {
return _columnClasses.size
}
override fun getColumnName(column: Int): String {
return _columnNames[column]
}
override fun getValueAt(rowIndex: Int, columnIndex: Int): Any {
val testSrcRoot = uiState.testSrcRoots[rowIndex]
return when (columnIndex) {
0 -> testSrcRoot.name
1 -> testSrcRoot.path
2 -> testSrcRoot.actionId
else -> throw IndexOutOfBoundsException()
}
}
override fun isCellEditable(rowIndex: Int, columnIndex: Int): Boolean {
return columnIndex != 2
}
override fun setValueAt(aValue: Any?, rowIndex: Int, columnIndex: Int) {
when (columnIndex) {
0 -> uiState.setTestSrcRootName(rowIndex, aValue as String)
1 -> uiState.setTestSrcRootPath(rowIndex, aValue as String)
else -> throw IndexOutOfBoundsException()
}
}
}
| 0 | Kotlin | 0 | 0 | 47e26f5850e45252145e2a7f0fab13fd8dcef511 | 1,380 | intellij-plugin-jumPy | Apache License 2.0 |
presentation/src/main/java/com/bikcodeh/mubi/presentation/navigation/Screens.kt | Bikcodeh | 553,763,395 | false | {"Kotlin": 253338} | package com.bikcodeh.mubi.presentation.navigation
/**
* Sealed class to wrap all the possible screens in the app
* @param route: the specific route of the screen
*/
sealed class Screens(val route: String) {
object Splash : Screens("splash_screen")
object Home : Screens("home_screen")
object Login : Screens("login_screen")
object Profile : Screens("profile_screen")
object Search : Screens("search_screen")
object Detail : Screens("detail_screen/{tvShowId}/{category}/{isFavorite}") {
const val NAV_ARG_KEY_ID = "tvShowId"
const val NAV_ARG_KEY_CATEGORY = "category"
const val NAV_ARG_KEY_FAVORITE = "isFavorite"
fun passTvShowId(tvShowId: String, category: String, isFavorite: Boolean): String {
return "detail_screen/$tvShowId/$category/$isFavorite"
}
}
object Season: Screens("season_screen/{tvShowId}/{seasonNumber}") {
const val NAV_ARG_KEY_ID = "tvShowId"
const val NAV_ARG_SEASON_KEY_ID = "seasonNumber"
fun passArgs(tvShowId: String, seasonNumber: Int): String {
return "season_screen/$tvShowId/$seasonNumber"
}
}
} | 0 | Kotlin | 0 | 1 | 25929e402744a1070357ff1af9b05eb7d8bd345c | 1,161 | Mubi | MIT License |
app/src/main/java/org/stepik/android/exams/util/TimeUtil.kt | StepicOrg | 139,451,308 | false | {"Gradle": 5, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Git Attributes": 1, "Proguard": 2, "XML": 107, "Kotlin": 265, "Prolog": 1, "Java": 29, "CSS": 1} | package org.stepik.android.exams.util
import android.content.Context
import org.stepik.android.exams.App
import org.stepik.android.exams.R
object TimeUtil {
private const val SECOND = 1
private const val MINUTE = SECOND * 60
fun getTimeToCompleteFormatted(seconds: Long, context: Context = App.getAppContext()): String {
val time = (seconds / MINUTE).toInt()
return context.resources.getQuantityString(R.plurals.minutes, time, time)
}
}
| 1 | null | 1 | 1 | f2ed2cff758f5531f84e39ab939a8f7ee4146a41 | 473 | stepik-android-exams | Apache License 2.0 |
app/src/androidTest/java/com/adriandeleon/friends/timeline/TimelineRobot.kt | adriandleon | 377,688,121 | false | null | package com.adriandeleon.friends.timeline
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.junit4.AndroidComposeTestRule
import androidx.compose.ui.test.onNodeWithText
import androidx.test.ext.junit.rules.ActivityScenarioRule
import com.adriandeleon.friends.MainActivity
import com.adriandeleon.friends.R
import com.adriandeleon.friends.signup.launchSignUpScreen
typealias MainActivityRule = AndroidComposeTestRule<ActivityScenarioRule<MainActivity>, MainActivity>
fun launchTimelineFor(
email: String,
password: String,
testRule: MainActivityRule,
block: TimelineRobot.() -> Unit
): TimelineRobot {
launchSignUpScreen(testRule) {
typeEmail(email)
typePassword(password)
submit()
}
return TimelineRobot(testRule).apply(block)
}
class TimelineRobot(
private val testRule: MainActivityRule
) {
infix fun verify(block: TimelineVerificationRobot.() -> Unit): TimelineVerificationRobot {
return TimelineVerificationRobot(testRule).apply(block)
}
}
class TimelineVerificationRobot(private val rule: MainActivityRule) {
fun emptyTimelineMessageIsDisplayed() {
val emptyTimelineMessage = rule.activity.getString(R.string.emptyTimelineMessage)
rule.onNodeWithText(emptyTimelineMessage)
.assertIsDisplayed()
}
}
| 0 | Kotlin | 0 | 0 | 6a5aeb6781e5f142dc86911b6a69643255cfc124 | 1,349 | friends | Apache License 2.0 |
app/src/main/kotlin/dev/patrickgold/florisboard/ime/text/smartbar/Smartbar.kt | florisboard | 254,202,848 | false | null | /*
* Copyright (C) 2021 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.patrickgold.florisboard.ime.smartbar
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.EnterTransition
import androidx.compose.animation.ExitTransition
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.animation.core.updateTransition
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.absoluteOffset
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.isUnspecified
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import dev.patrickgold.florisboard.R
import dev.patrickgold.florisboard.app.florisPreferenceModel
import dev.patrickgold.florisboard.ime.keyboard.FlorisImeSizing
import dev.patrickgold.florisboard.ime.theme.FlorisImeTheme
import dev.patrickgold.florisboard.ime.theme.FlorisImeUi
import dev.patrickgold.florisboard.lib.compose.autoMirrorForRtl
import dev.patrickgold.florisboard.lib.compose.horizontalTween
import dev.patrickgold.florisboard.lib.compose.verticalTween
import dev.patrickgold.florisboard.lib.snygg.ui.snyggBackground
import dev.patrickgold.florisboard.lib.snygg.ui.snyggBorder
import dev.patrickgold.florisboard.lib.snygg.ui.snyggShadow
import dev.patrickgold.florisboard.lib.snygg.ui.solidColor
import dev.patrickgold.jetpref.datastore.model.observeAsState
private const val AnimationDuration = 200
private val VerticalEnterTransition = EnterTransition.verticalTween(AnimationDuration)
private val VerticalExitTransition = ExitTransition.verticalTween(AnimationDuration)
private val HorizontalEnterTransition = EnterTransition.horizontalTween(AnimationDuration)
private val HorizontalExitTransition = ExitTransition.horizontalTween(AnimationDuration)
private val NoEnterTransition = EnterTransition.horizontalTween(0)
private val NoExitTransition = ExitTransition.horizontalTween(0)
private val AnimationTween = tween<Float>(AnimationDuration)
private val NoAnimationTween = tween<Float>(0)
@Composable
fun Smartbar() {
val prefs by florisPreferenceModel()
val smartbarEnabled by prefs.smartbar.enabled.observeAsState()
val secondaryRowPlacement by prefs.smartbar.secondaryActionsPlacement.observeAsState()
AnimatedVisibility(
visible = smartbarEnabled,
enter = VerticalEnterTransition,
exit = VerticalExitTransition,
) {
when (secondaryRowPlacement) {
SecondaryRowPlacement.ABOVE_PRIMARY -> {
Column {
SmartbarSecondaryRow()
SmartbarMainRow()
}
}
SecondaryRowPlacement.BELOW_PRIMARY -> {
Column {
SmartbarMainRow()
SmartbarSecondaryRow()
}
}
SecondaryRowPlacement.OVERLAY_APP_UI -> {
Box(
modifier = Modifier
.fillMaxWidth()
.height(FlorisImeSizing.smartbarHeight),
) {
Box(
modifier = Modifier
.fillMaxWidth()
.height(FlorisImeSizing.smartbarHeight * 2)
.absoluteOffset(y = -FlorisImeSizing.smartbarHeight),
contentAlignment = Alignment.BottomStart,
) {
SmartbarSecondaryRow()
}
SmartbarMainRow()
}
}
}
}
}
@Composable
private fun SmartbarMainRow(modifier: Modifier = Modifier) {
val prefs by florisPreferenceModel()
val flipToggles by prefs.smartbar.flipToggles.observeAsState()
val primaryActionsExpanded by prefs.smartbar.primaryActionsExpanded.observeAsState()
val secondaryActionsEnabled by prefs.smartbar.secondaryActionsEnabled.observeAsState()
val secondaryActionsExpanded by prefs.smartbar.secondaryActionsExpanded.observeAsState()
val shouldAnimate by prefs.smartbar.primaryActionsExpandWithAnimation.observeAsState()
val primaryRowStyle = FlorisImeTheme.style.get(FlorisImeUi.SmartbarPrimaryRow)
val primaryActionsToggleStyle = FlorisImeTheme.style.get(FlorisImeUi.SmartbarPrimaryActionsToggle)
val secondaryActionsToggleStyle = FlorisImeTheme.style.get(FlorisImeUi.SmartbarSecondaryActionsToggle)
@Composable
fun PrimaryActionsToggle() {
IconButton(
onClick = { prefs.smartbar.primaryActionsExpanded.set(!primaryActionsExpanded) },
) {
Box(
modifier = Modifier
.padding(4.dp)
.fillMaxHeight()
.aspectRatio(1f)
.snyggShadow(primaryActionsToggleStyle)
.snyggBorder(primaryActionsToggleStyle)
.snyggBackground(primaryActionsToggleStyle),
contentAlignment = Alignment.Center,
) {
val rotation by animateFloatAsState(
animationSpec = if (shouldAnimate) AnimationTween else NoAnimationTween,
targetValue = if (primaryActionsExpanded) 180f else 0f,
)
Icon(
modifier = Modifier
.autoMirrorForRtl()
.rotate(rotation),
painter = painterResource(
if (flipToggles) {
R.drawable.ic_keyboard_arrow_left
} else {
R.drawable.ic_keyboard_arrow_right
}
),
contentDescription = null,
tint = primaryActionsToggleStyle.foreground.solidColor(),
)
}
}
}
@Composable
fun RowScope.CenterContent() {
val primaryActionsRowType by prefs.smartbar.primaryActionsRowType.observeAsState()
Box(
modifier = Modifier
.weight(1f)
.height(FlorisImeSizing.smartbarHeight),
) {
val enterTransition = if (shouldAnimate) HorizontalEnterTransition else NoEnterTransition
val exitTransition = if (shouldAnimate) HorizontalExitTransition else NoExitTransition
androidx.compose.animation.AnimatedVisibility(
visible = !primaryActionsExpanded,
enter = enterTransition,
exit = exitTransition,
) {
CandidatesRow()
}
androidx.compose.animation.AnimatedVisibility(
visible = primaryActionsExpanded,
enter = enterTransition,
exit = exitTransition,
) {
SmartbarActionRowContent(rowType = primaryActionsRowType)
}
}
}
@Composable
fun SecondaryActionsToggle() {
IconButton(
onClick = { prefs.smartbar.secondaryActionsExpanded.set(!secondaryActionsExpanded) },
enabled = secondaryActionsEnabled,
) {
Box(
modifier = Modifier
.padding(4.dp)
.fillMaxHeight()
.aspectRatio(1f)
.snyggShadow(secondaryActionsToggleStyle)
.snyggBorder(secondaryActionsToggleStyle)
.snyggBackground(secondaryActionsToggleStyle),
contentAlignment = Alignment.Center,
) {
AnimatedVisibility(
visible = secondaryActionsEnabled,
enter = VerticalEnterTransition,
exit = VerticalExitTransition,
) {
val transition = updateTransition(secondaryActionsExpanded, label = "smartbarSecondaryRowToggleBtn")
val alpha by transition.animateFloat(label = "alpha") { if (it) 1f else 0f }
val rotation by transition.animateFloat(label = "rotation") { if (it) 180f else 0f }
// Expanded icon
Icon(
modifier = Modifier
.alpha(alpha)
.rotate(rotation),
painter = painterResource(R.drawable.ic_unfold_less),
contentDescription = null,
tint = secondaryActionsToggleStyle.foreground.solidColor(),
)
// Not expanded icon
Icon(
modifier = Modifier
.alpha(1f - alpha)
.rotate(rotation - 180f),
painter = painterResource(R.drawable.ic_unfold_more),
contentDescription = null,
tint = secondaryActionsToggleStyle.foreground.solidColor(),
)
}
}
}
}
SideEffect {
if (!shouldAnimate) {
prefs.smartbar.primaryActionsExpandWithAnimation.set(true)
}
}
Row(
modifier = modifier
.fillMaxWidth()
.height(FlorisImeSizing.smartbarHeight)
.snyggBackground(primaryRowStyle),
) {
if (flipToggles) {
SecondaryActionsToggle()
CenterContent()
PrimaryActionsToggle()
} else {
PrimaryActionsToggle()
CenterContent()
SecondaryActionsToggle()
}
}
}
@Composable
private fun SmartbarActionRowContent(
rowType: SmartbarRowType,
modifier: Modifier = Modifier,
) {
when (rowType) {
SmartbarRowType.QUICK_ACTIONS -> {
QuickActionsRow(
modifier = modifier
.fillMaxWidth()
.height(FlorisImeSizing.smartbarHeight),
)
}
SmartbarRowType.CLIPBOARD_CURSOR_TOOLS -> {
SmartbarClipboardCursorRow(
modifier = modifier
.fillMaxWidth()
.height(FlorisImeSizing.smartbarHeight),
)
}
}
}
@Composable
private fun SmartbarSecondaryRow(modifier: Modifier = Modifier) {
val prefs by florisPreferenceModel()
val secondaryRowStyle = FlorisImeTheme.style.get(FlorisImeUi.SmartbarSecondaryRow)
val secondaryActionsEnabled by prefs.smartbar.secondaryActionsEnabled.observeAsState()
val secondaryActionsExpanded by prefs.smartbar.secondaryActionsExpanded.observeAsState()
val secondaryActionsRowType by prefs.smartbar.secondaryActionsRowType.observeAsState()
val secondaryActionsPlacement by prefs.smartbar.secondaryActionsPlacement.observeAsState()
val background = secondaryRowStyle.background.solidColor().let { color ->
if (secondaryActionsPlacement == SecondaryRowPlacement.OVERLAY_APP_UI) {
if (color.isUnspecified || color.alpha == 0f) {
FlorisImeTheme.style.get(FlorisImeUi.Keyboard).background.solidColor(default = Color.Black)
} else {
color
}
} else {
color
}
}
AnimatedVisibility(
visible = secondaryActionsEnabled && secondaryActionsExpanded,
enter = VerticalEnterTransition,
exit = VerticalExitTransition,
) {
SmartbarActionRowContent(
modifier = modifier.background(background),
rowType = secondaryActionsRowType,
)
}
}
| 370 | null | 199 | 2,608 | 527543331a16416d0d617a1df1bbf1548efcb782 | 13,062 | florisboard | Apache License 2.0 |
src/main/kotlin/org/wfanet/measurement/reporting/service/api/v2alpha/MetricCalculationSpecsService.kt | world-federation-of-advertisers | 349,561,061 | false | {"Kotlin": 10133199, "Starlark": 948914, "C++": 627937, "CUE": 193204, "HCL": 162357, "TypeScript": 101485, "Python": 77652, "Shell": 20877, "CSS": 9620, "Go": 8063, "JavaScript": 5305, "HTML": 2489} | /*
* Copyright 2023 The Cross-Media Measurement Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wfanet.measurement.reporting.service.api.v2alpha
import com.google.type.DayOfWeek
import io.grpc.Status
import io.grpc.StatusException
import kotlin.random.Random
import org.projectnessie.cel.Env
import org.wfanet.measurement.api.v2alpha.MeasurementConsumerKey
import org.wfanet.measurement.common.base64UrlDecode
import org.wfanet.measurement.common.base64UrlEncode
import org.wfanet.measurement.common.grpc.failGrpc
import org.wfanet.measurement.common.grpc.grpcRequire
import org.wfanet.measurement.common.grpc.grpcRequireNotNull
import org.wfanet.measurement.config.reporting.MetricSpecConfig
import org.wfanet.measurement.internal.reporting.v2.ListMetricCalculationSpecsRequest as InternalListMetricCalculationSpecsRequest
import org.wfanet.measurement.internal.reporting.v2.ListMetricCalculationSpecsResponse as InternalListMetricCalculationSpecsResponse
import org.wfanet.measurement.internal.reporting.v2.MetricCalculationSpec as InternalMetricCalculationSpec
import org.wfanet.measurement.internal.reporting.v2.MetricCalculationSpecKt as InternalMetricCalculationSpecKt
import org.wfanet.measurement.internal.reporting.v2.MetricCalculationSpecsGrpcKt.MetricCalculationSpecsCoroutineStub
import org.wfanet.measurement.internal.reporting.v2.MetricSpec as InternalMetricSpec
import org.wfanet.measurement.internal.reporting.v2.createMetricCalculationSpecRequest
import org.wfanet.measurement.internal.reporting.v2.getMetricCalculationSpecRequest
import org.wfanet.measurement.internal.reporting.v2.listMetricCalculationSpecsRequest
import org.wfanet.measurement.internal.reporting.v2.metricCalculationSpec as internalMetricCalculationSpec
import org.wfanet.measurement.reporting.v2alpha.CreateMetricCalculationSpecRequest
import org.wfanet.measurement.reporting.v2alpha.GetMetricCalculationSpecRequest
import org.wfanet.measurement.reporting.v2alpha.ListMetricCalculationSpecsPageToken
import org.wfanet.measurement.reporting.v2alpha.ListMetricCalculationSpecsPageTokenKt
import org.wfanet.measurement.reporting.v2alpha.ListMetricCalculationSpecsRequest
import org.wfanet.measurement.reporting.v2alpha.ListMetricCalculationSpecsResponse
import org.wfanet.measurement.reporting.v2alpha.MetricCalculationSpec
import org.wfanet.measurement.reporting.v2alpha.MetricCalculationSpecKt
import org.wfanet.measurement.reporting.v2alpha.MetricCalculationSpecsGrpcKt.MetricCalculationSpecsCoroutineImplBase
import org.wfanet.measurement.reporting.v2alpha.copy
import org.wfanet.measurement.reporting.v2alpha.listMetricCalculationSpecsPageToken
import org.wfanet.measurement.reporting.v2alpha.listMetricCalculationSpecsResponse
import org.wfanet.measurement.reporting.v2alpha.metricCalculationSpec
class MetricCalculationSpecsService(
private val internalMetricCalculationSpecsStub: MetricCalculationSpecsCoroutineStub,
private val metricSpecConfig: MetricSpecConfig,
private val secureRandom: Random,
) : MetricCalculationSpecsCoroutineImplBase() {
override suspend fun createMetricCalculationSpec(
request: CreateMetricCalculationSpecRequest
): MetricCalculationSpec {
val parentKey: MeasurementConsumerKey =
grpcRequireNotNull(MeasurementConsumerKey.fromName(request.parent)) {
"Parent is either unspecified or invalid."
}
when (val principal: ReportingPrincipal = principalFromCurrentContext) {
is MeasurementConsumerPrincipal -> {
if (parentKey.measurementConsumerId != principal.resourceKey.measurementConsumerId) {
failGrpc(Status.PERMISSION_DENIED) {
"Cannot create a MetricCalculationSpec for another MeasurementConsumer."
}
}
}
}
grpcRequire(request.metricCalculationSpec.displayName.isNotEmpty()) {
"display_name must be set."
}
grpcRequire(request.metricCalculationSpec.metricSpecsList.isNotEmpty()) {
"No metric_spec is specified."
}
// Expand groupings to predicate groups in Cartesian product
val groupings: List<List<String>> =
request.metricCalculationSpec.groupingsList.map {
grpcRequire(it.predicatesList.isNotEmpty()) {
"The predicates in Grouping must be specified."
}
it.predicatesList
}
val allGroupingPredicates = groupings.flatten()
grpcRequire(allGroupingPredicates.size == allGroupingPredicates.distinct().size) {
"Cannot have duplicate predicates in different groupings."
}
grpcRequire(request.metricCalculationSpecId.matches(RESOURCE_ID_REGEX)) {
"metric_calculation_spec_id is invalid."
}
val internalCreateMetricCalculationSpecRequest = createMetricCalculationSpecRequest {
metricCalculationSpec =
request.metricCalculationSpec.toInternal(parentKey.measurementConsumerId)
externalMetricCalculationSpecId = request.metricCalculationSpecId
}
val internalMetricCalculationSpec =
try {
internalMetricCalculationSpecsStub.createMetricCalculationSpec(
internalCreateMetricCalculationSpecRequest
)
} catch (e: StatusException) {
throw Exception("Unable to create Metric Calculation Spec.", e)
}
return internalMetricCalculationSpec.toPublic()
}
override suspend fun getMetricCalculationSpec(
request: GetMetricCalculationSpecRequest
): MetricCalculationSpec {
val metricCalculationSpecKey =
grpcRequireNotNull(MetricCalculationSpecKey.fromName(request.name)) {
"MetricCalculationSpec name is either unspecified or invalid"
}
when (val principal: ReportingPrincipal = principalFromCurrentContext) {
is MeasurementConsumerPrincipal -> {
if (metricCalculationSpecKey.parentKey != principal.resourceKey) {
failGrpc(Status.PERMISSION_DENIED) {
"Cannot get MetricCalculationSpec belonging to other MeasurementConsumers."
}
}
}
}
val internalMetricCalculationSpec =
try {
internalMetricCalculationSpecsStub.getMetricCalculationSpec(
getMetricCalculationSpecRequest {
cmmsMeasurementConsumerId = metricCalculationSpecKey.cmmsMeasurementConsumerId
externalMetricCalculationSpecId = metricCalculationSpecKey.metricCalculationSpecId
}
)
} catch (e: StatusException) {
throw when (e.status.code) {
Status.Code.DEADLINE_EXCEEDED -> Status.DEADLINE_EXCEEDED
Status.Code.CANCELLED -> Status.CANCELLED
Status.Code.NOT_FOUND -> Status.NOT_FOUND
else -> Status.UNKNOWN
}
.withCause(e)
.withDescription("Unable to get MetricCalculationSpec.")
.asRuntimeException()
}
return internalMetricCalculationSpec.toPublic()
}
override suspend fun listMetricCalculationSpecs(
request: ListMetricCalculationSpecsRequest
): ListMetricCalculationSpecsResponse {
val parentKey: MeasurementConsumerKey =
grpcRequireNotNull(MeasurementConsumerKey.fromName(request.parent)) {
"Parent is either unspecified or invalid."
}
val listMetricCalculationSpecsPageToken = request.toListMetricCalculationSpecsPageToken()
when (val principal: ReportingPrincipal = principalFromCurrentContext) {
is MeasurementConsumerPrincipal -> {
if (parentKey.measurementConsumerId != principal.resourceKey.measurementConsumerId) {
failGrpc(Status.PERMISSION_DENIED) {
"Cannot list MetricCalculationSpecs belonging to other MeasurementConsumers."
}
}
}
}
val internalListMetricCalculationSpecsRequest =
listMetricCalculationSpecsPageToken.toInternalListMetricCalculationSpecsRequest()
val response: InternalListMetricCalculationSpecsResponse =
try {
internalMetricCalculationSpecsStub.listMetricCalculationSpecs(
internalListMetricCalculationSpecsRequest
)
} catch (e: StatusException) {
throw when (e.status.code) {
Status.Code.DEADLINE_EXCEEDED -> Status.DEADLINE_EXCEEDED
Status.Code.CANCELLED -> Status.CANCELLED
else -> Status.UNKNOWN
}
.withCause(e)
.withDescription("Unable to list MetricCalculationSpecs.")
.asRuntimeException()
}
val results = response.metricCalculationSpecsList
if (results.isEmpty()) {
return ListMetricCalculationSpecsResponse.getDefaultInstance()
}
val nextPageToken: ListMetricCalculationSpecsPageToken? =
if (response.limited) {
val lastResult = results.last()
listMetricCalculationSpecsPageToken.copy {
lastMetricCalculationSpec =
ListMetricCalculationSpecsPageTokenKt.previousPageEnd {
cmmsMeasurementConsumerId = lastResult.cmmsMeasurementConsumerId
externalMetricCalculationSpecId = lastResult.externalMetricCalculationSpecId
}
}
} else {
null
}
return listMetricCalculationSpecsResponse {
metricCalculationSpecs +=
filterMetricCalculationSpecs(
results.map { internalMetricCalculationSpec -> internalMetricCalculationSpec.toPublic() },
request.filter,
)
if (nextPageToken != null) {
this.nextPageToken = nextPageToken.toByteString().base64UrlEncode()
}
}
}
/** Converts a public [MetricCalculationSpec] to an internal [InternalMetricCalculationSpec]. */
private fun MetricCalculationSpec.toInternal(
cmmsMeasurementConsumerId: String
): InternalMetricCalculationSpec {
val source = this
if (source.hasTrailingWindow()) {
grpcRequire(source.hasMetricFrequencySpec()) {
"metric_frequency_spec must be set if trailing_window is set"
}
}
val internalMetricSpecs =
source.metricSpecsList.map { metricSpec ->
try {
metricSpec.withDefaults(metricSpecConfig, secureRandom).toInternal()
} catch (e: MetricSpecDefaultsException) {
failGrpc(Status.INVALID_ARGUMENT) {
listOfNotNull("Invalid metric_spec.", e.message, e.cause?.message)
.joinToString(separator = "\n")
}
} catch (e: Exception) {
failGrpc(Status.UNKNOWN) { "Failed to read the metric_spec." }
}
}
return internalMetricCalculationSpec {
this.cmmsMeasurementConsumerId = cmmsMeasurementConsumerId
details =
InternalMetricCalculationSpecKt.details {
displayName = source.displayName
metricSpecs += internalMetricSpecs
filter = source.filter
groupings +=
source.groupingsList.map { grouping ->
InternalMetricCalculationSpecKt.grouping { predicates += grouping.predicatesList }
}
if (source.hasMetricFrequencySpec()) {
metricFrequencySpec = source.metricFrequencySpec.toInternal()
}
if (source.hasTrailingWindow()) {
trailingWindow = source.trailingWindow.toInternal()
}
tags.putAll(source.tagsMap)
}
}
}
private fun filterMetricCalculationSpecs(
metricCalculationSpecs: List<MetricCalculationSpec>,
filter: String,
): List<MetricCalculationSpec> {
return try {
filterList(ENV, metricCalculationSpecs, filter)
} catch (e: IllegalArgumentException) {
throw Status.INVALID_ARGUMENT.withDescription(e.message).asRuntimeException()
}
}
companion object {
private val RESOURCE_ID_REGEX = Regex("^[a-z]([a-z0-9-]{0,61}[a-z0-9])?$")
private const val MIN_PAGE_SIZE = 1
private const val DEFAULT_PAGE_SIZE = 50
private const val MAX_PAGE_SIZE = 1000
private val ENV: Env = buildCelEnvironment(MetricCalculationSpec.getDefaultInstance())
/**
* Converts a public [ListMetricCalculationSpecsRequest] to a
* [ListMetricCalculationSpecsPageToken].
*/
private fun ListMetricCalculationSpecsRequest.toListMetricCalculationSpecsPageToken():
ListMetricCalculationSpecsPageToken {
grpcRequire(pageSize >= 0) { "Page size cannot be less than 0" }
val source = this
val parentKey: MeasurementConsumerKey =
grpcRequireNotNull(MeasurementConsumerKey.fromName(parent)) {
"Parent is either unspecified or invalid."
}
val cmmsMeasurementConsumerId = parentKey.measurementConsumerId
return if (pageToken.isNotBlank()) {
ListMetricCalculationSpecsPageToken.parseFrom(pageToken.base64UrlDecode()).copy {
grpcRequire(this.cmmsMeasurementConsumerId == cmmsMeasurementConsumerId) {
"Arguments must be kept the same when using a page token"
}
if (source.pageSize in MIN_PAGE_SIZE..MAX_PAGE_SIZE) {
pageSize = source.pageSize
}
}
} else {
listMetricCalculationSpecsPageToken {
pageSize =
when {
source.pageSize < MIN_PAGE_SIZE -> DEFAULT_PAGE_SIZE
source.pageSize > MAX_PAGE_SIZE -> MAX_PAGE_SIZE
else -> source.pageSize
}
this.cmmsMeasurementConsumerId = cmmsMeasurementConsumerId
}
}
}
/**
* Converts a [ListMetricCalculationSpecsPageToken] to an internal
* [InternalListMetricCalculationSpecsRequest].
*/
private fun ListMetricCalculationSpecsPageToken.toInternalListMetricCalculationSpecsRequest():
InternalListMetricCalculationSpecsRequest {
val source = this
return listMetricCalculationSpecsRequest {
limit = pageSize
cmmsMeasurementConsumerId = source.cmmsMeasurementConsumerId
if (source.hasLastMetricCalculationSpec()) {
externalMetricCalculationSpecIdAfter =
source.lastMetricCalculationSpec.externalMetricCalculationSpecId
}
}
}
/**
* Converts a public [MetricCalculationSpec.MetricFrequencySpec] to an internal
* [InternalMetricCalculationSpec.MetricFrequencySpec].
*/
private fun MetricCalculationSpec.MetricFrequencySpec.toInternal():
InternalMetricCalculationSpec.MetricFrequencySpec {
val source = this
@Suppress("WHEN_ENUM_CAN_BE_NULL_IN_JAVA") // Proto enum fields are never null.
return InternalMetricCalculationSpecKt.metricFrequencySpec {
when (source.frequencyCase) {
MetricCalculationSpec.MetricFrequencySpec.FrequencyCase.DAILY -> {
daily = InternalMetricCalculationSpec.MetricFrequencySpec.Daily.getDefaultInstance()
}
MetricCalculationSpec.MetricFrequencySpec.FrequencyCase.WEEKLY -> {
grpcRequire(
source.weekly.dayOfWeek != DayOfWeek.DAY_OF_WEEK_UNSPECIFIED &&
source.weekly.dayOfWeek != DayOfWeek.UNRECOGNIZED
) {
"day_of_week in weekly frequency is unspecified or invalid."
}
weekly =
InternalMetricCalculationSpecKt.MetricFrequencySpecKt.weekly {
dayOfWeek = source.weekly.dayOfWeek
}
}
MetricCalculationSpec.MetricFrequencySpec.FrequencyCase.MONTHLY -> {
grpcRequire(source.monthly.dayOfMonth > 0) {
"day_of_month in monthly frequency is unspecified or invalid."
}
monthly =
InternalMetricCalculationSpecKt.MetricFrequencySpecKt.monthly {
dayOfMonth = source.monthly.dayOfMonth
}
}
MetricCalculationSpec.MetricFrequencySpec.FrequencyCase.FREQUENCY_NOT_SET -> {}
}
}
}
/**
* Converts a public [MetricCalculationSpec.TrailingWindow] to an internal
* [InternalMetricCalculationSpec.TrailingWindow].
*/
private fun MetricCalculationSpec.TrailingWindow.toInternal():
InternalMetricCalculationSpec.TrailingWindow {
val source = this
grpcRequire(source.count >= 1) { "count in trailing_window must be greater than 0." }
@Suppress("WHEN_ENUM_CAN_BE_NULL_IN_JAVA") // Proto enum fields are never null.
return InternalMetricCalculationSpecKt.trailingWindow {
count = source.count
increment =
when (source.increment) {
MetricCalculationSpec.TrailingWindow.Increment.DAY ->
InternalMetricCalculationSpec.TrailingWindow.Increment.DAY
MetricCalculationSpec.TrailingWindow.Increment.WEEK ->
InternalMetricCalculationSpec.TrailingWindow.Increment.WEEK
MetricCalculationSpec.TrailingWindow.Increment.MONTH ->
InternalMetricCalculationSpec.TrailingWindow.Increment.MONTH
MetricCalculationSpec.TrailingWindow.Increment.UNRECOGNIZED,
MetricCalculationSpec.TrailingWindow.Increment.INCREMENT_UNSPECIFIED ->
throw Status.INVALID_ARGUMENT.withDescription(
"increment in trailing_window is not specified."
)
.asRuntimeException()
}
}
}
/** Converts an internal [InternalMetricCalculationSpec] to a public [MetricCalculationSpec]. */
private fun InternalMetricCalculationSpec.toPublic(): MetricCalculationSpec {
val source = this
val metricCalculationSpecKey =
MetricCalculationSpecKey(
source.cmmsMeasurementConsumerId,
source.externalMetricCalculationSpecId,
)
return metricCalculationSpec {
name = metricCalculationSpecKey.toName()
displayName = source.details.displayName
metricSpecs += source.details.metricSpecsList.map(InternalMetricSpec::toMetricSpec)
filter = source.details.filter
groupings +=
source.details.groupingsList.map { grouping ->
MetricCalculationSpecKt.grouping { predicates += grouping.predicatesList }
}
if (source.details.hasMetricFrequencySpec()) {
metricFrequencySpec = source.details.metricFrequencySpec.toPublic()
}
if (source.details.hasTrailingWindow()) {
trailingWindow = source.details.trailingWindow.toPublic()
}
tags.putAll(source.details.tagsMap)
}
}
/**
* Converts an internal [InternalMetricCalculationSpec.MetricFrequencySpec] to a public
* [MetricCalculationSpec.MetricFrequencySpec].
*/
private fun InternalMetricCalculationSpec.MetricFrequencySpec.toPublic():
MetricCalculationSpec.MetricFrequencySpec {
val source = this
@Suppress("WHEN_ENUM_CAN_BE_NULL_IN_JAVA") // Proto enum fields are never null.
return MetricCalculationSpecKt.metricFrequencySpec {
when (source.frequencyCase) {
InternalMetricCalculationSpec.MetricFrequencySpec.FrequencyCase.DAILY -> {
daily = MetricCalculationSpec.MetricFrequencySpec.Daily.getDefaultInstance()
}
InternalMetricCalculationSpec.MetricFrequencySpec.FrequencyCase.WEEKLY -> {
weekly =
MetricCalculationSpecKt.MetricFrequencySpecKt.weekly {
dayOfWeek = source.weekly.dayOfWeek
}
}
InternalMetricCalculationSpec.MetricFrequencySpec.FrequencyCase.MONTHLY -> {
monthly =
MetricCalculationSpecKt.MetricFrequencySpecKt.monthly {
dayOfMonth = source.monthly.dayOfMonth
}
}
InternalMetricCalculationSpec.MetricFrequencySpec.FrequencyCase.FREQUENCY_NOT_SET -> {}
}
}
}
/**
* Converts an internal [InternalMetricCalculationSpec.TrailingWindow] to a public
* [MetricCalculationSpec.TrailingWindow].
*/
private fun InternalMetricCalculationSpec.TrailingWindow.toPublic():
MetricCalculationSpec.TrailingWindow {
val source = this
@Suppress("WHEN_ENUM_CAN_BE_NULL_IN_JAVA") // Proto enum fields are never null.
return MetricCalculationSpecKt.trailingWindow {
count = source.count
increment =
when (source.increment) {
InternalMetricCalculationSpec.TrailingWindow.Increment.DAY ->
MetricCalculationSpec.TrailingWindow.Increment.DAY
InternalMetricCalculationSpec.TrailingWindow.Increment.WEEK ->
MetricCalculationSpec.TrailingWindow.Increment.WEEK
InternalMetricCalculationSpec.TrailingWindow.Increment.MONTH ->
MetricCalculationSpec.TrailingWindow.Increment.MONTH
InternalMetricCalculationSpec.TrailingWindow.Increment.UNRECOGNIZED,
InternalMetricCalculationSpec.TrailingWindow.Increment.INCREMENT_UNSPECIFIED ->
throw Status.FAILED_PRECONDITION.withDescription(
"MetricCalculationSpec trailing_window missing increment"
)
.asRuntimeException()
}
}
}
}
}
| 150 | Kotlin | 11 | 36 | b5c84f8051cd189e55f8c43ee2b9cc3f3a75e353 | 21,431 | cross-media-measurement | Apache License 2.0 |
src/main/kotlin/org/adligo/kt/jse/core/build/MathDeps.kt | adligo | 466,558,382 | false | null | package org.adligo.kt.jse.core.build
import org.gradle.api.Project
import org.gradle.kotlin.dsl.DependencyHandlerScope
/**
* This provides the dependencies for Mockito see methods
*
* @author scott
* <pre><code>
* ---------------- Apache ICENSE-2.0 --------------------------
*
* Copyright 2023 Adligo Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* </code><pre>
*/
object MathDeps {
/**
* provides a way for other projects to depend on i_ctx
*/
fun dependsOnMath(gradleCallback : I_GradleCallback) {
has(gradleCallback)
gradleCallback.implementation(gradleCallback.projectFun("math.adligo.org"))
}
fun has(gradleCallback : I_GradleCallback) {
I_MathDeps.dependsOnI_Math(gradleCallback)
}
fun testsHave(gradleCallback : I_GradleCallback) {
dependsOnMath(gradleCallback)
Tests4j4jjDeps.dependsOnTests4j4jj(gradleCallback)
}
}
| 0 | Kotlin | 0 | 0 | 47c1774746d25bf856f21f8cbbe8ad68ce00fdc9 | 1,399 | buildSrc.jse.core.kt.adligo.org | Apache License 2.0 |
app/src/main/java/sk/stuba/fei/uim/mobv_project/ui/contacts/ContactsFragment.kt | kirschovapetra | 426,998,955 | false | {"Kotlin": 127532} | package sk.stuba.fei.uim.mobv_project.ui.contacts
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import sk.stuba.fei.uim.mobv_project.R
import sk.stuba.fei.uim.mobv_project.data.entities.Contact
import sk.stuba.fei.uim.mobv_project.data.repositories.ContactRepository
import sk.stuba.fei.uim.mobv_project.data.utils.ViewModelFactory
import sk.stuba.fei.uim.mobv_project.data.view_models.contacts.ContactsViewModel
import sk.stuba.fei.uim.mobv_project.databinding.FragmentContactsBinding
import sk.stuba.fei.uim.mobv_project.ui.contacts.ContactsFragmentDirections.actionContactsFragmentToNewContactFragment
class ContactsFragment : Fragment(), ContactsRecycleViewAdapter.OnContactClickListener {
private val contactsViewModel: ContactsViewModel by viewModels {
ViewModelFactory(
ContactRepository.getInstance(context!!)
)
}
private lateinit var binding: FragmentContactsBinding
private lateinit var adapter: ContactsRecycleViewAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContactObserver()
adapter = ContactsRecycleViewAdapter(listOf(), this)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = DataBindingUtil.inflate(
inflater,
R.layout.fragment_contacts,
container,
false
)
attachListerToNewContactButton(binding)
attachViewModelToBinding(binding)
funInitializeRecycleAdapter(binding)
return binding.root
}
private fun attachViewModelToBinding(binding: FragmentContactsBinding) {
binding.contactsViewModel = contactsViewModel
binding.lifecycleOwner = viewLifecycleOwner
}
private fun funInitializeRecycleAdapter(binding: FragmentContactsBinding) {
val contactsRecyclerView = binding.contactsRecyclerView
contactsRecyclerView.layoutManager = LinearLayoutManager(context)
contactsRecyclerView.adapter = adapter
}
private fun attachListerToNewContactButton(binding: FragmentContactsBinding) {
binding.newContactButton.setOnClickListener {
findNavController().navigate(
actionContactsFragmentToNewContactFragment()
)
}
}
private fun setContactObserver() {
contactsViewModel.allContacts.observe(
this,
{ contacts -> adapter.setData(contacts) }
)
}
override fun onContactClick(contact: Contact) {
findNavController().navigate(
actionContactsFragmentToNewContactFragment().setContact(contact)
)
}
} | 6 | Kotlin | 1 | 0 | 909fd030682efcaf09220119a3537924d236151e | 3,047 | MOBV-project | Apache License 2.0 |
firebase-auth/src/commonMain/kotlin/dev/gitlive/firebase/auth/auth.kt | stevesoltys | 295,612,551 | true | {"Kotlin": 258495} | /*
* Copyright (c) 2020 GitLive Ltd. Use of this source code is governed by the Apache 2.0 license.
*/
@file:Suppress("EXTENSION_SHADOWED_BY_MEMBER")
package dev.gitlive.firebase.auth
import dev.gitlive.firebase.Firebase
import dev.gitlive.firebase.FirebaseApp
import dev.gitlive.firebase.FirebaseException
import kotlinx.coroutines.flow.Flow
expect val Firebase.auth: FirebaseAuth
expect fun Firebase.auth(app: FirebaseApp): FirebaseAuth
expect class FirebaseAuth {
val currentUser: FirebaseUser?
val authStateChanged: Flow<FirebaseUser?>
val idTokenChanged: Flow<FirebaseUser?>
var languageCode: String
suspend fun applyActionCode(code: String)
suspend fun checkActionCode(code: String): ActionCodeResult
suspend fun confirmPasswordReset(code: String, newPassword: String)
suspend fun createUserWithEmailAndPassword(email: String, password: String): AuthResult
suspend fun fetchSignInMethodsForEmail(email: String): SignInMethodQueryResult
suspend fun sendPasswordResetEmail(email: String, actionCodeSettings: ActionCodeSettings? = null)
suspend fun sendSignInLinkToEmail(email: String, actionCodeSettings: ActionCodeSettings)
suspend fun signInWithEmailAndPassword(email: String, password: String): AuthResult
suspend fun signInWithCustomToken(token: String): AuthResult
suspend fun signInAnonymously(): AuthResult
suspend fun signInWithCredential(authCredential: AuthCredential): AuthResult
suspend fun signOut()
suspend fun updateCurrentUser(user: FirebaseUser)
suspend fun verifyPasswordResetCode(code: String): String
}
expect class AuthResult {
val user: FirebaseUser?
}
expect class ActionCodeResult {
val operation: Operation
fun <T, A: ActionCodeDataType<T>> getData(type: A): T?
}
expect class SignInMethodQueryResult {
val signInMethods: List<String>
}
enum class Operation {
PasswordReset,
VerifyEmail,
RecoverEmail,
Error,
SignInWithEmailLink,
VerifyBeforeChangeEmail,
RevertSecondFactorAddition
}
sealed class ActionCodeDataType<T> {
object Email : ActionCodeDataType<String>()
object PreviousEmail : ActionCodeDataType<String>()
object MultiFactor : ActionCodeDataType<MultiFactorInfo>()
}
expect class ActionCodeSettings {
class Builder {
fun setAndroidPackageName(androidPackageName: String, installIfNotAvailable: Boolean, minimumVersion: String?): Builder
fun setDynamicLinkDomain(dynamicLinkDomain: String): Builder
fun setHandleCodeInApp(canHandleCodeInApp: Boolean): Builder
fun setIOSBundleId(iOSBundleId: String): Builder
fun setUrl(url: String): Builder
fun build(): ActionCodeSettings
}
val canHandleCodeInApp: Boolean
val androidInstallApp: Boolean
val androidMinimumVersion: String?
val androidPackageName: String?
val iOSBundle: String?
val url: String
}
expect open class FirebaseAuthException : FirebaseException
expect class FirebaseAuthActionCodeException : FirebaseAuthException
expect class FirebaseAuthEmailException : FirebaseAuthException
expect class FirebaseAuthInvalidCredentialsException : FirebaseAuthException
expect class FirebaseAuthInvalidUserException : FirebaseAuthException
expect class FirebaseAuthMultiFactorException: FirebaseAuthException
expect class FirebaseAuthRecentLoginRequiredException : FirebaseAuthException
expect class FirebaseAuthUserCollisionException : FirebaseAuthException
expect class FirebaseAuthWebException : FirebaseAuthException
| 0 | Kotlin | 0 | 0 | 4cbcf4c8ceb010d24432d08d061cbffb2173a678 | 3,532 | firebase-kotlin-sdk | Apache License 2.0 |
client/android/div-core/src/main/java/com/yandex/div/core/annotations/InternalApi.kt | divkit | 523,491,444 | false | {"Kotlin": 7327303, "Swift": 5164616, "Svelte": 1148832, "TypeScript": 912803, "Dart": 630920, "Python": 536031, "Java": 507940, "JavaScript": 152546, "CSS": 37870, "HTML": 23434, "C++": 20911, "CMake": 18677, "Shell": 8895, "PEG.js": 7210, "Ruby": 3723, "C": 1425, "Objective-C": 38} | package com.yandex.div.core.annotations
@RequiresOptIn(
message = "This API is for internal use only. It shouldn't be used as it may be changed or removed without notice and will cause a compilation error in a future release.",
level = RequiresOptIn.Level.WARNING
)
@Retention(AnnotationRetention.BINARY)
public annotation class InternalApi
| 5 | Kotlin | 128 | 2,240 | dd102394ed7b240ace9eaef9228567f98e54d9cf | 350 | divkit | Apache License 2.0 |
src/main/kotlin/com/kirakishou/photoexchange/database/repository/LocationMapRepository.kt | K1rakishou | 109,591,197 | false | null | package com.kirakishou.photoexchange.database.repository
import com.kirakishou.photoexchange.core.DatabaseTransactionException
import com.kirakishou.photoexchange.core.LocationMap
import com.kirakishou.photoexchange.core.LocationMapId
import com.kirakishou.photoexchange.core.PhotoId
import com.kirakishou.photoexchange.database.dao.LocationMapsDao
import com.kirakishou.photoexchange.database.dao.PhotosDao
import com.kirakishou.photoexchange.database.entity.LocationMapEntity
import com.kirakishou.photoexchange.util.TimeUtils
import kotlinx.coroutines.CoroutineDispatcher
import org.jetbrains.exposed.sql.Database
import org.joda.time.DateTime
import org.slf4j.LoggerFactory
open class LocationMapRepository(
private val locationMapsDao: LocationMapsDao,
private val photosDao: PhotosDao,
database: Database,
dispatcher: CoroutineDispatcher
) : AbstractRepository(database, dispatcher) {
private val logger = LoggerFactory.getLogger(LocationMapRepository::class.java)
open suspend fun save(photoId: PhotoId): Boolean {
return dbQuery(false) {
return@dbQuery locationMapsDao.save(photoId)
}
}
open suspend fun getOldest(count: Int, currentTime: DateTime): List<LocationMap> {
return dbQuery(emptyList()) {
return@dbQuery locationMapsDao.findOldest(count, currentTime)
.map { it.toLocationMap() }
}
}
open suspend fun setMapReady(photoId: PhotoId, locationMapId: LocationMapId) {
dbQuery(null) {
if (!locationMapsDao.updateSetMapStatus(photoId, LocationMapEntity.MapStatus.Ready)) {
throw DatabaseTransactionException(
"Could not update map with id (${locationMapId.id}) of photo (${photoId.id}) with status Ready"
)
}
if (!photosDao.updateSetLocationMapId(photoId, locationMapId)) {
throw DatabaseTransactionException(
"Could not update photo with id (${photoId.id}) with locationMapId (${locationMapId.id})"
)
}
}
}
open suspend fun setMapAnonymous(photoId: PhotoId, locationMapId: LocationMapId) {
dbQuery {
if (!locationMapsDao.updateSetMapStatus(photoId, LocationMapEntity.MapStatus.Anonymous)) {
throw DatabaseTransactionException(
"Could not update map with id (${locationMapId.id}) of photo (${photoId.id}) with status Anonymous"
)
}
if (!photosDao.updateSetLocationMapId(photoId, locationMapId)) {
throw DatabaseTransactionException(
"Could not update photo with id (${photoId.id}) with locationMapId (${locationMapId.id})"
)
}
}
}
open suspend fun setMapFailed(photoId: PhotoId, locationMapId: LocationMapId) {
dbQuery {
if (!locationMapsDao.updateSetMapStatus(photoId, LocationMapEntity.MapStatus.Failed)) {
throw DatabaseTransactionException(
"Could not update map with id (${locationMapId.id}) of photo (${photoId.id}) with status Failed"
)
}
}
}
open suspend fun increaseAttemptsCountAndNextAttemptTime(photoId: PhotoId, repeatTimeDelta: Long) {
dbQuery {
val nextAttemptTime = TimeUtils.getCurrentDateTime().plus(repeatTimeDelta)
if (!locationMapsDao.incrementAttemptsCount(photoId)) {
throw DatabaseTransactionException(
"Could not increase attempts count for photo with id (${photoId.id})"
)
}
if (!locationMapsDao.updateNextAttemptTime(photoId, nextAttemptTime)) {
throw DatabaseTransactionException(
"Could not update next attempt time for photo with id (${photoId.id}) and time (${nextAttemptTime})"
)
}
}
}
} | 0 | Kotlin | 0 | 1 | eb6343fbac212833755d22de6dc9b12b4b022d39 | 3,616 | photoexchange-backend | Do What The F*ck You Want To Public License |
yoonit-facefy/src/main/java/ai/cyberlabs/yoonit/facefy/model/FaceDetected.kt | teo265 | 344,572,313 | true | {"Kotlin": 20683} | /**
* +-+-+-+-+-+-+
* |y|o|o|n|i|t|
* +-+-+-+-+-+-+
*
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Yoonit Face lib for Android applications |
* | <NAME> & <NAME> @ Cyberlabs AI 2020 |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
package ai.cyberlabs.yoonit.facefy.model
import android.graphics.PointF
import android.graphics.Rect
data class FaceDetected(
var leftEyeOpenProbability: Float?,
var rightEyeOpenProbability: Float?,
var smilingProbability: Float?,
var headEulerAngleX: Float,
var headEulerAngleY: Float,
var headEulerAngleZ: Float,
var contours: MutableList<PointF> = mutableListOf(),
var boundingBox: Rect
) | 0 | null | 0 | 0 | 1448a6c23b3c952c02f70358ac1fda3fae144870 | 757 | android-yoonit-facefy | MIT License |
src/commonMain/kotlin/com/codeborne/selenide/logevents/ErrorsCollector.kt | TarCV | 358,762,107 | true | {"Kotlin": 998044, "Java": 322706, "HTML": 46587, "XSLT": 7418} | package com.codeborne.selenide.logevents
import com.codeborne.selenide.AssertionMode
import com.codeborne.selenide.Config
import com.codeborne.selenide.ex.SoftAssertionError
import com.codeborne.selenide.logevents.LogEvent.EventStatus
import com.codeborne.selenide.logevents.SelenideLogger.hasListener
class ErrorsCollector : LogEventListener {
private val errors: MutableList<Throwable?> = ArrayList()
override fun afterEvent(logEvent: LogEvent) {
if (logEvent.status === EventStatus.FAIL) {
errors.add(logEvent.error)
}
}
override fun beforeEvent(logEvent: LogEvent) {
// ignore
}
fun clear() {
errors.clear()
}
fun getErrors(): List<Throwable?> {
return (errors)
}
/**
* 1. Clears all collected errors, and
* 2. throws SoftAssertionError if there were some errors
*
* @param testName any string, usually name of current test
*/
fun failIfErrors(testName: String?) {
val errors: List<Throwable?> = ArrayList(errors)
this.errors.clear()
if (errors.size == 1) {
throw SoftAssertionError(errors[0].toString())
}
if (errors.isNotEmpty()) {
val sb = StringBuilder()
sb.append("Test ").append(testName).append(" failed.").appendLine()
sb.append(errors.size).append(" checks failed").appendLine()
var i = 0
for (error in errors) {
sb.appendLine().append("FAIL #").append(++i).append(": ")
sb.append(error).appendLine()
}
throw SoftAssertionError(sb.toString())
}
}
companion object {
const val LISTENER_SOFT_ASSERT = "softAssert"
fun validateAssertionMode(config: Config) {
if (config.assertionMode() === AssertionMode.SOFT) {
check(hasListener(LISTENER_SOFT_ASSERT)) {
"You must configure you classes using JUnit4/JUnit5/TestNG " +
"mechanism as documented in https://github.com/selenide/selenide/wiki/SoftAssertions"
}
}
}
}
}
| 0 | Kotlin | 0 | 0 | c86103748bdf214adb8a027492d21765059d3629 | 2,168 | selenide.kt-js | MIT License |
restdocs-api-spec-openapi3-generator/src/test/kotlin/com/epages/restdocs/apispec/openapi3/OpenApi3GeneratorTest.kt | lgaida | 235,079,951 | true | {"Kotlin": 362626, "Java": 83093, "Shell": 180} | package com.epages.restdocs.apispec.openapi3
import com.epages.restdocs.apispec.model.FieldDescriptor
import com.epages.restdocs.apispec.model.HTTPMethod
import com.epages.restdocs.apispec.model.HeaderDescriptor
import com.epages.restdocs.apispec.model.Oauth2Configuration
import com.epages.restdocs.apispec.model.ParameterDescriptor
import com.epages.restdocs.apispec.model.RequestModel
import com.epages.restdocs.apispec.model.ResourceModel
import com.epages.restdocs.apispec.model.ResponseModel
import com.epages.restdocs.apispec.model.SecurityRequirements
import com.epages.restdocs.apispec.model.SecurityType
import com.jayway.jsonpath.Configuration
import com.jayway.jsonpath.DocumentContext
import com.jayway.jsonpath.JsonPath
import com.jayway.jsonpath.Option
import io.swagger.parser.OpenAPIParser
import io.swagger.parser.models.ParseOptions
import io.swagger.v3.oas.models.servers.Server
import org.assertj.core.api.BDDAssertions.then
import org.junit.jupiter.api.Test
class OpenApi3GeneratorTest {
lateinit var resources: List<ResourceModel>
lateinit var openApiSpecJsonString: String
lateinit var openApiJsonPathContext: DocumentContext
@Test
fun `should convert single resource model to openapi`() {
givenGetProductResourceModel()
whenOpenApiObjectGenerated()
thenGetProductByIdOperationIsValid("application/json")
thenOAuth2SecuritySchemesPresent()
thenInfoFieldsPresent()
thenTagFieldsPresent()
thenServersPresent()
thenSchemaPresentNamedLike("product")
thenOpenApiSpecIsValid()
}
@Test
fun `should convert single resource model to openapi with xml in response body`() {
givenGetProductResourceModelWithXmlResponse()
whenOpenApiObjectGenerated()
thenGetProductByIdOperationIsValid("application/xml")
thenOAuth2SecuritySchemesPresent()
thenInfoFieldsPresent()
thenTagFieldsPresent()
thenServersPresent()
thenSchemaPresentNamedLike("TestDataHolder")
thenOpenApiSpecIsValid()
}
@Test
fun `should convert resource model with JWT Bearer SecurityRequirements to openapi`() {
givenGetProductResourceModelWithJWTSecurityRequirement()
whenOpenApiObjectGeneratedWithoutOAuth2()
thenJWTSecuritySchemesPresent()
}
@Test
fun `should convert single delete resource model to openapi`() {
givenDeleteProductResourceModel()
whenOpenApiObjectGenerated()
then(openApiJsonPathContext.read<Any>("paths./products/{id}.delete")).isNotNull()
then(openApiJsonPathContext.read<Any>("paths./products/{id}.delete.requestBody")).isNull()
then(openApiJsonPathContext.read<Any>("paths./products/{id}.delete.responses.204")).isNotNull()
then(openApiJsonPathContext.read<Any>("paths./products/{id}.delete.responses.204.content")).isNull()
thenOpenApiSpecIsValid()
}
@Test
fun `should aggregate responses with different content type`() {
givenResourcesWithSamePathAndDifferentContentType()
whenOpenApiObjectGenerated()
val productPatchByIdPath = "paths./products/{id}.patch"
then(openApiJsonPathContext.read<Any>("$productPatchByIdPath.requestBody.content.application/json.schema.\$ref")).isNotNull()
then(openApiJsonPathContext.read<Any>("$productPatchByIdPath.requestBody.content.application/json.examples.test")).isNotNull()
then(openApiJsonPathContext.read<Any>("$productPatchByIdPath.requestBody.content.application/json-patch+json.schema.\$ref")).isNotNull()
then(openApiJsonPathContext.read<Any>("$productPatchByIdPath.requestBody.content.application/json-patch+json.examples.test-1")).isNotNull()
then(openApiJsonPathContext.read<Any>("$productPatchByIdPath.responses.200.content.application/json.schema.\$ref")).isNotNull()
then(openApiJsonPathContext.read<Any>("$productPatchByIdPath.responses.200.content.application/json.examples.test")).isNotNull()
then(openApiJsonPathContext.read<Any>("$productPatchByIdPath.responses.200.content.application/hal+json.schema.\$ref")).isNotNull()
then(openApiJsonPathContext.read<Any>("$productPatchByIdPath.responses.200.content.application/hal+json.examples.test-1")).isNotNull()
thenOpenApiSpecIsValid()
}
@Test
fun `should aggregate example responses with same path and status and content type`() {
givenResourcesWithSamePathAndContentType()
whenOpenApiObjectGenerated()
val productGetByIdPath = "paths./products/{id}.get"
then(openApiJsonPathContext.read<Any>("$productGetByIdPath.responses.200.content.application/json.schema.\$ref")).isNotNull()
then(openApiJsonPathContext.read<Any>("$productGetByIdPath.responses.200.content.application/json.examples.test")).isNotNull()
then(openApiJsonPathContext.read<Any>("$productGetByIdPath.responses.200.content.application/json.examples.test-1")).isNotNull()
thenOpenApiSpecIsValid()
}
@Test
fun `should aggregate responses with same path and content type but different status`() {
givenResourcesWithSamePathAndContentTypeButDifferentStatus()
whenOpenApiObjectGenerated()
val productGetByIdPath = "paths./products/{id}.get"
then(openApiJsonPathContext.read<Any>("$productGetByIdPath.responses.200.content.application/json.schema.\$ref")).isNotNull()
then(openApiJsonPathContext.read<Any>("$productGetByIdPath.responses.200.content.application/json.examples.test")).isNotNull()
then(openApiJsonPathContext.read<Any>("$productGetByIdPath.responses.400.content.application/json.schema.\$ref")).isNotNull()
then(openApiJsonPathContext.read<Any>("$productGetByIdPath.responses.400.content.application/json.examples.test-1")).isNotNull()
thenOpenApiSpecIsValid()
}
@Test
fun `should aggregate equal schemas across operations`() {
givenResourcesWithSamePathAndDifferentMethods()
whenOpenApiObjectGenerated()
val patchResponseSchemaRef = openApiJsonPathContext.read<String>("paths./products/{id}.patch.responses.200.content.application/json.schema.\$ref")
val getResponseSchemaRef = openApiJsonPathContext.read<String>("paths./products/{id}.get.responses.200.content.application/json.schema.\$ref")
then(patchResponseSchemaRef).isEqualTo(getResponseSchemaRef)
val schemaId = getResponseSchemaRef.removePrefix("#/components/schemas/")
then(openApiJsonPathContext.read<Any>("components.schemas.$schemaId.type")).isEqualTo("object")
thenOpenApiSpecIsValid()
}
@Test
fun `should aggregate requests with same path and method but different parameters`() {
givenResourcesWithSamePathAndContentTypeAndDifferentParameters()
whenOpenApiObjectGenerated()
val params = openApiJsonPathContext.read<List<Map<String, String>>>("paths./products/{id}.get.parameters.*")
then(params).anyMatch { it["name"] == "id" }
then(params).anyMatch { it["name"] == "locale" }
then(params).anyMatch { it["name"] == "color" && it["description"] == "Changes the color of the product" }
then(params).anyMatch { it["name"] == "Authorization" }
then(params).hasSize(4) // should not contain duplicated parameter descriptions
thenOpenApiSpecIsValid()
}
fun thenGetProductByIdOperationIsValid(contentType: String) {
val productGetByIdPath = "paths./products/{id}.get"
then(openApiJsonPathContext.read<List<String>>("$productGetByIdPath.tags")).isNotNull()
then(openApiJsonPathContext.read<String>("$productGetByIdPath.operationId")).isNotNull()
then(openApiJsonPathContext.read<String>("$productGetByIdPath.summary")).isNotNull()
then(openApiJsonPathContext.read<String>("$productGetByIdPath.description")).isNotNull()
then(openApiJsonPathContext.read<Any>("$productGetByIdPath.deprecated")).isNull()
then(openApiJsonPathContext.read<List<String>>("$productGetByIdPath.parameters[?(@.name == 'id')].in")).containsOnly("path")
then(openApiJsonPathContext.read<List<Boolean>>("$productGetByIdPath.parameters[?(@.name == 'id')].required")).containsOnly(true)
then(openApiJsonPathContext.read<List<String>>("$productGetByIdPath.parameters[?(@.name == 'locale')].in")).containsOnly("query")
then(openApiJsonPathContext.read<List<Boolean>>("$productGetByIdPath.parameters[?(@.name == 'locale')].required")).containsOnly(false)
then(openApiJsonPathContext.read<List<String>>("$productGetByIdPath.parameters[?(@.name == 'locale')].schema.type")).containsOnly("string")
then(openApiJsonPathContext.read<List<String>>("$productGetByIdPath.parameters[?(@.name == 'Authorization')].in")).containsOnly("header")
then(openApiJsonPathContext.read<List<Boolean>>("$productGetByIdPath.parameters[?(@.name == 'Authorization')].required")).containsOnly(true)
then(openApiJsonPathContext.read<List<String>>("$productGetByIdPath.parameters[?(@.name == 'Authorization')].example")).containsOnly(
"some example")
then(openApiJsonPathContext.read<List<String>>("$productGetByIdPath.parameters[?(@.name == 'Authorization')].schema.type")).containsOnly(
"string")
then(openApiJsonPathContext.read<String>("$productGetByIdPath.requestBody")).isNull()
then(openApiJsonPathContext.read<Any>("$productGetByIdPath.responses.200.description")).isNotNull()
then(openApiJsonPathContext.read<Any>("$productGetByIdPath.responses.200.headers.SIGNATURE.schema.type")).isNotNull()
then(openApiJsonPathContext.read<Any>("$productGetByIdPath.responses.200.content.$contentType.schema.\$ref")).isNotNull()
then(openApiJsonPathContext.read<Any>("$productGetByIdPath.responses.200.content.$contentType.examples.test.value")).isNotNull()
then(openApiJsonPathContext.read<List<List<String>>>("$productGetByIdPath.security[*].oauth2_clientCredentials").flatMap { it }).containsOnly(
"prod:r")
then(openApiJsonPathContext.read<List<List<String>>>("$productGetByIdPath.security[*].oauth2_authorizationCode").flatMap { it }).containsOnly(
"prod:r")
}
private fun thenServersPresent() {
then(openApiJsonPathContext.read<List<String>>("servers[*].url")).contains("https://localhost/api")
}
private fun thenInfoFieldsPresent() {
then(openApiJsonPathContext.read<String>("info.title")).isEqualTo("API")
then(openApiJsonPathContext.read<String>("info.description")).isEqualTo("API Description")
then(openApiJsonPathContext.read<String>("info.version")).isEqualTo("1.0.0")
}
private fun thenTagFieldsPresent() {
then(openApiJsonPathContext.read<String>("tags[0].name")).isEqualTo("tag1")
then(openApiJsonPathContext.read<String>("tags[0].description")).isEqualTo("tag1 description")
then(openApiJsonPathContext.read<String>("tags[1].name")).isEqualTo("tag2")
then(openApiJsonPathContext.read<String>("tags[1].description")).isEqualTo("tag2 description")
}
private fun thenSchemaPresentNamedLike(desiredNamepart: String) {
val schemas = openApiJsonPathContext.read<Map<String, Any>>("components.schemas")
then(schemas).isNotEmpty()
val schemakey = schemas.filterKeys { key -> key.contains(desiredNamepart) }.keys
then(schemakey).hasSize(1)
then(openApiJsonPathContext.read<Map<String, Any>>("components.schemas." + schemakey.first() + ".properties")).hasSize(
2)
}
private fun thenOAuth2SecuritySchemesPresent() {
then(openApiJsonPathContext.read<String>("components.securitySchemes.oauth2.type")).isEqualTo("oauth2")
then(openApiJsonPathContext.read<Map<String, Any>>("components.securitySchemes.oauth2.flows"))
.containsKeys("clientCredentials", "authorizationCode")
then(openApiJsonPathContext.read<Map<String, Any>>("components.securitySchemes.oauth2.flows.clientCredentials.scopes"))
.containsKeys("prod:r")
then(openApiJsonPathContext.read<Map<String, Any>>("components.securitySchemes.oauth2.flows.authorizationCode.scopes"))
.containsKeys("prod:r")
}
private fun thenJWTSecuritySchemesPresent() {
then(openApiJsonPathContext.read<String>("components.securitySchemes.bearerAuthJWT.type")).isEqualTo("http")
then(openApiJsonPathContext.read<String>("components.securitySchemes.bearerAuthJWT.scheme")).isEqualTo("bearer")
then(openApiJsonPathContext.read<String>("components.securitySchemes.bearerAuthJWT.bearerFormat")).isEqualTo("JWT")
}
private fun whenOpenApiObjectGenerated() {
openApiSpecJsonString = OpenApi3Generator.generateAndSerialize(
resources = resources,
servers = listOf(Server().apply { url = "https://localhost/api" }),
oauth2SecuritySchemeDefinition = Oauth2Configuration(
"http://example.com/token",
"http://example.com/authorize",
arrayOf("clientCredentials", "authorizationCode")
),
format = "json",
description = "API Description",
tagDescriptions = mapOf("tag1" to "tag1 description", "tag2" to "tag2 description")
)
println(openApiSpecJsonString)
openApiJsonPathContext = JsonPath.parse(openApiSpecJsonString, Configuration.defaultConfiguration().addOptions(
Option.SUPPRESS_EXCEPTIONS))
}
private fun whenOpenApiObjectGeneratedWithoutOAuth2() {
openApiSpecJsonString = OpenApi3Generator.generateAndSerialize(
resources = resources,
servers = listOf(Server().apply { url = "https://localhost/api" }),
format = "json",
description = "API Description",
tagDescriptions = mapOf("tag1" to "tag1 description", "tag2" to "tag2 description")
)
println(openApiSpecJsonString)
openApiJsonPathContext = JsonPath.parse(openApiSpecJsonString, Configuration.defaultConfiguration().addOptions(
Option.SUPPRESS_EXCEPTIONS))
}
private fun givenResourcesWithSamePathAndContentType() {
resources = listOf(
ResourceModel(
operationId = "test",
summary = "summary",
description = "description",
privateResource = false,
deprecated = false,
tags = setOf("tag1", "tag2"),
request = getProductRequest(),
response = getProductResponse()
),
ResourceModel(
operationId = "test-1",
summary = "summary 1",
description = "description 1",
privateResource = false,
deprecated = false,
tags = setOf("tag1", "tag2"),
request = getProductRequest(),
response = getProductResponse()
)
)
}
private fun givenResourcesWithSamePathAndContentTypeButDifferentStatus() {
resources = listOf(
ResourceModel(
operationId = "test",
summary = "summary",
description = "description",
privateResource = false,
deprecated = false,
tags = setOf("tag1", "tag2"),
request = getProductRequest(),
response = getProductResponse()
),
ResourceModel(
operationId = "test-1",
summary = "summary 1",
description = "description 1",
privateResource = false,
deprecated = false,
tags = setOf("tag1", "tag2"),
request = getProductRequest(),
response = getProductErrorResponse()
)
)
}
private fun givenResourcesWithSamePathAndContentTypeAndDifferentParameters() {
resources = listOf(
ResourceModel(
operationId = "test",
summary = "summary",
description = "description",
privateResource = false,
deprecated = false,
tags = setOf("tag1", "tag2"),
request = getProductRequest(),
response = getProductResponse()
),
ResourceModel(
operationId = "test",
summary = "summary",
description = "description",
privateResource = false,
deprecated = false,
tags = setOf("tag1", "tag2"),
request = getProductRequest(),
response = getProductResponse()
),
ResourceModel(
operationId = "test-1",
summary = "summary 1",
description = "description 1",
privateResource = false,
deprecated = false,
tags = setOf("tag1", "tag2"),
request = getProductRequestWithDifferentParameter("color", "Changes the color of the product"),
response = getProductResponse()
),
ResourceModel(
operationId = "test-1",
summary = "summary 1",
description = "description 1",
privateResource = false,
deprecated = false,
tags = setOf("tag1", "tag2"),
request = getProductRequestWithDifferentParameter("color", "Modifies the color of the product"),
response = getProductResponse()
)
)
}
private fun givenResourcesWithSamePathAndDifferentMethods() {
resources = listOf(
ResourceModel(
operationId = "test",
summary = "summary",
description = "description",
privateResource = false,
deprecated = false,
tags = setOf("tag1", "tag2"),
request = getProductPatchRequest(),
response = getProductResponse()
),
ResourceModel(
operationId = "test-1",
summary = "summary 1",
description = "description 1",
privateResource = false,
deprecated = false,
tags = setOf("tag1", "tag2"),
request = getProductRequest(),
response = getProductResponse()
)
)
}
private fun givenResourcesWithSamePathAndDifferentContentType() {
resources = listOf(
ResourceModel(
operationId = "test",
summary = "summary",
description = "description",
privateResource = false,
deprecated = false,
tags = setOf("tag1", "tag2"),
request = getProductPatchRequest(),
response = getProductResponse()
),
ResourceModel(
operationId = "test-1",
summary = "summary 1",
description = "description 1",
privateResource = false,
deprecated = false,
tags = setOf("tag1", "tag2"),
request = getProductPatchJsonPatchRequest(),
response = getProductHalResponse()
)
)
}
private fun givenDeleteProductResourceModel() {
resources = listOf(
ResourceModel(
operationId = "test",
summary = "summary",
description = "description",
privateResource = false,
deprecated = false,
request = RequestModel(
path = "/products/{id}",
method = HTTPMethod.DELETE,
headers = listOf(),
pathParameters = listOf(),
requestParameters = listOf(),
securityRequirements = null,
requestFields = listOf()
),
response = ResponseModel(
status = 204,
contentType = null,
headers = emptyList(),
responseFields = listOf()
)
)
)
}
private fun givenGetProductResourceModel() {
resources = listOf(
ResourceModel(
operationId = "test",
summary = "summary",
description = "description",
privateResource = false,
deprecated = false,
tags = setOf("tag1", "tag2"),
request = getProductRequest(),
response = getProductResponse()
)
)
}
private fun givenGetProductResourceModelWithXmlResponse() {
resources = listOf(
ResourceModel(
operationId = "test",
summary = "summary",
description = "description",
privateResource = false,
deprecated = false,
tags = setOf("tag1", "tag2"),
request = getProductRequest(),
response = getProductXmlResponse()
)
)
}
private fun givenGetProductResourceModelWithJWTSecurityRequirement() {
resources = listOf(
ResourceModel(
operationId = "test",
summary = "summary",
description = "description",
privateResource = false,
deprecated = false,
tags = setOf("tag1", "tag2"),
request = getProductRequest(::getJWTSecurityRequirement),
response = getProductResponse()
)
)
}
private fun getProductErrorResponse(): ResponseModel {
return ResponseModel(
status = 400,
contentType = "application/json",
headers = listOf(),
responseFields = listOf(
FieldDescriptor(
path = "error",
description = "error message.",
type = "STRING"
)
),
example = """{
"error": "bad stuff!"
}"""
)
}
private fun getProductResponse(): ResponseModel {
return ResponseModel(
status = 200,
contentType = "application/json",
headers = listOf(
HeaderDescriptor(
name = "SIGNATURE",
description = "This is some signature",
type = "STRING",
optional = false
)
),
responseFields = listOf(
FieldDescriptor(
path = "_id",
description = "ID of the product",
type = "STRING"
),
FieldDescriptor(
path = "description",
description = "Product description, localized.",
type = "STRING"
)
),
example = """{
"_id": "123",
"description": "Good stuff!"
}"""
)
}
private fun getProductXmlResponse(): ResponseModel {
return ResponseModel(
status = 200,
contentType = "application/xml",
headers = listOf(
HeaderDescriptor(
name = "SIGNATURE",
description = "This is some signature",
type = "STRING",
optional = false
)
),
responseFields = listOf(
FieldDescriptor(
path = "TestDataHolder/_id",
description = "ID of the product",
type = "STRING"
),
FieldDescriptor(
path = "TestDataHolder/description",
description = "Product description, localized.",
type = "STRING"
)
),
example = """<?xml version="1.0" encoding="UTF-8"?><TestDataHolder><_id>123</_id><description>Good stuff!</description></TestDataHolder>""".trimMargin()
)
}
private fun getProductHalResponse(): ResponseModel {
return ResponseModel(
status = 200,
contentType = "application/hal+json",
responseFields = listOf(
FieldDescriptor(
path = "_id",
description = "ID of the product",
type = "STRING"
),
FieldDescriptor(
path = "description1",
description = "Product description, localized.",
type = "STRING"
)
),
headers = emptyList(),
example = """{
"_id": "123",
"description": "Good stuff!",
"_links": {
"self": "http://localhost/"
}
}"""
)
}
private fun getProductPatchRequest(): RequestModel {
return RequestModel(
path = "/products/{id}",
method = HTTPMethod.PATCH,
headers = listOf(),
pathParameters = listOf(),
requestParameters = listOf(),
securityRequirements = null,
requestFields = listOf(
FieldDescriptor(
path = "description1",
description = "Product description, localized.",
type = "STRING"
)
),
contentType = "application/json",
example = """{
"description": "Good stuff!",
}"""
)
}
private fun getProductPatchJsonPatchRequest(): RequestModel {
return RequestModel(
path = "/products/{id}",
method = HTTPMethod.PATCH,
headers = listOf(),
pathParameters = listOf(),
requestParameters = listOf(),
securityRequirements = null,
requestFields = listOf(
FieldDescriptor(
path = "[].op",
description = "operation",
type = "STRING"
),
FieldDescriptor(
path = "[].path",
description = "path",
type = "STRING"
),
FieldDescriptor(
path = "[].value",
description = "the new value",
type = "STRING"
)
),
contentType = "application/json-patch+json",
example = """
[
{
"op": "add",
"path": "/description",
"value": "updated
}
]
""".trimIndent()
)
}
private fun getProductRequest(getSecurityRequirement: () -> SecurityRequirements = ::getOAuth2SecurityRequirement): RequestModel {
return RequestModel(
path = "/products/{id}",
method = HTTPMethod.GET,
securityRequirements = getSecurityRequirement(),
headers = listOf(
HeaderDescriptor(
name = "Authorization",
description = "Access token",
type = "string",
optional = false,
example = "some example"
)
),
pathParameters = listOf(
ParameterDescriptor(
name = "id",
description = "Product ID",
type = "STRING",
optional = false,
ignored = false
)
),
requestParameters = listOf(
ParameterDescriptor(
name = "locale",
description = "Localizes the product fields to the given locale code",
type = "STRING",
optional = true,
ignored = false
)
),
requestFields = listOf()
)
}
private fun getOAuth2SecurityRequirement() = SecurityRequirements(
type = SecurityType.OAUTH2,
requiredScopes = listOf("prod:r")
)
private fun getJWTSecurityRequirement() = SecurityRequirements(
type = SecurityType.JWT_BEARER
)
private fun getProductRequestWithDifferentParameter(name: String, description: String): RequestModel {
return getProductRequest().copy(requestParameters = listOf(
ParameterDescriptor(
name = name,
description = description,
type = "STRING",
optional = true,
ignored = false
)
))
}
private fun thenOpenApiSpecIsValid() {
val messages = OpenAPIParser().readContents(openApiSpecJsonString, emptyList(), ParseOptions()).messages
then(messages).describedAs("OpenAPI validation messages should be empty").isEmpty()
}
}
| 0 | Kotlin | 0 | 0 | fc31b9275365fa910160901cd393e19e7ac53be3 | 31,126 | restdocs-api-spec | MIT License |
acrarium/src/main/kotlin/com/faendir/acra/persistence/jooq/CustomConverterProvider.kt | F43nd1r | 91,593,043 | false | null | package com.faendir.acra.persistence.jooq
import org.jooq.Converter
import org.jooq.ConverterProvider
import org.jooq.impl.DefaultConverterProvider
import org.springframework.stereotype.Component
@Component
class CustomConverterProvider(convertersIn: List<Converter<*, *>>) : ConverterProvider {
private val converters: Map<Class<*>, Map<Class<*>, Converter<*, *>>> =
(convertersIn + convertersIn.map { it.invert() }).groupBy { it.fromType() }.mapValues { (_, value) -> value.associateBy { it.toType() } }
private val delegate = DefaultConverterProvider()
@Suppress("UNCHECKED_CAST")
override fun <T : Any?, U : Any?> provide(t: Class<T>, u: Class<U>): Converter<T, U>? {
return converters[t]?.get(u) as Converter<T, U>? ?: delegate.provide(t, u)
}
}
fun <T, U> Converter<T, U>.invert(): Converter<U, T> = Converter.of(toType(), fromType(), this::to, this::from)
| 6 | Kotlin | 46 | 169 | f277b0abf211fbd3149becd2b59a138b3d6177cc | 905 | Acrarium | Apache License 2.0 |
app/src/main/java/com/github/miwu/service/QuickActionTileService.kt | sky130 | 680,024,437 | false | {"Kotlin": 186722} | @file:Suppress("FunctionName")
package com.github.miwu.service
import androidx.wear.protolayout.DimensionBuilders.expand
import androidx.wear.protolayout.DimensionBuilders.weight
import androidx.wear.protolayout.DimensionBuilders.wrap
import androidx.wear.protolayout.ModifiersBuilders.Clickable
import androidx.wear.protolayout.material.Typography
import com.github.miwu.miot.manager.MiotQuickManager
import com.github.miwu.miot.quick.MiotBaseQuick
import kndroidx.wear.tile.*
import kndroidx.wear.tile.layout.*
import com.github.miwu.R
import kndroidx.KndroidX
import kndroidx.wear.tile.widget.*
import kndroidx.wear.tile.service.TileServiceX
class QuickActionTileService : TileServiceX() {
val list get() = MiotQuickManager.quickList
override val version = "1"
init {
imageMap.apply {
set("device", R.drawable.ic_miwu_placeholder.toImage())
set("scene", R.drawable.ic_miwu_scene_tile.toImage())
}
}
override fun onClick(id: String) {
try {
val position = id.toInt()
MiotQuickManager.doQuick(position)
} catch (e: Exception) {
e.printStackTrace()
}
}
override fun onEnter() = MiotQuickManager.refresh(must = true)
override fun onLayout() = layout {
Grid(
width = expand(),
height = wrap(),
modifiers = Modifier.padding(horizontal = 25.dp),
rowModifiers = Modifier.padding(vertical = 3.dp),
spanCount = 2
) {
for ((i, quick) in list.withIndex()) {
val resId = when (quick) {
is MiotBaseQuick.DeviceQuick<*> -> "device"
is MiotBaseQuick.SceneQuick -> "scene"
else -> ""
}
QuickCard(
quick = quick, resId = resId, Clickable(i.toString())
)
}
}
}
private fun Any.QuickCard(
quick: MiotBaseQuick, resId: String, clickable: Clickable
) = Box(width = weight(1f), height = wrap(),modifier = Modifier.padding(horizontal = 3.dp)) {
val background = quick.run {
if (this is MiotBaseQuick.DeviceQuick<*> && value is Boolean && value != null && (value as Boolean)) {
ShapeBackground(0xee57D1B8.color, 15.dp)
} else {
ShapeBackground(0xFF202020.color, 15.dp)
}
}
Box(
width = expand(),
height = wrap(),
modifier = Modifier.background(background)
.clickable(clickable)
) {
Column(
width = weight(1f),
height = wrap(),
modifier = Modifier.padding(vertical = 10.dp, horizontal = 10.dp)
) {
Image(width = 25.dp, height = 25.dp, resId = resId)
Spacer(width = 0.dp, height = 5.dp)
Text(
text = quick.name,
textColors = 0xFFFFFFFF.color,
typography = Typography.TYPOGRAPHY_BUTTON
)
}
}
}
companion object {
fun update() {
getUpdater(KndroidX.context).requestUpdate(QuickActionTileService::class.java)
}
}
}
| 0 | Kotlin | 13 | 36 | dc18b49dc7f27798335834e1d127bc5c79199d25 | 3,311 | MiWu | MIT License |
codebase/android/core/data/src/main/java/com/makeappssimple/abhimanyu/financemanager/android/core/data/source/usecase/InsertSourcesUseCase.kt | Abhimanyu14 | 429,663,688 | false | null | package com.makeappssimple.abhimanyu.financemanager.android.core.data.source.usecase
import com.makeappssimple.abhimanyu.financemanager.android.core.data.preferences.repository.MyPreferencesRepository
import com.makeappssimple.abhimanyu.financemanager.android.core.data.source.repository.SourceRepository
import com.makeappssimple.abhimanyu.financemanager.android.core.model.Source
interface InsertSourcesUseCase {
suspend operator fun invoke(
vararg sources: Source,
)
}
class InsertSourcesUseCaseImpl(
private val myPreferencesRepository: MyPreferencesRepository,
private val sourceRepository: SourceRepository,
) : InsertSourcesUseCase {
override suspend operator fun invoke(
vararg sources: Source,
) {
myPreferencesRepository.setLastDataChangeTimestamp()
return sourceRepository.insertSources(
sources = sources,
)
}
}
| 0 | Kotlin | 0 | 0 | ad9e8d4a2e74a010949cde1315dedb0d294acec8 | 907 | finance-manager | Apache License 2.0 |
app/src/main/java/in/ceeq/paginglib/view/PostItemViewModel.kt | rachitmishra | 125,669,319 | false | null | package `in`.ceeq.paginglib.view
import `in`.ceeq.paginglib.data.entity.Post
class PostItemViewModel(val post: Post?,
isDividerVisible: Boolean)
| 1 | Kotlin | 1 | 1 | 6686ebb0c5a749d35b73031b5b5bd7d0dbab90fd | 171 | PagingLib | MIT License |
di/src/commonMain/kotlin/ivy/di/autowire/AutowireSingleton.kt | Ivy-Apps | 845,095,104 | false | {"Kotlin": 53820} | package ivy.di.autowire
import ivy.di.Di.Scope
import ivy.di.Di.singleton
import kotlin.jvm.JvmName
inline fun <reified R : Any> Scope.autoWireSingleton(
crossinline constructor: () -> R,
named: Any? = null,
) {
singleton(named = named) { new(constructor) }
}
@JvmName("autoWire1")
inline fun <reified R : Any, reified T1> Scope.autoWireSingleton(
crossinline constructor: (T1) -> R,
named: Any? = null,
) {
singleton(named = named) { new(constructor) }
}
@JvmName("autoWire2")
inline fun <reified R : Any, reified T1, reified T2> Scope.autoWireSingleton(
crossinline constructor: (T1, T2) -> R,
named: Any? = null,
) {
singleton(named = named) { new(constructor) }
}
@JvmName("autoWire3")
inline fun <reified R : Any, reified T1, reified T2, reified T3> Scope.autoWireSingleton(
crossinline constructor: (T1, T2, T3) -> R,
named: Any? = null,
) {
singleton(named = named) { new(constructor) }
}
@JvmName("autoWire4")
inline fun <reified R : Any, reified T1, reified T2, reified T3, reified T4> Scope.autoWireSingleton(
crossinline constructor: (T1, T2, T3, T4) -> R,
named: Any? = null,
) {
singleton(named = named) { new(constructor) }
}
@JvmName("autoWire5")
inline fun <reified R : Any, reified T1, reified T2, reified T3, reified T4, reified T5> Scope.autoWireSingleton(
crossinline constructor: (T1, T2, T3, T4, T5) -> R,
named: Any? = null,
) {
singleton(named = named) { new(constructor) }
}
@JvmName("autoWire6")
inline fun <reified R : Any, reified T1, reified T2, reified T3, reified T4, reified T5, reified T6> Scope.autoWireSingleton(
crossinline constructor: (T1, T2, T3, T4, T5, T6) -> R,
named: Any? = null,
) {
singleton(named = named) { new(constructor) }
}
@JvmName("autoWire7")
inline fun <reified R : Any, reified T1, reified T2, reified T3, reified T4, reified T5, reified T6, reified T7> Scope.autoWireSingleton(
crossinline constructor: (T1, T2, T3, T4, T5, T6, T7) -> R,
named: Any? = null,
) {
singleton(named = named) { new(constructor) }
}
@JvmName("autoWire8")
inline fun <reified R : Any, reified T1, reified T2, reified T3, reified T4, reified T5, reified T6, reified T7, reified T8> Scope.autoWireSingleton(
crossinline constructor: (T1, T2, T3, T4, T5, T6, T7, T8) -> R,
named: Any? = null,
) {
singleton(named = named) { new(constructor) }
}
@JvmName("autoWire9")
inline fun <reified R : Any, reified T1, reified T2, reified T3, reified T4, reified T5, reified T6, reified T7, reified T8, reified T9> Scope.autoWireSingleton(
crossinline constructor: (T1, T2, T3, T4, T5, T6, T7, T8, T9) -> R,
named: Any? = null,
) {
singleton(named = named) { new(constructor) }
}
@JvmName("autoWire10")
inline fun <reified R : Any, reified T1, reified T2, reified T3, reified T4, reified T5, reified T6, reified T7, reified T8, reified T9, reified T10> Scope.autoWireSingleton(
crossinline constructor: (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10) -> R,
named: Any? = null,
) {
singleton(named = named) { new(constructor) }
}
@JvmName("autoWire11")
inline fun <reified R : Any, reified T1, reified T2, reified T3, reified T4, reified T5, reified T6, reified T7, reified T8, reified T9, reified T10, reified T11> Scope.autoWireSingleton(
crossinline constructor: (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11) -> R,
named: Any? = null,
) {
singleton(named = named) { new(constructor) }
}
@JvmName("autoWire12")
inline fun <reified R : Any, reified T1, reified T2, reified T3, reified T4, reified T5, reified T6, reified T7, reified T8, reified T9, reified T10, reified T11, reified T12> Scope.autoWireSingleton(
crossinline constructor: (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12) -> R,
named: Any? = null,
) {
singleton(named = named) { new(constructor) }
}
@JvmName("autoWire13")
inline fun <reified R : Any, reified T1, reified T2, reified T3, reified T4, reified T5, reified T6, reified T7, reified T8, reified T9, reified T10, reified T11, reified T12, reified T13> Scope.autoWireSingleton(
crossinline constructor: (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13) -> R,
named: Any? = null,
) {
singleton(named = named) { new(constructor) }
}
@JvmName("autoWire14")
inline fun <reified R : Any, reified T1, reified T2, reified T3, reified T4, reified T5, reified T6, reified T7, reified T8, reified T9, reified T10, reified T11, reified T12, reified T13, reified T14> Scope.autoWireSingleton(
crossinline constructor: (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14) -> R,
named: Any? = null,
) {
singleton(named = named) { new(constructor) }
}
@JvmName("autoWire15")
inline fun <reified R : Any, reified T1, reified T2, reified T3, reified T4, reified T5, reified T6, reified T7, reified T8, reified T9, reified T10, reified T11, reified T12, reified T13, reified T14, reified T15> Scope.autoWireSingleton(
crossinline constructor: (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15) -> R,
named: Any? = null,
) {
singleton(named = named) { new(constructor) }
}
@JvmName("autoWire16")
inline fun <reified R : Any, reified T1, reified T2, reified T3, reified T4, reified T5, reified T6, reified T7, reified T8, reified T9, reified T10, reified T11, reified T12, reified T13, reified T14, reified T15, reified T16> Scope.autoWireSingleton(
crossinline constructor: (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16) -> R,
named: Any? = null,
) {
singleton(named = named) { new(constructor) }
}
@JvmName("autoWire17")
inline fun <reified R : Any, reified T1, reified T2, reified T3, reified T4, reified T5, reified T6, reified T7, reified T8, reified T9, reified T10, reified T11, reified T12, reified T13, reified T14, reified T15, reified T16, reified T17> Scope.autoWireSingleton(
crossinline constructor: (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17) -> R,
named: Any? = null,
) {
singleton(named = named) { new(constructor) }
}
@JvmName("autoWire18")
inline fun <reified R : Any, reified T1, reified T2, reified T3, reified T4, reified T5, reified T6, reified T7, reified T8, reified T9, reified T10, reified T11, reified T12, reified T13, reified T14, reified T15, reified T16, reified T17, reified T18> Scope.autoWireSingleton(
crossinline constructor: (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18) -> R,
named: Any? = null,
) {
singleton(named = named) { new(constructor) }
}
@JvmName("autoWire19")
inline fun <reified R : Any, reified T1, reified T2, reified T3, reified T4, reified T5, reified T6, reified T7, reified T8, reified T9, reified T10, reified T11, reified T12, reified T13, reified T14, reified T15, reified T16, reified T17, reified T18, reified T19> Scope.autoWireSingleton(
crossinline constructor: (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19) -> R,
named: Any? = null,
) {
singleton(named = named) { new(constructor) }
}
@JvmName("autoWire20")
inline fun <reified R : Any, reified T1, reified T2, reified T3, reified T4, reified T5, reified T6, reified T7, reified T8, reified T9, reified T10, reified T11, reified T12, reified T13, reified T14, reified T15, reified T16, reified T17, reified T18, reified T19, reified T20> Scope.autoWireSingleton(
crossinline constructor: (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20) -> R,
named: Any? = null,
) {
singleton(named = named) { new(constructor) }
}
@JvmName("autoWire21")
inline fun <reified R : Any, reified T1, reified T2, reified T3, reified T4, reified T5, reified T6, reified T7, reified T8, reified T9, reified T10, reified T11, reified T12, reified T13, reified T14, reified T15, reified T16, reified T17, reified T18, reified T19, reified T20, reified T21> Scope.autoWireSingleton(
crossinline constructor: (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21) -> R,
named: Any? = null,
) {
singleton(named = named) { new(constructor) }
}
@JvmName("autoWire22")
inline fun <reified R : Any, reified T1, reified T2, reified T3, reified T4, reified T5, reified T6, reified T7, reified T8, reified T9, reified T10, reified T11, reified T12, reified T13, reified T14, reified T15, reified T16, reified T17, reified T18, reified T19, reified T20, reified T21, reified T22> Scope.autoWireSingleton(
crossinline constructor: (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22) -> R,
named: Any? = null,
) {
singleton(named = named) { new(constructor) }
}
@JvmName("autoWire23")
inline fun <reified R : Any, reified T1, reified T2, reified T3, reified T4, reified T5, reified T6, reified T7, reified T8, reified T9, reified T10, reified T11, reified T12, reified T13, reified T14, reified T15, reified T16, reified T17, reified T18, reified T19, reified T20, reified T21, reified T22, reified T23> Scope.autoWireSingleton(
crossinline constructor: (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23) -> R,
named: Any? = null,
) {
singleton(named = named) { new(constructor) }
}
@JvmName("autoWire24")
inline fun <reified R : Any, reified T1, reified T2, reified T3, reified T4, reified T5, reified T6, reified T7, reified T8, reified T9, reified T10, reified T11, reified T12, reified T13, reified T14, reified T15, reified T16, reified T17, reified T18, reified T19, reified T20, reified T21, reified T22, reified T23, reified T24> Scope.autoWireSingleton(
crossinline constructor: (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24) -> R,
named: Any? = null,
) {
singleton(named = named) { new(constructor) }
}
@JvmName("autoWire25")
inline fun <reified R : Any, reified T1, reified T2, reified T3, reified T4, reified T5, reified T6, reified T7, reified T8, reified T9, reified T10, reified T11, reified T12, reified T13, reified T14, reified T15, reified T16, reified T17, reified T18, reified T19, reified T20, reified T21, reified T22, reified T23, reified T24, reified T25> Scope.autoWireSingleton(
crossinline constructor: (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25) -> R,
named: Any? = null,
) {
singleton(named = named) { new(constructor) }
}
@JvmName("autoWire26")
inline fun <reified R : Any, reified T1, reified T2, reified T3, reified T4, reified T5, reified T6, reified T7, reified T8, reified T9, reified T10, reified T11, reified T12, reified T13, reified T14, reified T15, reified T16, reified T17, reified T18, reified T19, reified T20, reified T21, reified T22, reified T23, reified T24, reified T25, reified T26> Scope.autoWireSingleton(
crossinline constructor: (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26) -> R,
named: Any? = null,
) {
singleton(named = named) { new(constructor) }
}
@JvmName("autoWire27")
inline fun <reified R : Any, reified T1, reified T2, reified T3, reified T4, reified T5, reified T6, reified T7, reified T8, reified T9, reified T10, reified T11, reified T12, reified T13, reified T14, reified T15, reified T16, reified T17, reified T18, reified T19, reified T20, reified T21, reified T22, reified T23, reified T24, reified T25, reified T26, reified T27> Scope.autoWireSingleton(
crossinline constructor: (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27) -> R,
named: Any? = null,
) {
singleton(named = named) { new(constructor) }
}
@JvmName("autoWire28")
inline fun <reified R : Any, reified T1, reified T2, reified T3, reified T4, reified T5, reified T6, reified T7, reified T8, reified T9, reified T10, reified T11, reified T12, reified T13, reified T14, reified T15, reified T16, reified T17, reified T18, reified T19, reified T20, reified T21, reified T22, reified T23, reified T24, reified T25, reified T26, reified T27, reified T28> Scope.autoWireSingleton(
crossinline constructor: (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28) -> R,
named: Any? = null,
) {
singleton(named = named) { new(constructor) }
}
@JvmName("autoWire29")
inline fun <reified R : Any, reified T1, reified T2, reified T3, reified T4, reified T5, reified T6, reified T7, reified T8, reified T9, reified T10, reified T11, reified T12, reified T13, reified T14, reified T15, reified T16, reified T17, reified T18, reified T19, reified T20, reified T21, reified T22, reified T23, reified T24, reified T25, reified T26, reified T27, reified T28, reified T29> Scope.autoWireSingleton(
crossinline constructor: (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29) -> R,
named: Any? = null,
) {
singleton(named = named) { new(constructor) }
}
@JvmName("autoWire30")
inline fun <reified R : Any, reified T1, reified T2, reified T3, reified T4, reified T5, reified T6, reified T7, reified T8, reified T9, reified T10, reified T11, reified T12, reified T13, reified T14, reified T15, reified T16, reified T17, reified T18, reified T19, reified T20, reified T21, reified T22, reified T23, reified T24, reified T25, reified T26, reified T27, reified T28, reified T29, reified T30> Scope.autoWireSingleton(
crossinline constructor: (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30) -> R,
named: Any? = null,
) {
singleton(named = named) { new(constructor) }
} | 0 | Kotlin | 0 | 0 | b1214b51b99b156bace4d097aa367736c7f9d2d0 | 13,986 | di | Apache License 2.0 |
database/src/main/kotlin/fi/vauhtijuoksu/vauhtijuoksuapi/database/impl/GameDataDatabase.kt | Vauhtijuoksu | 394,707,727 | false | null | package fi.vauhtijuoksu.vauhtijuoksuapi.database.impl
import fi.vauhtijuoksu.vauhtijuoksuapi.database.api.VauhtijuoksuDatabase
import fi.vauhtijuoksu.vauhtijuoksuapi.database.configuration.DatabaseConfiguration
import fi.vauhtijuoksu.vauhtijuoksuapi.exceptions.ServerError
import fi.vauhtijuoksu.vauhtijuoksuapi.models.GameData
import io.vertx.core.Future
import io.vertx.sqlclient.SqlClient
import io.vertx.sqlclient.templates.SqlTemplate
import mu.KotlinLogging
import javax.inject.Inject
class GameDataDatabase @Inject constructor(
private val client: SqlClient,
configuration: DatabaseConfiguration
) : AbstractModelDatabase<GameData>(
client,
configuration,
"gamedata",
"start_time",
{ GameData::class.java }
),
VauhtijuoksuDatabase<GameData> {
private val logger = KotlinLogging.logger {}
@Suppress("MaxLineLength") // SQL is prettier without too many splits
override fun add(record: GameData): Future<GameData> {
return SqlTemplate.forUpdate(
client,
"INSERT INTO gamedata " +
"(game, player, start_time, end_time, category, device, published, vod_link, img_filename, player_twitch) VALUES " +
"(#{game}, #{player}, #{start_time}, #{end_time}, #{category}, #{device}, #{published}, #{vod_link}, #{img_filename}, #{player_twitch} ) " +
"RETURNING *"
)
.mapFrom(GameData::class.java)
.mapTo(GameData::class.java)
.execute(record)
.recover {
throw ServerError("Failed to insert $record because of ${it.message}")
}
.map {
logger.debug { "Inserted gamedata $record" }
return@map it.iterator().next()
}
}
override fun update(record: GameData): Future<GameData?> {
TODO("Not yet implemented")
}
}
| 0 | Kotlin | 0 | 0 | a8ed1c12a4483fc14a6be8747a6778027da9e3f0 | 1,886 | vauhtijuoksu-api | MIT License |
database/src/main/kotlin/fi/vauhtijuoksu/vauhtijuoksuapi/database/impl/GameDataDatabase.kt | Vauhtijuoksu | 394,707,727 | false | null | package fi.vauhtijuoksu.vauhtijuoksuapi.database.impl
import fi.vauhtijuoksu.vauhtijuoksuapi.database.api.VauhtijuoksuDatabase
import fi.vauhtijuoksu.vauhtijuoksuapi.database.configuration.DatabaseConfiguration
import fi.vauhtijuoksu.vauhtijuoksuapi.exceptions.ServerError
import fi.vauhtijuoksu.vauhtijuoksuapi.models.GameData
import io.vertx.core.Future
import io.vertx.sqlclient.SqlClient
import io.vertx.sqlclient.templates.SqlTemplate
import mu.KotlinLogging
import javax.inject.Inject
class GameDataDatabase @Inject constructor(
private val client: SqlClient,
configuration: DatabaseConfiguration
) : AbstractModelDatabase<GameData>(
client,
configuration,
"gamedata",
"start_time",
{ GameData::class.java }
),
VauhtijuoksuDatabase<GameData> {
private val logger = KotlinLogging.logger {}
@Suppress("MaxLineLength") // SQL is prettier without too many splits
override fun add(record: GameData): Future<GameData> {
return SqlTemplate.forUpdate(
client,
"INSERT INTO gamedata " +
"(game, player, start_time, end_time, category, device, published, vod_link, img_filename, player_twitch) VALUES " +
"(#{game}, #{player}, #{start_time}, #{end_time}, #{category}, #{device}, #{published}, #{vod_link}, #{img_filename}, #{player_twitch} ) " +
"RETURNING *"
)
.mapFrom(GameData::class.java)
.mapTo(GameData::class.java)
.execute(record)
.recover {
throw ServerError("Failed to insert $record because of ${it.message}")
}
.map {
logger.debug { "Inserted gamedata $record" }
return@map it.iterator().next()
}
}
override fun update(record: GameData): Future<GameData?> {
TODO("Not yet implemented")
}
}
| 0 | Kotlin | 0 | 0 | a8ed1c12a4483fc14a6be8747a6778027da9e3f0 | 1,886 | vauhtijuoksu-api | MIT License |
browser-kotlin/src/jsMain/kotlin/web/audio/DistanceModelType.kt | karakum-team | 393,199,102 | false | {"Kotlin": 6149909} | // Automatically generated - do not modify!
@file:Suppress(
"NAME_CONTAINS_ILLEGAL_CHARS",
"NESTED_CLASS_IN_EXTERNAL_INTERFACE",
)
package web.audio
// language=JavaScript
@JsName("""(/*union*/{exponential: 'exponential', inverse: 'inverse', linear: 'linear'}/*union*/)""")
sealed external interface DistanceModelType {
companion object {
val exponential: DistanceModelType
val inverse: DistanceModelType
val linear: DistanceModelType
}
}
| 0 | Kotlin | 6 | 26 | 3fcfd2c61da8774151cf121596e656cc123b37db | 482 | types-kotlin | Apache License 2.0 |
core/src/test/kotlin/fixtures/brokenhex/port/out/OutMessage.kt | toolisticon | 725,230,561 | false | {"Kotlin": 50528} | package io.toolisticon.jmolecules.archunit.fixtures.brokenhex.port.out
data class OutMessage(
val value: String
)
| 3 | Kotlin | 0 | 1 | ef59ff183d87557d0776c3118755960be7f97404 | 117 | jmolecules-archunit-kotlin | Apache License 2.0 |
src/main/java/com/handarui/game/biz/bean/PatentStatusEnum.kt | Caius1L | 185,622,228 | false | {"Java Properties": 6, "Maven POM": 1, "Text": 1, "Ignore List": 1, "Markdown": 1, "Java": 42, "Kotlin": 73, "XML": 19, "JavaScript": 2, "HTML": 1, "JSON": 2, "CSS": 1} | package com.handarui.game.biz.bean
/**
* ็ถๆ๏ผ
* 0 ๆฐๅไบคๅบไนฆใ1ๆไบค็ณ่ฏทใ2ๅ็ใ3ๅฎๅฎกใ4ๅ็ปใ5ๆๆใ
* 6 ้ฉณๅใ7ๅคๅฎกใ8ๅผ่ฎฎใ9ๆ ๆใ10ๅๆญฅๅฎกๆฅใ11ๆๆๅ
ฌๅใ12 ่กๆฟๅค่ฎฎ
*/
enum class PatentStatusEnum(val code: Int, val type: String) {
WRITING_BOOK(0, "ๆฐๅไบคๅบไนฆ"),
SUBMIT_APPLY(1, "ๆไบค็ณ่ฏท"),
ACCEPT(2, "ๅ็"),
ACTUAL_REVIEW(3 ,"ๅฎๅฎก"),
REGISTRATION(4 ,"ๅ็ป"),
AUTHORIZATION(5 ,"ๆๆ"),
REJECT(6 ,"้ฉณๅ"),
REHEAR(7 ,"ๅคๅฎก"),
OBJECTION(8 ,"ๅผ่ฎฎ"),
INVALID(9 ,"ๆ ๆ"),
PRELIMINARY_REVIEW(10 ,"ๅๆญฅๅฎกๆฅ"),
AUTHORIZATION_NOTICE(11 ,"ๆๆๅ
ฌๅ"),
ADMINISTRATIVE_RECONSIDERATION(12 ,"่กๆฟๅค่ฎฎ"),
DEFAULT(99, "้ป่ฎค");
companion object {
fun getByStatusName(status: String): PatentStatusEnum {
val enums = values()
val match = enums.firstOrNull {
it.type == status
}
return match ?: DEFAULT
}
fun getByStatusCode(code: Int): PatentStatusEnum {
val enums = values()
val match = enums.firstOrNull {
it.code == code
}
return match ?: DEFAULT
}
}
} | 0 | Kotlin | 0 | 1 | 90ca32dad913e94454725a4c5ba163616c0c80e0 | 1,083 | game-version-manage | Apache License 2.0 |
src/jvmMain/kotlin/application/ui/objects/graph_ui.kt | Fovteltar | 508,838,894 | false | null | package application.ui.objects
import logic.Graph
import logic.Vertex
class GraphUI(private val graph: Graph) {
val verticesUI: MutableMap<VertexUI, VertexInfoUI> = mutableMapOf()
val vertexToUI = mutableMapOf<Vertex, VertexUI>()
fun addVertex(vertexUI: VertexUI) {
graph.addVertex(vertexUI.vertex)
verticesUI[vertexUI] = VertexInfoUI() ////
vertexToUI[vertexUI.vertex] = vertexUI
}
fun addEdge(edgeUI: EdgeUI) {
graph.addEdge(edgeUI.edge)
verticesUI[edgeUI.verticesUI.first]!!.addOutGoingEdge(edgeUI.verticesUI.second, edgeUI)
verticesUI[edgeUI.verticesUI.second]!!.addInputEdge(edgeUI.verticesUI.first, edgeUI)
}
private fun removeUIEdgesTo(vertexUI: VertexUI):UInt{
var removedEdgesAmount = 0u
val toDeleteEdgesInfo = verticesUI[vertexUI]
toDeleteEdgesInfo?.outGoingEdges?.values?.forEach {
verticesUI[it.verticesUI.second]?.inputGoingEdges?.remove(it.verticesUI.first)
++removedEdgesAmount
}
toDeleteEdgesInfo?.outGoingEdges?.clear()
toDeleteEdgesInfo?.inputGoingEdges?.values?.forEach {
verticesUI[it.verticesUI.first]?.outGoingEdges?.remove(it.verticesUI.second)
++removedEdgesAmount
}
toDeleteEdgesInfo?.inputGoingEdges?.clear()
return removedEdgesAmount
}
fun removeVertex(vertexUI: VertexUI):UInt {
if (verticesUI.containsKey(vertexUI)) {
graph.removeVertex(vertexUI.vertex)
val removedEdgesAmount = removeUIEdgesTo(vertexUI)
verticesUI.remove(vertexUI)
vertexToUI.remove(vertexUI.vertex)
return removedEdgesAmount
}
return 0u
}
fun removeEdge(edgeUI: EdgeUI) {
if (verticesUI[edgeUI.verticesUI.first]?.outGoingEdges?.values?.contains(edgeUI) == true) {
graph.removeEdge(edgeUI.edge)
verticesUI[edgeUI.verticesUI.first]?.outGoingEdges?.remove(edgeUI.verticesUI.second)
verticesUI[edgeUI.verticesUI.second]?.inputGoingEdges?.remove(edgeUI.verticesUI.first)
}
}
fun getEdges():MutableList<EdgeUI>{
val edges:MutableList<EdgeUI> = mutableListOf()
verticesUI.keys.forEach {
val currentEdges = verticesUI[it]!!.getOutGoingEdges()
edges.addAll(currentEdges)
}
return edges
}
} | 0 | Kotlin | 0 | 0 | f5d465bfa4e24716b8cc48a7bd315dd87bfe11f0 | 2,407 | dijkstra_algorithm | MIT License |
app/src/main/java/br/com/movieapp/favorite/feature/domain/usecase/GetMoviesFavoriteUseCase.kt | wilsonleandro | 724,752,199 | false | {"Kotlin": 124798} | package br.com.movieapp.favorite.feature.domain.usecase
import br.com.movieapp.core.domain.model.Movie
import br.com.movieapp.favorite.feature.domain.repository.MovieFavoriteRepository
import kotlinx.coroutines.flow.Flow
import javax.inject.Inject
interface GetMoviesFavoriteUseCase {
suspend fun invoke(): Flow<List<Movie>>
}
class GetMoviesFavoriteUseCaseImpl @Inject constructor(
private val movieFavoriteRepository: MovieFavoriteRepository
) : GetMoviesFavoriteUseCase {
override suspend fun invoke(): Flow<List<Movie>> {
return movieFavoriteRepository.getMovies()
}
}
| 0 | Kotlin | 0 | 0 | 45d3ed2419090d0dd5b1492fa4df162f9aabaca9 | 600 | movieapp | MIT License |
app/src/main/java/br/com/movieapp/favorite/feature/domain/usecase/GetMoviesFavoriteUseCase.kt | wilsonleandro | 724,752,199 | false | {"Kotlin": 124798} | package br.com.movieapp.favorite.feature.domain.usecase
import br.com.movieapp.core.domain.model.Movie
import br.com.movieapp.favorite.feature.domain.repository.MovieFavoriteRepository
import kotlinx.coroutines.flow.Flow
import javax.inject.Inject
interface GetMoviesFavoriteUseCase {
suspend fun invoke(): Flow<List<Movie>>
}
class GetMoviesFavoriteUseCaseImpl @Inject constructor(
private val movieFavoriteRepository: MovieFavoriteRepository
) : GetMoviesFavoriteUseCase {
override suspend fun invoke(): Flow<List<Movie>> {
return movieFavoriteRepository.getMovies()
}
}
| 0 | Kotlin | 0 | 0 | 45d3ed2419090d0dd5b1492fa4df162f9aabaca9 | 600 | movieapp | MIT License |
kotlin-delegation-playground-library/src/commonMain/kotlin/ru/spbstu/ErasableDelegate.kt | belyaev-mikhail | 398,021,822 | false | null | package ru.spbstu
annotation class ErasableDelegate
| 0 | Kotlin | 0 | 0 | c5951d16130ceb12f83fa11297de24ef676a394f | 53 | kotlin-delegation-playground | Apache License 2.0 |
app/src/main/java/com/example/temi_beta/hook/connectivity_state.kt | kaomao1234 | 700,679,188 | false | {"Kotlin": 96630, "Python": 6013} | package com.example.temi_beta.hook
import androidx.compose.runtime.Composable
import androidx.compose.runtime.State
import androidx.compose.runtime.produceState
import androidx.compose.ui.platform.LocalContext
import com.example.temi_beta.utils.ConnectionState
import com.example.temi_beta.utils.currentConnectivityState
import com.example.temi_beta.utils.observeConnectivityAsFlow
import kotlinx.coroutines.ExperimentalCoroutinesApi
@ExperimentalCoroutinesApi
@Composable
fun connectivityState(): State<ConnectionState> {
val context = LocalContext.current
// Creates a State<ConnectionState> with current connectivity state as initial value
return produceState(initialValue = context.currentConnectivityState) {
// In a coroutine, can make suspend calls
context.observeConnectivityAsFlow().collect { value = it }
}
} | 0 | Kotlin | 0 | 0 | 3645e45cce1dedcb6f1da327f57344641f1b069f | 853 | temibeta | MIT License |
src/main/kotlin/com/sk/topicWise/tree/easy/1394. Find Lucky Integer in an Array.kt | sandeep549 | 262,513,267 | false | {"Gradle": 2, "INI": 2, "Shell": 1, "Text": 4, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "Kotlin": 511} | package com.sk.topicWise.tree.easy
import java.util.*
class Solution1394 {
fun findLucky(arr: IntArray): Int {
val map = TreeMap<Int, Int>(Collections.reverseOrder())
for (key in arr) {
map[key] = map.getOrDefault(key, 0) + 1
}
for ((k, v) in map) {
if (k == v) return k
}
return -1
}
fun findLucky2(arr: IntArray): Int {
val a = IntArray(501)
for (e in arr) {
a[e]++
}
for (i in a.indices.reversed()) {
if (a[i] == i && i != 0) return i
}
return -1
}
} | 1 | null | 1 | 1 | 67688ec01551e9981f4be07edc11e0ee7c0fab4c | 619 | leetcode-answers-kotlin | Apache License 2.0 |
korge-core/src/korlibs/io/file/std/MemoryNodeTree.kt | korlibs | 80,095,683 | false | {"WebAssembly": 14293935, "Kotlin": 9728800, "C": 77092, "C++": 20878, "TypeScript": 12397, "HTML": 6043, "Python": 4296, "Swift": 1371, "JavaScript": 328, "Shell": 254, "CMake": 202, "CSS": 66, "Batchfile": 41} | package korlibs.io.file.std
import korlibs.datastructure.iterators.*
import korlibs.io.file.*
import korlibs.io.lang.*
import korlibs.io.stream.*
class MemoryNodeTree(val caseSensitive: Boolean = true) {
val rootNode = Node("", isDirectory = true)
open inner class Node(
val name: String,
val isDirectory: Boolean = false,
parent: Node? = null
) : Iterable<Node> {
val nameLC = name.toLowerCase()
override fun iterator(): Iterator<Node> = children.values.iterator()
var parent: Node? = null
set(value) {
if (field != null) {
field!!.children.remove(this.name)
field!!.childrenLC.remove(this.nameLC)
}
field = value
field?.children?.set(name, this)
field?.childrenLC?.set(nameLC, this)
}
init {
this.parent = parent
}
var bytes: ByteArray? = null
var data: Any? = null
val children = linkedMapOf<String, Node>()
val childrenLC = linkedMapOf<String, Node>()
val root: Node get() = parent?.root ?: this
var stream: AsyncStream? = null
var link: String? = null
val path: String get() = if (parent == null) "/" else "/" + "${parent?.path ?: ""}/$name".trimStart('/')
fun child(name: String): Node? = when (name) {
"", "." -> this
".." -> parent
else -> if (caseSensitive) {
children[name]
} else {
childrenLC[name.lowercase()]
}
}
fun createChild(name: String, isDirectory: Boolean = false): Node =
Node(name, isDirectory = isDirectory, parent = this)
operator fun get(path: String): Node = access(path, createFolders = false)
fun getOrNull(path: String): Node? = try {
access(path, createFolders = false)
} catch (e: FileNotFoundException) {
null
}
fun accessOrNull(path: String): Node? = getOrNull(path)
fun access(path: String, createFolders: Boolean = false): Node {
var node = if (path.startsWith('/')) root else this
path.pathInfo.parts().fastForEach { part ->
var child = node.child(part)
if (child == null && createFolders) child = node.createChild(part, isDirectory = true)
node = child ?: throw FileNotFoundException("Can't find '$part' in $path")
}
return node
}
fun followLinks(): Node = link?.let { accessOrNull(it)?.followLinks() } ?: this
fun mkdir(name: String): Boolean {
if (child(name) != null) {
return false
} else {
createChild(name, isDirectory = true)
return true
}
}
fun delete() {
parent?.children?.remove(this.name)
parent?.childrenLC?.remove(this.nameLC)
}
}
}
| 444 | WebAssembly | 121 | 2,207 | dc3d2080c6b956d4c06f4bfa90a6c831dbaa983a | 3,050 | korge | Apache License 2.0 |
app/src/main/java/com/example/movies/MoviesFragment.kt | hopeDeJesusCodes | 699,382,123 | false | {"Kotlin": 8944} | package com.example.movies
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import com.google.gson.reflect.TypeToken
import androidx.core.widget.ContentLoadingProgressBar
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.codepath.asynchttpclient.AsyncHttpClient
import com.codepath.asynchttpclient.RequestParams
import com.codepath.asynchttpclient.callback.JsonHttpResponseHandler
import com.google.gson.Gson
import okhttp3.Headers
import org.json.JSONObject
// --------------------------------//
// CHANGE THIS TO BE YOUR API KEY //
// --------------------------------//
private const val API_KEY = "<KEY>"
private const val TMDB_BASE_URL = "https://api.themoviedb.org/3/movie/now_playing"
class MoviesFragment : Fragment(), OnListFragmentInteractionListener {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.item_movie, container, false)
val progressBar = view.findViewById<View>(R.id.progress) as ContentLoadingProgressBar
val recyclerView = view.findViewById<View>(R.id.list) as RecyclerView
val context = view.context
recyclerView.layoutManager = GridLayoutManager(context, 1)
updateAdapter(progressBar, recyclerView)
return view
}
private fun updateAdapter(progressBar: ContentLoadingProgressBar, recyclerView: RecyclerView) {
progressBar.show()
// Create and set up an AsyncHTTPClient() here
val client = AsyncHttpClient()
val params = RequestParams()
params["api_key"] = API_KEY
// Using the client, perform the HTTP request
client[TMDB_BASE_URL, params, object : JsonHttpResponseHandler() {
override fun onSuccess(
statusCode: Int,
headers: Headers,
json: JsonHttpResponseHandler.JSON
) {
try {
val movies = parseTmdbResponse(json)
recyclerView.adapter = MovieInfo(movies, this@MoviesFragment)
progressBar.hide()
} catch (e: Exception) {
Log.e("MoviesFragment", "Error parsing JSON: ${e.message}")
}
}
override fun onFailure(
statusCode: Int,
headers: Headers?,
errorResponse: String,
t: Throwable?
) {
progressBar.hide()
t?.message?.let {
Log.e("MoviesFragment", "HTTP Request Failed: $errorResponse")
Log.e("MoviesFragment", "Error Message: ${t.message}")
}
}
}]
}
override fun onItemClick(item: InTheatersMovie) {
Toast.makeText(context, "Movie: ${item.title}", Toast.LENGTH_LONG).show()
}
data class TmdbResponse(
val results: List<InTheatersMovie>
)
private fun parseTmdbResponse(json: JsonHttpResponseHandler.JSON): List<InTheatersMovie> {
val movieList = mutableListOf<InTheatersMovie>()
try {
val jsonString = json.toString() // Convert the JSON response to a string
// Check if the string starts with "jsonObject="
if (jsonString.startsWith("jsonObject=")) {
// Remove the prefix to get the JSON data
val jsonData = jsonString.substring("jsonObject=".length)
// Create a JSON object from the JSON data
val jsonObject = JSONObject(jsonData)
// Extract the "results" array
val resultsArray = jsonObject.getJSONArray("results")
val gson = Gson()
for (i in 0 until resultsArray.length()) {
val movieResponse = resultsArray.getJSONObject(i)
val title = movieResponse.getString("title")
val posterPath = movieResponse.getString("poster_path")
val overview = movieResponse.getString("overview") // Extract the overview
// Create an InTheatersMovie object for this movie
val movieInfo = InTheatersMovie(id = 0, title = title, overview = overview, posterPath = posterPath)
// Add the InTheatersMovie object to the list
movieList.add(movieInfo)
}
Log.d("MoviesFragment", "Number of movies: ${movieList.size}")
} else {
Log.e("MoviesFragment", "Invalid JSON format: $jsonString")
}
} catch (e: Exception) {
Log.e("MoviesFragment", "Error parsing JSON: ${e.message}")
Log.e("MoviesFragment", "JSON Response: ${json.toString()}")
}
// Return the list of InTheatersMovie objects
return movieList
}
}
| 0 | Kotlin | 0 | 0 | d0d498c03b9261e86d990e4f5e047a24c40b11e7 | 5,117 | Movies | Apache License 2.0 |
app/src/main/java/com/example/movies/MoviesFragment.kt | hopeDeJesusCodes | 699,382,123 | false | {"Kotlin": 8944} | package com.example.movies
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import com.google.gson.reflect.TypeToken
import androidx.core.widget.ContentLoadingProgressBar
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.codepath.asynchttpclient.AsyncHttpClient
import com.codepath.asynchttpclient.RequestParams
import com.codepath.asynchttpclient.callback.JsonHttpResponseHandler
import com.google.gson.Gson
import okhttp3.Headers
import org.json.JSONObject
// --------------------------------//
// CHANGE THIS TO BE YOUR API KEY //
// --------------------------------//
private const val API_KEY = "<KEY>"
private const val TMDB_BASE_URL = "https://api.themoviedb.org/3/movie/now_playing"
class MoviesFragment : Fragment(), OnListFragmentInteractionListener {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.item_movie, container, false)
val progressBar = view.findViewById<View>(R.id.progress) as ContentLoadingProgressBar
val recyclerView = view.findViewById<View>(R.id.list) as RecyclerView
val context = view.context
recyclerView.layoutManager = GridLayoutManager(context, 1)
updateAdapter(progressBar, recyclerView)
return view
}
private fun updateAdapter(progressBar: ContentLoadingProgressBar, recyclerView: RecyclerView) {
progressBar.show()
// Create and set up an AsyncHTTPClient() here
val client = AsyncHttpClient()
val params = RequestParams()
params["api_key"] = API_KEY
// Using the client, perform the HTTP request
client[TMDB_BASE_URL, params, object : JsonHttpResponseHandler() {
override fun onSuccess(
statusCode: Int,
headers: Headers,
json: JsonHttpResponseHandler.JSON
) {
try {
val movies = parseTmdbResponse(json)
recyclerView.adapter = MovieInfo(movies, this@MoviesFragment)
progressBar.hide()
} catch (e: Exception) {
Log.e("MoviesFragment", "Error parsing JSON: ${e.message}")
}
}
override fun onFailure(
statusCode: Int,
headers: Headers?,
errorResponse: String,
t: Throwable?
) {
progressBar.hide()
t?.message?.let {
Log.e("MoviesFragment", "HTTP Request Failed: $errorResponse")
Log.e("MoviesFragment", "Error Message: ${t.message}")
}
}
}]
}
override fun onItemClick(item: InTheatersMovie) {
Toast.makeText(context, "Movie: ${item.title}", Toast.LENGTH_LONG).show()
}
data class TmdbResponse(
val results: List<InTheatersMovie>
)
private fun parseTmdbResponse(json: JsonHttpResponseHandler.JSON): List<InTheatersMovie> {
val movieList = mutableListOf<InTheatersMovie>()
try {
val jsonString = json.toString() // Convert the JSON response to a string
// Check if the string starts with "jsonObject="
if (jsonString.startsWith("jsonObject=")) {
// Remove the prefix to get the JSON data
val jsonData = jsonString.substring("jsonObject=".length)
// Create a JSON object from the JSON data
val jsonObject = JSONObject(jsonData)
// Extract the "results" array
val resultsArray = jsonObject.getJSONArray("results")
val gson = Gson()
for (i in 0 until resultsArray.length()) {
val movieResponse = resultsArray.getJSONObject(i)
val title = movieResponse.getString("title")
val posterPath = movieResponse.getString("poster_path")
val overview = movieResponse.getString("overview") // Extract the overview
// Create an InTheatersMovie object for this movie
val movieInfo = InTheatersMovie(id = 0, title = title, overview = overview, posterPath = posterPath)
// Add the InTheatersMovie object to the list
movieList.add(movieInfo)
}
Log.d("MoviesFragment", "Number of movies: ${movieList.size}")
} else {
Log.e("MoviesFragment", "Invalid JSON format: $jsonString")
}
} catch (e: Exception) {
Log.e("MoviesFragment", "Error parsing JSON: ${e.message}")
Log.e("MoviesFragment", "JSON Response: ${json.toString()}")
}
// Return the list of InTheatersMovie objects
return movieList
}
}
| 0 | Kotlin | 0 | 0 | d0d498c03b9261e86d990e4f5e047a24c40b11e7 | 5,117 | Movies | Apache License 2.0 |
feature/media/local/domain/implementation/src/main/kotlin/com/savvasdalkitsis/uhuruphotos/feature/media/local/domain/implementation/repository/MediaStoreVersionRepository.kt | savvasdalkitsis | 485,908,521 | false | null | /*
Copyright 2022 <NAME>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.savvasdalkitsis.uhuruphotos.feature.media.local.domain.implementation.repository
import com.savvasdalkitsis.uhuruphotos.feature.media.local.domain.implementation.service.LocalMediaService
import com.savvasdalkitsis.uhuruphotos.foundation.preferences.api.PlainTextPreferences
import com.savvasdalkitsis.uhuruphotos.foundation.preferences.api.Preferences
import com.savvasdalkitsis.uhuruphotos.foundation.preferences.api.get
import com.savvasdalkitsis.uhuruphotos.foundation.preferences.api.set
import javax.inject.Inject
class MediaStoreVersionRepository @Inject constructor(
private val localMediaService: LocalMediaService,
@PlainTextPreferences
private val preferences: Preferences,
) {
private val key = "media_store_version"
var currentMediaStoreVersion
get() = preferences.get(key, defaultValue = "")
set(value) { preferences.set(key, value) }
val latestMediaStoreVersion get() = localMediaService.mediaStoreCurrentVersion
} | 71 | null | 26 | 358 | 22c2ac7d953f88b4d60fb74953667ef0c4beacc5 | 1,539 | uhuruphotos-android | Apache License 2.0 |
app/src/main/java/com/ilhomsoliev/paging/data/network/model/location/LocationResponse.kt | ilhomsoliev | 672,033,927 | false | null | package com.ilhomsoliev.rikandmortytest.data.network.model.location
data class LocationResponse(
val created: String,
val dimension: String,
val id: Int,
val name: String,
val residents: List<String>,
val type: String,
val url: String
) | 0 | Kotlin | 0 | 0 | 806d4484d80dc4a38e0b6a7839d9142c80079e16 | 265 | CustomPagingCompose | Apache License 2.0 |
test-suite-kotlin-ksp/src/test/kotlin/io/micronaut/docs/server/suspend/SuspendServiceInterceptorSpec.kt | micronaut-projects | 124,230,204 | false | null | /*
* Copyright 2017-2019 original authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.micronaut.docs.server.suspend
import io.kotest.core.spec.style.StringSpec
import io.kotest.matchers.shouldBe
import io.micronaut.context.ApplicationContext
class SuspendServiceInterceptorSpec : StringSpec() {
val context = autoClose(
ApplicationContext.run()
)
private var suspendService = context.getBean(SuspendService::class.java)
init {
"should append to context " {
coroutineContext[MyContext] shouldBe null
suspendService.call1() shouldBe "call1"
suspendService.call2() shouldBe "call2"
suspendService.call3() shouldBe "call1"
suspendService.call4() shouldBe "call4"
}
}
}
| 753 | null | 1061 | 6,059 | c9144646b31b23bd3c4150dec8ddd519947e55cf | 1,305 | micronaut-core | Apache License 2.0 |
src/main/kotlin/ru/kosolapov/course/configuration/HTTP.kt | Zymik | 637,872,394 | false | null | package ru.kosolapov.course.configuration
import io.ktor.server.application.*
import io.ktor.server.plugins.swagger.*
import io.ktor.server.routing.*
fun Application.configureHTTP() {
routing {
swaggerUI(path = "openapi", swaggerFile = "openapi/documentation.yaml")
}
}
| 0 | Kotlin | 0 | 0 | de6beb0c5ee63c5afad164e6169bb3a6f8c7944a | 288 | course-api | MIT License |
privacy-dashboard/src/main/java/com/github/privacydashboard/modules/home/PrivacyDashboardDashboardViewModel.kt | L3-iGrant | 174,165,127 | false | {"Kotlin": 309440} | package com.github.privacydashboard.modules.home
import android.content.Context
import android.content.Intent
import androidx.lifecycle.MutableLiveData
import com.github.privacydashboard.communication.PrivacyDashboardAPIManager
import com.github.privacydashboard.communication.PrivacyDashboardAPIServices
import com.github.privacydashboard.communication.repositories.GetConsentsByIdApiRepository
import com.github.privacydashboard.communication.repositories.GetDataAgreementsApiRepository
import com.github.privacydashboard.communication.repositories.GetOrganisationDetailApiRepository
import com.github.privacydashboard.communication.repositories.UpdateDataAgreementStatusApiRepository
import com.github.privacydashboard.models.Organization
import com.github.privacydashboard.models.OrganizationDetailResponse
import com.github.privacydashboard.models.PurposeConsent
import com.github.privacydashboard.models.v2.consent.ConsentStatusRequestV2
import com.github.privacydashboard.models.v2.dataAgreement.dataAgreementRecords.DataAgreementLatestRecordResponseV2
import com.github.privacydashboard.modules.base.PrivacyDashboardBaseViewModel
import com.github.privacydashboard.modules.dataAttribute.PrivacyDashboardDataAttributeListingActivity
import com.github.privacydashboard.utils.PrivacyDashboardDataUtils
import com.github.privacydashboard.utils.PrivacyDashboardNetWorkUtil
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class PrivacyDashboardDashboardViewModel() : PrivacyDashboardBaseViewModel() {
var orgName = MutableLiveData<String>("")
var orgLocation = MutableLiveData<String>("")
var orgDescription = MutableLiveData<String>("")
val organization = MutableLiveData<Organization?>()
var consentId: String? = null
val purposeConsents = MutableLiveData<ArrayList<PurposeConsent>>()
var isListLoading = MutableLiveData<Boolean>()
private fun updateUI(orgDetail: OrganizationDetailResponse?) {
consentId = orgDetail?.consentID
purposeConsents.value = orgDetail?.purposeConsents ?: ArrayList()
}
private fun updateOrganization(orgDetail: OrganizationDetailResponse?) {
organization.value = orgDetail?.organization
orgName.value = orgDetail?.organization?.name
orgLocation.value = orgDetail?.organization?.location
orgDescription.value = orgDetail?.organization?.description
}
init {
isLoading.value = true
isListLoading.value = false
organization.value = null
purposeConsents.value = ArrayList()
}
fun getOrganizationDetail(showProgress: Boolean, context: Context) {
if (PrivacyDashboardNetWorkUtil.isConnectedToInternet(context)) {
isLoading.value = showProgress
val apiService: PrivacyDashboardAPIServices = PrivacyDashboardAPIManager.getApi(
apiKey = PrivacyDashboardDataUtils.getStringValue(
context,
PrivacyDashboardDataUtils.EXTRA_TAG_TOKEN,
null
),
accessToken = PrivacyDashboardDataUtils.getStringValue(
context,
PrivacyDashboardDataUtils.EXTRA_TAG_ACCESS_TOKEN,
null
),
baseUrl = PrivacyDashboardDataUtils.getStringValue(
context,
PrivacyDashboardDataUtils.EXTRA_TAG_BASE_URL
)
)?.service!!
val organizationDetailRepository = GetOrganisationDetailApiRepository(apiService)
GlobalScope.launch {
val result = organizationDetailRepository.getOrganizationDetail(
PrivacyDashboardDataUtils.getStringValue(
context,
PrivacyDashboardDataUtils.EXTRA_TAG_ORGANISATIONID,
null
)
)
if (result.isSuccess) {
withContext(Dispatchers.Main) {
isLoading.value = false
isListLoading.value = purposeConsents.value?.isEmpty()
updateOrganization(result.getOrNull())
}
} else {
withContext(Dispatchers.Main) {
isLoading.value = false
isListLoading.value = purposeConsents.value?.isEmpty()
}
}
}
}
}
fun getDataAgreements(showProgress: Boolean, context: Context) {
if (PrivacyDashboardNetWorkUtil.isConnectedToInternet(context)) {
// isLoading.value = showProgress
val apiService: PrivacyDashboardAPIServices = PrivacyDashboardAPIManager.getApi(
apiKey = PrivacyDashboardDataUtils.getStringValue(
context,
PrivacyDashboardDataUtils.EXTRA_TAG_TOKEN,
null
),
accessToken = PrivacyDashboardDataUtils.getStringValue(
context,
PrivacyDashboardDataUtils.EXTRA_TAG_ACCESS_TOKEN,
null
),
baseUrl = PrivacyDashboardDataUtils.getStringValue(
context,
PrivacyDashboardDataUtils.EXTRA_TAG_BASE_URL
)
)?.service!!
val organizationDetailRepository = GetDataAgreementsApiRepository(apiService)
GlobalScope.launch {
val result = organizationDetailRepository.getOrganizationDetail(
PrivacyDashboardDataUtils.getStringValue(
context,
PrivacyDashboardDataUtils.EXTRA_TAG_USERID,
null
)
)
if (result.isSuccess) {
withContext(Dispatchers.Main) {
isListLoading.value = false
updateUI(result.getOrNull())
}
} else {
withContext(Dispatchers.Main) {
isListLoading.value = false
}
}
}
}
}
fun setOverallStatus(consent: PurposeConsent?, isChecked: Boolean?, context: Context) {
if (PrivacyDashboardNetWorkUtil.isConnectedToInternet(context)) {
isLoading.value = true
val body = ConsentStatusRequestV2()
body.optIn = isChecked == true
val apiService: PrivacyDashboardAPIServices = PrivacyDashboardAPIManager.getApi(
apiKey = PrivacyDashboardDataUtils.getStringValue(
context,
PrivacyDashboardDataUtils.EXTRA_TAG_TOKEN,
null
) ,
accessToken = PrivacyDashboardDataUtils.getStringValue(
context,
PrivacyDashboardDataUtils.EXTRA_TAG_ACCESS_TOKEN,
null
),
baseUrl = PrivacyDashboardDataUtils.getStringValue(
context,
PrivacyDashboardDataUtils.EXTRA_TAG_BASE_URL
)
)?.service!!
val updateDataAgreementStatusApiRepository =
UpdateDataAgreementStatusApiRepository(apiService)
GlobalScope.launch {
val result = updateDataAgreementStatusApiRepository.updateDataAgreementStatus(
userId = PrivacyDashboardDataUtils.getStringValue(
context,
PrivacyDashboardDataUtils.EXTRA_TAG_USERID,
null
),
dataAgreementId = consent?.purpose?.iD,
body = body
)
if (result.isSuccess) {
withContext(Dispatchers.Main) {
isLoading.value = false
// getDataAgreements(false, context)
updatePurposeConsent(result.getOrNull())
}
} else {
withContext(Dispatchers.Main) {
isLoading.value = false
}
}
}
} else {
// adapter!!.notifyDataSetChanged()
}
}
private fun updatePurposeConsent(record: DataAgreementLatestRecordResponseV2?) {
val count =
purposeConsents.value?.find { it.purpose?.iD == record?.dataAgreementRecord?.dataAgreementId }?.count?.total
purposeConsents.value?.find { it.purpose?.iD == record?.dataAgreementRecord?.dataAgreementId }?.count?.consented =
if (record?.dataAgreementRecord?.optIn == true) count else 0
purposeConsents.value = purposeConsents.value
}
fun getConsentList(consent: PurposeConsent?, context: Context) {
isLoading.value = true
if (PrivacyDashboardNetWorkUtil.isConnectedToInternet(context)) {
val apiService: PrivacyDashboardAPIServices = PrivacyDashboardAPIManager.getApi(
apiKey = PrivacyDashboardDataUtils.getStringValue(
context,
PrivacyDashboardDataUtils.EXTRA_TAG_TOKEN,
null
),
accessToken = PrivacyDashboardDataUtils.getStringValue(
context,
PrivacyDashboardDataUtils.EXTRA_TAG_ACCESS_TOKEN,
null
),
baseUrl = PrivacyDashboardDataUtils.getStringValue(
context,
PrivacyDashboardDataUtils.EXTRA_TAG_BASE_URL
)
)?.service!!
val consentListRepository = GetConsentsByIdApiRepository(apiService)
GlobalScope.launch {
val result = consentListRepository.getConsentsById(
userId = PrivacyDashboardDataUtils.getStringValue(
context,
PrivacyDashboardDataUtils.EXTRA_TAG_USERID,
null
),
dataAgreementId = consent?.purpose?.iD,
isAllAllowed = consent?.count?.consented == consent?.count?.total
)
if (result.isSuccess) {
withContext(Dispatchers.Main) {
isLoading.value = false
val intent = Intent(
context,
PrivacyDashboardDataAttributeListingActivity::class.java
)
intent.putExtra(
PrivacyDashboardDataAttributeListingActivity.TAG_EXTRA_NAME,
consent?.purpose?.name
)
intent.putExtra(
PrivacyDashboardDataAttributeListingActivity.TAG_EXTRA_DESCRIPTION,
consent?.purpose?.description
)
context.startActivity(intent)
PrivacyDashboardDataAttributeListingActivity.dataAttributesResponse =
result.getOrNull()
}
} else {
withContext(Dispatchers.Main) {
isLoading.value = false
}
}
}
}
}
} | 2 | Kotlin | 0 | 1 | cfe12a5047c92bba82ebb975d0c74b376824fa4e | 11,612 | privacy-dashboard-android | Apache License 2.0 |
mobius-base/src/main/java/org/simple/clinic/mobius/MobiusBaseViewModel.kt | simpledotorg | 132,515,649 | false | null | package org.simple.clinic.mobius
import android.os.Parcelable
import androidx.lifecycle.Observer
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.distinctUntilChanged
import com.spotify.mobius.Init
import com.spotify.mobius.MobiusLoop
import com.spotify.mobius.android.MobiusLoopViewModel
import com.spotify.mobius.android.runners.MainThreadWorkRunner
import com.spotify.mobius.functions.Consumer
import timber.log.Timber
private const val MAX_EFFECTS_QUEUE_SIZE = 100
class MobiusBaseViewModel<M : Parcelable, E, F, V>(
private val modelKey: String,
private val savedStateHandle: SavedStateHandle,
loopFactoryProvider: (Consumer<V>) -> MobiusLoop.Builder<M, E, F>,
defaultModel: M,
init: Init<M, F>,
) : MobiusLoopViewModel<M, E, F, V>(
loopFactoryProvider,
savedStateHandle.get<M>(modelKey) ?: defaultModel,
init,
MainThreadWorkRunner.create(),
MAX_EFFECTS_QUEUE_SIZE
) {
@get:JvmName("distinctSavedStateModels")
val models = savedStateHandle.getLiveData<M>(modelKey).distinctUntilChanged()
// At the time of writing, `MobiusLoopViewModel` function doesn't provide a public function
// to hook into model changes in the ViewModel. `onModelChanged` function is private.
// Instead we are observing the `getModels` livedata to update the saved state handle.
private val modelsObserver = Observer<M> {
val currentSavedModel = savedStateHandle.get<M>(modelKey)
if (currentSavedModel != it) {
savedStateHandle[modelKey] = it
}
}
init {
getModels().distinctUntilChanged().observeForever(modelsObserver)
}
override fun onClearedInternal() {
getModels().removeObserver(modelsObserver)
}
}
| 13 | null | 73 | 236 | ff699800fbe1bea2ed0492df484777e583c53714 | 1,698 | simple-android | MIT License |
libnavui-maneuver/src/main/java/com/mapbox/navigation/ui/maneuver/ManeuverAction.kt | liangxiaohit | 383,684,199 | true | {"Kotlin": 3195469, "Java": 94102, "Python": 11580, "Makefile": 6255, "Shell": 1686} | package com.mapbox.navigation.ui.maneuver
import com.mapbox.api.directions.v5.models.DirectionsRoute
import com.mapbox.api.directions.v5.models.RouteLeg
import com.mapbox.navigation.base.formatter.DistanceFormatter
import com.mapbox.navigation.base.trip.model.RouteProgress
internal sealed class ManeuverAction {
data class GetManeuverList(
val routeProgress: RouteProgress,
val maneuverState: ManeuverState,
val distanceFormatter: DistanceFormatter
) : ManeuverAction()
data class GetManeuverListWithRoute(
val route: DirectionsRoute,
val routeLeg: RouteLeg? = null,
val maneuverState: ManeuverState,
val distanceFormatter: DistanceFormatter
) : ManeuverAction()
}
| 0 | null | 0 | 0 | 02f5fb7db8113a776c0382e7d4c9dbffe9348ceb | 742 | mapbox-navigation-android | Apache License 2.0 |
app/src/main/java/eu/kanade/tachiyomi/ui/reader/ReaderChapterFilter.kt | Jays2Kings | 266,951,526 | false | null | package eu.kanade.tachiyomi.ui.reader
import eu.kanade.tachiyomi.data.database.models.Chapter
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.data.download.DownloadManager
import eu.kanade.tachiyomi.data.preference.PreferencesHelper
/**
* This class filters chapters for the reader based on the user enabled preferences and filters
*/
class ReaderChapterFilter(
private val downloadManager: DownloadManager,
private val preferences: PreferencesHelper
) {
fun filterChapter(
dbChapters: List<Chapter>,
manga: Manga,
selectedChapter: Chapter? = null
): List<Chapter> {
// if neither preference is enabled don't even filter
if (!preferences.skipRead() && !preferences.skipFiltered()) {
return dbChapters
}
var filteredChapters = dbChapters
if (preferences.skipRead()) {
filteredChapters = filteredChapters.filter { !it.read }
}
if (preferences.skipFiltered()) {
val readEnabled = manga.readFilter == Manga.SHOW_READ
val unreadEnabled = manga.readFilter == Manga.SHOW_UNREAD
val downloadEnabled = manga.downloadedFilter == Manga.SHOW_DOWNLOADED
val bookmarkEnabled = manga.bookmarkedFilter == Manga.SHOW_BOOKMARKED
// if none of the filters are enabled skip the filtering of them
if (readEnabled || unreadEnabled || downloadEnabled || bookmarkEnabled) {
filteredChapters = filteredChapters.filter {
if (readEnabled && it.read.not() ||
(unreadEnabled && it.read) ||
(bookmarkEnabled && it.bookmark.not()) ||
(downloadEnabled && downloadManager.isChapterDownloaded(it, manga).not())
) {
return@filter false
}
return@filter true
}
}
}
// add the selected chapter to the list in case it was filtered out
if (selectedChapter?.id != null) {
val find = filteredChapters.find { it.id == selectedChapter.id }
if (find == null) {
val mutableList = filteredChapters.toMutableList()
mutableList.add(selectedChapter)
filteredChapters = mutableList.toList()
}
}
return filteredChapters
}
}
| 0 | null | 1 | 18 | 3ef4505f43bc0084ddd73347a220f0ec8a455961 | 2,455 | Neko | Apache License 2.0 |
debugger/server/src/commonMain/kotlin/pro/respawn/flowmvi/debugger/server/navigation/util/DestinationLocals.kt | respawn-app | 477,143,989 | false | {"Kotlin": 497111} | package pro.respawn.flowmvi.debugger.server.navigation.util
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import org.koin.compose.LocalKoinScope
import pro.respawn.flowmvi.compose.dsl.LocalSubscriberLifecycle
import pro.respawn.flowmvi.compose.dsl.rememberSubscriberLifecycle
import pro.respawn.flowmvi.debugger.server.di.LocalDestinationScope
import pro.respawn.flowmvi.debugger.server.navigation.component.DestinationComponent
import pro.respawn.flowmvi.essenty.lifecycle.asSubscriberLifecycle
@Composable
internal fun ProvideDestinationLocals(
component: DestinationComponent,
content: @Composable () -> Unit
) = CompositionLocalProvider(
LocalSubscriberLifecycle provides rememberSubscriberLifecycle(component.lifecycle) { asSubscriberLifecycle },
LocalDestinationScope provides component,
LocalKoinScope provides component.scope,
content = content,
)
| 10 | Kotlin | 10 | 305 | 80ea0a5eedc948fe50d3f23ddce041d8144f0f23 | 936 | FlowMVI | Apache License 2.0 |
plugins/filePrediction/src/com/intellij/filePrediction/FilePredictionNotifications.kt | ingokegel | 72,937,917 | true | 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 com.intellij.filePrediction
import com.intellij.notification.NotificationGroupManager
import com.intellij.notification.NotificationType
import com.intellij.openapi.project.Project
import org.jetbrains.annotations.Nls
internal object FilePredictionNotifications {
private val NOTIFICATION_GROUP = NotificationGroupManager.getInstance().getNotificationGroup("NextFilePrediction")
fun showWarning(project: Project?, @Nls message: String) {
showNotification(project, NotificationType.WARNING, message)
}
fun showInfo(project: Project?, @Nls message: String) {
showNotification(project, NotificationType.INFORMATION, message)
}
private fun showNotification(project: Project?, type: NotificationType, @Nls message: String) {
val title = FilePredictionBundle.message("file.prediction.notification.group.title")
NOTIFICATION_GROUP.createNotification(title, message, type).notify(project)
}
} | 1 | null | 1 | 2 | b07eabd319ad5b591373d63c8f502761c2b2dfe8 | 1,068 | intellij-community | Apache License 2.0 |
src/main/kotlin/github/comiccorps/kilowog/services/comicvine/volume/Volume.kt | Buried-In-Code | 674,466,125 | false | {"Kotlin": 165736} | package github.comiccorps.kilowog.services.comicvine.volume
import github.comiccorps.kilowog.LocalDateTimeSerializer
import github.comiccorps.kilowog.services.comicvine.GenericEntry
import github.comiccorps.kilowog.services.comicvine.Image
import github.comiccorps.kilowog.services.comicvine.IssueEntry
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.JsonNames
import java.time.LocalDateTime
@OptIn(ExperimentalSerializationApi::class)
@Serializable
data class Volume(
val aliases: String? = null,
@JsonNames("api_detail_url")
val apiUrl: String,
@Serializable(with = LocalDateTimeSerializer::class)
val dateAdded: LocalDateTime,
@Serializable(with = LocalDateTimeSerializer::class)
val dateLastUpdated: LocalDateTime,
val description: String? = null,
val firstIssue: IssueEntry? = null,
val id: Long,
val image: Image,
@JsonNames("count_of_issues")
val issueCount: Int,
val lastIssue: IssueEntry? = null,
val name: String,
val publisher: GenericEntry? = null,
@JsonNames("site_detail_url")
val siteUrl: String,
val startYear: Int? = null,
@JsonNames("deck")
val summary: String? = null,
val characters: List<CountEntry> = emptyList(),
val concepts: List<CountEntry> = emptyList(),
@JsonNames("people")
val creators: List<CountEntry> = emptyList(),
val issues: List<IssueEntry> = emptyList(),
val locations: List<CountEntry> = emptyList(),
val objects: List<CountEntry> = emptyList(),
) {
@Serializable
data class CountEntry(
@JsonNames("api_detail_url")
val apiUrl: String,
val id: Long,
val name: String? = null,
@JsonNames("site_detail_url")
val siteUrl: String? = null,
val count: Int,
)
}
| 0 | Kotlin | 0 | 1 | 09d24bb1aaed446a89f3de81905ef75ef4019d15 | 1,862 | Kilowog | MIT License |
Base/src/main/java/xy/xy/base/widget/recycler/listener/OnChildItemLongClickListener.kt | xiuone | 291,512,847 | false | {"Kotlin": 696966, "Java": 245782} | package xy.xy.base.widget.recycler.listener
import android.view.View
import xy.xy.base.widget.recycler.holder.BaseViewHolder
interface OnChildItemLongClickListener<T>{
fun onItemChildLongClick(view:View,data:T, holder: BaseViewHolder?):Boolean
} | 0 | Kotlin | 1 | 2 | dc9f035dae4c876c6acb3e2e96742d5eb5cebe18 | 251 | ajinlib | Apache License 2.0 |
twitlin/src/common/test/kotlin/com/sorrowblue/twitlin/users/AccountApiTest.kt | SorrowBlue | 278,215,181 | false | null | package com.sorrowblue.twitlin.users
import com.sorrowblue.twitlin.Twitlin
import com.sorrowblue.twitlin.users.account.AccountApi
import kotlin.test.Test
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runTest
import test.AbstractTest
import test.resultLog
@ExperimentalCoroutinesApi
class AccountApiTest : AbstractTest {
private val accountApi = Twitlin.getApi<AccountApi>(oauth1aClient)
@Test
fun verifyCredentialsTest() = runTest {
accountApi.verifyCredentials(
includeEntities = true,
includeEmail = true,
skipStatus = false
).resultLog()
}
@Test
fun settingTest() = runTest { accountApi.settings().resultLog() }
@Test
fun updateProfileLinkColorTest() = runTest {
accountApi.updateProfile(
profileLinkColor = "FF0000"
).resultLog()
}
}
| 0 | Kotlin | 0 | 1 | d6a3fdf66dea3d44f95e6800d35031d9339293cd | 897 | Twitlin | MIT License |
src/nativeTest/kotlin/SortedArrayList.kt | alex-s168 | 751,722,987 | false | {"Kotlin": 51939, "C": 1521} | import me.alex_s168.kollektions.SortedArrayList
import kotlin.test.Test
import kotlin.test.assertEquals
@Test
fun testSortedArrayList() {
val sar = SortedArrayList<Int, Int> { it }
sar += 5
sar += 9
sar += 2
sar += 3
sar += 10
assertEquals(sar[0], 2)
assertEquals(sar[1], 3)
assertEquals(sar[2], 5)
assertEquals(sar[3], 9)
assertEquals(sar[4], 10)
} | 0 | Kotlin | 0 | 0 | 7c59abf07af1dfd277223c65aa55d8870ba76183 | 396 | kjit | Apache License 2.0 |
app/src/main/java/dev/shorthouse/coinwatch/di/NetworkDataModule.kt | shorthouse | 655,260,745 | false | null | package dev.shorthouse.coinwatch.di
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import dev.shorthouse.coinwatch.data.mapper.CoinChartMapper
import dev.shorthouse.coinwatch.data.mapper.CoinDetailMapper
import dev.shorthouse.coinwatch.data.mapper.CoinMapper
import dev.shorthouse.coinwatch.data.repository.chart.CoinChartRepository
import dev.shorthouse.coinwatch.data.repository.chart.CoinChartRepositoryImpl
import dev.shorthouse.coinwatch.data.repository.coin.CoinRepository
import dev.shorthouse.coinwatch.data.repository.coin.CoinRepositoryImpl
import dev.shorthouse.coinwatch.data.repository.detail.CoinDetailRepository
import dev.shorthouse.coinwatch.data.repository.detail.CoinDetailRepositoryImpl
import dev.shorthouse.coinwatch.data.source.remote.CoinApi
import dev.shorthouse.coinwatch.data.source.remote.CoinNetworkDataSourceImpl
import javax.inject.Singleton
import kotlinx.coroutines.CoroutineDispatcher
@Module
@InstallIn(SingletonComponent::class)
object NetworkDataModule {
@Provides
@Singleton
fun provideCoinRepository(
coinNetworkDataSource: CoinNetworkDataSourceImpl,
coinMapper: CoinMapper,
@IoDispatcher ioDispatcher: CoroutineDispatcher
): CoinRepository {
return CoinRepositoryImpl(
coinNetworkDataSource = coinNetworkDataSource,
ioDispatcher = ioDispatcher,
coinMapper = coinMapper
)
}
@Provides
@Singleton
fun provideCoinDetailRepository(
coinNetworkDataSource: CoinNetworkDataSourceImpl,
coinDetailMapper: CoinDetailMapper,
@IoDispatcher ioDispatcher: CoroutineDispatcher
): CoinDetailRepository {
return CoinDetailRepositoryImpl(
coinNetworkDataSource = coinNetworkDataSource,
coinDetailMapper = coinDetailMapper,
ioDispatcher = ioDispatcher
)
}
@Provides
@Singleton
fun provideCoinChartRepository(
coinNetworkDataSource: CoinNetworkDataSourceImpl,
coinChartMapper: CoinChartMapper,
@IoDispatcher ioDispatcher: CoroutineDispatcher
): CoinChartRepository {
return CoinChartRepositoryImpl(
coinNetworkDataSource = coinNetworkDataSource,
coinChartMapper = coinChartMapper,
ioDispatcher = ioDispatcher
)
}
@Provides
@Singleton
fun provideCoinNetworkDataSource(coinApi: CoinApi): CoinNetworkDataSourceImpl {
return CoinNetworkDataSourceImpl(coinApi = coinApi)
}
}
| 0 | null | 0 | 4 | 6059a9e9c08add44975af25c96d9632f58d613bd | 2,582 | CoinWatch | Apache License 2.0 |
app/src/main/kotlin/com/hiczp/spaceengineers/remoteclient/android/activity/MainActivity.kt | czp3009 | 202,709,016 | false | null | package com.hiczp.spaceengineers.remoteclient.android.activity
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.Gravity
import android.widget.ImageButton
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.observe
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.appbar.AppBarLayout
import com.hiczp.spaceengineers.remoteclient.android.*
import com.hiczp.spaceengineers.remoteclient.android.adapter.ProfileListAdapter
import com.hiczp.spaceengineers.remoteclient.android.extension.horizontalRecyclerView
import com.hiczp.spaceengineers.remoteclient.android.layout.defaultAppBar
import org.jetbrains.anko.*
import org.jetbrains.anko.constraint.layout.constraintLayout
import org.jetbrains.anko.design.coordinatorLayout
import org.jetbrains.anko.design.floatingActionButton
import org.jetbrains.anko.sdk27.coroutines.onClick
class MainActivity : AppCompatActivity() {
private lateinit var model: ProfileListViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
model = ViewModelProvider(this)[ProfileListViewModel::class.java]
lateinit var createButton: ImageButton
lateinit var recycleView: RecyclerView
coordinatorLayout {
defaultAppBar().lparams(matchParent)
constraintLayout {
recycleView = horizontalRecyclerView().lparams(matchParent)
}.lparams(matchParent) {
behavior = AppBarLayout.ScrollingViewBehavior()
}
createButton = floatingActionButton {
setImageResource(R.drawable.ic_add_white)
}.lparams {
gravity = Gravity.END + Gravity.BOTTOM
margin = dip(12)
}
}
model.creating.observe(this) {
createButton.isEnabled = !it
}
createButton.onClick {
model.creating.value = true
startActivityForResult<ProfileActivity>(0)
}
val profileListAdapter = ProfileListAdapter(
model.opening,
onDelete = { model.delete(it) },
onOpen = { startActivity<VRageActivity>(VRageActivity.inputValue to it) },
onModify = {
startActivityForResult<ProfileActivity>(
0,
ProfileActivity.inputValue to it
)
}
)
recycleView.adapter = profileListAdapter
// recycleView.swipeToDismiss {
// profileListAdapter.notifyItemRemoved(it)
// }
model.profiles.observe(this) {
profileListAdapter.setProfiles(it)
}
}
override fun onResume() {
super.onResume()
model.opening.postValue(false)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
model.creating.postValue(false)
if (resultCode != Activity.RESULT_OK) return
val newProfile = data!!.extras!!.get(ProfileActivity.returnValue) as Profile
model.save(newProfile)
}
}
class ProfileListViewModel : ViewModel() {
val profiles: MutableLiveData<List<Profile>> = MutableLiveData()
val creating = MutableLiveData(false)
val opening = MutableLiveData(false)
init {
pullData()
}
private fun pullData() {
profiles.postValue(database.use { findAll() })
}
fun save(profile: Profile) {
database.use { save(profile) }
pullData()
}
fun delete(profile: Profile) {
database.use { deleteById(profile.id!!) }
pullData()
}
}
| 0 | Kotlin | 2 | 7 | 22c1cbaf6d1b4d90ff73ebc2681a42a1d7c9bee1 | 3,869 | SpaceEngineersRemoteClient | Apache License 2.0 |
app/src/main/java/com/niravtukadiya/compat/biometric/sample/MainActivity.kt | nirav-tukadiya | 141,876,146 | true | {"Kotlin": 22646} | package com.niravtukadiya.compat.biometric.sample
import android.os.Bundle
import android.widget.Toast
import com.niravtukadiya.compat.biometric.BiometricCallback
import com.niravtukadiya.compat.biometric.BiometricCompat
import androidx.appcompat.app.AppCompatActivity
import com.niravtukadiya.compat.biometric.BiometricError
import kotlinx.android.synthetic.main.activity_main.*
/**
* Created by <NAME> on 22/07/18 8:58 PM.
* <EMAIL>
*/
class MainActivity : AppCompatActivity(), BiometricCallback {
override fun onPreConditionsFailed(error: BiometricError) {
when(error){
BiometricError.ON_SDK_NOT_SUPPORTED -> Toast.makeText(applicationContext, getString(R.string.biometric_error_sdk_not_supported), Toast.LENGTH_LONG).show()
BiometricError.ON_BIOMETRIC_AUTH_NOT_SUPPORTED -> Toast.makeText(applicationContext, getString(R.string.biometric_error_hardware_not_supported), Toast.LENGTH_LONG).show()
BiometricError.ON_BIOMETRIC_AUTH_NOT_AVAILABLE -> Toast.makeText(applicationContext, getString(R.string.biometric_error_fingerprint_not_available), Toast.LENGTH_LONG).show()
BiometricError.ON_BIOMETRIC_AUTH_PERMISSION_NOT_GRANTED -> Toast.makeText(applicationContext, getString(R.string.biometric_error_permission_not_granted), Toast.LENGTH_LONG).show()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
btn_authenticate.setOnClickListener {
BiometricCompat.BiometricBuilder(this)
.setTitle(getString(R.string.biometric_title))
.setLayout(R.layout.custom_view_bottom_sheet)
.setSubtitle(getString(R.string.biometric_subtitle))
.setDescription(getString(R.string.biometric_description))
.setNegativeButtonText(getString(R.string.biometric_negative_button_text))
.build()
.authenticate(this)
}
}
override fun onBiometricAuthenticationInternalError(error: String?) {
Toast.makeText(applicationContext, error, Toast.LENGTH_LONG).show()
}
override fun onAuthenticationFailed() {
// Toast.makeText(getApplicationContext(), getString(R.string.biometric_failure), Toast.LENGTH_LONG).show();
}
override fun onAuthenticationCancelled() {
Toast.makeText(applicationContext, getString(R.string.biometric_cancelled), Toast.LENGTH_LONG).show()
}
override fun onAuthenticationSuccessful() {
Toast.makeText(applicationContext, getString(R.string.biometric_success), Toast.LENGTH_LONG).show()
}
override fun onAuthenticationHelp(helpCode: Int, helpString: CharSequence?) {
// Toast.makeText(getApplicationContext(), helpString, Toast.LENGTH_LONG).show();
}
override fun onAuthenticationError(errorCode: Int, errString: CharSequence?) {
// Toast.makeText(getApplicationContext(), errString, Toast.LENGTH_LONG).show();
}
}
| 2 | Kotlin | 1 | 6 | b655d12bf59606de54b3cb0192e6d4311210cef6 | 3,081 | Biometric-Compat | Apache License 2.0 |
rsocket-transports/netty-quic/src/jvmMain/kotlin/io/rsocket/kotlin/transport/netty/quic/NettyQuicStreamHandler.kt | rsocket | 109,894,810 | false | {"Kotlin": 628647, "JavaScript": 203} | /*
* Copyright 2015-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.rsocket.kotlin.transport.netty.quic
import io.ktor.utils.io.core.*
import io.netty.buffer.*
import io.netty.channel.*
import io.netty.channel.socket.*
import io.netty.incubator.codec.quic.*
import io.rsocket.kotlin.internal.io.*
import io.rsocket.kotlin.transport.*
import io.rsocket.kotlin.transport.netty.internal.*
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
import kotlinx.coroutines.channels.Channel
// TODO: first stream is a hack to initiate first stream because of buffering
// quic streams could be received unordered by server, so f.e we could receive first stream with id 4 and then with id 0
// for this, we disable buffering for first client stream, so that first frame will be sent first
// this will affect performance for this stream, so we need to do something else here.
@RSocketTransportApi
internal class NettyQuicStreamState(val startMarker: CompletableJob?) {
val closeMarker: CompletableJob = Job()
val outbound = channelForCloseable<ByteReadPacket>(Channel.BUFFERED)
val inbound = channelForCloseable<ByteReadPacket>(Channel.UNLIMITED)
fun wrapStream(stream: QuicStreamChannel): RSocketMultiplexedConnection.Stream =
NettyQuicStream(stream, outbound, inbound, closeMarker)
}
@RSocketTransportApi
internal class NettyQuicStreamHandler(
private val channel: QuicStreamChannel,
scope: CoroutineScope,
private val state: NettyQuicStreamState,
private val isClient: Boolean,
) : ChannelInboundHandlerAdapter() {
private val handlerJob = scope.launch(start = CoroutineStart.LAZY) {
val outbound = state.outbound
val writerJob = launch(start = CoroutineStart.UNDISPATCHED) {
try {
while (true) {
// we write all available frames here, and only after it flush
// in this case, if there are several buffered frames we can send them in one go
// avoiding unnecessary flushes
// TODO: could be optimized to avoid allocation of not-needed promises
var lastWriteFuture = channel.write(outbound.receiveCatching().getOrNull()?.toByteBuf() ?: break)
while (true) lastWriteFuture = channel.write(outbound.tryReceive().getOrNull()?.toByteBuf() ?: break)
//println("FLUSH: $isClient: ${channel.streamId()}")
channel.flush()
// await writing to respect transport backpressure
lastWriteFuture.awaitFuture()
state.startMarker?.complete()
}
} finally {
withContext(NonCancellable) {
channel.shutdownOutput().awaitFuture()
}
}
}.onCompletion { outbound.cancel() }
try {
state.closeMarker.join()
} finally {
outbound.close() // will cause `writerJob` completion
// no more reading
state.inbound.cancel()
withContext(NonCancellable) {
writerJob.join()
// TODO: what is the correct way to properly shutdown stream?
channel.shutdownInput().awaitFuture()
channel.close().awaitFuture()
}
}
}
override fun channelActive(ctx: ChannelHandlerContext) {
handlerJob.start()
ctx.pipeline().addLast("rsocket-inbound", NettyQuicStreamInboundHandler(state.inbound))
ctx.fireChannelActive()
}
override fun channelInactive(ctx: ChannelHandlerContext) {
handlerJob.cancel("Channel is not active")
ctx.fireChannelInactive()
}
@Suppress("OVERRIDE_DEPRECATION")
override fun exceptionCaught(ctx: ChannelHandlerContext, cause: Throwable?) {
handlerJob.cancel("exceptionCaught", cause)
}
}
private class NettyQuicStreamInboundHandler(
private val inbound: SendChannel<ByteReadPacket>,
) : ChannelInboundHandlerAdapter() {
override fun channelRead(ctx: ChannelHandlerContext, msg: Any) {
msg as ByteBuf
try {
val frame = msg.toByteReadPacket()
if (inbound.trySend(frame).isFailure) {
frame.close()
}
} finally {
msg.release()
}
}
override fun userEventTriggered(ctx: ChannelHandlerContext?, evt: Any?) {
if (evt is ChannelInputShutdownEvent) {
inbound.close()
}
super.userEventTriggered(ctx, evt)
}
}
@RSocketTransportApi
private class NettyQuicStream(
// for priority
private val stream: QuicStreamChannel,
private val outbound: SendChannel<ByteReadPacket>,
private val inbound: ReceiveChannel<ByteReadPacket>,
private val closeMarker: CompletableJob,
) : RSocketMultiplexedConnection.Stream {
@OptIn(DelicateCoroutinesApi::class)
override val isClosedForSend: Boolean get() = outbound.isClosedForSend
override fun setSendPriority(priority: Int) {
stream.updatePriority(QuicStreamPriority(priority, false))
}
override suspend fun sendFrame(frame: ByteReadPacket) {
outbound.send(frame)
}
override suspend fun receiveFrame(): ByteReadPacket? {
return inbound.receiveCatching().getOrNull()
}
override fun close() {
closeMarker.complete()
}
}
| 23 | Kotlin | 37 | 550 | b7f27ba4c3a0d639d375731231f347e595ed307c | 5,984 | rsocket-kotlin | Apache License 2.0 |
zircon.core/src/commonMain/kotlin/org/hexworks/zircon/api/dsl/component/Dsls.kt | EdaKalabak | 385,504,580 | true | {"Kotlin": 1760072, "Java": 118844, "Shell": 152} | package org.hexworks.zircon.api.dsl.component
import org.hexworks.zircon.api.component.Component
import org.hexworks.zircon.api.component.builder.ComponentBuilder
import org.hexworks.zircon.api.component.builder.base.BaseContainerBuilder
internal fun <T : Component, B : ComponentBuilder<T, B>> buildChildFor(
parent: BaseContainerBuilder<*, *>,
builder: B,
init: B.() -> Unit
): T {
val result = builder.apply(init).build()
parent.withAddedChildren(result)
return result
} | 0 | null | 0 | 0 | 8143a56d9c82c07cb1a91dcb4cf355bd2afe45cc | 499 | zircon | Apache License 2.0 |
app/src/main/java/live/hms/app2/ui/meeting/MeetingActivity.kt | 100mslive | 330,654,934 | false | null | package live.hms.app2.ui.meeting
import android.annotation.SuppressLint
import android.content.res.Configuration
import android.graphics.Color
import android.os.Bundle
import android.view.Menu
import android.view.View
import android.view.WindowManager
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.view.menu.MenuBuilder
import androidx.core.view.forEach
import androidx.navigation.NavController
import androidx.navigation.fragment.NavHostFragment
import live.hms.app2.R
import live.hms.app2.databinding.ActivityMeetingBinding
import live.hms.app2.model.RoomDetails
import live.hms.app2.ui.settings.SettingsStore
import live.hms.app2.util.ROOM_DETAILS
class MeetingActivity : AppCompatActivity() {
private var _binding: ActivityMeetingBinding? = null
private val binding: ActivityMeetingBinding
get() = _binding!!
var settingsStore : SettingsStore? = null
private val meetingViewModel: MeetingViewModel by viewModels {
MeetingViewModelFactory(
application,
intent!!.extras!![ROOM_DETAILS] as RoomDetails
)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
_binding = ActivityMeetingBinding.inflate(layoutInflater)
setContentView(binding.root)
supportActionBar?.setDisplayShowTitleEnabled(false)
settingsStore = SettingsStore(this)
val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
val navController = navHostFragment.navController
val topFragment = navHostFragment.childFragmentManager.fragments.firstOrNull()
if (settingsStore?.showPreviewBeforeJoin == true && (topFragment is MeetingFragment).not()) {
navController?.setGraph(R.navigation.preview_nav_graph)
} else {
navController?.setGraph(R.navigation.meeting_nav_graph)
}
initViewModels()
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
}
override fun onDestroy() {
super.onDestroy()
_binding = null
}
private fun initViewModels() {
meetingViewModel.title.observe(this) {
}
meetingViewModel.isRecording.observe(this) {
invalidateOptionsMenu()
}
}
}
| 19 | null | 27 | 73 | 0d72314bb1f6b837eb60205cc52dd93879466d69 | 2,231 | 100ms-android | MIT License |
ui-lib-navigation/src/main/kotlin/com/purewowstudio/bodystats/ui/navigation/di/NavModule.kt | phillwiggins | 497,633,079 | false | {"Kotlin": 263828, "Shell": 443} | package com.purewowstudio.bodystats.ui.navigation.di
import com.purewowstudio.bodystats.ui.navigation.NavigationManager
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
class NavModule {
@Singleton
@Provides
fun providesNavigationManager() = NavigationManager()
} | 0 | Kotlin | 1 | 8 | 41a56fb6a7f4fade0806b8fda3cf20a8f6b5a306 | 427 | bodystats | Apache License 2.0 |
bert_qa/app/src/main/java/org/tensorflow/lite/examples/bertqa/ui/QuestionAdapter.kt | SunitRoy2703 | 405,389,854 | false | {"Kotlin": 441677, "Java": 11281} | /* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
package org.tensorflow.lite.examples.bertqa.ui
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.chip.Chip
import org.tensorflow.lite.examples.bertqa.R
import org.tensorflow.lite.examples.bertqa.ui.QuestionAdapter.MyViewHolder
/** Adapter class to show question suggestion chips. */
class QuestionAdapter(context: Context?, questions: Array<String>) :
RecyclerView.Adapter<MyViewHolder>() {
private val inflater: LayoutInflater
private val questions: Array<String>
private var onQuestionSelectListener: OnQuestionSelectListener? = null
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val view =
inflater.inflate(R.layout.tfe_qa_question_chip, parent, false)
return MyViewHolder(view)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
holder.chip.text = questions[position]
holder.chip.setOnClickListener { view: View? ->
onQuestionSelectListener!!.onQuestionSelect(
questions[position]
)
}
}
override fun getItemCount(): Int {
return questions.size
}
fun setOnQuestionSelectListener(onQuestionSelectListener: OnQuestionSelectListener?) {
this.onQuestionSelectListener = onQuestionSelectListener
}
inner class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var chip: Chip
init {
chip = itemView.findViewById(R.id.chip)
}
}
/** Interface for callback when a question is selected. */
interface OnQuestionSelectListener {
fun onQuestionSelect(question: String?)
}
init {
inflater = LayoutInflater.from(context)
this.questions = questions
}
} | 2 | Kotlin | 11 | 37 | c7628b3e58d9ae1ff902f4a9ff0142a051f91958 | 2,593 | Tensorflow-lite-kotlin-samples | Apache License 2.0 |
core/domain/src/main/kotlin/com/espressodev/gptmap/core/domain/SignInUpWithGoogleUseCase.kt | f-arslan | 714,072,263 | false | {"Kotlin": 312117, "Dockerfile": 852} | package com.espressodev.gptmap.core.domain
import android.util.Log
import com.espressodev.gptmap.core.data.FirestoreService
import com.espressodev.gptmap.core.google_auth.GoogleAuthService
import com.espressodev.gptmap.core.google_auth.OneTapSignInUpResponse
import com.espressodev.gptmap.core.google_auth.SignInUpWithGoogleResponse
import com.espressodev.gptmap.core.model.Exceptions.FirebaseDisplayNameNullException
import com.espressodev.gptmap.core.model.Exceptions.FirebaseEmailNullException
import com.espressodev.gptmap.core.model.Exceptions.FirebasePhotoUrlNullException
import com.espressodev.gptmap.core.model.Exceptions.FirebaseUserIdIsNullException
import com.espressodev.gptmap.core.model.Provider
import com.espressodev.gptmap.core.model.User
import com.espressodev.gptmap.core.model.ext.classTag
import com.espressodev.gptmap.core.model.google.GoogleResponse
import com.espressodev.gptmap.core.mongodb.RealmAccountService
import com.google.firebase.auth.AuthCredential
import com.google.firebase.auth.AuthResult
import com.google.firebase.auth.FirebaseAuthException
import com.google.firebase.auth.FirebaseUser
import io.realm.kotlin.exceptions.RealmException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.tasks.await
import kotlinx.coroutines.withContext
import java.io.IOException
import javax.inject.Inject
class SignInUpWithGoogleUseCase @Inject constructor(
private val googleAuthService: GoogleAuthService,
private val realmAccountService: RealmAccountService,
private val firestoreService: FirestoreService,
) {
suspend fun oneTapSignUpWithGoogle(): OneTapSignInUpResponse =
withContext(Dispatchers.IO) {
googleAuthService.oneTapSignUpWithGoogle()
}
suspend fun oneTapSignInWithGoogle(): OneTapSignInUpResponse =
withContext(Dispatchers.IO) {
googleAuthService.oneTapSignInWithGoogle()
}
suspend fun firebaseSignInUpWithGoogle(googleCredential: AuthCredential): SignInUpWithGoogleResponse =
withContext(Dispatchers.IO) {
try {
val authResult = googleAuthService.firebaseSignInWithGoogle(googleCredential)
loginToRealm(authResult)
addUserToDatabaseIfUserIsNew(authResult)
GoogleResponse.Success(data = true)
} catch (e: FirebaseAuthException) {
Log.e(classTag(), "Firebase auth exception", e)
GoogleResponse.Failure(e)
} catch (e: RealmException) {
Log.e(classTag(), "Realm exception", e)
GoogleResponse.Failure(e)
} catch (e: IOException) {
Log.e(classTag(), "I/O exception", e)
GoogleResponse.Failure(e)
}
}
private suspend fun loginToRealm(authResult: AuthResult) {
authResult.user?.getIdToken(true)?.await()?.token?.let {
realmAccountService.loginWithEmail(it).getOrThrow()
} ?: throw FirebaseUserIdIsNullException()
}
private fun addUserToDatabaseIfUserIsNew(authResult: AuthResult) {
authResult.additionalUserInfo?.isNewUser?.also {
if (it) {
authResult.user?.also { user ->
addUserToFirestore(user).getOrThrow()
}
}
}
}
private fun addUserToFirestore(firebaseUser: FirebaseUser): Result<Boolean> {
firebaseUser.apply {
val displayName = displayName ?: throw FirebaseDisplayNameNullException()
val email = email ?: throw FirebaseEmailNullException()
val photoUrl = photoUrl ?: throw FirebasePhotoUrlNullException()
val user =
User(
userId = uid,
fullName = displayName,
email = email,
provider = Provider.GOOGLE.name,
profilePictureUrl = photoUrl.toString(),
)
firestoreService.saveUser(user)
}
return Result.success(value = true)
}
}
| 0 | Kotlin | 0 | 2 | dcc8c8c7a2d40a19e08dd7c4f1c56c7d18e59518 | 4,066 | GptMap | MIT License |
Meld-Module-World/src/main/kotlin/io/github/daylightnebula/meld/world/World.kt | DaylightNebula | 652,923,400 | false | null | package io.github.daylightnebula.meld.world
import io.github.daylightnebula.meld.entities.Entity
import io.github.daylightnebula.meld.entities.EntityType
import io.github.daylightnebula.meld.server.events.EventBus
import io.github.daylightnebula.meld.world.chunks.FilledSection
import io.github.daylightnebula.meld.world.chunks.FlexiblePalette
import io.github.daylightnebula.meld.world.chunks.Section
import io.github.daylightnebula.meld.world.chunks.chunk
import org.cloudburstmc.math.vector.Vector3f
import org.cloudburstmc.math.vector.Vector3i
object World {
val dimensions = hashMapOf(
dimension(
"overworld",
*(0..10000).map { index ->
// create chunk
val x = index / 100
val y = index % 100
val chunk = chunk(
x - 50,
y - 50,
"overworld",
Array(24) { idx ->
FilledSection(if (idx < 6) FlexiblePalette.filled(79) else FlexiblePalette.filled())
}
)
// return chunk
chunk
}.toTypedArray()
)
)
fun getBlock(dimension: String, position: Vector3i) = dimensions[dimension]?.getBlock(position)
fun setBlock(dimension: String, position: Vector3i, blockID: Int) = dimensions[dimension]?.setBlock(position, blockID)
fun fillBlocks(dimension: String, from: Vector3i, to: Vector3i, blockID: Int) = dimensions[dimension]?.fillBlocks(from, to, blockID)
fun clearBlocks(dimension: String, from: Vector3i, to: Vector3i) = dimensions[dimension]?.clearBlocks(from, to)
fun getBlock(dimension: Dimension, position: Vector3i) = dimension.getBlock(position)
fun setBlock(dimension: Dimension, position: Vector3i, blockID: Int) = dimension.setBlock(position, blockID)
fun fillBlocks(dimension: Dimension, from: Vector3i, to: Vector3i, blockID: Int) = dimension.fillBlocks(from, to, blockID)
fun clearBlocks(dimension: Dimension, from: Vector3i, to: Vector3i) = dimension.clearBlocks(from, to)
fun init() {}
} | 0 | null | 0 | 1 | 2290a5266ae56ef2e59cad88fc1f38e825b2cc88 | 2,129 | Meld | Apache License 2.0 |
src/main/java/io/collapp/model/StatisticForExport.kt | devendarsai | 428,018,987 | false | {"Text": 16, "JSON": 3, "Ruby": 1, "Maven POM": 1, "Markdown": 28, "JavaScript": 319, "HTML": 245, "CSS": 182, "SVG": 168, "XML": 8, "INI": 4, "Java Properties": 4, "SQL": 225, "PLpgSQL": 3, "Java": 234, "Batchfile": 3, "Fluent": 1, "Shell": 1, "YAML": 2, "Kotlin": 87, "Puppet": 3} |
package io.collapp.model
import ch.digitalfondue.npjt.ConstructorAnnotationRowMapper.Column
import io.collapp.model.BoardColumn.BoardColumnLocation
import java.util.*
class StatisticForExport(@Column("BOARD_STATISTICS_TIME") val date: Date,
@Column("BOARD_COLUMN_DEFINITION_VALUE") val columnDefinition: ColumnDefinition,
@Column("BOARD_STATISTICS_LOCATION") val location: BoardColumnLocation,
@Column("BOARD_STATISTICS_COUNT") val count: Long)
| 1 | null | 1 | 1 | 74f22288043be85066d4d653267d987daa37b554 | 523 | CollApp | MIT License |
features/core/command/lib/src/test/java/command/strategy/AddToEndSingleStrategyTest.kt | game-x50 | 361,364,864 | false | null | package command.strategy
import com.ruslan.hlushan.core.command.strategy.AddToEndSingleStrategy
import com.ruslan.hlushan.core.extensions.withoutFirst
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotEquals
import org.junit.Test
@SuppressWarnings("MaxLineLength")
class AddToEndSingleStrategyTest {
@Test
fun `beforeApply removes single instance of command class if there are another commands after in state and adds new command`() {
val (oldState, incomingCommand) = `create state contains single instance of command class and another commands after`()
val newState = AddToEndSingleStrategy().beforeApply(oldState, incomingCommand)
val expectedNewState = oldState.drop(1).plus(incomingCommand)
assertNotEquals(oldState, newState)
assertEquals(expectedNewState, newState)
}
@Test
fun `beforeApply removes single instance of command class if there are another commands before in state and adds new command`() {
val (oldState, incomingCommand) = `create state contains single instance of command class and another commands before`()
val newState = AddToEndSingleStrategy().beforeApply(oldState, incomingCommand)
val expectedNewState = oldState.dropLast(1).plus(incomingCommand)
assertNotEquals(oldState, newState)
assertEquals(expectedNewState, newState)
}
@Test
fun `beforeApply removes single instance of command class if there are another commands before and after in state and adds new command`() {
val (oldState, incomingCommand) = `create state contains single instance of command class and another commands before and after`()
val newState = AddToEndSingleStrategy().beforeApply(oldState, incomingCommand)
val expectedNewState = oldState.filter { command -> command.javaClass != incomingCommand.javaClass }.plus(incomingCommand)
assertNotEquals(oldState, newState)
assertEquals(expectedNewState, newState)
}
@Test
fun `beforeApply removes single instance of command class if there are NO other commands in state and adds new command`() {
val (oldState, incomingCommand) = `create state contains single instance of command class but NO other commands`()
val newState = AddToEndSingleStrategy().beforeApply(oldState, incomingCommand)
val expectedNewState = listOf(incomingCommand)
assertNotEquals(oldState, newState)
assertEquals(expectedNewState, newState)
}
@Test
fun `beforeApply not removes other than first instance of command class if there are another commands in state and adds new command`() {
val (oldState, incomingCommand) = `create state contains many instances of command class and another commands`()
val newState = AddToEndSingleStrategy().beforeApply(oldState, incomingCommand)
val expectedNewState = oldState.withoutFirst { command -> command.javaClass == incomingCommand.javaClass }.plus(incomingCommand)
assertNotEquals(oldState, newState)
assertEquals(expectedNewState, newState)
}
@Test
fun `beforeApply not removes other than first instance of command class if there are NO other commands in state and adds new command`() {
val (oldState, incomingCommand) = `create state contains many instances of command class but NO another commands`()
val newState = AddToEndSingleStrategy().beforeApply(oldState, incomingCommand)
val expectedNewState = oldState.drop(1).plus(incomingCommand)
assertNotEquals(oldState, newState)
assertEquals(expectedNewState, newState)
}
@Test
fun `beforeApply removes single equal command if there are another commands after in state and adds new command again`() {
val (oldState, incomingCommand) = `create state contains single equal command and another commands after`()
val newState = AddToEndSingleStrategy().beforeApply(oldState, incomingCommand)
val expectedNewState = oldState.drop(1).plus(incomingCommand)
assertNotEquals(oldState, newState)
assertEquals(expectedNewState, newState)
}
@Test
fun `beforeApply removes single equal command if there are another commands before in state and adds new command again`() =
`assert beforeApply not mutate state`(
strategy = AddToEndSingleStrategy(),
oldStateWithIncomingCommand = `create state contains single equal command and another commands before`()
)
@Test
fun `beforeApply removes single equal command if there are another commands before and after in state and adds new command again`() {
val (oldState, incomingCommand) = `create state contains single equal command and another commands before and after`()
val newState = AddToEndSingleStrategy().beforeApply(oldState, incomingCommand)
val expectedNewState = oldState.filter { command -> command.javaClass != incomingCommand.javaClass }.plus(incomingCommand)
assertNotEquals(oldState, newState)
assertEquals(expectedNewState, newState)
}
@Test
fun `beforeApply removes single equal command if there are NO other commands in state and adds new command again`() =
`assert beforeApply not mutate state`(
strategy = AddToEndSingleStrategy(),
oldStateWithIncomingCommand = `create state contains single equal command but NO other commands`()
)
@Suppress("MaxLineLength")
@Test
fun `beforeApply not removes other than first duplicated equal commands if state contains many duplicated equal commands and another commands and adds new command again`() =
`assert beforeApply not mutate state`(
strategy = AddToEndSingleStrategy(),
oldStateWithIncomingCommand = `create state contains many duplicated equal commands but NO another commands`()
)
@Suppress("MaxLineLength")
@Test
fun `beforeApply not removes other than first duplicated equal commands if state contains just many duplicated equal commands and adds new command again`() {
val (oldState, incomingCommand) = `create state contains many duplicated equal commands and another commands`()
val newState = AddToEndSingleStrategy().beforeApply(oldState, incomingCommand)
val expectedNewState = oldState.withoutFirst { command -> command.javaClass == incomingCommand.javaClass }.plus(incomingCommand)
assertNotEquals(oldState, newState)
assertEquals(expectedNewState, newState)
}
@Test
fun `beforeApply not mutate state if there is no instances of command class but there are another commands in state and adds new command`() {
val (oldState, incomingCommand) = `create state contains NO instances of command class but there are another commands`()
val newState = AddToEndSingleStrategy().beforeApply(oldState, incomingCommand)
val expectedNewState = oldState.plus(incomingCommand)
assertNotEquals(oldState, newState)
assertEquals(expectedNewState, newState)
}
@Test
fun `beforeApply just adds new command to empty state`() {
val (oldState, incomingCommand) = `create empty state`()
val newState = AddToEndSingleStrategy().beforeApply(oldState, incomingCommand)
val expectedNewState = listOf(incomingCommand)
assertNotEquals(oldState, newState)
assertEquals(expectedNewState, newState)
}
@Test
fun `afterApply not mutate state if state contains single instance of command class and another commands after`() =
`assert afterApply not mutate state`(
strategy = AddToEndSingleStrategy(),
oldStateWithIncomingCommand = `create state contains single instance of command class and another commands after`()
)
@Test
fun `afterApply not mutate state if state contains single instance of command class and another commands before`() =
`assert afterApply not mutate state`(
strategy = AddToEndSingleStrategy(),
oldStateWithIncomingCommand = `create state contains single instance of command class and another commands before`()
)
@Test
fun `afterApply not mutate state if state contains single instance of command class and another commands before and after`() =
`assert afterApply not mutate state`(
strategy = AddToEndSingleStrategy(),
oldStateWithIncomingCommand = `create state contains single instance of command class and another commands before and after`()
)
@Test
fun `afterApply not mutate state if state contains single instance of command class but NO other commands`() =
`assert afterApply not mutate state`(
strategy = AddToEndSingleStrategy(),
oldStateWithIncomingCommand = `create state contains single instance of command class but NO other commands`()
)
@Test
fun `afterApply not mutate state if state contains many instances of command class and another commands`() =
`assert afterApply not mutate state`(
strategy = AddToEndSingleStrategy(),
oldStateWithIncomingCommand = `create state contains many instances of command class and another commands`()
)
@Test
fun `afterApply not mutate state if state contains many instances of command class but NO another commands`() =
`assert afterApply not mutate state`(
strategy = AddToEndSingleStrategy(),
oldStateWithIncomingCommand = `create state contains many instances of command class but NO another commands`()
)
@Test
fun `afterApply not mutate state if state contains single equal command and another commands after`() =
`assert afterApply not mutate state`(
strategy = AddToEndSingleStrategy(),
oldStateWithIncomingCommand = `create state contains single equal command and another commands after`()
)
@Test
fun `afterApply not mutate state if state contains single equal command and another commands before`() =
`assert afterApply not mutate state`(
strategy = AddToEndSingleStrategy(),
oldStateWithIncomingCommand = `create state contains single equal command and another commands before`()
)
@Test
fun `afterApply not mutate state if state contains single equal command and another commands before and after`() =
`assert afterApply not mutate state`(
strategy = AddToEndSingleStrategy(),
oldStateWithIncomingCommand = `create state contains single equal command and another commands before and after`()
)
@Test
fun `afterApply not mutate state if state contains single equal command but NO other commands`() =
`assert afterApply not mutate state`(
strategy = AddToEndSingleStrategy(),
oldStateWithIncomingCommand = `create state contains single equal command but NO other commands`()
)
@Test
fun `afterApply not mutate state if state contains many duplicated equal commands and another commands`() =
`assert afterApply not mutate state`(
strategy = AddToEndSingleStrategy(),
oldStateWithIncomingCommand = `create state contains many duplicated equal commands and another commands`()
)
@Test
fun `afterApply not mutate state if state contains many duplicated equal commands but NO other commands`() =
`assert afterApply not mutate state`(
strategy = AddToEndSingleStrategy(),
oldStateWithIncomingCommand = `create state contains many duplicated equal commands but NO another commands`()
)
@Test
fun `afterApply not mutate state if there is no instances of command class but there are other commands`() =
`assert afterApply not mutate state`(
strategy = AddToEndSingleStrategy(),
oldStateWithIncomingCommand = `create state contains NO instances of command class but there are another commands`()
)
@Test
fun `afterApply not mutate empty state`() =
`assert afterApply not mutate state`(
strategy = AddToEndSingleStrategy(),
oldStateWithIncomingCommand = `create empty state`()
)
} | 22 | Kotlin | 0 | 0 | 159a035109fab5cf777dd7a60f142a89f441df63 | 12,698 | android_client_app | Apache License 2.0 |
AURDroid.kts | bgroJr | 267,879,594 | false | null | import org.junit.*
import org.junit.runner.*
import org.junit.runners.*
import io.appium.java_client.*
import org.openqa.selenium.remote.*
@RunWith(JUnit4::class)
class UITest {
lateinit var home: Home.Screen
@Before
fun setUp() {
val app = AppiumDriver<MobileElement>(
java.net.URL("http://localhost:4723/wd/hub"),
DesiredCapabilities(
mapOf(
"platformName" to "Android",
"deviceName" to "Android Emulator",
"automationName" to "UiAutomator2",
"appPackage" to "com.rascarlo.aurdroid",
"appActivity" to ".MainActivity",
"skipDeviceInitialization" to true,
"skipServerInstallation" to true,
"noSign" to true
)
)
)
home = Home.Screen(app)
}
@Test
fun `search for package to retrieve upstream URL`() {
val results = home.selectCriteria("Name")
.enterTerm("spotify")
.search()
val pkg = results.scrollTo("spotify")
.choose("spotify")
val upstreamURL = pkg.retrieveUpstreamURL()
Assert.assertEquals(upstreamURL, "https://www.spotify.com")
}
@After
fun tearDown() {
home.app.quit()
}
}
| 0 | Kotlin | 0 | 2 | eca7b8b012304a6b3557e9904da53adf5651765e | 1,222 | AURDroidTest | MIT License |
kotlin/shrine/app/src/main/java/com/google/codelabs/mdc/kotlin/shrine/ProductCardViewHolder.kt | alena-ku | 183,390,773 | false | {"Java": 23536, "Kotlin": 14198, "Shell": 2805} | package com.google.codelabs.mdc.kotlin.shrine
import android.support.v7.widget.RecyclerView
import android.view.View
class ProductCardViewHolder(itemView: View) //TODO: Find and store views from itemView
: RecyclerView.ViewHolder(itemView)
| 1 | Java | 1 | 2 | 8d1d40daad76eacc5710811988f57e86574d92dd | 246 | material-shopping | Apache License 2.0 |
to-do-app-sample/src/main/kotlin/com/example/domain/security/authenticate/AuthenticateInteractor.kt | t-matsumo | 666,923,183 | false | null | package com.example.domain.security.authenticate
import com.example.domain.security.*
class AuthenticateInteractor(
credentialRepository: CredentialRepository,
passwordEncoder: PasswordEncoder
): AuthenticateUseCase {
private val credentialService = CredentialService(credentialRepository, passwordEncoder)
override fun handle(request: AuthenticateRequest): AuthenticateResponse {
val requestCredential = RequestCredential(Id(request.name), Password(request.password))
return credentialService.authenticate(requestCredential)
.fold(
onSuccess = { Result.success(it) },
onFailure = { Result.failure(AuthenticateNoSuchMemberException()) }
).let { AuthenticateResponse(it) }
}
} | 0 | Kotlin | 0 | 0 | b736aba827209d153f4e7dbf98011b939a841c37 | 770 | ToDoAppSample | MIT License |
daemon/src/main/kotlin/dev/krud/boost/daemon/actuator/model/EnvActuatorResponse.kt | krud-dev | 576,882,508 | false | null | package dev.krud.boost.daemon.actuator.model
import dev.krud.boost.daemon.utils.TypeDefaults
data class EnvActuatorResponse(
val activeProfiles: Set<String> = emptySet(),
val propertySources: List<PropertySource> = emptyList()
) {
data class PropertySource(
val name: String = TypeDefaults.STRING,
val properties: Map<String, Property>? = null
) {
data class Property(
val value: String = TypeDefaults.STRING,
val origin: String? = null
)
}
} | 34 | TypeScript | 3 | 203 | a9fdbd1408a051c2744b3bd06912f727a4041fae | 520 | ostara | Apache License 2.0 |
one.lfa.updater.opds.xml.v1_0/src/main/java/one/lfa/updater/opds/xml/v1_0/OPDSManifestXML1ManifestHandler.kt | AULFA | 189,855,520 | false | null | package one.lfa.updater.opds.xml.v1_0
import one.lfa.updater.opds.api.OPDSFile
import one.lfa.updater.opds.api.OPDSManifest
import one.lfa.updater.xml.spi.SPIFormatXMLAbstractContentHandler
import one.lfa.updater.xml.spi.SPIFormatXMLContentHandlerType
import org.joda.time.DateTime
import org.joda.time.DateTimeZone
import org.joda.time.LocalDateTime
import org.joda.time.format.ISODateTimeFormat
import org.xml.sax.Attributes
import org.xml.sax.SAXParseException
import org.xml.sax.ext.Locator2
import java.net.URI
import java.util.UUID
class OPDSManifestXML1ManifestHandler(
private val baseURIDefault: URI,
locator2: Locator2)
: SPIFormatXMLAbstractContentHandler<OPDSFile, OPDSManifest>(locator2, "Manifest") {
private lateinit var id: UUID
private lateinit var items: MutableList<OPDSFile>
private lateinit var rootFile: URI
private lateinit var title: String
private lateinit var updated: DateTime
private var baseURI: URI? = null
private var searchIndex: URI? = null
override fun onWantHandlerName(): String =
OPDSManifestXML1ManifestHandler::class.java.simpleName
override fun onWantChildHandlers(): Map<String, () -> SPIFormatXMLContentHandlerType<OPDSFile>> =
mapOf(Pair("File", { OPDSManifestXML1FileHandler(super.locator(), this.baseURIOrDefault()) }))
private fun baseURIOrDefault(): URI {
return this.baseURI ?: this.baseURIDefault
}
override fun onElementFinishDirectly(
namespace: String,
name: String,
qname: String
): OPDSManifest? {
return OPDSManifest(
baseURI = this.baseURI,
rootFile = this.rootFile,
updated = DateTime(this.updated, DateTimeZone.UTC),
searchIndex = this.searchIndex,
id = this.id,
files = this.items.toList(),
title = this.title
)
}
override fun onElementStartDirectly(
namespace: String,
name: String,
qname: String,
attributes: Attributes
) {
val formatter = ISODateTimeFormat.dateTimeParser()
try {
this.id = UUID.fromString(attributes.getValue("id"))
this.updated = formatter.parseDateTime(attributes.getValue("updated"))
val titleOpt = attributes.getValue("title")
if (titleOpt != null) {
this.title = titleOpt
} else {
this.title = ""
}
val baseOpt = attributes.getValue("base")
if (baseOpt != null) {
this.baseURI = URI.create(baseOpt)
}
val searchOpt = attributes.getValue("searchIndex")
if (searchOpt != null) {
this.searchIndex = URI.create(searchOpt)
}
this.rootFile = URI.create(attributes.getValue("rootFile"))
this.items = mutableListOf()
} catch (e: Exception) {
throw SAXParseException(e.message, this.locator(), e)
}
}
override fun onChildResultReceived(value: OPDSFile) {
this.items.add(value)
}
} | 2 | null | 1 | 1 | 5cde488e4e9f9e60f5737d9e1a8fc8817f6b22a8 | 2,846 | updater | Apache License 2.0 |
app/src/main/kotlin/dto/CancelCoffeeResponse.kt | DiUS | 87,150,714 | false | null | package au.com.dius.coffee.dto
import au.com.dius.coffee.model.Coffee
data class CancelCoffeeResponse(
val id: Long,
val path: String
) {
companion object {
fun from(coffee: Coffee, orderId: Long) =
CancelCoffeeResponse(
id=coffee.number,
path="/order/${orderId}/coffee/${coffee.number}"
)
}
}
| 0 | Kotlin | 2 | 0 | 2bcc3bd702fbf9829a4f4c3d2bca64bc9f33ae8c | 340 | dius-mentor_boris_coffee-api | MIT License |
app/src/main/java/com/example/moviedb/ui/screen/popularmovie/PopularMovieViewModel.kt | dangquanuet | 127,717,732 | false | {"Kotlin": 277738, "Makefile": 1159} | package com.example.moviedb.ui.screen.popularmovie
import androidx.lifecycle.viewModelScope
import com.example.moviedb.data.constant.MovieListType
import com.example.moviedb.data.model.Movie
import com.example.moviedb.data.remote.api.ApiParams
import com.example.moviedb.ui.base.items.ItemsViewModel
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class PopularMovieViewModel @Inject constructor(
) : ItemsViewModel<Movie>() {
val mode = MutableStateFlow(MovieListType.POPULAR.type)
override fun loadData(page: Int) {
val hashMap = HashMap<String, String>()
hashMap[ApiParams.PAGE] = page.toString()
when (mode.value) {
MovieListType.POPULAR.type -> hashMap[ApiParams.SORT_BY] = ApiParams.POPULARITY_DESC
MovieListType.TOP_RATED.type -> hashMap[ApiParams.SORT_BY] = ApiParams.VOTE_AVERAGE_DESC
else -> hashMap[ApiParams.SORT_BY] = ApiParams.POPULARITY_DESC
}
viewModelScope.launch {
try {
onLoadSuccess(page, userRepo.getMovieList(hashMap).results)
} catch (e: Exception) {
onError(e)
}
}
}
}
| 3 | Kotlin | 93 | 413 | c5031dcfa879243c0ea44d0973153078e568c013 | 1,288 | The-Movie-DB-Kotlin | Apache License 2.0 |
Kazak-Android/core/src/main/kotlin/io/kazak/repository/JsonRepository.kt | frakbot | 38,201,466 | false | {"Java": 137822, "Kotlin": 29863, "XSLT": 6315, "Groovy": 5469} | package io.kazak.repository
import rx.Observable
interface JsonRepository {
fun store(json: String): Observable<Unit>
fun read(): Observable<String>
}
| 2 | Java | 1 | 1 | a33a0271ee8235fd23f90ad33b818ce4d3b7c856 | 164 | kazak-android | MIT License |
hilibrary/src/main/java/org/devio/hi/library/restful/HiRestful.kt | yanyonghua | 572,538,089 | false | null | package org.devio.hi.library.restful
import java.lang.reflect.InvocationHandler
import java.lang.reflect.Method
import java.lang.reflect.Proxy
import java.util.concurrent.ConcurrentHashMap
/**
* @Author yanyonghua
* @Date 2022/11/3-13:54
* @Des $.
*/
open class HiRestful constructor(val baseUrl: String,val callFactory: HiCall.Factory) {
private var interceptors: MutableList<HiInterceptor> = mutableListOf()
private var methodService :ConcurrentHashMap<Method,MethodParser> = ConcurrentHashMap()
private var scheduler:Scheduler
fun addInterceptor(interceptor: HiInterceptor) {
interceptors.add(interceptor)
}
init {
scheduler =Scheduler(callFactory,interceptors)
}
/**
* interface ApiService {
* @Headers("auth-token:token", "accountId:123456")
* @BaseUrl("https://api.devio.org/as/")
* @POST("/cities/{province}")
* @GET("/cities")
* fun listCities(@Path("province") province: Int,@Filed("page") page: Int): HiCall<JsonObject>
* }
*/
fun <T> create(service: Class<T>): T {
return Proxy.newProxyInstance(
service.classLoader,
arrayOf<Class<*>>(service)
,object :InvocationHandler{
override fun invoke(proxy: Any?, method: Method, args: Array<out Any>?): Any {
var methodParser = methodService.get(method)
if (methodParser == null){
methodParser= MethodParser.parse(baseUrl, method)
methodService.put(method,methodParser)
}
//bugFix๏ผๆญคๅค ๅบๅฝ่่ๅฐ methodParserๅค็จ๏ผๆฏๆฌก่ฐ็จ้ฝๅบๅฝ่งฃๆๅ
ฅๅ
val newRequest = methodParser.newRequest(method,args)
// callFactory.newCall(newRequest)
return scheduler.newCall(newRequest)
}
}
) as T
}
} | 0 | Kotlin | 0 | 0 | e8263ab3ed0869183f8c95d2217f3e44fe88ff51 | 1,889 | hi-library | Apache License 2.0 |
app/src/androidTest/java/com/example/wordsfragmentapp/NavigationTests.kt | kawauso018 | 484,982,659 | false | {"Kotlin": 21259} | package com.example.wordsfragmentapp
class NavigationTests {
//ใใใใใใพใใใงใใใใใ
} | 0 | Kotlin | 0 | 0 | b394c3521652d1202609068b11cd7e30d430a3e1 | 84 | words-fragment | Apache License 2.0 |
engine/game/src/main/kotlin/org/rsmod/game/entity/Npc.kt | rsmod | 293,875,986 | false | {"Kotlin": 1695754} | package org.rsmod.game.entity
import org.rsmod.coroutine.GameCoroutine
import org.rsmod.game.entity.npc.NpcMode
import org.rsmod.game.entity.shared.PathingEntityCommon
import org.rsmod.game.map.Direction
import org.rsmod.game.movement.BlockWalk
import org.rsmod.game.movement.MoveRestrict
import org.rsmod.game.movement.MoveSpeed
import org.rsmod.game.type.npc.UnpackedNpcType
import org.rsmod.map.CoordGrid
import org.rsmod.pathfinder.collision.CollisionFlagMap
import org.rsmod.pathfinder.collision.CollisionStrategy
private typealias RspAvatar = net.rsprot.protocol.game.outgoing.info.npcinfo.NpcAvatar
public class Npc(
public val type: UnpackedNpcType,
override val avatar: PathingEntityAvatar = NpcAvatar(type.size),
) : PathingEntity() {
public constructor(type: UnpackedNpcType, coords: CoordGrid) : this(type) {
this.coords = coords
this.spawnCoords = coords
}
override val isBusy: Boolean
get() = isDelayed
override val blockWalkCollisionFlag: Int?
get() = blockWalk.collisionFlag
override val collisionStrategy: CollisionStrategy?
get() = moveRestrict.collisionStrategy
public var spawnCoords: CoordGrid = coords
public var defaultMoveSpeed: MoveSpeed = MoveSpeed.Walk
public var mode: NpcMode? = type.defaultMode
public var lifecycleAddCycle: Int = -1
public var lifecycleDelCycle: Int = -1
public var lifecycleRevealCycle: Int = -1
public var patrolWaypointIndex: Int = 0
public var patrolIdleTicks: Int = -1
public var patrolPauseTicks: Int = 0
public var wanderIdleTicks: Int = -1
public lateinit var rspAvatar: RspAvatar
public val id: Int
get() = type.id
public val name: String
get() = type.name
public val moveRestrict: MoveRestrict
get() = type.moveRestrict
public val blockWalk: BlockWalk
get() = type.blockWalk
public val respawnDir: Direction
get() = type.respawnDir
public val wanderRange: Int
get() = type.wanderRange
public val defaultMode: NpcMode
get() = type.defaultMode
public fun walk(dest: CoordGrid): Unit = PathingEntityCommon.walk(this, dest)
public fun teleport(collision: CollisionFlagMap, dest: CoordGrid): Unit =
PathingEntityCommon.teleport(this, collision, dest)
public fun telejump(collision: CollisionFlagMap, dest: CoordGrid): Unit =
PathingEntityCommon.telejump(this, collision, dest)
public fun resetMode() {
resetFaceEntity()
mode = null
}
public fun say(text: String) {
rspAvatar.extendedInfo.setSay(text)
}
public fun facePlayer(target: Player) {
PathingEntityCommon.facePlayer(this, target)
rspAvatar.extendedInfo.setFacePathingEntity(faceEntitySlot)
}
public fun faceNpc(target: Npc) {
PathingEntityCommon.faceNpc(this, target)
rspAvatar.extendedInfo.setFacePathingEntity(faceEntitySlot)
}
public fun resetFaceEntity() {
PathingEntityCommon.resetFaceEntity(this)
rspAvatar.extendedInfo.setFacePathingEntity(faceEntitySlot)
}
public fun facingTarget(playerList: PlayerList): Player? =
if (faceEntitySlot >= PathingEntityCommon.FACE_PLAYER_START_SLOT) {
playerList[faceEntitySlot - PathingEntityCommon.FACE_PLAYER_START_SLOT]
} else {
null
}
public fun forceDespawn() {
// TODO: force
}
/**
* Suspends the call site until this [Npc] has gone a tick without moving. If the npc was not
* moving when this function was called, the coroutine will not suspend and this function will
* instantly return.
*
* For similar functionality with a [Player], it must be done with "protected access."
*
* @see [delay]
*/
public suspend fun GameCoroutine.arriveDelay() {
if (!hasMovedThisTick) {
return
}
delay()
}
/**
* Adds a delay to this [Npc] and suspends the coroutine. Once the npc is no longer delayed, the
* coroutine will resume.
*
* For similar functionality with a [Player], it must be done with "protected access."
*
* @throws IllegalArgumentException if [ticks] is not greater than 0.
*/
public suspend fun GameCoroutine.delay(ticks: Int = 1) {
require(ticks > 0) { "`ticks` must be greater than 0. (ticks=$ticks)" }
delay(ticks)
pause { isNotDelayed }
}
override fun toString(): String = "Npc(slot=$slotId, coords=$coords, type=$type)"
}
| 0 | Kotlin | 64 | 92 | 8821a9cddc54314c03c873d4fdaaef760a3a2ada | 4,584 | rsmod | ISC License |
app/src/main/java/com/khaled/nytimesmostpopulararticles/model/database/MostPopularArticleDao.kt | khaboshama | 335,725,471 | false | null | package com.khaled.nytimesmostpopulararticles.model.database
import androidx.lifecycle.LiveData
import androidx.room.*
import com.khaled.nytimesmostpopulararticles.model.ArticleItem
/**
* Data Access Object for the articles table.
*/
@Dao
interface MostPopularArticleDao {
@Query("SELECT * FROM article")
fun getMostPopularArticleList(): LiveData<List<ArticleItem>>
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertAll(vararg articleItem: ArticleItem)
@Query("DELETE FROM article")
suspend fun deleteAll()
} | 0 | Kotlin | 0 | 0 | 841209defa4f4e1a2dc36c357bf7ae9b3678db9e | 555 | NYTimesMostPopularArticles | Apache License 2.0 |
android-basics-kotlin-bus-schedule-app-starter/app/src/main/java/com/example/busschedule/database/AppDatabase.kt | amoralesc | 482,319,767 | false | {"Kotlin": 363730} | package com.example.busschedule.database
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import com.example.busschedule.database.schedule.Schedule
import com.example.busschedule.database.schedule.ScheduleDao
@Database(entities = arrayOf(Schedule::class), version = 1)
abstract class AppDatabase: RoomDatabase() {
abstract fun scheduleDao(): ScheduleDao
companion object {
@Volatile
private var INSTANCE: AppDatabase? = null
fun getDatabase(context: Context) : AppDatabase {
return INSTANCE ?: synchronized(this) {
val instance = Room.databaseBuilder(
context,
AppDatabase::class.java,
"app_database")
.createFromAsset("database/bus_schedule.db")
.build()
INSTANCE = instance
instance
}
}
}
} | 0 | Kotlin | 0 | 0 | 4d8104a46772935b069bbb9bb181d1104aca3cca | 823 | android-basics-kotlin | Apache License 2.0 |
src/main/kotlin/tech/gdragon/koin/KoinApplicationEx.kt | guacamoledragon | 96,600,559 | false | {"Kotlin": 186592, "Clojure": 16441, "Shell": 5769, "HTML": 4662, "Just": 2918, "Dockerfile": 1530, "Makefile": 785, "Batchfile": 629} | package tech.gdragon.koin
import org.koin.core.KoinApplication
import org.koin.core.annotation.KoinInternalApi
import org.koin.core.logger.Level
import java.io.File
import java.io.FileInputStream
import java.util.*
/**
* Generate a hashmap from a Properties object.
*/
private fun fromProperties(properties: Properties): Map<String, Any> = buildMap {
properties.forEach { property ->
put(property.key as String, property.value)
}
}
@OptIn(KoinInternalApi::class)
fun KoinApplication.overrideFileProperties(overrideFilename: String): KoinApplication {
val overrideFile = File(overrideFilename)
if (overrideFile.exists()) {
FileInputStream(overrideFile).use { inputStream ->
val overrideProperties = Properties().also {
it.load(inputStream)
}
properties(fromProperties(overrideProperties))
if (koin.logger.isAt(Level.INFO)) {
koin.logger.info("loaded properties from file:'${overrideFile.canonicalPath}'")
}
}
} else {
koin.logger.error("Override file $overrideFilename doesn't exist, please double check the file path.")
}
return this
}
| 5 | Kotlin | 18 | 45 | 0837d5e02a765b05281e485d57fc251815e1f2cf | 1,120 | throw-voice | Apache License 2.0 |
plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/tasks/GenerateReportsTask.kt | JLLeitschuh | 84,131,083 | false | null | package org.jlleitschuh.gradle.ktlint.tasks
import org.gradle.api.DefaultTask
import org.gradle.api.file.ConfigurableFileCollection
import org.gradle.api.file.DirectoryProperty
import org.gradle.api.file.ProjectLayout
import org.gradle.api.file.RegularFileProperty
import org.gradle.api.model.ObjectFactory
import org.gradle.api.provider.Property
import org.gradle.api.provider.SetProperty
import org.gradle.api.tasks.CacheableTask
import org.gradle.api.tasks.Classpath
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.InputFile
import org.gradle.api.tasks.Optional
import org.gradle.api.tasks.OutputDirectory
import org.gradle.api.tasks.PathSensitive
import org.gradle.api.tasks.PathSensitivity
import org.gradle.api.tasks.TaskAction
import org.gradle.workers.WorkerExecutor
import org.jlleitschuh.gradle.ktlint.reporter.LoadedReporter
import org.jlleitschuh.gradle.ktlint.reporter.ReporterType
import org.jlleitschuh.gradle.ktlint.worker.ConsoleReportWorkAction
import org.jlleitschuh.gradle.ktlint.worker.GenerateReportsWorkAction
import java.io.File
import java.io.FileInputStream
import java.io.ObjectInputStream
import javax.inject.Inject
/**
* Generates reports and prints errors into Gradle console.
*
* This will actually fail the build in case some non-corrected lint issues.
*/
@CacheableTask
abstract class GenerateReportsTask @Inject constructor(
private val workerExecutor: WorkerExecutor,
private val projectLayout: ProjectLayout,
objectFactory: ObjectFactory
) : DefaultTask() {
@get:Classpath
internal abstract val ktLintClasspath: ConfigurableFileCollection
@get:Classpath
internal abstract val reportersClasspath: ConfigurableFileCollection
@get:PathSensitive(PathSensitivity.RELATIVE)
@get:InputFile
internal abstract val loadedReporterProviders: RegularFileProperty
@get:PathSensitive(PathSensitivity.RELATIVE)
@get:InputFile
internal abstract val loadedReporters: RegularFileProperty
@get:PathSensitive(PathSensitivity.RELATIVE)
@get:InputFile
internal abstract val discoveredErrors: RegularFileProperty
@get:Input
internal abstract val reportsName: Property<String>
@get:Input
internal abstract val enabledReporters: SetProperty<ReporterType>
@get:Input
internal abstract val outputToConsole: Property<Boolean>
@get:Input
internal abstract val coloredOutput: Property<Boolean>
@get:Input
internal abstract val outputColorName: Property<String>
@get:Input
internal abstract val ignoreFailures: Property<Boolean>
@get:Input
internal abstract val verbose: Property<Boolean>
@get:Input
internal abstract val ktLintVersion: Property<String>
@get:Input
internal abstract val relative: Property<Boolean>
@get:PathSensitive(PathSensitivity.RELATIVE)
@get:InputFile
@get:Optional
internal abstract val baseline: RegularFileProperty
/**
* Reading a project's rootDir within a task's action is not allowed for configuration
* cache, so read it eagerly on task initialization.
* see: https://docs.gradle.org/current/userguide/configuration_cache.html#config_cache
*/
private val rootDir: File = project.rootDir
init {
// Workaround for https://github.com/gradle/gradle/issues/2919
onlyIf {
val errorsFile = (it as GenerateReportsTask).discoveredErrors.asFile.get()
errorsFile.exists()
}
}
/**
* Reports output directory.
*
* Default is "build/reports/ktlint/${taskName}/".
*/
@Suppress("UnstableApiUsage")
@get:OutputDirectory
val reportsOutputDirectory: DirectoryProperty = objectFactory
.directoryProperty()
.convention(
reportsName.flatMap {
projectLayout
.buildDirectory
.dir("reports${File.separator}ktlint${File.separator}$it")
}
)
@Suppress("UnstableApiUsage")
@TaskAction
fun generateReports() {
// Classloader isolation is enough here as we just want to use some classes from KtLint classpath
// to get errors and generate files/console reports. No KtLint main object is initialized/used in this case.
val queue = workerExecutor.classLoaderIsolation {
classpath.from(ktLintClasspath, reportersClasspath)
}
val loadedReporters = loadLoadedReporters()
.associateWith {
reportsOutputDirectory.file("${reportsName.get()}.${it.fileExtension}")
}
val task = this
loadedReporters.forEach { (loadedReporter, reporterOutput) ->
queue.submit(GenerateReportsWorkAction::class.java) {
discoveredErrorsFile.set(task.discoveredErrors)
loadedReporterProviders.set(task.loadedReporterProviders)
reporterId.set(loadedReporter.reporterId)
this.reporterOutput.set(reporterOutput)
reporterOptions.set(generateReporterOptions(loadedReporter))
ktLintVersion.set(task.ktLintVersion)
baseline.set(task.baseline)
projectDirectory.set(task.projectLayout.projectDirectory)
if (task.relative.get()) {
filePathsRelativeTo.set(rootDir)
}
}
}
queue.submit(ConsoleReportWorkAction::class.java) {
discoveredErrors.set(task.discoveredErrors)
outputToConsole.set(task.outputToConsole)
ignoreFailures.set(task.ignoreFailures)
verbose.set(task.verbose)
generatedReportsPaths.from(loadedReporters.values)
ktLintVersion.set(task.ktLintVersion)
baseline.set(task.baseline)
projectDirectory.set(projectLayout.projectDirectory)
}
}
private fun loadLoadedReporters() = ObjectInputStream(
FileInputStream(loadedReporters.asFile.get())
).use {
@Suppress("UNCHECKED_CAST")
it.readObject() as List<LoadedReporter>
}
private fun generateReporterOptions(
loadedReporter: LoadedReporter
): Map<String, String> {
val options = mutableMapOf(
"verbose" to verbose.get().toString(),
"color" to coloredOutput.get().toString()
)
if (outputColorName.get().isNotBlank()) {
options["color_name"] = outputColorName.get()
} else {
// Same default as in the KtLint CLI
options["color_name"] = "DARK_GRAY"
}
options.putAll(loadedReporter.reporterOptions)
return options.toMap()
}
internal enum class LintType(
val suffix: String
) {
CHECK("Check"),
FORMAT("Format")
}
internal companion object {
internal fun generateNameForSourceSets(
sourceSetName: String,
lintType: LintType
): String = "ktlint${sourceSetName.capitalize()}SourceSet${lintType.suffix}"
internal fun generateNameForKotlinScripts(
lintType: LintType
): String = "ktlintKotlinScript${lintType.suffix}"
const val DESCRIPTION = "Generates reports and prints errors into Gradle console."
}
}
| 88 | null | 157 | 1,385 | d29b339587cc1eb0aebc48b9bb98e242dafdd7ff | 7,274 | ktlint-gradle | MIT License |
navigation-core/src/commonMain/kotlin/com.chrynan.navigation/DestinationAndContext.kt | chRyNaN | 439,481,580 | false | {"Kotlin": 178365} | @file:Suppress("unused")
package com.chrynan.navigation
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
/**
* A wrapper class around a [NavigationDestination] and an associated [NavigationContext].
*/
@Serializable
class DestinationAndContext<Destination : NavigationDestination, Context : NavigationContext<Destination>>(
@SerialName(value = "destination") val destination: Destination,
@SerialName(value = "context") val context: Context
) {
/**
* Creates a copy of this [DestinationAndContext] instance, overriding the provided values.
*/
fun copy(
destination: Destination = this.destination,
context: Context = this.context
): DestinationAndContext<Destination, Context> = DestinationAndContext(
destination = destination,
context = context
)
operator fun component1(): Destination = destination
operator fun component2(): Context = context
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is DestinationAndContext<*, *>) return false
if (context != other.context) return false
return destination == other.destination
}
override fun hashCode(): Int {
var result = context.hashCode()
result = 31 * result + destination.hashCode()
return result
}
override fun toString(): String =
"DestinationAndContext(destination=$destination, context=$context)"
}
| 1 | Kotlin | 2 | 43 | f48e6dbf813e86fa2f11ea4f02c6351fbcadf4b9 | 1,497 | navigation | Apache License 2.0 |
state-keeper/src/commonTest/kotlin/com/arkivanov/essenty/statekeeper/TestUtils.kt | arkivanov | 385,374,863 | false | {"Kotlin": 150573} | package com.arkivanov.essenty.statekeeper
internal fun SerializableContainer.serializeAndDeserialize(): SerializableContainer =
serialize(strategy = SerializableContainer.serializer())
.deserialize(strategy = SerializableContainer.serializer())
| 2 | Kotlin | 13 | 378 | 58cbe45b10aec85e8170bcde26ba25a7596081a4 | 258 | Essenty | Apache License 2.0 |
state-keeper/src/commonTest/kotlin/com/arkivanov/essenty/statekeeper/TestUtils.kt | arkivanov | 385,374,863 | false | {"Kotlin": 150573} | package com.arkivanov.essenty.statekeeper
internal fun SerializableContainer.serializeAndDeserialize(): SerializableContainer =
serialize(strategy = SerializableContainer.serializer())
.deserialize(strategy = SerializableContainer.serializer())
| 2 | Kotlin | 13 | 378 | 58cbe45b10aec85e8170bcde26ba25a7596081a4 | 258 | Essenty | Apache License 2.0 |
composeApp/src/androidMain/kotlin/com/github/theapache64/rebugger/App.android.kt | theapache64 | 619,400,431 | false | {"Kotlin": 8098, "Swift": 532, "JavaScript": 475, "HTML": 279} | package com.github.theapache64.rebugger
import android.app.Application
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import com.theapache64.rebuggersample.RebuggerSample
class AndroidApp : Application() {
companion object {
lateinit var INSTANCE: AndroidApp
}
override fun onCreate() {
super.onCreate()
INSTANCE = this
}
}
class AppActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
RebuggerSample()
}
}
} | 3 | Kotlin | 6 | 593 | 784ef7195fe4ed79ed2740fabd624b6412518a39 | 695 | rebugger | Apache License 2.0 |
components/gateway/src/test/kotlin/net/corda/p2p/gateway/messaging/http/HostnameMatcherTest.kt | corda | 346,070,752 | false | {"Kotlin": 18843439, "Java": 318792, "Smarty": 101152, "Shell": 48766, "Groovy": 30378, "PowerShell": 6350, "TypeScript": 5826, "Solidity": 2024} | package net.corda.p2p.gateway.messaging.http
import net.corda.testing.p2p.certificates.Certificates
import org.assertj.core.api.Assertions.assertThat
import org.bouncycastle.asn1.x500.X500Name
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import java.security.KeyStore
import javax.net.ssl.SNIHostName
import javax.security.auth.x500.X500Principal
class HostnameMatcherTest {
@Test
fun `C4 SNI match`() {
val keyStore: KeyStore = KeyStore.getInstance("JKS").also {
it.load(Certificates.c4KeyStoreFile.openStream(), "cordacadevpass".toCharArray())
}
val x500Name = X500Name.getInstance(X500Principal("O=PartyA,L=London,C=GB").encoded)
val calculatedSNI = SniCalculator.calculateCorda4Sni(x500Name.toString())
val matcher = HostnameMatcher(keyStore)
assertTrue(matcher.matches(SNIHostName(calculatedSNI)))
assertFalse(matcher.matches(SNIHostName("PartyA.net")))
// Invalid C4 style SNI - incorrect suffix
assertFalse(matcher.matches(SNIHostName("b597e8858a2fa87424f5e8c39dc4f93c.p2p.corda.com")))
// Invalid C4 style SNI - incorrect length
assertFalse(matcher.matches(SNIHostName("b597e8858a2fa87424f5e8c39d.p2p.corda.net")))
// Invalid C4 style SNI - invalid hash (not hex)
assertFalse(matcher.matches(SNIHostName("n597q8858z2fm87424f5e8c39dc4f93c.p2p.corda.net")))
}
@Test
fun `C5 SNI match with ip address`() {
val ipAddress = "127.0.0.1"
val keyStore: KeyStore = KeyStore.getInstance("JKS").also {
it.load(Certificates.ipKeyStore.openStream(), "password".toCharArray())
}
val matcher = HostnameMatcher(keyStore)
assertThat(matcher.matches(SNIHostName(ipAddress + SniCalculator.IP_SNI_SUFFIX))).isTrue
}
@Test
fun `C5 SNI match`() {
// Because the tool used to create this certificate (tinycert.org) performs validations over subject alt names,
// only happy paths can be tested using the certificate as input
val keyStore: KeyStore = KeyStore.getInstance("JKS").also {
it.load(Certificates.c5KeyStoreFile.openStream(), "password".toCharArray())
}
val matcher = HostnameMatcher(keyStore)
assertFalse(matcher.matches(SNIHostName("alice.net")))
assertTrue(matcher.matches(SNIHostName("www.TesT.com")))
assertTrue(matcher.matches(SNIHostName("www.test.co.uk")))
assertTrue(matcher.matches(SNIHostName("alice.test.net"))) // matches with *.test.net
assertTrue(matcher.matches(SNIHostName("bob.test.net"))) // matches with *.test.net
assertTrue(matcher.matches(SNIHostName("Test2"))) // matches the CN in the subject name
// Certificate tool wouldn't allow using a DNS name with only part of a group wildcarded, even though the RFC allows it
// We test this match using the direct HostnameMatcher method
assertTrue(matcher.matchWithWildcard("alice.test.net", "al*.test.net"))
// Use of wildcard
assertTrue(matcher.illegalWildcard("*"))
assertTrue(matcher.illegalWildcard("*."))
assertTrue(matcher.illegalWildcard("*.*.net"))
assertTrue(matcher.illegalWildcard("www.*.foo.bar.net"))
assertTrue(matcher.illegalWildcard("www.*foo.bar.net"))
assertTrue(matcher.illegalWildcard("www.f*o.bar.net"))
assertTrue(matcher.illegalWildcard("www.foo.*"))
assertTrue(matcher.illegalWildcard("www.foo.ne*"))
assertTrue(matcher.illegalWildcard("www.foo.*et"))
assertFalse(matcher.illegalWildcard("*.r3.com"))
assertFalse(matcher.illegalWildcard("*.corda.r3.com"))
}
}
| 96 | Kotlin | 21 | 51 | 08c3e610a0e6ec20143c47d044e0516019ba6578 | 3,771 | corda-runtime-os | Apache License 2.0 |
linguine-runtime/src/jvmMain/kotlin/io/github/cleverlance/linguine/linguineruntime/presentation/LanguageRepository.kt | Cleverlance | 777,740,595 | false | {"Kotlin": 53018} | @file:Suppress("EXPECT_ACTUAL_CLASSIFIERS_ARE_IN_BETA_WARNING")
package io.github.cleverlance.linguine.linguineruntime.presentation
import java.util.Locale
internal actual object LanguageRepository {
actual fun load(): Language {
return Language(Locale.getDefault().language)
}
}
| 3 | Kotlin | 0 | 0 | 24935567aa872bdb5606b4c6132f476e5fbfeb99 | 299 | linguine | MIT License |
ios/src/main/kotlin/sessiondetail/SessionDetailViewController.kt | kikuchy | 117,505,507 | false | null | package sessiondetail
import kotlinx.cinterop.ExportObjCClass
import kotlinx.cinterop.ObjCOutlet
import kotlinx.cinterop.initBy
import platform.Foundation.NSCoder
import platform.UIKit.*
@ExportObjCClass
class SessionDetailViewController(aDecoder: NSCoder) : UIViewController(aDecoder) {
@ObjCOutlet lateinit var containerScroll: UIScrollView
@ObjCOutlet lateinit var titleLabel: UILabel
@ObjCOutlet lateinit var speakerAvatarImage: UIImageView
@ObjCOutlet lateinit var speakerNameLabel: UILabel
@ObjCOutlet lateinit var timeLabel: UILabel
@ObjCOutlet lateinit var placeLabel: UILabel
@ObjCOutlet lateinit var descriptionText: UITextView
override fun initWithCoder(aDecoder: NSCoder): UIViewController? = initBy(SessionDetailViewController(aDecoder))
override fun viewDidLoad() {
super.viewDidLoad()
// FIXME: It's not elegant.
containerScroll.contentInset = UIEdgeInsetsMake(64.0 /* = Status bar height + Navigation bar height */, 0.0, 0.0, 0.0)
}
} | 15 | null | 1 | 2 | 55375a6e66d124cb19f1ebbce45e20aa6f6d7823 | 1,021 | conference-app-2018 | Apache License 2.0 |
rtron-transformer/src/main/kotlin/io/rtron/transformer/opendrive2roadspaces/roadspaces/RoadBuilder.kt | wangruoyi123456 | 320,456,663 | true | {"Kotlin": 951747, "SCSS": 37} | /*
* Copyright 2019-2020 Chair of Geoinformatics, Technical University of Munich
*
* 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.rtron.transformer.opendrive2roadspaces.roadspaces
import com.github.kittinunf.result.Result
import com.github.kittinunf.result.map
import io.rtron.math.geometry.curved.threed.surface.CurveRelativeParametricSurface3D
import io.rtron.math.range.Range
import io.rtron.math.range.shiftLowerEndpointTo
import io.rtron.model.opendrive.common.EContactPoint
import io.rtron.model.opendrive.road.lanes.RoadLanesLaneSection
import io.rtron.model.roadspaces.roadspace.RoadspaceIdentifier
import io.rtron.model.roadspaces.roadspace.attribute.AttributeList
import io.rtron.model.roadspaces.roadspace.attribute.attributes
import io.rtron.model.roadspaces.roadspace.road.*
import io.rtron.model.roadspaces.topology.junction.JunctionIdentifier
import io.rtron.std.Optional
import io.rtron.std.handleFailure
import io.rtron.std.map
import io.rtron.transformer.opendrive2roadspaces.analysis.FunctionBuilder
import io.rtron.transformer.opendrive2roadspaces.parameter.Opendrive2RoadspacesConfiguration
import io.rtron.model.opendrive.road.Road as OpendriveRoad
/**
* Builder for [Road] objects of the RoadSpaces data model.
*/
class RoadBuilder(
private val configuration: Opendrive2RoadspacesConfiguration
) {
// Properties and Initializers
private val _reportLogger = configuration.getReportLogger()
private val _functionBuilder = FunctionBuilder(_reportLogger, configuration.parameters)
private val _laneBuilder = LaneBuilder(configuration)
// Methods
/**
* Builds a single road from the OpenDRIVE data model.
*
* @param id identifier of the road space
* @param srcRoad source road model of OpenDRIVE
* @param roadSurface road surface with torsion applied
* @param roadSurfaceWithoutTorsion road surface without torsion applied (needed for lanes with true level entry)
* @param baseAttributes attributes attached to each element of the road (e.g. lanes)
*/
fun buildRoad(id: RoadspaceIdentifier, srcRoad: OpendriveRoad, roadSurface: CurveRelativeParametricSurface3D,
roadSurfaceWithoutTorsion: CurveRelativeParametricSurface3D, baseAttributes: AttributeList):
Result<Road, Exception> {
val laneOffset = _functionBuilder.buildLaneOffset(id, srcRoad.lanes)
val laneSections = srcRoad.lanes.getLaneSectionsWithRanges(srcRoad.length)
.mapIndexed { currentId, currentLaneSection ->
buildLaneSection(LaneSectionIdentifier(currentId, id), currentLaneSection.first,
currentLaneSection.second, baseAttributes)
}
.handleFailure { return it }
if (laneSections.isEmpty())
return Result.error(IllegalArgumentException("Road element contains no valid lane sections."))
val roadLinkage = buildRoadLinkage(id, srcRoad)
val road = Road(id, roadSurface, roadSurfaceWithoutTorsion, laneOffset, laneSections, roadLinkage)
return Result.success(road)
}
/**
* Builds a [LaneSection] which corresponds to OpenDRIVE's concept of lane sections.
*/
private fun buildLaneSection(laneSectionIdentifier: LaneSectionIdentifier, curvePositionDomain: Range<Double>,
srcLaneSection: RoadLanesLaneSection, baseAttributes: AttributeList):
Result<LaneSection, Exception> {
// check whether source model is processable
srcLaneSection.isProcessable()
.map { _reportLogger.log(it, laneSectionIdentifier.toString()) }
.handleFailure { return it }
val localCurvePositionDomain = curvePositionDomain.shiftLowerEndpointTo(0.0)
val laneSectionAttributes = buildAttributes(srcLaneSection)
val lanes = srcLaneSection.getLeftRightLanes()
.map { (currentLaneId, currentSrcLane) ->
val laneIdentifier = LaneIdentifier(currentLaneId, laneSectionIdentifier)
val attributes = baseAttributes + laneSectionAttributes
_laneBuilder.buildLane(laneIdentifier, localCurvePositionDomain, currentSrcLane, attributes)
}
val centerLane = _laneBuilder.buildCenterLane(laneSectionIdentifier, localCurvePositionDomain,
srcLaneSection.center.lane, baseAttributes)
val laneSection = LaneSection(laneSectionIdentifier, curvePositionDomain, lanes, centerLane)
return Result.success(laneSection)
}
private fun buildRoadLinkage(id: RoadspaceIdentifier, srcRoad: OpendriveRoad): RoadLinkage {
val belongsToJunctionId = srcRoad.getJunction()
.map { JunctionIdentifier(it, id.modelIdentifier) }
val predecessorRoadspaceId = srcRoad.link.predecessor.getRoadPredecessorSuccessor()
.map { RoadspaceIdentifier(it, id.modelIdentifier) }
val predecessorJunctionId = srcRoad.link.predecessor.getJunctionPredecessorSuccessor()
.map { JunctionIdentifier(it, id.modelIdentifier) }
val predecessorContactPoint = srcRoad.link.predecessor
.contactPoint.toContactPoint(default = Optional(ContactPoint.START))
val successorRoadspaceId = srcRoad.link.successor.getRoadPredecessorSuccessor()
.map { RoadspaceIdentifier(it, id.modelIdentifier) }
val successorJunctionId = srcRoad.link.successor.getJunctionPredecessorSuccessor()
.map { JunctionIdentifier(it, id.modelIdentifier) }
val successorContactPoint = srcRoad.link.successor.contactPoint
.toContactPoint(default = Optional(ContactPoint.START))
return RoadLinkage(belongsToJunctionId, predecessorRoadspaceId, predecessorJunctionId, predecessorContactPoint,
successorRoadspaceId, successorJunctionId, successorContactPoint)
}
private fun buildAttributes(srcLaneSection: RoadLanesLaneSection) =
attributes("${configuration.parameters.attributesPrefix}laneSection_") {
attribute("curvePositionStart", srcLaneSection.laneSectionStart.curvePosition)
}
}
fun EContactPoint.toContactPoint(default: Optional<ContactPoint> = Optional.empty()) =
when (this) {
EContactPoint.START -> Optional(ContactPoint.START)
EContactPoint.END -> Optional(ContactPoint.END)
else -> default
}
| 0 | null | 0 | 0 | bed54522ed1f8801fc9789008d08f00bf77c74e5 | 7,029 | rtron | Apache License 2.0 |
src/main/kotlin/io/gladed/watchable/ListChange.kt | gladed | 171,806,576 | false | null | /*
* (c) Copyright 2019 Glade Diviney.
*
* 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.gladed.watchable
/** Describes a change to a [List]. */
sealed class ListChange<T> : HasSimpleChange<ListChange.Simple<T>> {
override val isInitial = false
/** The initial state of the list, delivered upon first watch. */
data class Initial<T>(val list: List<T>) : ListChange<T>() {
override val isInitial = true
override val simple by lazy {
list.mapIndexed { index, item -> Simple(index, add = item, isInitial = true) }
}
}
/** An insertion of items at [index]. */
data class Insert<T>(val index: Int, val insert: List<T>) : ListChange<T>(), Addable<ListChange<T>> {
override val simple by lazy {
insert.mapIndexed { addIndex, item -> Simple(index + addIndex, add = item) }
}
override operator fun plus(other: ListChange<T>): ListChange<T>? =
if (other is Insert && index + insert.size == other.index) {
copy(insert = insert + other.insert)
} else null
}
/** A removal of [remove] at [index]. */
data class Remove<T>(val index: Int, val remove: T) : ListChange<T>() {
override val simple by lazy {
listOf(Simple(index, remove = remove))
}
}
/** An overwriting of [remove] at [index], replacing with [add]. */
data class Replace<T>(val index: Int, val remove: T, val add: T) : ListChange<T>() {
override val simple by lazy {
listOf(Simple(index, remove, add))
}
}
/** The simplest form of a list change, affecting only a single position in the list. */
data class Simple<T>(
/** Index at which a change occurred. */
val index: Int,
/** Item removed at [index] if any. */
val remove: T? = null,
/** Item added at [index] if any. */
val add: T? = null,
/** Originally came from an initial change. */
val isInitial: Boolean = false
)
}
| 4 | Kotlin | 2 | 3 | 0c06cee9600c550a6b3d4bbaa4e1f00f61f18958 | 2,552 | watchable | Apache License 2.0 |
Sui/sgx-components/src/main/java/com/bestswlkh0310/sgx_components/component/organization/calendar/SgxBasicCalendarCategory.kt | HNW-DevON | 674,124,124 | false | null | package com.bestswlkh0310.sgx_components.component.organization.calendar
import androidx.compose.ui.graphics.Color
val sgxBasicCalendarCategories = listOf(
SgxBasicCalendarCategory.FirstGrade(),
SgxBasicCalendarCategory.SecondGrade(),
SgxBasicCalendarCategory.ThirdGrade(),
SgxBasicCalendarCategory.AllGrade(),
SgxBasicCalendarCategory.Others(),
)
sealed class SgxBasicCalendarCategory(val color: Color, val name: String) {
class FirstGrade(
color: Color = Color(0x70F0AC3C),
name: String = "1ํ๋
",
) : SgxBasicCalendarCategory(color, name)
class SecondGrade(
color: Color = Color(0x7064BAE1),
name: String = "2ํ๋
",
) : SgxBasicCalendarCategory(color, name)
class ThirdGrade(
color: Color = Color(0x709856DA),
name: String = "3ํ๋
",
) : SgxBasicCalendarCategory(color, name)
class AllGrade(
color: Color = Color(0x70F09771),
name: String = "์ ํ๋
",
) : SgxBasicCalendarCategory(color, name)
class Others(
color: Color = Color(0x700067BC),
name: String = "๊ธฐํ",
) : SgxBasicCalendarCategory(color, name)
}
| 0 | Kotlin | 0 | 1 | 3f16377f1cb71aee2bbe4115b6fe8e7734c8b32b | 1,148 | HNW-Android | MIT License |
medpod/src/main/java/com/zhukofff/medpod/Patient.kt | MedPod | 378,226,864 | false | null | package com.zhukofff.medpod
import com.google.gson.annotations.SerializedName
import java.util.*
data class Patient(
@SerializedName("id") val id: String,
@SerializedName("sex") val sex: String,
@SerializedName("birth-date") val birthdate: Date,
@SerializedName("name") val name: String,
@SerializedName("last-name") val lastname: String,
@SerializedName("middle-name") val middlename: String,
@SerializedName("height") val height: Int,
@SerializedName("weight") val weight: Int
)
| 0 | Kotlin | 0 | 1 | 8cb0779a04cb28babd8645fa9f7a9065d0ca745e | 515 | blood-pressure-diary | Apache License 2.0 |
src/rider/main/kotlin/com/jetbrains/rider/plugins/efcore/features/migrations/add/AddMigrationCommand.kt | JetBrains | 426,422,572 | false | {"Kotlin": 210142, "C#": 38911} | package com.jetbrains.rider.plugins.efcore.features.migrations.add
import com.jetbrains.rider.plugins.efcore.features.shared.dialog.DialogCommand
import com.jetbrains.rider.plugins.efcore.features.shared.dialog.DialogCommonOptions
class AddMigrationCommand(
common: DialogCommonOptions,
val migrationName: String,
val outputFolder: String
) : DialogCommand(common) | 27 | Kotlin | 15 | 177 | a155d33ef5121551707ad65251d0dffecdef640c | 378 | rider-efcore | MIT License |
app/src/main/kotlin/libmensago/Schema.kt | mensago | 345,165,883 | false | {"Kotlin": 1004519} | package libmensago
import keznacl.CryptoString
import keznacl.Hash
import libkeycard.*
/**
* Enum class for denoting MsgField types during Schema validation
*
* @see MsgField
* @see Schema
*/
enum class MsgFieldType {
CryptoString,
Domain,
Hash,
Integer,
Long,
MAddress,
Path,
RandomID,
String,
UnixTime,
UserID,
}
/**
* The MsgField type contains validation information about a message field.
*
* @see Schema
*/
data class MsgField(val name: String, val type: MsgFieldType, val req: Boolean)
/**
* The Schema class is used for validating attached message data and converting it to the desired
* data types.
*
* @return True on success and null on failure.
* @see MsgField
* @see MsgFieldType
*/
class Schema(vararg args: MsgField) {
val fields = args.associateBy { it.name }
/**
* Validates the data map passed to it and executes the handler code if validation should fail
*
* @return True if the data map passes validation and null if not. False is never returned.
*/
fun validate(data: Map<String, String>, failHandler: (String, Throwable) -> Unit): Boolean? {
for (field in fields.values) {
if (!data.containsKey(field.name)) {
if (field.req) {
val out = MissingFieldException()
failHandler(field.name, out)
return null
}
continue
}
val isValid = when (field.type) {
MsgFieldType.CryptoString, MsgFieldType.Hash ->
CryptoString.checkFormat(data[field.name]!!)
MsgFieldType.Domain -> Domain.checkFormat(data[field.name]!!)
MsgFieldType.Integer -> {
val result = runCatching { data[field.name]!!.toInt() }
if (result.isSuccess)
result.getOrNull()!! >= 0
else
false
}
MsgFieldType.Long -> {
val result = runCatching { data[field.name]!!.toLong() }
if (result.isSuccess)
result.getOrNull()!! >= 0
else
false
}
MsgFieldType.MAddress -> MAddress.checkFormat(data[field.name]!!)
MsgFieldType.Path -> MServerPath.checkFormat(data[field.name]!!)
MsgFieldType.RandomID -> RandomID.checkFormat(data[field.name]!!)
MsgFieldType.String -> data[field.name]!!.isNotEmpty()
MsgFieldType.UnixTime -> {
val result = runCatching { data[field.name]!!.toLong() }
if (result.isSuccess)
result.getOrNull()!! >= 0
else
false
}
MsgFieldType.UserID -> UserID.checkFormat(data[field.name]!!)
}
if (!isValid) {
val out = BadFieldValueException()
failHandler(field.name, out)
return null
}
}
return true
}
/**
* Returns the requested field as a CryptoString or null if (a) the field isn't in the schema or
* (b) the field's data is invalid or isn't present in the case of optional fields.
*/
fun getCryptoString(field: String, data: Map<String, String>): CryptoString? {
if (field !in fields.keys || field !in data.keys) return null
return CryptoString.fromString(data[field]!!)
}
/**
* Returns the requested field as a Domain or null if (a) the field isn't in the schema or
* (b) the field's data is invalid or isn't present in the case of optional fields.
*/
fun getDomain(field: String, data: Map<String, String>): Domain? {
if (field !in fields.keys) return null
return Domain.fromString(data[field])
}
/**
* Returns the requested field as a Hash or null if (a) the field isn't in the schema or
* (b) the field's data is invalid or isn't present in the case of optional fields.
*/
fun getHash(field: String, data: Map<String, String>): CryptoString? {
if (field !in fields.keys || field !in data.keys) return null
return Hash.fromString(data[field]!!)
}
/**
* Returns the requested field as an Int or null if (a) the field isn't in the schema or
* (b) the field's data is invalid or isn't present in the case of optional fields. Because the
* API does not deal in negative values, integers returned by this call are non-negative, but
* the call does not return UInt for compatibility reasons -- Int is used everywhere in the
* Java API. :(
*/
fun getInteger(field: String, data: Map<String, String>): Int? {
if (field !in fields.keys || field !in data.keys) return null
return runCatching {
val out = data[field]!!.toInt()
if (out >= 0) out else null
}.getOrElse { null }
}
/**
* Returns the requested field as a Long or null if (a) the field isn't in the schema or
* (b) the field's data is invalid or isn't present in the case of optional fields. Because the
* API does not deal in negative values, integers returned by this call are non-negative, but
* the call does not return UInt for compatibility reasons -- Int is used everywhere in the
* Java API. :(
*/
fun getLong(field: String, data: Map<String, String>): Long? {
if (field !in fields.keys || field !in data.keys) return null
return runCatching {
val out = data[field]!!.toLong()
if (out >= 0) out else null
}.getOrElse { null }
}
/**
* Returns the requested field as a MAddress or null if (a) the field isn't in the schema or
* (b) the field's data is invalid or isn't present in the case of optional fields.
*/
fun getMAddress(field: String, data: Map<String, String>): MAddress? {
if (field !in fields.keys) return null
return MAddress.fromString(data[field])
}
/**
* Returns the requested field as an MServerPath or null if (a) the field isn't in the schema or
* (b) the field's data is invalid or isn't present in the case of optional fields.
*/
fun getPath(field: String, data: Map<String, String>): MServerPath? {
if (field !in fields.keys || field !in data.keys) return null
return MServerPath.fromString(data[field]!!)
}
/**
* Returns the requested field as a RandomID or null if (a) the field isn't in the schema or
* (b) the field's data is invalid or isn't present in the case of optional fields.
*/
fun getRandomID(field: String, data: Map<String, String>): RandomID? {
if (field !in fields.keys) return null
return RandomID.fromString(data[field])
}
/**
* Returns the requested field as a String or null if (a) the field isn't in the schema or
* (b) the field's data is empty or isn't present in the case of optional fields.
*/
fun getString(field: String, data: Map<String, String>): String? {
if (field !in fields.keys || field !in data.keys) return null
return data[field]!!.ifEmpty { null }
}
/**
* Returns the requested field as an Int or null if (a) the field isn't in the schema or
* (b) the field's data is invalid or isn't present in the case of optional fields.
*/
fun getUnixTime(field: String, data: Map<String, String>): Long? {
if (field !in fields.keys || field !in data.keys) return null
return runCatching {
data[field]!!.toLong()
}.getOrElse { null }
}
/**
* Returns the requested field as a UserID or null if (a) the field isn't in the schema or
* (b) the field's data is invalid or isn't present in the case of optional fields.
*/
fun getUserID(field: String, data: Map<String, String>): UserID? {
if (field !in fields.keys) return null
return UserID.fromString(data[field])
}
}
| 0 | Kotlin | 0 | 0 | 9956b4687b985e86c35155e96686f27df2254e35 | 8,164 | mensagod | MIT License |
example/android/app/src/main/kotlin/com/jagritjkh/custom_clippers/example/MainActivity.kt | jagritjkh | 334,287,729 | false | {"Dart": 39157, "Swift": 404, "Kotlin": 142, "Objective-C": 38} | package com.jagritjkh.custom_clippers.example
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 1 | Dart | 1 | 7 | 0c6204db4002338c21eabddd7da6f895985d5e7a | 142 | custom_clippers | MIT License |
src/main/kotlin/no/nav/pensjon/kalkulator/person/client/pdl/dto/PersonResponseDto.kt | navikt | 596,104,195 | false | {"Kotlin": 718616, "Java": 1630, "Dockerfile": 153} | package no.nav.pensjon.kalkulator.person.client.pdl.dto
import com.fasterxml.jackson.annotation.JsonCreator
import com.fasterxml.jackson.annotation.JsonValue
import java.time.LocalDate
data class PersonResponseDto(
val data: PersonEnvelopeDto?,
val extensions: ExtensionsDto?,
val errors: List<ErrorDto>?
)
data class PersonEnvelopeDto(val hentPerson: PersonDto)
data class PersonDto(
val navn: List<NavnDto>?,
val foedsel: List<FoedselDto>?,
val sivilstand: List<SivilstandDto>?,
val adressebeskyttelse: List<AdressebeskyttelseDto>?
)
data class NavnDto(val fornavn: String)
data class FoedselDto(val foedselsdato: DateDto)
data class SivilstandDto(val type: String)
data class AdressebeskyttelseDto(val gradering: String)
data class ErrorDto(val message: String)
data class ExtensionsDto(val warnings: List<WarningDto>?)
data class WarningDto(
val query: String?,
val id: String?,
val code: String?,
val message: String?,
val details: Any?
)
data class DateDto(val value: LocalDate) {
@JsonValue
fun rawValue() = converter.toJson(value)
companion object {
val converter = DateScalarConverter()
@JsonCreator
@JvmStatic
fun create(rawValue: String) = DateDto(converter.toScalar(rawValue))
}
}
| 1 | Kotlin | 0 | 0 | d8acdd177180c838c9d94f71f0d6b276ef2d7815 | 1,303 | pensjonskalkulator-backend | MIT License |
app/src/main/java/com/github/pullrequest/di/module/ActivityModule.kt | gauravk95 | 160,923,274 | false | {"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "YAML": 1, "Markdown": 1, "Proguard": 1, "Java": 2, "XML": 23, "Kotlin": 60} | /*
Copyright 2018 Gaurav Kumar
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.github.pullrequest.di.module
import android.content.Context
import android.support.v7.app.AppCompatActivity
import com.github.pullrequest.di.ActivityContext
import com.github.pullrequest.utils.rx.AppSchedulerProvider
import com.github.pullrequest.utils.rx.SchedulerProvider
import dagger.Module
import dagger.Provides
import io.reactivex.disposables.CompositeDisposable
/**
* Modules related to activity
*
* Created by gk.
*/
@Module
class ActivityModule(private val activity: AppCompatActivity) {
@Provides
@ActivityContext
internal fun provideContext(): Context {
return activity
}
@Provides
internal fun provideActivity(): AppCompatActivity {
return activity
}
@Provides
internal fun provideCompositeDisposable(): CompositeDisposable {
return CompositeDisposable()
}
@Provides
internal fun provideSchedulerProvider(): SchedulerProvider {
return AppSchedulerProvider()
}
}
| 0 | Kotlin | 1 | 2 | edced49544fae23076740d999b0b2768f1ffee98 | 1,580 | github-pull-request-viewer | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.