path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/main/kotlin/kool/buffers operators.kt
|
kotlin-graphics
| 134,720,217
| false
| null |
package kool
import org.lwjgl.PointerBuffer
import org.lwjgl.system.Pointer
import org.lwjgl.system.Struct
import org.lwjgl.system.StructBuffer
import java.nio.*
operator fun IntBuffer.get(e: Enum<*>): Int = get(e.ordinal)
operator fun IntBuffer.set(e: Enum<*>, value: Int): IntBuffer = put(e.ordinal, value)
operator fun IntArray.get(e: Enum<*>): Int = get(e.ordinal)
operator fun IntArray.set(e: Enum<*>, int: Int) = set(e.ordinal, int)
/** for opengl */
inline fun <reified E : Enum<E>> IntBuffer(): IntBuffer = IntBuffer(enumValues<E>().size)
//operator fun <E : Enum<E>, T> Array<T>.get(enum: Enum<E>): T = get(enum.ordinal)
operator fun <T : Struct, SELF : StructBuffer<T, SELF>> StructBuffer<T, SELF>.set(index: Int, value: T) {
put(index, value)
}
| 1
| null |
3
| 9
|
1b53bab946be2e0296e7663ca88b4210d20d84c2
| 766
|
kool
|
MIT License
|
app/src/main/kotlin/com/github/muneebwanee/dash/ui/fragments/message/InterfaceInteractorMessage.kt
|
muneebwanee
| 321,685,263
| false
| null |
package com.github.muneebwanee.dash.ui.fragments.message
import com.github.muneebwanee.dash.di.PerActivity
import com.github.muneebwanee.dash.ui.activities.base.InterfaceInteractor
/**
* Created by muneebwanee on 15/12/20.
*/
@PerActivity
interface InterfaceInteractorMessage<V : InterfaceViewMessage> : InterfaceInteractor<V>
| 4
|
Kotlin
|
37
| 81
|
1fa68abddacedc7866cc09c6908f885fc9bf0281
| 330
|
Dash
|
Apache License 2.0
|
app/src/main/kotlin/com/github/muneebwanee/dash/ui/fragments/message/InterfaceInteractorMessage.kt
|
muneebwanee
| 321,685,263
| false
| null |
package com.github.muneebwanee.dash.ui.fragments.message
import com.github.muneebwanee.dash.di.PerActivity
import com.github.muneebwanee.dash.ui.activities.base.InterfaceInteractor
/**
* Created by muneebwanee on 15/12/20.
*/
@PerActivity
interface InterfaceInteractorMessage<V : InterfaceViewMessage> : InterfaceInteractor<V>
| 4
|
Kotlin
|
37
| 81
|
1fa68abddacedc7866cc09c6908f885fc9bf0281
| 330
|
Dash
|
Apache License 2.0
|
app/src/main/java/com/muratozturk/breakingbad/HiltApplication.kt
|
muratozturk5
| 559,985,666
| false
|
{"Kotlin": 36465}
|
package com.muratozturk.breakingbad
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class HiltApplication : Application() {
}
| 0
|
Kotlin
|
3
| 13
|
e36da837b61e5f849e8d17252960382248124785
| 169
|
Breaking-Bad
|
MIT License
|
basics/src/main/kotlin/basics/syntax/03_functions.kt
|
bnorm
| 230,536,701
| false
| null |
package basics.syntax
//
//
//
//
//
//
//
//
//
//
/**
* Things to observe:
* 1. Function return type is list after function signature
* 2. No primitive style `int`
*/
fun sum(a: Int, b: Int): Int {
return a + b
}
//
//
//
//
//
//
//
//
//
//
/**
* Things to observe:
* 1. Simple functions can be simplified
*/
fun multiply(a: Int, b: Int) = a * b
//
//
//
//
//
//
//
//
//
//
/**
* Things to observe:
* 1. `if` is actually an expression
*/
fun max(a: Int, b: Int): Int {
return if (a > b) a else b
}
//
//
//
//
//
//
//
//
//
//
/**
* Things to observe:
* 1. `..` as range operator
* 2. `for` loop only supports for-each style
* 3. Index access to `List` is similar to `Array`
*/
fun max(values: List<Int>): Int? {
var max: Int? = null
for (i in 0..values.size - 1) {
max = max(max ?: Int.MIN_VALUE, values[i])
}
return max
}
//
//
//
//
//
//
//
//
//
//
/**
* Things to observe:
* 1. `when` keyword instead of `switch`
* 2. Instance checks use `is`
*/
fun name(obj: Any): String {
return when (obj) {
1 -> "One"
"Hello" -> "Greeting"
is Long -> "Long"
!is String -> "Not a string"
else -> "Unknown"
}
}
//
//
//
//
//
//
//
//
//
//
/**
* Things to observe:
* 1. Default parameters
* 2. No `new` keyword for object instantiation
* 3. Names of parameters can be used and reordered
*/
fun joinToString(
list: Iterable<String>,
separator: String = ", ",
prefix: String = "",
postfix: String = ""
): String {
val buffer = StringBuffer()
buffer.append(prefix)
var count = 0
for (element in list) {
if (++count > 1) buffer.append(separator)
buffer.append(element)
}
buffer.append(postfix)
return buffer.toString()
}
fun main() {
val names = listOf("Ed", "Marc", "Mark", "Mike")
println(joinToString(names, prefix = "Our Founders are ", separator = " and "))
}
//
//
//
//
//
//
//
//
//
//
fun exceptions() {
try {
throw Exception()
} catch (t: Throwable) {
t.printStackTrace()
}
}
//
//
//
//
//
//
//
//
//
//
| 0
|
Kotlin
|
0
| 0
|
031f454298f01a7fc8078e781e6d2780c6812694
| 2,204
|
kotlin.examples
|
Apache License 2.0
|
basics/src/main/kotlin/basics/syntax/03_functions.kt
|
bnorm
| 230,536,701
| false
| null |
package basics.syntax
//
//
//
//
//
//
//
//
//
//
/**
* Things to observe:
* 1. Function return type is list after function signature
* 2. No primitive style `int`
*/
fun sum(a: Int, b: Int): Int {
return a + b
}
//
//
//
//
//
//
//
//
//
//
/**
* Things to observe:
* 1. Simple functions can be simplified
*/
fun multiply(a: Int, b: Int) = a * b
//
//
//
//
//
//
//
//
//
//
/**
* Things to observe:
* 1. `if` is actually an expression
*/
fun max(a: Int, b: Int): Int {
return if (a > b) a else b
}
//
//
//
//
//
//
//
//
//
//
/**
* Things to observe:
* 1. `..` as range operator
* 2. `for` loop only supports for-each style
* 3. Index access to `List` is similar to `Array`
*/
fun max(values: List<Int>): Int? {
var max: Int? = null
for (i in 0..values.size - 1) {
max = max(max ?: Int.MIN_VALUE, values[i])
}
return max
}
//
//
//
//
//
//
//
//
//
//
/**
* Things to observe:
* 1. `when` keyword instead of `switch`
* 2. Instance checks use `is`
*/
fun name(obj: Any): String {
return when (obj) {
1 -> "One"
"Hello" -> "Greeting"
is Long -> "Long"
!is String -> "Not a string"
else -> "Unknown"
}
}
//
//
//
//
//
//
//
//
//
//
/**
* Things to observe:
* 1. Default parameters
* 2. No `new` keyword for object instantiation
* 3. Names of parameters can be used and reordered
*/
fun joinToString(
list: Iterable<String>,
separator: String = ", ",
prefix: String = "",
postfix: String = ""
): String {
val buffer = StringBuffer()
buffer.append(prefix)
var count = 0
for (element in list) {
if (++count > 1) buffer.append(separator)
buffer.append(element)
}
buffer.append(postfix)
return buffer.toString()
}
fun main() {
val names = listOf("Ed", "Marc", "Mark", "Mike")
println(joinToString(names, prefix = "Our Founders are ", separator = " and "))
}
//
//
//
//
//
//
//
//
//
//
fun exceptions() {
try {
throw Exception()
} catch (t: Throwable) {
t.printStackTrace()
}
}
//
//
//
//
//
//
//
//
//
//
| 0
|
Kotlin
|
0
| 0
|
031f454298f01a7fc8078e781e6d2780c6812694
| 2,204
|
kotlin.examples
|
Apache License 2.0
|
mastodon4j/src/main/java/com/sys1yagi/mastodon4j/api/entity/Card.kt
|
sys1yagi
| 88,990,462
| false
| null |
package com.sys1yagi.mastodon4j.api.entity
import com.google.gson.annotations.SerializedName
/**
* see more https://github.com/tootsuite/documentation/blob/master/Using-the-API/API.md#card
*/
class Card(
@SerializedName("url")
val url: String = "",
@SerializedName("title")
val title: String = "",
@SerializedName("description")
val description: String = "",
@SerializedName("image")
val image: String = "") {
}
| 23
|
Kotlin
|
18
| 91
|
b7fbb565abd024ce113e3a6f0caf2eb9bbc10fc7
| 483
|
mastodon4j
|
MIT License
|
src/main/kotlin/no/nav/eessi/pensjon/fagmodul/config/KafkaErrorHandler.kt
|
navikt
| 178,813,650
| false
| null |
package no.nav.eessi.pensjon.config
import org.apache.kafka.clients.consumer.Consumer
import org.apache.kafka.clients.consumer.ConsumerRecord
import org.slf4j.LoggerFactory
import org.springframework.context.annotation.Profile
import org.springframework.kafka.listener.ContainerAwareErrorHandler
import org.springframework.kafka.listener.ContainerStoppingErrorHandler
import org.springframework.kafka.listener.MessageListenerContainer
import org.springframework.stereotype.Component
import java.io.PrintWriter
import java.io.StringWriter
@Profile("prod")
@Component
class KafkaErrorHandler : ContainerAwareErrorHandler {
private val logger = LoggerFactory.getLogger(KafkaErrorHandler::class.java)
private val stopper = ContainerStoppingErrorHandler()
override fun handle(
thrownException: java.lang.Exception,
records: MutableList<ConsumerRecord<*, *>>?,
consumer: Consumer<*, *>,
container: MessageListenerContainer
) {
val stacktrace = StringWriter()
thrownException.printStackTrace(PrintWriter(stacktrace))
logger.error("En feil oppstod under kafka konsumering av meldinger: \n ${hentMeldinger(records)} \n" +
"Stopper containeren ! Restart er nødvendig for å fortsette konsumering, $stacktrace")
stopper.handle(thrownException, records, consumer, container)
}
fun hentMeldinger(records: MutableList<ConsumerRecord<*, *>>?): String {
var meldinger = ""
records?.forEach { it ->
meldinger += "--------------------------------------------------------------------------------\n"
meldinger += it.toString()
meldinger += "\n"
}
return meldinger
}
}
| 2
| null |
1
| 4
|
cae98846b6d85aaf567e055dc86189b01600ce03
| 1,731
|
eessi-pensjon-journalforing
|
MIT License
|
next/kmp/browser/src/commonMain/kotlin/org/dweb_browser/browser/desk/DesktopControllerRender.kt
|
BioforestChain
| 594,577,896
| false
|
{"Kotlin": 2719211, "TypeScript": 733573, "Swift": 350492, "Vue": 150380, "SCSS": 39016, "Objective-C": 17350, "HTML": 13200, "Shell": 11193, "JavaScript": 3998, "CSS": 818}
|
package org.dweb_browser.browser.desk
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.twotone.Error
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.key
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import org.dweb_browser.browser.desk.render.NewDesktopView
import org.dweb_browser.core.module.NativeMicroModule
import org.dweb_browser.dwebview.Render
import org.dweb_browser.helper.compose.ENV_SWITCH_KEY
import org.dweb_browser.helper.compose.LocalCompositionChain
import org.dweb_browser.helper.compose.envSwitch
import org.dweb_browser.helper.platform.SetSystemBarsColor
import org.dweb_browser.sys.window.core.constant.LocalWindowMM
import org.dweb_browser.sys.window.render.SceneRender
@Composable
fun DesktopController.Render(
desktopController: DesktopController,
taskbarController: TaskbarController,
microModule: NativeMicroModule.NativeRuntime,
) {
// TODO 这里的颜色应该是自动适应的,特别是窗口最大化的情况下,遮盖了顶部 status-bar 的时候,需要根据 status-bar 来改变颜色
SetSystemBarsColor(Color.Transparent, if (isSystemInDarkTheme()) Color.White else Color.Black)
LocalCompositionChain.current.Provider(
LocalWindowMM provides microModule,
) {
Box(modifier = Modifier.fillMaxWidth()) {
if (remember { envSwitch.isEnabled(ENV_SWITCH_KEY.DESKTOP_STYLE_COMPOSE) }) {
NewDesktopView(desktopController, microModule)
} else {
DesktopView {
Render(Modifier.fillMaxSize())
}
}
/// 窗口视图
DesktopWindowsManager {
SceneRender()
}
}
/// 悬浮框
Box(contentAlignment = Alignment.TopStart, modifier = Modifier) {
taskbarController.TaskbarView { FloatWindow() }
}
/// 错误信息
for (message in alertMessages) {
key(message) {
val dismissHandler = {
alertMessages.remove(message);
}
AlertDialog(onDismissRequest = {
dismissHandler()
}, icon = {
Icon(Icons.TwoTone.Error, contentDescription = "error")
}, title = {
Text(message.title)
}, text = {
Text(message.message)
}, confirmButton = {
Button(onClick = { dismissHandler() }) {
Text("关闭")
}
})
}
break
}
/// 新版本
// newVersionController.NewVersionView() // 先不搞这个
}
}
| 60
|
Kotlin
|
4
| 11
|
8ef7e1f585c6eaf4c508681173bf729dadb82536
| 2,822
|
dweb_browser
|
MIT License
|
app/src/main/java/com/ztute/memereview/domain/repository/DefaultMemeRepository.kt
|
SrikantPadala
| 471,776,177
| false
| null |
package com.ztute.memereview.domain.repository
import com.ztute.memereview.database.DatabaseMeme
import com.ztute.memereview.database.MemeDao
import com.ztute.memereview.network.MemeNetworkResponse
import com.ztute.memereview.network.MemeReviewApiService
import com.ztute.memereview.network.ResultWrapper
import com.ztute.memereview.network.safeApiCall
import kotlinx.coroutines.Dispatchers
import javax.inject.Inject
class DefaultMemeRepository @Inject constructor(
private val memeDao: MemeDao,
private val memeReviewApiService: MemeReviewApiService
) : MemeRepository {
override suspend fun refreshMemes(): ResultWrapper<MemeNetworkResponse> {
return safeApiCall(Dispatchers.IO) { memeReviewApiService.getMemes() }
}
override suspend fun cacheData(memeList: List<DatabaseMeme>) {
memeDao.insertAll(*memeList.toTypedArray())
}
override suspend fun getMemes(): List<DatabaseMeme> = memeDao.getMemes()
}
| 0
|
Kotlin
|
0
| 0
|
7a4f82346c45c350a1e7024ba021398a8e871756
| 952
|
MemeReview
|
Apache License 2.0
|
client_end_user/shared/src/commonMain/kotlin/presentation/search/SearchScreen.kt
|
TheChance101
| 671,967,732
| false
| null |
package presentation.search
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import cafe.adriel.voyager.navigator.Navigator
import com.beepbeep.designSystem.ui.composable.BpImageLoader
import com.beepbeep.designSystem.ui.composable.BpSimpleTextField
import com.beepbeep.designSystem.ui.theme.Theme
import kotlinx.coroutines.delay
import org.jetbrains.compose.resources.ExperimentalResourceApi
import org.jetbrains.compose.resources.painterResource
import presentation.auth.login.LoginScreen
import presentation.base.BaseScreen
import presentation.cart.CartScreen
import presentation.composable.BottomSheet
import presentation.composable.MealBottomSheet
import presentation.composable.MealCard
import presentation.composable.ModalBottomSheetState
import presentation.composable.modifier.noRippleEffect
import presentation.composable.modifier.roundedBorderShape
import presentation.resturantDetails.Composable.NeedToLoginSheet
import presentation.composable.ToastMessage
import presentation.resturantDetails.Composable.WarningCartIsFullDialog
import presentation.resturantDetails.RestaurantScreen
import resources.Resources
import util.getNavigationBarPadding
import util.getStatusBarPadding
import util.root
class SearchScreen :
BaseScreen<SearchScreenModel, SearchUiState, SearchUiEffect, SearchInteractionListener>() {
@Composable
override fun Content() {
initScreen(getScreenModel())
}
override fun onEffect(effect: SearchUiEffect, navigator: Navigator) {
when (effect) {
is SearchUiEffect.NavigateToRestaurant -> navigator.root?.push(RestaurantScreen(effect.restaurantId))
is SearchUiEffect.NavigateToLogin -> navigator.push(LoginScreen())
is SearchUiEffect.onGoToCart -> navigator.root?.push(CartScreen())
}
}
@Composable
override fun onRender(state: SearchUiState, listener: SearchInteractionListener) {
val sheetState = remember { ModalBottomSheetState() }
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.TopCenter
) {
WarningCartIsFullDialog(
modifier = Modifier.padding(getNavigationBarPadding()),
text = Resources.strings.addFromDifferentCartMessage,
onClickClearCart = listener::onClearCart,
onClickGoToCart = listener::onGoToCart,
onDismiss = listener::onDismissSheet,
isVisitable = state.showWarningCartIsFull
)
BottomSheet(
sheetContent = {
if (state.showMealSheet)
MealBottomSheet(
meal = state.selectedMeal,
isLoading = state.isAddToCartLoading,
onAddToCart = listener::onAddToCart,
onDismissSheet = listener::onDismissSheet,
onIncreaseQuantity = listener::onIncreaseMealQuantity,
onDecreaseQuantity = listener::onDecreaseMealQuantity
)
if (state.showLoginSheet)
NeedToLoginSheet(
text = Resources.strings.loginToAddToFavourite,
onClick = listener::onLoginClicked,
)
},
sheetBackgroundColor = Theme.colors.background,
onBackGroundClicked = listener::onDismissSheet,
sheetState = sheetState,
content = { content(state, listener) }
)
LaunchedEffect(state.showToast) {
if (state.showToast) {
delay(2000)
listener.onDismissSnackBar()
}
}
LaunchedEffect(state.showToastClearCart) {
if (state.showToastClearCart) {
delay(2000)
listener.onDismissSnackBar()
}
}
ToastMessage(
modifier = Modifier.align(Alignment.BottomCenter),
state = state.showToast,
message = if (state.errorAddToCart == null)
Resources.strings.mealAddedToYourCart else Resources.strings.mealFailedToAddInCart,
isError = state.errorAddToCart != null
)
ToastMessage(
modifier = Modifier.align(Alignment.BottomCenter),
state = state.showToastClearCart,
message = Resources.strings.youCanAddMeal ,
isError = false
)
}
LaunchedEffect(state.showMealSheet, state.showLoginSheet) {
if (state.showMealSheet || state.showLoginSheet) {
sheetState.show()
} else {
sheetState.dismiss()
}
}
}
@OptIn(ExperimentalFoundationApi::class, ExperimentalResourceApi::class)
@Composable
private fun content(
state: SearchUiState,
listener: SearchInteractionListener,
modifier: Modifier = Modifier,
) {
LazyColumn(
modifier = modifier
.fillMaxSize()
.background(Theme.colors.background)
.padding(getStatusBarPadding())
.padding(top = 16.dp),
verticalArrangement = Arrangement.spacedBy(16.dp),
contentPadding = PaddingValues(bottom = 16.dp)
) {
stickyHeader {
BpSimpleTextField(
state.query,
hint = Resources.strings.searchHint,
hintColor = Theme.colors.contentSecondary,
onValueChange = listener::onSearchInputChanged,
onClick = {},
leadingPainter = painterResource(Resources.images.searchOutlined),
modifier = Modifier.background(Theme.colors.background)
.padding(horizontal = 16.dp),
)
}
item {
LazyRow(
contentPadding = PaddingValues(horizontal = 16.dp),
horizontalArrangement = Arrangement.spacedBy(16.dp)
) {
items(state.restaurants) {
Restaurant(
restaurant = it,
onClick = listener::onRestaurantClicked
)
}
}
}
items(state.meals) {
MealCard(
meal = it,
modifier = Modifier.noRippleEffect { listener.onMealClicked(it) }
)
}
}
}
@Composable
private fun Restaurant(
restaurant: RestaurantUiState,
onClick: (String) -> Unit,
modifier: Modifier = Modifier,
) {
Column(
modifier = modifier.widthIn(max = 64.dp).noRippleEffect { onClick(restaurant.id) },
verticalArrangement = Arrangement.spacedBy(8.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
BpImageLoader(
modifier = Modifier.roundedBorderShape().size(64.dp),
imageUrl = restaurant.image,
errorPlaceholderImageUrl = Resources.images.restaurantErrorPlaceholder,
contentDescription = restaurant.name,
)
Text(
text = restaurant.name,
style = Theme.typography.body,
color = Theme.colors.contentPrimary,
maxLines = 2,
textAlign = TextAlign.Center,
overflow = TextOverflow.Ellipsis
)
}
}
}
| 5
| null |
55
| 572
|
1d2e72ba7def605529213ac771cd85cbab832241
| 8,800
|
beep-beep
|
Apache License 2.0
|
kittybot/src/main/kotlin/org/bezsahara/kittybot/bot/dispatchers/y/scopes/CommandScope.kt
|
bezsahara
| 846,146,531
| false
|
{"Kotlin": 752625}
|
package org.bezsahara.kittybot.bot.dispatchers.y.scopes
import org.bezsahara.kittybot.bot.KittyBot
import org.bezsahara.kittybot.telegram.classes.messages.inaccessible.Message
class CommandScope(
bot: KittyBot,
message: Message,
@JvmField val commandArgs: String?
) : MessageScope(message, bot)
| 0
|
Kotlin
|
1
| 5
|
a0b831c9f4ad00f681b2bfba5376e321766a8cfe
| 308
|
TelegramKitty
|
MIT License
|
dynatest-engine/src/test/kotlin/com/github/mvysny/dynatest/DynaTestEngineTest.kt
|
mvysny
| 120,896,466
| false
|
{"Kotlin": 111405}
|
package com.github.mvysny.dynatest
import java.io.IOException
import java.lang.IllegalArgumentException
import kotlin.test.expect
import kotlin.test.fail
/**
* Bunch of tests for the engine.
*
* If you add tests here, don't forget to fix the `build.gradle.kts` - there is a check that there are in fact 33
* test methods executed by this test.
*/
class DynaTestEngineTest : DynaTest({
group("test the 'beforeEach' behavior") {
test("test that beforeEach runs before every test") {
runTests {
var called = false
test("check that 'beforeEach' ran") {
expect(true) { called }
}
beforeEach { called = true }
}
}
test("test that 'beforeEach' is also applied to tests nested inside a child group") {
runTests {
var called = false
// an artificial group, only for the purpose of nesting the test that checks whether the 'beforeEach' block ran
group("artificial group") {
test("check that 'beforeEach' ran") {
expect(true) { called }
}
}
beforeEach { called = true }
}
}
test("when beforeEach throws, the test is not called") {
expectFailures({
runTests {
beforeEach { throw RuntimeException("expected") }
test("should not have been called") { fail("should not have been called since beforeEach failed") }
}
}) {
expectStats(0, 1, 0)
expectFailure<RuntimeException>("should not have been called")
}
}
test("when beforeEach throws, the afterEach is still called") {
var called = false
expectFailures({
runTests {
beforeEach { throw RuntimeException("expected") }
test("should not have been called") { fail("should not have been called since beforeEach failed") }
afterEach { called = true }
}
}) {
expectStats(0, 1, 0)
expectFailure<RuntimeException>("should not have been called")
}
expect(true) { called }
}
}
group("test the 'afterEach' behavior") {
test("test that 'afterEach' runs after every test") {
lateinit var outcome: Outcome
runTests {
afterEach { outcome = it }
test("dummy test which triggers 'afterEach'") {}
}
expect(true) { outcome.isSuccess }
}
test("test that 'afterEach' is also applied to tests nested inside a child group") {
var called = 0
runTests {
afterEach { called++ }
// an artificial group, only for the purpose of nesting the test that checks whether the 'afterEach' block ran
group("artificial group") {
test("dummy test which triggers 'afterEach'") {}
}
}
expect(1) { called }
}
test("when both beforeEach and afterEach throws, the afterEach's exception is added as suppressed") {
var called = false
expectFailures({
runTests {
beforeEach { throw RuntimeException("expected") }
test("should not have been called") { called = true; fail("should not have been called since beforeEach failed") }
afterEach { throw IOException("simulated") }
}
}) {
expectStats(0, 1, 0)
expect<Class<out Throwable>>(IOException::class.java) { getFailure("should not have been called").suppressed[0].javaClass }
}
expect(false) { called }
}
test("throwing in `afterEach` will make the test fail") {
expectFailures({
runTests {
test("dummy") {}
afterEach { throw IOException("simulated") }
}
}) {
expectStats(0, 1, 0)
expectFailure<IOException>("dummy")
}
}
test("throwing in test should invoke all `afterEach`") {
expectFailures({
runTests {
test("simulated failure") { throw RuntimeException("simulated") }
afterEach { throw IOException("simulated") }
}
}) {
expectStats(0, 1, 0)
expect<Class<out Throwable>>(IOException::class.java) { getFailure("simulated failure").suppressed[0].javaClass }
}
}
test("all `afterEach` should have been invoked even if some of them fail") {
lateinit var outcome: Outcome
expectFailures({
runTests {
test("dummy") {}
afterEach { throw RuntimeException("simulated") }
afterEach { outcome = it }
}
}) {
expectStats(0, 1, 0)
expectFailure<RuntimeException>("dummy")
}
expect(true) { outcome.isFailure }
expect<Class<*>?>(RuntimeException::class.java) { outcome.failureCause?.javaClass }
expect("simulated") { outcome.failureCause?.message }
}
test("if `beforeEach` fails, no `afterEach` in subgroup should be called") {
var called = false
expectFailures({
runTests {
beforeEach { throw RuntimeException("simulated") }
group("nested group") {
test("dummy") { called = true; fail("should not have been called") }
afterEach { called = true; fail("should not have been called") }
}
}
}) {
expectStats(0, 1, 0)
expectFailure<RuntimeException>("dummy")
expect(listOf()) { getFailure("dummy").suppressed.toList() }
}
expect(false) { called }
}
}
group("test the 'beforeGroup' behavior") {
test("simple before-test") {
var called = false
runTests {
test("check that 'beforeGroup' ran") {
expect(true) { called }
}
beforeGroup { called = true }
}
expect(true) { called }
}
test("before-group") {
var called = false
runTests {
group("artificial group") {
test("check that 'beforeEach' ran") {
expect(true) { called }
}
}
beforeGroup { called = true }
}
expect(true) { called }
}
group("test when `beforeGroup` fails") {
test("`beforeEach`, `test`, `afterEach`, `afterGroup` doesn't get called when `beforeGroup` fails") {
var called = false
expectFailures({
runTests {
beforeGroup { throw RuntimeException("Simulated") }
beforeEach { called = true; fail("shouldn't be called") }
test("shouldn't be called") { called = true; fail("shouldn't be called") }
afterEach { called = true; fail("shouldn't be called") }
}
}) {
expectStats(0, 1, 0)
expectFailure<RuntimeException>("root")
expect(0) { getFailure("root").suppressed.size }
}
expect(false) { called }
}
}
}
group("test the 'afterGroup' behavior") {
test("simple after-test") {
var called = 0
runTests {
afterGroup { called++ }
test("dummy test") {}
test("dummy test2") {}
}
expect(1) { called }
}
test("`afterGroup` is called only once even when there are nested groups") {
var called = 0
runTests {
afterGroup { called++ }
group("artificial group") {
test("dummy test which triggers 'afterEach'") {}
}
}
expect(1) { called }
}
group("exceptions") {
test("`afterGroup` is called even if `beforeGroup` fails") {
var called = 0
expectFailures({
runTests {
beforeGroup { throw RuntimeException("Simulated") }
afterGroup { called++ }
}
}) {
expectStats(0, 1, 0)
}
expect(1) { called }
}
test("Exceptions thrown in `afterGroup` are attached as suppressed to the exception thrown in `beforeGroup`") {
expectFailures({
runTests {
beforeGroup { throw RuntimeException("Simulated") }
afterGroup { throw IOException("Simulated") }
}
}) {
expectStats(0, 1, 0)
expectFailure<RuntimeException>("root")
expect<Class<out Throwable>>(IOException::class.java) { getFailure("root").suppressed[0].javaClass }
}
}
test("Exceptions thrown from `beforeGroup` do not prevent other groups from running") {
var called = false
expectFailures({
runTests {
group("failing group") {
beforeGroup { throw RuntimeException("Simulated") }
}
group("successful group") {
test("test") { called = true }
}
}
}) {
expectStats(1, 1, 0)
expectFailure<RuntimeException>("failing group")
}
expect(true) { called }
}
test("Failure in `afterGroup` won't prevent `afterGroup` from being called in the parent group") {
var called = false
expectFailures({
runTests {
group("Failing group") {
test("dummy") {}
afterGroup { throw RuntimeException("Simulated") }
}
afterGroup { called = true }
}
}) {
expectStats(1, 1, 0)
}
expect(true) { called }
}
test("Failure in a test won't prevent `afterGroup` from being called") {
var called = false
expectFailures({
runTests {
test("failing") { fail("simulated") }
afterGroup { called = true }
}
}) {
expectStats(0, 1, 0)
}
expect(true) { called }
}
test("Failure in a `afterEach` won't prevent `afterGroup` from being called") {
var called = false
expectFailures({
runTests {
test("dummy") {}
afterEach { throw RuntimeException("Simulated") }
afterGroup { called = true }
}
}) {
expectStats(0, 1, 0)
}
expect(true) { called }
}
}
}
group("nesting DynaTest inside a test block is forbidden") {
test("calling test") {
var called = false
expectFailures({
runTests {
test("should fail") {
this@runTests.test("can't define a test inside a test") { called = true }
}
}
}) {
expectStats(0, 1, 0)
expectFailure<IllegalStateException>("should fail")
}
expect(false) { called }
}
test("calling beforeGroup") {
var called = false
expectFailures({
runTests {
test("should fail") {
this@runTests.beforeGroup { called = true }
}
}
}) {
expectStats(0, 1, 0)
expectFailure<IllegalStateException>("should fail")
}
expect(false) { called }
}
test("calling beforeEach") {
var called = false
expectFailures({
runTests {
test("should fail") {
this@runTests.beforeEach { called = true }
}
}
}) {
expectStats(0, 1, 0)
expectFailure<IllegalStateException>("should fail")
}
expect(false) { called }
}
test("calling afterEach") {
var called = false
expectFailures({
runTests {
test("should fail") {
this@runTests.afterEach { called = true }
}
}
}) {
expectStats(0, 1, 0)
expectFailure<IllegalStateException>("should fail")
}
expect(false) { called }
}
test("calling afterGroup") {
var called = false
expectFailures({
runTests {
test("should fail") {
this@runTests.afterGroup { called = true }
}
}
}) {
expectStats(0, 1, 0)
expectFailure<IllegalStateException>("should fail")
}
expect(false) { called }
}
}
group("make sure Gradle runs same-named tests") {
// this is actually checked by the build.gradle.kts
group("group 1") {
test("a test") { "foo".indices.count { "foo".substring(it).startsWith("bar") } }
}
group("group 2") {
test("a test") {}
}
}
// intellij gets confused and only runs the first test; even if the second one fails, the failure is not reported
// in the UI.
group("prohibit same-named tests/groups in the same group") {
test("test/test") {
var called = 0
expectThrows<IllegalArgumentException>("test/group with name 'duplicite' is already present: duplicite") {
runTests {
test("duplicite") { called++; fail("shouldn't be called") }
test("duplicite") { called++; fail("shouldn't be called") }
}
}
expect(0) { called }
}
test("test/group") {
var called = 0
expectThrows<IllegalArgumentException>("test/group with name 'duplicite' is already present: duplicite") {
runTests {
test("duplicite") { called++; fail("shouldn't be called") }
group("duplicite") { called++; fail("shouldn't be called") }
}
}
expect(0) { called }
}
test("group/test") {
var called = 0
expectThrows<IllegalArgumentException>("test/group with name 'duplicite' is already present: duplicite") {
runTests {
group("duplicite") { }
test("duplicite") { called++; fail("shouldn't be called") }
}
}
expect(0) { called }
}
test("group/group") {
var called = 0
expectThrows(IllegalArgumentException::class, "test/group with name 'duplicite' is already present: duplicite") {
runTests {
group("duplicite") { }
group("duplicite") { called++; fail("shouldn't be called") }
}
}
expect(0) { called }
}
}
group("xtest") {
test("xtest body not called") {
var called = 0
runTests {
xtest("xtest") { called++ }
}
expect(0) { called }
}
test("beforeEach/afterEach not called") {
var called = 0
runTests {
beforeEach { called++ }
afterEach { called++ }
xtest("test") { called++ }
}
expect(0) { called }
}
test("parent beforeEach/afterEach not called") {
var called = 0
runTests {
beforeEach { called++ }
afterEach { called++ }
group("foo") {
xtest("test") { called++ }
}
}
expect(0) { called }
}
test("beforeGroup/afterGroup still called since the group is enabled") {
var called = 0
runTests {
beforeGroup { called++ }
afterGroup { called++ }
xtest("test") { called++ }
}
expect(2) { called }
}
test("parent beforeGroup/afterGroup still called since the group is enabled") {
var called = 0
runTests {
beforeGroup { called++ }
afterGroup { called++ }
group("foo") {
xtest("test") { called++ }
}
}
expect(2) { called }
}
xtest("this test must be marked in intellij as skipped") {
fail("should be skipped")
}
}
group("xgroup") {
test("tests not called") {
var called = 0
runTests {
xgroup("xgroup") {
test("should be skipped") { called++ }
}
}
expect(0) { called }
}
test("beforeEach/afterEach not called") {
var called = 0
runTests {
xgroup("disabled") {
beforeEach { called++; fail("x") }
afterEach { called++; fail("x") }
test("test") { called++; fail("x") }
}
}
expect(0) { called }
}
test("parent beforeEach/afterEach not called") {
var called = 0
runTests {
beforeEach { called++; fail("x") }
afterEach { called++; fail("x") }
xgroup("disabled") {
test("test") { called++; fail("x") }
}
}
expect(0) { called }
}
test("beforeGroup/afterGroup still called since the group is enabled") {
var called = 0
runTests {
beforeGroup { called++ }
afterGroup { called++ }
xgroup("disabled") {
test("test") { called++ }
}
}
expect(2) { called }
}
test("beforeGroup/afterGroup not called for disabled group") {
var called = 0
runTests {
xgroup("disabled") {
beforeGroup { called++ }
afterGroup { called++ }
test("test") { called++ }
}
}
expect(0) { called }
}
xgroup("group must be marked in intellij as skipped") {
test("test must be marked in intellij as skipped") {
fail("should be skipped")
}
}
}
})
| 2
|
Kotlin
|
2
| 22
|
ab657fa619e6d6592108cf9b9bc5b4ea904c76f1
| 20,268
|
dynatest
|
Apache License 2.0
|
src/me/anno/graph/render/compiler/ExpressionRenderer.kt
|
AntonioNoack
| 456,513,348
| false
| null |
package me.anno.graph.render.compiler
import me.anno.ecs.components.mesh.TypeValue
import me.anno.gpu.GFX
import me.anno.gpu.GFXState
import me.anno.gpu.framebuffer.DepthBufferType
import me.anno.gpu.framebuffer.FBStack
import me.anno.gpu.shader.DepthTransforms
import me.anno.gpu.shader.GLSLType
import me.anno.gpu.shader.Shader
import me.anno.gpu.shader.ShaderLib
import me.anno.gpu.shader.builder.Variable
import me.anno.gpu.shader.builder.VariableMode
import me.anno.gpu.texture.ITexture2D
import me.anno.graph.Graph
import me.anno.graph.NodeInput
import me.anno.graph.types.FlowGraph
import me.anno.graph.types.flow.ReturnNode
import me.anno.maths.Maths
import org.joml.Vector4f
interface ExpressionRenderer {
var shader: Shader?
val graph: Graph?
val name: String
val inputs: Array<NodeInput>?
var typeValues: HashMap<String, TypeValue>?
fun getInput(index: Int): Any?
fun setInput(index: Int, value: Any?)
fun init() {
setInput(1, Vector4f(1f, 0f, 1f, 1f))
setInput(2, 256)
setInput(3, 256)
setInput(4, 4)
setInput(5, 1)
}
fun invalidate() {
shader?.destroy()
shader = null
}
fun render(fp: Boolean): ITexture2D {
// todo if input matches request, just return directly
val w = getInput(2) as Int
val h = getInput(3) as Int
val channels = Maths.clamp(getInput(4) as Int, 1, 4)
val samples = Maths.clamp(getInput(5) as Int, 1, GFX.maxSamples)
val shader = shader ?: kotlin.run {
val compiler = object : GraphCompiler(graph as FlowGraph) {
// not being used, as we only have an expression
override fun handleReturnNode(node: ReturnNode) = throw NotImplementedError()
val shader: Shader
init {
val expr = expr(inputs!![1])
defineLocalVars(builder)
val variables = typeValues.map { (k, v) -> Variable(v.type, k) } +
listOf(Variable(GLSLType.V4F, "result", VariableMode.OUT)) +
DepthTransforms.depthVars
shader = Shader(
"ExpressionRenderer", ShaderLib.coordsList, ShaderLib.coordsUVVertexShader,
ShaderLib.uvList, variables, extraFunctions.toString() +
builder.toString() +
"void main(){\n" +
" result = $expr;\n" +
"}\n"
)
shader.setTextureIndices(variables.filter { it.type.isSampler }.map { it.name })
shader.ignoreNameWarnings("d_camRot")
}
override val currentShader: Shader get() = shader
}
typeValues = compiler.typeValues
compiler.shader
}
this.shader = shader
val buffer = FBStack["expr-renderer", w, h, channels, fp, samples, DepthBufferType.NONE]
GFXState.useFrame(w, h, false, buffer) {
GFXState.renderPurely {
shader.use()
DepthTransforms.bindDepthToPosition(shader)
val tv = typeValues
if (tv != null) {
for ((k, v) in tv) {
v.bind(shader, k)
}
}
GFX.flat01.draw(shader)
}
}
return buffer.getTexture0()
}
}
| 0
|
Kotlin
|
3
| 9
|
566e183d43bff96ee3006fecf0142e6d20828857
| 3,544
|
RemsEngine
|
Apache License 2.0
|
src/main/kotlin/uk/gov/justice/digital/hmpps/locationsinsideprison/service/LocationService.kt
|
ministryofjustice
| 738,978,080
| false
| null |
package uk.gov.justice.digital.hmpps.locationsinsideprison.service
import com.fasterxml.jackson.annotation.JsonInclude
import com.microsoft.applicationinsights.TelemetryClient
import io.swagger.v3.oas.annotations.media.Schema
import jakarta.persistence.EntityManager
import jakarta.persistence.EntityNotFoundException
import jakarta.validation.ValidationException
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.data.domain.Page
import org.springframework.data.domain.PageRequest
import org.springframework.data.domain.Pageable
import org.springframework.data.domain.Sort
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import uk.gov.justice.digital.hmpps.locationsinsideprison.dto.CreateNonResidentialLocationRequest
import uk.gov.justice.digital.hmpps.locationsinsideprison.dto.CreateResidentialLocationRequest
import uk.gov.justice.digital.hmpps.locationsinsideprison.dto.CreateWingRequest
import uk.gov.justice.digital.hmpps.locationsinsideprison.dto.LegacyLocation
import uk.gov.justice.digital.hmpps.locationsinsideprison.dto.LocationGroupDto
import uk.gov.justice.digital.hmpps.locationsinsideprison.dto.LocationPrefixDto
import uk.gov.justice.digital.hmpps.locationsinsideprison.dto.PatchLocationRequest
import uk.gov.justice.digital.hmpps.locationsinsideprison.dto.PatchNonResidentialLocationRequest
import uk.gov.justice.digital.hmpps.locationsinsideprison.dto.PatchResidentialLocationRequest
import uk.gov.justice.digital.hmpps.locationsinsideprison.dto.UpdateLocationLocalNameRequest
import uk.gov.justice.digital.hmpps.locationsinsideprison.jpa.AccommodationType
import uk.gov.justice.digital.hmpps.locationsinsideprison.jpa.Cell
import uk.gov.justice.digital.hmpps.locationsinsideprison.jpa.ConvertedCellType
import uk.gov.justice.digital.hmpps.locationsinsideprison.jpa.DeactivatedReason
import uk.gov.justice.digital.hmpps.locationsinsideprison.jpa.Location
import uk.gov.justice.digital.hmpps.locationsinsideprison.jpa.LocationAttribute
import uk.gov.justice.digital.hmpps.locationsinsideprison.jpa.LocationSummary
import uk.gov.justice.digital.hmpps.locationsinsideprison.jpa.LocationType
import uk.gov.justice.digital.hmpps.locationsinsideprison.jpa.NonResidentialUsageType
import uk.gov.justice.digital.hmpps.locationsinsideprison.jpa.ResidentialAttributeType
import uk.gov.justice.digital.hmpps.locationsinsideprison.jpa.ResidentialHousingType
import uk.gov.justice.digital.hmpps.locationsinsideprison.jpa.ResidentialLocation
import uk.gov.justice.digital.hmpps.locationsinsideprison.jpa.SpecialistCellType
import uk.gov.justice.digital.hmpps.locationsinsideprison.jpa.UsedForType
import uk.gov.justice.digital.hmpps.locationsinsideprison.jpa.repository.CellLocationRepository
import uk.gov.justice.digital.hmpps.locationsinsideprison.jpa.repository.LocationRepository
import uk.gov.justice.digital.hmpps.locationsinsideprison.jpa.repository.NonResidentialLocationRepository
import uk.gov.justice.digital.hmpps.locationsinsideprison.jpa.repository.PrisonSignedOperationCapacityRepository
import uk.gov.justice.digital.hmpps.locationsinsideprison.jpa.repository.ResidentialLocationRepository
import uk.gov.justice.digital.hmpps.locationsinsideprison.resource.AlreadyDeactivatedLocationException
import uk.gov.justice.digital.hmpps.locationsinsideprison.resource.CapacityException
import uk.gov.justice.digital.hmpps.locationsinsideprison.resource.CellWithSpecialistCellTypes
import uk.gov.justice.digital.hmpps.locationsinsideprison.resource.DeactivateLocationsRequest
import uk.gov.justice.digital.hmpps.locationsinsideprison.resource.ErrorCode
import uk.gov.justice.digital.hmpps.locationsinsideprison.resource.LocationAlreadyExistsException
import uk.gov.justice.digital.hmpps.locationsinsideprison.resource.LocationCannotBeReactivatedException
import uk.gov.justice.digital.hmpps.locationsinsideprison.resource.LocationContainsPrisonersException
import uk.gov.justice.digital.hmpps.locationsinsideprison.resource.LocationNotFoundException
import uk.gov.justice.digital.hmpps.locationsinsideprison.resource.LocationPrefixNotFoundException
import uk.gov.justice.digital.hmpps.locationsinsideprison.resource.LocationResidentialResource.AllowedAccommodationTypeForConversion
import uk.gov.justice.digital.hmpps.locationsinsideprison.resource.PermanentlyDeactivatedUpdateNotAllowedException
import uk.gov.justice.digital.hmpps.locationsinsideprison.resource.PrisonNotFoundException
import uk.gov.justice.digital.hmpps.locationsinsideprison.resource.ReactivateLocationsRequest
import uk.gov.justice.digital.hmpps.locationsinsideprison.resource.ReasonForDeactivationMustBeProvidedException
import uk.gov.justice.digital.hmpps.locationsinsideprison.resource.UpdateCapacityRequest
import uk.gov.justice.digital.hmpps.locationsinsideprison.utils.AuthenticationFacade
import java.time.Clock
import java.time.LocalDate
import java.time.LocalDateTime
import java.util.Properties
import java.util.UUID
import java.util.function.Predicate
import kotlin.jvm.optionals.getOrNull
import uk.gov.justice.digital.hmpps.locationsinsideprison.dto.Location as LocationDTO
@Service
@Transactional(readOnly = true)
class LocationService(
private val locationRepository: LocationRepository,
private val nonResidentialLocationRepository: NonResidentialLocationRepository,
private val residentialLocationRepository: ResidentialLocationRepository,
private val signedOperationCapacityRepository: PrisonSignedOperationCapacityRepository,
private val cellLocationRepository: CellLocationRepository,
private val entityManager: EntityManager,
private val prisonerLocationService: PrisonerLocationService,
private val prisonService: PrisonService,
private val clock: Clock,
private val telemetryClient: TelemetryClient,
private val authenticationFacade: AuthenticationFacade,
private val locationGroupFromPropertiesService: LocationGroupFromPropertiesService,
@Qualifier("residentialGroups") private val groupsProperties: Properties,
) {
companion object {
val log: Logger = LoggerFactory.getLogger(this::class.java)
}
fun getLocationById(id: UUID, includeChildren: Boolean = false, includeHistory: Boolean = false): LocationDTO? {
val toDto = locationRepository.findById(id).getOrNull()?.toDto(
includeChildren = includeChildren,
includeHistory = includeHistory,
)
return toDto
}
fun getLocationByPrison(prisonId: String): List<LocationDTO> =
locationRepository.findAllByPrisonIdOrderByPathHierarchy(prisonId)
.filter { !it.isPermanentlyDeactivated() }
.map {
it.toDto()
}
.sortedBy { it.getKey() }
fun getLocationGroupsForPrison(prisonId: String): List<LocationGroupDto> {
val groups = locationGroupFromPropertiesService.getLocationGroups(prisonId)
return groups.ifEmpty {
residentialLocationRepository.findAllByPrisonIdAndParentIsNull(prisonId)
.filter { it.isActiveAndAllParentsActive() && it.isStructural() }
.map {
it.toLocationGroupDto()
}
.sortedWith(NaturalOrderComparator())
}
}
fun getLocationPrefixFromGroup(prisonId: String, group: String): LocationPrefixDto {
val agencyGroupKey = "${prisonId}_$group"
val pattern = groupsProperties.getProperty(agencyGroupKey)
?: throw LocationPrefixNotFoundException(agencyGroupKey)
val locationPrefix = pattern
.replace(".", "")
.replace("+", "")
return LocationPrefixDto(locationPrefix)
}
fun getCellLocationsForGroup(prisonId: String, groupName: String): List<LocationDTO> =
cellsInGroup(prisonId, groupName, cellLocationRepository.findAllByPrisonIdAndActive(prisonId, true))
.toMutableList()
.map { it.toDto() }
.sortedWith(NaturalOrderComparator())
private fun cellsInGroup(
prisonId: String,
groupName: String?,
cellsToFilter: List<Cell>,
): List<Cell> {
return if (groupName != null) {
cellsToFilter.filter(locationGroupFilter(prisonId, groupName)::test)
} else {
cellsToFilter
}
}
private fun locationGroupFilter(prisonId: String, groupName: String): Predicate<Location> {
return try {
locationGroupFromPropertiesService.locationGroupFilter(prisonId, groupName)
} catch (e: EntityNotFoundException) {
fallBackLocationGroupFilter(groupName)
}
}
private fun fallBackLocationGroupFilter(groupName: String): Predicate<Location> {
val prefixToMatch = "${groupName.replace('_', '-')}-"
return Predicate { it.getPathHierarchy().startsWith(prefixToMatch) }
}
fun getLocationsByPrisonAndNonResidentialUsageType(
prisonId: String,
usageType: NonResidentialUsageType,
): List<LocationDTO> =
nonResidentialLocationRepository.findAllByPrisonIdAndNonResidentialUsages(prisonId, usageType)
.map {
it.toDto()
}
fun getLocationByKey(key: String, includeChildren: Boolean = false, includeHistory: Boolean = false): LocationDTO? {
return locationRepository.findOneByKey(key)?.toDto(
includeChildren = includeChildren,
includeHistory = includeHistory,
)
}
fun getLocationsByKeys(keys: List<String>): List<LocationDTO> =
locationRepository.findAllByKeys(keys)
.map { it.toDto() }
.sortedBy { it.getKey() }
fun getLocations(pageable: Pageable = PageRequest.of(0, 20, Sort.by("id"))): Page<LegacyLocation> {
return locationRepository.findAll(pageable).map(Location::toLegacyDto)
}
fun getLocationByPrisonAndLocationType(prisonId: String, locationType: LocationType): List<LocationDTO> =
locationRepository.findAllByPrisonIdAndLocationTypeOrderByPathHierarchy(prisonId, locationType)
.filter { it.isActive() }
.map {
it.toDto()
}
.sortedBy { it.getKey() }
@Transactional
fun createResidentialLocation(request: CreateResidentialLocationRequest): LocationDTO {
val parentLocation = getParentLocation(request.parentId)
checkParentValid(
parentLocation = parentLocation,
code = request.code,
prisonId = request.prisonId,
) // check that code doesn't clash with existing location
val locationToCreate = request.toNewEntity(authenticationFacade.getUserOrSystemInContext(), clock)
parentLocation?.let { locationToCreate.setParent(it) }
val capacityChanged = request.isCell() && request.capacity != null
val createdLocation = locationRepository.save(locationToCreate)
log.info("Created Residential Location [${createdLocation.getKey()}]")
trackLocationUpdate(createdLocation, "Created Residential Location")
return createdLocation.toDto(includeParent = capacityChanged)
}
@Transactional
fun createNonResidentialLocation(request: CreateNonResidentialLocationRequest): LocationDTO {
val parentLocation = getParentLocation(request.parentId)
checkParentValid(
parentLocation = parentLocation,
code = request.code,
prisonId = request.prisonId,
) // check that code doesn't clash with existing location
val locationToCreate = request.toNewEntity(authenticationFacade.getUserOrSystemInContext(), clock)
parentLocation?.let { locationToCreate.setParent(it) }
val usageChanged = request.usage != null
val createdLocation = locationRepository.save(locationToCreate)
log.info("Created Non-Residential Location [${createdLocation.getKey()}]")
trackLocationUpdate(createdLocation, "Created Non-Residential Location")
return createdLocation.toDto(includeParent = usageChanged)
}
@Transactional
fun createWing(createWingRequest: CreateWingRequest): LocationDTO {
locationRepository.findOneByPrisonIdAndPathHierarchy(createWingRequest.prisonId, createWingRequest.wingCode)
?.let { throw LocationAlreadyExistsException("${createWingRequest.prisonId}-${createWingRequest.wingCode}") }
val wing = createWingRequest.toEntity(authenticationFacade.getUserOrSystemInContext(), clock)
return locationRepository.save(wing).toDto(includeChildren = true, includeNonResidential = false)
}
@Transactional
fun updateResidentialLocation(id: UUID, patchLocationRequest: PatchResidentialLocationRequest): UpdateLocationResult {
val residentialLocation =
residentialLocationRepository.findById(id).orElseThrow { LocationNotFoundException(id.toString()) }
return patchLocation(residentialLocation, patchLocationRequest).also {
trackLocationUpdate(it.location)
}
}
@Transactional
fun updateResidentialLocation(
key: String,
patchLocationRequest: PatchResidentialLocationRequest,
): UpdateLocationResult {
val residentialLocation = residentialLocationRepository.findOneByKey(key) ?: throw LocationNotFoundException(key)
return patchLocation(residentialLocation, patchLocationRequest).also {
trackLocationUpdate(it.location)
}
}
@Transactional
fun updateNonResidentialLocation(
id: UUID,
patchLocationRequest: PatchNonResidentialLocationRequest,
): UpdateLocationResult {
val nonResLocation =
nonResidentialLocationRepository.findById(id).orElseThrow { LocationNotFoundException(id.toString()) }
return patchLocation(nonResLocation, patchLocationRequest).also {
trackLocationUpdate(it.location)
}
}
@Transactional
fun updateNonResidentialLocation(
key: String,
patchLocationRequest: PatchNonResidentialLocationRequest,
): UpdateLocationResult {
val nonResLocation = nonResidentialLocationRepository.findOneByKey(key) ?: throw LocationNotFoundException(key)
return patchLocation(nonResLocation, patchLocationRequest).also {
trackLocationUpdate(it.location)
}
}
private fun patchLocation(
location: Location,
patchLocationRequest: PatchLocationRequest,
): UpdateLocationResult {
val (codeChanged, oldParent, parentChanged) = updateCoreLocationDetails(location, patchLocationRequest)
location.update(patchLocationRequest, authenticationFacade.getUserOrSystemInContext(), clock)
return UpdateLocationResult(
location.toDto(
includeChildren = codeChanged || parentChanged,
includeParent = parentChanged,
includeNonResidential = false,
),
if (parentChanged && oldParent != null) oldParent.toDto(includeParent = true) else null,
)
}
@Transactional
fun updateResidentialLocationUsedForTypes(id: UUID, usedFor: Set<UsedForType>): LocationDTO {
val residentialLocation = residentialLocationRepository.findById(id)
.orElseThrow { LocationNotFoundException(id.toString()) }
residentialLocation.updateCellUsedFor(
usedFor,
authenticationFacade.getUserOrSystemInContext(),
clock,
)
log.info("Updated Used for types for below Location [$residentialLocation.getKey()]")
trackLocationUpdate(residentialLocation, "Updated Used For Type below Residential Location")
return residentialLocation.toDto(includeChildren = true, includeNonResidential = false)
}
private fun updateCoreLocationDetails(
locationToUpdate: Location,
patchLocationRequest: PatchLocationRequest,
): UpdatedSummary {
if (locationToUpdate.isPermanentlyDeactivated()) {
throw PermanentlyDeactivatedUpdateNotAllowedException(locationToUpdate.getKey())
}
val codeChanged = patchLocationRequest.code != null && patchLocationRequest.code != locationToUpdate.getCode()
val oldParent = locationToUpdate.getParent()
val parentChanged = (patchLocationRequest.parentId != null && patchLocationRequest.parentId != oldParent?.id) ||
(patchLocationRequest.parentLocationKey != null && patchLocationRequest.parentLocationKey != oldParent?.getKey())
if (codeChanged || parentChanged) {
val newCode = patchLocationRequest.code ?: locationToUpdate.getCode()
val theParent = patchLocationRequest.parentId?.let {
locationRepository.findById(it).getOrNull() ?: throw LocationNotFoundException(it.toString())
} ?: patchLocationRequest.parentLocationKey?.let {
locationRepository.findOneByKey(it) ?: throw LocationNotFoundException(it)
} ?: oldParent
checkParentValid(theParent, newCode, locationToUpdate.prisonId)
if (parentChanged && theParent?.id == locationToUpdate.id) throw ValidationException("Cannot set parent to self")
theParent?.let { locationToUpdate.setParent(it) }
if (parentChanged) {
locationToUpdate.addHistory(
LocationAttribute.PARENT_LOCATION,
oldParent?.id?.toString(),
theParent?.id?.toString(),
authenticationFacade.getUserOrSystemInContext(),
LocalDateTime.now(clock),
)
}
}
return UpdatedSummary(codeChanged = codeChanged, oldParent = oldParent, parentChanged = parentChanged)
}
@Transactional
fun updateCellCapacity(id: UUID, maxCapacity: Int, workingCapacity: Int): LocationDTO {
val locCapChange = cellLocationRepository.findById(id)
.orElseThrow { LocationNotFoundException(id.toString()) }
if (locCapChange.isPermanentlyDeactivated()) {
throw PermanentlyDeactivatedUpdateNotAllowedException(locCapChange.getKey())
}
val prisoners = prisonerLocationService.prisonersInLocations(locCapChange)
if (maxCapacity < prisoners.size) {
throw CapacityException(
locCapChange.getKey(),
"Max capacity ($maxCapacity) cannot be decreased below current cell occupancy (${prisoners.size})",
ErrorCode.MaxCapacityCannotBeBelowOccupancyLevel,
)
}
locCapChange.setCapacity(
maxCapacity = maxCapacity,
workingCapacity = workingCapacity,
userOrSystemInContext = authenticationFacade.getUserOrSystemInContext(),
clock = clock,
)
telemetryClient.trackEvent(
"Capacity updated",
mapOf(
"id" to id.toString(),
"key" to locCapChange.getKey(),
"maxCapacity" to maxCapacity.toString(),
"workingCapacity" to workingCapacity.toString(),
),
null,
)
return locCapChange.toDto(includeParent = true, includeNonResidential = false)
}
@Transactional
fun updateSpecialistCellTypes(id: UUID, specialistCellTypes: Set<SpecialistCellType>): LocationDTO {
val cell = cellLocationRepository.findById(id)
.orElseThrow { LocationNotFoundException(id.toString()) }
if (cell.isPermanentlyDeactivated()) {
throw PermanentlyDeactivatedUpdateNotAllowedException(cell.getKey())
}
// Check that the workingCapacity is not set to 0 for normal accommodations when removing the specialists cell types
if (specialistCellTypes.isEmpty() && cell.accommodationType == AccommodationType.NORMAL_ACCOMMODATION && cell.getWorkingCapacity() == 0) {
throw CapacityException(
cell.getKey(),
"Cannot removes specialist cell types for a normal accommodation with a working capacity of 0",
ErrorCode.ZeroCapacityForNonSpecialistNormalAccommodationNotAllowed,
)
}
cell.updateSpecialistCellTypes(
specialistCellTypes,
authenticationFacade.getUserOrSystemInContext(),
clock,
)
log.info("Updated specialist cell types = $specialistCellTypes")
telemetryClient.trackEvent(
"Specialist cell types updated",
mapOf(
"id" to id.toString(),
"key" to cell.getKey(),
"specialistCellTypes" to specialistCellTypes.toString(),
),
null,
)
return cell.toDto(includeParent = false, includeNonResidential = false)
}
@Transactional
fun updateLocalName(id: UUID, updateLocationLocalNameRequest: UpdateLocationLocalNameRequest): LocationDTO {
val location = locationRepository.findById(id)
.orElseThrow { LocationNotFoundException(id.toString()) }
if (location.isPermanentlyDeactivated()) {
throw PermanentlyDeactivatedUpdateNotAllowedException(location.getKey())
}
location.updateLocalName(
localName = updateLocationLocalNameRequest.localName,
userOrSystemInContext = updateLocationLocalNameRequest.updatedBy
?: authenticationFacade.getUserOrSystemInContext(),
clock = clock,
)
log.info("Location local name updated [${location.getKey()}")
trackLocationUpdate(location, "Location local name updated")
return location.toDto()
}
@Transactional
fun deactivateLocations(locationsToDeactivate: DeactivateLocationsRequest): Map<InternalLocationDomainEventType, List<LocationDTO>> {
val deactivatedLocations = mutableSetOf<Location>()
locationsToDeactivate.locations.forEach { (id, deactivationDetail) ->
val locationToDeactivate = locationRepository.findById(id)
.orElseThrow { LocationNotFoundException(id.toString()) }
if (locationToDeactivate.isTemporarilyDeactivated()) {
throw AlreadyDeactivatedLocationException(locationToDeactivate.getKey())
}
checkForPrisonersInLocation(locationToDeactivate)
with(deactivationDetail) {
if (deactivationReason == DeactivatedReason.OTHER && deactivationReasonDescription.isNullOrEmpty()) {
throw ReasonForDeactivationMustBeProvidedException(locationToDeactivate.getKey())
}
if (locationToDeactivate.temporarilyDeactivate(
deactivatedReason = deactivationReason,
deactivatedDate = LocalDateTime.now(clock),
deactivationReasonDescription = deactivationReasonDescription,
planetFmReference = planetFmReference,
proposedReactivationDate = proposedReactivationDate,
userOrSystemInContext = authenticationFacade.getUserOrSystemInContext(),
clock = clock,
deactivatedLocations = deactivatedLocations,
)
) {
deactivatedLocations.forEach {
trackLocationUpdate(it, "Temporarily Deactivated Location")
}
}
}
}
val deactivatedLocationsDto = deactivatedLocations.map { it.toDto() }.toSet()
return mapOf(
InternalLocationDomainEventType.LOCATION_AMENDED to deactivatedLocations.flatMap { deactivatedLoc ->
deactivatedLoc.getParentLocations().map { it.toDto() }
}.toSet().minus(
deactivatedLocationsDto,
).toList(),
InternalLocationDomainEventType.LOCATION_DEACTIVATED to deactivatedLocationsDto.toList(),
)
}
@Transactional
fun updateDeactivatedDetails(
id: UUID,
deactivatedReason: DeactivatedReason,
deactivationReasonDescription: String? = null,
proposedReactivationDate: LocalDate? = null,
planetFmReference: String? = null,
): LocationDTO {
val locationToUpdate = locationRepository.findById(id)
.orElseThrow { LocationNotFoundException(id.toString()) }
if (deactivatedReason == DeactivatedReason.OTHER && deactivationReasonDescription.isNullOrEmpty()) {
throw ReasonForDeactivationMustBeProvidedException(locationToUpdate.getKey())
}
if (locationToUpdate.isTemporarilyDeactivated()) {
locationToUpdate.updateDeactivatedDetails(
deactivatedReason = deactivatedReason,
deactivationReasonDescription = deactivationReasonDescription,
planetFmReference = planetFmReference,
proposedReactivationDate = proposedReactivationDate,
userOrSystemInContext = authenticationFacade.getUserOrSystemInContext(),
clock = clock,
)
telemetryClient.trackEvent(
"Temporarily Deactivated Location Details Updated",
mapOf(
"id" to id.toString(),
"prisonId" to locationToUpdate.prisonId,
"path" to locationToUpdate.getPathHierarchy(),
),
null,
)
}
return locationToUpdate.toDto()
}
@Transactional
fun permanentlyDeactivateLocation(
id: UUID,
reasonForPermanentDeactivation: String,
): LocationDTO {
val locationToArchive = locationRepository.findById(id)
.orElseThrow { LocationNotFoundException(id.toString()) }
if (locationToArchive.isPermanentlyDeactivated()) {
throw PermanentlyDeactivatedUpdateNotAllowedException(locationToArchive.getKey())
}
checkForPrisonersInLocation(locationToArchive)
locationToArchive.permanentlyDeactivate(
deactivatedDate = LocalDateTime.now(clock),
reason = reasonForPermanentDeactivation,
userOrSystemInContext = authenticationFacade.getUserOrSystemInContext(),
clock = clock,
)
trackLocationUpdate(locationToArchive, "Permanently Deactivated Location")
return locationToArchive.toDto(includeChildren = true, includeParent = true)
}
@Transactional
fun updateCapacityOfCellLocations(capacitiesToUpdate: UpdateCapacityRequest): CapacityUpdateResult {
val updatedCapacities = mutableSetOf<ResidentialLocation>()
val audit = mutableMapOf<String, List<CapacityChanges>>()
capacitiesToUpdate.locations.forEach { (key, capacityChange) ->
val changes = mutableListOf<CapacityChanges>()
val location = residentialLocationRepository.findOneByKey(key)
if (location != null) {
if (!location.isPermanentlyDeactivated()) {
if (location is Cell) {
with(capacityChange) {
if (location.getMaxCapacity() != maxCapacity || location.getWorkingCapacity() != workingCapacity) {
try {
val oldWorkingCapacity = location.getWorkingCapacity()
val oldMaxCapacity = location.getMaxCapacity()
updateCellCapacity(
location.id!!,
maxCapacity = maxCapacity,
workingCapacity = workingCapacity,
)
if (oldMaxCapacity != maxCapacity) {
changes.add(CapacityChanges(key, message = "Max capacity from $oldMaxCapacity ==> $maxCapacity", type = "maxCapacity", previousValue = oldMaxCapacity, newValue = maxCapacity))
}
if (oldWorkingCapacity != workingCapacity) {
changes.add(CapacityChanges(key, message = "Working capacity from $oldWorkingCapacity ==> $workingCapacity", type = "workingCapacity", previousValue = oldWorkingCapacity, newValue = workingCapacity))
}
updatedCapacities.add(location)
} catch (e: Exception) {
changes.add(CapacityChanges(key, message = "Update failed: ${e.message}"))
}
} else {
changes.add(CapacityChanges(key, message = "Capacity not changed"))
}
if (capacityOfCertifiedCell != null && capacityOfCertifiedCell != location.getCapacityOfCertifiedCell()) {
val oldCapacityOfCertifiedCell = location.getCapacityOfCertifiedCell()
location.setCapacityOfCertifiedCell(
capacityOfCertifiedCell,
authenticationFacade.getUserOrSystemInContext(),
clock,
)
changes.add(CapacityChanges(key, message = "Baseline CNA from $oldCapacityOfCertifiedCell ==> $capacityOfCertifiedCell", type = "CNA", previousValue = oldCapacityOfCertifiedCell, newValue = capacityOfCertifiedCell))
updatedCapacities.add(location)
}
}
} else {
changes.add(CapacityChanges(key, message = "Not a cell"))
}
} else {
changes.add(CapacityChanges(key, message = "Archived location"))
}
} else {
changes.add(CapacityChanges(key, message = "Location not found"))
}
audit[key] = changes
log.info("$key: ${changes.joinToString { "${it.type}: ${it.previousValue} ==> ${it.newValue}" }}")
}
val updatedLocationsDto = updatedCapacities.map { it.toDto() }.toSet()
audit.flatMap { it.value }.forEach { l ->
var trackMap = mapOf("key" to l.key, "message" to l.message)
l.type?.let { trackMap = trackMap.plus("${l.type}" to "${l.previousValue} ==> ${l.newValue}") }
telemetryClient.trackEvent("CAPACITY_CHANGE", trackMap, null)
}
return CapacityUpdateResult(
updatedLocations = mapOf(
InternalLocationDomainEventType.LOCATION_AMENDED to updatedCapacities.flatMap { changed ->
changed.getParentLocations().map { it.toDto() }
}.toSet().plus(updatedLocationsDto).toList(),
),
audit = audit,
)
}
@Transactional
fun reactivateLocations(locationsToReactivate: ReactivateLocationsRequest): Map<InternalLocationDomainEventType, List<LocationDTO>> {
val locationsReactivated = mutableSetOf<Location>()
locationsToReactivate.locations.forEach { (id, reactivationDetail) ->
val locationToUpdate = locationRepository.findById(id)
.orElseThrow { LocationNotFoundException(id.toString()) }
if (locationToUpdate.isPermanentlyDeactivated()) {
throw LocationCannotBeReactivatedException("Location [${locationToUpdate.getKey()}] permanently deactivated")
}
locationToUpdate.reactivate(
userOrSystemInContext = authenticationFacade.getUserOrSystemInContext(),
clock = clock,
reactivatedLocations = locationsReactivated,
maxCapacity = reactivationDetail.capacity?.maxCapacity,
workingCapacity = reactivationDetail.capacity?.workingCapacity,
)
if (reactivationDetail.cascadeReactivation) {
locationToUpdate.findSubLocations().forEach { location ->
location.reactivate(
userOrSystemInContext = authenticationFacade.getUserOrSystemInContext(),
clock = clock,
reactivatedLocations = locationsReactivated,
)
}
}
}
val reactivatedLocationsDto = locationsReactivated.map { it.toDto() }.toSet()
locationsReactivated.forEach { trackLocationUpdate(it, "Re-activated Location") }
return mapOf(
InternalLocationDomainEventType.LOCATION_AMENDED to locationsReactivated.flatMap { reactivated ->
reactivated.getParentLocations().map { it.toDto() }
}.toSet().minus(
reactivatedLocationsDto,
).toList(),
InternalLocationDomainEventType.LOCATION_REACTIVATED to reactivatedLocationsDto.toList(),
)
}
private fun trackLocationUpdate(location: Location, trackDescription: String) {
telemetryClient.trackEvent(
trackDescription,
mapOf(
"id" to location.id!!.toString(),
"prisonId" to location.prisonId,
"path" to location.getPathHierarchy(),
),
null,
)
}
private fun trackLocationUpdate(location: LocationDTO) {
telemetryClient.trackEvent(
"Updated Location",
mapOf(
"id" to location.id.toString(),
"prisonId" to location.prisonId,
"path" to location.pathHierarchy,
),
null,
)
}
@Transactional
fun updateNonResidentialCellType(
id: UUID,
convertedCellType: ConvertedCellType,
otherConvertedCellType: String? = null,
): LocationDTO {
var nonResCellToUpdate = cellLocationRepository.findById(id)
.orElseThrow { LocationNotFoundException(id.toString()) }
if (!nonResCellToUpdate.isConvertedCell()) {
throw LocationNotFoundException("${nonResCellToUpdate.getKey()} is not a non-residential cell")
}
nonResCellToUpdate.updateNonResidentialCellType(
convertedCellType = convertedCellType,
otherConvertedCellType = otherConvertedCellType,
userOrSystemInContext = authenticationFacade.getUserOrSystemInContext(),
clock = clock,
)
trackLocationUpdate(nonResCellToUpdate, "Updated non-residential cell type")
return nonResCellToUpdate.toDto()
}
@Transactional
fun convertToNonResidentialCell(
id: UUID,
convertedCellType: ConvertedCellType,
otherConvertedCellType: String? = null,
): LocationDTO {
var locationToConvert = residentialLocationRepository.findById(id)
.orElseThrow { LocationNotFoundException(id.toString()) }
if (locationToConvert.isNonResType()) {
locationRepository.updateLocationType(locationToConvert.id!!, LocationType.CELL.name)
locationRepository.updateResidentialHousingType(
locationToConvert.id!!,
ResidentialHousingType.OTHER_USE.name,
AccommodationType.OTHER_NON_RESIDENTIAL.name,
)
entityManager.flush()
entityManager.clear()
locationToConvert = residentialLocationRepository.findById(id)
.orElseThrow { LocationNotFoundException(id.toString()) }
}
checkForPrisonersInLocation(locationToConvert)
if (locationToConvert is Cell) {
locationToConvert.convertToNonResidentialCell(
convertedCellType = convertedCellType,
otherConvertedCellType = otherConvertedCellType,
userOrSystemInContext = authenticationFacade.getUserOrSystemInContext(),
clock = clock,
)
} else {
throw LocationNotFoundException(id.toString())
}
trackLocationUpdate(locationToConvert, "Converted Location to non-residential cell")
return locationToConvert.toDto(includeParent = true)
}
@Transactional
fun convertToCell(
id: UUID,
accommodationType: AllowedAccommodationTypeForConversion,
specialistCellTypes: Set<SpecialistCellType>? = null,
maxCapacity: Int = 0,
workingCapacity: Int = 0,
usedForTypes: List<UsedForType>? = null,
): LocationDTO {
val locationToConvert = residentialLocationRepository.findById(id)
.orElseThrow { LocationNotFoundException(id.toString()) }
if (locationToConvert is Cell && locationToConvert.isConvertedCell()) {
locationToConvert.convertToCell(
accommodationType = accommodationType,
usedForTypes = usedForTypes,
specialistCellTypes = specialistCellTypes,
maxCapacity = maxCapacity,
workingCapacity = workingCapacity,
userOrSystemInContext = authenticationFacade.getUserOrSystemInContext(),
clock = clock,
)
} else {
throw LocationNotFoundException(id.toString())
}
trackLocationUpdate(locationToConvert, "Converted non-residential cell to residential cell")
return locationToConvert.toDto(includeParent = true)
}
private fun buildNewPathHierarchy(parentLocation: Location?, code: String) =
if (parentLocation != null) {
parentLocation.getPathHierarchy() + "-"
} else {
""
} + code
private fun checkParentValid(
parentLocation: Location?,
code: String,
prisonId: String,
) {
val pathHierarchy = buildNewPathHierarchy(parentLocation, code)
locationRepository.findOneByPrisonIdAndPathHierarchy(prisonId, pathHierarchy)
?.let { throw LocationAlreadyExistsException("$prisonId-$pathHierarchy") }
}
private fun getParentLocation(parentId: UUID?): Location? =
parentId?.let {
locationRepository.findById(parentId).getOrNull()
?: throw LocationNotFoundException(it.toString())
}
fun getResidentialLocations(
prisonId: String,
parentLocationId: UUID? = null,
parentPathHierarchy: String? = null,
returnLatestHistory: Boolean = false,
): ResidentialSummary {
val currentLocation =
if (parentLocationId != null) {
residentialLocationRepository.findById(parentLocationId).getOrNull()
?: throw LocationNotFoundException(parentLocationId.toString())
} else if (parentPathHierarchy != null) {
residentialLocationRepository.findOneByPrisonIdAndPathHierarchy(prisonId, parentPathHierarchy)
?: throw LocationNotFoundException("$prisonId-$parentPathHierarchy")
} else {
null
}
val id = currentLocation?.id
val locations = (
if (id != null) {
residentialLocationRepository.findAllByPrisonIdAndParentId(prisonId, id)
} else {
residentialLocationRepository.findAllByPrisonIdAndParentIsNull(prisonId)
}
)
.filter { !it.isPermanentlyDeactivated() }
.filter { it.isCell() || it.isLocationShownOnResidentialSummary() }
.map { it.toDto(countInactiveCells = true, countCells = true) }
.sortedWith(NaturalOrderComparator())
val subLocationTypes = calculateSubLocationDescription(locations)
return ResidentialSummary(
topLevelLocationType = if (currentLocation == null) {
subLocationTypes ?: "Wings"
} else {
currentLocation.getHierarchy()[0].type.description + "s"
},
prisonSummary = if (id == null) {
val prisonDetails = prisonService.lookupPrisonDetails(prisonId) ?: throw PrisonNotFoundException(prisonId)
PrisonSummary(
prisonName = prisonDetails.prisonName,
workingCapacity = locations.sumOf { it.capacity?.workingCapacity ?: 0 },
maxCapacity = locations.sumOf { it.capacity?.maxCapacity ?: 0 },
numberOfCellLocations = locations.sumOf { it.numberOfCellLocations ?: 0 },
signedOperationalCapacity = signedOperationCapacityRepository.findOneByPrisonId(prisonId)?.signedOperationCapacity
?: 0,
)
} else {
null
},
locationHierarchy = currentLocation?.getHierarchy(),
parentLocation = currentLocation?.toDto(countInactiveCells = true, useHistoryForUpdate = true, countCells = true),
subLocations = locations,
subLocationName = subLocationTypes,
)
}
private fun calculateSubLocationDescription(locations: List<LocationDTO>): String? {
if (locations.isEmpty()) return null
val mostCommonType = mostCommon(locations.map { it.locationType })
return (mostCommonType?.description) + "s"
}
fun <T> mostCommon(list: List<T>): T? {
return list.groupingBy { it }.eachCount().maxByOrNull { it.value }?.key
}
fun getArchivedLocations(prisonId: String): List<LocationDTO> =
residentialLocationRepository.findAllByPrisonIdAndArchivedIsTrue(prisonId).map { it.toDto() }
.sortedWith(NaturalOrderComparator())
fun getResidentialInactiveLocations(prisonId: String, parentLocationId: UUID?): List<LocationDTO> {
val startLocation = parentLocationId?.let {
residentialLocationRepository.findById(parentLocationId).getOrNull() ?: throw LocationNotFoundException(
parentLocationId.toString(),
)
}
return (
startLocation?.findAllLeafLocations() ?: cellLocationRepository.findAllByPrisonIdAndActive(prisonId, false)
)
.filter { it.isTemporarilyDeactivated() }
.map { it.toDto() }
.sortedWith(NaturalOrderComparator())
}
private fun checkForPrisonersInLocation(location: Location) {
val locationsWithPrisoners = prisonerLocationService.prisonersInLocations(location).groupBy { it.cellLocation!! }
if (locationsWithPrisoners.isNotEmpty()) {
throw LocationContainsPrisonersException(locationsWithPrisoners)
}
}
fun getCellsWithCapacity(
prisonId: String,
locationId: UUID? = null,
groupName: String? = null,
specialistCellType: SpecialistCellType? = null,
includePrisonerInformation: Boolean = false,
): List<CellWithSpecialistCellTypes> {
val cellsToFilter = if (locationId != null) {
residentialLocationRepository.findOneByPrisonIdAndId(prisonId, locationId)?.cellLocations()
?: throw LocationNotFoundException(locationId.toString())
} else {
cellLocationRepository.findAllByPrisonIdAndActive(prisonId, true)
}
val cellsWithCapacity = cellsInGroup(
prisonId = prisonId,
groupName = groupName,
cellsToFilter = cellsToFilter,
)
.filter { cell -> cell.isActiveAndAllParentsActive() && cell.isCertified() && !cell.isPermanentlyDeactivated() }
.filter { cell ->
specialistCellType == null || specialistCellType in cell.specialistCellTypes.map { it.specialistCellType }
}
val mapOfOccupancy = prisonerLocationService.prisonersInLocations(prisonId, cellsWithCapacity)
.groupBy { it.cellLocation }
return cellsWithCapacity.map { cell ->
CellWithSpecialistCellTypes(
id = cell.id!!,
prisonId = cell.prisonId,
pathHierarchy = cell.getPathHierarchy(),
maxCapacity = cell.getMaxCapacity() ?: 0,
workingCapacity = cell.getWorkingCapacity() ?: 0,
localName = cell.localName,
specialistCellTypes = cell.specialistCellTypes.map {
CellWithSpecialistCellTypes.CellType(
it.specialistCellType,
it.specialistCellType.description,
)
},
legacyAttributes = cell.attributes.filter { it.attributeType == ResidentialAttributeType.LOCATION_ATTRIBUTE }
.map {
CellWithSpecialistCellTypes.ResidentialLocationAttribute(
it.attributeValue,
it.attributeValue.description,
)
},
noOfOccupants = mapOfOccupancy[cell.getPathHierarchy()]?.size ?: 0,
prisonersInCell = if (includePrisonerInformation) {
mapOfOccupancy[cell.getPathHierarchy()]
} else {
null
},
)
}.filter {
it.hasSpace()
}.sortedBy { it.pathHierarchy }
}
fun getUsedForTypesForPrison(prisonId: String): List<UsedForType> {
val prisonDetails = prisonService.lookupPrisonDetails(prisonId) ?: throw PrisonNotFoundException(prisonId)
return UsedForType.entries.filter { it.isStandard() || (prisonDetails.female && it.femaleOnly) || (prisonDetails.lthse && it.secureEstateOnly) }
}
}
fun buildEventsToPublishOnUpdate(results: UpdateLocationResult): () -> Map<InternalLocationDomainEventType, List<LocationDTO>> {
val locationsChanged = if (results.otherParentLocationChanged != null) {
listOf(results.location, results.otherParentLocationChanged)
} else {
listOf(results.location)
}
return {
mapOf(
InternalLocationDomainEventType.LOCATION_AMENDED to locationsChanged,
)
}
}
@Schema(description = "Residential Summary")
@JsonInclude(JsonInclude.Include.NON_NULL)
data class ResidentialSummary(
@Schema(description = "Prison summary for top level view", required = false)
val prisonSummary: PrisonSummary? = null,
@Schema(description = "The top level type of locations", required = true, example = "Wings")
val topLevelLocationType: String,
@Schema(
description = "The description of the type of sub locations most common",
required = false,
examples = ["Wings", "Landings", "Spurs", "Cells"],
)
val subLocationName: String? = null,
@Schema(description = "Parent locations, top to bottom", required = true)
val locationHierarchy: List<LocationSummary>? = null,
@Schema(description = "The current parent location (e.g Wing or Landing) details")
val parentLocation: LocationDTO? = null,
@Schema(description = "All residential locations under this parent")
val subLocations: List<LocationDTO>,
)
@Schema(description = "Prison Summary Information")
@JsonInclude(JsonInclude.Include.NON_NULL)
data class PrisonSummary(
@Schema(description = "Prison name")
val prisonName: String,
@Schema(description = "Prison working capacity")
val workingCapacity: Int,
@Schema(description = "Prison signed operational capacity")
val signedOperationalCapacity: Int,
@Schema(description = "Prison max capacity")
val maxCapacity: Int,
@Schema(description = "Total number of non-structural locations e.g. cells and rooms")
val numberOfCellLocations: Int,
)
data class UpdatedSummary(
val codeChanged: Boolean = false,
val oldParent: Location? = null,
val parentChanged: Boolean = false,
)
data class UpdateLocationResult(
val location: LocationDTO,
val otherParentLocationChanged: LocationDTO? = null,
)
data class CapacityUpdateResult(
val updatedLocations: Map<InternalLocationDomainEventType, List<LocationDTO>>,
val audit: Map<String, List<CapacityChanges>>,
)
@Schema(description = "Capacity change audit")
@JsonInclude(JsonInclude.Include.NON_NULL)
data class CapacityChanges(
@Schema(description = "Location reference", example = "MDI-1-1-001")
val key: String,
@Schema(description = "textual description of the changes", example = "Working capacity from 2 ==> 1")
val message: String,
@Schema(description = "Attribute changed in the update", example = "workingCapacity")
val type: String? = null,
@Schema(description = "Old value of this attribute", example = "2")
val previousValue: Int? = null,
@Schema(description = "New value of this attribute", example = "1")
val newValue: Int? = null,
)
| 0
| null |
0
| 2
|
9946a37ef6ee0301ce3bd626015f5a927e991007
| 44,428
|
hmpps-locations-inside-prison-api
|
MIT License
|
plot-api/src/commonMain/kotlin/org/jetbrains/letsPlot/scale/ColorViridis.kt
|
JetBrains
| 172,682,391
| false
| null |
/*
* Copyright (c) 2021. JetBrains s.r.o.
* Use of this source code is governed by the MIT license that can be found in the LICENSE file.
*/
@file:Suppress("unused")
package org.jetbrains.letsPlot.scale
import org.jetbrains.letsPlot.core.spec.Option
import org.jetbrains.letsPlot.core.plot.base.Aes
import org.jetbrains.letsPlot.intern.Options
import org.jetbrains.letsPlot.intern.Scale
/**
*
* The `viridis` color maps are designed to be perceptually-uniform,
* both in regular form and also when converted to black-and-white.
*
* The `viridis` color scales are suitable for viewers with common forms of colour blindness.
* See also [https://bids.github.io/colormap](https://bids.github.io/colormap).
*
* @param aesthetic Aesthetic or a list of aesthetics that this scale works with.
* @param option Name of colormap.
* Supported colormaps:
* - "magma" (or "A"),
* - "inferno" (or "B"),
* - "plasma" (or "C"),
* - "viridis" (or "D"),
* - "cividis" (or "E"),
* - "turbo",
* - "twilight".
* @param alpha Alpha transparency channel. 0 means transparent and 1 means opaque.
* @param begin default = 0.0.
* Corresponds to a color hue to start at. Accepts values between 0 and 1. Should be less than `end`.
* @param end default = 1.0.
* Corresponds to a color hue to end with. Accepts values between 0 and 1. Should be greater than `begin`.
* @param direction default = 1.
* Sets the order of colors in the scale.
* If -1, the order of colors is reversed.
* @param name The name of the scale - used as the axis label or the legend title. If null, the default, the name of the scale
* is taken from the first mapping used for that aesthetic.
* @param breaks List of data values.
* A vector specifying values to display as ticks on axis.
* @param labels A vector of labels (on ticks).
* @param lablim The maximum label length (in characters) before trimming is applied.
* @param limits Data range for this scale.
* Continuous scale: a pair of numbers providing limits of the scale. Use `null` to refer to default min/max.
* Discrete scale: list of data values to display, and their order.
* @param naValue An aesthetic value which is used when data in not available.
* @param format Specifies the format pattern for labels on the scale.
* @param guide Guide to use for this scale.
* It can either be a string ("colorbar", "legend") or a call to a guide function (`guideColorbar()`, `guideLegend()`)
* specifying additional arguments.
* "none" will hide the guide.
* @param trans Name of built-in transformation ("identity", "log10", "log2", "symlog", "reverse", "sqrt").
*
* Format patterns in the `format` parameter can be just a number format (like "d") or
* a string template where number format is surrounded by curly braces: "{d} cylinders".
* Note: the "$" must be escaped as "\$".
* For more info see: [formats.md](https://github.com/JetBrains/lets-plot-kotlin/blob/master/docs/formats.md)
*
* Examples:
* - ".2f" -> "12.45";
* - "Score: {.2f}" -> "Score: 12.45";
* - "Score: {}" -> "Score: 12.454789".
*
*/
fun scaleViridis(
aesthetic: Any,
option: String? = null,
alpha: Number? = null,
begin: Number? = null,
end: Number? = null,
direction: Number? = null,
name: String? = null,
breaks: List<Any>? = null,
labels: List<String>? = null,
lablim: Int? = null,
limits: Any? = null,
naValue: Any? = null,
format: String? = null,
guide: Any? = null,
trans: String? = null
) = Scale(
aesthetic = aesthetic,
name = name,
breaks = breaks,
labels = labels,
lablim = lablim,
limits = limits,
naValue = naValue,
format = format,
guide = guide,
trans = trans,
otherOptions = Options(
mapOf(
Option.Scale.Viridis.CMAP_NAME to option,
Option.Scale.Viridis.ALPHA to alpha,
Option.Scale.Viridis.BEGIN to begin,
Option.Scale.Viridis.END to end,
Option.Scale.Viridis.DIRECTION to direction,
Option.Scale.SCALE_MAPPER_KIND to Option.Scale.MapperKind.COLOR_CMAP
)
)
)
/**
*
* The `viridis` color maps are designed to be perceptually-uniform,
* both in regular form and also when converted to black-and-white.
*
* The `viridis` color scales are suitable for viewers with common forms of colour blindness.
* See also [https://bids.github.io/colormap](https://bids.github.io/colormap).
*
* ## Examples
*
* - [color_space_update.ipynb](https://nbviewer.jupyter.org/github/JetBrains/lets-plot-kotlin/blob/master/docs/examples/jupyter-notebooks/f-4.4.4/color_space_update.ipynb)
*
* @param option Name of colormap.
* Supported colormaps:
* - "magma" (or "A"),
* - "inferno" (or "B"),
* - "plasma" (or "C"),
* - "viridis" (or "D"),
* - "cividis" (or "E"),
* - "turbo",
* - "twilight".
* @param alpha Alpha transparency channel. 0 means transparent and 1 means opaque.
* @param begin default = 0.0.
* Corresponds to a color hue to start at. Accepts values between 0 and 1. Should be less than `end`.
* @param end default = 1.0.
* Corresponds to a color hue to end with. Accepts values between 0 and 1. Should be greater than `begin`.
* @param direction default = 1.
* Sets the order of colors in the scale.
* If -1, the order of colors is reversed.
* @param name The name of the scale - used as the axis label or the legend title. If null, the default, the name of the scale
* is taken from the first mapping used for that aesthetic.
* @param breaks List of data values.
* A vector specifying values to display as ticks on axis.
* @param labels A vector of labels (on ticks).
* @param lablim The maximum label length (in characters) before trimming is applied.
* @param limits Data range for this scale.
* Continuous scale: a pair of numbers providing limits of the scale. Use `null` to refer to default min/max.
* Discrete scale: list of data values to display, and their order.
* @param naValue An aesthetic value which is used when data in not available.
* @param format Specifies the format pattern for labels on the scale.
* @param guide Guide to use for this scale.
* It can either be a string ("colorbar", "legend") or a call to a guide function (`guideColorbar()`, `guideLegend()`)
* specifying additional arguments.
* "none" will hide the guide.
* @param trans Name of built-in transformation ("identity", "log10", "log2", "symlog", "reverse", "sqrt").
*
* Format patterns in the `format` parameter can be just a number format (like "d") or
* a string template where number format is surrounded by curly braces: "{d} cylinders".
* Note: the "$" must be escaped as "\$".
* For more info see: [formats.md](https://github.com/JetBrains/lets-plot-kotlin/blob/master/docs/formats.md)
*
* Examples:
* - ".2f" -> "12.45";
* - "Score: {.2f}" -> "Score: 12.45";
* - "Score: {}" -> "Score: 12.454789".
*
*/
fun scaleFillViridis(
option: String? = null,
alpha: Number? = null,
begin: Number? = null,
end: Number? = null,
direction: Number? = null,
name: String? = null,
breaks: List<Any>? = null,
labels: List<String>? = null,
lablim: Int? = null,
limits: Any? = null,
naValue: Any? = null,
format: String? = null,
guide: Any? = null,
trans: String? = null
) = scaleViridis(
aesthetic = Aes.FILL,
option = option,
alpha = alpha,
begin = begin, end = end,
direction = direction,
name = name,
breaks = breaks,
labels = labels,
lablim = lablim,
limits = limits,
naValue = naValue,
format = format,
guide = guide,
trans = trans
)
/**
*
* The `viridis` color maps are designed to be perceptually-uniform,
* both in regular form and also when converted to black-and-white.
*
* The `viridis` color scales are suitable for viewers with common forms of colour blindness.
* See also [https://bids.github.io/colormap](https://bids.github.io/colormap).
*
* ## Examples
*
* - [color_space_update.ipynb](https://nbviewer.jupyter.org/github/JetBrains/lets-plot-kotlin/blob/master/docs/examples/jupyter-notebooks/f-4.4.4/color_space_update.ipynb)
*
* @param option Name of colormap.
* Supported colormaps:
* - "magma" (or "A"),
* - "inferno" (or "B")
* - "plasma" (or "C")
* - "viridis" (or "D")
* - "cividis" (or "E")
* - "turbo"
* - "twilight"
* @param alpha Alpha transparency channel (0 means transparent and 1 means opaque).
* @param begin default = 0.0.
* Corresponds to a color hue to start at. Accepts values between 0 and 1. Should be less than `end`.
* @param end default = 1.0.
* Corresponds to a color hue to end with. Accepts values between 0 and 1. Should be greater than `begin`.
* @param direction default = 1.
* Sets the order of colors in the scale.
* If -1, the order of colors is reversed.
* @param name The name of the scale - used as the axis label or the legend title. If null, the default, the name of the scale
* is taken from the first mapping used for that aesthetic.
* @param breaks A vector specifying values to display as ticks on axis.
* @param labels A vector of labels (on ticks)
* @param lablim The maximum label length (in characters) before trimming is applied.
* @param limits Data range for this scale.
* Continuous scale: a pair of numbers providing limits of the scale. Use `null` to refer to default min/max.
* Discrete scale: list of data values to display, and their order.
* @param naValue An aesthetic value which is used when data in not available.
* @param format Specifies the format pattern for labels on the scale.
* @param guide Guide to use for this scale.
* It can either be a string ("colorbar", "legend") or a call to a guide function (`guideColorbar()`, `guideLegend()`)
* specifying additional arguments.
* "none" will hide the guide.
* @param trans Name of built-in transformation ("identity", "log10", "log2", "symlog", "reverse", "sqrt").
*
* Format patterns in the `format` parameter can be just a number format (like "d") or
* a string template where number format is surrounded by curly braces: "{d} cylinders".
* Note: the "$" must be escaped as "\$".
* For more info see: [formats.md](https://github.com/JetBrains/lets-plot-kotlin/blob/master/docs/formats.md)
*
* Examples:
* - ".2f" -> "12.45"
* - "Score: {.2f}" -> "Score: 12.45"
* - "Score: {}" -> "Score: 12.454789"
*
*/
fun scaleColorViridis(
option: String? = null,
alpha: Number? = null,
begin: Number? = null,
end: Number? = null,
direction: Number? = null,
name: String? = null,
breaks: List<Any>? = null,
labels: List<String>? = null,
lablim: Int? = null,
limits: Any? = null,
naValue: Any? = null,
format: String? = null,
guide: Any? = null,
trans: String? = null
) = scaleViridis(
aesthetic = Aes.COLOR,
option = option,
alpha = alpha,
begin = begin, end = end,
direction = direction,
name = name,
breaks = breaks,
labels = labels,
lablim = lablim,
limits = limits,
naValue = naValue,
format = format,
guide = guide,
trans = trans
)
| 17
| null |
37
| 433
|
f6edab1a67783d14e2378675f065ef7111bdc1a0
| 11,166
|
lets-plot-kotlin
|
MIT License
|
ui/reader/src/main/java/com/kafka/reader/online/OnlineReader.kt
|
vipulyaara
| 612,950,214
| false
| null |
@file:Suppress("DEPRECATION")
package com.kafka.reader.online
import android.annotation.SuppressLint
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.window.DialogProperties
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.google.accompanist.web.WebContent
import com.google.accompanist.web.WebViewState
import com.kafka.data.feature.item.DownloadInfo
import com.kafka.data.feature.item.DownloadStatus
import com.kafka.data.feature.item.ItemWithDownload
import org.kafka.common.image.Icons
import org.kafka.common.widgets.IconButton
import org.kafka.reader.R.string
import org.kafka.ui.components.ProvideScaffoldPadding
import org.kafka.ui.components.R
import org.kafka.ui.components.file.DownloadStatusIcons
import org.kafka.ui.components.material.AlertDialog
import org.kafka.ui.components.material.AlertDialogAction
import org.kafka.ui.components.material.CloseButton
import org.kafka.ui.components.material.TopBar
import org.kafka.ui.components.topScaffoldPadding
import com.google.accompanist.web.WebView as AccompanistWebView
@SuppressLint("SetJavaScriptEnabled")
@Composable
fun OnlineReader(
viewModel: OnlineReaderViewModel = hiltViewModel(),
openOfflineReader: (String) -> Unit,
) {
val context = LocalContext.current
val state by viewModel.state.collectAsStateWithLifecycle()
val fileId = state.readerState?.fileId.orEmpty()
val readerState by viewModel.readerState.collectAsStateWithLifecycle()
val webViewState by remember(readerState?.url) {
mutableStateOf(readerState?.url?.let { WebViewState(WebContent.Url(url = it)) })
}
LaunchedEffect(fileId, state.autoDownload) {
if (state.autoDownload) {
viewModel.downloadItem(fileId)
}
}
LaunchedEffect(state.download) {
if (state.download?.downloadInfo?.status == DownloadStatus.COMPLETED) {
viewModel.showDownloadComplete.value = true
}
}
val downloadComplete by viewModel.showDownloadComplete
if (downloadComplete) {
DownloadCompleteDialog(
openOfflineReader = {
viewModel.showDownloadComplete.value = false
openOfflineReader(fileId)
},
onDismiss = { viewModel.showDownloadComplete.value = false }
)
}
Scaffold(
topBar = {
if (webViewState != null) {
TopBar(
webViewState = webViewState!!,
fileId = fileId,
download = state.download,
openOfflineReader = {
viewModel.logOpenOfflineReader()
openOfflineReader(fileId)
},
downloadItem = { viewModel.downloadItem(fileId) },
shareItem = { viewModel.shareItem(context) },
goBack = { viewModel.goBack() }
)
}
}
) { paddingValues ->
ProvideScaffoldPadding(padding = paddingValues) {
if (webViewState != null) {
WebView(webViewState = webViewState!!, updateUrl = viewModel::updateCurrentPage)
}
}
}
}
@SuppressLint("SetJavaScriptEnabled")
@Composable
private fun WebView(
webViewState: WebViewState,
updateUrl: (String) -> Unit,
modifier: Modifier = Modifier,
) {
AccompanistWebView(
state = webViewState,
modifier = modifier
.fillMaxSize()
.padding(top = topScaffoldPadding())
.navigationBarsPadding(),
onCreated = { it.settings.javaScriptEnabled = true },
client = remember { ReaderWebViewClient(updateUrl) }
)
}
@Composable
private fun TopBar(
webViewState: WebViewState,
fileId: String?,
download: ItemWithDownload?,
shareItem: () -> Unit,
openOfflineReader: () -> Unit,
downloadItem: () -> Unit,
goBack: () -> Unit,
) {
Column {
TopBar(
title = webViewState.pageTitle.orEmpty(),
navigationIcon = { CloseButton(onClick = goBack) },
actions = {
if (webViewState.lastLoadedUrl != null) {
IconButton(
tint = MaterialTheme.colorScheme.primary,
imageVector = Icons.Share,
onClick = shareItem,
)
}
if (fileId != null) {
DownloadIcon(
downloadInfo = download?.downloadInfo,
onDownloadClicked = downloadItem,
openOfflineReader = openOfflineReader
)
}
}
)
AnimatedVisibility(webViewState.isLoading) {
LinearProgressIndicator(modifier = Modifier.fillMaxWidth())
}
}
}
@Composable
fun DownloadIcon(
downloadInfo: DownloadInfo?,
onDownloadClicked: () -> Unit,
openOfflineReader: () -> Unit,
) {
if (downloadInfo?.status == DownloadStatus.COMPLETED) {
IconButton(
imageVector = Icons.ReadOffline,
tint = MaterialTheme.colorScheme.primary,
onClick = openOfflineReader,
)
} else if (downloadInfo != null) {
DownloadStatusIcons(
downloadInfo = downloadInfo
)
} else {
IconButton(
imageVector = Icons.Download,
tint = MaterialTheme.colorScheme.primary,
contentDescription = stringResource(R.string.cd_download_file),
onClick = onDownloadClicked
)
}
}
@Composable
fun DownloadCompleteDialog(openOfflineReader: () -> Unit, onDismiss: () -> Unit) {
AlertDialog(
title = stringResource(string.download_complete),
text = stringResource(string.continue_reading_offline),
confirmButton = {
AlertDialogAction(
text = stringResource(string.open_offline),
onClick = openOfflineReader
)
},
cancelButton = {
AlertDialogAction(text = stringResource(string.close), onClick = onDismiss)
},
onDismissRequest = onDismiss,
properties = DialogProperties(dismissOnBackPress = false, dismissOnClickOutside = false)
)
}
| 4
| null |
19
| 257
|
b8dda2dd483b8faee6bd752c1daec525e1461405
| 7,148
|
Kafka
|
Apache License 2.0
|
src/main/kotlin/org/caffeine/chaos/api/client/ClientFriend.kt
|
caffeine-moe
| 479,810,319
| false
|
{"Kotlin": 158081}
|
package org.caffeine.chaos.api.client
@kotlinx.serialization.Serializable
data class ClientFriend(
override val username : String,
override val discriminator : String,
override val id : String,
override val avatar : String?,
) : DiscordUser() {
override val discriminatedName = "$username#$discriminator"
}
| 2
|
Kotlin
|
3
| 29
|
e378093a0694af80681f0433063e5b28a84086be
| 327
|
CHAOS
|
MIT License
|
sample/src/main/java/com/tabesto/printer/sample/PrinterItem.kt
|
Tabesto
| 339,833,685
| false
| null |
package com.tabesto.printer.sample
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.widget.doAfterTextChanged
import androidx.recyclerview.widget.RecyclerView
import com.mikepenz.fastadapter.FastAdapter
import com.mikepenz.fastadapter.binding.AbstractBindingItem
import com.mikepenz.fastadapter.listeners.ClickEventHook
import com.mikepenz.fastadapter.select.SelectExtension
import com.tabesto.printer.model.PrinterData
import com.tabesto.printer.sample.databinding.ItemviewPrinterItemBinding
import com.tabesto.printer.sample.util.asBinding
class PrinterItem(var printerData: PrinterData?, private val listener: Listener? = null) :
AbstractBindingItem<ItemviewPrinterItemBinding>() {
override val type: Int
get() = R.id.fastadapter_printer_item_id
override fun bindView(binding: ItemviewPrinterItemBinding, payloads: List<Any>) {
binding.edittextPrinterItemAddress.apply {
setText(printerData?.printerAddress)
doAfterTextChanged {
val enteredAddress = it.toString()
val newPrinterData = printerData?.copy(printerAddress = enteredAddress)
printerData = newPrinterData
}
}
isSelected = binding.checkboxPrinterItem.isChecked
binding.checkboxPrinterItem.setOnCheckedChangeListener { _, isChecked ->
if (isChecked) {
listener?.onPrinterSelected(this)
} else {
listener?.onPrinterUnselected(this)
}
}
}
override fun createBinding(inflater: LayoutInflater, parent: ViewGroup?): ItemviewPrinterItemBinding =
ItemviewPrinterItemBinding.inflate(inflater, parent, false)
class CheckBoxClickEvent : ClickEventHook<PrinterItem>() {
override fun onBind(viewHolder: RecyclerView.ViewHolder): View? {
return viewHolder.asBinding<ItemviewPrinterItemBinding> {
it.checkboxPrinterItem
}
}
override fun onClick(
v: View,
position: Int,
fastAdapter: FastAdapter<PrinterItem>,
item: PrinterItem
) {
val selectExtension: SelectExtension<PrinterItem> = fastAdapter.requireExtension()
selectExtension.toggleSelection(position)
}
}
class StatusClickEvent(private val listener: Listener? = null) : ClickEventHook<PrinterItem>() {
override fun onBind(viewHolder: RecyclerView.ViewHolder): View? {
return viewHolder.asBinding<ItemviewPrinterItemBinding> {
it.imageviewPrinterItemStatusButton
}
}
override fun onClick(
v: View,
position: Int,
fastAdapter: FastAdapter<PrinterItem>,
item: PrinterItem
) {
listener?.onPrinterStatusButtonClick(position, item)
}
}
interface Listener {
fun onPrinterStatusButtonClick(position: Int, item: PrinterItem)
fun onPrinterSelected(item: PrinterItem)
fun onPrinterUnselected(item: PrinterItem)
}
}
| 0
|
Kotlin
|
0
| 2
|
b423b830e99f8b2250678d43be876de322502d06
| 3,146
|
android-pos-printer
|
MIT License
|
app/src/main/java/io/chipotie/gifinder/model/OriginalGif.kt
|
chipotledev
| 177,696,457
| false
| null |
package io.chipotie.gifinder.model
import android.os.Parcelable
import com.google.gson.annotations.SerializedName
import kotlinx.android.parcel.Parcelize
/*
* @author savirdev on 26/03/19
*/
@Parcelize
data class OriginalGif(
@SerializedName("url")
val url : String
) : Parcelable
| 0
|
Kotlin
|
0
| 2
|
df7f7e822fddd1b9db45b1595a533987fbaa7243
| 293
|
Gifinder
|
Apache License 2.0
|
src/commonMain/kotlin/data/items/BlackFelsteelBracers.kt
|
marisa-ashkandi
| 332,658,265
| false
| null |
package `data`.items
import `data`.Constants
import `data`.model.Item
import `data`.model.ItemSet
import `data`.model.Socket
import `data`.model.SocketBonus
import character.Buff
import character.Stats
import kotlin.Array
import kotlin.Boolean
import kotlin.Double
import kotlin.Int
import kotlin.String
import kotlin.collections.List
import kotlin.js.JsExport
@JsExport
public class BlackFelsteelBracers : Item() {
public override var isAutoGenerated: Boolean = true
public override var id: Int = 23537
public override var name: String = "Black Felsteel Bracers"
public override var itemLevel: Int = 105
public override var quality: Int = 4
public override var icon: String = "inv_bracer_07.jpg"
public override var inventorySlot: Int = 9
public override var itemSet: ItemSet? = null
public override var itemClass: Constants.ItemClass? = Constants.ItemClass.ARMOR
public override var itemSubclass: Constants.ItemSubclass? = Constants.ItemSubclass.PLATE
public override var allowableClasses: Array<Constants.AllowableClass>? = null
public override var minDmg: Double = 0.0
public override var maxDmg: Double = 0.0
public override var speed: Double = 0.0
public override var stats: Stats = Stats(
strength = 26,
stamina = 15,
armor = 581,
meleeCritRating = 22.0,
rangedCritRating = 22.0
)
public override var sockets: Array<Socket> = arrayOf()
public override var socketBonus: SocketBonus? = null
public override val buffs: List<Buff> by lazy {
listOf()}
}
| 21
|
Kotlin
|
11
| 25
|
9cb6a0e51a650b5d04c63883cb9bf3f64057ce73
| 1,556
|
tbcsim
|
MIT License
|
string-util/src/main/kotlin/com/seanshubin/condorcet/backend/string/util/RowStyleTableFormatter.kt
|
SeanShubin
| 238,518,165
| false
| null |
package com.seanshubin.game_4x.format
import com.seanshubin.game_4x.format.TableFormatter.Companion.escapeString
import com.seanshubin.game_4x.format.TableFormatter.Companion.toBufferedReader
import com.seanshubin.game_4x.format.TableFormatter.Companion.transpose
import com.seanshubin.game_4x.format.TableFormatter.Justify.Left
import com.seanshubin.game_4x.format.TableFormatter.Justify.Right
import java.io.Reader
data class RowStyleTableFormatter(
private val cellToString: (Any?) -> String,
private val content: RowStyle,
private val top: RowStyle? = null,
private val bottom: RowStyle? = null,
private val separator: RowStyle? = null
) : TableFormatter {
override fun format(originalRows: List<List<Any?>>): List<String> {
val paddedRows = makeAllRowsTheSameSize(originalRows, "")
val columns = paddedRows.transpose()
val columnWidths = columns.map { a: List<Any?> -> maxWidthForColumn(a) }
val formattedRows = formatRows(columnWidths, paddedRows)
val content = if (separator == null) {
formattedRows
} else {
val content = separator.format(columnWidths)
interleave(formattedRows, content)
}
val top = if (top == null) listOf() else listOf(top.format(columnWidths))
val bottom = if (bottom == null) listOf() else listOf(bottom.format(columnWidths))
return top + content + bottom
}
override fun <T> parse(reader: Reader, mapToElement: (Map<String, String>) -> T): Iterable<T> {
val lineIterator = LineIterator(reader)
return TableIterable(lineIterator, mapToElement)
}
private class LineIterator(reader: Reader) : Iterator<String> {
private val bufferedReader = reader.toBufferedReader()
private var currentLine: String? = bufferedReader.readLine()
override fun hasNext(): Boolean = currentLine != null
override fun next(): String {
val result = currentLine!!
currentLine = bufferedReader.readLine()
return result
}
}
private class EmptyIterator<T> : Iterator<T> {
override fun hasNext(): Boolean = false
override fun next(): T {
throw UnsupportedOperationException("next() on an empty iterator")
}
}
private class TableIteratorWithColumnIndices<T>(
val lineIterator: LineIterator,
val mapToElement: (Map<String, String>) -> T,
val columnIndexNamePairs: List<Pair<Int, String>>
) : Iterator<T> {
val columnIndexToNameMap = columnIndexNamePairs.toMap()
val columnIndices = columnIndexNamePairs.map { it.first }
val windowed = columnIndices.windowed(2)
override fun hasNext(): Boolean = lineIterator.hasNext()
override fun next(): T {
val line = lineIterator.next()
val cells = parseCells(line)
val map = cells.mapIndexed { index, cell -> Pair(columnIndexNamePairs[index].second, cell) }.toMap()
return mapToElement(map)
}
private fun parseCells(line: String): List<String> {
val exceptLast = windowed.map { (startIndex, endIndex) ->
line.substring(startIndex, endIndex)
}
val last = line.substring(columnIndices.last())
return exceptLast + last
}
}
private class TableIterable<T>(val lineIterator: LineIterator, val mapToElement: (Map<String, String>) -> T) :
Iterable<T> {
override operator fun iterator(): Iterator<T> {
if (!lineIterator.hasNext()) return EmptyIterator<T>()
val columnIndices = parseColumnIndices(lineIterator.next())
return TableIteratorWithColumnIndices(lineIterator, mapToElement, columnIndices)
}
fun parseColumnIndices(header: String): List<Pair<Int, String>> {
val word = Regex("""[^\s]+""")
val matches = word.findAll(header)
return matches.map { matchResult ->
val index = matchResult.range.first
val name = matchResult.value
Pair(index, name)
}.toList()
}
}
private fun makeAllRowsTheSameSize(rows: List<List<Any?>>, value: Any): List<List<Any?>> {
val rowSizes = rows.map { row -> row.size }
val targetSize = rowSizes.maxOrNull() ?: 0
fun makeRowSameSize(row: List<Any?>): List<Any?> {
val extraCells = makeExtraCells(targetSize - row.size, value)
return row + extraCells
}
return rows.map { makeRowSameSize(it) }
}
private fun makeExtraCells(howMany: Int, contents: Any): List<Any> {
return (1..howMany).map { contents }
}
private fun formatRows(columnWidths: List<Int>, rows: List<List<Any?>>): List<String> =
rows.map { row ->
content.format(columnWidths, row, ::formatCell)
}
private fun <T> interleave(data: List<T>, separator: T): List<T> {
fun combine(soFar: List<T>, next: T): List<T> {
return listOf(next) + listOf(separator) + soFar
}
val combineLambda = { a: List<T>, b: T -> combine(a, b) }
return if (data.isEmpty()) {
emptyList()
} else {
data.drop(1).fold(listOf(data.first()), combineLambda).asReversed()
}
}
private fun maxWidthForColumn(column: List<Any?>): Int {
return column.map { cell -> cellWidth(cell) }.max() ?: 0
}
private fun cellWidth(cell: Any?): Int = justifiedCellToString(cell).length
private fun formatCell(cell: Any?, width: Int, padding: String): String =
when (cell) {
is Left -> leftJustify(justifiedCellToString(cell.x), width, padding)
is Right -> rightJustify(justifiedCellToString(cell.x), width, padding)
null -> rightJustify(justifiedCellToString(cell = null), width, padding)
is String -> leftJustify(justifiedCellToString(cell), width, padding)
is Boolean -> leftJustify(justifiedCellToString(cell), width, padding)
is Enum<*> -> leftJustify(justifiedCellToString(cell), width, padding)
else -> rightJustify(justifiedCellToString(cell), width, padding)
}
private fun rightJustify(s: String, width: Int, padding: String = " "): String {
return paddingFor(s, width, padding) + s
}
private fun leftJustify(s: String, width: Int, padding: String = " "): String {
return s + paddingFor(s, width, padding)
}
private fun paddingFor(s: String, width: Int, padding: String): String {
val quantity = width - s.length
return padding.repeat(quantity)
}
private fun justifiedCellToString(cell: Any?): String =
when (cell) {
is Left -> justifiedCellToString(cell.x)
is Right -> justifiedCellToString(cell.x)
else -> cellToString(cell)
}
data class RowStyle(
val left: String,
val middle: String,
val right: String,
val separator: String
) {
fun format(columnWidths: List<Int>): String {
val columns: List<String> = columnWidths.map(middle::repeat)
val expandedMiddle: String = columns.joinToString(separator)
return left + expandedMiddle + right
}
fun format(columnWidths: List<Int>, data: List<Any?>, formatCell: (Any?, Int, String) -> String): String {
val cells = (columnWidths zip data).map { (width, data) -> formatCell(data, width, middle) }
val expandedCells = cells.joinToString(separator)
return left + expandedCells + right
}
}
companion object {
val boxDrawing = RowStyleTableFormatter(
cellToString = escapeString,
content = RowStyle(
left = "║",
middle = " ",
right = "║",
separator = "│"
),
top = RowStyle(
left = "╔",
middle = "═",
right = "╗",
separator = "╤"
),
bottom = RowStyle(
left = "╚",
middle = "═",
right = "╝",
separator = "╧"
),
separator = RowStyle(
left = "╟",
middle = "─",
right = "╢",
separator = "┼"
)
)
val plainText = RowStyleTableFormatter(
cellToString = escapeString,
content = RowStyle(
left = "|",
middle = " ",
right = "|",
separator = "|"
),
top = RowStyle(
left = "/",
middle = "-",
right = "\\",
separator = "+"
),
bottom = RowStyle(
left = "\\",
middle = "-",
right = "/",
separator = "+"
),
separator = RowStyle(
left = "+",
middle = "-",
right = "+",
separator = "+"
)
)
val minimal = RowStyleTableFormatter(
cellToString = escapeString,
content = RowStyle(
left = "",
middle = " ",
right = "",
separator = " "
),
top = null,
bottom = null,
separator = null
)
}
}
| 1
| null |
1
| 1
|
c6dd3e86d9f722829c57d215fcfa7cb18b7955cd
| 9,605
|
kotlin-tryme
|
The Unlicense
|
buildSrc/src/main/kotlin/io/petros/movies/config/deps/Versions.kt
|
ParaskP7
| 148,126,048
| false
| null |
package io.petros.movies.config.deps
@Suppress("StringLiteralDuplication")
object Versions {
// DEBUG IMPLEMENTATION // *****************************************************************************************
object LeakCanary {
// Releases: https://github.com/square/leakcanary/releases
const val LEAK_CANARY = "2.7" // Released: 26-03-21
}
// IMPLEMENTATION // ***********************************************************************************************
object Kotlin {
// Releases: https://github.com/Kotlin/kotlinx.coroutines/releases
@Suppress("unused") const val COROUTINES = "1.5.2" // Released: 02-09-21
const val COROUTINES_RC = "1.6.0-RC3" // Released: 16-12-21
}
@Suppress("MemberNameEqualsClassName")
object Material {
// Releases: https://github.com/material-components/material-components-android/releases
@Suppress("unused") const val MATERIAL = "1.4.0" // Released: 02-07-21
const val MATERIAL_RC = "1.5.0-rc01" // Released: 13-12-21
}
object Android {
object Core {
// Releases: https://developer.android.com/jetpack/androidx/releases/appcompat
const val APP_COMPAT = "1.4.0" // Released: 17-11-20
// Releases: https://developer.android.com/jetpack/androidx/releases/fragment
const val FRAGMENT = "1.4.0" // Released: 17-11-21
// Releases: https://developer.android.com/jetpack/androidx/releases/recyclerview
const val RECYCLER_VIEW = "1.2.1" // Released: 02-06-21
// Releases: https://developer.android.com/jetpack/androidx/releases/constraintlayout
const val CONSTRAINT_LAYOUT = "2.1.2" // Released: 16-11-21
// Releases: https://developer.android.com/jetpack/androidx/releases/drawerlayout
const val DRAWER_LAYOUT = "1.1.1" // Released: 02-09-20
// Releases: https://developer.android.com/jetpack/androidx/releases/coordinatorlayout
@Suppress("unused") const val COORDINATOR_LAYOUT = "1.1.0" // Released: 04-12-19
const val COORDINATOR_LAYOUT_RC = "1.2.0-rc01" // Released: 15-12-21
}
object Ktx {
// Releases: https://developer.android.com/jetpack/androidx/releases/core
const val CORE = "1.7.0" // Released: 27-10-21
}
@Suppress("MemberNameEqualsClassName")
object Compose {
// Releases: https://developer.android.com/jetpack/androidx/releases/compose
@Suppress("unused") const val COMPOSE = "1.0.5" // Released: 03-11-21
const val COMPOSE_RC1 = "1.1.0-rc01" // Released: 15-12-21
const val COMPOSE_RC2 = "1.1.0-rc02" // Released: 16-12-21
object ConstraintLayout {
// Releases: https://developer.android.com/jetpack/androidx/releases/constraintlayout
const val CONSTRAINT_LAYOUT_RC = "1.0.0-rc02" // Released: 16-11-21
}
}
object Arch {
@Suppress("MemberNameEqualsClassName")
object Core {
// Releases: https://developer.android.com/jetpack/androidx/releases/arch-core
const val CORE = "2.1.0" // Released: 05-09-19
}
@Suppress("MemberNameEqualsClassName")
object Lifecycle {
// Releases: https://developer.android.com/jetpack/androidx/releases/lifecycle
const val LIFECYCLE = "2.4.0" // Released: 27-10-21
}
@Suppress("MemberNameEqualsClassName")
object SavedState {
// Releases: https://developer.android.com/jetpack/androidx/releases/savedstate
const val SAVED_STATE = "1.1.0" // Released: 10-02-20
}
@Suppress("MemberNameEqualsClassName")
object Navigation {
// Releases: https://developer.android.com/jetpack/androidx/releases/navigation
@Suppress("unused") const val NAVIGATION = "2.3.5" // Released: 07-04-21
const val NAVIGATION_RC = "2.4.0-rc01" // Released: 15-12-21
}
object CustomView {
// Releases: https://developer.android.com/jetpack/androidx/releases/customview
const val CUSTOM_VIEW = "1.1.0" // Release: 24-06-20
}
@Suppress("MemberNameEqualsClassName")
object DataStore {
// Releases: https://developer.android.com/jetpack/androidx/releases/datastore
const val DATASTORE = "1.0.0" // Release: 04-08-21
}
object Database {
@Suppress("MemberNameEqualsClassName")
object SQLight {
// Releases: https://developer.android.com/jetpack/androidx/releases/sqlite
const val SQLIGHT = "2.2.0" // Release: 15-12-21
}
@Suppress("MemberNameEqualsClassName")
object Room {
// Releases: https://developer.android.com/jetpack/androidx/releases/room
const val ROOM = "2.4.0" // Release: 15-12-21
}
}
@Suppress("MemberNameEqualsClassName")
object Pagination {
// Releases: https://developer.android.com/jetpack/androidx/releases/paging
const val PAGING = "3.1.0" // Release: 17-11-21
}
}
object Test {
// Releases: https://developer.android.com/jetpack/androidx/releases/test
const val CORE = "1.4.0" // Released: 30-06-21
const val ESPRESSO = "3.4.0" // Released: 30-06-21
const val J_UNIT = "1.1.3" // Released: 30-06-21
// Releases: https://github.com/robolectric/robolectric/releases
const val ROBOLECTRIC = "4.7.3" // Released: 01-12-21
}
}
object Di {
@Suppress("MemberNameEqualsClassName")
object Koin {
// Releases: https://github.com/InsertKoinIO/koin/releases
const val KOIN = "3.1.4" // Released: 26-11-21
}
}
object Net {
object OkHttp {
// Releases: https://github.com/square/okhttp/releases
@Suppress("unused") const val OK_HTTP = "4.9.3" // Released: 21-11-21
@Suppress("unused") const val OK_HTTP_RC = "4.10.0-RC1" // Released: 07-10-21
const val OK_HTTP_ALPHA = "5.0.0-alpha.3" // Released: 22-02-21
}
@Suppress("MemberNameEqualsClassName")
object Gson {
// Releases: https://github.com/google/gson/releases
const val GSON = "2.8.9" // Released: 29-10-21
}
object Rest {
// Releases: https://github.com/square/retrofit/releases
const val RETROFIT = "2.9.0" // Released: 20-05-20
}
}
object Image {
@Suppress("MemberNameEqualsClassName")
object Glide {
// Releases: https://github.com/bumptech/glide/releases
const val GLIDE = "4.12.0" // Released: 29-01-21
}
@Suppress("MemberNameEqualsClassName")
object Coil {
// Releases: https://github.com/coil-kt/coil/releases
@Suppress("unused") const val COIL = "1.4.0" // Released: 06-10-21
const val COIL_ALPHA = "2.0.0-alpha05" // Released: 28-11-21
}
}
object Log {
// Releases: https://github.com/JakeWharton/timber/releases
const val TIMBER = "5.0.1" // Released: 13-08-18
}
// TEST IMPLEMENTATION // ******************************************************************************************
object Test {
object JUnit {
// Releases: https://github.com/junit-team/junit4/releases
const val J_UNIT_4 = "4.13.2" // Released: 13-02-21
}
@Suppress("MemberNameEqualsClassName")
object Hamcrest {
// Releases: https://github.com/hamcrest/JavaHamcrest/releases
const val HAMCREST = "1.3" // Released: 10-06-12
}
object Assert {
// Releases: https://github.com/robfletcher/strikt/releases
const val STRIKT = "0.33.0" // Released: 16-11-21
}
object Mock {
// Releases: https://github.com/mockk/mockk/releases
const val MOCK_K = "1.12.1" // Released: 17-11-21
}
}
}
| 0
| null |
21
| 130
|
c86a669c4c21a2702a63404e6abf2547c3cec3fd
| 8,525
|
sample-code-movies
|
Apache License 2.0
|
app/src/main/java/io/horizontalsystems/bankwallet/modules/walletconnect/scanqr/WalletConnectScanQrViewModel.kt
|
fahimaltinordu
| 312,207,740
| false
| null |
package io.horizontalsystems.bankwallet.modules.walletconnect.scanqr
import androidx.lifecycle.ViewModel
import io.horizontalsystems.bankwallet.modules.walletconnect.WalletConnectService
import io.horizontalsystems.core.SingleLiveEvent
class WalletConnectScanQrViewModel(private val service: WalletConnectService) : ViewModel() {
val openMainLiveEvent = SingleLiveEvent<Unit>()
val openErrorLiveEvent = SingleLiveEvent<Throwable>()
fun handleScanned(string: String) {
try {
service.connect(string)
openMainLiveEvent.postValue(Unit)
} catch (t: Throwable) {
openErrorLiveEvent.postValue(t)
}
}
}
| 0
| null |
1
| 4
|
d3094c4afaa92a5d63ce53583bc07c8fb343f90b
| 676
|
WILC-wallet-android
|
MIT License
|
app/src/main/java/ru/lozenko/kotlincompiletimereflection/ManualSettingsRealization.kt
|
Ivan876l678
| 164,870,372
| false
| null |
package ru.lozenko.kotlincompiletimereflection
import android.content.Context
/**
* Created by <NAME>
*
*
*/
class ManualSettingsRealization(context: Context){
private val sharedPreferences = context.getSharedPreferences("MANUAL_SETTINGS", Context.MODE_PRIVATE)
var setting1: Boolean
get() = sharedPreferences.getBoolean("setting1", false)
set(value) = sharedPreferences.edit().putBoolean("setting1", value).apply()
var setting2: String?
get() = sharedPreferences.getString("setting2", null)
set(value) = sharedPreferences.edit().putString("setting2", value).apply()
}
| 0
|
Kotlin
|
1
| 1
|
342289b352c72f71c55af180d2dca40af554d0b9
| 607
|
KotlinCompileTimeReflection
|
Apache License 2.0
|
network_scanner/app/src/main/java/com/example/scrima/ui/ProfileFragment.kt
|
2020-B-Aplicaciones-Web-Software
| 389,814,671
| false
| null |
package com.example.scrima.ui
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import com.example.scrima.R
import com.example.scrima.general.FirebaseConnection
import com.google.firebase.auth.FirebaseAuth
import org.w3c.dom.Text
class ProfileFragment : Fragment(R.layout.fragment_profile) {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val auth = FirebaseAuth.getInstance()
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_profile, container, false)
// Fill text views
val name = view.findViewById<TextView>(R.id.tv_userprofile_name)
val email = view.findViewById<TextView>(R.id.tv_userprofile_email)
val totalScans = view.findViewById<TextView>(R.id.tv_userprofile_scan)
FirebaseConnection.getInstance()
.collection("users")
.whereEqualTo("uid", auth.currentUser!!.uid)
.get()
.addOnSuccessListener { result ->
for(document in result){
name.setText("${document.get("username")} ${document.get("lastname")}")
email.setText("${document.get("email")}")
totalScans.setText("${document.get("totalScans")}")
}
}
// Sign Out
view.findViewById<Button>(R.id.btn_signout).setOnClickListener {
auth.signOut()
if (container != null) {
openActivity(container.context, LogInActivity::class.java)
}
}
// Edit Users information
view.findViewById<Button>(R.id.btn_edit_user_profile).setOnClickListener {
openActivity(container!!.context, EditUserProfileActivity::class.java)
}
return view
}
override fun onResume() {
super.onResume()
requireFragmentManager()!!.beginTransaction().detach(this).attach(this).commit();
}
fun openActivity(context: Context, classRef: Class<*>) {
val intentExplicito = Intent(
context,
classRef
)
startActivity(intentExplicito)
}
}
| 0
|
Kotlin
|
1
| 1
|
09d0cc7b6a04b07e105a65fd9b5ec9ae5d489d7d
| 2,614
|
mov-soft-llanganate-quimbiamba-proyecto
|
MIT License
|
src/main/kotlin/no/uib/inf273/data/VesselCargo.kt
|
elgbar
| 237,403,030
| false
| null |
package no.uib.inf273.data
import no.uib.inf273.processor.DataParser.Companion.INCOMPATIBLE
data class VesselCargo(val originPortTime: Int, val originPortCost: Int, val destPortTime: Int, val destPortCost: Int) {
companion object {
/**
* Object to be used when vessel and cargo is not compatible
*/
val incompatibleVesselCargo = VesselCargo(INCOMPATIBLE, INCOMPATIBLE, INCOMPATIBLE, INCOMPATIBLE)
}
}
| 0
|
Kotlin
|
0
| 3
|
1f76550a631527713b1eba22817e6c1215f5d84e
| 448
|
INF273
|
The Unlicense
|
src/test/kotlin/no/nav/familie/ba/skatteetaten/maskinporten/MaskinportenClient.kt
|
navikt
| 400,165,747
| false
| null |
package no.nav.familie.ba.skatteetaten.maskinporten
import com.nimbusds.jose.JOSEException
import com.nimbusds.jose.JOSEObjectType
import com.nimbusds.jose.JWSAlgorithm
import com.nimbusds.jose.JWSHeader
import com.nimbusds.jose.JWSSigner
import com.nimbusds.jose.crypto.RSASSASigner
import com.nimbusds.jose.jwk.RSAKey
import com.nimbusds.jwt.JWTClaimsSet
import com.nimbusds.jwt.SignedJWT
import no.nav.familie.eksterne.kontrakter.skatteetaten.SkatteetatenPerioderRequest
import no.nav.familie.eksterne.kontrakter.skatteetaten.SkatteetatenPerioderResponse
import no.nav.familie.eksterne.kontrakter.skatteetaten.SkatteetatenPersonerResponse
import no.nav.familie.kontrakter.felles.objectMapper
import org.springframework.http.HttpEntity
import org.springframework.http.HttpHeaders
import org.springframework.http.HttpMethod
import org.springframework.http.MediaType
import org.springframework.util.LinkedMultiValueMap
import org.springframework.web.client.RestTemplate
import java.io.File
import java.time.Instant
import java.time.LocalDateTime
import java.util.Date
fun main() {
val jwkPrivate: String = System.getenv("MASKINPORTEN_CLIENT_JWK")
assert(jwkPrivate.isNotBlank())
val clientId: String = System.getenv("MASKINPORTEN_CLIENT_ID")
assert(clientId.isNotBlank())
val token = MaskinportenClient().hentToken("nav:familie/v1/barnetrygd/utvidet", jwkPrivate, clientId)
println(token)
val jsonNodes = objectMapper.readTree(token)
val restTemplate = RestTemplate()
val httpHeaders = HttpHeaders()
httpHeaders.accept = listOf(MediaType.APPLICATION_JSON)
httpHeaders.setBearerAuth(jsonNodes.get("access_token").asText())
val entity: HttpEntity<*> = HttpEntity<Any?>(httpHeaders)
val responsePersoner =
restTemplate.exchange(
"https://familie-ba-skatteetaten-api.ekstern.dev.nav.no/api/v1/personer?aar=2021",
HttpMethod.GET,
entity,
SkatteetatenPersonerResponse::class.java,
)
val første1000identer = responsePersoner.body?.brukere?.take(1000)?.map { it.ident }!!
println(objectMapper.writeValueAsString(første1000identer))
val entityPerioder: HttpEntity<*> = HttpEntity<Any?>(SkatteetatenPerioderRequest("2021", første1000identer), httpHeaders)
val responsePerioder =
restTemplate.exchange(
"https://familie-ba-skatteetaten-api.ekstern.dev.nav.no/api/v1/perioder",
HttpMethod.POST,
entityPerioder,
SkatteetatenPerioderResponse::class.java,
)
val f = File.createTempFile("${LocalDateTime.now()}-skatt-perioder", ".tmp")
f.writeText(objectMapper.writeValueAsString(responsePerioder.body))
println("File created ${f.absolutePath}")
}
class MaskinportenClient {
private val restTemplate = RestTemplate()
private fun createSignedJWT(
rsaJwk: RSAKey,
claimsSet: JWTClaimsSet?,
): SignedJWT {
return try {
val header =
JWSHeader.Builder(JWSAlgorithm.RS256)
.keyID(rsaJwk.keyID)
.type(JOSEObjectType.JWT)
val signedJWT = SignedJWT(header.build(), claimsSet)
val signer: JWSSigner = RSASSASigner(rsaJwk.toPrivateKey())
signedJWT.sign(signer)
signedJWT
} catch (e: JOSEException) {
throw RuntimeException(e)
}
}
fun hentToken(
scope: String,
jwkPrivate: String,
clientId: String,
): String {
val rsaKey = RSAKey.parse(jwkPrivate)
val time = Instant.now()
val jwtClaimsSet =
JWTClaimsSet.Builder()
.audience(AUD)
.issuer(clientId)
.issueTime(Date.from(time))
.expirationTime(Date.from(time.plusSeconds(120)))
.claim(SCOPE, scope)
.build()
val signedJWT = createSignedJWT(rsaKey, jwtClaimsSet)
val headers = HttpHeaders()
headers.contentType = MediaType.APPLICATION_FORM_URLENCODED
val requestBody = LinkedMultiValueMap<Any, Any>()
requestBody.add("grant_type", GRANT_TYPE_VALUE)
requestBody.add("assertion", signedJWT.serialize())
val httpEntity = HttpEntity(requestBody, headers)
val json =
restTemplate.exchange(
TOKEN_ENDPOINT,
HttpMethod.POST,
httpEntity,
String::class.java,
).body!!
return json
}
companion object {
private const val SCOPE = "scope"
private const val GRANT_TYPE_VALUE = "urn:ietf:params:oauth:grant-type:jwt-bearer"
private const val AUD = "https://test.maskinporten.no/"
private const val TOKEN_ENDPOINT = "$AUD/token"
}
}
| 2
|
Kotlin
|
0
| 0
|
d2b8a1bcf2a433e501f05c3254baa93fb028d7eb
| 4,812
|
familie-ba-skatteetaten-api
|
MIT License
|
src/main/kotlin/org/ivcode/mvn/services/basicauth/model/BasicAuthModels.kt
|
iv-buildsystem
| 744,432,718
| false
|
{"Kotlin": 54402, "Shell": 2162, "FreeMarker": 1906, "Dockerfile": 870}
|
package org.ivcode.mvn.services.basicauth.model
public data class BasicAuthUser (
val username: String,
val write: Boolean
)
public data class CreateBasicAuthUser (
val username: String,
val password: String,
val write: Boolean
)
| 0
|
Kotlin
|
0
| 0
|
cba7a7853677ef502f648b186be88233b1375ae4
| 252
|
iv-mvn
|
Apache License 2.0
|
presentation/src/main/java/com/phelat/splash/presentation/photolist/viewmodel/PhotoListViewModel.kt
|
PHELAT
| 135,176,443
| false
|
{"Kotlin": 83388}
|
package com.phelat.splash.presentation.photolist.viewmodel
import android.arch.lifecycle.LiveData
import android.arch.lifecycle.MutableLiveData
import com.phelat.splash.data.entity.PhotoEntity
import com.phelat.splash.presentation.viewmodel.SplashViewModel
class PhotoListViewModel : SplashViewModel<MutableList<PhotoEntity>>() {
private val mutablePhotosObservable by lazy(LazyThreadSafetyMode.NONE) {
MutableLiveData<MutableList<PhotoEntity>>()
}
val photosObservable: LiveData<MutableList<PhotoEntity>> by lazy(LazyThreadSafetyMode.NONE) {
mutablePhotosObservable
}
override fun accept(mutableListOfPhotos: MutableList<PhotoEntity>) {
val listOfPhotos = mutablePhotosObservable.value
if (listOfPhotos != null) {
listOfPhotos.addAll(mutableListOfPhotos)
mutablePhotosObservable.value = listOfPhotos
} else {
mutablePhotosObservable.value = mutableListOfPhotos
}
}
}
| 0
|
Kotlin
|
1
| 2
|
8493fdf5b67a9e425839427cf7f43c9565c34e0b
| 981
|
Splash
|
Apache License 2.0
|
compiler/testData/compileKotlinAgainstCustomBinaries/obsoleteInlineSuspend/source.kt
|
JakeWharton
| 99,388,807
| false
| null |
import library.*
import kotlin.coroutines.experimental.*
suspend fun test() {
append("[foo]")
foo { // we are inlining foo here
append("(block)")
}
append("[bar]")
bar() // and invoking suspending function bar
append("[test]")
}
fun runBlockingLibrary(block: suspend () -> Unit): String {
var done = false
block.startCoroutine(object : Continuation<Unit> {
override val context: CoroutineContext = EmptyCoroutineContext
override fun resume(value: Unit) { done = true }
override fun resumeWithException(exception: Throwable) { throw exception }
})
var resumeCounter = 0
while (!done) {
resumeCounter++
resumeLibrary()
}
return "$libraryResult:resumes=$resumeCounter"
}
// Retruns array of expected and received string
fun run(): Array<String> {
val result = runBlockingLibrary {
test()
}
return arrayOf("[foo](foo)(block)[bar](bar)[test]:resumes=2", result)
}
| 0
| null |
28
| 83
|
4383335168338df9bbbe2a63cb213a68d0858104
| 983
|
kotlin
|
Apache License 2.0
|
spring-web/src/test/kotlin/org/springframework/http/codec/json/KotlinSerializationJsonDecoderTests.kt
|
spring-projects
| 1,148,753
| false
| null |
/*
* Copyright 2002-2022 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.http.codec.json
import kotlinx.serialization.Serializable
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.springframework.core.Ordered
import org.springframework.core.ResolvableType
import org.springframework.core.io.buffer.DataBuffer
import org.springframework.core.testfixture.codec.AbstractDecoderTests
import org.springframework.http.MediaType
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
import reactor.test.StepVerifier
import reactor.test.StepVerifier.FirstStep
import java.lang.UnsupportedOperationException
import java.nio.charset.Charset
import java.nio.charset.StandardCharsets
/**
* Tests for the JSON decoding using kotlinx.serialization.
*
* @author <NAME>
*/
class KotlinSerializationJsonDecoderTests : AbstractDecoderTests<KotlinSerializationJsonDecoder>(KotlinSerializationJsonDecoder()) {
@Suppress("UsePropertyAccessSyntax", "DEPRECATION")
@Test
override fun canDecode() {
val jsonSubtype = MediaType("application", "vnd.test-micro-type+json")
assertThat(decoder.canDecode(ResolvableType.forClass(Pojo::class.java), MediaType.APPLICATION_JSON)).isTrue()
assertThat(decoder.canDecode(ResolvableType.forClass(Pojo::class.java), jsonSubtype)).isTrue()
assertThat(decoder.canDecode(ResolvableType.forClass(Pojo::class.java), null)).isTrue()
assertThat(decoder.canDecode(ResolvableType.forClass(String::class.java), null)).isFalse()
assertThat(decoder.canDecode(ResolvableType.forClass(Pojo::class.java), MediaType.APPLICATION_XML)).isFalse()
assertThat(decoder.canDecode(ResolvableType.forClass(Pojo::class.java),
MediaType("application", "json", StandardCharsets.UTF_8))).isTrue()
assertThat(decoder.canDecode(ResolvableType.forClass(Pojo::class.java),
MediaType("application", "json", StandardCharsets.US_ASCII))).isTrue()
assertThat(decoder.canDecode(ResolvableType.forClass(Pojo::class.java),
MediaType("application", "json", StandardCharsets.ISO_8859_1))).isTrue()
assertThat(decoder.canDecode(ResolvableType.forClassWithGenerics(List::class.java, Int::class.java), MediaType.APPLICATION_JSON)).isTrue()
assertThat(decoder.canDecode(ResolvableType.forClassWithGenerics(List::class.java, Ordered::class.java), MediaType.APPLICATION_JSON)).isFalse()
assertThat(decoder.canDecode(ResolvableType.forClassWithGenerics(List::class.java, Pojo::class.java), MediaType.APPLICATION_JSON)).isTrue()
assertThat(decoder.canDecode(ResolvableType.forClassWithGenerics(ArrayList::class.java, Int::class.java), MediaType.APPLICATION_JSON)).isTrue()
assertThat(decoder.canDecode(ResolvableType.forClassWithGenerics(ArrayList::class.java, Int::class.java), MediaType.APPLICATION_PDF)).isFalse()
assertThat(decoder.canDecode(ResolvableType.forClass(Ordered::class.java), MediaType.APPLICATION_JSON)).isFalse()
assertThat(decoder.canDecode(ResolvableType.NONE, MediaType.APPLICATION_JSON)).isFalse()
}
@Test
override fun decode() {
val output = decoder.decode(Mono.empty(), ResolvableType.forClass(Pojo::class.java), null, emptyMap())
StepVerifier
.create(output)
.expectError(UnsupportedOperationException::class.java)
}
@Test
override fun decodeToMono() {
val input = Flux.concat(
stringBuffer("[{\"bar\":\"b1\",\"foo\":\"f1\"},"),
stringBuffer("{\"bar\":\"b2\",\"foo\":\"f2\"}]"))
val elementType = ResolvableType.forClassWithGenerics(List::class.java, Pojo::class.java)
testDecodeToMonoAll(input, elementType, { step: FirstStep<Any> ->
step
.expectNext(listOf(Pojo("f1", "b1"), Pojo("f2", "b2")))
.expectComplete()
.verify()
}, null, null)
}
private fun stringBuffer(value: String): Mono<DataBuffer> {
return stringBuffer(value, StandardCharsets.UTF_8)
}
private fun stringBuffer(value: String, charset: Charset): Mono<DataBuffer> {
return Mono.defer {
val bytes = value.toByteArray(charset)
val buffer = bufferFactory.allocateBuffer(bytes.size)
buffer.write(bytes)
Mono.just(buffer)
}
}
@Serializable
data class Pojo(val foo: String, val bar: String, val pojo: Pojo? = null)
}
| 4
| null |
4
| 56,506
|
52e813d0ad2a5d3439c1880b481b6942a138a8dc
| 4,745
|
spring-framework
|
Apache License 2.0
|
src/main/kotlin/org/example/util/UUIDUtil.kt
|
WuJianeng
| 256,488,250
| false
| null |
package org.example.util
import java.util.*
fun uuid(): String {
return UUID.randomUUID().toString().replace("-", "")
}
//fun main() {
// println(uuid())
//}
| 1
|
Kotlin
|
0
| 0
|
12e48eeef10878443e740cb7dc8998c424ba5808
| 167
|
seconds
|
MIT License
|
Application/app/src/main/java/com/demo/code/manualencoding/StudentInfo.kt
|
devrath
| 586,183,600
| false
| null |
package com.demo.code.manualencoding
import android.os.Build
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.Transient
import kotlinx.serialization.json.Json
@Serializable
data class StudentInfo(
@SerialName("name")
val studentName: String,
@SerialName("age")
val studentAge: Int,
val address: Address
)
fun main() {
val lollipop = StudentInfo("Ramesh", 21)
println(lollipop)
val json = Json.encodeToString(StudentInfo.serializer(), lollipop)
println(json)
}
| 0
|
Kotlin
|
0
| 0
|
14d51ba1c3fdb01e63670ff5ef7279bd6690be6a
| 562
|
KotlinSerialization
|
Apache License 2.0
|
src/test/kotlin/org/move/ide/inspections/MvUnusedVariableInspectionTest.kt
|
pontem-network
| 279,299,159
| false
| null |
package org.move.ide.inspections
import org.move.utils.tests.annotation.InspectionTestBase
class MvUnusedVariableInspectionTest : InspectionTestBase(MvUnusedVariableInspection::class) {
fun `test used function parameter`() = checkByText(
"""
module 0x1::M {
fun call(a: u8): u8 {
a + 1
}
}
"""
)
fun `test used variable`() = checkByText(
"""
module 0x1::M {
fun call(): u8 {
let a = 1;
a + 1
}
}
"""
)
fun `test no error if prefixed with underscore`() = checkByText(
"""
module 0x1::M {
fun call(_a: u8) {
let _b = 1;
}
}
"""
)
fun `test no unused parameter for native function`() = checkByText("""
module 0x1::main {
native fun main(a: u8);
}
""")
fun `test no unused parameter on uninterpreted spec function`() = checkByText("""
spec 0x1::main {
// An uninterpreted spec function to represent the stake reward formula.
spec fun spec_rewards_amount(
stake_amount: u64,
num_successful_proposals: u64,
num_total_proposals: u64,
rewards_rate: u64,
rewards_rate_denominator: u64,
): u64;
}
""")
}
| 9
|
Kotlin
|
14
| 50
|
af0e2bde6ee134efc96115b38ad6362c9207e29e
| 1,282
|
intellij-move
|
MIT License
|
src/main/java/com/bukowiecki/weevil/ui/SearchController.kt
|
marcin-bukowiecki
| 401,079,122
| false
| null |
/*
* Copyright 2021 <NAME>.
* Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
*/
package com.bukowiecki.weevil.ui
import com.bukowiecki.weevil.search.impl.SearchInputComponent
import com.intellij.debugger.engine.DebugProcessImpl
import com.intellij.debugger.engine.events.DebuggerCommandImpl
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project
/**
* @author <NAME>
*/
class SearchController(val searchDialog: SearchDialog,
val debugProcess: DebugProcessImpl,
val project: Project) {
private val log = Logger.getInstance(SearchController::class.java)
fun search(searchInputComponent: SearchInputComponent) {
val code = searchInputComponent.provideCode()
if (code.expression.isEmpty()) {
log.info("Searching code is empty")
return
}
log.info("Starting search for: $code")
searchDialog.clearTree()
searchDialog.setupTree()
val evaluator = searchDialog.getEvaluator() ?: return
disableSearchButton()
searchInputComponent
.getSearcher()?.search(this, searchInputComponent, evaluator) ?:
log.info("Could not find searcher for language: " + searchInputComponent.language)
}
fun dispatch(toDispatch: () -> Unit) {
debugProcess.managerThread.invoke(
object : DebuggerCommandImpl() {
override fun action() {
toDispatch.invoke()
}
}
)
}
fun enableSearchButton() {
searchDialog.enableSearchButton()
}
private fun disableSearchButton() {
searchDialog.disableSearchButton()
}
}
| 0
|
Kotlin
|
1
| 3
|
1461169f0e1cbf3e4006b71fff9a97b271f43231
| 1,783
|
weevil-debugger-plugin
|
Apache License 2.0
|
app/src/main/java/org/simple/clinic/feature/Feature.kt
|
appdev-academy
| 292,263,031
| true
|
{"Kotlin": 4738177, "Shell": 3719, "Python": 3162}
|
package org.simple.clinic.feature
import android.os.Build
enum class Feature(
val enabledByDefault: Boolean,
val remoteConfigKey: String = ""
) {
EditBloodSugar(true),
NotifyAppUpdateAvailable(false, "appupdate_enabled"),
DeletePatient(true, "delete_patient_feature_enabled"),
SecureCalling(false, "phonenumbermasker_masking_enabled"),
LogSavedStateSizes(false, "log_saved_state_sizes_enabled"),
/**
* API levels 21 and 22 cause a framework level crash in appcompat 1.2.0 when overriding
* the configuration locale if a WebView is present in the layout. Since critical features
* in the app depend on a WebView, we will disable the change language feature for these
* API levels until this issue is resolved.
*
* There's a corresponding activity [org.simple.clinic.WebviewTestActivity], which you
* can run to verify the fix.
**/
ChangeLanguage(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M),
MLKitQrCodeScanner(true, "ml_kit_qr_code_scanner"),
InstantSearch(true, "instant_search")
}
| 0
|
Kotlin
|
0
| 0
|
2c7cc71a824bbe4a809bebaa95aef9555c6e7a18
| 1,038
|
simple-app-cameroon-android
|
MIT License
|
native/android/app/src/main/java/work/calmato/prestopay/database/DatabaseFriend.kt
|
calmato
| 260,225,803
| false
|
{"Go": 321615, "Kotlin": 266100, "TypeScript": 86093, "Swift": 24138, "HCL": 18561, "Java": 17973, "Vue": 6512, "Makefile": 6357, "Ruby": 6299, "Shell": 4355, "Dockerfile": 2406, "JavaScript": 1850, "SCSS": 138}
|
package work.calmato.prestopay.database
import androidx.room.Entity
import androidx.room.PrimaryKey
import androidx.room.TypeConverter
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import work.calmato.prestopay.network.*
@Entity
data class DatabaseFriend constructor(
@PrimaryKey
val id: String,
val name: String,
val username: String,
val email: String,
val thumbnailUrl: String?,
var checked: Boolean = false
)
@Entity
data class DatabaseGroup(
@PrimaryKey
val id: String,
val name: String,
val thumbnailUrl: String,
val userIds: List<String>,
val createdAt: String,
val updateAt: String,
val lendingStatus: List<NetworkPayer> = listOf()
)
@Entity
data class DatabasePayment(
@PrimaryKey
val id: String,
val groupId: String,
val name: String,
val currency: String,
val total: Float,
val payers: List<NetworkPayer>,
val positivePayers: List<NetworkPayer>,
val negativePayers: List<NetworkPayer>,
val isCompleted: Boolean,
val tags: List<String>?,
val comment: String?,
val imageUrls: List<String>?,
val paidAt: String,
val createdAt: String,
val updatedAt: String
)
@Entity
data class DatabaseTag(
@PrimaryKey
val name: String,
val imageId: Int,
var isSelected: Boolean = false
)
@Entity
data class DatabaseNationalFlag(
@PrimaryKey
val name: String,
val imageId: Int,
val fullName: String
)
fun List<DatabaseFriend>.asDomainModel(): List<UserProperty> {
return map {
UserProperty(
id = it.id,
name = it.name,
username = it.username,
email = it.email,
thumbnailUrl = it.thumbnailUrl,
checked = it.checked
)
}
}
fun List<DatabaseGroup>.asGroupModel(): List<GroupPropertyResponse> {
return map {
GroupPropertyResponse(
id = it.id,
name = it.name,
thumbnailUrl = it.thumbnailUrl,
userIds = it.userIds,
createdAt = it.createdAt,
updatedAt = it.updateAt
)
}
}
fun List<DatabasePayment>.asPaymentModel(): List<PaymentPropertyGet> {
return map {
PaymentPropertyGet(
id = it.id,
name = it.name,
currency = it.currency,
total = it.total,
payers = it.payers,
positivePayers = it.positivePayers,
negativePayers = it.negativePayers,
isCompleted = it.isCompleted,
tags = it.tags,
comment = it.comment,
imageUrls = it.imageUrls,
paidAt = it.paidAt,
createdAt = it.createdAt,
updatedAt = it.updatedAt
)
}
}
fun DatabaseTag.asTagModel(): Tag {
return Tag(
name = this.name,
imageId = this.imageId,
isSelected = this.isSelected
)
}
fun DatabaseNationalFlag.asNationalFlagModel(): NationalFlag {
return NationalFlag(
name = this.name,
imageId = this.imageId,
fullName = this.fullName
)
}
class ListTypeConverter {
@TypeConverter
fun toString(userIds: List<String?>?): String = userIds?.joinToString() ?: ""
@TypeConverter
fun toList(userIds: String): List<String> = listOf(userIds)
}
class ListPayerConverter {
@TypeConverter
fun storedStringToMyObjects(data: String?): List<NetworkPayer>? {
if (data == null) {
return emptyList()
}
return Gson().fromJson(data, object : TypeToken<List<NetworkPayer?>?>() {}.type)
}
@TypeConverter
fun myObjectsToStoredString(myObjects: List<NetworkPayer?>?): String? {
return Gson().toJson(myObjects)
}
}
| 42
|
Go
|
0
| 3
|
4350bb99485e5a8c9edc2e833e78546a24240bb9
| 3,406
|
presto-pay
|
MIT License
|
stripe/src/test/java/com/stripe/android/FingerprintDataRepositoryTest.kt
|
wchristiansen
| 249,545,106
| true
|
{"Kotlin": 2035465, "Java": 67744, "Ruby": 6208}
|
package com.stripe.android
import android.content.Context
import androidx.test.core.app.ApplicationProvider
import com.google.common.truth.Truth.assertThat
import java.util.UUID
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
class FingerprintDataRepositoryTest {
private val repository: FingerprintDataRepository = FingerprintDataRepository.Default(
ApplicationProvider.getApplicationContext<Context>()
)
@Test
fun roundtrip_shouldReturnOriginalObject() {
var fingerprintData: FingerprintData? = null
repository.save(DATA)
repository.get().observeForever {
fingerprintData = it
}
assertThat(fingerprintData)
.isEqualTo(DATA)
}
internal companion object {
val DATA = FingerprintData(
guid = UUID.randomUUID().toString(),
timestamp = 500
)
}
}
| 0
|
Kotlin
|
0
| 0
|
8e098bee0cdb559c8f11db6a64fc90f06339f850
| 978
|
stripe-android
|
MIT License
|
app/src/main/kotlin/cn/govast/vmusic/ui/fragment/LoginCodeFragment.kt
|
SakurajimaMaii
| 351,469,044
| false
| null |
/*
* Copyright 2022 <NAME> <EMAIL>
*
* 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 cn.govast.vmusic.ui.fragment
import android.os.Bundle
import android.view.View
import androidx.navigation.fragment.findNavController
import cn.govast.vasttools.fragment.VastVbVmFragment
import cn.govast.vasttools.utils.ToastUtils
import cn.govast.vmusic.R
import cn.govast.vmusic.databinding.FragmentLoginCodeBinding
import cn.govast.vmusic.model.net.qrcode.GenQRCodeOption
import cn.govast.vmusic.model.net.qrcode.QRCodeCheckState
import cn.govast.vmusic.network.ServiceCreator
import cn.govast.vmusic.network.service.LoginNetService
import cn.govast.vmusic.sharedpreferences.UserSp
import cn.govast.vmusic.ui.base.UIStateListener
import cn.govast.vmusic.utils.BitmapUtils
import cn.govast.vmusic.viewModel.StartVM
// Author: <NAME>
// Email: <EMAIL>
// Date: 2022/9/29
// Description:
// Documentation:
// Reference:
class LoginCodeFragment : VastVbVmFragment<FragmentLoginCodeBinding, StartVM>(), UIStateListener {
// 获取用户Service
private val mQRCodeService by lazy {
ServiceCreator.create(LoginNetService::class.java)
}
// 获取QRCode key
private var qrCodeKey: String = ""
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
getRequestBuilder()
.suspendWithListener({ mQRCodeService.generateQRCode() }) {
onSuccess = {
getRequestBuilder().suspendWithListener({
qrCodeKey = it.data.unikey
mQRCodeService.getQRCode(
GenQRCodeOption(it.data.unikey, true)
)
}) {
onSuccess = { QRCodeInfo ->
getBinding().loginCode.setImageBitmap(
BitmapUtils.getBitmapFromBase64(
QRCodeInfo.data.qrimg
)
)
getViewModel().checkQRCode(qrCodeKey)
}
onEmpty = {
ToastUtils.showShortMsg("二维码生成失败")
}
}
}
}
initUIState()
}
override fun setVmBySelf(): Boolean {
return true
}
override fun initUIState() {
getViewModel().qrCodeCheck.observe(viewLifecycleOwner) {
if (it.code == QRCodeCheckState.SURE.code) {
UserSp.setCookie(it.cookie)
findNavController().navigate(R.id.mainActivity)
} else {
getViewModel().checkQRCode(qrCodeKey)
}
}
}
override fun initUI() {
}
}
| 2
|
Kotlin
|
0
| 8
|
af1cb8e620cb3e65f9ad5a0d05b240142db2608b
| 3,335
|
Music-Voice
|
Apache License 2.0
|
ktor-server/ktor-server-host-common/nix/src/io/ktor/server/engine/ServerEngineUtilsNix.kt
|
ktorio
| 40,136,600
| false
| null |
/*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.server.engine
import kotlinx.cinterop.*
import platform.posix.*
@OptIn(UnsafeNumber::class)
internal actual val WORKING_DIRECTORY_PATH: String get() = memScoped {
val result = allocArray<ByteVar>(512)
getcwd(result, 512)
result.toKString()
}
| 302
| null |
806
| 9,709
|
9e0eb99aa2a0a6bc095f162328525be1a76edb21
| 400
|
ktor
|
Apache License 2.0
|
joybao-esign-java/src/main/kotlin/com/joybao/esign/Seal.kt
|
MarsCWD
| 144,733,773
| false
|
{"JavaScript": 812625, "Objective-C": 164921, "Java": 40541, "Kotlin": 38548, "C#": 13655, "Vue": 11890, "Python": 1722, "Shell": 120, "CSS": 111}
|
package com.joybao.esign
import DDP.DDPListener
import com.joybao.constants.ProjectConstants
import com.joybao.util.TaskCallBack
import com.timevale.esign.sdk.tech.bean.result.AddSealResult
import com.timevale.esign.sdk.tech.service.factory.SealServiceFactory
import org.slf4j.LoggerFactory
import com.timevale.esign.sdk.tech.bean.seal.SealColor
import com.timevale.esign.sdk.tech.bean.seal.PersonTemplateType
import com.timevale.esign.sdk.tech.bean.seal.OrganizeTemplateType
import esign.utils.constant.type.Color
/**
* Created by MyShe on 2017/5/14.
*/
object Seal {
private val Logger = LoggerFactory.getLogger(Seal::class.java)
private val SEAL = SealServiceFactory.instance()
/**
* 创建公司签章
*/
fun newCompanySeal(data: Map<String, Any>, cb: TaskCallBack) {
val userId = data["mainAccountId"] as String
val accountId = data["accountId"] as String
val type = OrganizeTemplateType.STAR
val color = SealColor.RED
cb.result(SEAL.addTemplateSeal(accountId, type, color, "", ""), userId, accountId)
}
/**
* 添加公司模板签章OK
*/
fun newCompanySealOK(companyId: String, userId: String, accountId: String, res: AddSealResult) {
val params = HashMap<String, String>()
params.put("userId", userId)
params.put("accountId", accountId)
params.put("companyId", companyId)
params.put("sealData", res.sealData)
val methodArgs = arrayOfNulls<Any>(1)
methodArgs[0] = params
ProjectConstants.ddp?.call("esign.company.seal.ok", methodArgs, object : DDPListener() {
override fun onResult(resultFields: MutableMap<String, Any>?) {
super.onResult(resultFields)
Logger.info(resultFields.toString())
}
})
}
/**
* 添加公司模板签章失败
*/
fun newCompanySealNo(userId: String, companyId: String, accountId: String, res: AddSealResult) {
val params = HashMap<String, String>()
params.put("userId", userId)
params.put("accountId", accountId)
params.put("companyId", companyId)
params.put("errCode", res.errCode.toString())
params.put("errMsg", res.msg.toString())
val methodArgs = arrayOfNulls<Any>(1)
methodArgs[0] = params
Logger.info("生成第三方公司签章失败")
ProjectConstants.ddp?.call("esign.company.seal.no", methodArgs, object : DDPListener() {
override fun onResult(resultFields: MutableMap<String, Any>?) {
super.onResult(resultFields)
Logger.info(resultFields.toString())
}
})
}
/**
* 创建签名
*/
fun newSeal(data: Map<String, Any>, cb: TaskCallBack) {
val auditId = data["auditId"] as String
val accountId = data["accountId"] as String
val type = data["templateType"] as String
val color = if (data.containsKey("color")) data["color"] as String else ""
val imgB64 = if (data.containsKey("imgB64")) data["imgB64"] as String else ""
val hText = if (data.containsKey("hText")) data["hText"] as String else ""
val qText = if (data.containsKey("qText")) data["qText"] as String else ""
when (type) {
"CompanySeal" -> signModel(accountId, true, color, hText, qText, auditId, cb)
"PersonSeal" -> signModel(accountId, false, color, hText, qText, auditId, cb)
else -> {
// TODO 获取网络图片并转换成 Base64编码
// val data = Util.getURLImage("http://joybao.oss-cn-hangzhou.aliyuncs.com/wximages/$imgB64")
// Logger.info("获取网络图片的Base64编码Ko")
// createSeal(accountId, data)
}
}
}
/**
* 根据Base64生成个人签名
*/
fun createSeal(devId: String, accountId: String, sealData: String, color: String, auditId: String, cb: TaskCallBack): AddSealResult? {
// 签署文档使用的印章数据,若存在
val data = sealData.substring(sealData.indexOf(',') + 1)
Logger.debug("sign seal data: ${data}")
var sColor: SealColor? = null
for (sealColor in SealColor.values()) {
if (color.equals(sealColor.color().color, ignoreCase = true)) {
sColor = sealColor
break
}
}
return SEAL.addFileSeal(devId, accountId, sealData, sColor);
}
/**
* 创建模板印章
*/
fun signModel(accountId: String, isCompany: Boolean, color: String, hText: String, qText: String, auditId: String, cb: TaskCallBack) {
if (isCompany) {
this.createSealOrganize(accountId, OrganizeTemplateType.STAR, color, hText, qText, auditId, cb)
} else {
this.createSealPersonal(accountId, PersonTemplateType.SQUARE, color, auditId, cb)
}
}
/**
* 创建个人签章
*/
fun createSealPersonal(accountId: String, template: PersonTemplateType, color: String, auditId: String, cb: TaskCallBack) {
var sColor: SealColor? = null
for (sealColor in SealColor.values()) {
if (color.equals(sealColor.color().color, ignoreCase = true)) {
sColor = sealColor
break
}
}
cb.result(SEAL.addTemplateSeal(accountId, template, sColor), auditId)
}
/**
* 创建公司签章
*/
fun createSealOrganize(accountId: String, template: OrganizeTemplateType, color: String, hText: String, qText: String, auditId: String, cb: TaskCallBack) {
var sColor: SealColor? = null
for (sealColor in SealColor.values()) {
if (color.equals(sealColor.color().color, ignoreCase = true)) {
sColor = sealColor
break
}
}
cb.result(SEAL.addTemplateSeal(accountId, template, sColor, hText, qText), auditId)
}
fun newSealOK(sealId: String, auditId: String, res: AddSealResult) {
val params = HashMap<String, String>()
params.put("sealId", sealId)
params.put("auditId", auditId)
params.put("sealData", res.sealData)
Logger.info("签章生成成功 $sealId")
val methodArgs = arrayOfNulls<Any>(1)
methodArgs[0] = params
ProjectConstants.ddp?.call("esign.seal.ok", methodArgs, object : DDPListener() {
override fun onResult(resultFields: MutableMap<String, Any>?) {
super.onResult(resultFields)
Logger.info(resultFields.toString())
}
})
}
fun newSealNo(sealId: String, auditId: String, res: AddSealResult) {
val params = HashMap<String, String>()
params.put("sealId", sealId)
params.put("errCode", res.errCode.toString())
params.put("errMsg", res.msg.toString())
Logger.info("签章生成失败 $sealId")
val methodArgs = arrayOfNulls<Any>(1)
methodArgs[0] = params
ProjectConstants.ddp?.call("esign.seal.no", methodArgs, object : DDPListener() {
override fun onResult(resultFields: MutableMap<String, Any>?) {
super.onResult(resultFields)
Logger.info(resultFields.toString())
}
})
}
}
| 0
|
JavaScript
|
0
| 0
|
6dae7021ecd3e3c51f250cdcb4491d1fd90bbbcc
| 7,126
|
joybao
|
Apache License 2.0
|
app/src/main/java/com/example/android_study/android/ipc/IPCMainActivity.kt
|
RhythmCoderZZF
| 281,057,053
| false
| null |
package com.example.android_study.android.ipc
import android.os.Bundle
import com.example.android_study.R
import com.example.android_study._base.BaseActivity
import com.example.android_study._base.adapter.Entry
import com.example.android_study.android.ipc.binder.IPCAIDLActivity
import com.example.android_study.android.ipc.messager.IPCMessengerActivity
import kotlinx.android.synthetic.main.activity_rv.*
class IPCMainActivity : BaseActivity() {
override fun getLayoutId()= R.layout.activity_rv
override fun initViewAndData(savedInstanceState: Bundle?) {
setRecyclerView(rv, listOf(
Entry("1 AIDL", IPCAIDLActivity::class.java,"一个aidl实现的binder通信机制,本app属于Service,请启动client app使用"),
Entry("2 Messenger", IPCMessengerActivity::class.java,"Messenger本质是封装Binder和Handler"),
))
}
}
| 0
|
Kotlin
|
0
| 0
|
b569adcacfdba5ea6b4c323454c3c5130a1b4763
| 838
|
AndroidStudy
|
Apache License 2.0
|
app/src/main/java/com/puutaro/commandclick/fragment_lib/command_index_fragment/list_view_lib/filter/TextChangedListenerAdder.kt
|
puutaro
| 596,852,758
| false
| null |
package com.puutaro.commandclick.fragment_lib.command_index_fragment.list_view_lib.filter
import android.text.Editable
import android.text.InputFilter
import android.text.TextWatcher
import android.widget.ArrayAdapter
import androidx.fragment.app.activityViewModels
import com.puutaro.commandclick.common.variable.ReadLines
import com.puutaro.commandclick.fragment.CommandIndexFragment
import com.puutaro.commandclick.fragment_lib.command_index_fragment.common.CommandListManager
import com.puutaro.commandclick.fragment_lib.command_index_fragment.list_view_lib.internet_button.GoogleSuggest
import com.puutaro.commandclick.view_model.activity.TerminalViewModel
class TextChangedListenerAdder {
companion object {
fun add (
cmdIndexCommandIndexFragment: CommandIndexFragment,
filteringCmdStrList: List<String>,
cmdListAdapter: ArrayAdapter<String>
){
val context = cmdIndexCommandIndexFragment.context
val terminalViewModel: TerminalViewModel by cmdIndexCommandIndexFragment.activityViewModels()
val binding = cmdIndexCommandIndexFragment.binding
val cmdSearchEditText = binding.cmdSearchEditText
val cmdListView = binding.cmdList
val googleSuggest = GoogleSuggest(
cmdIndexCommandIndexFragment,
cmdSearchEditText
)
val filter = InputFilter { source, _, _, _, _, _ ->
if (source.contains(" ")) " " else source
}
if (filter !in cmdSearchEditText.filters) cmdSearchEditText.filters = arrayOf(*cmdSearchEditText.filters, filter)
cmdSearchEditText.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
if(!cmdSearchEditText.hasFocus()) return
if(
terminalViewModel.readlinesNum == ReadLines.SHORTH
) {
cmdSearchEditText.threshold = 100000;
return
}
if(!cmdIndexCommandIndexFragment.WebSearchSwitch) return
googleSuggest.set(cmdSearchEditText.text)
}
override fun afterTextChanged(s: Editable?) {
if(!cmdSearchEditText.hasFocus()) return
if(
!cmdIndexCommandIndexFragment.WebSearchSwitch
) {
val listener = context as? CommandIndexFragment.OnFilterWebViewListener
listener?.onFilterWebView(
s.toString(),
)
return
}
if(
terminalViewModel.readlinesNum != ReadLines.SHORTH
) return
val filteredCmdStrList = filteringCmdStrList.filter {
Regex(
s.toString().lowercase()
).containsMatchIn(
it.lowercase()
)
}
CommandListManager.execListUpdateByEditText(
filteredCmdStrList,
cmdListAdapter,
cmdListView
)
}
})
}
}
}
| 2
|
Kotlin
|
2
| 44
|
b57ff32350e2e5fe7e7d69b959702d3a3b2c83d0
| 3,579
|
CommandClick
|
MIT License
|
app/src/main/kotlin/com/xiaocydx/sample/viewpager2/shared/FooCategoryViewModel.kt
|
xiaocydx
| 460,257,515
| false
| null |
package com.xiaocydx.sample.viewpager2.shared
import androidx.lifecycle.ViewModel
import com.xiaocydx.accompanist.viewmodel.RetainedViewModels
import com.xiaocydx.accompanist.viewmodel.getOrPut
import com.xiaocydx.sample.common.FooListViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
/**
* @author xcc
* @date 2022/7/12
*/
class FooCategoryViewModel : ViewModel() {
private val viewModels = RetainedViewModels<FooListViewModel>(host = this)
private val _state = MutableStateFlow(FooCategoryState(
list = (1L..10L).map { FooCategory(id = it) }
))
val state = _state.asStateFlow()
fun getFooViewModel(categoryId: Long): FooListViewModel {
return viewModels.getOrPut(categoryId.toString()) { FooListViewModel() }
}
fun addItemToLast() = updateState {
val id = if (list.isEmpty()) 1 else list.maxOf { it.id } + 1
copy(list = list + FooCategory(id = id))
}
fun removeCurrentItem() = updateState {
val item = list.getOrNull(currentItem) ?: return
viewModels.remove(item.id.toString())
var newItem = currentItem
if (newItem == list.lastIndex) {
newItem = (newItem - 1).coerceAtLeast(0)
}
val list = list.toMutableList().apply { removeAt(currentItem) }
copy(list = list, currentItem = newItem, pendingItem = newItem)
}
fun moveCurrentItemToFirst() = updateState {
val newItem = 0
if (currentItem == newItem) return
val list = list.toMutableList()
list.add(newItem, list.removeAt(currentItem))
copy(list = list, currentItem = newItem, pendingItem = newItem)
}
fun setCurrentItem(currentItem: Int) = updateState {
if (this.currentItem == currentItem) return
copy(currentItem = currentItem)
}
fun consumePendingItem() = updateState {
if (pendingItem == NO_ITEM) return
copy(pendingItem = NO_ITEM)
}
private inline fun updateState(newState: FooCategoryState.() -> FooCategoryState) {
_state.value = newState(_state.value)
}
}
private const val NO_ITEM = -1
data class FooCategoryState(
val list: List<FooCategory>,
val currentItem: Int = 0,
val pendingItem: Int = NO_ITEM
)
data class FooCategory(
val id: Long,
val title: String = "LIST-${id}"
)
val FooCategoryState.hasPendingItem: Boolean
get() = pendingItem != NO_ITEM
| 0
| null |
0
| 9
|
cee300e1e33e5a5cd877ad9c64e46e3325cce37f
| 2,455
|
CXRV
|
Apache License 2.0
|
adaptive-ui/src/commonMain/kotlin/fun/adaptive/ui/fragment/layout/AbstractContainer.kt
|
spxbhuhb
| 788,711,010
| false
|
{"Kotlin": 2104845, "Java": 23090, "HTML": 7707, "JavaScript": 3880, "Shell": 687}
|
/*
* Copyright © 2020-2024, Simplexion, Hungary and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package hu.simplexion.adaptive.ui.common.fragment.layout
import hu.simplexion.adaptive.foundation.AdaptiveFragment
import hu.simplexion.adaptive.foundation.fragment.AdaptiveAnonymous
import hu.simplexion.adaptive.foundation.internal.BoundFragmentFactory
import hu.simplexion.adaptive.ui.common.AbstractCommonAdapter
import hu.simplexion.adaptive.ui.common.AbstractCommonFragment
import hu.simplexion.adaptive.utility.alsoIfInstance
import hu.simplexion.adaptive.utility.checkIfInstance
/**
* Two uses: layouts and loop/select containers.
*/
abstract class AbstractContainer<RT, CRT : RT>(
adapter: AbstractCommonAdapter<RT, CRT>,
parent: AdaptiveFragment?,
declarationIndex: Int,
instructionsIndex: Int,
stateSize: Int
) : AbstractCommonFragment<RT>(
adapter, parent, declarationIndex, instructionsIndex, stateSize
) {
val unbound
get() = Double.POSITIVE_INFINITY
@Suppress("LeakingThis") // instance construction should not perform any actions
override val receiver: CRT = adapter.makeContainerReceiver(this)
override val uiAdapter = adapter
val layoutItems = mutableListOf<AbstractCommonFragment<RT>>() // Items to consider during layout.
val directItems = mutableListOf<AbstractCommonFragment<RT>>() // Items to update directly, see class docs.
val structuralItems = mutableListOf<AbstractCommonFragment<RT>>() // Items to update directly, see class docs.
val content: BoundFragmentFactory
get() = state[state.size - 1].checkIfInstance()
override fun genBuild(parent: AdaptiveFragment, declarationIndex: Int): AdaptiveFragment? {
if (declarationIndex != 0) invalidIndex(declarationIndex)
// FIXME I think this anonymous fragment is superfluous
return AdaptiveAnonymous(this, declarationIndex, 0, content).apply { create() }
}
/**
* An optimization to remove the whole subtree of fragments from the actual UI at once.
* See [AbstractCommonAdapter.actualBatchOwner].
*/
override fun unmount() {
if (uiAdapter.actualBatchOwner != null) {
super.unmount()
return
}
try {
uiAdapter.actualBatchOwner = this.renderData.layoutFragment
super.unmount()
} finally {
uiAdapter.actualBatchOwner = null
}
}
override fun addActual(fragment: AdaptiveFragment, direct: Boolean?) {
if (trace) trace("addActual", "item=$fragment, direct=$direct")
fragment.alsoIfInstance<AbstractCommonFragment<RT>> { itemFragment ->
itemFragment.renderData.layoutFragment = this
when (direct) {
true -> {
layoutItems += itemFragment
directItems += itemFragment
uiAdapter.addActual(receiver, itemFragment.receiver)
}
false -> {
layoutItems += itemFragment
}
null -> {
structuralItems += itemFragment
uiAdapter.addActual(receiver, itemFragment.receiver)
}
}
if (isMounted) {
// FIXME layout with late additions may affect higher level layouts
computeLayout(renderData.finalWidth, renderData.finalHeight)
}
}
}
override fun removeActual(fragment: AdaptiveFragment, direct: Boolean?) {
if (trace) trace("removeActual", "item=$fragment, direct=$direct")
fragment.alsoIfInstance<AbstractCommonFragment<RT>> { itemFragment ->
// when in a batch, everything will be removed at once
if (uiAdapter.actualBatchOwner != null && uiAdapter.actualBatchOwner != itemFragment.renderData.layoutFragment) return
itemFragment.renderData.layoutFragment = null
when (direct) {
true -> {
layoutItems.removeAt(layoutItems.indexOfFirst { it.id == fragment.id })
directItems.removeAt(directItems.indexOfFirst { it.id == fragment.id })
uiAdapter.removeActual(itemFragment.receiver)
}
false -> {
layoutItems.removeAt(layoutItems.indexOfFirst { it.id == fragment.id })
}
null -> {
structuralItems.removeAt(structuralItems.indexOfFirst { it.id == fragment.id })
uiAdapter.removeActual(itemFragment.receiver)
}
}
if (isMounted) {// FIXME layout with late removals may affect higher level layouts
computeLayout(renderData.finalWidth, renderData.finalHeight)
}
}
}
fun placeStructural() {
for (item in structuralItems) {
item.computeLayout(renderData.finalWidth, renderData.finalHeight)
item.placeLayout(0.0, 0.0)
}
}
abstract fun layoutChange(fragment: AbstractCommonFragment<*>)
}
| 35
|
Kotlin
|
0
| 3
|
a423e127a406395002bbc663bb2fea6fcad749f1
| 5,153
|
adaptive
|
Apache License 2.0
|
grazel-gradle-plugin/src/test/kotlin/com/grab/grazel/gradle/variant/VariantTestProject.kt
|
grab
| 379,151,190
| false
| null |
package com.grab.grazel.gradle.variant
import com.android.build.gradle.AppExtension
import com.grab.grazel.gradle.ANDROID_APPLICATION_PLUGIN
import com.grab.grazel.gradle.JAVA_LIBRARY_PLUGIN
import com.grab.grazel.gradle.KOTLIN_ANDROID_PLUGIN
import com.grab.grazel.gradle.KOTLIN_KAPT
import com.grab.grazel.gradle.KOTLIN_PLUGIN
import com.grab.grazel.util.doEvaluate
import org.gradle.api.Project
import org.gradle.kotlin.dsl.configure
import org.gradle.kotlin.dsl.dependencies
import org.gradle.kotlin.dsl.repositories
const val TEST_FLAVOR_DIMENSION = "service"
const val TEST_FLAVOR_FREE = "paid"
const val TEST_FLAVOR_PAID = "free"
const val TEST_DEBUG = "debug"
const val TEST_RELEASE = "release"
fun setupAndroidVariantProject(androidProject: Project) {
with(androidProject) {
with(plugins) {
apply(ANDROID_APPLICATION_PLUGIN)
apply(KOTLIN_ANDROID_PLUGIN)
apply(KOTLIN_KAPT)
}
repositories {
google()
mavenCentral()
}
configure<AppExtension> {
defaultConfig {
compileSdkVersion(32)
}
flavorDimensions(TEST_FLAVOR_DIMENSION)
productFlavors {
create("paid") {
dimension = TEST_FLAVOR_DIMENSION
}
create("free") {
dimension = TEST_FLAVOR_DIMENSION
}
}
dataBinding.isEnabled = true
}
dependencies {
add(
"implementation",
"androidx.appcompat:appcompat:1.5.1"
)
add(
"freeImplementation",
"androidx.constraintlayout:constraintlayout:2.1.3"
)
add(
"paidImplementation",
"androidx.constraintlayout:constraintlayout:2.1.2"
)
add(
"kapt",
"com.google.dagger:dagger:2.37"
)
}
}
androidProject.doEvaluate()
}
fun setupJvmVariantProject(project: Project) {
with(project) {
with(plugins) {
apply(JAVA_LIBRARY_PLUGIN)
apply(KOTLIN_PLUGIN)
apply(KOTLIN_KAPT)
}
repositories {
google()
mavenCentral()
}
dependencies {
add(
"implementation",
"com.google.dagger:dagger:2.37"
)
add(
"kapt",
"com.google.dagger:dagger:2.37"
)
}
}
project.doEvaluate()
}
| 9
| null |
21
| 274
|
6d44b7fc7d5210cc4e4211cfd002547a3126124c
| 2,628
|
grazel
|
Apache License 2.0
|
app/src/main/java/com/example/liziweather/ui/weather/WeatherViewModel.kt
|
freezeailis
| 631,947,522
| false
| null |
package com.example.liziweather.ui.weather
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import androidx.lifecycle.ViewModel
import com.example.liziweather.logic.Repository
import com.example.liziweather.logic.model.Location
import java.security.KeyStore.LoadStoreParameter
import kotlin.math.ln
class WeatherViewModel: ViewModel() {
// 用于观察location的变化
private val locationLiveData = MutableLiveData<Location>()
/**
* 根据 getWeatherInfo 传入的 location 所对应的经纬度坐标请求当日天气信息
*@author aris
*@time 2023/6/20 15:10
*/
val weatherInfo = Transformations.switchMap(locationLiveData){
Repository.getWeatherInfo(it.lng, it.lat)
}
fun getWeatherInfo(location: Location){
locationLiveData.value = Location(location.lng, location.lat)
}
}
| 0
|
Kotlin
|
0
| 0
|
ef42205e8422f47e8c4220c8a0e2f8a730b6221e
| 827
|
LiziWeather
|
Apache License 2.0
|
common/src/main/kotlin/ru/memebattle/common/dto/AuthenticationResponseDto.kt
|
Onotole1
| 242,397,687
| false
| null |
package ru.memebattle.common.dto
data class AuthenticationResponseDto(val token: String)
| 0
|
Kotlin
|
0
| 3
|
fd2b1e526af65649b734810ef3bcdb9d4ea7539a
| 90
|
memebattle-template
|
Apache License 2.0
|
common/src/main/kotlin/ru/memebattle/common/dto/AuthenticationResponseDto.kt
|
Onotole1
| 242,397,687
| false
| null |
package ru.memebattle.common.dto
data class AuthenticationResponseDto(val token: String)
| 0
|
Kotlin
|
0
| 3
|
fd2b1e526af65649b734810ef3bcdb9d4ea7539a
| 90
|
memebattle-template
|
Apache License 2.0
|
theme-m3/schedules/schedules-feature/src/main/kotlin/org/gdglille/devfest/android/theme/m3/schedules/feature/ScheduleListOrientable.kt
|
GerardPaligot
| 444,230,272
| false
|
{"Kotlin": 653807, "Swift": 114556, "Shell": 1148, "Dockerfile": 369}
|
package org.gdglille.devfest.android.theme.m3.schedules.feature
import android.content.res.Configuration
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.PagerState
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalConfiguration
import kotlinx.collections.immutable.ImmutableList
import org.gdglille.devfest.models.ui.AgendaUi
import org.gdglille.devfest.models.ui.TalkItemUi
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun ScheduleListOrientable(
agendas: ImmutableList<AgendaUi>,
pagerState: PagerState,
onTalkClicked: (id: String) -> Unit,
onFavoriteClicked: (TalkItemUi) -> Unit,
modifier: Modifier = Modifier,
isLoading: Boolean = false,
) {
val orientation = LocalConfiguration.current
HorizontalPager(
state = pagerState,
modifier = Modifier.fillMaxSize(),
verticalAlignment = Alignment.Top
) { page ->
if (orientation.orientation == Configuration.ORIENTATION_LANDSCAPE) {
ScheduleListHorizontal(
agenda = agendas[page],
modifier = modifier,
onTalkClicked = onTalkClicked,
onFavoriteClicked = onFavoriteClicked,
isLoading = isLoading
)
} else {
ScheduleListVertical(
agenda = agendas[page],
modifier = modifier,
onTalkClicked = onTalkClicked,
onFavoriteClicked = onFavoriteClicked,
isLoading = isLoading
)
}
}
}
| 11
|
Kotlin
|
6
| 127
|
821d903836d23effe8830f16f646898a88cc7406
| 1,797
|
conferences4hall
|
Apache License 2.0
|
src/main/services/challenge/GetChainsForChallengeService.kt
|
ncent-archive
| 150,326,270
| false
|
{"Kotlin": 352866, "JavaScript": 7544, "Makefile": 563, "Shell": 222}
|
package main.services.challenge
import framework.models.idValue
import kotlinserverless.framework.services.SOAResult
import kotlinserverless.framework.services.SOAResultType
import main.daos.*
import main.helpers.ChallengeHelper
import main.services.transaction.GetProvidenceChainService
import main.services.transaction.GetTransactionsService
import org.jetbrains.exposed.sql.select
object GetChainsForChallengeService {
fun execute(caller: UserAccount, challengeId: Int): SOAResult<Challenger<UserAccount>> {
val challenge = ChallengeHelper.findChallengeById(challengeId)
val transaction = getOriginatingTransaction(challenge)
if(transaction == null)
return SOAResult(SOAResultType.FAILURE, "Failed to find a correct transaction for this challenge.")
val challengers = getChildrenGraph(transaction)
return SOAResult(SOAResultType.SUCCESS,null, challengers)
}
private fun getChildrenGraph(currentTransaction: Transaction): Challenger<UserAccount> {
var children = GetProvidenceChainService.getChildren(currentTransaction.id).toMutableList()
var childrenGraph = mutableListOf<Challenger<UserAccount>>()
while(children.any()) {
val currentChild = children.removeAt(0)
val currentChildChildrenGraph = getChildrenGraph(currentChild)
childrenGraph.add(currentChildChildrenGraph)
}
return Challenger(getUserAccountByPublicKey(currentTransaction.to!!), childrenGraph)
}
private fun getOriginatingTransaction(challenge: Challenge): Transaction? {
val transactionsListResult = GetTransactionsService.execute(
from = challenge.cryptoKeyPair.publicKey,
to = challenge.challengeSettings.admin.cryptoKeyPair.publicKey,
previousTxId = null,
actionNamespace = ActionNamespace(
type = ActionType.SHARE,
data = challenge.idValue,
dataType = Challenge::class.simpleName!!
)
)
if(transactionsListResult?.data?.transactions?.count() == 1)
return transactionsListResult.data!!.transactions.first()
return null
}
private fun getUserAccountByPublicKey(publicKey: String): UserAccount {
val query = UserAccounts
.innerJoin(CryptoKeyPairs)
.select {
CryptoKeyPairs.publicKey eq publicKey
}
return UserAccount.wrapRows(query).toList().first()
}
}
| 16
|
Kotlin
|
2
| 2
|
802160f3332c4b6d63d4219067848e38a689c48b
| 2,510
|
ncent-api-v2
|
MIT License
|
module/notification/src/main/java/me/pxq/eyepetizer/notification/ui/PrivateFragment.kt
|
drkingwater
| 279,571,591
| false
| null |
package me.pxq.eyepetizer.notification.ui
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import me.pxq.common.R
import me.pxq.common.ui.BaseFragment
/**
* Description: 通知-互动Fragment
* Author : pxq
* Date : 2020/8/23 4:31 PM
*/
class InteractFragment : BaseFragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_no_account, container, false)
}
override fun fetchData() = Unit
companion object {
@JvmStatic
fun newInstance() = InteractFragment()
}
}
| 0
| null |
4
| 15
|
0feb6ce3cbd9d396ef79d7bd4e6da60f11a13f2c
| 713
|
eyepetizer-kotlin
|
Apache License 2.0
|
app/src/main/java/me/capcom/smsgateway/modules/messages/MessagesService.kt
|
capcom6
| 503,827,141
| false
| null |
package me.capcom.smsgateway.modules.messages
import android.Manifest
import android.app.Activity
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.telephony.SmsManager
import android.telephony.SubscriptionManager
import android.telephony.TelephonyManager
import androidx.core.app.ActivityCompat
import com.aventrix.jnanoid.jnanoid.NanoIdUtils
import me.capcom.smsgateway.data.dao.MessageDao
import me.capcom.smsgateway.data.entities.Message
import me.capcom.smsgateway.data.entities.MessageRecipient
import me.capcom.smsgateway.data.entities.MessageWithRecipients
import me.capcom.smsgateway.helpers.PhoneHelper
import me.capcom.smsgateway.modules.encryption.EncryptionService
import me.capcom.smsgateway.modules.events.EventBus
import me.capcom.smsgateway.receivers.EventsReceiver
class MessagesService(
private val context: Context,
private val dao: MessageDao, // todo: use MessagesRepository
private val encryptionService: EncryptionService,
) {
val events = EventBus()
private val countryCode: String? =
(context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager).networkCountryIso
suspend fun sendMessage(
id: String?,
text: String,
recipients: List<String>,
source: Message.Source,
simNumber: Int?,
withDeliveryReport: Boolean?,
isEncrypted: Boolean,
): MessageWithRecipients {
val id = id ?: NanoIdUtils.randomNanoId()
val message = MessageWithRecipients(
Message(id, text, source, isEncrypted),
recipients.map {
MessageRecipient(
id,
it,
Message.State.Pending
)
},
)
dao.insert(message)
if (message.state != Message.State.Pending) {
updateState(id, null, message.state)
return message
}
try {
sendSMS(
id,
text,
message.recipients.filter { it.state == Message.State.Pending }
.map { it.phoneNumber },
simNumber,
withDeliveryReport ?: true,
isEncrypted
)
} catch (e: Exception) {
e.printStackTrace()
updateState(id, null, Message.State.Failed, "Sending: " + e.message)
return requireNotNull(getMessage(id))
}
return message
}
fun getMessage(id: String): MessageWithRecipients? {
val message = dao.get(id)
?: return null
val state = message.state
if (state == message.message.state) {
return message
}
if (state != message.message.state) {
dao.updateMessageState(message.message.id, state)
}
return dao.get(id)
}
suspend fun processStateIntent(intent: Intent, resultCode: Int) {
val state = when (intent.action) {
EventsReceiver.ACTION_SENT -> when (resultCode) {
Activity.RESULT_OK -> Message.State.Sent
else -> Message.State.Failed
}
EventsReceiver.ACTION_DELIVERED -> Message.State.Delivered
else -> return
}
val error = when (resultCode) {
Activity.RESULT_OK -> null
else -> "Send result: " + this.resultToErrorMessage(resultCode)
}
val (id, phone) = intent.dataString?.split("|", limit = 2) ?: return
updateState(id, phone, state, error)
}
private suspend fun updateState(
id: String,
phone: String?,
state: Message.State,
error: String? = null
) {
phone?.let {
dao.updateRecipientState(id, it, state, error)
}
?: kotlin.run {
dao.updateRecipientsState(id, state, error)
}
val msg = requireNotNull(getMessage(id))
events.emitEvent(
MessageStateChangedEvent(
id,
msg.state,
msg.message.source,
msg.recipients.map {
MessageStateChangedEvent.Recipient(
it.phoneNumber,
it.state,
it.error
)
}
)
)
}
private suspend fun sendSMS(
id: String,
message: String,
recipients: List<String>,
simNumber: Int?,
withDeliveryReport: Boolean,
isEncrypted: Boolean
) {
val smsManager: SmsManager = getSmsManager(simNumber)
val message = when (isEncrypted) {
true -> encryptionService.decrypt(message)
false -> message
}
recipients.forEach {
val sentIntent = PendingIntent.getBroadcast(
context,
0,
Intent(
EventsReceiver.ACTION_SENT,
Uri.parse("$id|$it"),
context,
EventsReceiver::class.java
),
PendingIntent.FLAG_IMMUTABLE
)
val deliveredIntent = when (withDeliveryReport) {
false -> null
true -> PendingIntent.getBroadcast(
context,
0,
Intent(
EventsReceiver.ACTION_DELIVERED,
Uri.parse("$id|$it"),
context,
EventsReceiver::class.java
),
PendingIntent.FLAG_IMMUTABLE
)
}
try {
val parts = smsManager.divideMessage(message)
val phoneNumber = when (isEncrypted) {
true -> encryptionService.decrypt(it)
false -> it
}
val normalizedPhoneNumber =
PhoneHelper.filterPhoneNumber(phoneNumber, countryCode ?: "RU")
if (parts.size > 1) {
smsManager.sendMultipartTextMessage(
normalizedPhoneNumber,
null,
parts,
ArrayList(parts.map { sentIntent }),
deliveredIntent?.let { ArrayList(parts.map { deliveredIntent }) }
)
} else {
smsManager.sendTextMessage(
normalizedPhoneNumber,
null,
message,
sentIntent,
deliveredIntent
)
}
updateState(id, it, Message.State.Processed)
} catch (th: Throwable) {
th.printStackTrace()
updateState(id, it, Message.State.Failed, "Sending: " + th.message)
}
}
}
private fun getSmsManager(simNumber: Int?): SmsManager {
return if (simNumber != null) {
if (ActivityCompat.checkSelfPermission(
context,
Manifest.permission.READ_PHONE_STATE
) != PackageManager.PERMISSION_GRANTED
) {
throw UnsupportedOperationException("SIM selection requires READ_PHONE_STATE permission")
}
val subscriptionManager: SubscriptionManager = when {
Build.VERSION.SDK_INT < 22 -> throw UnsupportedOperationException("SIM selection available from API 22")
Build.VERSION.SDK_INT < 31 -> SubscriptionManager.from(context)
else -> context.getSystemService(SubscriptionManager::class.java)
}
if (subscriptionManager.activeSubscriptionInfoCount <= simNumber) {
throw UnsupportedOperationException("SIM ${simNumber + 1} not found")
}
subscriptionManager.activeSubscriptionInfoList.find {
it.simSlotIndex == simNumber
}?.let {
if (Build.VERSION.SDK_INT < 31) {
SmsManager.getSmsManagerForSubscriptionId(it.subscriptionId)
} else {
context.getSystemService(SmsManager::class.java)
.createForSubscriptionId(it.subscriptionId)
}
} ?: throw UnsupportedOperationException("SIM ${simNumber + 1} not found")
} else {
if (Build.VERSION.SDK_INT < 31) {
SmsManager.getDefault()
} else {
context.getSystemService(SmsManager::class.java)
}
}
}
private fun resultToErrorMessage(resultCode: Int): String {
return when (resultCode) {
SmsManager.RESULT_ERROR_GENERIC_FAILURE -> "RESULT_ERROR_GENERIC_FAILURE"
SmsManager.RESULT_ERROR_RADIO_OFF -> "RESULT_ERROR_RADIO_OFF"
SmsManager.RESULT_ERROR_NULL_PDU -> "RESULT_ERROR_NULL_PDU"
SmsManager.RESULT_ERROR_NO_SERVICE -> "RESULT_ERROR_NO_SERVICE"
SmsManager.RESULT_ERROR_LIMIT_EXCEEDED -> "RESULT_ERROR_LIMIT_EXCEEDED"
SmsManager.RESULT_ERROR_FDN_CHECK_FAILURE -> "RESULT_ERROR_FDN_CHECK_FAILURE"
SmsManager.RESULT_ERROR_SHORT_CODE_NOT_ALLOWED -> "RESULT_ERROR_SHORT_CODE_NOT_ALLOWED"
SmsManager.RESULT_ERROR_SHORT_CODE_NEVER_ALLOWED -> "RESULT_ERROR_SHORT_CODE_NEVER_ALLOWED"
SmsManager.RESULT_RADIO_NOT_AVAILABLE -> "RESULT_RADIO_NOT_AVAILABLE"
SmsManager.RESULT_NETWORK_REJECT -> "RESULT_NETWORK_REJECT"
SmsManager.RESULT_INVALID_ARGUMENTS -> "RESULT_INVALID_ARGUMENTS"
SmsManager.RESULT_INVALID_STATE -> "RESULT_INVALID_STATE"
SmsManager.RESULT_NO_MEMORY -> "RESULT_NO_MEMORY"
SmsManager.RESULT_INVALID_SMS_FORMAT -> "RESULT_INVALID_SMS_FORMAT"
SmsManager.RESULT_SYSTEM_ERROR -> "RESULT_SYSTEM_ERROR"
SmsManager.RESULT_MODEM_ERROR -> "RESULT_MODEM_ERROR"
SmsManager.RESULT_NETWORK_ERROR -> "RESULT_NETWORK_ERROR"
SmsManager.RESULT_ENCODING_ERROR -> "RESULT_ENCODING_ERROR"
SmsManager.RESULT_INVALID_SMSC_ADDRESS -> "RESULT_INVALID_SMSC_ADDRESS"
SmsManager.RESULT_OPERATION_NOT_ALLOWED -> "RESULT_OPERATION_NOT_ALLOWED"
SmsManager.RESULT_INTERNAL_ERROR -> "RESULT_INTERNAL_ERROR"
SmsManager.RESULT_NO_RESOURCES -> "RESULT_NO_RESOURCES"
SmsManager.RESULT_CANCELLED -> "RESULT_CANCELLED"
SmsManager.RESULT_REQUEST_NOT_SUPPORTED -> "RESULT_REQUEST_NOT_SUPPORTED"
SmsManager.RESULT_NO_BLUETOOTH_SERVICE -> "RESULT_NO_BLUETOOTH_SERVICE"
SmsManager.RESULT_INVALID_BLUETOOTH_ADDRESS -> "RESULT_INVALID_BLUETOOTH_ADDRESS"
SmsManager.RESULT_BLUETOOTH_DISCONNECTED -> "RESULT_BLUETOOTH_DISCONNECTED"
SmsManager.RESULT_UNEXPECTED_EVENT_STOP_SENDING -> "RESULT_UNEXPECTED_EVENT_STOP_SENDING"
SmsManager.RESULT_SMS_BLOCKED_DURING_EMERGENCY -> "RESULT_SMS_BLOCKED_DURING_EMERGENCY"
SmsManager.RESULT_SMS_SEND_RETRY_FAILED -> "RESULT_SMS_SEND_RETRY_FAILED"
SmsManager.RESULT_REMOTE_EXCEPTION -> "RESULT_REMOTE_EXCEPTION"
SmsManager.RESULT_NO_DEFAULT_SMS_APP -> "RESULT_NO_DEFAULT_SMS_APP"
SmsManager.RESULT_RIL_RADIO_NOT_AVAILABLE -> "RESULT_RIL_RADIO_NOT_AVAILABLE"
SmsManager.RESULT_RIL_SMS_SEND_FAIL_RETRY -> "RESULT_RIL_SMS_SEND_FAIL_RETRY"
SmsManager.RESULT_RIL_NETWORK_REJECT -> "RESULT_RIL_NETWORK_REJECT"
SmsManager.RESULT_RIL_INVALID_STATE -> "RESULT_RIL_INVALID_STATE"
SmsManager.RESULT_RIL_INVALID_ARGUMENTS -> "RESULT_RIL_INVALID_ARGUMENTS"
SmsManager.RESULT_RIL_NO_MEMORY -> "RESULT_RIL_NO_MEMORY"
SmsManager.RESULT_RIL_REQUEST_RATE_LIMITED -> "RESULT_RIL_REQUEST_RATE_LIMITED"
SmsManager.RESULT_RIL_INVALID_SMS_FORMAT -> "RESULT_RIL_INVALID_SMS_FORMAT"
SmsManager.RESULT_RIL_SYSTEM_ERR -> "RESULT_RIL_SYSTEM_ERR"
SmsManager.RESULT_RIL_ENCODING_ERR -> "RESULT_RIL_ENCODING_ERR"
SmsManager.RESULT_RIL_INVALID_SMSC_ADDRESS -> "RESULT_RIL_INVALID_SMSC_ADDRESS"
SmsManager.RESULT_RIL_MODEM_ERR -> "RESULT_RIL_MODEM_ERR"
SmsManager.RESULT_RIL_NETWORK_ERR -> "RESULT_RIL_NETWORK_ERR"
SmsManager.RESULT_RIL_INTERNAL_ERR -> "RESULT_RIL_INTERNAL_ERR"
SmsManager.RESULT_RIL_REQUEST_NOT_SUPPORTED -> "RESULT_RIL_REQUEST_NOT_SUPPORTED"
SmsManager.RESULT_RIL_INVALID_MODEM_STATE -> "RESULT_RIL_INVALID_MODEM_STATE"
SmsManager.RESULT_RIL_NETWORK_NOT_READY -> "RESULT_RIL_NETWORK_NOT_READY"
SmsManager.RESULT_RIL_OPERATION_NOT_ALLOWED -> "RESULT_RIL_OPERATION_NOT_ALLOWED"
SmsManager.RESULT_RIL_NO_RESOURCES -> "RESULT_RIL_NO_RESOURCES"
SmsManager.RESULT_RIL_CANCELLED -> "RESULT_RIL_CANCELLED"
SmsManager.RESULT_RIL_SIM_ABSENT -> "RESULT_RIL_SIM_ABSENT"
SmsManager.RESULT_RIL_SIMULTANEOUS_SMS_AND_CALL_NOT_ALLOWED -> "RESULT_RIL_SIMULTANEOUS_SMS_AND_CALL_NOT_ALLOWED"
SmsManager.RESULT_RIL_ACCESS_BARRED -> "RESULT_RIL_ACCESS_BARRED"
SmsManager.RESULT_RIL_BLOCKED_DUE_TO_CALL -> "RESULT_RIL_BLOCKED_DUE_TO_CALL"
else -> "UNKNOWN"
}
}
}
| 5
| null |
8
| 39
|
1d992f096fdfcc060855c71e4bedf9b684613ca1
| 13,588
|
android-sms-gateway
|
Apache License 2.0
|
library/src/main/java/com/github/pelmenstar1/rangecalendar/CompatDateFormatter.kt
|
pelmenstar1
| 454,918,220
| false
| null |
package com.github.pelmenstar1.rangecalendar
import android.content.Context
import android.os.Build
import com.github.pelmenstar1.rangecalendar.utils.getLocaleCompat
import java.text.FieldPosition
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
internal class CompatDateFormatter(context: Context, private val pattern: String) {
// If API >= 24, the type should be android.icu.text.SimpleDateFormat,
// otherwise java.text.SimpleDateFormat.
private var dateFormatter: Any? = null
private val calendarOrDate: Any = if (Build.VERSION.SDK_INT >= 24) {
android.icu.util.Calendar.getInstance()
} else {
Date()
}
private val stringBuffer = StringBuffer(32)
init {
refreshFormatter(context.getLocaleCompat())
}
private fun refreshFormatter(currentLocale: Locale) {
// Find the best format if we can
val bestFormat = if (Build.VERSION.SDK_INT >= 18) {
android.text.format.DateFormat.getBestDateTimePattern(currentLocale, pattern)
} else {
pattern
}
dateFormatter = if (Build.VERSION.SDK_INT >= 24) {
android.icu.text.SimpleDateFormat(bestFormat, currentLocale)
} else {
SimpleDateFormat(bestFormat, currentLocale)
}
}
fun onLocaleChanged(newLocale: Locale) {
refreshFormatter(newLocale)
}
fun format(date: PackedDate): String {
val millis = date.toEpochDay() * PackedDate.MILLIS_IN_DAY
val buffer = stringBuffer
buffer.setLength(0)
// Use the appropriate formatter
if (Build.VERSION.SDK_INT >= 24) {
val formatter = dateFormatter as android.icu.text.SimpleDateFormat
val calendar = calendarOrDate as android.icu.util.Calendar
calendar.timeInMillis = millis
formatter.format(calendar, buffer, FIELD_POS)
} else {
val formatter = dateFormatter as SimpleDateFormat
val javaUtilDate = calendarOrDate as Date
javaUtilDate.time = millis
formatter.format(javaUtilDate, buffer, FIELD_POS)
}
return buffer.toString()
}
companion object {
private val FIELD_POS = FieldPosition(0)
}
}
| 6
|
Kotlin
|
0
| 10
|
839345e66f6b06336c3df8221d0f0f51622f0022
| 2,286
|
RangeCalendar
|
MIT License
|
src/main/kotlin/io/zeko/restapi/core/security/JWTAuthHandler.kt
|
darkredz
| 259,352,372
| false
| null |
package io.zeko.restapi.core.security
import io.vertx.core.Handler
import io.vertx.core.http.HttpHeaders
import io.vertx.ext.web.RoutingContext
import io.vertx.ext.auth.jwt.JWTAuth
import io.zeko.restapi.core.security.JWTAuthHelper
import io.zeko.restapi.core.utilities.endJson
open class JWTAuthHandler(
protected val jwtAuth: JWTAuth,
protected val skipAuth: List<String>,
protected val continueAfterFail: Boolean = false,
protected val statusFail: Int = 401,
protected val useCamelCase: Boolean = false
) : Handler<RoutingContext> {
override fun handle(ctx: RoutingContext) {
var skip = false
if (this.skipAuth != null) {
val path = ctx.normalizedPath()
if (this.skipAuth.contains(path)) {
skip = true
ctx.next()
} else {
val matchList = skipAuth.filter { it.indexOf("*") > 1 }
for (urlToMatch in matchList) {
val parts = urlToMatch.split("*")
if (parts.size == 2) {
if (
parts[1].isNullOrEmpty() && path.indexOf(parts[0]) === 0 ||
(!parts[1].isNullOrEmpty() && path.indexOf(parts[0]) === 0 && path.indexOf(parts[1]) === path.length - parts[1].length)
) {
skip = true
ctx.next()
break
}
}
}
}
}
if (!skip) {
var authHeader = ctx.request().getHeader(HttpHeaders.AUTHORIZATION.toString())
val helper = JWTAuthHelper(jwtAuth, null, useCamelCase)
helper.validateToken(authHeader) { user, result ->
if (user == null) {
if (continueAfterFail) {
ctx.put("tokenStatus", result)
ctx.next()
} else {
ctx.endJson(result, statusFail)
}
} else {
ctx.setUser(user)
ctx.next()
}
}
}
}
}
| 3
|
Kotlin
|
2
| 18
|
b7063e66ff90ae945293fc441eb000c021118300
| 2,218
|
zeko-restapi-framework
|
Apache License 2.0
|
app/src/androidTest/java/com/petrulak/cleankotlin/ui/example2/Example2ActivityTest.kt
|
Petrulak
| 104,648,833
| false
| null |
package com.petrulak.cleankotlin.ui.example2
import android.content.Intent
import android.support.test.InstrumentationRegistry
import android.support.test.espresso.Espresso.onView
import android.support.test.espresso.assertion.ViewAssertions.matches
import android.support.test.espresso.matcher.ViewMatchers.withId
import android.support.test.espresso.matcher.ViewMatchers.withText
import android.support.test.rule.ActivityTestRule
import android.support.test.runner.AndroidJUnit4
import com.petrulak.cleankotlin.MockApp
import com.petrulak.cleankotlin.R
import com.petrulak.cleankotlin.di.component.ApplicationMockComponent
import com.petrulak.cleankotlin.di.component.DaggerViewMockComponent
import com.petrulak.cleankotlin.di.module.PresenterMockModule
import com.petrulak.cleankotlin.domain.interactor.definition.GetWeatherRemotelyUseCase
import com.petrulak.cleankotlin.domain.model.Weather
import io.reactivex.Single
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mockito
import javax.inject.Inject
@RunWith(AndroidJUnit4::class)
class Example2ActivityTest {
@get:Rule
var activity = ActivityTestRule(Example2Activity::class.java, true, false) // do not launch the activity immediately
@Inject lateinit var useCase: GetWeatherRemotelyUseCase
@Before
fun setUp() {
val instrumentation = InstrumentationRegistry.getInstrumentation()
val app = instrumentation.targetContext.applicationContext as MockApp
val component = app.applicationComponent as ApplicationMockComponent
DaggerViewMockComponent.builder()
.presenterMockModule(PresenterMockModule())
.applicationMockComponent(component)
.build().inject(this)
}
@Test
fun shouldUpdateUIAfterObtainingWeatherData() {
val mockedWeather = Weather(1L, "Bratislava", 456)
val mockedSingle = Single.just(mockedWeather)
Mockito.`when`(useCase.execute(mockedWeather.name)).thenReturn(mockedSingle)
activity.launchActivity(Intent())
onView(withId(R.id.tv_city)).check(matches(withText(mockedWeather.name)))
}
}
| 0
|
Kotlin
|
10
| 111
|
51033f30ecdb9573000454f1b8890d20c2438002
| 2,181
|
android-kotlin-mvp-clean-architecture
|
MIT License
|
app/src/main/java/com/bura/kotlinnotes/NoteDatabase.kt
|
vikrorcz
| 380,305,629
| false
| null |
package com.bura.kotlinnotes
import android.content.Context
import androidx.lifecycle.LifecycleCoroutineScope
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import androidx.lifecycle.lifecycleScope
@Database(entities = [Note::class], version = 1)
abstract class NoteDatabase : RoomDatabase() {
abstract fun noteDao(): NoteDao
/*
companion object{
var instance: NoteDatabase?=null
fun getAppDatabase(context: Context):NoteDatabase?{
if (instance == null){
synchronized(NoteDatabase::class){
instance = Room.databaseBuilder(context.applicationContext,NoteDatabase::class.java, "notedb").fallbackToDestructiveMigration().allowMainThreadQueries().build()
}
}
return instance
}
}
*/
/*
private fun <R> CoroutineScope.executeAsyncTask(
onPreExecute: () -> Unit,
doInBackground: () -> R,
onPostExecute: (R) -> Unit
) = launch {
onPreExecute()
val result = withContext(Dispatchers.IO) { // runs in background thread without blocking the Main Thread
doInBackground()
}
onPostExecute(result)
}
*/
}
| 0
|
Kotlin
|
0
| 0
|
f4082628f19632ed401deb5544f1c703fbaf7872
| 1,392
|
KotlinNotes
|
MIT License
|
src/main/kotlin/com/coditory/gradle/build/DetektConfiguration.kt
|
coditory
| 250,102,071
| false
| null |
package com.coditory.gradle.build
import io.gitlab.arturbosch.detekt.Detekt
import io.gitlab.arturbosch.detekt.extensions.DetektExtension
import org.gradle.api.Project
internal object DetektConfiguration {
fun configure(project: Project) {
project.plugins.withId("io.gitlab.arturbosch.detekt") {
configureOnPluginEnabled(project)
}
}
private fun configureOnPluginEnabled(project: Project) {
val detektExtension = project.extensions.getByType(DetektExtension::class.java)
detektExtension.buildUponDefaultConfig = true
detektExtension.config.setFrom(project.fileTree(project.projectDir).include("/config/detekt/config.yml"))
project.tasks.withType(Detekt::class.java) { task ->
// task.buildUponDefaultConfig = true
// task.config.setFrom(project.fileTree(project.projectDir).include("/config/detekt/config.yml"))
task.jvmTarget = Versions.JVM_VERSION
task.reports.apply {
html.required.set(true)
xml.required.set(true)
}
}
}
}
| 0
|
Kotlin
|
0
| 1
|
22adc5508092832cbb9811f973ae69014c58fbb8
| 1,105
|
gradle-build-plugin
|
MIT License
|
dist/src/main/kotlin/kr/toxicity/hud/manager/ListenerManagerImpl.kt
|
toxicity188
| 766,189,896
| false
| null |
package kr.toxicity.hud.manager
import kr.toxicity.hud.api.listener.HudListener
import kr.toxicity.hud.api.manager.ListenerManager
import kr.toxicity.hud.api.update.UpdateEvent
import kr.toxicity.hud.resource.GlobalResource
import kr.toxicity.hud.util.armor
import kr.toxicity.hud.util.ifNull
import org.bukkit.attribute.Attribute
import org.bukkit.configuration.ConfigurationSection
import java.util.function.Function
object ListenerManagerImpl: BetterHudManager, ListenerManager {
private val listenerMap = mutableMapOf<String, (ConfigurationSection) -> (UpdateEvent) -> HudListener>(
"health" to { _ ->
{
HudListener { p ->
p.bukkitPlayer.health / p.bukkitPlayer.getAttribute(Attribute.GENERIC_MAX_HEALTH)!!.value
}
}
},
"food" to { _ ->
{
HudListener { p ->
p.bukkitPlayer.foodLevel / 20.0
}
}
},
"armor" to { _ ->
{
HudListener { p ->
p.bukkitPlayer.armor / 20.0
}
}
},
"air" to { _ ->
{
HudListener { p ->
(p.bukkitPlayer.remainingAir.toDouble() / p.bukkitPlayer.maximumAir).coerceAtLeast(0.0)
}
}
},
"exp" to { _ ->
{
HudListener { p ->
p.bukkitPlayer.exp.toDouble()
}
}
},
"absorption" to { _ ->
{
HudListener { p ->
p.bukkitPlayer.absorptionAmount / p.bukkitPlayer.getAttribute(Attribute.GENERIC_MAX_HEALTH)!!.value
}
}
},
"placeholder" to placeholder@ { c ->
val v = PlaceholderManagerImpl.find(c.getString("value").ifNull("value value not set."))
val m = PlaceholderManagerImpl.find(c.getString("max").ifNull("max value not set."))
return@placeholder { event ->
val value = v.build(event)
val max = m.build(event)
if (value.clazz == max.clazz && value.clazz == java.lang.Number::class.java) {
HudListener {
runCatching {
(value(it) as Number).toDouble() / (max(it) as Number).toDouble()
}.getOrNull() ?: 0.0
}
} else throw RuntimeException("this type is not a number: ${value.clazz.simpleName} and ${max.clazz.simpleName}")
}
}
)
override fun start() {
}
fun getListener(section: ConfigurationSection): (UpdateEvent) -> HudListener {
val clazz = section.getString("class").ifNull("class value not set.")
return listenerMap[clazz].ifNull("this class doesn't exist: $clazz")(section)
}
override fun addListener(name: String, listenerFunction: Function<ConfigurationSection, Function<UpdateEvent, HudListener>>) {
listenerMap[name] = { c ->
listenerFunction.apply(c).let { t ->
{
t.apply(it)
}
}
}
}
override fun reload(resource: GlobalResource) {
}
override fun end() {
}
}
| 4
| null |
7
| 87
|
75d3aef889effb28cfe229f4cd22689ef85b3c7d
| 3,342
|
BetterHud
|
MIT License
|
src/main/kotlin/io/mustelidae/otter/sumatrana/api/domain/slack/convertor/SlackPayloadConvertor.kt
|
otter-world
| 595,030,375
| false
| null |
package io.mustelidae.otter.sumatrana.api.domain.slack.convertor
import io.mustelidae.otter.sumatrana.api.domain.sentry.Sentry
import io.mustelidae.otter.sumatrana.api.domain.sentry.SentryResources
import io.mustelidae.otter.sumatrana.api.domain.slack.SlackResources
interface SlackPayloadConvertor {
fun sentryToSlack(sentry: Sentry, payload: SentryResources.Payload): SlackResources.Payload
}
| 0
|
Kotlin
|
0
| 0
|
dc22b11823bace8b21c3fcf12bb1eb53f6a3db71
| 401
|
sumatrana-otter
|
MIT License
|
app/src/main/java/app/books/tanga/data/user/UserRepository.kt
|
rygelouv
| 605,776,570
| false
| null |
package app.books.tanga.data.user
import app.books.tanga.data.preferences.DefaultPrefDataStoreRepository
import app.books.tanga.entity.User
import app.books.tanga.entity.UserId
import app.books.tanga.firestore.FirestoreDatabase
import app.books.tanga.firestore.FirestoreOperationHandler
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.CollectionReference
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.ktx.snapshots
import javax.inject.Inject
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.emitAll
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.tasks.await
interface UserRepository {
suspend fun getUser(): Result<User?>
suspend fun getUserStream(): Flow<User?>
suspend fun getUserId(): UserId?
suspend fun createUser(user: User): Result<Unit>
suspend fun deleteUser(user: User): Result<Unit>
suspend fun updateUser(user: User): Result<Unit>
}
val FirebaseFirestore.userCollection: CollectionReference
get() = collection(FirestoreDatabase.Users.COLLECTION_NAME)
class UserRepositoryImpl @Inject constructor(
private val firestore: FirebaseFirestore,
private val prefDataStoreRepo: DefaultPrefDataStoreRepository,
private val operationHandler: FirestoreOperationHandler,
private val firebaseAuth: FirebaseAuth
) : UserRepository, FirestoreOperationHandler by operationHandler {
override suspend fun getUser(): Result<User?> {
val sessionId = prefDataStoreRepo.getSessionId().first()
val currentUser = firebaseAuth.currentUser
var result: Result<User?> = Result.success(null)
if (sessionId != null) {
result = if (currentUser?.isAnonymous == true) {
Result.success(currentUser.toAnonymousUser())
} else {
executeOperation {
val uid = sessionId.value
val userDocument =
firestore
.userCollection
.document(uid)
.get()
.await()
val userDataMap = userDocument.data
userDataMap?.toUser(uid)
}
}
}
return result
}
override suspend fun getUserStream(): Flow<User?> = flow {
val sessionId = prefDataStoreRepo.getSessionId().first()
val currentUser = firebaseAuth.currentUser
if (sessionId != null) {
if (currentUser?.isAnonymous == true) {
emit(currentUser.toAnonymousUser())
} else {
val uid = sessionId.value
val stream = firestore.userCollection
.document(uid)
.snapshots().map { documentSnapshot ->
val userDataMap = documentSnapshot.data
userDataMap?.toUser(uid)
}
emitAll(stream)
}
} else {
emit(null)
}
}
override suspend fun getUserId(): UserId? {
val sessionId = prefDataStoreRepo.getSessionId().first()
return sessionId?.value?.let { UserId(it) }
}
override suspend fun createUser(user: User): Result<Unit> {
val userMap = user.toFireStoreUserData()
return executeOperation {
firestore
.userCollection
.document(user.id.value)
.set(userMap)
.await()
}
}
override suspend fun updateUser(user: User): Result<Unit> {
val userMap = user.toFireStoreUserData()
return executeOperation {
firestore
.userCollection
.document(user.id.value)
.update(userMap)
.await()
}
}
override suspend fun deleteUser(user: User): Result<Unit> =
executeOperation {
firestore
.userCollection
.document(user.id.value)
.delete()
.await()
}
}
| 7
| null |
0
| 9
|
81cb866802300e3c835a6db36aff2a36a6eeacf8
| 4,224
|
Tanga
|
Apache License 2.0
|
kotest-tests/kotest-tests-timeout/src/test/kotlin/com/sksamuel/kotest/timeout/TimeoutExceptionTest.kt
|
unaryops
| 399,195,014
| true
|
{"Kotlin": 2969978, "CSS": 352, "Java": 145}
|
package com.sksamuel.kotest.timeout
import io.kotest.core.spec.style.FunSpec
import io.kotest.core.test.TestResult
import io.kotest.core.test.TestStatus
import io.kotest.matchers.shouldBe
import kotlinx.coroutines.delay
import kotlin.time.Duration
import kotlin.time.milliseconds
// tests that the values in the timeout exception are populated correctly
class SpecInvocationTimeoutExceptionTest : FunSpec() {
init {
timeout = 897
invocationTimeout = 10 // millis
test("timeout exception should use the value that caused the test to fail") {
delay(Duration.milliseconds(250))
}
aroundTest { (test, execute) ->
val result = execute(test)
result.error?.message shouldBe "Test did not complete within 10ms"
TestResult.success(0)
}
}
}
// tests that the values in the timeout exception are populated correctly
class TestInvocationTimeoutExceptionTest : FunSpec() {
init {
timeout = 965
invocationTimeout = 800 // millis
test("timeout exception should use the value that caused the test to fail 1").config(
invocationTimeout = Duration.milliseconds(
44
)
) {
delay(Duration.milliseconds(500))
}
test("timeout exception should use the value that caused the test to fail 2").config(
timeout = Duration.milliseconds(454),
invocationTimeout = Duration.milliseconds(44)
) {
delay(Duration.milliseconds(500))
}
aroundTest { (test, execute) ->
val result = execute(test)
(result.status == TestStatus.Failure || result.status == TestStatus.Error) shouldBe true
result.error?.message shouldBe "Test did not complete within 44ms"
TestResult.success(0)
}
}
}
// tests that the values in the timeout exception are populated correctly
class SpecTimeoutExceptionTest : FunSpec() {
init {
timeout = 21
test("timeout exception should use the value that caused the test to fail") {
delay(Duration.milliseconds(100))
}
aroundTest { (test, execute) ->
val result = execute(test)
result.error?.message shouldBe "Test did not complete within 21ms"
TestResult.success(0)
}
}
}
// tests that the values in the timeout exception are populated correctly
class TestTimeoutExceptionTest : FunSpec() {
init {
timeout = 250
test("timeout exception should use the value that caused the test to fail").config(
timeout = Duration.milliseconds(
23
)
) {
delay(Duration.milliseconds(100))
}
aroundTest { (test, execute) ->
val result = execute(test)
result.error?.message shouldBe "Test did not complete within 23ms"
TestResult.success(0)
}
}
}
| 0
| null |
0
| 0
|
77ce26af5690956fc29b8adf4ff14abbdda188ec
| 2,851
|
kotest
|
Apache License 2.0
|
quiz/src/test/kotlin/no/group3/springQuiz/quiz/model/CategoryJPATest.kt
|
husjoh15
| 130,742,823
| true
|
{"Kotlin": 125433, "Shell": 38808, "Batchfile": 29964, "Java": 14426}
|
package no.group3.springQuiz.quiz.model
import no.group3.springQuiz.quiz.model.entity.Category
import no.group3.springQuiz.quiz.model.entity.Question
import no.group3.springQuiz.quiz.model.repository.CategoryRepository
import org.junit.Assert.assertNotNull
import org.junit.Test
import org.junit.runner.RunWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest
import org.springframework.test.context.junit4.SpringRunner
@RunWith(SpringRunner::class)
@DataJpaTest
class CategoryJPATest {
@Autowired
lateinit var categoryRepository : CategoryRepository
private fun createCategory(name: String){
var cat = Category(name = name)
}
@Test
fun testCreateCategory(){
var cat = Category(name = "testCat")
val id = categoryRepository.save(cat)
println("id : " + id.id)
assertNotNull(categoryRepository.findByName("testCat"))
}
}
| 0
|
Kotlin
|
0
| 0
|
156b74477a3c304eda5bedaefea6fd7f0f640976
| 925
|
SpringQuiz
|
MIT License
|
app/src/main/java/com/example/benne/daisyapp2/playback/DaisyPlaybackPreparer.kt
|
m760622
| 163,889,029
| true
|
{"Kotlin": 144211, "Java": 51603}
|
package com.example.benne.daisyapp2.playback
import android.net.Uri
import android.os.Bundle
import android.os.ResultReceiver
import android.support.v4.media.MediaBrowserCompat
import android.support.v4.media.MediaMetadataCompat
import android.support.v4.media.session.PlaybackStateCompat
import android.util.Log
import com.example.benne.daisyapp2.data.PlayableClip
import com.example.benne.daisyapp2.data.daisy202.toMediaMetadata
import com.google.android.exoplayer2.ExoPlayer
import com.google.android.exoplayer2.Player
import com.google.android.exoplayer2.ext.mediasession.MediaSessionConnector
import com.google.android.exoplayer2.source.ClippingMediaSource
import com.google.android.exoplayer2.source.ExtractorMediaSource
import com.google.android.exoplayer2.source.MediaSource
import com.google.android.exoplayer2.upstream.DataSource
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
class DaisyPlaybackPreparer(
private val queueManager: QueueManager,
private val exoPlayer: ExoPlayer,
private val dataSourceFactory: DataSource.Factory
) : MediaSessionConnector.PlaybackPreparer
, Player.EventListener {
private var currentPreparedMediaId: String? = ""
override fun onPlayerStateChanged(playWhenReady: Boolean, playbackState: Int) {
Log.d(TAG, "state change new state: $playbackState")
GlobalScope.launch (Dispatchers.Main) {
when (playbackState) {
// track ended play next if there is one
Player.STATE_BUFFERING -> {
}
Player.STATE_ENDED -> {
val playableClip = queueManager.nextPlayableClip()
playableClip?.let {
exoPlayer.prepare(it.toClippingMediaSource(dataSourceFactory))
}
}
Player.STATE_READY -> {
// todo handle next
}
}
}
}
override fun onPrepareFromSearch(query: String?, extras: Bundle?) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun onCommand(player: Player?, command: String?, extras: Bundle?, cb: ResultReceiver?) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getSupportedPrepareActions(): Long =
PlaybackStateCompat.ACTION_PREPARE_FROM_MEDIA_ID or
PlaybackStateCompat.ACTION_PLAY_FROM_MEDIA_ID or
PlaybackStateCompat.ACTION_PREPARE_FROM_SEARCH or
PlaybackStateCompat.ACTION_PLAY_FROM_SEARCH
override fun getCommands(): Array<String>? = null
override fun onPrepareFromMediaId(mediaId: String?, extras: Bundle?) {
queueManager.setCurrentBook(extras!!.getString("bookMediaId")!!)
queueManager.currentQueueMediaId = mediaId!!
val playableClip = queueManager.currentClip()
playableClip?.let {
Log.d(TAG, "playing $playableClip")
val source = playableClip.toClippingMediaSource(dataSourceFactory)
val mediaIsSame =
currentPreparedMediaId == playableClip.hashCode().toString()
if (!mediaIsSame) {
currentPreparedMediaId = playableClip.hashCode().toString()
exoPlayer.prepare(source)
}
exoPlayer.playWhenReady = true
}
}
override fun onPrepareFromUri(uri: Uri?, extras: Bundle?) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun onPrepare() = Unit
companion object {
private val TAG: String = DaisyPlaybackPreparer::class.java.simpleName
private fun Pair<PlayableClip, MediaBrowserCompat.MediaItem>.toClippingMediaSource(dataSourceFactory: DataSource.Factory): MediaSource {
// The MediaSource represents the media to be played.
val extractorMediaSource = ExtractorMediaSource
.Factory(dataSourceFactory)
.setTag(this.second.description)
.createMediaSource(Uri.parse(this.first.file.path))
return if (this.first.clipStart == null || this.first.clipEnd == null) {
extractorMediaSource
} else {
ClippingMediaSource(
extractorMediaSource,
this.first.clipStart!!,
this.first.clipEnd!!,
true,
true,
false)
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
3cff9202d8ec94f1fcefddd02b08956ec95222c8
| 4,753
|
mobile-ebook-player
|
Apache License 2.0
|
compiler/fir/raw-fir/psi2fir/testData/rawBuilder/declarations/secondaryConstructor.kt
|
JetBrains
| 3,432,266
| false
| null |
// MEMBER_CLASS_FILTER: org.jetbrains.kotlin.fir.symbols.impl.FirConstructorSymbol
// BODY_RESOLVE
package util
@Target(AnnotationTarget.TYPE)
annotation class Anno(val position: String)
const val prop = "str"
abstract class AbstractClass<T>
class <caret>MyClass() : @Anno("super type call $prop") AbstractClass<@Anno("nested super type ref $prop") List<@Anno("nested nested super type ref $prop") Int>>()
| 181
| null |
5748
| 49,172
|
33eb9cef3d146062c103f9853d772f0a1da0450e
| 409
|
kotlin
|
Apache License 2.0
|
spring-data-cassandra/src/test/kotlin/org/springframework/data/cassandra/core/ReactiveUpdateOperationExtensionsUnitTests.kt
|
spring-projects
| 2,183,665
| false
| null |
/*
* Copyright 2018-2021 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.cassandra.core
import io.mockk.every
import io.mockk.mockk
import io.mockk.verify
import kotlinx.coroutines.runBlocking
import org.assertj.core.api.Assertions
import org.junit.jupiter.api.Test
import org.springframework.data.cassandra.core.query.Update
import org.springframework.data.cassandra.domain.Person
import reactor.core.publisher.Mono
/**
* Unit tests for [ReactiveUpdateOperationExtensions].
*
* @author Mark Paluch
*/
class ReactiveUpdateOperationExtensionsUnitTests {
val operations = mockk<ReactiveFluentCassandraOperations>(relaxed = true)
@Test // DATACASS-484
fun `update(KClass) extension should call its Java counterpart`() {
operations.update(Person::class);
verify { operations.update(Person::class.java) }
}
@Test // DATACASS-484
fun `update() with reified type parameter extension should call its Java counterpart`() {
operations.update<Person>()
verify { operations.update(Person::class.java) }
}
@Test // DATACASS-632
fun applyAndAwait() {
val update = mockk<ReactiveUpdateOperation.TerminatingUpdate>()
val result = mockk<WriteResult>()
val updateObj = mockk<Update>();
every { update.apply(updateObj) } returns Mono.just(result)
runBlocking {
Assertions.assertThat(update.applyAndAwait(updateObj)).isEqualTo(result)
}
verify {
update.apply(updateObj)
}
}
}
| 39
| null |
311
| 379
|
67d8e597ae900b1c2f1eb145e76755cb25a1bb57
| 1,993
|
spring-data-cassandra
|
Apache License 2.0
|
native/native.tests/tests/org/jetbrains/kotlin/konan/test/blackbox/EchoServerTest.kt
|
JetBrains
| 3,432,266
| false
|
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
|
/*
* Copyright 2010-2024 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
@file:Suppress("JUnitTestCaseWithNoTests")
package org.jetbrains.kotlin.konan.test.blackbox
import com.intellij.testFramework.TestDataPath
import org.jetbrains.kotlin.konan.target.Family
import org.jetbrains.kotlin.konan.test.blackbox.support.*
import org.jetbrains.kotlin.konan.test.blackbox.support.compilation.TestCompilationFactory
import org.jetbrains.kotlin.konan.test.blackbox.support.compilation.TestCompilationResult.Companion.assertSuccess
import org.jetbrains.kotlin.konan.test.blackbox.support.group.FirPipeline
import org.jetbrains.kotlin.konan.test.blackbox.support.runner.TestRunChecks
import org.jetbrains.kotlin.test.TestMetadata
import org.junit.jupiter.api.Assumptions
import org.junit.jupiter.api.Tag
import org.junit.jupiter.api.Test
import java.io.File
import java.net.Socket
import kotlin.test.assertEquals
import kotlin.time.Duration
@TestMetadata("native/native.tests/testData/echoServer")
@TestDataPath("\$PROJECT_ROOT")
class ClassicEchoServerTest : EchoServerBaseTest()
@FirPipeline
@Tag("frontend-fir")
@TestMetadata("native/native.tests/testData/echoServer")
@TestDataPath("\$PROJECT_ROOT")
class FirEchoServerTest : EchoServerBaseTest()
abstract class EchoServerBaseTest : AbstractNativeSimpleTest() {
private val testCompilationFactory = TestCompilationFactory()
@Test
fun test() {
Assumptions.assumeFalse(targets.testTarget.family == Family.MINGW)
Assumptions.assumeFalse(targets.areDifferentTargets(), "The test uses localhost networking")
val rootDir = File("native/native.tests/testData/echoServer")
val cinteropModule = TestModule.Exclusive("sockets", emptySet(), emptySet(), emptySet()).apply {
files += TestFile.createCommitted(rootDir.resolve("sockets.def"), this)
}
val ktModule = TestModule.Exclusive("server", setOf(cinteropModule.name), emptySet(), emptySet()).apply {
files += TestFile.createCommitted(rootDir.resolve("echo_server.kt"), this)
}
val testCase = TestCase(
id = TestCaseId.Named("echo_server"),
kind = TestKind.STANDALONE_NO_TR,
modules = setOf(cinteropModule, ktModule),
freeCompilerArgs = TestCompilerArgs.EMPTY,
nominalPackageName = PackageName("echo_server"),
checks = TestRunChecks.Default(Duration.INFINITE),
extras = TestCase.NoTestRunnerExtras(),
).apply {
initialize(null, null)
}
val compilationResult = testCompilationFactory.testCasesToExecutable(listOf(testCase), testRunSettings).result.assertSuccess()
val process = ProcessBuilder(compilationResult.resultingArtifact.path).start()
try {
val port = process.inputStream.bufferedReader().readLine().toInt()
Socket("localhost", port).use { socket ->
val inputStream = socket.getInputStream().bufferedReader()
val outputStream = socket.getOutputStream().writer()
outputStream.write("Hello\n")
outputStream.flush()
val read = inputStream.readLine()
assertEquals("Hello", read)
}
} finally {
// Make sure the process is gone no matter what.
process.destroyForcibly()
}
}
}
| 181
|
Kotlin
|
5748
| 49,172
|
33eb9cef3d146062c103f9853d772f0a1da0450e
| 3,519
|
kotlin
|
Apache License 2.0
|
plugin/src/main/kotlin/io/pulsarRPC/plugin/main.kt
|
geomagilles
| 515,543,252
| false
| null |
package io.pulsarRPC.plugin
import com.salesforce.jprotoc.ProtocPlugin
fun main(args: Array<String>) {
if (args.isEmpty()) {
ProtocPlugin.generate(Plugin())
} else {
ProtocPlugin.debug(Plugin(), args[0])
}
}
| 0
|
Kotlin
|
0
| 2
|
471168e344526a138c910ca9d7ee68bd2a9d5c02
| 238
|
pulsarRPC
|
Apache License 2.0
|
app/src/main/java/cash/z/ecc/android/ui/send/AutoShieldViewModel.kt
|
zcash
| 223,814,143
| false
| null |
package cash.z.ecc.android.ui.send
import androidx.lifecycle.ViewModel
import cash.z.ecc.android.di.DependenciesHolder
import cash.z.ecc.android.ext.Const
import cash.z.ecc.android.lockbox.LockBox
import cash.z.ecc.android.sdk.Synchronizer
import cash.z.ecc.android.sdk.ext.ZcashSdk
import cash.z.ecc.android.sdk.ext.convertZatoshiToZecString
import cash.z.ecc.android.sdk.model.Account
import cash.z.ecc.android.sdk.model.BlockHeight
import cash.z.ecc.android.sdk.model.PendingTransaction
import cash.z.ecc.android.sdk.model.WalletBalance
import cash.z.ecc.android.sdk.model.Zatoshi
import cash.z.ecc.android.sdk.model.isMined
import cash.z.ecc.android.sdk.model.isSubmitSuccess
import cash.z.ecc.android.sdk.tool.DerivationTool
import cash.z.ecc.android.util.twig
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.combineTransform
import kotlinx.coroutines.flow.onEach
class AutoShieldViewModel : ViewModel() {
private val synchronizer: Synchronizer = DependenciesHolder.synchronizer
private val lockBox: LockBox = DependenciesHolder.lockBox
var latestBalance: BalanceModel? = null
val balances
get() = combineTransform(
synchronizer.orchardBalances,
synchronizer.saplingBalances,
synchronizer.transparentBalances,
) { o, s, t ->
BalanceModel(o, s, t).let {
latestBalance = it
emit(it)
}
}
val statuses
get() = combineTransform(
synchronizer.saplingBalances,
synchronizer.pendingTransactions,
synchronizer.processorInfo
) { balance, pending, info ->
val unconfirmed = pending.filter { !it.isConfirmed(info.networkBlockHeight) }
val unmined = pending.filter { it.isSubmitSuccess() && !it.isMined() }
val pending = balance?.pending?.value ?: 0
emit(StatusModel(unmined, unconfirmed, pending, info.networkBlockHeight))
}
private fun PendingTransaction.isConfirmed(networkBlockHeight: BlockHeight?): Boolean {
return networkBlockHeight?.let { height ->
isMined() && (height.value - minedHeight!!.value + 1) > 10
} ?: false
}
/**
* Update the autoshielding achievement and return true if this is the first time.
*/
fun updateAutoshieldAchievement(): Boolean {
val existingValue = lockBox.getBoolean(Const.Pref.EASTER_EGG_TRIGGERED_SHIELDING)
return if (!existingValue) {
lockBox.setBoolean(Const.Pref.EASTER_EGG_TRIGGERED_SHIELDING, true)
true
} else {
false
}
}
suspend fun shieldFunds(): Flow<PendingTransaction> {
return lockBox.getBytes(Const.Backup.SEED)?.let {
val usk =
DerivationTool.deriveUnifiedSpendingKey(it, synchronizer.network, Account.DEFAULT)
val addr = synchronizer.getTransparentAddress()
synchronizer.shieldFunds(
usk,
"${ZcashSdk.DEFAULT_SHIELD_FUNDS_MEMO_PREFIX}\nAll UTXOs from $addr"
).onEach { tx ->
twig("Received shielding txUpdate: ${tx?.toString()}")
// updateMetrics(it)
// reportFailures(it)
}
} ?: throw IllegalStateException("Seed was expected but it was not found!")
}
data class BalanceModel(
val orchardBalance: WalletBalance?,
val saplingBalance: WalletBalance?,
val transparentBalance: WalletBalance?,
) {
val balanceShielded: String = saplingBalance?.available.toDisplay()
val balanceTransparent: String = transparentBalance?.available.toDisplay()
val balanceTotal: String =
((saplingBalance?.available ?: Zatoshi(0)) + (transparentBalance?.available
?: Zatoshi(0))).toDisplay()
val canAutoShield: Boolean = (transparentBalance?.available?.value ?: 0) > 0L
val maxLength =
maxOf(balanceShielded.length, balanceTransparent.length, balanceTotal.length)
val paddedShielded = pad(balanceShielded)
val paddedTransparent = pad(balanceTransparent)
val paddedTotal = pad(balanceTotal)
private fun Zatoshi?.toDisplay(): String {
return convertZatoshiToZecString(8, 8)
}
private fun pad(balance: String): String {
var diffLength = maxLength - balance.length
return buildString {
repeat(diffLength) {
append(' ')
}
append(balance)
}
}
}
data class StatusModel(
val pendingUnconfirmed: List<PendingTransaction> = listOf(),
val pendingUnmined: List<PendingTransaction> = listOf(),
val pendingBalance: Long = 0L,
val latestHeight: BlockHeight? = null,
) {
val hasUnconfirmed = pendingUnconfirmed.isNotEmpty()
val hasUnmined = pendingUnmined.isNotEmpty()
val hasPendingBalance = pendingBalance > 0L
fun remainingConfirmations(latestHeight: Int, confirmationsRequired: Int = 10) =
pendingUnconfirmed
.map { confirmationsRequired - (latestHeight - it.minedHeight!!.value + 1) }
.filter { it > 0 }
.sortedDescending()
}
}
| 48
|
Kotlin
|
21
| 19
|
a06bd19d92aee8f928de995ca24d787d7ca47765
| 5,347
|
zcash-android-wallet
|
MIT License
|
retrofit/src/main/java/retrofit2/KotlinExtensions.kt
|
SnoopyCodeX
| 220,791,983
| false
| null |
/*
* Copyright (C) 2018 Square, 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.
*/
@file:JvmName("KotlinExtensions")
package retrofit2
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.yield
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
inline fun <reified T> Retrofit.create(): T = create(T::class.java)
suspend fun <T : Any> Call<T>.await(): T {
return suspendCancellableCoroutine { continuation ->
continuation.invokeOnCancellation {
cancel()
}
enqueue(object : Callback<T> {
override fun onResponse(call: Call<T>, response: Response<T>) {
if (response.isSuccessful) {
val body = response.body()
if (body == null) {
val invocation = call.request().tag(Invocation::class.java)!!
val method = invocation.method()
val e = KotlinNullPointerException("Response from " +
method.declaringClass.name +
'.' +
method.name +
" was null but response body type was declared as non-null")
continuation.resumeWithException(e)
} else {
continuation.resume(body)
}
} else {
continuation.resumeWithException(HttpException(response))
}
}
override fun onFailure(call: Call<T>, t: Throwable) {
continuation.resumeWithException(t)
}
})
}
}
@JvmName("awaitNullable")
suspend fun <T : Any> Call<T?>.await(): T? {
return suspendCancellableCoroutine { continuation ->
continuation.invokeOnCancellation {
cancel()
}
enqueue(object : Callback<T?> {
override fun onResponse(call: Call<T?>, response: Response<T?>) {
if (response.isSuccessful) {
continuation.resume(response.body())
} else {
continuation.resumeWithException(HttpException(response))
}
}
override fun onFailure(call: Call<T?>, t: Throwable) {
continuation.resumeWithException(t)
}
})
}
}
suspend fun <T : Any> Call<T>.awaitResponse(): Response<T> {
return suspendCancellableCoroutine { continuation ->
continuation.invokeOnCancellation {
cancel()
}
enqueue(object : Callback<T> {
override fun onResponse(call: Call<T>, response: Response<T>) {
continuation.resume(response)
}
override fun onFailure(call: Call<T>, t: Throwable) {
continuation.resumeWithException(t)
}
})
}
}
internal suspend fun Exception.yieldAndThrow(): Nothing {
yield()
throw this
}
| 0
| null |
0
| 1
|
d25a50a29ff8f1ab1196b5835930591cd062c1f6
| 3,111
|
retrofit
|
Apache License 2.0
|
shared/src/main/kotlin/io/github/aplcornell/viaduct/syntax/types/Type.kt
|
apl-cornell
| 169,159,978
| false
|
{"Kotlin": 1117382, "Java": 43793, "C++": 13898, "Lex": 12293, "Python": 11983, "Dockerfile": 1951, "Makefile": 1762, "SWIG": 1212, "Shell": 950}
|
package io.github.aplcornell.viaduct.syntax.types
import io.github.aplcornell.viaduct.prettyprinting.PrettyPrintable
/** A type assignable to data or computations. */
interface Type : PrettyPrintable
| 31
|
Kotlin
|
4
| 20
|
567491fdcfd313bf287b8cdd374e80f1e005ac62
| 202
|
viaduct
|
MIT License
|
app/src/main/java/com/keshavindustryfsm/features/viewAllOrder/interf/NewOrderSizeQtyDelOnClick.kt
|
DebashisINT
| 683,953,107
| false
| null |
package com.keshavindustryfsm.features.viewAllOrder.interf
import com.keshavindustryfsm.app.domain.NewOrderGenderEntity
import com.keshavindustryfsm.features.viewAllOrder.model.ProductOrder
import java.text.FieldPosition
interface NewOrderSizeQtyDelOnClick {
fun sizeQtySelListOnClick(product_size_qty: ArrayList<ProductOrder>)
fun sizeQtyListOnClick(product_size_qty: ProductOrder,position: Int)
}
| 0
|
Kotlin
|
0
| 0
|
1fe9474dbd328a18c1adaaca32036fda2b02ac53
| 408
|
KeshavIndustry
|
Apache License 2.0
|
clion-plugin/src/main/kotlin/org/utbot/cpp/clion/plugin/client/handlers/CoverageAndResultsHandler.kt
|
UnitTestBot
| 414,561,684
| false
|
{"C++": 1727348, "Kotlin": 269507, "C": 249924, "TypeScript": 230111, "Shell": 28129, "CMake": 23083, "JavaScript": 14798, "HTML": 13208, "CSS": 8653, "Python": 2980, "Batchfile": 882, "Makefile": 648}
|
package org.utbot.cpp.clion.plugin.client.handlers
import com.intellij.coverage.CoverageDataManager
import com.intellij.coverage.CoverageEngine
import com.intellij.coverage.CoverageRunner
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.project.Project
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.withContext
import org.utbot.cpp.clion.plugin.UTBot
import org.utbot.cpp.clion.plugin.actions.FocusAction
import org.utbot.cpp.clion.plugin.coverage.Coverage
import org.utbot.cpp.clion.plugin.coverage.UTBotCoverageEngine
import org.utbot.cpp.clion.plugin.coverage.UTBotCoverageRunner
import org.utbot.cpp.clion.plugin.coverage.UTBotCoverageSuite
import org.utbot.cpp.clion.plugin.listeners.UTBotTestResultsReceivedListener
import org.utbot.cpp.clion.plugin.utils.convertFromRemotePathIfNeeded
import org.utbot.cpp.clion.plugin.utils.logger
import org.utbot.cpp.clion.plugin.utils.notifyError
import org.utbot.cpp.clion.plugin.utils.notifyInfo
import testsgen.Testgen
import testsgen.Util
import java.nio.file.Path
class CoverageAndResultsHandler(
project: Project,
grpcStream: Flow<Testgen.CoverageAndResultsResponse>,
progressName: String,
cancellationJob: Job,
val sourceFilePath: Path? = null
) : StreamHandlerWithProgress<Testgen.CoverageAndResultsResponse>(project, grpcStream, progressName, cancellationJob) {
override fun Testgen.CoverageAndResultsResponse.getProgress(): Util.Progress = progress
override suspend fun handle() {
// Coverage api should be started from background thread
withContext(Dispatchers.Default) {
super.handle()
}
}
override fun onLastResponse(response: Testgen.CoverageAndResultsResponse?) {
if (response == null) {
project.logger.error { "No responses from server!" }
return
}
if (response.errorMessage.isNotEmpty()) {
notifyError(
UTBot.message("notify.title.error"),
response.errorMessage,
project
)
}
data class CoverageCollector(
val fullyCovered: MutableSet<Int> = mutableSetOf(),
val partiallyCovered: MutableSet<Int> = mutableSetOf(),
val notCovered: MutableSet<Int> = mutableSetOf()
) {
fun toCoverage() = Coverage(fullyCovered, partiallyCovered, notCovered)
}
val coverage = mutableMapOf<Path, CoverageCollector>()
response.coveragesList.forEach { fileCoverageSimplified ->
val local = fileCoverageSimplified.filePath.convertFromRemotePathIfNeeded(project).normalize()
if (local !in coverage)
coverage[local] = CoverageCollector()
fileCoverageSimplified.fullCoverageLinesList.forEach { sourceLine ->
coverage[local]?.fullyCovered?.add(sourceLine.line)
}
fileCoverageSimplified.partialCoverageLinesList.forEach { sourceLine ->
coverage[local]?.partiallyCovered?.add(sourceLine.line)
}
fileCoverageSimplified.noCoverageLinesList.forEach { sourceLine ->
coverage[local]?.notCovered?.add(sourceLine.line)
}
}
// when we received results, test statuses should be updated in the gutter
project.messageBus.let { bus ->
if (!bus.isDisposed)
bus.syncPublisher(UTBotTestResultsReceivedListener.TOPIC)
.testResultsReceived(response.testRunResultsList)
}
val engine = CoverageEngine.EP_NAME.findExtension(UTBotCoverageEngine::class.java)
?: error("UTBotEngine instance is not found!")
val coverageRunner = CoverageRunner.getInstance(UTBotCoverageRunner::class.java)
val manager = CoverageDataManager.getInstance(project)
val suite = UTBotCoverageSuite(
coverage.mapValues { it.value.toCoverage() },
engine,
response.coveragesList,
coverageRunner = coverageRunner,
name = "UTBot coverage suite",
project = project,
)
manager.coverageGathered(suite)
notifyCoverageReceived()
}
private fun notifyCoverageReceived() {
notifyInfo(
UTBot.message("notify.coverage.received.title"),
UTBot.message("notify.coverage.received"),
project,
sourceFilePath?.let { FocusAction(it) }
)
}
}
| 117
|
C++
|
21
| 95
|
b39958f776d32c3caa9cb5c367f56593be13e85b
| 4,569
|
UTBotCpp
|
Apache License 2.0
|
compiler/testData/diagnostics/tests/inference/implicitInvokeInObjectWithFunctionalArgument.kt
|
gigliovale
| 89,726,097
| false
| null |
// CHECK_TYPE
// DIAGNOSTICS: -UNUSED_PARAMETER, -UNUSED_VARIABLE
object TestClass {
inline operator fun <T> invoke(task: () -> T) = task()
}
fun test(s: String): String {
val a = TestClass { TestClass { TestClass } }
a checkType { _<TestClass>() }
<!UNREACHABLE_CODE!>val b =<!> TestClass { return s }
<!UNREACHABLE_CODE!>b checkType { _<Nothing>() }<!>
}
| 181
| null |
5748
| 6
|
ce145c015d6461c840050934f2200dbc11cb3d92
| 379
|
kotlin
|
Apache License 2.0
|
platform/lang-impl/src/com/intellij/util/indexing/roots/IndexingRootsCollectionUtil.kt
|
ingokegel
| 72,937,917
| true
| null |
// Copyright 2000-2024 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:JvmName("IndexingRootsCollectionUtil")
package com.intellij.util.indexing.roots
import com.intellij.openapi.diagnostic.thisLogger
import com.intellij.openapi.module.Module
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Condition
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.io.OSAgnosticPathUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.platform.backend.workspace.virtualFile
import com.intellij.platform.workspace.jps.entities.LibraryEntity
import com.intellij.platform.workspace.storage.EntityPointer
import com.intellij.platform.workspace.storage.EntityStorage
import com.intellij.platform.workspace.storage.WorkspaceEntity
import com.intellij.platform.workspace.storage.url.VirtualFileUrl
import com.intellij.util.containers.MultiMap
import com.intellij.util.indexing.CustomizingIndexingPresentationContributor
import com.intellij.util.indexing.ReincludedRootsUtil
import com.intellij.util.indexing.roots.IndexableEntityProvider.IndexableIteratorBuilder
import com.intellij.util.indexing.roots.IndexableEntityProviderMethods.createCustomKindEntityIterators
import com.intellij.util.indexing.roots.IndexableEntityProviderMethods.createGenericContentEntityIterators
import com.intellij.util.indexing.roots.IndexableEntityProviderMethods.createModuleAwareContentEntityIterators
import com.intellij.util.indexing.roots.LibraryIndexableFilesIteratorImpl.Companion.createIterator
import com.intellij.util.indexing.roots.builders.IndexableIteratorBuilders.forCustomKindEntity
import com.intellij.util.indexing.roots.builders.IndexableIteratorBuilders.forExternalEntity
import com.intellij.util.indexing.roots.builders.IndexableIteratorBuilders.forGenericContentEntity
import com.intellij.util.indexing.roots.builders.IndexableIteratorBuilders.forLibraryEntity
import com.intellij.util.indexing.roots.builders.IndexableIteratorBuilders.forModuleAwareCustomizedContentEntity
import com.intellij.util.indexing.roots.builders.IndexableIteratorBuilders.forModuleRootsFileBased
import com.intellij.util.indexing.roots.kind.IndexableSetOrigin
import com.intellij.util.indexing.roots.origin.*
import com.intellij.workspaceModel.core.fileIndex.*
import com.intellij.workspaceModel.core.fileIndex.impl.LibraryRootFileIndexContributor
import com.intellij.workspaceModel.core.fileIndex.impl.ModuleRelatedRootData
import com.intellij.workspaceModel.core.fileIndex.impl.WorkspaceFileIndexImpl
import com.intellij.workspaceModel.ide.impl.legacyBridge.library.findLibraryBridge
import com.intellij.workspaceModel.ide.legacyBridge.ModuleBridge
import org.jetbrains.jps.util.JpsPathUtil
import java.util.*
import java.util.function.Consumer
import java.util.function.Function
internal sealed interface IndexingRootsDescription {
fun createBuilders(): Collection<IndexableIteratorBuilder>
}
internal data class LibraryRootsDescription(val library: LibraryEntity,
val roots: IndexingSourceRootHolder) : IndexingRootsDescription {
override fun createBuilders(): Collection<IndexableIteratorBuilder> {
return forLibraryEntity(library.symbolicId, false, roots.roots, roots.sourceRoots)
}
fun createIterators(storage: EntityStorage): Collection<IndexableFilesIterator> {
val library = library.findLibraryBridge(storage) ?: return emptyList()
return listOfNotNull(createIterator(library, roots.roots, roots.sourceRoots))
}
}
internal data class LibraryUrlRootsDescription(val library: LibraryEntity,
val roots: IndexingUrlSourceRootHolder) : IndexingRootsDescription {
override fun createBuilders(): Collection<IndexableIteratorBuilder> {
return forLibraryEntity(library.symbolicId, false, roots)
}
fun createIterators(storage: EntityStorage): Collection<IndexableFilesIterator> {
val library = library.findLibraryBridge(storage) ?: return emptyList()
val fileRoots = roots.toSourceRootHolder()
if (fileRoots.isEmpty()) return emptyList()
return listOfNotNull(createIterator(library, fileRoots.roots, fileRoots.sourceRoots))
}
}
internal data class EntityContentRootsCustomizedModuleAwareDescription<E : WorkspaceEntity>(val module: Module,
val entityPointer: EntityPointer<E>,
val roots: IndexingUrlRootHolder,
val presentation: IndexableIteratorPresentation?) : IndexingRootsDescription {
override fun createBuilders(): Collection<IndexableIteratorBuilder> {
return forModuleAwareCustomizedContentEntity((module as ModuleBridge).moduleEntityId, entityPointer, roots, presentation)
}
fun createIterators(): Collection<IndexableFilesIterator> {
return createModuleAwareContentEntityIterators(module, entityPointer, roots, presentation)
}
}
internal data class EntityGenericContentRootsDescription<E : WorkspaceEntity>(val entityPointer: EntityPointer<E>,
val roots: IndexingUrlRootHolder,
val presentation: IndexableIteratorPresentation?) : IndexingRootsDescription {
override fun createBuilders(): Collection<IndexableIteratorBuilder> {
return forGenericContentEntity(entityPointer, roots, presentation)
}
fun createIterators(): Collection<IndexableFilesIterator> {
return createGenericContentEntityIterators(entityPointer, roots, presentation)
}
}
internal data class EntityExternalRootsDescription<E : WorkspaceEntity>(val entityPointer: EntityPointer<E>,
val urlRoots: IndexingUrlSourceRootHolder,
val presentation: IndexableIteratorPresentation?) : IndexingRootsDescription {
override fun createBuilders(): Collection<IndexableIteratorBuilder> {
return forExternalEntity(entityPointer, urlRoots, presentation)
}
fun createIterators(): Collection<IndexableFilesIterator> {
return IndexableEntityProviderMethods.createExternalEntityIterators(entityPointer, urlRoots, presentation)
}
}
internal data class EntityCustomKindRootsDescription<E : WorkspaceEntity>(val entityPointer: EntityPointer<E>,
val roots: IndexingUrlRootHolder,
val presentation: IndexableIteratorPresentation?) : IndexingRootsDescription {
override fun createBuilders(): Collection<IndexableIteratorBuilder> {
return forCustomKindEntity(entityPointer, roots, presentation)
}
fun createIterators(): Collection<IndexableFilesIterator> {
return createCustomKindEntityIterators(entityPointer, roots, presentation)
}
}
fun selectRootVirtualFiles(value: Collection<VirtualFile>): List<VirtualFile> {
return selectRootItems(value) { file -> file.path }
}
fun selectRootVirtualFileUrls(urls: Collection<VirtualFileUrl>): List<VirtualFileUrl> {
return selectRootItems(urls) { url -> JpsPathUtil.urlToPath(url.url) }
}
private fun <T> selectRootItems(items: Collection<T>, toPath: Function<T, String>): List<T> {
if (items.size < 2) {
if (items is List<T>) return items
return if (items.isEmpty()) emptyList() else ArrayList(items)
}
val pathMap = TreeMap<String, T>(OSAgnosticPathUtil.COMPARATOR)
for (item in items) {
val path = FileUtil.toSystemIndependentName(toPath.apply(item))
if (!isIncluded(pathMap, path)) {
pathMap[path] = item
while (true) {
val excludedPath = pathMap.higherKey(path)
if (excludedPath != null && OSAgnosticPathUtil.startsWith(excludedPath, path)) {
pathMap.remove(excludedPath)
}
else {
break
}
}
}
}
return pathMap.values.toList()
}
private fun isIncluded(existingFiles: NavigableMap<String, *>, path: String): Boolean {
val suggestedCoveringRoot = existingFiles.floorKey(path)
return suggestedCoveringRoot != null && OSAgnosticPathUtil.startsWith(path, suggestedCoveringRoot)
}
internal class WorkspaceIndexingRootsBuilder(private val ignoreModuleRoots: Boolean) {
private val moduleRoots: MutableMap<Module, MutableIndexingUrlRootHolder> = mutableMapOf()
private val descriptions: MutableCollection<IndexingRootsDescription> = mutableListOf()
private val reincludedRoots: MutableCollection<VirtualFile> = HashSet()
fun <E : WorkspaceEntity> registerAddedEntity(entity: E,
contributor: WorkspaceFileIndexContributor<E>,
storage: EntityStorage) {
val rootData = rootData(contributor, entity, storage)
rootData.cleanExcludedRoots()
loadRegistrarData(rootData)
}
private fun <E : WorkspaceEntity> rootData(contributor: WorkspaceFileIndexContributor<E>,
entity: E,
storage: EntityStorage): RootData<E> {
val registrar = MyWorkspaceFileSetRegistrar(contributor, ignoreModuleRoots)
contributor.registerFileSets(entity, registrar, storage)
return registrar.rootData
}
fun <E : WorkspaceEntity> registerRemovedEntity(entity: E, contributor: WorkspaceFileIndexContributor<E>, storage: EntityStorage) {
val rootData = rootData(contributor, entity, storage)
rootData.cleanIncludedRoots()
loadRegistrarData(rootData)
}
fun <E : WorkspaceEntity> registerChangedEntity(oldEntity: E,
newEntity: E,
contributor: WorkspaceFileIndexContributor<E>,
storage: EntityStorage) {
val oldRootData = rootData(contributor, oldEntity, storage)
val newRootData = rootData(contributor, newEntity, storage)
val data = RootData(contributor, ignoreModuleRoots)
addDiff(data.moduleContents, oldRootData.moduleContents, newRootData.moduleContents)
data.customizedModuleContentEntities.putAllValues(newRootData.customizedModuleContentEntities)
addDiff(data.customizedModuleContentRoots, oldRootData.customizedModuleContentRoots, newRootData.customizedModuleContentRoots)
addDiff(data.contentRoots, oldRootData.contentRoots, newRootData.contentRoots)
addUrlSourceDiff(data.libraryUrlRoots, oldRootData.libraryUrlRoots, newRootData.libraryUrlRoots)
addSourceDiff(data.libraryRoots, oldRootData.libraryRoots, newRootData.libraryRoots)
addUrlSourceDiff(data.externalRoots, oldRootData.externalRoots, newRootData.externalRoots)
data.excludedRoots.addAll(oldRootData.excludedRoots)
data.excludedRoots.removeAll(newRootData.excludedRoots)
data.customizationValues.putAll(newRootData.customizationValues)
loadRegistrarData(data)
}
private fun <K> addDiff(base: MutableMap<K, MutableIndexingUrlRootHolder>,
oldData: MutableMap<K, MutableIndexingUrlRootHolder>,
newData: MutableMap<K, MutableIndexingUrlRootHolder>) {
newData.entries.forEach { entry ->
entry.value.remove(oldData[entry.key])
base.getOrPut(entry.key) { MutableIndexingUrlRootHolder() }.addRoots(entry.value)
}
}
private fun <K> addSourceDiff(base: MutableMap<K, MutableIndexingSourceRootHolder>,
oldData: MutableMap<K, MutableIndexingSourceRootHolder>,
newData: MutableMap<K, MutableIndexingSourceRootHolder>) {
newData.entries.forEach { entry ->
entry.value.remove(oldData[entry.key])
base.getOrPut(entry.key) { MutableIndexingSourceRootHolder() }.addRoots(entry.value)
}
}
private fun <K> addUrlSourceDiff(base: MutableMap<K, MutableIndexingUrlSourceRootHolder>,
oldData: MutableMap<K, MutableIndexingUrlSourceRootHolder>,
newData: MutableMap<K, MutableIndexingUrlSourceRootHolder>) {
newData.entries.forEach { entry ->
entry.value.remove(oldData[entry.key])
base.getOrPut(entry.key) { MutableIndexingUrlSourceRootHolder() }.addRoots(entry.value)
}
}
private fun <E : WorkspaceEntity> loadRegistrarData(rootData: RootData<E>) {
rootData.moduleContents.entries.forEach { entry ->
moduleRoots.getOrPut(entry.key) { MutableIndexingUrlRootHolder() }.addRoots(entry.value)
}
for ((module, entityReferences) in rootData.customizedModuleContentEntities.entrySet()) {
for (entityReference in entityReferences) {
val roots = rootData.customizedModuleContentRoots[entityReference]
if (roots?.isEmpty() != false) continue
descriptions.add(
EntityContentRootsCustomizedModuleAwareDescription(module, entityReference, roots, rootData.customizationValues[entityReference]))
}
}
for (entry in rootData.contentRoots.entries) {
descriptions.add(EntityGenericContentRootsDescription(entry.key, entry.value, rootData.customizationValues[entry.key]))
}
for ((libraryEntity, roots) in rootData.libraryRoots.entries) {
descriptions.add(LibraryRootsDescription(libraryEntity, roots))
}
for ((libraryEntity, roots) in rootData.libraryUrlRoots.entries) {
descriptions.add(LibraryUrlRootsDescription(libraryEntity, roots))
}
for ((entityReference, roots) in rootData.externalRoots.entries) {
descriptions.add(EntityExternalRootsDescription(entityReference, roots, rootData.customizationValues[entityReference]))
}
for ((entityReference, roots) in rootData.customKindRoots.entries) {
descriptions.add(EntityCustomKindRootsDescription(entityReference, roots, rootData.customizationValues[entityReference]))
}
reincludedRoots.addAll(rootData.excludedRoots)
}
fun createBuilders(project: Project): Collection<IndexableIteratorBuilder> {
val builders = mutableListOf<IndexableIteratorBuilder>()
for (entry in moduleRoots.entries) {
builders.addAll(forModuleRootsFileBased((entry.key as ModuleBridge).moduleEntityId, entry.value))
}
for (description in descriptions) {
builders.addAll(description.createBuilders())
}
builders.addAll(ReincludedRootsUtil.createBuildersForReincludedFiles(project, reincludedRoots))
return builders
}
data class Iterators(val contentIterators: List<IndexableFilesIterator>,
val externalIterators: List<IndexableFilesIterator>,
val customIterators: List<IndexableFilesIterator>)
fun getIteratorsFromRoots(libraryOriginsToFilterDuplicates: MutableSet<IndexableSetOrigin>,
storage: EntityStorage): Iterators {
val contentIterators = mutableListOf<IndexableFilesIterator>()
for ((module, roots) in moduleRoots.entries) {
contentIterators.addAll(IndexableEntityProviderMethods.createIterators(module, roots))
}
val externalIterators = mutableListOf<IndexableFilesIterator>()
val customIterators = mutableListOf<IndexableFilesIterator>()
for (description in descriptions) {
when (description) {
is EntityContentRootsCustomizedModuleAwareDescription<*> -> contentIterators.addAll(description.createIterators())
is EntityGenericContentRootsDescription<*> -> contentIterators.addAll(description.createIterators())
is LibraryRootsDescription -> {
description.createIterators(storage).forEach { iterator ->
if (libraryOriginsToFilterDuplicates.add(iterator.origin)) {
externalIterators.add(iterator)
}
}
}
is LibraryUrlRootsDescription -> {
description.createIterators(storage).forEach { iterator ->
if (libraryOriginsToFilterDuplicates.add(iterator.origin)) {
externalIterators.add(iterator)
}
}
}
is EntityExternalRootsDescription<*> -> externalIterators.addAll(description.createIterators())
is EntityCustomKindRootsDescription<*> -> customIterators.addAll(description.createIterators())
}
}
return Iterators(contentIterators, externalIterators, customIterators)
}
fun <E : WorkspaceEntity> registerEntitiesFromContributor(contributor: WorkspaceFileIndexContributor<E>,
entityStorage: EntityStorage) {
entityStorage.entities(contributor.entityClass).forEach { entity ->
registerAddedEntity(entity, contributor, entityStorage)
}
}
fun forEachModuleContentEntitiesRoots(consumer: Consumer<IndexingUrlRootHolder>) {
for (entry in moduleRoots.entries) {
consumer.accept(entry.value)
}
}
fun forEachContentEntitiesRoots(consumer: Consumer<IndexingUrlRootHolder>) {
for (description in descriptions) {
if (description is EntityGenericContentRootsDescription<*>) {
consumer.accept(description.roots)
}
}
}
fun forEachExternalEntitiesRoots(consumer: Consumer<IndexingUrlSourceRootHolder>) {
for (description in descriptions) {
if (description is EntityExternalRootsDescription<*>) {
consumer.accept(description.urlRoots)
}
}
}
companion object {
@JvmOverloads
fun registerEntitiesFromContributors(entityStorage: EntityStorage,
settings: Settings = Settings.DEFAULT): WorkspaceIndexingRootsBuilder {
val builder = WorkspaceIndexingRootsBuilder(!settings.collectExplicitRootsForModules)
for (contributor in WorkspaceFileIndexImpl.EP_NAME.extensionList) {
ProgressManager.checkCanceled()
if (settings.shouldIgnore(contributor)) {
continue
}
builder.registerEntitiesFromContributor(contributor, entityStorage)
}
return builder
}
internal class Settings {
companion object {
val DEFAULT: Settings = Settings()
init {
DEFAULT.retainCondition = Condition<WorkspaceFileIndexContributor<*>> { contributor -> contributor.storageKind == EntityStorageKind.MAIN }
}
}
var retainCondition: Condition<WorkspaceFileIndexContributor<*>>? = null
var collectExplicitRootsForModules: Boolean = true
fun shouldIgnore(contributor: WorkspaceFileIndexContributor<*>): Boolean {
val condition = retainCondition
return condition != null && !condition.value(contributor)
}
}
}
}
private class RootData<E : WorkspaceEntity>(val contributor: WorkspaceFileIndexContributor<E>,
val ignoreModuleRoots: Boolean) {
val moduleContents = mutableMapOf<Module, MutableIndexingUrlRootHolder>()
val customizedModuleContentEntities = MultiMap<Module, EntityPointer<E>>()
val customizedModuleContentRoots = mutableMapOf<EntityPointer<E>, MutableIndexingUrlRootHolder>()
val contentRoots = mutableMapOf<EntityPointer<E>, MutableIndexingUrlRootHolder>()
val libraryUrlRoots = mutableMapOf<LibraryEntity, MutableIndexingUrlSourceRootHolder>()
val libraryRoots = mutableMapOf<LibraryEntity, MutableIndexingSourceRootHolder>()
val externalRoots = mutableMapOf<EntityPointer<E>, MutableIndexingUrlSourceRootHolder>()
val customKindRoots = mutableMapOf<EntityPointer<E>, MutableIndexingUrlRootHolder>()
val excludedRoots = mutableListOf<VirtualFile>()
val customizationValues = mutableMapOf<EntityPointer<*>, IndexableIteratorPresentation>()
private fun fillCustomizationValues(entity: E, entityPointer: EntityPointer<E>) {
if (contributor.entityClass.isAssignableFrom(entity.getEntityInterface())) {
if (contributor is CustomizingIndexingPresentationContributor<E>) {
contributor.customizeIteratorPresentation(entity)?.let { customizationValues[entityPointer] = it }
}
}
else {
thisLogger().error("Entity $entity is registered from WorkspaceFileIndexContributor $contributor of other class")
}
}
fun registerFileSet(root: VirtualFileUrl,
kind: WorkspaceFileKind,
entity: E,
customData: WorkspaceFileSetData?,
recursive: Boolean) {
val entityReference = entity.createPointer<E>()
fillCustomizationValues(entity, entityReference)
fun <K> addRoot(map: MutableMap<K, MutableIndexingUrlRootHolder>, key: K) {
val holder = map.getOrPut(key) { MutableIndexingUrlRootHolder() }
(if (recursive) holder.roots else holder.nonRecursiveRoots).add(root)
}
fun <K> addRoot(map: MutableMap<K, MutableIndexingUrlSourceRootHolder>, key: K, sourceRoot: Boolean) {
val holder = map.getOrPut(key) { MutableIndexingUrlSourceRootHolder() }
if (sourceRoot) {
(if (recursive) holder.sourceRoots else holder.nonRecursiveSourceRoots).add(root)
}
else {
(if (recursive) holder.roots else holder.nonRecursiveRoots).add(root)
}
}
if (customData is ModuleRelatedRootData) {
if (!ignoreModuleRoots) {
if (contributor is CustomizingIndexingPresentationContributor<E>) {
customizedModuleContentEntities.putValue(customData.module, entityReference)
addRoot(customizedModuleContentRoots, entityReference)
}
else {
addRoot(moduleContents, customData.module)
}
}
}
else if (kind.isContent) {
addRoot(contentRoots, entityReference)
}
else if (contributor is LibraryRootFileIndexContributor) {
addRoot(libraryUrlRoots, entity as LibraryEntity, kind === WorkspaceFileKind.EXTERNAL_SOURCE)
}
else if (kind == WorkspaceFileKind.CUSTOM) {
addRoot(customKindRoots, entityReference, )
}
else {
addRoot(externalRoots, entityReference, kind === WorkspaceFileKind.EXTERNAL_SOURCE)
}
}
fun registerFileSet(root: VirtualFile,
kind: WorkspaceFileKind,
entity: WorkspaceEntity,
recursive: Boolean) {
thisLogger().assertTrue(contributor is LibraryRootFileIndexContributor,
"Registering VirtualFile roots is not supported, register VirtualFileUrl from $contributor instead")
if (contributor !is LibraryRootFileIndexContributor) {
return
}
val holder = libraryRoots.getOrPut(entity as LibraryEntity) { MutableIndexingSourceRootHolder() }
if (kind === WorkspaceFileKind.EXTERNAL_SOURCE) {
(if (recursive) holder.sourceRoots else holder.nonRecursiveSourceRoots).add(root)
}
else {
(if (recursive) holder.roots else holder.nonRecursiveRoots).add(root)
}
}
fun registerExcludedRoot(root: VirtualFile) {
excludedRoots.add(root)
}
fun registerExcludedRoot(root: VirtualFileUrl) {
root.virtualFile?.let { excludedRoots.add(it) }
}
fun cleanIncludedRoots() {
moduleContents.clear()
customizedModuleContentRoots.clear()
customizedModuleContentEntities.clear()
contentRoots.clear()
libraryUrlRoots.clear()
libraryRoots.clear()
externalRoots.clear()
customKindRoots.clear()
customizationValues.clear()
}
fun cleanExcludedRoots() {
excludedRoots.clear()
}
}
private class MyWorkspaceFileSetRegistrar<E : WorkspaceEntity>(contributor: WorkspaceFileIndexContributor<E>,
ignoreModuleRoots: Boolean) : WorkspaceFileSetRegistrar {
val rootData: RootData<E> = RootData(contributor, ignoreModuleRoots)
override fun registerFileSet(root: VirtualFileUrl, kind: WorkspaceFileKind, entity: WorkspaceEntity, customData: WorkspaceFileSetData?) {
@Suppress("UNCHECKED_CAST")
rootData.registerFileSet(root, kind, entity as E, customData, true)
}
override fun registerFileSet(root: VirtualFile, kind: WorkspaceFileKind, entity: WorkspaceEntity, customData: WorkspaceFileSetData?) {
rootData.registerFileSet(root, kind, entity, true)
}
override fun registerExcludedRoot(excludedRoot: VirtualFileUrl, entity: WorkspaceEntity) {
rootData.registerExcludedRoot(excludedRoot)
}
override fun registerExcludedRoot(excludedRoot: VirtualFile, excludedFrom: WorkspaceFileKind, entity: WorkspaceEntity) {
rootData.registerExcludedRoot(excludedRoot)
}
override fun registerExcludedRoot(excludedRoot: VirtualFileUrl, excludedFrom: WorkspaceFileKind, entity: WorkspaceEntity) {
rootData.registerExcludedRoot(excludedRoot)
}
override fun registerExclusionPatterns(root: VirtualFileUrl, patterns: List<String>, entity: WorkspaceEntity) {
rootData.registerExcludedRoot(root)
}
override fun registerExclusionCondition(root: VirtualFileUrl, condition: (VirtualFile) -> Boolean, entity: WorkspaceEntity) {
rootData.registerExcludedRoot(root)
}
override fun registerExclusionCondition(root: VirtualFile, condition: (VirtualFile) -> Boolean, entity: WorkspaceEntity) {
rootData.registerExcludedRoot(root)
}
override fun registerNonRecursiveFileSet(file: VirtualFileUrl,
kind: WorkspaceFileKind,
entity: WorkspaceEntity,
customData: WorkspaceFileSetData?) {
@Suppress("UNCHECKED_CAST")
rootData.registerFileSet(file, kind, entity as E, customData, false)
}
}
| 284
| null |
5162
| 2
|
b07eabd319ad5b591373d63c8f502761c2b2dfe8
| 25,851
|
intellij-community
|
Apache License 2.0
|
messaginginapp/src/test/java/io/customer/messaginginapp/testutils/extension/GistExtensions.kt
|
customerio
| 355,691,391
| false
|
{"Kotlin": 563876, "Shell": 10050, "Makefile": 1568, "Ruby": 257}
|
package io.customer.messaginginapp.testutils.extension
import android.util.Base64
import com.google.gson.JsonParser
import io.customer.commontest.extensions.random
import io.customer.messaginginapp.gist.data.model.Message
import io.customer.messaginginapp.type.InAppMessage
import io.customer.messaginginapp.type.getMessage
import java.util.UUID
fun getNewRandomMessage(): Message = InAppMessage(String.random, String.random, String.random).getMessage()
fun mapToInAppMessage(message: Message): InAppMessage = InAppMessage.getFromGistMessage(gistMessage = message)
fun pageRuleContains(route: String): String = "^(.*$route.*)\$"
fun pageRuleEquals(route: String): String = "^($route)\$"
fun decodeOptionsString(options: String): Message {
val decodedOptions = String(Base64.decode(options, Base64.DEFAULT), Charsets.UTF_8)
val decodedMessage = JsonParser().parse(decodedOptions).asJsonObject
return Message(
messageId = decodedMessage["messageId"].asString,
instanceId = decodedMessage["instanceId"].asString,
priority = decodedMessage["priority"]?.asInt,
queueId = decodedMessage["queueId"]?.asString
)
}
fun createInAppMessage(
messageId: String = UUID.randomUUID().toString(),
campaignId: String? = "test_campaign_id",
queueId: String? = "test_queue_id",
position: String? = "center",
priority: Int? = null,
pageRule: String? = null
): Message = Message(
messageId = messageId,
queueId = queueId,
priority = priority,
properties = buildMap {
put(
"gist",
buildMap {
campaignId?.let { value -> put("campaignId", value) }
pageRule?.let { value -> put("routeRuleAndroid", value) }
position?.let { value -> put("position", value) }
}
)
}
)
| 8
|
Kotlin
|
9
| 13
|
0f20226f294f7dde38121585cc69c5fdfdfbb543
| 1,838
|
customerio-android
|
MIT License
|
data/src/main/java/com/yapp/bol/data/model/file/ImageFileUploadResponse.kt
|
onboard-github
| 704,021,246
| false
|
{"Kotlin": 462718}
|
package com.yapp.bol.data.model.file
data class ImageFileUploadResponse(
val uuid: String,
val url: String,
)
| 1
|
Kotlin
|
0
| 0
|
cb84e105e69d1e885e9b6b29ba007e192e36c403
| 119
|
onboard-aos
|
Apache License 2.0
|
backend/src/main/kotlin/metrik/project/domain/service/buddy/BuddyDTO.kt
|
thoughtworks
| 351,856,572
| false
|
{"Kotlin": 554181, "TypeScript": 146367, "Shell": 6226, "JavaScript": 6197, "Dockerfile": 2452, "HTML": 354, "Less": 341}
|
package metrik.project.domain.service.buddy
import metrik.infrastructure.utlils.toTimestamp
import java.time.Duration
import java.time.OffsetDateTime
data class ProjectDTO(
val name: String = "",
val status: String = ""
)
data class PipelineDTO(
val id: Int = 0,
val project: ProjectDTO = ProjectDTO(),
)
data class ActionDTO(
val name: String = ""
)
data class CommitDTO(
val revision: String = "",
val commitDate: OffsetDateTime = OffsetDateTime.MIN
) {
fun getTimestamp(): Long = commitDate.toTimestamp()
fun getDateString(): String = commitDate.toString()
}
data class ChangeSetDTO(
val commits: List<CommitDTO> = emptyList()
)
data class ActionExecutionDTO(
val status: String = "",
val startDate: OffsetDateTime? = null,
val finishDate: OffsetDateTime? = null,
val action: ActionDTO = ActionDTO()
) {
fun getDuration(): Long = if (startDate != null && finishDate != null)
Duration.between(startDate, finishDate).toMillis() else 0
fun getTimestamp(): Long = startDate?.let { it.toTimestamp() } ?: 0
}
data class ExecutionInfoDTO(
val id: Long = 0,
val url: String = "",
val status: String = "",
val branch: BranchDTO = BranchDTO(),
val startDate: OffsetDateTime = OffsetDateTime.MIN,
val finishDate: OffsetDateTime? = null,
val toRevision: CommitDTO? = null,
val fromRevision: CommitDTO? = null
) {
fun getDuration(): Long = finishDate?.let { Duration.between(startDate, it).toMillis() } ?: 0
fun getTimestamp(): Long = startDate.toTimestamp()
}
data class BranchDTO(val name: String = "")
data class ExecutionPageDTO(
val page: Int = 1,
val pageSize: Int = 20,
val totalPageCount: Int = 1,
val elementCount: Int = 0,
val totalElementCount: Int = 0,
val executions: List<ExecutionInfoDTO> = emptyList()
)
data class ExecutionDetailsDTO(
val actionExecutions: List<ActionExecutionDTO> = emptyList()
)
| 19
|
Kotlin
|
86
| 348
|
def6a52cb7339f6a422451710083177b9c79689a
| 1,957
|
metrik
|
MIT License
|
main/src/test/java/com/work/theIsle/SpellBook.kt
|
Tiannuo
| 498,562,269
| false
|
{"Kotlin": 218272, "Java": 43175}
|
package com.work.theIsle
import com.work.supportlib.LoggerUtils
import java.io.IOException
import kotlin.jvm.Throws
/**
* @Author TIKOU
* @Date 2022/8/15-12:53
* @Email <EMAIL> & <EMAIL>
* @Description
*/
class SpellBook {
@JvmField()
val spells = mapOf("A" to 3, "B" to 4)
public fun spell() {
}
@JvmOverloads
public fun spellUp(a: String = "a", b: String = "b") {
LoggerUtils.i("spellUp $a & $b")
}
@Throws(IOException::class)
fun accept() {
}
}
| 0
|
Kotlin
|
2
| 4
|
bf02c12830d80c6bcf7441c50c3f685d322fdf53
| 508
|
AndroidWork
|
Apache License 2.0
|
src/main/kotlin/io/unthrottled/doki/notification/UpdateNotification.kt
|
Rand01ph
| 319,239,521
| true
|
{"Kotlin": 239136, "Shell": 284}
|
package io.unthrottled.doki.notification
import com.intellij.ide.plugins.PluginManagerCore.getPlugin
import com.intellij.ide.plugins.PluginManagerCore.getPluginOrPlatformByClassName
import com.intellij.notification.Notification
import com.intellij.notification.NotificationDisplayType
import com.intellij.notification.NotificationGroup
import com.intellij.notification.NotificationListener
import com.intellij.notification.NotificationType
import com.intellij.notification.impl.NotificationsManagerImpl
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.popup.Balloon
import com.intellij.openapi.wm.WindowManager
import com.intellij.ui.BalloonLayoutData
import com.intellij.ui.IconManager
import com.intellij.ui.awt.RelativePoint
import io.unthrottled.doki.themes.ThemeManager
import org.jetbrains.annotations.Nls
import java.awt.Point
val UPDATE_MESSAGE: String = """
What's New?<br>
<ul>
<li>Added Miss Kobayashi's Dragon Maid's: Kanna!
<ul>
<li>A cute dark Theme & 2 stickers</li>
</ul>
</li>
<li>Small consistency fixes.</li>
</ul>
Please see the <a href="https://github.com/doki-theme/doki-theme-jetbrains/blob/master/changelog/CHANGELOG.md">changelog</a> for more details.
<br><br>
Did you the <b>Doki Theme</b> is available <a href='https://github.com/doki-theme'>on other platforms?</a>
<br><br>
Thanks for downloading!
<br><br>
<img alt='Thanks for downloading!' src="https://doki.assets.unthrottled.io/misc/update_celebration.gif" width='256'>
<br><br><br><br><br><br><br><br>
Thanks!
""".trimIndent()
object UpdateNotification {
private val NOTIFICATION_ICON = IconManager.getInstance().getIcon(
"/icons/doki/Doki-Doki-Logo.svg",
UpdateNotification::class.java
)
private val notificationGroup = NotificationGroup(
"Doki Theme Updates",
NotificationDisplayType.BALLOON,
false,
"Doki Theme Updates",
NOTIFICATION_ICON
)
private val defaultListener = NotificationListener.UrlOpeningListener(false)
private fun showDokiNotification(
@Nls(capitalization = Nls.Capitalization.Sentence) title: String = "",
@Nls(capitalization = Nls.Capitalization.Sentence) content: String,
project: Project? = null,
listener: NotificationListener? = defaultListener
) {
notificationGroup.createNotification(
title, content,
listener = listener
).setIcon(NOTIFICATION_ICON)
.notify(project)
}
fun sendMessage(
title: String,
message: String,
project: Project? = null
) {
showDokiNotification(
title,
message,
project = project,
listener = defaultListener
)
}
fun display(
project: Project,
newVersion: String
) {
val pluginName =
getPlugin(
getPluginOrPlatformByClassName(UpdateNotification::class.java.canonicalName)
)?.name
showNotification(
project,
notificationGroup.createNotification(
"$pluginName updated to v$newVersion",
UPDATE_MESSAGE,
NotificationType.INFORMATION
)
.setListener(NotificationListener.UrlOpeningListener(false))
.setIcon(NOTIFICATION_ICON)
)
}
private fun showNotification(
project: Project,
updateNotification: Notification
) {
try {
val ideFrame =
WindowManager.getInstance().getIdeFrame(project) ?: WindowManager.getInstance().allProjectFrames.first()
val frameBounds = ideFrame.component.bounds
val notificationPosition = RelativePoint(ideFrame.component, Point(frameBounds.x + frameBounds.width, 20))
val balloon = NotificationsManagerImpl.createBalloon(
ideFrame,
updateNotification,
true,
false,
BalloonLayoutData.fullContent(),
ThemeManager.instance
)
balloon.show(notificationPosition, Balloon.Position.atLeft)
} catch (e: Throwable) {
updateNotification.notify(project)
}
}
fun displayRestartMessage() {
showDokiNotification(
"Please restart your IDE",
"In order for the change to take effect, please restart your IDE. Thanks! ~"
)
}
fun displayFileColorInstallMessage() {
showDokiNotification(
"File Colors Installed",
"""File colors will remain in your IDE after uninstalling the plugin.
|To remove them, un-check this action or remove them at "Settings -> Appearance -> File Colors".
""".trimMargin()
)
}
fun displayAnimationInstallMessage() {
showDokiNotification(
"Theme Transition Animation Enabled",
"""The animations will remain in your IDE after uninstalling the plugin.
|To remove them, un-check this action or toggle the action at "Help -> Find Action -> ide.intellij.laf.enable.animation".
""".trimMargin()
)
}
fun displayReadmeInstallMessage() {
showDokiNotification(
"README.md will not show on startup",
"""This behavior will remain in your IDE after uninstalling the plugin.
|To re-enable it, un-check this action or toggle the action at "Help -> Find Action -> ide.open.readme.md.on.startup".
""".trimMargin()
)
}
}
| 0
| null |
0
| 0
|
6b7d7d729122e7fb771e5710a315d86af03dc395
| 5,238
|
doki-theme-jetbrains
|
MIT License
|
app/src/main/java/com/boreal/ultimatetest/modules/locations/data/DefaultLocationsRepository.kt
|
baudelioandalon
| 853,655,370
| false
|
{"Kotlin": 129014}
|
package com.boreal.ultimatetest.modules.locations.data
import com.boreal.ultimatetest.modules.locations.data.get_locations.GetListLocationsDataSource
import com.boreal.ultimatetest.modules.locations.domain.interfaces.LocationsRepository
import kotlinx.coroutines.flow.flow
import javax.inject.Inject
class DefaultLocationsRepository @Inject constructor(private val getListLocationsDataSource: GetListLocationsDataSource) :
LocationsRepository {
override suspend fun executeGetListLocations() = flow {
emit(getListLocationsDataSource.executeGetListLocations())
}
override suspend fun executeGetMoreLocations(page: Int) = flow {
emit(getListLocationsDataSource.executeGetMoreLocations(page))
}
}
| 0
|
Kotlin
|
0
| 0
|
29d5733fb3b9949665ef0da28df9bfc4c8b69b7d
| 733
|
UltimateTest
|
Apache License 2.0
|
retrofit/src/main/java/com/xmartlabs/bigbang/retrofit/helper/ServiceErrorHandler.kt
|
xmartlabs
| 50,346,596
| false
|
{"Kotlin": 232568, "Shell": 834}
|
package com.xmartlabs.bigbang.retrofit.helper
import com.xmartlabs.bigbang.core.helper.GeneralErrorHelper
import com.xmartlabs.bigbang.core.helper.ServiceHelper
import com.xmartlabs.bigbang.core.log.LoggerTree
import com.xmartlabs.bigbang.retrofit.exception.ServiceExceptionWithMessage
import retrofit2.HttpException
import java.util.HashMap
import javax.inject.Inject
/**
* Handles [HttpException] and [ServiceExceptionWithMessage] exceptions emitted by the
* [GeneralErrorHelper].
*/
class ServiceErrorHandler @Inject constructor() {
companion object {
private val LOGGER_KEY_RESPONSE_BODY = "response_body"
private val LOGGER_KEY_RESPONSE_HEADERS = "response_headers"
private val LOGGER_KEY_STATUS_CODE = "status_code"
private val LOGGER_KEY_URL = "url"
}
@Inject
internal lateinit var generalErrorHelper: GeneralErrorHelper
@Inject
internal lateinit var loggerTree: LoggerTree
private val serviceErrorHandler = { serviceException: Throwable ->
val exception = serviceException as ServiceExceptionWithMessage
val information = HashMap<String, String>()
information.put(LOGGER_KEY_URL, ServiceHelper.getUrl(exception.response.raw()))
information.put(LOGGER_KEY_STATUS_CODE, exception.code.toString())
information.put(LOGGER_KEY_RESPONSE_HEADERS, exception.response.headers().toString())
information.put(LOGGER_KEY_RESPONSE_BODY, exception.errorBody ?: "")
loggerTree.log(information, exception)
}
/**
* Handles the [HttpException] and [ServiceExceptionWithMessage] exceptions, logging them if any error
* is present.
*/
fun handleServiceErrors() {
generalErrorHelper.setErrorHandlerForThrowable(ServiceExceptionWithMessage::class) { ex -> serviceErrorHandler(ex) }
val handler: (Throwable) -> Unit = { throwable ->
when (throwable) {
is HttpException -> serviceErrorHandler(ServiceExceptionWithMessage(throwable))
}
}
generalErrorHelper.setErrorHandlerForThrowable(HttpException::class, handler)
generalErrorHelper.setErrorHandlerForThrowable(retrofit2.adapter.rxjava2.HttpException::class, handler)
}
}
| 1
|
Kotlin
|
11
| 51
|
74827bec72f607d909fcc923f53cf19d0152e732
| 2,145
|
bigbang
|
Apache License 2.0
|
analysis/analysis-api/src/org/jetbrains/kotlin/analysis/api/renderer/declarations/modifiers/renderers/KtModifiersFilter.kt
|
JetBrains
| 3,432,266
| false
| null |
/*
* Copyright 2010-2022 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.analysis.api.renderer.declarations.modifiers.renderers
import com.intellij.psi.tree.TokenSet
import org.jetbrains.kotlin.analysis.api.KtAnalysisSession
import org.jetbrains.kotlin.analysis.api.symbols.KtDeclarationSymbol
import org.jetbrains.kotlin.lexer.KtModifierKeywordToken
public interface KtRendererModifierFilter {
context(KtAnalysisSession)
public fun filter(modifier: KtModifierKeywordToken, symbol: KtDeclarationSymbol): Boolean
public infix fun and(other: KtRendererModifierFilter): KtRendererModifierFilter {
val self = this
return KtRendererModifierFilter { modifier, symbol ->
self.filter(modifier, symbol) && other.filter(modifier, symbol)
}
}
public infix fun or(other: KtRendererModifierFilter): KtRendererModifierFilter {
val self = this
return KtRendererModifierFilter { modifier, symbol ->
self.filter(modifier, symbol) || other.filter(modifier, symbol)
}
}
public object ALL : KtRendererModifierFilter {
context(KtAnalysisSession)
override fun filter(modifier: KtModifierKeywordToken, symbol: KtDeclarationSymbol): Boolean {
return true
}
}
public object NONE : KtRendererModifierFilter {
context(KtAnalysisSession)
override fun filter(modifier: KtModifierKeywordToken, symbol: KtDeclarationSymbol): Boolean {
return false
}
}
public companion object {
public operator fun invoke(
predicate: context(KtAnalysisSession)(modifier: KtModifierKeywordToken, symbol: KtDeclarationSymbol) -> Boolean
): KtRendererModifierFilter =
object : KtRendererModifierFilter {
context(KtAnalysisSession)
override fun filter(modifier: KtModifierKeywordToken, symbol: KtDeclarationSymbol): Boolean {
return predicate(this@KtAnalysisSession, modifier, symbol)
}
}
public fun onlyWith(vararg modifiers: KtModifierKeywordToken): KtRendererModifierFilter =
KtRendererModifierFilter { modifier, _ -> modifier in modifiers }
public fun onlyWith(modifiers: TokenSet): KtRendererModifierFilter =
KtRendererModifierFilter { modifier, _ -> modifier in modifiers }
public fun without(vararg modifiers: KtModifierKeywordToken): KtRendererModifierFilter =
KtRendererModifierFilter { modifier, _ -> modifier !in modifiers }
public fun without(modifiers: TokenSet): KtRendererModifierFilter =
KtRendererModifierFilter { modifier, _ -> modifier !in modifiers }
}
}
| 154
|
Kotlin
|
5566
| 45,025
|
8a69904d02dd3e40fae5f2a1be4093d44a227788
| 2,892
|
kotlin
|
Apache License 2.0
|
core/domain/src/main/kotlin/com/merxury/blocker/core/domain/UpdateRuleMatchedAppUseCase.kt
|
lihenggui
| 115,417,337
| false
| null |
/*
* Copyright 2023 Blocker
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.merxury.blocker.core.domain
import com.merxury.blocker.core.data.respository.app.AppRepository
import com.merxury.blocker.core.data.respository.component.ComponentRepository
import com.merxury.blocker.core.data.respository.generalrule.GeneralRuleRepository
import com.merxury.blocker.core.data.respository.userdata.UserDataRepository
import com.merxury.blocker.core.dispatchers.BlockerDispatchers.IO
import com.merxury.blocker.core.dispatchers.Dispatcher
import com.merxury.blocker.core.model.data.ComponentInfo
import com.merxury.blocker.core.model.data.GeneralRule
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import timber.log.Timber
import javax.inject.Inject
class UpdateRuleMatchedAppUseCase @Inject constructor(
private val generalRuleRepository: GeneralRuleRepository,
private val userDataRepository: UserDataRepository,
private val componentRepository: ComponentRepository,
private val appRepository: AppRepository,
@Dispatcher(IO) private val ioDispatcher: CoroutineDispatcher,
) {
operator fun invoke(rule: GeneralRule): Flow<Unit> = flow {
val userData = userDataRepository.userData.first()
val matchedComponents = mutableListOf<ComponentInfo>()
rule.searchKeyword.forEach { keyword ->
val components = componentRepository.searchComponent(keyword).first()
matchedComponents.addAll(components)
}
val matchedGroup = matchedComponents.groupBy { it.packageName }
.toMutableMap()
// Copy one list to avoid concurrent modification
val matchedPackages = matchedGroup.keys.toMutableList()
if (!userData.showSystemApps) {
matchedPackages.forEach { packageName ->
val appInfo = appRepository.getApplication(packageName).first()
?: return@forEach
if (appInfo.isSystem) {
matchedGroup.remove(packageName)
}
}
}
val updatedRule = rule.copy(matchedAppCount = matchedGroup.keys.size)
Timber.v("Updated rule: ${updatedRule.name}, count = ${updatedRule.matchedAppCount}")
generalRuleRepository.saveGeneralRule(updatedRule)
emit(Unit)
}
.flowOn(ioDispatcher)
}
| 25
| null |
54
| 988
|
9696c391c64d1aa4a74384d22b4433fb7c67c890
| 2,999
|
blocker
|
Apache License 2.0
|
client/src/main/java/org/phoenixframework/liveview/ui/modifiers/Actions.kt
|
liveview-native
| 459,214,950
| false
|
{"Kotlin": 2229783, "Elixir": 104334, "ANTLR": 4846}
|
package org.phoenixframework.liveview.ui.modifiers
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.selection.toggleable
import androidx.compose.foundation.selection.triStateToggleable
import androidx.compose.ui.Modifier
import androidx.compose.ui.semantics.Role
import org.phoenixframework.liveview.data.constants.ModifierArgs.argEnabled
import org.phoenixframework.liveview.data.constants.ModifierArgs.argOnClick
import org.phoenixframework.liveview.data.constants.ModifierArgs.argOnClickLabel
import org.phoenixframework.liveview.data.constants.ModifierArgs.argOnDoubleClick
import org.phoenixframework.liveview.data.constants.ModifierArgs.argOnLongClick
import org.phoenixframework.liveview.data.constants.ModifierArgs.argOnLongClickLabel
import org.phoenixframework.liveview.data.constants.ModifierArgs.argOnValueChange
import org.phoenixframework.liveview.data.constants.ModifierArgs.argRole
import org.phoenixframework.liveview.data.constants.ModifierArgs.argSelected
import org.phoenixframework.liveview.data.constants.ModifierArgs.argState
import org.phoenixframework.liveview.data.constants.ModifierArgs.argValue
import org.phoenixframework.liveview.ui.base.ComposableBuilder
import org.phoenixframework.liveview.ui.base.PushEvent
import org.phoenixframework.liveview.ui.view.onClickFromString
fun Modifier.clickableFromStyle(
arguments: List<ModifierDataAdapter.ArgumentData>,
pushEvent: PushEvent?
): Modifier {
val args = argsOrNamedArgs(arguments)
val enabled: Boolean?
val onClickLabel: String?
val role: Role?
val event: Pair<String, Any?>?
// If we pass just one param, it's the clickable function
if (args.size == 1) {
enabled = true
onClickLabel = null
role = null
event = argOrNamedArg(args, argOnClick, 0)?.let { eventFromArgument(it) }
} else {
enabled = argOrNamedArg(args, argEnabled, 0)?.booleanValue
onClickLabel = argOrNamedArg(args, argOnClickLabel, 1)?.stringValue
role = argOrNamedArg(args, argRole, 2)?.let { roleFromArgument(it) }
event = argOrNamedArg(args, argOnClick, 3)?.let { eventFromArgument(it) }
}
return event?.let {
this.then(
Modifier.clickable(
enabled = enabled ?: true,
onClickLabel = onClickLabel,
role = role,
onClick = {
val (eventName, eventArgs) = it
val clickFunction = onClickFromString(pushEvent, eventName, eventArgs)
clickFunction.invoke()
}
)
)
} ?: this
}
// combinedClickable lets you add double tap or long-press behavior (not both at the same time)
// in addition to normal click behavior.
@OptIn(ExperimentalFoundationApi::class)
fun Modifier.combinedClickableFromStyle(
arguments: List<ModifierDataAdapter.ArgumentData>,
pushEvent: PushEvent?
): Modifier {
val args = argsOrNamedArgs(arguments)
val enabled: Boolean?
val onClickLabel: String?
val onLongClickLabel: String?
val role: Role?
val onClickEvent: Pair<String, Any?>?
val onLongClickEvent: Pair<String, Any?>?
val onDoubleClickEvent: Pair<String, Any?>?
// If we pass just one param, it's the clickable function
if (args.size == 1) {
enabled = true
onClickLabel = null
role = null
onLongClickLabel = null
onLongClickEvent = null
onDoubleClickEvent = null
onClickEvent = argOrNamedArg(args, argOnClick, 0)?.let { eventFromArgument(it) }
} else {
enabled = argOrNamedArg(args, argEnabled, 0)?.booleanValue
onClickLabel = argOrNamedArg(args, argOnClickLabel, 1)?.stringValue
role = argOrNamedArg(args, argRole, 2)?.let { roleFromArgument(it) }
onLongClickLabel = argOrNamedArg(args, argOnLongClickLabel, 3)?.stringValue
onLongClickEvent = argOrNamedArg(args, argOnLongClick, 4)?.let { eventFromArgument(it) }
onDoubleClickEvent = argOrNamedArg(args, argOnDoubleClick, 5)?.let { eventFromArgument(it) }
onClickEvent = argOrNamedArg(args, argOnClick, 6)?.let { eventFromArgument(it) }
}
return onClickEvent?.let { clickEvent ->
this.then(
Modifier.combinedClickable(
enabled = enabled ?: true,
onClickLabel = onClickLabel,
role = role,
onLongClickLabel = onLongClickLabel,
onLongClick = onLongClickEvent?.let { onLongClick ->
{
val (eventName, eventArgs) = onLongClick
if (eventName.isNotEmpty()) {
pushEvent?.invoke(
ComposableBuilder.EVENT_TYPE_LONG_CLICK,
eventName,
eventArgs,
null
)
}
}
},
onDoubleClick = onDoubleClickEvent?.let { onDoubleClick ->
{
val (eventName, eventArgs) = onDoubleClick
if (eventName.isNotEmpty()) {
pushEvent?.invoke(
ComposableBuilder.EVENT_TYPE_DOUBLE_CLICK,
eventName,
eventArgs,
null
)
}
}
},
onClick = {
val (eventName, eventArgs) = clickEvent
val clickFunction = onClickFromString(pushEvent, eventName, eventArgs)
clickFunction.invoke()
},
)
)
} ?: this
}
fun Modifier.selectableFromStyle(
arguments: List<ModifierDataAdapter.ArgumentData>,
pushEvent: PushEvent?
): Modifier {
val args = argsOrNamedArgs(arguments)
val selected = argOrNamedArg(args, argSelected, 0)?.booleanValue
val enabled = argOrNamedArg(args, argEnabled, 1)?.booleanValue ?: true
val role = argOrNamedArg(args, argRole, 2)?.let { roleFromArgument(it) }
val event = argOrNamedArg(args, argOnClick, 3)?.let { eventFromArgument(it) }
return if (event != null && selected != null) {
Modifier.selectable(
selected = selected,
enabled = enabled,
role = role,
onClick = {
val (eventName, eventArgs) = event
val clickFunction = onClickFromString(pushEvent, eventName, eventArgs)
clickFunction.invoke()
}
)
} else this
}
fun Modifier.toggleableFromStyle(
arguments: List<ModifierDataAdapter.ArgumentData>,
pushEvent: PushEvent?
): Modifier {
val args = argsOrNamedArgs(arguments)
val value = argOrNamedArg(args, argValue, 0)?.booleanValue
val enabled = argOrNamedArg(args, argEnabled, 1)?.booleanValue ?: true
val role = argOrNamedArg(args, argRole, 2)?.let { roleFromArgument(it) }
val event = argOrNamedArg(args, argOnValueChange, 3)?.let { eventFromArgument(it) }
return if (event != null && value != null) {
Modifier.toggleable(
value = value,
enabled = enabled,
role = role,
onValueChange = { newValue ->
val (eventName, _) = event
if (eventName.isNotEmpty()) {
pushEvent?.invoke(
ComposableBuilder.EVENT_TYPE_CHANGE,
eventName,
newValue,
null
)
}
}
)
} else this
}
fun Modifier.triStateToggleableFromStyle(
arguments: List<ModifierDataAdapter.ArgumentData>,
pushEvent: PushEvent?
): Modifier {
val args = argsOrNamedArgs(arguments)
val state = argOrNamedArg(args, argState, 0)?.let { toggleableStateFromArgument(it) }
val enabled = argOrNamedArg(args, argEnabled, 1)?.booleanValue ?: true
val role = argOrNamedArg(args, argRole, 2)?.let { roleFromArgument(it) }
val event = argOrNamedArg(args, argOnClick, 3)?.let { eventFromArgument(it) }
return if (state != null && event != null) {
Modifier.triStateToggleable(
state = state,
enabled = enabled,
role = role,
onClick = {
val (eventName, eventArgs) = event
val clickFunction = onClickFromString(pushEvent, eventName, eventArgs)
clickFunction.invoke()
}
)
} else this
}
| 114
|
Kotlin
|
3
| 99
|
966beddce2bbf216f85b908e9ec8a43bc572433c
| 8,898
|
liveview-client-jetpack
|
MIT License
|
kotlin-mui-icons/src/main/generated/mui/icons/material/Add.kt
|
JetBrains
| 93,250,841
| false
| null |
// Automatically generated - do not modify!
@file:JsModule("@mui/icons-material/Add")
package mui.icons.material
@JsName("default")
external val Add: SvgIconComponent
| 12
| null |
5
| 983
|
a99345a0160a80a7a90bf1adfbfdc83a31a18dd6
| 170
|
kotlin-wrappers
|
Apache License 2.0
|
iteration8/music-matters/mobile/src/main/java/com/odesa/musicMatters/di/MobileDiModule.kt
|
Odhiambo-Michael-Allan
| 740,198,682
| false
|
{"Kotlin": 9540063}
|
package com.odesa.musicMatters.di
import android.content.Context
import com.odesa.musicMatters.core.common.di.CommonDiModule
import com.odesa.musicMatters.core.data.di.DataDiModule
class MobileDiModule( context: Context ) {
private val dataDiModule = DataDiModule( context )
private val commonDiModule = CommonDiModule(
context = context,
settingsRepository = dataDiModule.settingsRepository
)
val settingsRepository = dataDiModule.settingsRepository
val playlistRepository = dataDiModule.playlistRepository
val searchHistoryRepository = dataDiModule.searchHistoryRepository
val musicServiceConnection = commonDiModule.musicServiceConnection
}
| 0
|
Kotlin
|
0
| 3
|
05ad5e08002a78958ed7763e6685a0e15f635fae
| 689
|
music-matters
|
Apache License 2.0
|
sample/shared/src/commonMain/kotlin/App.kt
|
ismai117
| 738,651,050
| false
|
{"Kotlin": 51564, "Ruby": 4552, "Swift": 1167, "Shell": 579, "HTML": 573, "JavaScript": 475}
|
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import kottieComposition.KottieCompositionSpec
import kottieComposition.animateKottieCompositionAsState
import kottieComposition.rememberKottieComposition
@Composable
fun App(
modifier: Modifier = Modifier,
) {
val composition = rememberKottieComposition(
spec = KottieCompositionSpec.File("files/Animation.json")
)
var isPlaying by remember { mutableStateOf(false) }
val animationState by animateKottieCompositionAsState(
composition = composition,
iterations = 1,
isPlaying = isPlaying
)
MaterialTheme {
Column(
modifier = modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
KottieAnimation(
composition = composition,
progress = { animationState.progress },
modifier = modifier
.size(300.dp)
)
Button(
onClick = {
isPlaying = true
}
){
Text(
text = when(isPlaying){
true -> "Playing..."
false -> "Play"
}
)
}
}
}
LaunchedEffect(animationState.isPlaying){
if (animationState.isCompleted){
isPlaying = false
}
}
}
| 0
|
Kotlin
|
2
| 99
|
e2437955707dee7a549c575ec27ea8f210b42143
| 2,209
|
kottie
|
Apache License 2.0
|
src/test/resources/examples/pathLevelParameters/client/OAuth.kt
|
cjbooms
| 229,844,927
| false
| null |
package examples.okHttpClient.client
import okhttp3.Authenticator
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import okhttp3.Route
class OAuth2(val accessToken: () -> String) : Authenticator, Interceptor {
override fun authenticate(route: Route?, response: Response): Request =
response.request.newBuilder()
.header("Authorization", "Bearer ${accessToken().trim()}")
.build()
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request().newBuilder()
.header("Authorization", "Bearer ${accessToken().trim()}")
.build()
return chain.proceed(request)
}
}
| 33
|
Kotlin
|
41
| 99
|
81a003c45e518573a871621aef1a48599735c86f
| 700
|
fabrikt
|
Apache License 2.0
|
chronolens-core/src/main/kotlin/org/chronolens/core/model/ListEdit.kt
|
andreihh
| 83,168,079
| false
| null |
/*
* Copyright 2017-2021 <NAME> <<EMAIL>>
*
* 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.chronolens.core.model
/**
* An atomic change which should be applied to a list of elements.
*
* @param T the type of the elements of the edited list
*/
public sealed class ListEdit<T> {
/**
* Applies this edit on the given mutable [subject].
*
* @throws IllegalStateException if the [subject] has an invalid state and
* this edit couldn't be applied
*/
protected abstract fun applyOn(subject: MutableList<T>)
public companion object {
/**
* Applies the given [edits] on [this] list and returns the result.
*
* @throws IllegalStateException if this list has an invalid state and
* the given [edits] couldn't be applied
*/
@JvmStatic
public fun <T> List<T>.apply(edits: List<ListEdit<T>>): List<T> {
val result = toMutableList()
for (edit in edits) {
edit.applyOn(result)
}
return result
}
/** Utility method. */
@JvmStatic
public fun <T> List<T>.apply(vararg edits: ListEdit<T>): List<T> =
apply(edits.asList())
/**
* Returns the edits which should be applied on [this] list to obtain
* the [other] list.
*/
@JvmStatic
public fun <T> List<T>.diff(other: List<T>): List<ListEdit<T>> {
val objectToValue = hashMapOf<T, Int>()
val valueToObject = arrayListOf<T>()
for (it in (this + other)) {
if (it !in objectToValue) {
objectToValue[it] = valueToObject.size
valueToObject += it
}
}
val a = map(objectToValue::getValue).toIntArray()
val b = other.map(objectToValue::getValue).toIntArray()
val arrayEdits = diff(a, b)
return arrayEdits.map { edit ->
when (edit) {
is Add -> Add(edit.index, valueToObject[edit.value])
is Remove -> Remove<T>(edit.index)
}
}
}
}
/**
* Indicates that an element should be added to the edited list.
*
* @param T the type of the elements of the edited list
* @property index the index at which the element should be inserted
* @property value the element which should be added
* @throws IllegalArgumentException if [index] is negative
*/
public data class Add<T>(val index: Int, val value: T) : ListEdit<T>() {
init {
require(index >= 0) { "Can't add $value at negative index $index!" }
}
override fun applyOn(subject: MutableList<T>) {
check(index <= subject.size) {
"$index is out of bounds for $subject!"
}
subject.add(index, value)
}
}
/**
* Indicates that an element should be removed from the edited list.
*
* @param T the type of the elements of the edited list
* @property index the index of the element which should be removed
* @throws IllegalArgumentException if [index] is negative
*/
public data class Remove<T>(val index: Int) : ListEdit<T>() {
init {
require(index >= 0) { "Can't remove negative index $index!" }
}
override fun applyOn(subject: MutableList<T>) {
check(index < subject.size) {
"$index is out of bounds for $subject!"
}
subject.removeAt(index)
}
}
}
| 0
|
Kotlin
|
1
| 4
|
27f7f468e864638721290c8ae98e5a46008843ee
| 4,144
|
chronolens
|
Apache License 2.0
|
AnylineExamples/app/src/main/java/com/anyline/examples/ScanActivity.kt
|
Anyline
| 67,148,662
| false
|
{"Kotlin": 32570}
|
package com.anyline.examples
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.MenuItem
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import com.anyline.examples.databinding.ActivityScanBinding
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import io.anyline2.Event
import io.anyline2.ScanResult
import io.anyline2.legacy.trainer.AssetContext
import io.anyline2.legacy.trainer.ProjectContext
import io.anyline2.view.ScanView
import io.anyline2.viewplugin.ar.uiFeedback.UIFeedbackOverlayInfoEntry
import io.anyline2.viewplugin.ar.uiFeedback.UIFeedbackOverlayViewElementEventContent
import org.json.JSONObject
import timber.log.Timber
import java.util.*
open class ScanActivity : AppCompatActivity() {
private lateinit var binding: ActivityScanBinding
protected lateinit var scanView: ScanView
private var scanCount: Long = 0
private var lastScanResult: ScanResult? = null
/**
* Receives intrinsic run information
{"name":
"$resizeWidth",
"type":"Int",
"value":1080}"
*/
private val onScanInfo: (JSONObject) -> Unit = {
Timber.tag(TAG).e("onScanInfo: $it")
}
/**
* Receives errors during runs
*/
private val onError: (JSONObject) -> Unit = {
Timber.tag(TAG).e("onError: $it")
}
/**
* Receives info for unsuccessful runs
{"code":
5016,
"line":0,
"message":"NoLinesFound"}
*/
private val onRunSkipped: (JSONObject) -> Unit = {
Timber.tag(TAG).e("onRunSkipped: $it")
}
/**
* Receives visual feedback
{"squares":[
{"downLeft":{"x":414,"y":847},
"downRight":{"x":788,"y":842},
"upLeft":{"x":414,"y":949},
"upRight":{ x":781,"y":951}
}
]}
*/
private val onVisualFeedback: (JSONObject) -> Unit = {
Timber.tag(TAG).e("onVisualFeedback: $it")
}
/**
* Receives UIFeedback messages
{"messages":[
{"level":"Error","message":"Preset tin_custom_v11 not found."}
]}
*/
private val onUIFeedbackInfo: (JSONObject) -> Unit = {
it.optJSONArray("messages")?.let { msgArray ->
for (i in 0 until msgArray.length()) {
UIFeedbackOverlayInfoEntry.fromJson(msgArray[i] as JSONObject).also { msgEntry ->
when (msgEntry.level) {
UIFeedbackOverlayInfoEntry.Level.Info -> Timber.tag(TAG).i("onUIFeedbackInfo: ${msgEntry.message}")
UIFeedbackOverlayInfoEntry.Level.Warning -> Timber.tag(TAG).w("onUIFeedbackInfo: ${msgEntry.message}")
UIFeedbackOverlayInfoEntry.Level.Error -> Timber.tag(TAG).e("onUIFeedbackInfo: ${msgEntry.message}")
}
}
}
}
}
/**
* Receives scan results
{"barcodeResult":{
"barcodes":[{
"coordinates":[383,289,851,283,842,419,383,417],
"format":"TRIOPTIC",
"value":"NjU0OTg3"}]},
"confidence":-1,
"cropRect":{"height":692,"width":864,"x":108,"y":616},
"pluginID":"Barcode|Barcodes"}
*/
open val onResult: (ScanResult) -> Unit = {
evalResults(
listOf(it),
scanView.scanViewPlugin.activeScanViewPlugin.first().scanPlugin.scanPluginConfig.shouldCancelOnResult()
)
}
private val onResults: (List<ScanResult>) -> Unit = { scanResults ->
evalResults(scanResults, !scanView.scanViewPlugin?.isStarted!!)
}
private fun evalResults(scanResults: List<ScanResult>, showScanAgain: Boolean) {
for (it: ScanResult in scanResults) {
Timber.tag(TAG).e("onResult: ${it.result}")
lastScanResult = it
/*
Filter for an specific PluginId case where the aim is to
count the number of barcodes scanned on a single ScanResult
*/
if (it.pluginResult.pluginID.lowercase(Locale.getDefault()).contains("barcode")) {
scanCount += it.pluginResult.barcodeResult.barcodes.size
} else if (it.pluginResult.pluginID.lowercase(Locale.getDefault()).contains("mrz")) {
MaterialAlertDialogBuilder(this)
.setTitle(resources.getString(R.string.mrz_info_title))
.setMessage(resources.getString(R.string.mrz_info_message_read_nfc))
.setPositiveButton(resources.getString(R.string.button_yes)) { dialog, which ->
if (NFCMrzActivity.isNfcEnabled(this)) {
val intent = NFCMrzActivity.buildIntent(this, it.pluginResult.mrzResult)
intent.flags =
Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP
startActivity(intent)
}
}
.setNegativeButton(resources.getString(R.string.button_not_now)) { dialog, which ->
}
.show()
break
} else {
scanCount++
}
}
if (showScanAgain) {
binding.scanAgainButton.visibility = View.VISIBLE
}
binding.lastresultImageview.setImageBitmap(scanResults.last().cutoutImage.bitmap)
binding.lastresultImageview.visibility = View.VISIBLE
binding.textTotalscannedCountValue.text = scanCount.toString()
binding.textLastscannedResultValue.text = scanResults
.map {
it.result.toString(2)
}
.joinToString { it }
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityScanBinding.inflate(layoutInflater)
setContentView(binding.root)
scanView = binding.scanView
supportActionBar?.setDisplayHomeAsUpEnabled(true)
binding.scanAgainButton.setOnClickListener {
/*
This button is used to get a new scan for ScanPluginConfigs
set with attr "cancelOnResult" set to true since the ScanProcess
is canceled after first scan result
*/
scanView.start()
lastScanResult = null
binding.scanAgainButton.visibility = View.GONE
binding.lastresultImageview.setImageBitmap(null)
binding.lastresultImageview.visibility = View.GONE
binding.textLastscannedResultValue.text = ""
}
val assetContextInfo = intent.getStringExtra(INTENT_EXTRA_ASSETCONTEXT_INFO_CONTENT)
assetContextInfo?.let { assetInfo ->
val assetContextJSON = JSONObject(assetInfo)
val assetContext = ProjectContext(this, assetContextJSON)
try {
//initialize ScanView with AssetContext Info
scanView.init(assetContext, 30)
setupScanViewListeners()
} catch (e: Exception) {
showAlertDialog(
"Error",
resources.getString(R.string.ota_initAsset_error) + ": " + e
) { finish() }
}
} ?: run {
//initialize ScanView with JSON asset file config
scanView.init(intent.getStringExtra(INTENT_EXTRA_VIEW_CONFIG)!!)
setupScanViewListeners()
}
}
private fun setupScanViewListeners() {
//set ScanViewPlugin listeners
scanView.scanViewPlugin.apply {
scanInfoReceived = Event { data -> onScanInfo.invoke(data) }
runSkippedReceived = Event { data -> onRunSkipped.invoke(data) }
errorReceived = Event { data -> onError.invoke(data) }
visualFeedbackReceived = Event { data -> onVisualFeedback.invoke(data) }
uiFeedbackInfoReceived = Event { data -> onUIFeedbackInfo.invoke(data) }
resultReceived = Event { data -> onResult.invoke(data) }
resultsReceived = Event { data -> onResults.invoke(data) }
}
scanView.onCutoutChanged = Event { data ->
data.forEach { pair ->
Timber.tag(TAG).e(
"onCutoutChanged from ${pair.first.id()}: " +
"left: ${pair.second.left}, " +
"top: ${pair.second.top}, " +
"right: ${pair.second.right}, " +
"bottom: ${pair.second.bottom} "
)
}
}
scanView.onUIFeedbackOverlayViewClickedEvent = Event { data ->
val elementEventContent: UIFeedbackOverlayViewElementEventContent = data.second
if (elementEventContent.element.tag.isNotEmpty()) {
Toast.makeText(this,
elementEventContent.element.tag,
Toast.LENGTH_SHORT)
.show()
}
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
onBackPressed()
}
}
return super.onOptionsItemSelected(item)
}
override fun onResume() {
super.onResume()
//Starts scanning on Activity resume
scanView.start()
title = scanView.scanViewPlugin.id()
}
override fun onPause() {
//Stop scanning on Activity pause
scanView.stop()
super.onPause()
}
/**
* Display the last recognized result as prettified JSON in an AlertDialog Window
*/
private fun showDialogWithlastResult() {
lastScanResult?.result?.let {
showAlertDialog(getString(R.string.last_result), it.toString(2))
}
}
/**
* Show an AlertDialog with [title] and [message]
*/
protected fun showAlertDialog(title: String, message: String, onDismiss: (() -> Unit)? = null) {
val alertDialogBuilder = AlertDialog.Builder(this)
alertDialogBuilder.setTitle(title)
.setMessage(message)
.setOnDismissListener { onDismiss?.invoke() }
val alertDialog = alertDialogBuilder.create()
alertDialog.show()
}
companion object {
private const val TAG = "AnylineScanActivity"
const val INTENT_EXTRA_VIEW_CONFIG = "INTENT_EXTRA_VIEW_CONFIG"
const val INTENT_EXTRA_ASSETCONTEXT_INFO_CONTENT = "INTENT_EXTRA_ASSET_INFO_CONTENT"
fun buildIntent(context: Context, viewConfig: String): Intent {
val intent = Intent(context, ScanActivity::class.java)
intent.putExtra(INTENT_EXTRA_VIEW_CONFIG, viewConfig)
return intent
}
fun buildIntent(context: Context, assetContext: AssetContext): Intent {
val intent = Intent(context, ScanActivity::class.java)
intent.putExtra(
INTENT_EXTRA_ASSETCONTEXT_INFO_CONTENT,
assetContext.toJSONObject().toString()
)
return intent
}
}
}
| 0
|
Kotlin
|
26
| 22
|
124f5ff3d3fbe49e87ff0f91d27b74944d466c3a
| 11,141
|
anyline-ocr-examples-android
|
Apache License 2.0
|
camera/camera-camera2-pipe-integration/src/main/java/androidx/camera/camera2/pipe/integration/compat/quirk/DeviceQuirksLoader.kt
|
androidx
| 256,589,781
| false
|
{"Kotlin": 112114129, "Java": 66594571, "C++": 9132142, "AIDL": 635065, "Python": 325169, "Shell": 194520, "TypeScript": 40647, "HTML": 35176, "Groovy": 27178, "ANTLR": 26700, "Svelte": 20397, "CMake": 15512, "C": 15043, "GLSL": 3842, "Swift": 3153, "JavaScript": 3019}
|
/*
* Copyright 2023 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.camera.camera2.pipe.integration.compat.quirk
import androidx.camera.core.impl.Quirk
import androidx.camera.core.impl.QuirkSettings
/** Loads all device specific quirks required for the current device. */
public object DeviceQuirksLoader {
/**
* Goes through all defined device-specific quirks, and returns those that should be loaded on
* the current device.
*/
public fun loadQuirks(quirkSettings: QuirkSettings): List<Quirk> {
val quirks: MutableList<Quirk> = mutableListOf()
// Load all device specific quirks, preferably in lexicographical order
if (
quirkSettings.shouldEnableQuirk(
CloseCameraDeviceOnCameraGraphCloseQuirk::class.java,
CloseCameraDeviceOnCameraGraphCloseQuirk.isEnabled()
)
) {
quirks.add(CloseCameraDeviceOnCameraGraphCloseQuirk())
}
if (
quirkSettings.shouldEnableQuirk(
CloseCaptureSessionOnDisconnectQuirk::class.java,
CloseCaptureSessionOnDisconnectQuirk.isEnabled()
)
) {
quirks.add(CloseCaptureSessionOnDisconnectQuirk())
}
if (
quirkSettings.shouldEnableQuirk(
CrashWhenTakingPhotoWithAutoFlashAEModeQuirk::class.java,
CrashWhenTakingPhotoWithAutoFlashAEModeQuirk.isEnabled()
)
) {
quirks.add(CrashWhenTakingPhotoWithAutoFlashAEModeQuirk())
}
if (
quirkSettings.shouldEnableQuirk(
ControlZoomRatioRangeAssertionErrorQuirk::class.java,
ControlZoomRatioRangeAssertionErrorQuirk.isEnabled()
)
) {
quirks.add(ControlZoomRatioRangeAssertionErrorQuirk())
}
if (
quirkSettings.shouldEnableQuirk(
DisableAbortCapturesOnStopWithSessionProcessorQuirk::class.java,
DisableAbortCapturesOnStopWithSessionProcessorQuirk.isEnabled()
)
) {
quirks.add(DisableAbortCapturesOnStopWithSessionProcessorQuirk())
}
if (
quirkSettings.shouldEnableQuirk(
FlashAvailabilityBufferUnderflowQuirk::class.java,
FlashAvailabilityBufferUnderflowQuirk.isEnabled()
)
) {
quirks.add(FlashAvailabilityBufferUnderflowQuirk())
}
if (
quirkSettings.shouldEnableQuirk(
ImageCapturePixelHDRPlusQuirk::class.java,
ImageCapturePixelHDRPlusQuirk.isEnabled()
)
) {
quirks.add(ImageCapturePixelHDRPlusQuirk())
}
if (
quirkSettings.shouldEnableQuirk(
InvalidVideoProfilesQuirk::class.java,
InvalidVideoProfilesQuirk.isEnabled()
)
) {
quirks.add(InvalidVideoProfilesQuirk())
}
if (
quirkSettings.shouldEnableQuirk(
ExcludedSupportedSizesQuirk::class.java,
ExcludedSupportedSizesQuirk.isEnabled()
)
) {
quirks.add(ExcludedSupportedSizesQuirk())
}
if (
quirkSettings.shouldEnableQuirk(
ExtraCroppingQuirk::class.java,
ExtraCroppingQuirk.isEnabled()
)
) {
quirks.add(ExtraCroppingQuirk())
}
if (
quirkSettings.shouldEnableQuirk(
ExtraSupportedOutputSizeQuirk::class.java,
ExtraSupportedOutputSizeQuirk.isEnabled()
)
) {
quirks.add(ExtraSupportedOutputSizeQuirk())
}
if (
quirkSettings.shouldEnableQuirk(
ExtraSupportedSurfaceCombinationsQuirk::class.java,
ExtraSupportedSurfaceCombinationsQuirk.isEnabled()
)
) {
quirks.add(ExtraSupportedSurfaceCombinationsQuirk())
}
if (
quirkSettings.shouldEnableQuirk(
Nexus4AndroidLTargetAspectRatioQuirk::class.java,
Nexus4AndroidLTargetAspectRatioQuirk.isEnabled()
)
) {
quirks.add(Nexus4AndroidLTargetAspectRatioQuirk())
}
if (
quirkSettings.shouldEnableQuirk(
PreviewPixelHDRnetQuirk::class.java,
PreviewPixelHDRnetQuirk.isEnabled()
)
) {
quirks.add(PreviewPixelHDRnetQuirk())
}
if (
quirkSettings.shouldEnableQuirk(
RepeatingStreamConstraintForVideoRecordingQuirk::class.java,
RepeatingStreamConstraintForVideoRecordingQuirk.isEnabled()
)
) {
quirks.add(RepeatingStreamConstraintForVideoRecordingQuirk())
}
if (
quirkSettings.shouldEnableQuirk(
StillCaptureFlashStopRepeatingQuirk::class.java,
StillCaptureFlashStopRepeatingQuirk.isEnabled()
)
) {
quirks.add(StillCaptureFlashStopRepeatingQuirk())
}
if (
quirkSettings.shouldEnableQuirk(
TorchIsClosedAfterImageCapturingQuirk::class.java,
TorchIsClosedAfterImageCapturingQuirk.isEnabled()
)
) {
quirks.add(TorchIsClosedAfterImageCapturingQuirk())
}
if (
quirkSettings.shouldEnableQuirk(
SurfaceOrderQuirk::class.java,
SurfaceOrderQuirk.isEnabled()
)
) {
quirks.add(SurfaceOrderQuirk())
}
if (
quirkSettings.shouldEnableQuirk(
CaptureSessionOnClosedNotCalledQuirk::class.java,
CaptureSessionOnClosedNotCalledQuirk.isEnabled()
)
) {
quirks.add(CaptureSessionOnClosedNotCalledQuirk())
}
if (
quirkSettings.shouldEnableQuirk(ZslDisablerQuirk::class.java, ZslDisablerQuirk.load())
) {
quirks.add(ZslDisablerQuirk())
}
return quirks
}
}
| 30
|
Kotlin
|
984
| 5,321
|
98b929d303f34d569e9fd8a529f022d398d1024b
| 6,789
|
androidx
|
Apache License 2.0
|
typescript-kotlin/src/main/kotlin/typescript/updateDelete.kt
|
turansky
| 393,199,102
| false
| null |
// Automatically generated - do not modify!
@file:JsModule("typescript")
@file:JsNonModule
package typescript
/** @deprecated Use `factory.updateDeleteExpression` or the factory supplied by your transformation context instead. */
/*
external val updateDelete: (node: DeleteExpression, expression: Expression) => DeleteExpression
*/
| 0
|
Kotlin
|
1
| 10
|
bcf03704c0e7670fd14ec4ab01dff8d7cca46bf0
| 335
|
react-types-kotlin
|
Apache License 2.0
|
http_server_servlet/src/test/kotlin/com/hexagonkt/http/server/servlet/ServletServerTest.kt
|
mrpascal1
| 248,485,404
| true
|
{"Kotlin": 421825, "HTML": 25440, "Scala": 3554, "JavaScript": 2701, "Dockerfile": 2196, "CSS": 1122, "Shell": 894}
|
package com.hexagonkt.http.server.servlet
import com.hexagonkt.http.client.Client
import com.hexagonkt.http.client.ahc.AhcAdapter
import com.hexagonkt.http.server.Router
import io.mockk.Runs
import io.mockk.every
import io.mockk.just
import io.mockk.mockk
import org.eclipse.jetty.server.Server as JettyServer
import org.eclipse.jetty.webapp.WebAppContext
import org.testng.annotations.AfterClass
import org.testng.annotations.BeforeClass
import org.testng.annotations.Test
import java.net.InetSocketAddress
import javax.servlet.FilterChain
import javax.servlet.ServletRequest
import javax.servlet.ServletResponse
import javax.servlet.annotation.WebListener
@Test class ServletServerTest {
@WebListener
class WebAppServer : ServletServer() {
override fun createRouter() = Router {
get { ok("Hello Servlet!") }
}
}
private val jettyServer = JettyServer(InetSocketAddress("127.0.0.1", 9897))
@AfterClass fun shutdown() {
jettyServer.stopAtShutdown = true
jettyServer.stop()
}
@BeforeClass fun `Run server`() {
val context = WebAppContext()
context.contextPath = "/"
context.war = "."
context.addEventListener(WebAppServer())
jettyServer.handler = context
jettyServer.start()
}
@Test fun `Servlet server starts`() {
val response = Client(AhcAdapter(), "http://127.0.0.1:9897").get("/")
assert(response.body == "Hello Servlet!")
}
@Test(expectedExceptions = [ IllegalStateException::class ])
fun `Invalid types in filter calls raise an exception`() {
val filter = ServletFilter(emptyList())
val request = mockk<ServletRequest>()
val response = mockk<ServletResponse>()
val chain = mockk<FilterChain>()
every { request.setAttribute(any(), any()) } just Runs
filter.doFilter(request, response, chain)
}
}
| 0
|
Kotlin
|
0
| 0
|
a923180e63d27f3cf5f358d3808b4c1a54163d69
| 1,916
|
hexagon
|
MIT License
|
common-api/src/main/java/de/pbauerochse/worklogviewer/timereport/Project.kt
|
pbauerochse
| 34,003,778
| false
| null |
package de.pbauerochse.worklogviewer.timereport
/**
*
*/
open class Project(
/**
* Unique ID to distinguish this [Issue]
* from others. This field contains the
* technical id (e.g. Database Id from the source system)
*/
val id: String,
/**
* The full name of this [Project]
*/
val name: String,
/**
* A short name / key of this [Project]
*/
val shortName: String
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Project) return false
if (id != other.id) return false
return true
}
override fun hashCode(): Int {
return id.hashCode()
}
override fun toString(): String {
return "Project(id='$id', name='$name', shortName='$shortName')"
}
}
| 7
| null |
10
| 38
|
7bd7ca9a1eed08184bf30400160d424bee2ee258
| 830
|
youtrack-worklog-viewer
|
MIT License
|
src/main/kotlin/de/gesellix/docker/compose/types/PlacementPreferences.kt
|
docker-client
| 84,723,064
| false
| null |
package de.gesellix.docker.compose.types
data class PlacementPreferences(
var spread: String
)
| 5
|
Kotlin
|
4
| 19
|
aae581d14e547f8905154a877aa1f8f999449a93
| 106
|
docker-compose-v3
|
MIT License
|
client/app/src/main/java/com/hao/heji/ui/calendar/CalendarNoteFragment.kt
|
RUANHAOANDROID
| 324,589,079
| false
| null |
package com.hao.heji.ui.calendar
import android.content.Context
import android.view.View
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.Navigation
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.LogUtils
import com.chad.library.adapter.base.entity.node.BaseNode
import com.haibin.calendarview.Calendar
import com.haibin.calendarview.CalendarView.OnCalendarSelectListener
import com.hao.heji.R
import com.hao.heji.data.db.Bill
import com.hao.heji.databinding.FragmentCalendarNoteBinding
import com.hao.heji.render
import com.hao.heji.today
import com.hao.heji.ui.base.BaseFragment
import com.hao.heji.ui.adapter.DayBillsNode
import com.hao.heji.ui.adapter.NodeBillsAdapter
import com.hao.heji.ui.create.ArgAddBill
import com.hao.heji.ui.create.CreateBillFragmentArgs
import com.hao.heji.ui.popup.PopupBillInfo
import com.hao.heji.utils.YearMonth
import com.hao.heji.widget.CardDecoration
class CalendarNoteFragment : BaseFragment() {
val binding: FragmentCalendarNoteBinding by lazy {
FragmentCalendarNoteBinding.inflate(layoutInflater)
}
private val popupView by lazy {
PopupBillInfo.create(
activity = mainActivity,
delete = { notifyCalendar() },
update = {})
}
private val viewModel by lazy { ViewModelProvider(this)[CalendarNoteViewModule::class.java] }
lateinit var adapter: NodeBillsAdapter
override fun layout(): View {
return binding.root
}
override fun onAttach(context: Context) {
super.onAttach(context)
viewModel.selectYearMonth = mainActivity.viewModel.globalYearMonth
}
override fun setUpToolBar() {
super.setUpToolBar()
super.setUpToolBar()
showBlack()
val today = today()
val selectYearMonth = viewModel.selectYearMonth
with(selectYearMonth) {
showYearMonthTitle(
year = year, month = month,
onTabSelected = { year, month ->
binding.calendarView.scrollToCalendar(year, month, 1)
this.year = year
this.month = month
},
)
if (year != today.year || month != today.month) {
binding.calendarView.scrollToCalendar(year, month, today.day)
} else {
notifyCalendar()
}
}
}
override fun initView(rootView: View) {
initFab(rootView)
initCalendarView()
initAdapter()
render(viewModel) {
when (it) {
is CalenderUiState.DayBills -> {
adapter.setNewInstance(it.data as MutableList<BaseNode>)
adapter.notifyDataSetChanged()
}
is CalenderUiState.Calender -> {
if (it.data.isEmpty()) {
binding.calendarView.clearSchemeDate()
} else {
binding.calendarView.setSchemeDate(it.data)//更新日历视图
}
notifyBillsList()
}
is CalenderUiState.Images -> popupView.setImages(it.data)
}
}
}
private fun initFab(view: View) {
binding.addFab.setOnClickListener {
val year = binding.calendarView.selectedCalendar.year
val month = binding.calendarView.selectedCalendar.month
val day = binding.calendarView.selectedCalendar.day
val calendar = java.util.Calendar.getInstance()
calendar.set(year, month - 1, day)
val args =
CreateBillFragmentArgs.Builder(
ArgAddBill(
isModify = false,
bill = Bill(time = calendar.time)
)
)
.build()//选择的日期
Navigation.findNavController(view).navigate(R.id.nav_bill_add, args.toBundle())
}
binding.todayFab.setOnClickListener {
binding.calendarView.scrollToCurrent()
binding.todayFab.hide()
}
fabShow()
}
private fun initAdapter() {
binding.recycler.layoutManager = LinearLayoutManager(mainActivity)
adapter = NodeBillsAdapter()
binding.recycler.adapter = adapter
binding.recycler.addItemDecoration(CardDecoration(8))
adapter.setOnItemClickListener { adapter, _, position ->
if (adapter.getItem(position) is DayBillsNode) {
var billNode = adapter.getItem(position) as DayBillsNode
popupView.show(billNode.bill)
if (billNode.bill.images.isNotEmpty()) {
viewModel.doAction(CalenderAction.GetImages(billNode.bill.id))
}
}
}
}
private fun initCalendarView() {
viewModel.selectYearMonth.apply {
binding.calendarView.scrollToCalendar(year, month, day)
}
binding.calendarView.apply {
setOnMonthChangeListener { year, month -> //月份更改侦听
viewModel.selectYearMonth = YearMonth(year, month)
centerTitle.text = "$year.$month"
notifyCalendar()
fabShow()
}
setOnCalendarSelectListener(object : OnCalendarSelectListener {
override fun onCalendarOutOfRange(calendar: Calendar) {
LogUtils.d(calendar.toString())
}
override fun onCalendarSelect(calendar: Calendar, isClick: Boolean) {//选择日期事件
if (isClick) {
notifyBillsList()
}
}
})
}
}
private fun fabShow() {
val currentYearMonth = mainActivity.viewModel.currentYearMonth
if (viewModel.selectYearMonth == currentYearMonth)
binding.todayFab.hide()
else
binding.todayFab.show()
}
//更新日历天账单列表
private fun notifyBillsList() {
binding.calendarView.post {
viewModel.doAction(CalenderAction.GetDayBills((binding.calendarView.selectedCalendar)))
}
}
//更新日历
private fun notifyCalendar() {
viewModel.doAction(
CalenderAction.Update(
viewModel.selectYearMonth.year,
viewModel.selectYearMonth.month
)
)
}
}
| 0
| null |
15
| 45
|
879db94cf10b19e04f239fba9c987abe5806936a
| 6,468
|
heji
|
Apache License 2.0
|
build-logic/convention/src/main/kotlin/cn/wj/android/cashbook/buildlogic/ComposeAndroid.kt
|
WangJie0822
| 365,932,300
| false
|
{"Kotlin": 1528829, "Java": 1405038, "Batchfile": 263}
|
package cn.wj.android.cashbook.buildlogic
import com.android.build.api.dsl.CommonExtension
import org.gradle.api.Project
import org.gradle.api.artifacts.VersionCatalogsExtension
import org.gradle.kotlin.dsl.dependencies
import org.gradle.kotlin.dsl.getByType
import org.gradle.kotlin.dsl.withType
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
/**
* 配置 Android Compose
*
* > [王杰](mailto:<EMAIL>) 创建于 2023/2/7
*/
internal fun Project.configureAndroidCompose(
commonExtension: CommonExtension<*, *, *, *, *>,
) {
val libs = extensions.getByType<VersionCatalogsExtension>().named("libs")
commonExtension.apply {
buildFeatures {
compose = true
}
composeOptions {
kotlinCompilerExtensionVersion =
libs.findVersion("androidx-compose-compiler").get().toString()
}
dependencies {
val bom = libs.findLibrary("androidx-compose-bom").get()
add("implementation", platform(bom))
add("androidTestImplementation", platform(bom))
}
}
tasks.withType<KotlinCompile>().configureEach {
kotlinOptions {
freeCompilerArgs = freeCompilerArgs + buildComposeMetricsParameters()
}
}
}
private fun Project.buildComposeMetricsParameters(): List<String> {
val metricParameters = mutableListOf<String>()
val enableMetricsProvider = project.providers.gradleProperty("enableComposeCompilerMetrics")
val relativePath = projectDir.relativeTo(rootDir)
val enableMetrics = (enableMetricsProvider.orNull == "true")
val buildDir = rootProject.layout.buildDirectory.get().asFile
if (enableMetrics) {
val metricsFolder = buildDir.resolve("compose-metrics").resolve(relativePath)
metricParameters.add("-P")
metricParameters.add(
"plugin:androidx.compose.compiler.plugins.kotlin:metricsDestination=" + metricsFolder.absolutePath
)
}
val enableReportsProvider = project.providers.gradleProperty("enableComposeCompilerReports")
val enableReports = (enableReportsProvider.orNull == "true")
if (enableReports) {
val reportsFolder = buildDir.resolve("compose-reports").resolve(relativePath)
metricParameters.add("-P")
metricParameters.add(
"plugin:androidx.compose.compiler.plugins.kotlin:reportsDestination=" + reportsFolder.absolutePath
)
}
return metricParameters.toList()
}
| 0
|
Kotlin
|
8
| 30
|
b08893d4105673f0e5ab93e9c47e48cb8cf7f86b
| 2,464
|
Cashbook
|
Apache License 2.0
|
app/src/main/java/com/greedygame/musicwiki/presentation_mw/viewmodels/ViewModelAlbumDF.kt
|
himanshuyadv
| 628,220,734
| false
| null |
package com.greedygame.musicwiki.presentation_mw.viewmodels
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.greedygame.musicwiki.data_mw.api_retrofit.ApiClient
import com.greedygame.musicwiki.data_mw.models.album_details.AlbumInfoModel
import com.greedygame.musicwiki.data_mw.models.albums_top_tags.AlbumsTopTagsModel
import com.greedygame.musicwiki.data_mw.models.tags_top_albums.Album
import com.greedygame.musicwiki.data_mw.models.tags_top_albums.Albums
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
class ViewModelAlbumDF : ViewModel() {
// selected album Info
private val _albumInfo = MutableLiveData<AlbumInfoModel>()
val albumInfo: LiveData<AlbumInfoModel> = _albumInfo
// album top tags
private val _albumTopTags = MutableLiveData<AlbumsTopTagsModel>()
val albumTopTags: LiveData<AlbumsTopTagsModel> = _albumTopTags
// retrofit error
private val _errorMessage = MutableLiveData<String>()
val errorMessage: LiveData<String> = _errorMessage
fun fetchAlbumInfo(albumName:String,artistName:String) = viewModelScope.async(Dispatchers.IO) {
try {
val response = ApiClient.apiService.getAlbumInfo(albumName,artistName)
if (response.isSuccessful) {
_albumInfo.postValue(response.body())
fetchAlbumTopTags(albumName,artistName).await()
} else {
_errorMessage.postValue(response.message())
}
} catch (e: Exception) {
_errorMessage.postValue(e.message)
}
}
fun fetchAlbumTopTags(albumName:String,artistName:String) = viewModelScope.async(Dispatchers.IO) {
try {
val response = ApiClient.apiService.getAlbumTopTags(albumName,artistName)
if (response.isSuccessful) {
_albumTopTags.postValue(response.body())
} else {
_errorMessage.postValue(response.message())
}
} catch (e: Exception) {
_errorMessage.postValue(e.message)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
7d3f179715ff2f64581fc487058e25cf7f6adec0
| 2,212
|
music_wiki
|
MIT License
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.