path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
756M
| is_fork
bool 2
classes | languages_distribution
stringlengths 12
2.44k
⌀ | content
stringlengths 6
6.29M
| issues
float64 0
10k
⌀ | main_language
stringclasses 128
values | forks
int64 0
54.2k
| stars
int64 0
157k
| commit_sha
stringlengths 40
40
| size
int64 6
6.29M
| name
stringlengths 1
100
| license
stringclasses 104
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
code/app/src/main/java/com/tanfra/shopmob/features/smobPlanning/presentation/view/shops/PlanningShopsMutationReducer.kt | fwornle | 440,434,944 | false | {"Kotlin": 997071, "JavaScript": 29417, "HTML": 180, "Batchfile": 177} | package com.tanfra.shopmob.features.smobPlanning.presentation.view.shops
import com.tanfra.shopmob.features.common.arch.Reducer
import com.tanfra.shopmob.features.smobPlanning.presentation.model.PlanningMutation
import com.tanfra.shopmob.features.smobPlanning.presentation.view.PlanningViewState
import com.tanfra.shopmob.smob.data.repo.ato.SmobShopATO
class PlanningShopsMutationReducer : Reducer<PlanningMutation, PlanningViewState> {
override fun invoke(mutation: PlanningMutation, currentState: PlanningViewState): PlanningViewState =
when (mutation) {
is PlanningMutation.ShowShops ->
currentState.mutateToShowContent(
shopList = mutation.shops,
) // products screen
is PlanningMutation.ShowShopDetails ->
currentState.mutateToShowContent(shop = mutation.shop) // product details
else -> currentState // mutation not handled in this reducer --> maintain current state
}
// shops screen - show shops in DB
@JvmName("mutateToShowShops")
private fun PlanningViewState.mutateToShowContent(
shopList: List<SmobShopATO>
) =
copy(
isLoaderVisible = false,
isContentVisible = true,
shopItems = shopList,
isErrorVisible = false,
)
// shop details screen - show details of selected shop
@JvmName("mutateToShowShopDetails")
private fun PlanningViewState.mutateToShowContent(shop: SmobShopATO) =
copy(
isLoaderVisible = false,
isContentVisible = true,
selectedShop = shop,
isErrorVisible = false,
)
} | 0 | Kotlin | 0 | 0 | beb57c22e9b9618a592817990309ea6d415ffe3e | 1,688 | ShopMob | MIT License |
server/src/main/kotlin/com/heerkirov/hedge/server/utils/tools/Deferrable.kt | HeerKirov | 298,201,781 | false | null | package com.heerkirov.hedge.server.utils.tools
class Deferrable(private val completes: MutableList<() -> Unit>,
private val catches: MutableList<() -> Unit>,
private val finals: MutableList<() -> Unit>) {
/**
* 作用域内没有异常而正常离开时。相当于业务代码后的追加代码。
*/
fun returns(action: () -> Unit) {
completes.add(action)
}
/**
* 作用域内抛出异常而离开时,执行此块。相当于catch,但是不在意异常的内容。
*/
fun except(action: () -> Unit) {
catches.add(action)
}
/**
* 作用域退出时,无论如何都会执行此块。相当于finally。
*/
fun defer(action: () -> Unit) {
finals.add(action)
}
fun <T> T.applyReturns(action: T.() -> Unit): T {
completes.add { this.action() }
return this
}
fun <T> T.applyExcept(action: T.() -> Unit): T {
catches.add { this.action() }
return this
}
fun <T> T.applyDefer(action: T.() -> Unit): T {
finals.add { this.action() }
return this
}
fun <T> T.alsoReturns(action: (T) -> Unit): T {
completes.add { action(this) }
return this
}
fun <T> T.alsoExcept(action: (T) -> Unit): T {
catches.add { action(this) }
return this
}
}
/**
* 启动一个延后作用的作用域。
* 在作用域中,使用defer和except函数注册当退出作用域时执行的内容。
* 本质上仍相当于try catch finally结构,但是使用更加类似Go/Swift的defer模式体现。
*/
inline fun <T> defer(block: Deferrable.() -> T): T {
val completes: MutableList<() -> Unit> = mutableListOf()
val catches: MutableList<() -> Unit> = mutableListOf()
val finals: MutableList<() -> Unit> = mutableListOf()
val deferrable = Deferrable(completes, catches, finals)
try {
val ret = deferrable.block()
if(completes.isNotEmpty()) completes.asReversed().forEach { it() }
return ret
}catch (e: Throwable) {
if(catches.isNotEmpty()) catches.asReversed().forEach { it() }
throw e
}finally{
if(finals.isNotEmpty()) finals.asReversed().forEach { it() }
}
} | 0 | TypeScript | 0 | 1 | 8140cd693759a371dc5387c4a3c7ffcef6fb14b2 | 2,271 | Hedge-v2 | MIT License |
src/main/kotlin/net/lomeli/minewell/lib/EnumItemRarity.kt | Lomeli12 | 151,324,372 | false | null | package net.lomeli.minewell.lib
import net.minecraft.client.resources.I18n
import net.minecraft.util.text.TextFormatting
enum class EnumItemRarity {
COMMON("rarity.minewell.common", TextFormatting.WHITE),
UNCOMMON("rarity.minewell.uncommon", TextFormatting.GREEN),
RARE("rarity.minewell.rare", TextFormatting.AQUA),
LEGENDARY("rarity.minewell.legendary", TextFormatting.LIGHT_PURPLE),
EXOTIC("rarity.minewell.exotic", TextFormatting.GOLD);
private val tooltipText: String
private val textColor: TextFormatting
constructor(text: String, color: TextFormatting) {
tooltipText = text
textColor = color
}
fun getTooltipText(): String = I18n.format(tooltipText)
fun getTextColor(): TextFormatting = textColor
} | 0 | Kotlin | 0 | 0 | 4378a86bba82ac8772dd9bbc7c28f3964a964630 | 770 | Minewell | MIT License |
app/src/main/java/com/mezhendosina/sgo/data/netschool/repo/LessonRepository.kt | mezhendosina | 448,087,094 | false | {"Kotlin": 580262, "Java": 5030} | /*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mezhendosina.sgo.data.netschool.repo
import com.mezhendosina.sgo.app.model.answer.FileUiEntity
import com.mezhendosina.sgo.app.model.attachments.ANSWERS
import com.mezhendosina.sgo.app.model.attachments.HOMEWORK
import com.mezhendosina.sgo.app.model.journal.entities.LessonUiEntity
import com.mezhendosina.sgo.app.uiEntities.AboutLessonUiEntity
import com.mezhendosina.sgo.app.uiEntities.AssignTypeUiEntity
import com.mezhendosina.sgo.app.uiEntities.WhyGradeEntity
import com.mezhendosina.sgo.data.netschool.NetSchoolSingleton
import com.mezhendosina.sgo.data.netschool.api.attachments.AttachmentsSource
import com.mezhendosina.sgo.data.netschool.api.attachments.entities.AttachmentsRequestEntity
import com.mezhendosina.sgo.data.netschool.api.homework.HomeworkSource
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import javax.inject.Inject
typealias LessonActionListener = (lesson: AboutLessonUiEntity?) -> Unit
class LessonRepository @Inject constructor(
private val homeworkSource: HomeworkSource,
private val attachmentsSource: AttachmentsSource,
) : LessonRepositoryInterface {
private var assignTypes: List<AssignTypeUiEntity>? = null
private var lesson: AboutLessonUiEntity? = null
private val listeners = mutableSetOf<LessonActionListener>()
var answerFiles: List<FileUiEntity> = emptyList()
private var answerText: String = ""
override fun getAnswerText(): String = answerText
override fun editAnswerText(text: String) {
answerText = text
}
override fun getLesson(): AboutLessonUiEntity? {
return lesson
}
override suspend fun getAboutLesson(
lessonUiEntity: LessonUiEntity,
studentId: Int
) {
val attachmentsR = attachmentsSource.getAttachments(
studentId,
AttachmentsRequestEntity(lessonUiEntity.assignments?.map { it.id } ?: emptyList())
)
val answerFilesResponse =
attachmentsR.firstOrNull()?.answerFiles?.map {
it.attachment.toUiEntity(
ANSWERS,
lessonUiEntity.classmeetingId
)
}
val attachments = attachmentsR.firstOrNull()?.attachments?.map {
it.toUiEntity(
HOMEWORK,
lessonUiEntity.classmeetingId
)
}
val aboutAssign =
lessonUiEntity.homework?.id?.let { homeworkSource.getAboutAssign(it, studentId) }
val answerTextResponse =
lessonUiEntity.assignments?.firstOrNull { it.textAnswer != null }?.textAnswer?.answer
answerFiles = answerFilesResponse ?: emptyList()
answerText = answerTextResponse ?: ""
val out = AboutLessonUiEntity(
lessonUiEntity.classmeetingId,
lessonUiEntity.subjectName,
lessonUiEntity.homework?.assignmentName ?: "",
aboutAssign?.description,
attachments,
loadGrades(lessonUiEntity),
answerTextResponse,
answerFilesResponse
)
withContext(Dispatchers.Main) {
lesson = out
notifyListeners()
}
}
override fun editAnswers(files: List<FileUiEntity>?) {
lesson = lesson?.editAnswers(answerText, files)
notifyListeners()
}
private suspend fun loadGrades(lessonUiEntity: LessonUiEntity): List<WhyGradeEntity> {
val gradesList = mutableListOf<WhyGradeEntity>()
if (assignTypes.isNullOrEmpty()) assignTypes =
homeworkSource.assignmentTypes().map { it.toUiEntity() }
lessonUiEntity.assignments?.forEach { assign ->
if (assign.mark != null) {
gradesList.add(
WhyGradeEntity(
assign.assignmentName,
assign.mark,
assignTypes?.firstOrNull { it.id == assign.typeId }?.name
)
)
}
}
return gradesList
}
override fun addListener(listener: LessonActionListener) {
listeners.add(listener)
}
override fun removeListener(listener: LessonActionListener) {
listeners.remove(listener)
}
private fun notifyListeners() {
listeners.forEach { it.invoke(lesson) }
}
} | 0 | Kotlin | 0 | 11 | 747c5d1dcfe093009f51c0bf16009076a6784007 | 5,051 | che-zadali-app | Apache License 2.0 |
android/apollo/src/main/java/io/muun/apollo/domain/model/InstallSourceInfo.kt | muun | 150,655,434 | false | {"Java": 1896366, "Kotlin": 1448476, "C": 800452, "Go": 663376, "Shell": 4042, "Dockerfile": 2320, "Python": 1557} | package io.muun.apollo.domain.model
/**
* If OS.supportsInstallSourceInfo() (Api level 30+) contains 3 pieces of data.
* Else just install source.
*/
data class InstallSourceInfo(
val installingPackageName: String,
val initiatingPackageName: String? = null, //If !OS.supportsInstallSourceInfo()
val initiatingPackageSigningInfo: String? = null, // If !OS.supportsInstallSourceInfo()
) | 37 | Java | 47 | 250 | 56769fff08b0a38066f6be069bf9c1604793bb22 | 400 | apollo | MIT License |
type-safe-with-jooq/src/main/kotlin/dev/monosoul/shmonitoring/model/ServiceStatus.kt | monosoul | 644,004,275 | false | null | package dev.monosoul.shmonitoring.jackson
import com.fasterxml.jackson.annotation.JsonTypeInfo
import com.fasterxml.jackson.annotation.JsonTypeInfo.As
import com.fasterxml.jackson.annotation.JsonTypeInfo.Id
import com.fasterxml.jackson.annotation.JsonTypeName
import java.time.Duration
@JsonTypeInfo(use = Id.NAME, include = As.PROPERTY, property = "type")
sealed class ServiceStatus {
abstract override fun equals(other: Any?): Boolean
abstract override fun hashCode(): Int
abstract override fun toString(): String
@JsonTypeName("up")
data class Up(
val upTime: Duration,
val numberOfProcesses: NumberOfProcesses,
) : ServiceStatus()
@JsonTypeName("warning")
data class Warning(val message: WarningMessage) : ServiceStatus()
@JsonTypeName("down")
object Down : ServiceStatus() {
override fun equals(other: Any?): Boolean = javaClass == other?.javaClass
override fun hashCode(): Int = javaClass.hashCode()
override fun toString() = "Down()"
}
}
| 0 | Kotlin | 0 | 0 | c3fe2d8da8feba27abc80b247606228a42434704 | 1,034 | shmonitoring | Apache License 2.0 |
shared/src/commonMain/kotlin/main/MainScreen.kt | HaniFakhouri | 732,515,661 | false | {"Kotlin": 76383, "Swift": 592, "Shell": 228} | package main
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.tween
import androidx.compose.animation.slideInVertically
import androidx.compose.animation.slideOutVertically
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.requiredHeight
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyGridState
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.lazy.grid.rememberLazyGridState
import androidx.compose.foundation.lazy.staggeredgrid.LazyVerticalStaggeredGrid
import androidx.compose.foundation.lazy.staggeredgrid.StaggeredGridCells
import androidx.compose.foundation.lazy.staggeredgrid.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.Card
import androidx.compose.material.CircularProgressIndicator
import androidx.compose.material.ContentAlpha
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.FloatingActionButton
import androidx.compose.material.Icon
import androidx.compose.material.LinearProgressIndicator
import androidx.compose.material.MaterialTheme
import androidx.compose.material.ModalBottomSheetLayout
import androidx.compose.material.ModalBottomSheetValue
import androidx.compose.material.Text
import androidx.compose.material.TextField
import androidx.compose.material.TextFieldDefaults
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Clear
import androidx.compose.material.icons.filled.KeyboardArrowUp
import androidx.compose.material.icons.filled.List
import androidx.compose.material.icons.filled.Search
import androidx.compose.material.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import cafe.adriel.voyager.core.model.rememberScreenModel
import cafe.adriel.voyager.core.screen.Screen
import cafe.adriel.voyager.navigator.LocalNavigator
import cafe.adriel.voyager.navigator.currentOrThrow
import com.myapplication.common.MR
import components.ErrorUi
import components.LoadingUi
import dev.icerock.moko.resources.compose.fontFamilyResource
import io.kamel.core.Resource
import io.kamel.core.utils.cacheControl
import io.kamel.image.KamelImage
import io.kamel.image.asyncPainterResource
import io.ktor.client.request.header
import io.ktor.client.request.parameter
import io.ktor.client.utils.CacheControl
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.IO
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import model.FilterProductCategoryId
import model.ProductAttributes
import org.koin.compose.koinInject
import repo.IProductsRepo
import utils.applyIf
/**
* Created by hani.fakhouri on 2023-12-18.
*/
object MainScreen : Screen {
@Composable
override fun Content() {
val repo = koinInject<IProductsRepo>()
val vm = rememberScreenModel { MainVm(repo) }
val state by vm.uiState.collectAsState()
when {
state.loading && !state.silentLoading -> {
Column {
TopOptionsBar(state, vm)
LoadingUi()
}
}
state.error -> ErrorUi(vm::loadData)
else -> {
Column {
TopOptionsBar(state, vm)
if (state.silentLoading) {
LinearProgressIndicator(
modifier = Modifier.fillMaxWidth(),
color = Color.LightGray,
)
}
MainScreen(state, vm)
}
}
}
}
}
@Composable
private fun TopOptionsBar(
state: MainScreenUiState,
vm: MainVm,
) {
val readableFilter = state.readableFilter
val isLoading = state.silentLoading || state.loading
val isReadOnly = state.filter.category != null || isLoading
var input by remember { mutableStateOf("") }
val focusMgr = LocalFocusManager.current
Row(
Modifier.fillMaxWidth()
.background(color = MaterialTheme.colors.primary)
.padding(8.dp),
verticalAlignment = Alignment.CenterVertically,
) {
TextField(
modifier = Modifier.weight(1.0F),
value = readableFilter ?: input,
onValueChange = {
input = it
},
leadingIcon = {
val icon =
if (state.filter.category != null) Icons.Filled.List else Icons.Filled.Search
Icon(
imageVector = icon,
contentDescription = "Bar icon"
)
},
placeholder = {
Text("Search")
},
keyboardActions = KeyboardActions(
onDone = {
vm.search(input)
focusMgr.clearFocus(force = true)
}
),
keyboardOptions = KeyboardOptions.Default.copy(
imeAction = ImeAction.Done
),
singleLine = true,
readOnly = isReadOnly,
shape = CircleShape,
colors = TextFieldDefaults.textFieldColors(
textColor = MaterialTheme.colors.onPrimary,
placeholderColor = MaterialTheme.colors.onPrimary.copy(alpha = 0.85F),
backgroundColor = MaterialTheme.colors.onPrimary.copy(alpha = 0.10F),
cursorColor = MaterialTheme.colors.onPrimary,
focusedIndicatorColor = Color.Transparent,
unfocusedIndicatorColor = Color.Transparent,
leadingIconColor = MaterialTheme.colors.onPrimary,
)
)
Spacer(modifier = Modifier.width(8.dp))
if (state.filter.name != null || state.filter.category != null) {
Icon(
modifier = Modifier
.clip(CircleShape)
.clickable {
input = ""
vm.clearFilter()
}
.padding(8.dp),
tint = MaterialTheme.colors.onPrimary,
imageVector = Icons.Filled.Clear,
contentDescription = "Clear filter"
)
}
val alpha = if (isLoading) ContentAlpha.disabled else ContentAlpha.high
Icon(
modifier = Modifier
.clip(CircleShape)
.applyIf(!isLoading) {
clickable {
vm.toggleSheetVisibility()
}
}
.padding(8.dp),
tint = MaterialTheme.colors.onPrimary.copy(alpha = alpha),
imageVector = Icons.Filled.List,
contentDescription = "Categories icon"
)
}
}
@Composable
private fun CategoryUi(
text: String,
isSelected: Boolean,
onClick: () -> Unit,
) {
Box(
modifier = Modifier
.clip(CircleShape)
.then(
if (isSelected) {
Modifier.background(
color = MaterialTheme.colors.primary,
shape = CircleShape,
)
} else {
Modifier
.clickable { onClick() }
.border(
width = 1.dp, color = MaterialTheme.colors.secondary,
shape = CircleShape
)
}
)
.padding(8.dp),
contentAlignment = Alignment.Center
) {
Text(
text = text,
color = if (isSelected) MaterialTheme.colors.onPrimary else
MaterialTheme.colors.onSurface,
fontWeight = FontWeight.W700,
style = MaterialTheme.typography.caption,
maxLines = 1,
textAlign = TextAlign.Center
)
}
}
@OptIn(ExperimentalMaterialApi::class)
@Composable
private fun MainScreen(
state: MainScreenUiState,
vm: MainVm,
) {
val products = state.products
if (products.isEmpty()) {
if (state.isLoading()) {
LoadingUi()
} else {
Text(
modifier = Modifier.padding(16.dp),
color = MaterialTheme.colors.onSurface,
text = "No brands found",
fontWeight = FontWeight.W700,
style = MaterialTheme.typography.h4,
)
}
}
val scrollState: LazyGridState = rememberLazyGridState()
val scope = rememberCoroutineScope()
var showFab by remember { mutableStateOf(false) }
LaunchedEffect(scrollState.firstVisibleItemIndex) {
val index = scrollState.firstVisibleItemIndex
if (index >= 4 && !showFab) {
showFab = true
} else if (index < 4 && showFab) {
showFab = false
}
}
val loadMoreData = !scrollState.canScrollForward && scrollState.canScrollBackward
&& state.hasMoreData
LaunchedEffect(loadMoreData) {
if (loadMoreData) {
vm.loadMoreData()
}
}
val sheetState = rememberModalBottomSheetState(
if (state.showSheet) ModalBottomSheetValue.HalfExpanded else ModalBottomSheetValue.Hidden
)
LaunchedEffect(sheetState.isVisible) {
vm.setSheetVisibility(sheetState.isVisible)
}
ModalBottomSheetLayout(
sheetState = sheetState,
sheetBackgroundColor = Color.Transparent,
sheetContent = {
Column(
modifier = Modifier
.fillMaxWidth()
.background(
color = MaterialTheme.colors.surface,
shape = RoundedCornerShape(topStart = 16.dp, topEnd = 16.dp),
)
.padding(horizontal = 8.dp).padding(bottom = 16.dp)
) {
Box(
modifier = Modifier.fillMaxWidth().padding(vertical = 16.dp),
contentAlignment = Alignment.Center
) {
Box(
modifier = Modifier.width(28.dp).height(3.dp).background(
color = Color.DarkGray, shape = CircleShape
)
)
}
LazyVerticalStaggeredGrid(
columns = StaggeredGridCells.Adaptive(96.dp),
verticalItemSpacing = 8.dp,
horizontalArrangement = Arrangement.spacedBy(4.dp)
) {
items(FilterProductCategoryId.values()) { category ->
CategoryUi(
text = category.totoReadable(),
isSelected = state.filter.category == category,
) {
vm.filterCategory(category)
}
}
}
}
}
) {
Box(
modifier = Modifier.fillMaxSize()
) {
LazyVerticalGrid(
state = scrollState,
columns = GridCells.Fixed(2),
modifier = Modifier.fillMaxSize(),
contentPadding = PaddingValues(8.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
items(products) { product ->
ProductUi(product.attributes)
}
item {
Spacer(modifier = Modifier.height(56.dp))
}
}
if (state.isLoadingMoreData) {
Box(
modifier = Modifier
.padding(bottom = 12.dp)
.size(32.dp)
.align(Alignment.BottomCenter),
contentAlignment = Alignment.Center
) {
CircularProgressIndicator(strokeWidth = 4.dp)
}
}
AnimatedVisibility(
visible = showFab,
enter = slideInVertically(initialOffsetY = { it }),
exit = slideOutVertically(targetOffsetY = { it }),
modifier = Modifier.align(Alignment.BottomEnd)
) {
FloatingActionButton(
modifier = Modifier.padding(16.dp),
onClick = {
showFab = false
scope.launch {
scrollState.animateScrollToItem(0)
}
},
backgroundColor = Color(0xFF009736),
contentColor = Color.White,
) {
Icon(Icons.Filled.KeyboardArrowUp, "Floating action button.")
}
}
}
}
}
@Composable
private fun ProductUi(product: ProductAttributes) {
val navigator = LocalNavigator.currentOrThrow
var imageResource by remember { mutableStateOf<Resource<Painter>?>(null) }
fun onOpenProduct() {
navigator.push(
ProductScreen(
product = product,
imageResource = imageResource
)
)
}
Card(
shape = RoundedCornerShape(16.dp),
elevation = 4.dp,
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 4.dp),
) {
Column(
modifier = Modifier
.fillMaxWidth()
.clickable {
onOpenProduct()
},
verticalArrangement = Arrangement.Center,
) {
product.imageUrl?.let { imageUrl ->
//println("hanilogx: Loading: $imageUrl")
val res = getPainterResource(imageUrl)
imageResource = res
KamelImage(
modifier = Modifier
.size(56.dp)
.align(Alignment.CenterHorizontally),
animationSpec = tween(),
resource = res,
contentDescription = "image",
onLoading = {
CircularProgressIndicator(
modifier = Modifier.size(16.dp)
)
},
)
} ?: run {
Spacer(Modifier.height(56.dp))
}
Spacer(Modifier.height(8.dp))
var fontSize by remember { mutableStateOf(18.sp) }
Text(
modifier = Modifier.fillMaxWidth().requiredHeight(36.dp),
textAlign = TextAlign.Center,
text = product.name.uppercase(),
fontWeight = FontWeight.W500,
fontSize = fontSize,
maxLines = 1,
onTextLayout = {
if (it.lineCount > 1) {
fontSize = 14.sp
}
}
)
Box(
modifier = Modifier
.fillMaxWidth()
.background(
color = Color(0xFFB9261C)
).clickable {
onOpenProduct()
},
contentAlignment = Alignment.Center,
) {
Text(
modifier = Modifier.padding(vertical = 12.dp),
text = "Info",
color = Color.White,
fontWeight = FontWeight.W700,
)
}
}
}
}
@Composable
private fun getPainterResource(url: String): Resource<Painter> {
return asyncPainterResource(data = url) {
coroutineContext = Job() + Dispatchers.IO
requestBuilder {
header("Key", "Value")
parameter("Key", "Value")
cacheControl(CacheControl.MAX_AGE)
}
}
} | 0 | Kotlin | 0 | 0 | 41543c96abc988ced153d82ac9cbcd00b4f7666c | 17,822 | Boycotz | Apache License 2.0 |
swipeablescreens/src/main/java/com/srijith/swipeablescreens/SwipeScreenBehavior.kt | sjthn | 121,353,376 | false | null | /*
* MIT License
*
* Copyright (c) 2018 Srijith
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.srijith.swipeablescreens
import android.content.Context
import android.support.design.widget.CoordinatorLayout
import android.support.v4.view.ViewCompat
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import kotlin.math.abs
/**
* Created by Srijith on 2/8/2018.
*/
open class SwipeScreenBehavior<V : View>(context: Context?, attrs: AttributeSet?) :
CoordinatorLayout.Behavior<V>(context, attrs) {
private val friction = 0.25f
private val swipeThreshold = 14
private var touchStartY = 0f
private var totalDrag = 0f
private var isDragDown = false
private var isDragUp = false
private var isDismissed = false
private var dismissCallback: SwipeCallback? = null
constructor() : this(null, null)
override fun onInterceptTouchEvent(
parent: CoordinatorLayout?,
child: V,
ev: MotionEvent?
): Boolean {
return false
}
override fun onTouchEvent(parent: CoordinatorLayout?, child: V, ev: MotionEvent?): Boolean {
if (isDismissed) return false
var consumed = false
when (ev?.action) {
MotionEvent.ACTION_DOWN -> {
consumed = true
touchStartY = ev.y
}
MotionEvent.ACTION_MOVE -> {
parent?.let {
totalDrag = -(touchStartY - ev.y)
if (totalDrag != 0f) dragAndScaleView(totalDrag * friction, parent)
}
}
MotionEvent.ACTION_UP -> {
parent?.let { handleOnActionUp(it) }
consumed = false
resetValues()
}
else -> {
consumed = false
resetValues()
}
}
return consumed
}
private fun handleOnActionUp(parent: CoordinatorLayout) {
if (shouldDismissScreen(parent)) {
isDismissed = true
dismissCallback?.dismissListener(parent)
} else {
if (parent.y != 0f) {
parent.animate().translationY(0f).scaleX(1f).scaleY(1f)
}
}
}
override fun onStartNestedScroll(
coordinatorLayout: CoordinatorLayout,
child: V,
directTargetChild: View,
target: View,
axes: Int,
type: Int
): Boolean {
return (axes and ViewCompat.SCROLL_AXIS_VERTICAL) != 0 && type == ViewCompat.TYPE_TOUCH && !isDismissed
}
override fun onNestedPreScroll(
parent: CoordinatorLayout,
child: V,
target: View,
dx: Int,
dy: Int,
consumed: IntArray,
type: Int
) {
// Called when the view is already in dragged state.
if (dy != 0 && (isDragUp || isDragDown)) {
dragAndScaleNestedScroller(dy, parent)
consumed[1] = dy
}
}
override fun onNestedScroll(
parent: CoordinatorLayout,
child: V,
target: View,
dxConsumed: Int,
dyConsumed: Int,
dxUnconsumed: Int,
dyUnconsumed: Int,
type: Int
) {
if (dyUnconsumed == 0) return
dragAndScaleNestedScroller(dyUnconsumed, parent)
}
override fun onStopNestedScroll(
parent: CoordinatorLayout,
child: V,
target: View,
type: Int
) {
totalDrag = 0f
if (shouldDismissScreen(parent)) {
isDismissed = true
dismissCallback?.dismissListener(parent)
} else {
if (parent.y != 0f) {
parent.animate().translationY(0f).scaleX(1f).scaleY(1f)
}
}
isDragDown = false
isDragUp = false
}
fun setOnDismissListener(callback: SwipeCallback) {
dismissCallback = callback
}
private fun dragAndScaleNestedScroller(dy: Int, parent: CoordinatorLayout) {
if (dy < 0) isDragDown = true else isDragUp = true
totalDrag += -(dy) * friction
dragAndScaleView(totalDrag, parent)
}
private fun dragAndScaleView(dy: Float, parent: CoordinatorLayout) {
parent.translationY = dy
// parent.scaleX = 0.95f
// parent.scaleY = 0.95f
}
private fun shouldDismissScreen(parent: View?): Boolean {
parent?.let {
if (abs(parent.y) > parent.height / swipeThreshold) {
return true
}
}
return false
}
private fun resetValues() {
touchStartY = 0f
totalDrag = 0f
}
}
interface SwipeCallback {
fun dismissListener(parent: View?)
} | 0 | Kotlin | 2 | 27 | d732605c31779910e06b6984b277437fe0ace365 | 5,762 | SwipeScreenBehavior | MIT License |
app/src/main/java/com/zhowin/kotlinmvp/mvp/contract/HomeContract.kt | lucky-you | 334,590,579 | false | {"Kotlin": 289321, "Java": 17123} | package com.young.kotlinproject.mvp.contract
import com.young.kotlinproject.base.IBaseView
import com.young.kotlinproject.mvp.model.bean.HomeBean
/**
* 契约类
*/
interface HomeContract {
interface View : IBaseView {
/**
* 设置第一次请求的数据
*/
fun setHomeData(homeBean: HomeBean)
/**
* 设置加载更多的数据
*/
fun setMoreData(itemList:ArrayList<HomeBean.Issue.Item>)
/**
* 显示错误信息
*/
fun showError(msg: String,errorCode:Int)
}
interface Presenter {
/**
* 获取首页精选数据
*/
fun requestHomeData(num: Int)
/**
* 加载更多数据
*/
fun loadMoreData()
}
}
| 1 | Kotlin | 0 | 0 | 4c88a25133641d260c10466edcb09d755abd3d75 | 801 | LCloud | Apache License 2.0 |
relive-simulator-core/src/commonMain/kotlin/xyz/qwewqa/relive/simulator/core/presets/memoir/generated/equip3000024.kt | pointillion | 428,683,199 | true | {"Kotlin": 538588, "HTML": 47353, "CSS": 17418, "JavaScript": 79} | package xyz.qwewqa.relive.simulator.core.presets.memoir.generated
import xyz.qwewqa.relive.simulator.core.stage.actor.StatData
import xyz.qwewqa.relive.simulator.core.stage.autoskill.EffectTag
import xyz.qwewqa.relive.simulator.core.stage.dress.ActParameters
import xyz.qwewqa.relive.simulator.core.stage.memoir.CutinBlueprint
import xyz.qwewqa.relive.simulator.core.stage.memoir.PartialMemoirBlueprint
val equip3000024 = PartialMemoirBlueprint(
id = 3000024,
name = "練習で疲れたらやっぱコレだね!",
rarity = 3,
baseStats = StatData(
hp = 0,
actPower = 0,
normalDefense = 21,
specialDefense = 21,
),
growthStats = StatData(
hp = 0,
actPower = 0,
normalDefense = 2739,
specialDefense = 2739,
),
additionalTags = listOf(EffectTag.Karen, EffectTag.Mahiru)
)
| 0 | Kotlin | 0 | 0 | 53479fe3d1f4a067682509376afd87bdd205d19d | 821 | relive-simulator | MIT License |
common-impl/src/main/java/com/n0lik/sample/common/AppModule.kt | n0lik | 455,874,699 | false | {"Kotlin": 104510, "Shell": 487} | package com.n0lik.sample.common
import com.n0lik.sample.common.dispatcher.AppDispatcher
import com.n0lik.sample.common.dispatcher.AppDispatcherImpl
import dagger.Binds
import dagger.Module
@Module
internal interface AppModule {
@Binds
fun provideAppDispatcher(impl: AppDispatcherImpl): AppDispatcher
} | 0 | Kotlin | 0 | 7 | 03b9ee2a649bb24e98cf65117e2f9a1ac265d4c6 | 312 | TMDB-Android-Client | MIT License |
src/main/kotlin/herbaccara/toss/payments/model/brandpay/PointCard.kt | herbaccara | 605,863,825 | false | null | package herbaccara.toss.payments.model.brandpay
import com.fasterxml.jackson.annotation.JsonFormat
import java.time.LocalDate
data class PointCard(
val companyCode: String,
val minimumPaymentAmount: Long,
@field:JsonFormat(pattern = "yyyy-MM-dd") val dueDate: LocalDate
)
| 0 | Kotlin | 0 | 1 | de11b9e2cc0a8d8e109e8c29168a10691625b05d | 296 | spring-boot-starter-toss-payments | MIT License |
utils/src/main/java/ro/dobrescuandrei/utils/ContextX.kt | fossabot | 221,451,434 | true | {"Kotlin": 24622} | package ro.dobrescuandrei.utils
import android.app.Activity
import android.content.Context
import android.content.ContextWrapper
fun Context.toActivity() : Activity?
{
if (this is Activity)
return this
if (this is ContextWrapper)
return baseContext.toActivity()
return null
}
| 0 | Kotlin | 0 | 0 | 54e8e5f8115b5a3c71deb6939a657961f98eae79 | 306 | DobDroidMiscUtils | Apache License 2.0 |
app/src/main/java/com/ktor/application/model/response/PostResponse.kt | MansoorNisar92 | 442,403,473 | false | {"Kotlin": 30087} | package com.ktor.application.model.response
import kotlinx.serialization.Serializable
@Serializable
data class PostResponse(
val userId: Int,
val id: Int,
val title: String,
val body: String,
)
| 0 | Kotlin | 1 | 2 | 932e018a232cc39f8784bb670a525aac6f0ee755 | 212 | KTor-Client---Android | Apache License 2.0 |
HKBusETAPhoneCompanion/app/src/main/java/com/loohp/hkbuseta/utils/RemoteActivityUtils.kt | LOOHP | 686,756,915 | false | {"Kotlin": 312062, "Java": 145675} | package com.loohp.hkbuseta.utils
import android.content.Context
import com.google.android.gms.tasks.Task
import com.google.android.gms.wearable.Wearable
import org.json.JSONObject
import java.nio.charset.StandardCharsets
import java.util.concurrent.CompletableFuture
import java.util.concurrent.ForkJoinPool
class RemoteActivityUtils {
companion object {
fun dataToWatch(instance: Context, path: String, data: JSONObject, noWatch: () -> Unit = {}, failed: () -> Unit = {}, success: () -> Unit = {}) {
val dataRaw = data.toString().toByteArray(StandardCharsets.UTF_8)
Wearable.getNodeClient(instance).connectedNodes.addOnCompleteListener { nodes ->
if (nodes.result.isEmpty()) {
noWatch.invoke()
} else {
val futures = nodes.result.map { node ->
val future: CompletableFuture<Task<Int>> = CompletableFuture()
Wearable.getMessageClient(instance).sendMessage(node.id, path, dataRaw).addOnCompleteListener {
future.complete(it)
}
return@map future
}
ForkJoinPool.commonPool().execute {
var isSuccess = false
for (future in futures) {
try {
future.get()
isSuccess = true
break
} catch (_: Exception) {}
}
if (isSuccess) {
success.invoke()
} else {
failed.invoke()
}
}
}
}
}
}
} | 0 | Kotlin | 0 | 0 | 0fea9dc60746fca6ff376dfefb7cf9cf8280647e | 1,861 | HK-Bus-ETA-WearOS | MIT License |
app/src/main/java/io/horizontalsystems/bankwallet/modules/receive/ReceiveViewModel.kt | vab1970 | 553,091,477 | false | {"Kotlin": 3413262, "Shell": 2039, "Ruby": 1350} | package io.horizontalsystems.bankwallet.modules.receive
import androidx.lifecycle.ViewModel
import io.horizontalsystems.bankwallet.core.IAdapterManager
import io.horizontalsystems.bankwallet.entities.Wallet
import io.horizontalsystems.bankwallet.entities.addressType
class ReceiveViewModel(
val wallet: Wallet,
adapterManager: IAdapterManager
) : ViewModel() {
val receiveAddress: String
val addressType: String?
val testNet: Boolean
init {
val receiveAdapter =
adapterManager.getReceiveAdapterForWallet(wallet) ?: throw NoReceiverAdapter()
testNet = !receiveAdapter.isMainnet
receiveAddress = receiveAdapter.receiveAddress
addressType = wallet.coinSettings.derivation?.addressType
}
class NoReceiverAdapter : Error("No Receiver Adapter")
}
| 0 | Kotlin | 0 | 0 | ce11899b20ae8a9baaa4e5c31752c9331f4093ff | 824 | wallet | MIT License |
src/main/kotlin/shirates/core/driver/eventextension/TestDriveOnScreenExtension.kt | ldi-github | 538,873,481 | false | {"Kotlin": 3521140, "JavaScript": 12703, "CSS": 5002} | package shirates.core.driver.eventextension
import shirates.core.driver.TestDrive
import shirates.core.driver.TestElement
import shirates.core.driver.testContext
/**
* onScreen
*/
fun TestDrive.onScreen(
vararg screenNames: String,
onTrue: (TestDriverOnScreenContext) -> Unit
): TestElement {
for (screenName in screenNames) {
if (testContext.screenHandlers.containsKey(screenName).not()) {
testContext.screenHandlers[screenName] = onTrue
}
}
return lastElement
}
/**
* removeScreenHandler
*/
fun TestDrive.removeScreenHandler(
screenName: String,
vararg screenNames: String
): TestElement {
val list = screenNames.toMutableList()
list.add(0, screenName)
for (screenName in list) {
if (testContext.screenHandlers.containsKey(screenName)) {
testContext.screenHandlers.remove(screenName)
}
}
return lastElement
}
/**
* clearScreenHandlers
*/
fun TestDrive.clearScreenHandlers(): TestElement {
testContext.screenHandlers.clear()
return lastElement
} | 0 | Kotlin | 0 | 6 | eadef5e55b91e49f36c8f6782309118b7d9f1f55 | 1,075 | shirates-core | Apache License 2.0 |
omni-core/src/test/java/net/asere/omni/core/ExecutableContainerTest.kt | martppa | 561,509,000 | false | {"Kotlin": 95205} | package net.asere.omni.core
import junit.framework.TestCase.assertEquals
import junit.framework.TestCase.assertTrue
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runTest
import org.junit.Test
import kotlin.coroutines.EmptyCoroutineContext
@OptIn(ExperimentalCoroutinesApi::class)
class ExecutableContainerTest {
@Test
fun `On execution thrown error should be redirected to coroutine exception handler`() = runTest {
val expectedThrownError = Exception("random error message")
var actualThrownError: Throwable? = null
val container = object : ExecutableContainer(
coroutineScope = CoroutineScope(EmptyCoroutineContext),
coroutineExceptionHandler = CoroutineExceptionHandler { _, throwable ->
actualThrownError = throwable
}
) {}
container.execute(
context = EmptyCoroutineContext,
start = CoroutineStart.DEFAULT,
onError = {}
) {
throw expectedThrownError
}
container.awaitJobs()
assertEquals(expectedThrownError, actualThrownError)
}
@Test
fun `On execute must throw an IllegalStateException if the container is not an ExecutableContainer`() = runTest {
val container = object : Container {
override val coroutineScope: CoroutineScope = CoroutineScope(EmptyCoroutineContext)
override val coroutineExceptionHandler: CoroutineExceptionHandler = EmptyCoroutineExceptionHandler
}
val host = object : ContainerHost {
override val container = container
}
try {
host.execute(
scope = ExecutionScope(),
block = {}
)
} catch (ex: Exception) {
assertTrue(ex is IllegalStateException)
}
}
@Test
fun `On execute must call provided block`() = runTest {
var blockExecuted = false
val container = object : ExecutableContainer(
coroutineScope = CoroutineScope(EmptyCoroutineContext),
coroutineExceptionHandler = EmptyCoroutineExceptionHandler
) {}
val host = object : ContainerHost {
override val container = container
}
host.execute(
scope = ExecutionScope()
) {
blockExecuted = true
}
container.awaitJobs()
assert(blockExecuted)
}
@Test
fun `On execute must call provided block with expected scope`() = runTest {
var blockExecutedInScope = false
val container = object : ExecutableContainer(
coroutineScope = CoroutineScope(EmptyCoroutineContext),
coroutineExceptionHandler = EmptyCoroutineExceptionHandler
) {}
val host = object : ContainerHost {
override val container = container
}
val scope = ExecutionScope()
host.execute(
scope = scope
) {
blockExecutedInScope = this == scope
}
container.awaitJobs()
assert(blockExecutedInScope)
}
} | 0 | Kotlin | 0 | 4 | f4a31f942f2ba85e773c1f9e0f6ac94327e22f01 | 3,273 | omni-mvi | MIT License |
wear/src/main/java/com/steleot/jetpackcompose/playground/compose/material/ToggleChipScreen.kt | Sagar19RaoRane | 410,922,276 | true | {"Kotlin": 887894} | package com.steleot.jetpackcompose.playground.compose.material
import androidx.compose.runtime.Composable
@Composable
fun ChipScreen() {
} | 0 | null | 0 | 1 | 91d0a3571031a97a437e13ab103a6cd7092f1598 | 140 | Jetpack-Compose-Playground | Apache License 2.0 |
src/DayTEMPLATE.kt | hoppjan | 433,705,171 | false | {"Kotlin": 29015, "Shell": 338} | fun main() {
/**
*
*/
fun part1(input: List<String>) = 1
/**
*
*/
fun part2(input: List<String>) = 1
runEverything("TEMPLATE", 0, 0, ::part1, ::part2, StringInputReader)
}
| 0 | Kotlin | 0 | 0 | 04f10e8add373884083af2a6de91e9776f9f17b8 | 214 | advent-of-code-2021 | Apache License 2.0 |
buildSrc/src/main/kotlin/io/github/reactivecircus/streamlined/versioning/PrintAppVersionName.kt | DigitalKoi | 255,433,794 | true | {"Kotlin": 339346} | package io.github.reactivecircus.streamlined.versioning
import org.gradle.api.DefaultTask
import org.gradle.api.provider.Property
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.TaskAction
/**
* Prints the app version name to the console.
*/
abstract class PrintAppVersionName : DefaultTask() {
@get:Input
abstract val versionName: Property<String>
@TaskAction
fun print() {
println(versionName.get())
}
companion object {
const val TASK_NAME = "printAppVersionName"
const val TASK_DESCRIPTION = "Prints the app version name to the console."
}
}
| 0 | null | 0 | 1 | 58366bc4bd86a35b4825975120b6366d8273ae12 | 619 | streamlined | Apache License 2.0 |
devfun/src/main/java/com/nextfaze/devfun/overlay/OverlayWindow.kt | NextFaze | 90,596,780 | false | null | package com.nextfaze.devfun.overlay
import android.animation.ValueAnimator
import android.app.Application
import android.content.Context
import android.graphics.PixelFormat
import android.graphics.PointF
import android.graphics.Rect
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.view.Gravity
import android.view.MotionEvent
import android.view.View
import android.view.ViewConfiguration
import android.view.ViewGroup
import android.view.WindowManager
import android.view.animation.OvershootInterpolator
import androidx.annotation.LayoutRes
import androidx.core.math.MathUtils.clamp
import com.nextfaze.devfun.core.ActivityProvider
import com.nextfaze.devfun.core.ForegroundTracker
import com.nextfaze.devfun.core.R
import com.nextfaze.devfun.core.devFun
import com.nextfaze.devfun.error.ErrorHandler
import com.nextfaze.devfun.internal.WindowCallbacks
import com.nextfaze.devfun.internal.android.*
import com.nextfaze.devfun.internal.log.*
import com.nextfaze.devfun.internal.pref.*
import com.nextfaze.devfun.invoke.UiField
import com.nextfaze.devfun.invoke.uiField
import com.nextfaze.devfun.overlay.VisibilityScope.ALWAYS
import com.nextfaze.devfun.overlay.VisibilityScope.FOREGROUND_ONLY
import com.nextfaze.devfun.reference.DeveloperLogger
import java.lang.Math.abs
private const val MIN_ANIMATION_MILLIS = 250L
private const val MAX_ANIMATION_MILLIS = 500L
typealias ClickListener = (OverlayWindow) -> Unit
typealias OverlayReason = () -> CharSequence
typealias VisibilityPredicate = (Context) -> Boolean
typealias VisibilityListener = (visible: Boolean) -> Unit
typealias AttachListener = (attached: Boolean) -> Unit
/**
* Determines when an overlay can be visible.
*
* - [FOREGROUND_ONLY]: Only visible when the app is in the foreground.
* - [ALWAYS]: Visible even if the app has no active activities. _App cannot be swipe-closed if you have one of these._
*/
enum class VisibilityScope {
/** Only visible when the app is in the foreground. */
FOREGROUND_ONLY,
/** Visible even if the app has no active activities. _App cannot be swipe-closed if you have one of these._ */
ALWAYS
}
/**
* Overlay windows are used by DevFun to display the loggers [DeveloperLogger] and DevMenu cog.
*
* @see OverlayManager
* @see OverlayPermissions
*/
interface OverlayWindow {
/** User-friendly name. */
val name: String
/** Preferences file name to store non-default state - must be unique. */
val prefsName: String
/** If the overlay is enabled. Setting to false will hide it (but not remove it from the window). */
var enabled: Boolean
/**
* If enabled the overlay will snap to the closest edge of the window. If disabled it can be moved anywhere and will only snap if it
* leaves the windows's display bounds.
*/
var snapToEdge: Boolean
/**
* Determines when the overlay can be visible.
*
* - [FOREGROUND_ONLY]: Only visible when the app is in the foreground.
* - [ALWAYS]: Visible even if the app has no active activities. _App cannot be swipe-closed if you have one of these._
*/
var visibilityScope: VisibilityScope
/** If disabled this overlay will be visible when dialogs are visible (i.e. when DevMenu opens if `true` (default) this overlay will be hidden). */
var hideWhenDialogsPresent: Boolean
/**
* Insets the overlay window. For a docked window, a pos
*
* e.g. The DevMenu cog has an inset of half its width (and thus sits half way off the window).
*
* For non-docking overlays, this will affect how it sits if you try to drag it off window when it snaps back. _Be careful with this as
* it could result in the overlay sitting outside the window._
*/
var inset: Rect
/** The overlay's view. */
val view: View
/** Flag indicating if the overlay is currently visible. */
val isVisible: Boolean
/**
* Rendered only if the user has not granted overlay permissions.
*
* @see OverlayPermissions
*/
val reason: OverlayReason
/**
* Add this overlay to the window.
*
* @see removeFromWindow
* @see dispose
*/
fun addToWindow()
/**
* Remove this overlay from the window.
*
* @see addToWindow
*/
fun removeFromWindow()
/**
* Reset the position and state to its initial default values and clear its preferences.
*
* Please submit an issue if you needed to call this because it was out of bound or misbehaving our something.
*/
fun resetPositionAndState()
/** Clean up listeners and callbacks of this window. */
fun dispose()
/** Configuration options for this overlay. */
val configurationOptions: List<UiField<*>>
/** Callback when user taps the overlay. */
var onClickListener: ClickListener?
/**
* Callback when user long-presses the overlay (defaults to showing overlay config dialog).
*
* If set then the user must go via the menu (or other DevFun modules) to show the config dialog.
*/
var onLongClickListener: ClickListener?
/** Callback when overlay visibility changes. */
var onVisibilityListener: VisibilityListener?
/** Callback when overlay is added/removed to the window. */
var onAttachListener: AttachListener?
}
internal class OverlayWindowImpl(
private val application: Application,
private val overlays: OverlayManager,
private val permissions: OverlayPermissions,
private val activityProvider: ActivityProvider,
private val foregroundTracker: ForegroundTracker,
private val displayBoundsTracker: DisplayBoundsTracker,
private val windowCallbacks: WindowCallbacks,
@LayoutRes layoutId: Int,
name: String,
override val prefsName: String,
override val reason: OverlayReason,
override var onClickListener: ClickListener? = null,
override var onLongClickListener: ClickListener? = null,
override var onVisibilityListener: VisibilityListener? = null,
override var onAttachListener: AttachListener? = null,
private val visibilityPredicate: VisibilityPredicate? = null,
visibilityScope: VisibilityScope = VisibilityScope.FOREGROUND_ONLY,
dock: Dock = Dock.TOP_LEFT,
delta: Float = 0f,
snapToEdge: Boolean = true,
left: Float = 0f,
top: Float = 0f,
enabled: Boolean = true
) : OverlayWindow {
private val log = logger()
private val windowManager = application.windowManager
private val handler = Handler(Looper.getMainLooper())
private val preferences = KSharedPreferences.named(application, prefsName)
override val name by preferences["name", name]
private var dock by preferences["dock", dock]
private var delta by preferences["delta", delta]
private var left by preferences["left", left]
private var top by preferences["top", top]
override var snapToEdge: Boolean by preferences["snapToEdge", snapToEdge, { _, _ -> updatePosition(false) }]
override var enabled: Boolean by preferences["enabled", enabled, { _, _ -> updateVisibility() }]
override var visibilityScope: VisibilityScope by preferences["visibilityScope", visibilityScope, { _, _ -> updateVisibility() }]
override var hideWhenDialogsPresent: Boolean by preferences["hideWhenDialogsPresent", true, { _, _ -> updateVisibility() }]
override var inset = Rect()
private val isAdded get() = view.parent != null
private val params = createOverlayWindowParams()
private val overlayBounds = Rect()
private var moving = false
override val isVisible get() = isAdded && view.visibility == View.VISIBLE
private val foregroundListener = foregroundTracker.addForegroundChangeListener { updateVisibility() }
private val boundsListener = displayBoundsTracker.addDisplayBoundsChangeListener { _, bounds -> updateOverlayBounds(bounds) }
private val activityWindowFocusChangeListener = windowCallbacks.addResumedActivityFocusChangeListener { updateVisibility() }
private var permissionsListener: OverlayPermissionListener? = null
private var addToWindow = false
init {
if (permissionsListener == null) {
permissions += { if (addToWindow && it) addToWindow() }
}
}
private fun updateOverlayBounds(bounds: Rect, postUpdate: Boolean = true) {
overlayBounds.set(bounds)
loadSavedPosition(postUpdate)
}
private fun updateVisibility() {
if (!isAdded) {
if (addToWindow) {
addToWindow()
}
return
}
val visible = shouldBeVisible()
val visibility = view.visibility
val newVisibility = if (visible) View.VISIBLE else View.GONE
if (visibility != newVisibility) {
view.visibility = newVisibility
onVisibilityListener?.invoke(visible)
}
}
private fun shouldBeVisible() =
enabled && !(hideWhenDialogsPresent && !windowCallbacks.resumedActivityHasFocus) && overlays.canDrawOverlays &&
when (visibilityScope) {
VisibilityScope.FOREGROUND_ONLY -> {
val activity = activityProvider()
when (activity) {
null -> false
else -> foregroundTracker.isAppInForeground && visibilityPredicate?.invoke(activity) != false
}
}
VisibilityScope.ALWAYS -> visibilityPredicate?.invoke(activityProvider() ?: application) != false
}
override val view: View by lazy {
View.inflate(application, layoutId, null).apply {
setOnTouchListener(object : View.OnTouchListener {
private val tapTimeout = ViewConfiguration.getTapTimeout().toLong()
private val longPressTimeout = ViewConfiguration.getLongPressTimeout().toLong()
private val pressTimeout get() = if (onLongClickListener == null) tapTimeout else longPressTimeout
private val onLongClickRunnable = Runnable {
if (onLongClickListener != null) {
longClickPerformed = true
performLongClick()
}
}
private var postedOnLongClickRunnable: Runnable? = null
private fun postOnLongClick() {
if (onLongClickListener != null) {
postedOnLongClickRunnable = onLongClickRunnable
handler.postDelayed(postedOnLongClickRunnable, longPressTimeout)
}
}
private fun removeOnLongClick() {
if (onLongClickListener != null && postedOnLongClickRunnable != null) {
handler.removeCallbacks(postedOnLongClickRunnable)
postedOnLongClickRunnable = null
}
}
private var currentPosition = PointF(0f, 0f)
private var initialPosition = PointF(0f, 0f)
private var initialWindowPosition = PointF(0f, 0f)
private var actionDownTime = 0L
private var longClickPerformed = false
override fun onTouch(v: View, event: MotionEvent): Boolean {
return when (event.action) {
MotionEvent.ACTION_DOWN -> {
postOnLongClick()
actionDownTime = System.currentTimeMillis()
initialPosition.apply {
x = event.rawX
y = event.rawY
}
currentPosition.set(initialPosition)
initialWindowPosition.apply {
x = params.x.toFloat()
y = params.y.toFloat()
}
moving = false
true
}
MotionEvent.ACTION_MOVE -> {
if (longClickPerformed) return true
val rawX = event.rawX
val rawY = event.rawY
val dx = abs(rawX - currentPosition.x)
val dy = abs(rawY - currentPosition.y)
val slop = ViewConfiguration.get(application).scaledTouchSlop
val sinceDown = System.currentTimeMillis() - actionDownTime
if (moving || dx >= slop || dy >= slop || sinceDown > pressTimeout) {
removeOnLongClick()
moving = true
params.x = (rawX - initialPosition.x + initialWindowPosition.x).toInt()
params.y = (rawY - initialPosition.y + initialWindowPosition.y).toInt()
currentPosition.apply {
x = rawX
y = rawY
}
windowManager.updateViewLayout(v, params)
}
true
}
MotionEvent.ACTION_UP -> {
if (!moving) {
val sinceDown = System.currentTimeMillis() - actionDownTime
if (sinceDown < longPressTimeout) {
removeOnLongClick()
v.performClick()
}
} else {
updatePosition(true)
}
moving = false
actionDownTime = 0
longClickPerformed = false
true
}
else -> false
}
}
})
setOnClickListener {
try {
onClickListener?.invoke(this@OverlayWindowImpl)
} catch (t: Throwable) {
devFun.get<ErrorHandler>().onError(t, name, "OnClick invoke exception.")
}
}
setOnLongClickListener {
try {
onLongClickListener?.invoke(this@OverlayWindowImpl)
} catch (t: Throwable) {
devFun.get<ErrorHandler>().onError(t, name, "OnLongClick invoke exception.")
}
true
}
addOnLayoutChangeListener { _, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom ->
if (moving) return@addOnLayoutChangeListener
val prevWidth = oldRight - oldLeft
val newWidth = right - left
val prevHeight = oldBottom - oldTop
val newHeight = bottom - top
if (prevWidth != newWidth || prevHeight != newHeight) {
updatePosition(false)
}
}
}
}
private fun updatePosition(updatePrefs: Boolean) {
if (!snapToEdge && updatePrefs) {
saveNonSnapPosition()
}
adjustPosition(updatePrefs)
}
private fun loadSavedPosition(postUpdate: Boolean) {
val side = dock.takeIf { snapToEdge }
val displacement = delta
// initial position
var x = when (side) {
null -> (left * overlayBounds.width()).toInt()
Dock.LEFT, Dock.TOP_LEFT, Dock.BOTTOM_LEFT -> overlayBounds.left
Dock.RIGHT, Dock.TOP_RIGHT, Dock.BOTTOM_RIGHT -> overlayBounds.right - width
else -> {
val xOffset = (displacement * overlayBounds.width()).toInt()
clamp(overlayBounds.left + xOffset, overlayBounds.left, overlayBounds.right)
}
}
var y = when (side) {
null -> (top * overlayBounds.height()).toInt()
Dock.TOP, Dock.TOP_LEFT, Dock.TOP_RIGHT -> overlayBounds.top
Dock.BOTTOM, Dock.BOTTOM_LEFT, Dock.BOTTOM_RIGHT -> overlayBounds.bottom - height
else -> {
val yOffset = (displacement * overlayBounds.height()).toInt()
clamp(overlayBounds.top + yOffset, overlayBounds.top, overlayBounds.bottom)
}
}
// adjust for view inset
x -= when (side) {
Dock.LEFT, Dock.TOP_LEFT, Dock.BOTTOM_LEFT -> inset.left
Dock.RIGHT, Dock.TOP_RIGHT, Dock.BOTTOM_RIGHT -> -inset.right
else -> 0
}
y -= when (side) {
Dock.TOP, Dock.TOP_LEFT, Dock.TOP_RIGHT -> inset.top
Dock.BOTTOM, Dock.BOTTOM_LEFT, Dock.BOTTOM_RIGHT -> -inset.bottom
else -> 0
}
updateLayout(x, y)
adjustPosition(false)
if (postUpdate && width <= 0 && isAdded && enabled) {
postUpdateOverlayBounds()
}
}
override fun resetPositionAndState() {
preferences.clear()
loadSavedPosition(true)
}
override fun addToWindow() {
addToWindow = true
if (isAdded || !shouldBeVisible()) return
windowManager.addView(view, params)
if (overlayBounds.isEmpty) {
overlayBounds.set(displayBoundsTracker.displayBounds)
}
postUpdateOverlayBounds()
postAttachChangeCallback()
}
private fun postUpdateOverlayBounds() {
// after adding to window for first time or resetting position and state
// we need to wait to next loop to ensure view has had a layout pass (otherwise width=0) and
// end up with a 'left' value outside our overlay bounds
handler.post {
updateOverlayBounds(overlayBounds, false)
}
}
override fun removeFromWindow() {
addToWindow = false
if (!isAdded) return
try {
windowManager.removeView(view)
postAttachChangeCallback()
} catch (t: Throwable) {
log.w(t) { "Exception while removing window view :: view=$view, this=$this" }
}
}
private fun postAttachChangeCallback() {
if (onAttachListener == null) return
handler.post {
onAttachListener?.invoke(isAdded)
}
}
override fun dispose() {
foregroundTracker -= foregroundListener
displayBoundsTracker -= boundsListener
windowCallbacks -= activityWindowFocusChangeListener
}
override val configurationOptions: List<UiField<*>>
get() = listOf(
uiField(application.getString(R.string.df_devfun_enabled), enabled) { enabled = it },
uiField(application.getString(R.string.df_devfun_snap_to_edges), snapToEdge) { snapToEdge = it },
uiField(application.getString(R.string.df_devfun_visibility_scope), visibilityScope) { visibilityScope = it },
uiField(application.getString(R.string.df_devfun_hide_when_dialogs), hideWhenDialogsPresent) { hideWhenDialogsPresent = it }
)
private val width get() = view.width
private val height get() = view.height
private val windowLeft get() = params.x
private val windowRight get() = params.x + width
private val windowTop get() = params.y
private val windowBottom get() = params.y + height
private val leftEdge get() = windowLeft
private val rightEdge get() = overlayBounds.width() - leftEdge - width
private val topEdge get() = windowTop
private val bottomEdge get() = overlayBounds.height() - topEdge - height
private fun adjustPosition(updatePrefs: Boolean) {
// find nearest edge
val leftEdge = leftEdge
val rightEdge = rightEdge
val topEdge = topEdge
val bottomEdge = bottomEdge
// don't trigger force-snap for non-snapping mode
val snapToEdge = snapToEdge
val edgeValue = if (snapToEdge) 0 else -1
// force snap edges if out of bounds (preferentially to left/top if out of multiple sides)
val forceSnapLeft = leftEdge <= edgeValue
val forceSnapRight = !forceSnapLeft && rightEdge <= edgeValue
val forceSnapTop = topEdge <= edgeValue
val forceSnapBottom = !forceSnapTop && bottomEdge <= edgeValue
// where do we want to snap to (preferentially to left/top if equidistant)
val snapToLeft = snapToEdge && leftEdge <= rightEdge && leftEdge <= topEdge && leftEdge <= bottomEdge
val snapToRight = snapToEdge && rightEdge < leftEdge && rightEdge < topEdge && rightEdge < bottomEdge
val snapToTop = snapToEdge && topEdge < leftEdge && topEdge < rightEdge && topEdge <= bottomEdge
val snapToBottom = snapToEdge && bottomEdge < leftEdge && bottomEdge < rightEdge && bottomEdge < topEdge
// where are we snapping to
val toLeft = forceSnapLeft || snapToLeft
val toRight = !toLeft && (forceSnapRight || snapToRight)
val toTop = forceSnapTop || snapToTop
val toBottom = !toTop && (forceSnapBottom || snapToBottom)
// how far to move
val distanceX = when {
!toLeft && !toRight && !snapToEdge -> leftEdge - (left * overlayBounds.width()).toInt()
toLeft -> leftEdge + inset.left
toRight && rightEdge < 0 -> Math.min(-rightEdge, leftEdge) - inset.right // don't go over left of overlay bounds
toRight -> -rightEdge - inset.right
else -> 0
}
val distanceY = when {
!toTop && !toBottom && !snapToEdge -> topEdge - (top * overlayBounds.height()).toInt()
toTop -> topEdge + inset.top
toBottom && bottomEdge < 0 -> Math.min(-bottomEdge, topEdge) - inset.bottom // don't go over top of overlay bounds
toBottom -> -bottomEdge - inset.bottom
else -> 0
}
log.d(predicate = false) {
"""adjustPosition(updatePrefs=$updatePrefs):
|$this
|snapToEdge: $snapToEdge
|forceSnap: {l:$forceSnapLeft, r:$forceSnapRight, t:$forceSnapTop, b:$forceSnapBottom}
|wantSnap: {l:$snapToLeft, r:$snapToRight, t:$snapToTop, b:$snapToBottom}
|willSnap: {l:$toLeft, r:$toRight, t:$toTop, b:$toBottom}
|travel: {x:$distanceX, y:$distanceY}""".trimMargin()
}
animateToPosition(distanceX, distanceY) { percent ->
if (updatePrefs && percent >= 1.0f) {
if (snapToEdge) {
dock = when {
toLeft && toTop -> Dock.TOP_LEFT
toRight && toTop -> Dock.TOP_RIGHT
toLeft && toBottom -> Dock.BOTTOM_LEFT
toRight && toBottom -> Dock.BOTTOM_RIGHT
toLeft -> Dock.LEFT
toRight -> Dock.RIGHT
toTop -> Dock.TOP
toBottom -> Dock.BOTTOM
else -> Dock.TOP_LEFT
}
delta = when (dock) {
Dock.LEFT, Dock.RIGHT -> (params.y - overlayBounds.top) / overlayBounds.height().toFloat()
Dock.TOP, Dock.BOTTOM -> (params.x - overlayBounds.left) / overlayBounds.width().toFloat()
else -> 0f
}
} else {
saveNonSnapPosition()
}
}
}
}
private fun saveNonSnapPosition() {
left = (params.x - overlayBounds.left) / overlayBounds.width().toFloat()
top = (params.y - overlayBounds.top) / overlayBounds.height().toFloat()
}
private fun animateToPosition(distanceX: Int, distanceY: Int, onPercentChange: ((Float) -> Unit)? = null) {
// nothing to see
if (distanceX == 0 && distanceY == 0) {
onPercentChange?.invoke(1f)
return
}
val startX = windowLeft
val startY = windowTop
ValueAnimator.ofFloat(0f, 1.0f)?.apply {
duration = run calculateDuration@{
val proportionX = abs(if (distanceX != 0) distanceX.toFloat() / (overlayBounds.width() / 2f) else 0f)
val proportionY = abs(if (distanceY != 0) distanceY.toFloat() / (overlayBounds.height() / 2f) else 0f)
val proportion = Math.min(proportionX + proportionY, 1f)
Math.max((MAX_ANIMATION_MILLIS * proportion).toLong(), MIN_ANIMATION_MILLIS)
}
interpolator = OvershootInterpolator(0.8f)
addUpdateListener { valueAnimator ->
val percent = valueAnimator.animatedValue as Float
params.apply {
x = startX - (percent * distanceX).toInt()
y = startY - (percent * distanceY).toInt()
}
onPercentChange?.invoke(percent)
updateLayout()
}
start()
}
}
private fun updateLayout(x: Int? = null, y: Int? = null, width: Int? = null, height: Int? = null) {
x?.let { params.x = it }
y?.let { params.y = it }
width?.let { params.width = it }
height?.let { params.height = it }
view.parent?.let {
windowManager.updateViewLayout(view, params)
}
}
override fun toString() =
"""
|overlay: {
| name: $prefsName,
| isAdded: $isAdded,
| prefs: {
| dock: $dock,
| delta: $delta,
| left: $left,
| top: $top,
| snapToEdge: $snapToEdge,
| enabled: $enabled
| },
| position: {
| left: $windowLeft,
| right: $windowRight,
| top: $windowTop,
| bottom: $windowBottom
| },
| size: {
| width: $width,
| height: $height
| },
| inset: {
| left: ${inset.left},
| right: ${inset.right},
| top: ${inset.top},
| bottom: ${inset.bottom}
| },
| edges: {
| left: $leftEdge,
| right: $rightEdge,
| top: $topEdge,
| bottom: $bottomEdge
| },
| view: {w:${view.width}, h:${view.height}, visibility:${Visibility.fromValue(view.visibility)}},
| wind: {w:${params.width}, h:${params.height}},
| bounds: {l:${overlayBounds.left}, r:${overlayBounds.right}, t:${overlayBounds.top}, b:${overlayBounds.bottom}}
|}""".trimMargin()
private enum class Visibility(val value: Int) {
VISIBLE(0), INVISIBLE(4), GONE(8);
companion object {
private val values = values().associateBy { it.value }
fun fromValue(value: Int) = values[value]
}
}
}
internal fun createOverlayWindowParams() =
WindowManager.LayoutParams().apply {
type = windowOverlayType
format = PixelFormat.TRANSLUCENT
flags = WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS or WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
width = ViewGroup.LayoutParams.WRAP_CONTENT
height = ViewGroup.LayoutParams.WRAP_CONTENT
gravity = Gravity.TOP or Gravity.START
}
@Suppress("DEPRECATION")
private val windowOverlayType by lazy {
when {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.O -> WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
else -> WindowManager.LayoutParams.TYPE_PHONE
}
}
| 5 | Kotlin | 4 | 49 | cbf83014e478426750a2785b1e4e6a22d6964698 | 27,898 | dev-fun | Apache License 2.0 |
app/src/main/java/splitties/resources/PrimitiveResources.kt | YZune | 140,358,025 | false | null | /*
* Copyright 2019 <NAME>. Use of this source code is governed by the Apache 2.0 license.
*/
@file:Suppress("NOTHING_TO_INLINE")
package splitties.resources
import android.content.Context
import android.view.View
import androidx.annotation.ArrayRes
import androidx.annotation.AttrRes
import androidx.annotation.BoolRes
import androidx.annotation.IntegerRes
import androidx.fragment.app.Fragment
inline fun Context.bool(@BoolRes boolResId: Int): Boolean = resources.getBoolean(boolResId)
inline fun Fragment.bool(@BoolRes boolResId: Int) = context!!.bool(boolResId)
inline fun View.bool(@BoolRes boolResId: Int) = context.bool(boolResId)
inline fun Context.int(@IntegerRes intResId: Int): Int = resources.getInteger(intResId)
inline fun Fragment.int(@IntegerRes intResId: Int) = context!!.int(intResId)
inline fun View.int(@IntegerRes intResId: Int) = context.int(intResId)
inline fun Context.intArray(
@ArrayRes intArrayResId: Int
): IntArray = resources.getIntArray(intArrayResId)
inline fun Fragment.intArray(@ArrayRes intArrayResId: Int) = context!!.intArray(intArrayResId)
inline fun View.intArray(@ArrayRes intArrayResId: Int) = context.intArray(intArrayResId)
// Styled resources below
fun Context.styledBool(
@AttrRes attr: Int
): Boolean = withStyledAttributes(attr) { getBoolean(it, false) }
inline fun Fragment.styledBool(@AttrRes attr: Int) = context!!.styledBool(attr)
inline fun View.styledBool(@AttrRes attr: Int) = context.styledBool(attr)
fun Context.styledInt(@AttrRes attr: Int): Int = withStyledAttributes(attr) { getInteger(it, -1) }
inline fun Fragment.styledInt(@AttrRes attr: Int) = context!!.styledInt(attr)
inline fun View.styledInt(@AttrRes attr: Int) = context.styledInt(attr)
| 19 | Kotlin | 64 | 530 | a69fb7555e0917e0ba8a0dadbf3248364666b089 | 1,755 | WakeupSchedule_Kotlin | Apache License 2.0 |
application/src/main/java/de/pbauerochse/worklogviewer/settings/WorklogViewerFiles.kt | pbauerochse | 34,003,778 | false | null | package de.pbauerochse.worklogviewer.settings
import de.pbauerochse.worklogviewer.trimToNull
import java.io.File
/**
* Contains directories an files for locally written
* data.
*/
object WorklogViewerFiles {
private val USER_HOME = File(System.getProperty("user.home"))
/**
* The directory within the current users home directory,
* where configurations and logs for the current user
* are being stored
*/
val WORKLOG_VIEWER_HOME = File(USER_HOME, ".youtrack-worklog-viewer")
/**
* If the worklog viewer was installed via the installer,
* this property points to the directory, where it was installed to.
* This might be a place, were multiple users have access to,
* so any files written to here, should not contain any user
* specific data.
*
* If the worklog viewer was not installed using the installer,
* this property points to the [WORKLOG_VIEWER_HOME] directory
*/
val WORKLOG_VIEWER_INSTALLATION_HOME: File
get() {
val fromParameter = System.getProperty("worklogviewer.home")?.trimToNull()
return when {
isValidDirectory(fromParameter) -> File(fromParameter!!)
else -> USER_HOME
}
}
val OLD_SETTINGS_PROPERTIES_FILE = File(USER_HOME, "youtrack-worklog.properties")
val OLD_SETTINGS_JSON_FILE = File(USER_HOME, ".youtrack-worklog-viewer.json")
val SETTINGS_JSON_FILE = File(WORKLOG_VIEWER_HOME, "settings.json")
private fun isValidDirectory(fromParameter: String?): Boolean {
return fromParameter.isNullOrBlank().not() && File(fromParameter!!).isDirectory
}
} | 3 | Kotlin | 11 | 37 | df60ceea733c67e12698942999604acfb71e926f | 1,675 | youtrack-worklog-viewer | MIT License |
prosessering-core/src/main/kotlin/no/nav/yrkesskade/prosessering/internal/TaskWorker.kt | navikt | 449,309,028 | false | {"Kotlin": 132985} | package no.nav.yrkesskade.prosessering.internal
import io.micrometer.core.instrument.Counter
import io.micrometer.core.instrument.Metrics
import no.nav.yrkesskade.prosessering.AsyncITaskStep
import no.nav.yrkesskade.prosessering.TaskFeil
import no.nav.yrkesskade.prosessering.TaskStepBeskrivelse
import no.nav.yrkesskade.prosessering.domene.ITask
import no.nav.yrkesskade.prosessering.domene.ITaskLogg.Companion.BRUKERNAVN_NÅR_SIKKERHETSKONTEKST_IKKE_FINNES
import no.nav.yrkesskade.prosessering.domene.Status
import no.nav.yrkesskade.prosessering.error.RekjørSenereException
import org.slf4j.LoggerFactory
import org.springframework.aop.framework.AopProxyUtils
import org.springframework.core.annotation.AnnotationUtils
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Propagation
import org.springframework.transaction.annotation.Transactional
@Service
class TaskWorker(private val taskService: TaskService,
taskStepTyper: List<AsyncITaskStep<out ITask>>) {
private val taskStepMap: Map<String, AsyncITaskStep<ITask>>
private val maxAntallFeilMap: Map<String, Int>
private val triggerTidVedFeilMap: Map<String, Long>
private val feiltellereForTaskSteps: Map<String, Counter>
private val fullførttellereForTaskSteps: Map<String, Counter>
private val settTilManuellOppfølgningVedFeil: Map<String, Boolean>
init {
val tasksTilTaskStepBeskrivelse: Map<AsyncITaskStep<ITask>, TaskStepBeskrivelse> =
taskStepTyper.map { it as AsyncITaskStep<ITask> }.associateWith { task ->
val aClass = AopProxyUtils.ultimateTargetClass(task)
val annotation = AnnotationUtils.findAnnotation(aClass, TaskStepBeskrivelse::class.java)
requireNotNull(annotation) { "annotasjon mangler" }
annotation
}
taskStepMap = tasksTilTaskStepBeskrivelse.entries.associate { it.value.taskStepType to it.key }
maxAntallFeilMap = tasksTilTaskStepBeskrivelse.values.associate { it.taskStepType to it.maxAntallFeil }
triggerTidVedFeilMap = tasksTilTaskStepBeskrivelse.values.associate { it.taskStepType to it.triggerTidVedFeilISekunder }
settTilManuellOppfølgningVedFeil = tasksTilTaskStepBeskrivelse.values.associate { it.taskStepType to it.settTilManuellOppfølgning }
feiltellereForTaskSteps = tasksTilTaskStepBeskrivelse.values.associate {
it.taskStepType to Metrics.counter("mottak.feilede.tasks",
"status",
it.taskStepType,
"beskrivelse",
it.beskrivelse)
}
fullførttellereForTaskSteps = tasksTilTaskStepBeskrivelse.values.associate {
it.taskStepType to Metrics.counter("mottak.fullfort.tasks",
"status",
it.taskStepType,
"beskrivelse",
it.beskrivelse)
}
}
@Transactional(propagation = Propagation.REQUIRES_NEW)
fun doActualWork(taskId: Long) {
var task = taskService.findById(taskId)
if (task.status != Status.PLUKKET) {
return // en annen pod har startet behandling
}
task = task.behandler()
task = taskService.save(task)
// finn tasktype
val taskStep = finnTaskStep(task.type)
// execute
taskStep.preCondition(task)
taskStep.doTask(task)
taskStep.postCondition(task)
taskStep.onCompletion(task)
task = task.ferdigstill()
taskService.save(task)
secureLog.trace("Ferdigstiller task='{}'", task)
finnFullførtteller(task.type).increment()
}
@Transactional(propagation = Propagation.REQUIRES_NEW)
fun rekjørSenere(taskId: Long, e: RekjørSenereException) {
log.info("Rekjører task=$taskId senere, triggerTid=${e.triggerTid}")
secureLog.info("Rekjører task=$taskId senere, årsak=${e.årsak}", e)
val taskMedNyTriggerTid = taskService.findById(taskId)
.medTriggerTid(e.triggerTid)
.klarTilPlukk(endretAv = BRUKERNAVN_NÅR_SIKKERHETSKONTEKST_IKKE_FINNES,
melding = e.årsak)
taskService.save(taskMedNyTriggerTid)
}
@Transactional(propagation = Propagation.REQUIRES_NEW)
fun doFeilhåndtering(taskId: Long, e: Exception) {
var task = taskService.findById(taskId)
val maxAntallFeil = finnMaxAntallFeil(task.type)
val settTilManuellOppfølgning = finnSettTilManuellOppfølgning(task.type)
secureLog.trace("Behandler task='{}'", task)
task = task.feilet(TaskFeil(task, e), maxAntallFeil, settTilManuellOppfølgning)
// lager metrikker på tasks som har feilet max antall ganger.
if (task.status == Status.FEILET || task.status == Status.MANUELL_OPPFØLGING) {
finnFeilteller(task.type).increment()
log.error("Task ${task.id} av type ${task.type} har feilet/satt til manuell oppfølgning. " +
"Sjekk yrkesskade-prosessering for detaljer")
}
task = task.medTriggerTid(task.triggerTid.plusSeconds(finnTriggerTidVedFeil(task.type)))
taskService.save(task)
secureLog.info("Feilhåndtering lagret ok {}", task)
}
private fun finnTriggerTidVedFeil(taskType: String): Long {
return triggerTidVedFeilMap[taskType] ?: error("Ukjent tasktype $taskType")
}
private fun finnFeilteller(taskType: String): Counter {
return feiltellereForTaskSteps[taskType] ?: error("Ukjent tasktype $taskType")
}
private fun finnFullførtteller(taskType: String): Counter {
return fullførttellereForTaskSteps[taskType] ?: error("Ukjent tasktype $taskType")
}
private fun finnMaxAntallFeil(taskType: String): Int {
return maxAntallFeilMap[taskType] ?: error("Ukjent tasktype $taskType")
}
private fun finnTaskStep(taskType: String): AsyncITaskStep<ITask> {
return taskStepMap[taskType] ?: error("Ukjent tasktype $taskType")
}
private fun finnSettTilManuellOppfølgning(taskType: String): Boolean {
return settTilManuellOppfølgningVedFeil[taskType] ?: error("Ukjent tasktype $taskType")
}
@Transactional(propagation = Propagation.REQUIRES_NEW)
fun markerPlukket(id: Long): ITask? {
var task = taskService.findById(id)
if (task.status.kanPlukkes()) {
task = task.plukker()
return taskService.save(task)
}
return null
}
companion object {
private val secureLog = LoggerFactory.getLogger("secureLogger")
private val log = LoggerFactory.getLogger(this::class.java)
}
}
| 3 | Kotlin | 0 | 0 | cf93ce5b92bdeae56903dd10028416ab4535edb9 | 6,998 | yrkesskade-prosessering-backend | MIT License |
app/src/main/java/com/ttt/elpucherito/activities/restaurants/RestaurantAdapter.kt | AdrianZamarra | 333,070,968 | false | null | package com.ttt.elpucherito.activities.restaurants
import android.content.Context
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.RatingBar
import android.widget.TextView
import android.widget.Toast
import androidx.recyclerview.widget.RecyclerView
import com.ttt.elpucherito.R
import com.ttt.elpucherito.activities.restaurant.RestaurantActivity
import com.ttt.elpucherito.db.ElPucheritoDB
import java.lang.Exception
class RestaurantAdapter(private val restaurantsList : List<RestaurantItem>, private val context: Context) : RecyclerView.Adapter<RestaurantAdapter.ChartViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ChartViewHolder {
val itemView = LayoutInflater
.from(parent.context)
.inflate(R.layout.restaurants_list, parent, false)
return ChartViewHolder(
itemView
)
}
override fun getItemCount() = restaurantsList.size
override fun onBindViewHolder(holder: ChartViewHolder, position: Int) {
val currentItem = restaurantsList[position]
holder.name.text = currentItem.name
val id = context.resources.getIdentifier(currentItem.image, "drawable", context.packageName)
holder.image.setImageResource(id)
holder.category.text = currentItem.category
try {
holder.assesment.rating = getAvgAssessment(currentItem)
}catch (e : Exception){
holder.assesment.rating = 0f
}
holder.bind(currentItem, context)
}
@Throws(Exception::class)
private fun getAvgAssessment(restaurant : RestaurantItem) : Float{
var nAssesments = 0
var finalAssessment = 0f
Thread {
val db = ElPucheritoDB.getInstance(context).assessmentDao().getAssessments()
db.forEach {
if (it.restaurant_id == restaurant.resturant_id){
finalAssessment += it.rating
nAssesments += 1
}
}
}.start()
Thread.sleep(10)
return finalAssessment / nAssesments
}
class ChartViewHolder(itemView : View) : RecyclerView.ViewHolder(itemView) {
val name : TextView = itemView.findViewById(R.id.restaurants_name)
var image : ImageView = itemView.findViewById(R.id.restaurants_image)
val assesment : RatingBar = itemView.findViewById(R.id.restaurants_rating)
val category : TextView = itemView.findViewById(R.id.restaurants_tv_category)
fun bind(restaurant : RestaurantItem, context: Context) {
image.setOnClickListener {
val intent = Intent(context, RestaurantActivity::class.java)
intent.putExtra("Restaurant", restaurant)
context.startActivity(intent)
}
}
}
} | 0 | Kotlin | 0 | 1 | a3e53f90d9c2d47168e33df8fb676881b0262ba6 | 2,968 | El-Pucherito | Apache License 2.0 |
verik-compiler/src/main/kotlin/io/verik/compiler/core/declaration/kt/CoreKtIo.kt | frwang96 | 269,980,078 | false | null | /*
* SPDX-License-Identifier: Apache-2.0
*/
package io.verik.compiler.core.declaration.kt
import io.verik.compiler.ast.element.expression.common.ECallExpression
import io.verik.compiler.ast.element.expression.common.EExpression
import io.verik.compiler.ast.element.expression.kt.EStringTemplateExpression
import io.verik.compiler.ast.property.ExpressionStringEntry
import io.verik.compiler.core.common.BasicCoreFunctionDeclaration
import io.verik.compiler.core.common.Core
import io.verik.compiler.core.common.CorePackage
import io.verik.compiler.core.common.CoreScope
import io.verik.compiler.core.common.TransformableCoreFunctionDeclaration
import io.verik.compiler.target.common.Target
/**
* Core functions from the Kotlin IO package.
*/
object CoreKtIo : CoreScope(CorePackage.KT_IO) {
val F_print_Any = object : TransformableCoreFunctionDeclaration(parent, "print", "fun print(Any)") {
override fun transform(callExpression: ECallExpression): EExpression {
val valueArgument = callExpression.valueArguments[0]
val expression = if (valueArgument.type.reference == Core.Kt.C_String) {
valueArgument
} else {
EStringTemplateExpression(
callExpression.location,
listOf(ExpressionStringEntry(callExpression.valueArguments[0]))
)
}
return ECallExpression(
callExpression.location,
Core.Kt.C_Unit.toType(),
Target.F_write,
null,
false,
arrayListOf(expression),
ArrayList()
)
}
}
val F_print_Boolean = object : TransformableCoreFunctionDeclaration(parent, "print", "fun print(Boolean)") {
override fun transform(callExpression: ECallExpression): EExpression {
return F_print_Any.transform(callExpression)
}
}
val F_print_Int = object : TransformableCoreFunctionDeclaration(parent, "print", "fun print(Int)") {
override fun transform(callExpression: ECallExpression): EExpression {
return F_print_Any.transform(callExpression)
}
}
val F_print_Double = object : TransformableCoreFunctionDeclaration(parent, "print", "fun print(Double)") {
override fun transform(callExpression: ECallExpression): EExpression {
return F_print_Any.transform(callExpression)
}
}
val F_println = BasicCoreFunctionDeclaration(parent, "println", "fun println()", Target.F_display)
val F_println_Any = object : TransformableCoreFunctionDeclaration(parent, "println", "fun println(Any)") {
override fun transform(callExpression: ECallExpression): EExpression {
val valueArgument = callExpression.valueArguments[0]
val expression = if (valueArgument.type.reference == Core.Kt.C_String) {
valueArgument
} else {
EStringTemplateExpression(
callExpression.location,
listOf(ExpressionStringEntry(callExpression.valueArguments[0]))
)
}
return ECallExpression(
callExpression.location,
Core.Kt.C_Unit.toType(),
Target.F_display,
null,
false,
arrayListOf(expression),
ArrayList()
)
}
}
val F_println_Boolean = object : TransformableCoreFunctionDeclaration(parent, "println", "fun println(Boolean)") {
override fun transform(callExpression: ECallExpression): EExpression {
return F_println_Any.transform(callExpression)
}
}
val F_println_Int = object : TransformableCoreFunctionDeclaration(parent, "println", "fun println(Int)") {
override fun transform(callExpression: ECallExpression): EExpression {
return F_println_Any.transform(callExpression)
}
}
val F_println_Double = object : TransformableCoreFunctionDeclaration(parent, "println", "fun println(Double)") {
override fun transform(callExpression: ECallExpression): EExpression {
return F_println_Any.transform(callExpression)
}
}
}
| 0 | Kotlin | 1 | 33 | ee22969235460fd144294bcbcbab0338c638eb92 | 4,287 | verik | Apache License 2.0 |
src/main/kotlin/imgui/imgui/logging.kt | pakoito | 158,626,298 | true | {"Kotlin": 1162977, "C++": 26396, "Java": 8892, "GLSL": 552} | package imgui.imgui
import imgui.ImGui.button
import imgui.ImGui.popAllowKeyboardFocus
import imgui.ImGui.popId
import imgui.ImGui.popItemWidth
import imgui.ImGui.pushAllowKeyboardFocus
import imgui.ImGui.pushId
import imgui.ImGui.pushItemWidth
import imgui.ImGui.sameLine
import imgui.ImGui.setClipboardText
import imgui.ImGui.sliderInt
import imgui.g
import java.io.FileWriter
/** Logging/Capture: all text output from interface is captured to tty/file/clipboard.
* By default, tree nodes are automatically opened during logging. */
interface imgui_logging {
// IMGUI_API void LogToTTY(int max_depth = -1); // start logging to tty
// IMGUI_API void LogToFile(int max_depth = -1, const char* filename = NULL); // start logging to file
/** start logging ImGui output to OS clipboard */
fun logToClipboard(maxDepth: Int = -1) {
if (g.logEnabled) return
val window = g.currentWindow!!
assert(g.logFile != null)
g.logFile = null
g.logEnabled = true
g.logStartDepth = window.dc.treeDepth
if (maxDepth >= 0)
g.logAutoExpandMaxDepth = maxDepth
}
/** stop logging (close file, etc.) */
fun logFinish() {
if (!g.logEnabled) return
logText("%s","\n")
if(g.logFile != null){
g.logFile = null
}
if(g.logClipboard.length > 1){
setClipboardText(g.logClipboard.toString())
g.logClipboard = StringBuilder()
}
g.logEnabled = false
}
/** Helper to display buttons for logging to tty/file/clipboard */
fun logButtons() {
pushId("LogButtons")
val logToTty = button("Log To TTY"); sameLine()
val logToFile = button("Log To File"); sameLine()
val logToClipboard = button("Log To Clipboard"); sameLine()
pushItemWidth(80f)
pushAllowKeyboardFocus(false)
sliderInt("Depth", g::logAutoExpandMaxDepth, 0, 9)
popAllowKeyboardFocus()
popItemWidth()
popId()
// Start logging at the end of the function so that the buttons don't appear in the log
if (logToTty) TODO()//LogToTTY(g.LogAutoExpandMaxDepth)
if (logToFile) TODO()//LogToFile(g.LogAutoExpandMaxDepth, g.IO.LogFilename)
if (logToClipboard) TODO()//LogToClipboard(g.LogAutoExpandMaxDepth)
}
/** pass text data straight to log (without being displayed) */
fun logText(fmt: String, vararg args: Any) {
if(!g.logEnabled)
return
if(g.logFile != null) {
val writer = FileWriter(g.logFile, true)
writer.write(String.format(fmt, args))
}else{
g.logClipboard.append(String.format(fmt, args))
}
}
} | 0 | Kotlin | 1 | 1 | 46b930e62e42d26b6e63f3bfd24046c27080902b | 2,813 | imgui | MIT License |
app/src/main/java/ethiopia/covid/android/ui/fragment/HeatMapFragment.kt | brookmg | 249,926,845 | false | null | package ethiopia.covid.android.ui.fragment
import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.MapView
import com.google.android.gms.maps.MapsInitializer
import com.google.android.gms.maps.model.Circle
import com.google.android.gms.maps.model.CircleOptions
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.MapStyleOptions
import com.google.android.material.floatingactionbutton.FloatingActionButton
import ethiopia.covid.android.App.Companion.instance
import ethiopia.covid.android.R
import ethiopia.covid.android.data.WorldCovid
import ethiopia.covid.android.network.API.OnItemReady
import ethiopia.covid.android.util.Utils.calculateTheDelta
import ethiopia.covid.android.util.Utils.getCurrentTheme
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import timber.log.Timber
import kotlin.math.max
/**
* Created by BrookMG on 3/23/2020 in ethiopia.covid.android.ui.fragment
* inside the project CoVidEt .
*/
class HeatMapFragment : BaseFragment() {
private var mainMapView: MapView? = null
private var backButton: FloatingActionButton? = null
private val circles: MutableList<Circle> = mutableListOf()
override fun onResume() {
super.onResume()
mainMapView?.onResume()
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val mainView = inflater.inflate(R.layout.heat_map_fragment, container, false)
mainMapView = mainView.findViewById(R.id.main_map_view)
backButton = mainView.findViewById(R.id.back_button)
CoroutineScope(Dispatchers.Default).launch { MapsInitializer.initialize(activity) }
mainMapView?.getMapAsync { googleMap: GoogleMap ->
val success = googleMap.setMapStyle(
MapStyleOptions.loadRawResourceStyle(
activity,
if (getCurrentTheme(activity) == 0) R.raw.light_map_style else R.raw.dark_map_style
))
if (!success) {
Timber.e("Some problem happened around parsing the style.")
}
setUpClusterManager(googleMap)
}
mainMapView?.onCreate(savedInstanceState)
backButton?.setOnClickListener { activity?.onBackPressed() }
return mainView
}
private fun setUpClusterManager(map: GoogleMap) {
if (activity == null) return
instance.mainAPI.getWorldStat(object : OnItemReady<List<WorldCovid>?> {
override fun onItem(item: List<WorldCovid>?, err: String?) {
CoroutineScope(Dispatchers.Main).launch { addCountryCircles(map, item ?: listOf()) }
}
})
}
private suspend fun addCountryCircles(map: GoogleMap, items: List<WorldCovid>) {
withContext(Dispatchers.Default) {
var maximum = Int.MIN_VALUE
for ((_, cases) in items) {
if (maximum < cases) maximum = cases
}
maximum /= items.size
for ((_, cases, _, _, _, _, _, _, _, _, _, countryInfo) in items) {
val colors = calculateTheDelta(intArrayOf(234, 20, 20), intArrayOf(20, 180, 12),
max(0f, 1f.coerceAtMost((1f - cases.toFloat() / maximum.toFloat()))))
withContext(Dispatchers.Main) {
circles.add(
map.addCircle(CircleOptions()
.center(LatLng(countryInfo!!.lat, countryInfo.lon))
.radius(80000.0.coerceAtLeast(400000.0.coerceAtMost(10 * (cases.toDouble() / maximum.toDouble()))))
.fillColor(Color.argb(186, colors[0], colors[1], colors[2]))
.strokeColor(Color.argb(0, 255, 255, 255))
.clickable(false)
.strokeWidth(0f))
)
}
}
}
}
// We should consider working on this method
// private void scaleAllCircles(float mapZoomLevel, boolean isZoomingIn) {
// for (Circle circle : circles) {
// circle.setVisible(true);
// circle.setRadius(isZoomingIn ? Math.max(20, circle.getRadius() / (mapZoomLevel)) : Math.min(400_000, circle.getRadius() * (mapZoomLevel * 3.8)));
// }
// }
override fun onPause() {
super.onPause()
mainMapView?.onPause()
}
override fun onLowMemory() {
super.onLowMemory()
mainMapView?.onLowMemory()
}
override fun onDestroy() {
super.onDestroy()
mainMapView?.onDestroy()
}
companion object {
// float mapZoomLevel = 0f;
fun newInstance(): HeatMapFragment {
val args = Bundle()
val fragment = HeatMapFragment()
fragment.arguments = args
return fragment
}
}
} | 14 | Kotlin | 5 | 18 | 2feaf0f03d316c4fc08c2ebea1d77ee773eaa5b6 | 5,287 | CovidAndroid | Apache License 2.0 |
owmdroidclient/src/main/kotlin/com/zymosi3/util/Util.kt | zymosi3 | 42,667,295 | false | null | package com.zymosi3.util
/**
* Common util functions
*/
/**
* Current thread name.
*/
public fun threadName():String {
return Thread.currentThread().name
}
/**
* Helper method for logcat prints current thread name as "Thread : <threadName>".
*/
public fun logThreadName():String {
return "Thread: ${threadName()}.";
}
/**
* Tries to do action n times. In case of any exception sleeps the given interval and tries again.
*/
public fun <Result> retry(n: Int, sleepMs: Int, action: (tryN: Int) -> Result): Result {
for (i in 1..n) {
try {
return action(i)
} catch (t: Throwable) {
if (i == n) {
throw t
}
Thread.sleep(sleepMs.toLong())
}
}
throw RuntimeException("That should never happen")
}
| 0 | Kotlin | 0 | 0 | 3581e2f54f993809b5485551730c2d50998a6318 | 810 | owmdroidclient | Apache License 2.0 |
base/sdk-common/src/main/java/com/android/ide/common/fonts/FontDetail.kt | qiangxu1996 | 255,410,085 | false | {"Java": 38854631, "Kotlin": 10438678, "C++": 1701601, "HTML": 795500, "FreeMarker": 695102, "Starlark": 542991, "C": 148853, "RenderScript": 58853, "Shell": 51803, "CSS": 36591, "Python": 32879, "XSLT": 23593, "Batchfile": 8747, "Dockerfile": 7341, "Emacs Lisp": 4737, "Makefile": 4067, "JavaScript": 3488, "CMake": 3295, "PureBasic": 2359, "GLSL": 1628, "Objective-C": 308, "Prolog": 214, "D": 121} | /*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.ide.common.fonts
import java.util.Objects
const val DEFAULT_WEIGHT = 400
const val DEFAULT_WIDTH = 100
/**
* A [FontDetail] is a reference to a specific font with weight, width, and italics attributes.
* Each instance refers to a possibly remote (*.ttf) font file.
*/
class FontDetail {
val family: FontFamily
val weight: Int
val width: Int
val italics: Boolean
val fontUrl: String
val styleName: String
val hasExplicitStyle: Boolean
val fontStyle: String
get() = if (italics) "italic" else "normal"
constructor(fontFamily: FontFamily, font: MutableFontDetail) {
family = fontFamily
weight = font.weight
width = font.width
italics = font.italics
fontUrl = font.fontUrl
hasExplicitStyle = font.hasExplicitStyle
styleName = generateStyleName(font)
}
/**
* Special use for creating synonyms in font-family files with references to other fonts.
*/
constructor(detail: FontDetail, withStyle: MutableFontDetail) {
family = detail.family
weight = withStyle.weight
width = withStyle.width
italics = withStyle.italics
fontUrl = detail.fontUrl
hasExplicitStyle = detail.hasExplicitStyle
styleName = generateStyleName(withStyle)
}
fun toMutableFontDetail(): MutableFontDetail {
return MutableFontDetail(weight, width, italics, fontUrl, styleName, false, hasExplicitStyle)
}
fun generateQuery(exact: Boolean): String {
if (weight == DEFAULT_WEIGHT && width == DEFAULT_WIDTH && !italics && !exact) {
return family.name
}
val query = StringBuilder().append("name=").append(family.name)
if (weight != DEFAULT_WEIGHT) {
query.append("&weight=").append(weight)
}
if (italics) {
query.append("&italic=1")
}
if (width != DEFAULT_WIDTH) {
query.append("&width=").append(width)
}
if (exact) {
query.append("&besteffort=false")
}
return query.toString()
}
override fun hashCode(): Int {
return Objects.hash(weight, width, italics)
}
override fun equals(other: Any?): Boolean {
return other is FontDetail
&& weight == other.weight
&& width == other.width
&& italics == other.italics
}
private fun generateStyleName(font: MutableFontDetail): String {
if (font.styleName.isNotEmpty()) {
return font.styleName
}
return getWeightStyleName(font.weight) + getItalicStyleNameSuffix(font.italics)
}
private fun getWeightStyleName(weight: Int): String {
when (weight) {
100 -> return "Thin"
200 -> return "Extra-Light"
300 -> return "Light"
400 -> return "Regular"
500 -> return "Medium"
600 -> return "Semi-Bold"
700 -> return "Bold"
800 -> return "Extra-Bold"
900 -> return "Black"
else -> return if (weight > 400) {
"Custom-Bold"
} else {
"Custom-Light"
}
}
}
private fun getItalicStyleNameSuffix(italics: Boolean): String {
return if (italics) " Italic" else ""
}
}
| 1 | Java | 1 | 1 | 3411c5436d0d34e6e2b84cbf0e9395ac8c55c9d4 | 3,997 | vmtrace | Apache License 2.0 |
libB/src/main/java/package_B_2/Foo_B_20.kt | alekseikurnosenko | 118,451,085 | false | {"Kotlin": 466490, "Python": 1964} | package package_B_11
class Foo_B_1110 {
fun foo0() {
var i=0
i+=Math.random().toInt()
i+=Math.random().toInt()
i+=Math.random().toInt()
i+=Math.random().toInt()
i+=Math.random().toInt()
i+=Math.random().toInt()
i+=Math.random().toInt()
i+=Math.random().toInt()
i+=Math.random().toInt()
i+=Math.random().toInt()
i+=Math.random().toInt()
i+=Math.random().toInt()
i+=Math.random().toInt()
i+=Math.random().toInt()
i+=Math.random().toInt()
i+=Math.random().toInt()
i+=Math.random().toInt()
i+=Math.random().toInt()
i+=Math.random().toInt()
i+=Math.random().toInt()
Foo_B_119().foo0()
}
} | 0 | Kotlin | 0 | 0 | 8182b7f6e92f9d65efb954c32ca640fe50ae6b79 | 583 | ModuleTest | Apache License 2.0 |
src/main/kotlin/watch/dependency/dependencyNotifier.kt | JakeWharton | 281,296,048 | false | {"Kotlin": 58079, "Shell": 2975, "Dockerfile": 1099} | package watch.dependency
import java.nio.file.Path
import kotlin.io.path.getLastModifiedTime
import kotlin.io.path.readText
import kotlin.time.Duration
import kotlinx.coroutines.CoroutineStart.UNDISPATCHED
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.supervisorScope
class DependencyNotifier(
private val mavenRepositoryFactory: MavenRepository.Factory,
private val database: Database,
private val versionNotifier: VersionNotifier,
private val configPath: Path,
private val debug: Debug = Debug.Disabled,
) {
private fun readRepositoryConfigs(): List<RepositoryConfig> {
val configs = RepositoryConfig.parseConfigsFromToml(configPath.readText())
for (config in configs) {
debug.log { config.toString() }
}
return configs
}
private fun createChecker(config: RepositoryConfig): DependencyChecker {
val mavenRepository = mavenRepositoryFactory.maven2(config.name, config.host)
return DependencyChecker(
mavenRepository = mavenRepository,
coordinates = config.coordinates,
database = database,
versionNotifier = versionNotifier,
debug = debug,
)
}
suspend fun run() {
val configs = readRepositoryConfigs()
supervisorScope {
for (config in configs) {
launch {
createChecker(config).check()
}
}
}
}
suspend fun monitor(checkInterval: Duration): Nothing {
var lastModified: Long? = null
var checkers = emptyList<DependencyChecker>()
while (true) {
// Parse the config inside the loop so you can edit it while running.
val newLastModified = configPath.getLastModifiedTime().toMillis()
if (newLastModified != lastModified) {
lastModified = newLastModified
checkers = readRepositoryConfigs().map(::createChecker)
}
supervisorScope {
for (checker in checkers) {
launch {
checker.check()
}
}
}
debug.log { "Sleeping $checkInterval..." }
delay(checkInterval)
}
}
}
private class DependencyChecker(
private val mavenRepository: MavenRepository,
private val coordinates: List<MavenCoordinate>,
private val database: Database,
private val versionNotifier: VersionNotifier,
private val debug: Debug,
) {
suspend fun check() {
supervisorScope {
for (coordinates in coordinates) {
launch(start = UNDISPATCHED) {
debug.log { "Fetching metadata for $coordinates..." }
val versions = mavenRepository.versions(coordinates)
debug.log { "$coordinates $versions" }
if (versions != null) {
val notifyVersions = if (database.coordinateSeen(coordinates)) {
versions.all.filterNot { database.coordinateVersionSeen(coordinates, it) }
} else {
listOf(versions.latest)
}
for (mavenVersion in versions.all) {
database.markCoordinateVersionSeen(coordinates, mavenVersion)
}
for (version in notifyVersions) {
versionNotifier.notify(mavenRepository.name, coordinates, version)
}
}
}
}
}
}
}
| 5 | Kotlin | 9 | 266 | 65f638421b52783db640c7b136df7ca9984f4ee4 | 2,964 | dependency-watch | Apache License 2.0 |
example/application/src/main/kotlin/com/github/pozo/mapper/DivisionMapper.kt | Pozo | 163,214,478 | false | null | package com.github.pozo.mapper
import com.github.pozo.domain.Division
import com.github.pozo.domain.DivisionDto
import org.mapstruct.Mapper
import org.mapstruct.Mappings
@Mapper
interface DivisionMapper {
@Mappings
fun toDto(division: Division): DivisionDto
@Mappings
fun toOrder(division: Division): Division
} | 7 | Kotlin | 20 | 102 | 85b95d912f263e0bbeb40e5158c2593d08ce96db | 332 | mapstruct-kotlin | MIT License |
api/src/main/java/com/nspu/riotapi/models/MatchTimeline.kt | nspu | 127,918,560 | false | null | package com.nspu.riotapi.models
import android.os.Parcel
import android.os.Parcelable
data class MatchTimeline(
var frames: List<MatchFrame>? = null,
var frameInterval: Long? = null
) : Parcelable {
constructor(source: Parcel) : this(
source.createTypedArrayList(MatchFrame.CREATOR),
source.readValue(Long::class.java.classLoader) as Long?
)
override fun describeContents() = 0
override fun writeToParcel(dest: Parcel, flags: Int) = with(dest) {
writeTypedList(frames)
writeValue(frameInterval)
}
companion object {
@JvmField
val CREATOR: Parcelable.Creator<MatchTimeline> = object : Parcelable.Creator<MatchTimeline> {
override fun createFromParcel(source: Parcel): MatchTimeline = MatchTimeline(source)
override fun newArray(size: Int): Array<MatchTimeline?> = arrayOfNulls(size)
}
}
} | 0 | Kotlin | 0 | 1 | 75fa318a2a936438edc9eb45056cd1b27bcc0f3d | 925 | riot-api-android | MIT License |
core/modal/src/main/kotlin/com/walletconnect/modal/ui/model/UiState.kt | WalletConnect | 435,951,419 | false | {"Kotlin": 2031812, "Java": 4358, "Shell": 1892} | package com.walletconnect.modal.ui.model
sealed class UiState<T> {
data class Success<T>(val data: T) : UiState<T>()
data class Loading<T>(val data: T? = null, val loadingState: LoadingState = LoadingState.REFRESH) : UiState<T>()
data class Error<T>(val error: Throwable) : UiState<T>()
}
enum class LoadingState {
REFRESH, APPEND
}
| 157 | Kotlin | 76 | 172 | e86a4194a5bb37e9f66feec4192d108dadfa4e81 | 351 | WalletConnectKotlinV2 | Apache License 2.0 |
theme-m3/ui/src/main/java/org/gdglille/devfest/android/components/tags/AmethystTagTokens.kt | kipkiruikenedy | 660,904,865 | false | null | package org.gdglille.devfest.android.components.tags
import org.gdglille.devfest.android.theme.DecorativeColorSchemeTokens
internal object AmethystTagTokens {
val ContainerColor = DecorativeColorSchemeTokens.Amethyst
val ContentColor = DecorativeColorSchemeTokens.OnAmethyst
}
| 0 | Kotlin | 0 | 0 | 97d4f369b4a4ad62135465f147251ab4eec9aec0 | 287 | conference-android-and--IOS-APP-kotlin | Apache License 2.0 |
src/chapter4/section1/Search.kt | w1374720640 | 265,536,015 | false | {"Kotlin": 1373556} | package chapter4.section1
/**
* 统计图中所有与点s连通的点
*/
abstract class Search(graph: Graph, s: Int) {
/**
* 判断点v是否与s连通
*/
abstract fun marked(v: Int): Boolean
/**
* 与s点联通的顶点总数
*/
abstract fun count(): Int
} | 0 | Kotlin | 1 | 6 | 879885b82ef51d58efe578c9391f04bc54c2531d | 297 | Algorithms-4th-Edition-in-Kotlin | MIT License |
app/src/main/java/co/candyhouse/app/base/BaseDeviceFG.kt | ccjpn | 538,786,907 | false | {"Kotlin": 264438, "Java": 14044} | package co.candyhouse.app.base
import android.widget.TextView
import androidx.fragment.app.activityViewModels
import co.candyhouse.app.R
import co.candyhouse.app.tabs.devices.model.CHDeviceViewModel
import com.google.android.material.snackbar.Snackbar
import no.nordicsemi.android.dfu.DfuProgressListener
import no.nordicsemi.android.dfu.DfuServiceListenerHelper
open class BaseDeviceFG(layout: Int) : BaseNFG(layout) {
private val dfuText: TextView? by lazy { getView()?.findViewById<TextView>(R.id.device_version_txt) }
private val snackbar: Snackbar? by lazy {
Snackbar.make(getView()!!, "", Snackbar.LENGTH_INDEFINITE)
}
val mDeviceModel: CHDeviceViewModel by activityViewModels()
override fun onResume() {
super.onResume()
DfuServiceListenerHelper.registerProgressListener(activity!!, dfuLs)
}
override fun onPause() {
super.onPause()
DfuServiceListenerHelper.unregisterProgressListener(activity!!, dfuLs)
snackbar?.dismiss()
}
val dfuLs = object : DfuProgressListener {
override fun onProgressChanged(deviceAddress: String, percent
: Int, speed: Float, avgSpeed: Float, currentPart: Int, partsTotal: Int) {
dfuText?.post {
dfuText?.text = "$percent%"
} ?: snackbar?.setText("$percent%")
}
override fun onDeviceDisconnecting(deviceAddress: String?) {
dfuText?.post {
dfuText?.text = getString(R.string.onDeviceDisconnecting)//初期化中…
} ?: snackbar?.setText(R.string.onDeviceDisconnecting)
}
override fun onDeviceDisconnected(deviceAddress: String) {
dfuText?.post {
dfuText?.text = getString(R.string.onDeviceDisconnected)//初期化中…
} ?: snackbar?.setText(R.string.onDeviceDisconnected)
}
override fun onDeviceConnected(deviceAddress: String) {
dfuText?.post {
dfuText?.text = getString(R.string.onDeviceConnected)//初期化中…
} ?: snackbar?.setText(R.string.onDeviceConnected)
}
override fun onDfuProcessStarting(deviceAddress: String) {
dfuText?.post {
dfuText?.text = getString(R.string.onDfuProcessStarting)//初期化中…
}
?: snackbar?.show()
snackbar?.setText(R.string.onDfuProcessStarting)
}
override fun onDfuAborted(deviceAddress: String) {
dfuText?.post {
dfuText?.text = getString(R.string.onDfuAborted)//初期化中…
} ?: snackbar?.setText(R.string.onDfuAborted)
}
override fun onEnablingDfuMode(deviceAddress: String) {
dfuText?.post {
dfuText?.text = getString(R.string.onEnablingDfuMode)//初期化中…
} ?: snackbar?.setText(R.string.onEnablingDfuMode)
}
override fun onDfuCompleted(deviceAddress: String) {
dfuText?.post {
dfuText?.text = getString(R.string.onDfuCompleted)//初期化中…
} ?: snackbar?.setText(R.string.onDfuCompleted)
snackbar?.dismiss()
}
override fun onFirmwareValidating(deviceAddress: String) {
dfuText?.post {
dfuText?.text = getString(R.string.onFirmwareValidating)//初期化中…
} ?: snackbar?.setText(R.string.onFirmwareValidating)
}
override fun onDfuProcessStarted(deviceAddress: String) {
dfuText?.post {
dfuText?.text = getString(R.string.onDfuProcessStarted)//初期化中…
} ?: snackbar?.setText(R.string.onDfuProcessStarted)
}
override fun onDeviceConnecting(deviceAddress: String) {
dfuText?.post {
dfuText?.text = getString(R.string.onDeviceConnecting)//初期化中…
} ?: snackbar?.setText(R.string.onDeviceConnecting)
}
override fun onError(deviceAddress: String, error
: Int, errorType: Int, message: String?) {
dfuText?.post {
dfuText?.text = getString(R.string.dfu_status_error_msg) + ":" + message
} ?: snackbar?.apply {
setAction(R.string.cancel) {
snackbar?.dismiss()
}
setText(getString(R.string.dfu_status_error_msg) + ":" + message)
}
}
}
}
| 0 | Kotlin | 0 | 0 | 376f861b9c15fdd286513a255f3c69cbc249c4e0 | 4,488 | sesame-demo | MIT License |
open_source_licences/src/main/java/mohamedalaa/open_source_licences/view_model/fragments/OpenSourceLicencesFragmentViewModel.kt | MohamedAlaaEldin636 | 178,618,838 | false | null | /*
* Copyright (c) 2019 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and limitations under the License.
*/
package mohamedalaa.open_source_licences.view_model.fragments
import android.app.Application
import android.content.res.AssetManager
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import mohamedalaa.mautils.core_android.extensions.logError
import mohamedalaa.mautils.core_android.extensions.logWarn
import mohamedalaa.mautils.core_kotlin.extensions.substring
import mohamedalaa.mautils.lifecycle_extensions.custom_classes.QuickMutableLiveData
import mohamedalaa.open_source_licences.custom_classes.Constants
import java.io.BufferedReader
import java.io.InputStreamReader
internal class OpenSourceLicencesFragmentViewModel(
application: Application,
assetsFolderPath: String,
searchViewIsIconified: Boolean,
searchText: String?,
matchCase: Boolean,
anyLetter: Boolean,
includeAuthor: Boolean
) : AndroidViewModel(application) {
/** [Pair.first] represents license name while [Pair.second] represents content isa. */
val mutableLiveDataLicencesNameAndContent = MutableLiveData<List<Pair<String, String>>>()
val mutableLiveDataSearchViewIsIconified = QuickMutableLiveData(searchViewIsIconified)
val mutableLiveDataSearchText = QuickMutableLiveData(searchText)
val mutableLiveDataMatchCase = QuickMutableLiveData(matchCase)
val mutableLiveDataAnyLetter = QuickMutableLiveData(anyLetter)
val mutableLiveDataIncludeAuthor = QuickMutableLiveData(includeAuthor)
val mutableLiveDataLicensesAreEmpty = QuickMutableLiveData(false)
init {
viewModelScope.launch(Dispatchers.Default) {
val assetManager: AssetManager? = application.assets
val subPathList = withContext(Dispatchers.IO) {
assetManager?.list(assetsFolderPath)?.toList()?.filterNotNull()
?.filter { it.length > 4 && it.endsWith(".txt") }.orEmpty()
}
val apacheLicenceNameAndContent = listOf(Constants.APACHE_2_0_LICENCE_NAME to Constants.APACHE_2_0_LICENCE_CONTENT)
val listOfLicencesNameAndContent = apacheLicenceNameAndContent + subPathList.mapNotNull {
val fullPath = if (assetsFolderPath.isNotEmpty()) "$assetsFolderPath/$it" else it
val licenceName = it.substring(0, ".")
readTextFileToGetLicenceContent(assetManager, fullPath)?.run {
licenceName to this
}
}
if (listOfLicencesNameAndContent.size != listOfLicencesNameAndContent.distinct().size) {
logWarn(
"There are 2 or more licences with same content" +
"\nIt's better to remove duplications since .txt files affect size of app isa."
)
}
withContext(Dispatchers.Main) {
mutableLiveDataLicencesNameAndContent.value = listOfLicencesNameAndContent
}
}
}
private fun readTextFileToGetLicenceContent(assetManager: AssetManager?, fullPath: String): String? {
if (assetManager == null) return null
var reader: BufferedReader? = null
var licenceContent = ""
try {
reader = BufferedReader(InputStreamReader(assetManager.open(fullPath), "UTF-8"))
reader.forEachLine {
licenceContent += it
licenceContent += "\n"
}
licenceContent = licenceContent.trim()
}catch (throwable: Throwable) {
logError("Unexpected error code 1092 isa, with msg ${throwable.message}\nAnd stacktrace $throwable")
}finally {
kotlin.runCatching { reader?.close() }
}
return if (licenceContent.isEmpty()) null else licenceContent
}
} | 0 | Kotlin | 0 | 0 | 16d6a8fdbf0d851c74485bdc1a609afaf3bb76f9 | 4,495 | MAUtils | Apache License 2.0 |
Baselibrary/src/main/java/com/kotlin/base/ui/fragment/BaseMvpFragment.kt | heisexyyoumo | 145,665,152 | false | null | package com.kotlin.base.ui.fragment
import android.app.Activity
import android.os.Bundle
import com.kotlin.base.common.BaseApplication
import com.kotlin.base.injection.component.ActivityComponent
import com.kotlin.base.injection.component.DaggerActivityComponent
import com.kotlin.base.injection.module.ActivityModule
import com.kotlin.base.injection.module.LifecycleProviderModule
import com.kotlin.base.presenter.BasePresenter
import com.kotlin.base.presenter.view.BaseView
import org.jetbrains.anko.support.v4.toast
import javax.inject.Inject
open abstract class BaseMvpFragment<T : BasePresenter<*>> : BaseFragment(), BaseView {
override fun showLoading() {
}
override fun hideLoading() {
}
override fun onError(text:String) {
toast(text)
}
@Inject
lateinit var mPresenter: T
lateinit var activityComponent: ActivityComponent
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
initActivityInjection()
injectComponent()
}
abstract fun injectComponent()
private fun initActivityInjection() {
activityComponent = DaggerActivityComponent.builder().
appComponent((activity?.application as BaseApplication).appComponent)
.activityModule(ActivityModule(activity as Activity))
.lifecycleProviderModule(LifecycleProviderModule(this))
.build()
}
} | 0 | Kotlin | 1 | 2 | 27fea0090cea5fb636f8db5025379d274693b1b4 | 1,456 | KotlinMall | Apache License 2.0 |
app/src/main/java/com/callebdev/valorant/domain/models/Ability.kt | callebdev | 515,700,444 | false | {"Kotlin": 48662} | package com.callebdev.valorant.domain.models
data class Ability(
val description: String,
val displayIcon: String,
val displayName: String,
val slot: String,
)
| 0 | Kotlin | 1 | 11 | 2869944f539f987e09d90955eb34990aa9f1f11f | 177 | Valorant | Apache License 2.0 |
mobile_app1/module425/src/main/java/module425packageKt0/Foo74.kt | uber-common | 294,831,672 | false | null | package module425packageKt0;
annotation class Foo74Fancy
@Foo74Fancy
class Foo74 {
fun foo0(){
module425packageKt0.Foo73().foo3()
}
fun foo1(){
foo0()
}
fun foo2(){
foo1()
}
fun foo3(){
foo2()
}
} | 6 | Java | 6 | 72 | 9cc83148c1ca37d0f2b2fcb08c71ac04b3749e5e | 233 | android-build-eval | Apache License 2.0 |
src/main/java/cn/tino/animatedwebp/MainScreen.kt | TinoGuo | 96,733,128 | false | null | package cn.tino.animatedwebp
import javafx.beans.binding.BooleanBinding
import javafx.collections.FXCollections
import javafx.collections.ObservableList
import javafx.scene.control.*
import javafx.scene.layout.GridPane
import javafx.stage.FileChooser
import main.java.cn.tino.animatedwebp.Styles.Companion.mainScreen
import main.java.cn.tino.animatedwebp.WebpParameter
import sun.misc.Launcher
import tornadofx.*
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.InputStream
import java.nio.charset.Charset
/**
* mailTo:<EMAIL>
* Created by tino on 2017 June 17, 18:08.
*/
class MainScreen : View() {
companion object {
val singleFileCmd = " -frame %s +%d+0+0+0-b"
val encodeWebpCmd = "%s/cwebp -q %d %s -o %s"
val webpMuxCmd = "%s/webpmux %s -loop %d -bgcolor 0,0,0,0 -o %s.webp"
val singleWebpCmd = "%s/cwebp -q %d %s -o %s"
val ERROR = "Error"
}
override val root = GridPane()
val parameter = WebpParameter()
var projectDir: File by singleAssign()
var quality: TextField by singleAssign()
var speed: TextField by singleAssign()
var loop: CheckBox by singleAssign()
var loopTimes: TextField by singleAssign()
var chooseFile: Button by singleAssign()
var chooseDir: Button by singleAssign()
var execute: Button by singleAssign()
var fileFilter: Spinner<String> by singleAssign()
init {
title = "Animated Webp Tools"
with(root) {
maxWidth = 1200.px.value
addClass(mainScreen)
row("webp quality(0~100)") {
quality = textfield {
text = "75"
bind(parameter.qualityProperty())
}
}
row("webp speed(frames/s)") {
speed = textfield {
text = "30"
bind(parameter.speedProperty())
}
}
row("infinity loop") {
loop = checkbox {
bind(parameter.loopInfinityProperty())
}
label("loop times")
loopTimes = textfield {
disableProperty().bind(parameter.loopInfinityProperty().isEqualTo(true))
bind(parameter.loopTimesProperty())
}
}
row {
chooseFile = button("choose single file") {
setOnAction {
parameter.fileSelected = tornadofx.chooseFile(null,
arrayOf(FileChooser.ExtensionFilter("image", "*.jpg", "*.png", "*.gif")),
FileChooserMode.Single,
primaryStage,
null).let {
if (it.isEmpty()) {
return@let null
}
return@let it.first()
}
}
}
chooseDir = button("choose dir") {
setOnAction {
parameter.fileSelected = chooseDirectory(null,
null,
primaryStage,
null)
}
}
label("File filter")
fileFilter = spinner(FXCollections.observableArrayList(".png", ".jpg", ".gif"),
false,
parameter.fileFilterProperty()) {
disableProperty().bind(parameter.fileSelectedProperty().let {
return@let object : BooleanBinding() {
init {
super.bind(it)
}
override fun getDependencies(): ObservableList<*> {
return FXCollections.singletonObservableList(it)
}
override fun dispose() {
super.unbind(it)
}
override fun computeValue(): Boolean {
if (it.get() == null) {
return true
}
return it.get().isFile
}
}
})
}
}
row("") {
execute = button("execute") {
setOnAction {
when (parameter.fileSelected.isDirectory) {
true -> processMultiFiles()
false -> processSingle()
}
}
disableProperty().bind(parameter.qualityProperty().isNull.or(parameter.speedProperty().isNull)
.or(parameter.fileSelectedProperty().isNull))
}
}
}
quality.text = "75"
speed.text = "30"
loop.isSelected = true
loopTimes.text = "1"
val file = File(javaClass.protectionDomain.codeSource.location.path)
if (file.isFile) {
var preProcess = false
file.parentFile.listFiles().forEach { it ->
if (it.name.contains("webpLib")) {
preProcess = it.list().findAllLib()
return@forEach
}
}
if (!preProcess) {
alert(Alert.AlertType.ERROR, ERROR, "webpLib directory lose!", ButtonType.OK,
actionFn = {
buttonType ->
if (buttonType.buttonData == ButtonBar.ButtonData.OK_DONE) {
System.exit(0)
}
})
} else {
projectDir = file.parentFile.listFiles{pathname -> pathname.endsWith("webpLib")}.first()
}
} else {
val url = Launcher::class.java.getResource("/")
if (url != null) {
projectDir = File(File(url.toURI()).parentFile.parentFile.absolutePath + "/webpLib")
} else {
alert(Alert.AlertType.ERROR, ERROR, "webpLib directory lose!", ButtonType.OK,
actionFn = {
buttonType ->
if (buttonType.buttonData == ButtonBar.ButtonData.OK_DONE) {
System.exit(0)
}
})
}
}
}
fun Array<String>.findAllLib(): Boolean {
val count = mutableMapOf<String, Int>()
forEach { it ->
count.put(it, 1)
}
return count.size == 3
}
fun String?.isDigitsOnly(): Boolean {
val len = this?.length ?: 0
var cp: Int
var i = 0
while (i < len) {
cp = Character.codePointAt(this, i)
if (!Character.isDigit(cp)) {
return false
}
i += Character.charCount(cp)
}
return true
}
fun InputStream.convertString(): String {
val outStream = ByteArrayOutputStream(1024)
val data: ByteArray = ByteArray(1024)
var count = this.read(data, 0, 1024)
while (count != -1) {
outStream.write(data, 0, 1024)
count = this.read(data, 0, 1024)
}
return String(outStream.toByteArray(), Charset.defaultCharset())
}
fun Runtime.openFileBrowser(path: String) {
val os = System.getProperty("os.name").toLowerCase()
if (os.startsWith("win")) {
this.exec("explorer.exe /select,$path")
} else {
this.exec("open $path")
}
}
fun preProcessParameter(): Boolean {
if (parameter.quality.isEmpty() || parameter.speed.isEmpty() || (!parameter.loopInfinity && parameter.loopTimes.isEmpty())) {
alert(Alert.AlertType.ERROR, ERROR, "content must not empty!", ButtonType.OK)
return false
}
if (!parameter.quality.isDigitsOnly()) {
alert(Alert.AlertType.ERROR, ERROR, "quality must be digits!", ButtonType.OK)
return false
}
if (parameter.quality.toInt() !in 1..100) {
alert(Alert.AlertType.ERROR, ERROR, "quality must in the range(0,100]!", ButtonType.OK)
return false
}
if (!parameter.speed.isDigitsOnly()) {
alert(Alert.AlertType.ERROR, "", "speed must be digits!", ButtonType.OK)
return false
}
if (!parameter.loopInfinity && !parameter.loopTimes.isDigitsOnly()) {
alert(Alert.AlertType.ERROR, "", "loop times must be digits!", ButtonType.OK)
return false
}
if (parameter.loopTimes.toInt() <= 0) {
alert(Alert.AlertType.ERROR, ERROR, "loop time must greater than 0!", ButtonType.OK)
return false
}
return true
}
fun processSingle() {
if (preProcessParameter()) {
val runTime = Runtime.getRuntime()
val tmpName = parameter.fileSelected.absolutePath.replaceAfter('.', "webp")
runAsync {
runTime.exec(String.format(singleWebpCmd,
projectDir,
parameter.quality.toInt(),
parameter.fileSelected.absolutePath,
tmpName)).apply { waitFor() }
} ui { process ->
when (process.exitValue()) {
0 -> alert(Alert.AlertType.INFORMATION, "", tmpName, ButtonType.OK)
else -> runAsync {
process.errorStream.convertString()
} ui { str ->
alert(Alert.AlertType.ERROR, ERROR, str, ButtonType.OK)
}
}
}
}
}
fun processMultiFiles() {
if (!preProcessParameter()) {
return
}
runAsync {
val runTime = Runtime.getRuntime()
var files = parameter.fileSelected.listFiles { pathname ->
pathname!!.name.endsWith(parameter.fileFilter)
}
if (files.isEmpty()) {
return@runAsync null
}
files.forEach { it ->
val name = it.name.replace(parameter.fileFilter, "")
runTime.exec(String.format(encodeWebpCmd,
projectDir.absolutePath,
parameter.quality.toInt(),
it.absolutePath,
it.parent + "/" + name + ".webp"))
.waitFor()
}
val sb = StringBuilder()
files = parameter.fileSelected.listFiles { pathname -> pathname!!.name.endsWith(".webp") }
if (files.isEmpty()) {
return@runAsync null
}
files.sort()
for (file in files) {
sb.append(String.format(singleFileCmd, file.absolutePath, 1000 / parameter.speed.toInt()))
}
val loopCount = if (parameter.loopInfinity) 0 else parameter.loopTimes.toInt()
runTime.exec(String.format(webpMuxCmd,
projectDir.absolutePath,
sb.toString(),
loopCount,
parameter.fileSelected.parent + "/" + parameter.fileSelected.name))
.apply {
this.waitFor()
files.forEach { it.delete() }
}
} ui { process ->
if (process == null) {
alert(Alert.AlertType.ERROR, ERROR, "selected files is empty", ButtonType.OK)
}
when (process?.exitValue()) {
0 -> alert(Alert.AlertType.INFORMATION,
"",
"output file is: ${parameter.fileSelected.absolutePath}.webp\nOpen the directory now?",
ButtonType.OK,
ButtonType.CANCEL,
actionFn = {
btnType ->
if (btnType.buttonData == ButtonBar.ButtonData.OK_DONE) {
Runtime.getRuntime().openFileBrowser(parameter.fileSelected.parentFile.absolutePath)
}
})
else -> runAsync {
process?.errorStream?.convertString() ?: "EXECUTE FAIL!"
} ui { str ->
alert(Alert.AlertType.ERROR, ERROR, str, ButtonType.OK)
}
}
}
}
}
| 0 | Kotlin | 5 | 33 | 25ef5674915ca37fcd4e47a8fecaacdd7e00fe1f | 12,918 | AnimatedWebp2 | Apache License 2.0 |
year2019/day14/part1/src/test/kotlin/com/curtislb/adventofcode/year2019/day14/part1/Year2019Day14Part1Test.kt | curtislb | 226,797,689 | false | {"Kotlin": 2146738} | package com.curtislb.adventofcode.year2019.day14.part1
import java.nio.file.Paths
import kotlin.test.assertEquals
import org.junit.jupiter.api.Test
/**
* Tests the solution to the puzzle for 2019, day 14, part 1.
*/
class Year2019Day14Part1Test {
@Test
fun testSolutionWithRealInput() {
assertEquals(843220L, solve())
}
@Test
fun testSolutionWithTestInput() {
val solution = solve(inputPath = Paths.get("..", "input", "test_input.txt"))
assertEquals(2210736L, solution)
}
}
| 0 | Kotlin | 1 | 1 | 6b64c9eb181fab97bc518ac78e14cd586d64499e | 527 | AdventOfCode | MIT License |
Synergy-Android/app/src/main/java/io/anyrtc/teamview/activity/MainActivity.kt | anyRTC-UseCase | 436,955,268 | false | {"Go": 189589, "Vue": 120209, "JavaScript": 82884, "Kotlin": 70978, "Java": 12422, "HTML": 1534, "CSS": 594} | package io.anyrtc.teamview.activity
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.widget.TextView
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import android.view.View
import android.view.Window
import android.view.WindowInsets
import android.view.WindowManager
import androidx.core.view.GravityCompat
import androidx.activity.viewModels
import androidx.recyclerview.widget.RecyclerView
import io.anyrtc.teamview.R
import io.anyrtc.teamview.databinding.ActivityMainBinding
import io.anyrtc.teamview.utils.*
import io.anyrtc.teamview.vm.MainVM
import io.anyrtc.teamview.utils.RtcManager
import org.ar.rtm.LocalInvitation
import java.util.*
import kotlin.collections.HashSet
class MainActivity : BaseActivity() {
private lateinit var binding: ActivityMainBinding
private val vm: MainVM by viewModels()
private lateinit var uid: str
private var roomId = ""
private var roomName = ""
private var roomTs = 0
private var userName = ""
private var notMore = false
private var loadingMore = false
private var isRefreshing = false
private val itemBtnStatusTextArr = arrayOf("邀请中", "通话中", "邀请", "离线")
private val itemStatusColorArr = arrayOf(
R.color.blue, R.color.red, R.color.blue, R.color.gray
)
private val statusToWeightsArr = arrayOf(1, 2, 0, 3)
private val adapter by lazy {
Adapter(arrayListOf(), this@MainActivity::bindItem, R.layout.item_main)
}
private val mLocalDataMap = HashMap<String, ItemData>()
private var mTimer: Timer? = null
private val mRtcHandler = RtcHandler()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
requestWindowFeature(Window.FEATURE_NO_TITLE)
binding = ActivityMainBinding.inflate(layoutInflater)
hideBottomNavigationBar()
setContentView(binding.root)
// full screen, hide status bar
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R)
window.insetsController?.hide(WindowInsets.Type.statusBars())
else this.window.setFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN
)
val userTs = intent.getIntExtra("userTs", 0)
val userType = intent.getIntExtra("userType", 0)
val workName = intent.getStringExtra("workName")!!
val rtcToken = intent.getStringExtra("rtcToken")!!
roomId = intent.getStringExtra("roomId")!!
roomName = intent.getStringExtra("roomName")!!
roomTs = intent.getIntExtra("roomTs", 0)
userName = intent.getStringExtra("userName")!!
uid = SpUtil.get().getString(MyConstants.UID, "")!!
if (uid.isEmpty()) {
// error
}
vm.addRtcHandler(mRtcHandler)
initRtc(rtcToken, roomId)
initWidget()
initData()
}
private fun initWidget() {
binding.recycle.run {
layoutManager = LinearLayoutManager(
this@MainActivity, LinearLayoutManager.VERTICAL, false
)
adapter = [email protected]
addItemDecoration(MainItemDecoration())
addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrollStateChanged(view: RecyclerView, newState: Int) {
if (!canScrollVertically(1)) {
loadOrRefreshSpecialList()
}
}
})
}
binding.hangUp.setOnClickListener { // TODO: may need a dialog to confirm
finish()
}
binding.invite.setOnClickListener {
binding.drawer.openDrawer(GravityCompat.END)
}
binding.close.setOnClickListener {
binding.drawer.closeDrawer(GravityCompat.END)
}
binding.refresh.setOnRefreshListener {
notMore = false
loadOrRefreshSpecialList(false)
}
}
private fun initData() {
vm.specialListResponse.observe(this) {
binding.refresh.isRefreshing = false
if (it.data == null) {
Toast.makeText(this@MainActivity, it.errMsg, Toast.LENGTH_SHORT).show()
loadingMore = false
return@observe
}
// 1. Add if local hashMap don't have that uid
// 2. Also add it to the new ArrayList
// 3. Sorted new ArrayList & add to adapter & notify refresh
val list = it.data.list
if (list.size == adapter.data.size && !isRefreshing) {
binding.refresh.isRefreshing = false
notMore = true
loadingMore = false
return@observe
}
isRefreshing = false
val copiedLocalMap = HashMap(mLocalDataMap)
val newList = mutableListOf<ItemData>()
var index = 0
val adapterSize = adapter.itemCount
val sortedList = list.map { item ->
// 0=邀请中,1=通话中,2=空闲,3=离线
val status = if (item.userState == 1) if (item.roomId != roomId) 2 else 1 else item.userState
val itemData = ItemData(
item.uid,
item.userName,
status,
weights = statusToWeightsArr[status]
)
// check status change if not null
if (mLocalDataMap[item.uid] != null) {
copiedLocalMap.remove(item.uid)
val localItemData = mLocalDataMap[item.uid]!!
if (localItemData.status == 0 && itemData.status == 2) {
itemData.status = 0
itemData.weights = statusToWeightsArr[0]
} else {
mLocalDataMap.remove(item.uid)
}
}
if (index++ >= adapterSize) {
newList.add(itemData)
}
itemData
}.sortedBy { item -> item.weights }
if (copiedLocalMap.isNotEmpty())
mLocalDataMap.removeAll(copiedLocalMap)
adapter.data.addAll(newList)
adapter.notifyItemRangeInserted(adapterSize, newList.size)
adapter.data.clear()
adapter.data.addAll(sortedList)
adapter.notifyItemRangeChanged(0, sortedList.size)
binding.title.text = String.format("邀请协调(%d)", adapter.data.size)
loadingMore = false
}
loadOrRefreshSpecialList()
}
private fun <K, V> HashMap<K, V>.removeAll(m: Map<in K, V>): Boolean {
var modified = false
if (size > m.size) {
val i = m.iterator()
while (i.hasNext()) {
modified = modified or (remove(i.next().key) != null)
}
} else {
val i = iterator()
while (i.hasNext()) {
if (m.containsKey(i.next().key)) {
i.remove()
modified = true
}
}
}
return modified
}
private fun initRtc(rtcToken: str, roomId: str) {
vm.sdkJoinRoom(this, rtcToken, roomId, uid) { joinFailed ->
if (joinFailed) {
Toast.makeText(binding.root.context, "join rtc failed", Toast.LENGTH_SHORT).show()
throw IllegalStateException("join rtc failed.")
}
}
val textureView = vm.createRendererView(this, uid)
binding.cameraParent.run {
removeAllViews()
addView(textureView)
vm.switchCamera()
}
}
private fun loadOrRefreshSpecialList(isLoadMore: Boolean = true) {
if (isLoadMore && notMore)
return
if (loadingMore)
return
loadingMore = true
binding.refresh.isRefreshing = true
if (isLoadMore) {
vm.getSpecialList(1, adapter.data.size + 10)
return
}
// 下拉刷新清除本地数据
binding.title.text = "邀请协调"
val removeSize = adapter.data.size
adapter.data.clear()
adapter.notifyItemRangeRemoved(0, removeSize)
vm.getSpecialList(1, 10)
}
override fun adapterScreenVertical(): Boolean {
return true
}
private fun bindItem(holder: Adapter.Holder, data: ItemData, position: int) {
val nickname = holder.findView<TextView>(R.id.nickname)
val statusView = holder.findView<TextView>(R.id.invite_status)
nickname.text = data.nickname
statusView.text = itemBtnStatusTextArr[data.status]
statusView.visibility = if (data.status == 3) View.GONE else View.VISIBLE
statusView.setBackgroundResource(
if (data.status == 2) R.drawable.shape_item_req_btn else android.R.color.transparent
)
statusView.setTextColor(ContextCompat.getColor(this, itemStatusColorArr[data.status]))
statusView.setOnClickListener {
if (data.status != 2 || binding.refresh.isRefreshing)
return@setOnClickListener
val sendCallBlock = {
vm.sendCall(
data.uid,
roomId,
roomName,
roomTs,
userName
) { success, err, localInvitation ->
if (!success) {
if (null != err)
Toast.makeText(this@MainActivity, err.toString(), Toast.LENGTH_SHORT).show()
return@sendCall
}
data.status = 0
data.weights = statusToWeightsArr[data.status]
data.sentInvitation = localInvitation
adapter.notifyItemChanged(position)
mLocalDataMap[data.uid] = data
}
}
if (data.sentInvitation != null) {
vm.cancelCall(data.sentInvitation!!) { cancelSuccess, cancelErr ->
if (!cancelSuccess) {
if (null != cancelErr)
Toast.makeText(this, cancelErr.toString(), Toast.LENGTH_LONG).show()
return@cancelCall
}
sendCallBlock.invoke()
}
} else {
sendCallBlock.invoke()
}
}
}
private inner class RtcHandler : RtcManager.RtcHandler() {
private var waitingDestroyThread: Thread? = null
override fun onCallLocalAccept(var1: LocalInvitation?) {
var1 ?: return
var i = 0
while (1 < adapter.data.size) {
if (adapter.data[i].uid == var1.calleeId) {
break
}
i++
}
if (i == adapter.data.size) {
// not found.
return
}
runOnUiThread {
val nickname = adapter.data[i].nickname
binding.notify.showMessage("$nickname 同意了你的邀请")
refreshSpecialList()
}
}
override fun onCallLocalReject(var1: LocalInvitation?) {
var1 ?: return
var i = 0
while (1 < adapter.data.size) {
if (adapter.data[i].uid == var1.calleeId) {
break
}
i++
}
if (i == adapter.data.size) {
// not found.
return
}
mLocalDataMap[adapter.data[i].uid]?.status = 2
runOnUiThread {
val nickname = adapter.data[i].nickname
binding.notify.showMessage("$nickname 拒绝了你的邀请")
refreshSpecialList()
}
}
override fun onCallFailure(var1: LocalInvitation?, var2: Int) {
var1 ?: return
if (var2 == 0) return
var i = 0
while (true) {
if (adapter.data[i].uid == var1.calleeId)
break
i++
}
if (i == adapter.data.size) {
// not found.
return
}
mLocalDataMap[adapter.data[i].uid]?.status = 2
runOnUiThread {
Toast.makeText(applicationContext, "对方60秒内未接受邀请", Toast.LENGTH_SHORT).show()
refreshSpecialList()
}
}
override fun onUserJoined(uid: String?, elapsed: Int) {
uid ?: return
var i = 0
while (i < adapter.data.size) {
val item = adapter.data[i]
if (item.uid == uid)
break
++i
}
if (i < adapter.data.size) runOnUiThread {
val nickname = adapter.data[i].nickname
binding.notify.showMessage("$nickname 进入了协同")
refreshSpecialList()
}
}
override fun onUserLeave(uid: String?, reason: Int) {
uid ?: return
var i = 0
while (i < adapter.data.size) {
val item = adapter.data[i]
if (item.uid == uid)
break
++i
}
if (i < adapter.data.size) runOnUiThread {
val nickname = adapter.data[i].nickname
binding.notify.showMessage("$nickname 离开了协同")
refreshSpecialList()
}
}
override fun onRtcTokenExpired() {
runOnUiThread {
Toast.makeText(this@MainActivity, "体验时间已到", Toast.LENGTH_LONG).show()
finish()
}
}
override fun selfNetworkChange(disconnect: bool) {
if (!disconnect && waitingDestroyThread != null) {
waitingDestroyThread?.interrupt()
waitingDestroyThread = null
runOnUiThread { binding.loading.hideLoading() }
} else if (disconnect && waitingDestroyThread == null) {
runOnUiThread {
binding.loading.run {
setCardColor(Color.TRANSPARENT)
setFontColor(Color.WHITE)
showLoading("连网中")
}
}
waitingDestroyThread = ShutdownThread {
runOnUiThread {
Toast.makeText(this@MainActivity, "连接已断开", Toast.LENGTH_LONG).show()
finish()
}
}
waitingDestroyThread?.start()
}
}
override fun onOtherClientLogin() {
runOnUiThread {
finish()
}
}
private fun refreshSpecialList() {
binding.refresh.isRefreshing = true
isRefreshing = true
vm.getSpecialList(1, adapter.itemCount)
}
}
private fun hideBottomNavigationBar() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R)
window.insetsController?.hide(WindowInsets.Type.navigationBars())
else
window.decorView.systemUiVisibility =
window.decorView.systemUiVisibility or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_LOW_PROFILE
}
override fun onDestroy() {
if (roomId.isNotBlank())
vm.leaveRoom(roomId, uid)
vm.releaseRtc()
vm.removeRtcHandler(mRtcHandler)
mTimer?.let {
it.cancel()
it.purge()
}
mTimer = null
adapter.data.forEach { item ->
if (item.sentInvitation != null) {
vm.cancelCall(item.sentInvitation!!)
}
}
super.onDestroy()
}
data class ItemData(
val uid: str,
val nickname: str,
/*
* 0=邀请中,1=通话中,2=空闲,3=离线
* 0=邀请中,1=在线,2=空闲,3=离线, 4=通话中
*/
var status: int,
var weights: int,
var sentInvitation: LocalInvitation? = null
)
private class ShutdownThread(private val destroyCallback: () -> Unit) : Thread() {
private var lifetime = 60
override fun run() {
while (!isInterrupted) {
try {
sleep(1000)
if (--lifetime <= 0) {
destroyCallback.invoke()
break
}
} catch (e: InterruptedException) {
break
}
}
}
}
}
| 0 | Go | 0 | 2 | 15b62cc83b366f2b516f1538e5f537bb473bacbb | 15,947 | Synergy | MIT License |
library/src/main/java/com/secoo/coobox/library/ktx/java/io/FileExt.kt | secoo-android | 314,480,117 | false | null | package com.secoo.coobox.library.ktx.java.io
import com.secoo.coobox.library.util.crash.getValueSafely
import org.apache.commons.io.FileUtils
import java.io.File
/**
* 获取目录的文件大小,bytes为单位
* 如果是非目录,返回null
*/
val File.directorySize: Long?
get() {
return getValueSafely {
FileUtils.sizeOfDirectory(this)
}
}
| 0 | Kotlin | 4 | 42 | 1fe4f10c0144972c3c263994634018ca2a239c6f | 392 | coobox | Apache License 2.0 |
src/main/kotlin/common/IssuesLoader.kt | JetBrains | 317,343,420 | false | null | package com.jetbrains.space.import.common
import com.jetbrains.space.import.space.IssueTemplate
import kotlin.reflect.KClass
interface IssuesLoader {
suspend fun load(params: Params): IssuesLoadResult
sealed interface Params {
class Notion(
val query: String?,
val databaseId: String,
val assigneeProperty: ExternalProjectProperty?,
val assigneePropertyMappingType: ProjectPropertyType = defaultProjectPropertyType,
val statusProperty: ExternalProjectProperty?,
val statusPropertyMappingType: ProjectPropertyType = defaultProjectPropertyType,
val tagProperty: ExternalProjectProperty?,
val tagPropertyMappingType: ProjectPropertyType = defaultProjectPropertyType,
) : Params
class YouTrack(
val query: String?
) : Params
class Jira(
val query: String?
) : Params
class GitHub(
val owner: String,
val repository: String
) : Params
}
}
sealed interface IssuesLoadResult {
data class Failed(val message: String) : IssuesLoadResult {
companion object {
fun messageOrUnknownException(e: Exception)
= Failed(e.message ?: "unknown exception")
fun <T : Any> wrongParams(loader: KClass<T>)
= Failed("wrong parameters passed to ${loader.simpleName}")
}
}
data class Success(val issues: List<IssueTemplate>) : IssuesLoadResult
}
| 1 | Kotlin | 13 | 17 | 53061896db64c2e79db6b5d31f9ae0ae2ee70253 | 1,531 | space-issues-import | Apache License 2.0 |
app/src/main/java/com/c653d0/kotlinstudy/SearchDataAdapter.kt | c653d0 | 367,893,934 | false | {"Kotlin": 44411, "Java": 940} | package com.c653d0.kotlinstudy
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.navigation.NavController
import androidx.navigation.Navigation
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import org.jetbrains.annotations.NotNull
class SearchDataAdapter : RecyclerView.Adapter<SearchDataAdapter.SearchDataViewHolder>() {
private var allSearchResultList:ArrayList<SearchPageList> = ArrayList()
private val sakuraUrl = "http://www.dm88.me/"
fun setResultList(list:ArrayList<SearchPageList>){
this.allSearchResultList = list
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SearchDataViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
val view = layoutInflater.inflate(R.layout.item_search_result,parent,false)
return SearchDataViewHolder(view)
}
override fun getItemCount(): Int {
return allSearchResultList.size
}
override fun onBindViewHolder(holder: SearchDataViewHolder, position: Int) {
holder.searchTitle.text = allSearchResultList[position].getTitle()
holder.searchIntroduction.text = holder.itemView.context.getString(R.string.introduction)+allSearchResultList[position].getIntroduction()
holder.searchEpisode.text = allSearchResultList[position].getLatestEpisode()
Glide.with(holder.itemView.context).load(allSearchResultList[position].getPictureUrl()).into(holder.searchPicture)
//点击事件,跳转到详情页
holder.itemView.setOnClickListener(View.OnClickListener {
val controller:NavController = Navigation.findNavController(it)
val bundle = Bundle()
bundle.putString("resUrl",sakuraUrl+allSearchResultList[position].getId())
bundle.putString("resPicture",allSearchResultList[position].getPictureUrl())
bundle.putString("resTitle",allSearchResultList[position].getTitle())
bundle.putString("resIntroduction",allSearchResultList[position].getIntroduction())
controller.navigate(R.id.action_searchPageFragment_to_detailsFragment,bundle)
})
}
class SearchDataViewHolder(@NotNull itemView: View) : RecyclerView.ViewHolder(itemView) {
val searchPicture:ImageView = itemView.findViewById(R.id.searchPicture)
val searchTitle:TextView = itemView.findViewById(R.id.searchTitle)
val searchEpisode:TextView = itemView.findViewById(R.id.searchEpisode)
val searchIntroduction:TextView = itemView.findViewById(R.id.searchIntroduction)
}
} | 0 | Kotlin | 0 | 1 | edcaf3fc07081e2edc89d4921d5d8b0297e386b0 | 2,730 | sakuraVideo | MIT License |
app/src/main/java/com/example/ydword/fragments/FragmentB.kt | android-app-development-course | 550,845,718 | false | {"Kotlin": 39981} | package com.example.ydword.fragments
import android.content.DialogInterface
import android.os.Bundle
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 android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.Fragment
import com.example.ydword.R
import com.example.ydword.database.DBResult
import com.example.ydword.database.DBWords
import com.example.ydword.info.Word
class FragmentB : Fragment{
var title=""
lateinit var textView: TextView
lateinit var editText: EditText
lateinit var button_ensure: Button
lateinit var button_delete:Button
var dbWords: DBWords? = null
var dbResult: DBResult? = null
var wordscount = 0
var number = 0
var word: Word? = null
var count = 0
var right = 0 //正确数量
var wrong = 0 //错误数量
var delete = 0 //删除数量
constructor(title:String):super(){
this.title=title
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_b, null)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
textView = view.findViewById(R.id.recite_tv_translate)
editText = view.findViewById(R.id.recite_et_word)
button_ensure = view.findViewById(R.id.recite_btn_ensure)
button_delete = view.findViewById(R.id.recite_btn_delete)
dbWords = DBWords(activity, "tb_words", null, 1)
dbResult = DBResult(activity, "tb_result", null, 1)
setButtonListener()
Test()
}
fun Test(){
if(count<10){
wordscount= dbWords?.count ?: 0
number=(wordscount*Math.random()).toInt()
word= dbWords?.getWord(number)
textView.text = word!!.translate
count++
}else{
ifBackToFirst()
}
}
fun setButtonListener(){
button_ensure.setOnClickListener {
if(word?.word.equals(editText.text.toString())){
Toast.makeText(context,"回答正确! ", Toast.LENGTH_SHORT).show()
right++
editText.text.clear()
}else{
Toast.makeText(context,"回答错误! ",Toast.LENGTH_SHORT).show()
wrong++
editText.text.clear()
}
Test()
}
button_delete.setOnClickListener {
dbWords!!.deleteWord(number.toString() + "")
textView.text = ""
editText!!.setText("")
delete++
Test()
}
}
fun ifBackToFirst() {
dbResult!!.writeData(dbResult!!.readableDatabase, "正确:$right", "错误:$wrong", "删除:$delete")
wrong = 0
delete = 0
right = 0
val builder= activity?.let { AlertDialog.Builder(it) }
builder?.setTitle("已经背到最后了")?.setMessage("是否再来一组?")
?.setIcon(R.drawable.icon_image)
?.setPositiveButton("是", DialogInterface.OnClickListener { dialogInterface, j ->
count = 0
Test()
})?.setNegativeButton("否", DialogInterface.OnClickListener { dialogInterface, i ->
Toast.makeText(activity,"已背完最后一组啦!",Toast.LENGTH_SHORT).show()
textView.text = ""
editText.setText("")
})?.show()
}
}
| 0 | Kotlin | 0 | 0 | accf18d5b6284624dd80d9ef5b9abde45f05cf3b | 3,689 | 2022autumn-5-Memorize-words | Apache License 2.0 |
app/src/main/java/com/apx6/chipmunk/app/ui/base/BaseBottomSheetDialog.kt | volt772 | 506,075,620 | false | {"Kotlin": 305901} | package com.apx6.chipmunk.app.ui.base
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import androidx.annotation.LayoutRes
import androidx.annotation.StyleRes
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.DialogFragment
import com.apx6.chipmunk.app.ext.hideKeyboard
import com.apx6.chipmunk.app.ext.showKeyboard
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
abstract class BaseBottomSheetDialog<B : ViewDataBinding, PARAM>(
@LayoutRes private val layoutResId: Int,
@StyleRes private val styleResId: Int,
) : BottomSheetDialogFragment() {
private var _binding: B? = null
protected val binding get() = _binding!!
protected var param: PARAM? = null
protected abstract fun prepareDialog(param: PARAM)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setStyle(DialogFragment.STYLE_NORMAL, styleResId)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = DataBindingUtil.inflate(inflater, layoutResId, container, false)
return binding.root
}
private fun performDataBinding() {
binding.lifecycleOwner = viewLifecycleOwner
binding.executePendingBindings()
}
fun showKeyBoard(view: EditText?) {
requireActivity().showKeyboard(view)
}
fun hideKeyBoard() {
requireActivity().hideKeyboard()
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
performDataBinding()
param?.let {
prepareDialog(it)
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
| 0 | Kotlin | 0 | 0 | c3d4a20422090153b40f9542bbc51a3368750034 | 1,980 | chipmunk | Apache License 2.0 |
src/main/kotlin/com/learning/controller/HelloController.kt | NashTech-Labs | 693,112,365 | false | {"Kotlin": 10342} | package com.learning.controller
import com.learning.entity.Employee
import io.micronaut.http.MediaType
import io.micronaut.http.annotation.*
@Controller("/hello")
class HelloController {
/**
* The @Get annotation maps the index method to an HTTP GET request on /hello.
*
* By default, a Micronaut response uses application/json as Content-Type.
* We are returning a String, not a JSON object, so we set it to text/plain
**/
@Get
@Produces(MediaType.TEXT_PLAIN)
fun index() = "Hello World! Welcome to the journey of learning MICRONAUT with KOTLIN!!"
@Get("/message")
@Produces(MediaType.TEXT_PLAIN)
fun greet() = "Hi, Have a fantastic future ahead..!"
@Get("/employee")
fun getEmployee(): Employee {
return Employee(101, "Rishika")
}
}
| 0 | Kotlin | 0 | 0 | b9274413c9a177acefb3b553dce066c6c3ad3ac7 | 816 | micronaut_with_kotlin | MIT License |
devbricksx/src/main/java/com/dailystudio/devbricksx/ui/NonRecyclableListView.kt | dailystudio | 264,874,323 | false | {"Java": 1002565, "Kotlin": 832349, "Shell": 6356, "HTML": 1286} | package com.dailystudio.devbricksx.ui
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.recyclerview.widget.RecyclerView
import com.dailystudio.devbricksx.R
import com.dailystudio.devbricksx.development.Logger
open class NonRecyclableListView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0) : FrameLayout(context, attrs, defStyleAttr) {
private var adapter: RecyclerView.Adapter<*>? = null
private var selfScrollable: Boolean = false
private var itemsContainer: ViewGroup? = null
init {
setupViews()
attrs?.let {
val a = context.obtainStyledAttributes(attrs,
R.styleable.NonRecyclableListView, defStyleAttr, 0)
val selfScrollable = a.getBoolean(
R.styleable.NonRecyclableListView_self_scrollable,
false)
setSelfScrollable(selfScrollable)
a.recycle()
}
}
private fun setupViews() {
initLayout()
}
fun setSelfScrollable(scrollable: Boolean) {
selfScrollable = scrollable
initLayout()
}
private fun initLayout() {
removeAllViews()
LayoutInflater.from(context).inflate(if (selfScrollable) {
R.layout.non_recyclable_list_view_self_scrollable
} else {
R.layout.non_recyclable_list_view
}, this)
itemsContainer = findViewById(R.id.items_container)
}
fun setAdapter(listAdapter: RecyclerView.Adapter<*>?) {
adapter?.unregisterAdapterDataObserver(mAdapterObserver)
Logger.debug("unregister observer from old adapter: $adapter")
adapter = listAdapter
adapter?.registerAdapterDataObserver(mAdapterObserver)
Logger.debug("register observer on new adapter: $adapter")
requestItemsUpdate()
}
fun getAdapter(): RecyclerView.Adapter<*>? {
return adapter
}
protected open fun requestItemsUpdate() {
post {
appendItems()
}
}
protected open fun appendItems() {
val adapter = adapter ?: return
val container = itemsContainer?: return
container.removeAllViews()
val count = adapter.itemCount
Logger.debug("new items: count = $count")
for (pos in 0 until count) {
val type = adapter.getItemViewType(pos) ?: 0
val viewHolder: RecyclerView.ViewHolder =
adapter.onCreateViewHolder(this, type)
container.addView(viewHolder.itemView)
(adapter as RecyclerView.Adapter<RecyclerView.ViewHolder>
).onBindViewHolder(viewHolder, pos)
}
}
private val mAdapterObserver
= object : RecyclerView.AdapterDataObserver() {
override fun onChanged() {
super.onChanged()
Logger.debug("adapter changed: $this")
requestItemsUpdate()
}
}
} | 0 | Java | 6 | 53 | 25ddb0284dcf8c81410e0a76b75cbda39d9fbc2f | 3,123 | devbricksx-android | Apache License 2.0 |
sdk/core/src/main/java/com/rocbillow/core/binding/AutoClearedValue.kt | wptdxii | 278,525,387 | false | null | package com.rocbillow.core.binding
import android.view.View
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import androidx.viewbinding.ViewBinding
import kotlin.properties.ReadOnlyProperty
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
/**
* @author rocbillow
* @date 2020-09-07
*/
abstract class AutoCleared<T : ViewBinding>(private val fragment: Fragment) {
protected open var binding: T? = null
init {
fragment.lifecycle.addObserver(object : DefaultLifecycleObserver {
val viewLifecycleOwnerLiveDataObserver = Observer<LifecycleOwner?> {
val viewLifecycleOwner = it ?: return@Observer
viewLifecycleOwner.lifecycle.addObserver(object : DefaultLifecycleObserver {
override fun onDestroy(owner: LifecycleOwner) {
binding = null
}
})
}
override fun onCreate(owner: LifecycleOwner) {
fragment.viewLifecycleOwnerLiveData.observeForever(
viewLifecycleOwnerLiveDataObserver
)
}
override fun onDestroy(owner: LifecycleOwner) {
fragment.viewLifecycleOwnerLiveData.removeObserver(
viewLifecycleOwnerLiveDataObserver
)
}
})
}
}
class AutoClearedReadWriteDelete<T : ViewBinding>(fragment: Fragment) :
AutoCleared<T>(fragment), ReadWriteProperty<Fragment, T> {
override fun setValue(thisRef: Fragment, property: KProperty<*>, value: T) {
if (value is ViewDataBinding) {
value.lifecycleOwner = thisRef.viewLifecycleOwner
}
binding = value
}
override fun getValue(thisRef: Fragment, property: KProperty<*>): T {
return binding ?: throw IllegalStateException(
"should never call auto-cleared-value get when it might not be available"
)
}
}
class AutoClearedReadOnlyDelegate<T : ViewBinding>(
fragment: Fragment,
private val bindingFactory: (View) -> T,
) : AutoCleared<T>(fragment), ReadOnlyProperty<Fragment, T> {
override fun getValue(thisRef: Fragment, property: KProperty<*>): T {
val value = binding
if (value != null) return value
if (!thisRef.lifecycle.currentState.isAtLeast(Lifecycle.State.INITIALIZED)) {
throw IllegalStateException(
"should never call auto-cleared-value get when it might not be available"
)
}
return bindingFactory(thisRef.requireView())
.apply { bindLifecycleOwner(thisRef) }
.also { binding = it }
}
private fun T.bindLifecycleOwner(thisRef: Fragment) {
if (this is ViewDataBinding) {
lifecycleOwner = thisRef.viewLifecycleOwner
}
}
} | 0 | Kotlin | 0 | 0 | 33fe10f5686664f99b1b0e37c9391562e81e56bf | 3,053 | kit-android | Apache License 2.0 |
src/test/kotlin/LoggerUtilsTest.kt | uk-gov-mirror | 356,709,418 | false | null | /**
Please see notes in the file under test (LoggerUtils) and it's class LoggerLayoutAppender.
*/
import ch.qos.logback.classic.Level
import ch.qos.logback.classic.spi.ILoggingEvent
import ch.qos.logback.classic.spi.IThrowableProxy
import ch.qos.logback.classic.spi.ThrowableProxy
import ch.qos.logback.classic.spi.ThrowableProxyUtil
import com.nhaarman.mockitokotlin2.*
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.fail
import org.junit.Before
import org.junit.Test
class LoggerUtilsTest {
@Before
fun setup() {
overrideLoggerStaticFieldsForTests("test-host", "test-env", "my-app", "v1", "tests", "9876543000")
}
@After
fun tearDown() {
resetLoggerStaticFieldsForTests()
}
private fun catchMe1(): Throwable {
try {
MakeStacktrace1().callMe1()
}
catch (ex: Exception) {
return ex
}
return RuntimeException("boom")
}
private fun catchMe2(): Throwable {
try {
MakeStacktrace2().callMe2()
}
catch (ex: Exception) {
return ex
}
return RuntimeException("boom")
}
private fun catchMe3(): Throwable {
try {
MakeStacktrace3().callMe3()
}
catch (ex: Exception) {
return ex
}
return RuntimeException("boom")
}
class MakeStacktrace1 {
fun callMe1() {
throw RuntimeException("boom1 - /:'!@£\$%^&*()")
}
}
class MakeStacktrace2 {
fun callMe2() {
throw RuntimeException("boom2")
}
}
class MakeStacktrace3 {
fun callMe3() {
throw RuntimeException("boom3")
}
}
@Test
fun testFormattedTimestamp_WillUseDefaultFormat_WhenCalled() {
assertEquals("1970-01-01T00:00:00.000", formattedTimestamp(0))
assertEquals("1973-03-01T23:29:03.210", formattedTimestamp(99876543210))
assertEquals("A long time ago in a galaxy far, far away....", "292278994-08-17T07:12:55.807", formattedTimestamp(Long.MAX_VALUE))
}
@Test
fun testSemiFormattedTuples_WillFormatAsPartialJson_WhenCalledWithoutMatchingKeyValuePairs() {
assertEquals(
"my-message",
semiFormattedTuples("my-message"))
}
@Test
fun testSemiFormattedTuples_WillFormatAsPartialJson_WhenCalledWithMatchingKeyValuePairs() {
assertEquals(
"my-message\", \"key1\":\"value1\", \"key2\":\"value2",
semiFormattedTuples("my-message", "key1", "value1", "key2", "value2"))
}
@Test
fun testSemiFormattedTuples_WillEscapeJsonInMessageAndTupleValues_WhenCalled() {
assertEquals(
"This is almost unreadable, but a necessary test, sorry!",
"message-\\/:'!@\\u00A3\$%^&*()\\n\\t\\r\", \"key-unchanged\":\"value-\\/:!@\\u00A3\$%^&*()\\n\\t\\r",
semiFormattedTuples("message-/:'!@£\$%^&*()\n\t\r", "key-unchanged", "value-/:!@£\$%^&*()\n\t\r"))
}
@Test
fun testSemiFormattedTuples_WillFailWithException_WhenCalledWithoutMatchingKeyValuePairs() {
try {
semiFormattedTuples("my-message", "key1")
fail("Expected an IllegalArgumentException")
}
catch (expected: IllegalArgumentException) {
assertEquals(
"Must have matched key-value pairs but had 1 argument(s)",
expected.message)
}
}
@Test
fun testLoggerUtils_Debug_WillFormatAsPartialJson_WhenCalled() {
val mockLogger: org.slf4j.Logger = mock()
whenever(mockLogger.isDebugEnabled).thenReturn(true)
JsonLoggerWrapper(mockLogger).debug("main-message", "key1", "value1", "key2", "value2")
verify(mockLogger, times(1)).isDebugEnabled
verify(mockLogger, times(1)).debug("main-message\", \"key1\":\"value1\", \"key2\":\"value2")
verifyNoMoreInteractions(mockLogger)
}
@Test
fun testLoggerUtils_Info_WillFormatAsPartialJson_WhenCalled() {
val mockLogger: org.slf4j.Logger = mock()
whenever(mockLogger.isInfoEnabled).thenReturn(true)
JsonLoggerWrapper(mockLogger).info("main-message", "key1", "value1", "key2", "value2")
verify(mockLogger, times(1)).isInfoEnabled
verify(mockLogger, times(1)).info("main-message\", \"key1\":\"value1\", \"key2\":\"value2")
verifyNoMoreInteractions(mockLogger)
}
@Test
fun testLoggerUtils_Error_WillFormatAsPartialJson_WhenCalled() {
val mockLogger: org.slf4j.Logger = mock()
whenever(mockLogger.isErrorEnabled).thenReturn(true)
JsonLoggerWrapper(mockLogger).error("main-message", "key1", "value1", "key2", "value2")
verify(mockLogger, times(1)).isErrorEnabled
verify(mockLogger, times(1)).error("main-message\", \"key1\":\"value1\", \"key2\":\"value2")
verifyNoMoreInteractions(mockLogger)
}
@Test
fun testLoggerUtils_Error_WillFormatAsPartialJson_WhenCalledWithKeyValuePairsAndException() {
val mockLogger: org.slf4j.Logger = mock()
whenever(mockLogger.isErrorEnabled).thenReturn(true)
val exception = RuntimeException("boom")
JsonLoggerWrapper(mockLogger).error("main-message", exception, "key1", "value1", "key2", "value2")
verify(mockLogger, times(1)).isErrorEnabled
verify(mockLogger, times(1)).error(eq("main-message\", \"key1\":\"value1\", \"key2\":\"value2"), same(exception))
verifyNoMoreInteractions(mockLogger)
}
@Test
fun testInlineStackTrace_WillRemoveTabsAndNewlinesAndEscapeJsonChars_WhenCalled() {
val stubThrowable = ThrowableProxy(catchMe1())
ThrowableProxyUtil.build(stubThrowable, catchMe2(), ThrowableProxy(catchMe3()))
val trace = "java.lang.RuntimeException: boom1 - /:'!@£\$%^&*()\n" +
"\tat LoggerUtilsTest\$MakeStacktrace2.callMe2(LoggerUtilsTest.kt:67)\n" +
"\tat LoggerUtilsTest.catchMe2(LoggerUtilsTest.kt:41)\n" +
"\t... 50 common frames omitted\n"
val throwableStr = ThrowableProxyUtil.asString(stubThrowable)
assertEquals(trace, throwableStr)
val result = inlineStackTrace(throwableStr)
assertEquals("java.lang.RuntimeException: boom1 - \\/:'!@\\u00A3\$%^&*() | at LoggerUtilsTest\$MakeStacktrace2.callMe2(LoggerUtilsTest.kt:67) | at LoggerUtilsTest.catchMe2(LoggerUtilsTest.kt:41) | ... 50 common frames omitted | ", result)
}
@Test
fun testFlattenMultipleLines_WillRemoveTabsAndNewlinesAndNotEscape_WhenCalled() {
val trace = "java.lang.RuntimeException: boom1 - /:'!@£\$%^&*()\n" +
"\tat LoggerUtilsTest\$MakeStacktrace2.callMe2(LoggerUtilsTest.kt:87)\n"
val result = flattenMultipleLines(trace)
assertEquals("java.lang.RuntimeException: boom1 - /:'!@£\$%^&*() | at LoggerUtilsTest\$MakeStacktrace2.callMe2(LoggerUtilsTest.kt:87) | ", result)
}
@Test
fun testMakeLoggerStaticDataTuples_WillCreatePartialJson_WhenCalled() {
overrideLoggerStaticFieldsForTests("a-host", "b-env", "c-app", "d-version", "e-component", "9876543000")
val expected = """"hostname":"a-host", "environment":"b-env", "application":"c-app", "app_version":"d-version", "component":"e-component", "instance_id":"NOT_SET", "column_family":"cf", "column_qualifier":"record", "region_replication":"3""""
assertEquals(expected, makeLoggerStaticDataTuples())
}
@Test
fun testThrowableProxyEventToString_EmbedsAsJsonKey_WhenCalled() {
val mockEvent = mock<ILoggingEvent>()
whenever(mockEvent.timeStamp).thenReturn(9876543210)
whenever(mockEvent.level).thenReturn(Level.WARN)
whenever(mockEvent.threadName).thenReturn("my.thread.is.betty")
whenever(mockEvent.loggerName).thenReturn("logger.name.is.mavis")
whenever(mockEvent.formattedMessage).thenReturn("some message about stuff")
val stubThrowable = ThrowableProxy(catchMe1())
ThrowableProxyUtil.build(stubThrowable, catchMe2(), ThrowableProxy(catchMe3()))
whenever(mockEvent.throwableProxy).thenReturn(stubThrowable as IThrowableProxy)
val result = throwableProxyEventToString(mockEvent)
assertEquals("\"exception\":\"java.lang.RuntimeException: boom1 - \\/:'!@\\u00A3\$%^&*() | at LoggerUtilsTest\$MakeStacktrace2.callMe2(LoggerUtilsTest.kt:67) | at LoggerUtilsTest.catchMe2(LoggerUtilsTest.kt:41) | ... 50 common frames omitted | \", ", result)
}
@Test
fun testLoggerLayoutAppender_WillReturnEmpty_WhenCalledWithNothing() {
val result = LoggerLayoutAppender().doLayout(null)
assertEquals("", result)
}
@Test
fun testLoggerLayoutAppender_WillReturnSkinnyJson_WhenCalledWithEmptyEvent() {
val result = LoggerLayoutAppender().doLayout(mock())
val expected = """{ "timestamp":"1970-01-01T00:00:00.000", "log_level":"null", "message":"null", "thread":"null", "logger":"null", "hostname":"test-host", "environment":"test-env", "application":"my-app", "app_version":"v1", "component":"tests", "instance_id":"NOT_SET", "column_family":"cf", "column_qualifier":"record", "region_replication":"3" }
"""
assertEquals(expected, result)
}
@Test
fun testLoggerLayoutAppender_WillFormatAsJson_WhenCalledWithVanillaMessage() {
val mockEvent = mock<ILoggingEvent>()
whenever(mockEvent.timeStamp).thenReturn(9876543210)
whenever(mockEvent.level).thenReturn(Level.WARN)
whenever(mockEvent.threadName).thenReturn("my.thread.is.betty")
whenever(mockEvent.loggerName).thenReturn("logger.name.is.mavis")
whenever(mockEvent.formattedMessage).thenReturn("some message about stuff")
whenever(mockEvent.hasCallerData()).thenReturn(false)
val expected = """{ "timestamp":"1970-04-25T07:29:03.210", "log_level":"WARN", "message":"some message about stuff", "thread":"my.thread.is.betty", "logger":"logger.name.is.mavis", "hostname":"test-host", "environment":"test-env", "application":"my-app", "app_version":"v1", "component":"tests", "instance_id":"NOT_SET", "column_family":"cf", "column_qualifier":"record", "region_replication":"3" }
"""
val result = LoggerLayoutAppender().doLayout(mockEvent)
assertEquals(expected, result)
}
@Test
fun testLoggerLayoutAppender_WillFlattenMultilineMessages_WhenCalledWithAnyMessage() {
val mockEvent = mock<ILoggingEvent>()
whenever(mockEvent.timeStamp).thenReturn(9876543210)
whenever(mockEvent.level).thenReturn(Level.WARN)
whenever(mockEvent.threadName).thenReturn("my.thread.is.betty")
whenever(mockEvent.loggerName).thenReturn("logger.name.is.mavis")
whenever(mockEvent.formattedMessage).thenReturn("some\nmessage\nabout\nstuff with\ttabs")
whenever(mockEvent.hasCallerData()).thenReturn(false)
val result = LoggerLayoutAppender().doLayout(mockEvent)
val expected = """{ "timestamp":"1970-04-25T07:29:03.210", "log_level":"WARN", "message":"some | message | about | stuff with tabs", "thread":"my.thread.is.betty", "logger":"logger.name.is.mavis", "hostname":"test-host", "environment":"test-env", "application":"my-app", "app_version":"v1", "component":"tests", "instance_id":"NOT_SET", "column_family":"cf", "column_qualifier":"record", "region_replication":"3" }
"""
assertEquals(expected, result)
}
@Test
fun testLoggerLayoutAppender_WillFormatAsJson_WhenCalledWithEmbeddedTuplesInMessage() {
val mockEvent = mock<ILoggingEvent>()
whenever(mockEvent.timeStamp).thenReturn(9876543210)
whenever(mockEvent.level).thenReturn(Level.WARN)
whenever(mockEvent.threadName).thenReturn("my.thread.is.betty")
whenever(mockEvent.loggerName).thenReturn("logger.name.is.mavis")
val embeddedTokens = semiFormattedTuples("some message about stuff", "key1", "value1", "key2", "value2")
whenever(mockEvent.formattedMessage).thenReturn(embeddedTokens)
whenever(mockEvent.hasCallerData()).thenReturn(false)
val result = LoggerLayoutAppender().doLayout(mockEvent)
val expected = """{ "timestamp":"1970-04-25T07:29:03.210", "log_level":"WARN", "message":"some message about stuff", "key1":"value1", "key2":"value2", "thread":"my.thread.is.betty", "logger":"logger.name.is.mavis", "hostname":"test-host", "environment":"test-env", "application":"my-app", "app_version":"v1", "component":"tests", "instance_id":"NOT_SET", "column_family":"cf", "column_qualifier":"record", "region_replication":"3" }
"""
assertEquals(expected, result)
}
@Test
fun testLoggerLayoutAppender_ShouldNotEscapeTheJsonMessage_AsThatWouldMessWithOurCustomStaticLogMethodsWhichDo() {
val mockEvent = mock<ILoggingEvent>()
whenever(mockEvent.timeStamp).thenReturn(9876543210)
whenever(mockEvent.level).thenReturn(Level.WARN)
whenever(mockEvent.threadName).thenReturn("my.thread.is.betty")
whenever(mockEvent.loggerName).thenReturn("logger.name.is.mavis")
whenever(mockEvent.formattedMessage).thenReturn("message-/:'!@")
whenever(mockEvent.hasCallerData()).thenReturn(false)
val result = LoggerLayoutAppender().doLayout(mockEvent)
val expected = """{ "timestamp":"1970-04-25T07:29:03.210", "log_level":"WARN", "message":"message-/:'!@", "thread":"my.thread.is.betty", "logger":"logger.name.is.mavis", "hostname":"test-host", "environment":"test-env", "application":"my-app", "app_version":"v1", "component":"tests", "instance_id":"NOT_SET", "column_family":"cf", "column_qualifier":"record", "region_replication":"3" }
"""
assertEquals(expected, result)
}
@Test
fun testLoggerLayoutAppender_ShouldAddExceptions_WhenProvided() {
val mockEvent = mock<ILoggingEvent>()
whenever(mockEvent.timeStamp).thenReturn(9876543210)
whenever(mockEvent.level).thenReturn(Level.WARN)
whenever(mockEvent.threadName).thenReturn("my.thread.is.betty")
whenever(mockEvent.loggerName).thenReturn("logger.name.is.mavis")
whenever(mockEvent.formattedMessage).thenReturn("some message about stuff")
val stubThrowable = ThrowableProxy(catchMe1())
ThrowableProxyUtil.build(stubThrowable, catchMe2(), ThrowableProxy(catchMe3()))
whenever(mockEvent.throwableProxy).thenReturn(stubThrowable as IThrowableProxy)
val expected = """{ "timestamp":"1970-04-25T07:29:03.210", "log_level":"WARN", "message":"some message about stuff", "exception":"java.lang.RuntimeException: boom1 - \/:'!@\u00A3$%^&*() | at LoggerUtilsTest${"$"}MakeStacktrace2.callMe2(LoggerUtilsTest.kt:67) | at LoggerUtilsTest.catchMe2(LoggerUtilsTest.kt:41) | ... 50 common frames omitted | ", "thread":"my.thread.is.betty", "logger":"logger.name.is.mavis", "hostname":"test-host", "environment":"test-env", "application":"my-app", "app_version":"v1", "component":"tests", "instance_id":"NOT_SET", "column_family":"cf", "column_qualifier":"record", "region_replication":"3" }
"""
val result = LoggerLayoutAppender().doLayout(mockEvent)
assertEquals("The standard logger should add exception messages", expected, result)
}
}
| 0 | null | 0 | 0 | 9015c4827e4599ba44ee96735d929d456df4f4cd | 15,307 | dwp.streaming-data-importer | MIT License |
fs-client/src/main/kotlin/eece513/fsClient/Main.kt | kierse | 177,886,921 | false | null | package eece513.fsClient
import eece513.common.SERVERS_FILE_PATH
import eece513.common.TinyLogWrapper
import eece513.common.mapper.ConnectionPurposeMapper
import eece513.common.util.FileIO
import eece513.fsClient.mapper.FsCommandByteMapper
import eece513.fsClient.mapper.FsResponseObjectMapper
import eece513.common.model.FsCommand
import eece513.fsClient.message.MessageBuilder
import eece513.fsClient.message.MessageReader
import kotlin.system.exitProcess
fun main(args: Array<String>) {
// val logger = TinyLogWrapper(FS_LOG_LOCATION)
val logger = TinyLogWrapper()
val remoteAddresses = FileIO().ReadLinesAsInetAddress(SERVERS_FILE_PATH)
val purposeMapper = ConnectionPurposeMapper()
val commandMapper = FsCommandByteMapper()
val responseMapper = FsResponseObjectMapper()
val messageBuilder = MessageBuilder()
val messageReader = MessageReader(logger)
try {
val client = FsClient(remoteAddresses, purposeMapper, commandMapper, responseMapper, messageBuilder, messageReader, logger)
client.executeCommand(FsCommand.from(args))
} catch (e: IllegalArgumentException) {
print("error: ${e.message}")
exitProcess(-1)
}
}
| 0 | Kotlin | 0 | 0 | 88b400a74bbb62b0b7053dbab24f824df87f7fd9 | 1,197 | distributed-app | MIT License |
app/src/main/java/com/tanmay/composegallery/GalleryViewModel.kt | Patil-Tanmay | 634,550,870 | false | null | package com.tanmay.composegallery
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.cachedIn
import com.tanmay.composegallery.data.db.GalleryDatabase
import com.tanmay.composegallery.data.paging.AlbumPagingSource
import com.tanmay.composegallery.data.paging.GalleryPagingSource
import com.tanmay.composegallery.data.repository.GalleryRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class GalleryViewModel @Inject constructor(
private val repository: GalleryRepository,
private val db: GalleryDatabase
) : ViewModel() {
private val _isRefreshing: MutableStateFlow<Boolean> = MutableStateFlow(false)
val isRefreshing: StateFlow<Boolean> = _isRefreshing.asStateFlow()
private val _showPhotos: MutableStateFlow<ShowPhotoStates> =
MutableStateFlow(ShowPhotoStates.SplashScreen)
val showPhotos: StateFlow<ShowPhotoStates> = _showPhotos.asStateFlow()
fun updatePhotoState(value: ShowPhotoStates) {
_showPhotos.value = value
}
fun getPhotos() = Pager(
config = PagingConfig(
initialLoadSize = 60,
pageSize = 60,
),
pagingSourceFactory = {
GalleryPagingSource(db)
}
).flow.cachedIn(viewModelScope)
fun getPhotosFromSystem() = viewModelScope.launch{
_isRefreshing.value = true
try {
val photos = repository.getPhotosFromSystem()
if (photos.isNotEmpty()) {
updatePhotoState(ShowPhotoStates.Albums)
} else {
updatePhotoState(ShowPhotoStates.EmptyScreen)
}
} catch (e: Exception) {
// Handle error
updatePhotoState(ShowPhotoStates.PermissionDenied)
} finally {
_isRefreshing.value = false
}
}
fun getPhotosFromAlbum(bucketId: Long) = viewModelScope.launch{
_isRefreshing.value = true
try {
val photos = repository.getPhotosFromAlbum(bucketId)
if (photos.isNotEmpty()) {
updatePhotoState(ShowPhotoStates.AlbumPhotos)
} else {
updatePhotoState(ShowPhotoStates.EmptyScreen)
}
} catch (e: Exception) {
// Handle error
updatePhotoState(ShowPhotoStates.PermissionDenied)
} finally {
_isRefreshing.value = false
}
}
fun getAllAlbums()= viewModelScope.launch {
try {
val albums = repository.getAllAlbums()
if (albums.isNotEmpty()) {
updatePhotoState(ShowPhotoStates.Albums)
} else {
updatePhotoState(ShowPhotoStates.EmptyScreen)
}
} catch (e: Exception) {
// Handle error
updatePhotoState(ShowPhotoStates.PermissionDenied)
}
}
fun getPagedAlbums() = Pager(
config = PagingConfig(
initialLoadSize = 60,
pageSize = 60,
),
pagingSourceFactory = {
AlbumPagingSource(db)
}
).flow.cachedIn(viewModelScope)
}
enum class ShowPhotoStates {
Loading,
Albums,
AlbumPhotos,
PermissionDenied,
EmptyScreen,
SplashScreen
} | 0 | Kotlin | 0 | 1 | d10cfa416545a9a767f887210f1ead6313999361 | 3,523 | Compose-Gallery | MIT License |
core/model/src/main/kotlin/au/com/dius/pact/core/model/generators/TimeExpression.kt | pact-foundation | 15,750,847 | false | {"Kotlin": 1698665, "Groovy": 1639695, "Java": 648241, "Gherkin": 99299, "Scala": 34232, "Clojure": 7545, "Dockerfile": 582} | package au.com.dius.pact.core.model.generators
import au.com.dius.pact.core.support.Result
import au.com.dius.pact.core.support.generators.expressions.Adjustment
import au.com.dius.pact.core.support.generators.expressions.Operation
import au.com.dius.pact.core.support.generators.expressions.TimeBase
import au.com.dius.pact.core.support.generators.expressions.TimeExpressionLexer
import au.com.dius.pact.core.support.generators.expressions.TimeExpressionParser
import au.com.dius.pact.core.support.generators.expressions.TimeOffsetType
import io.github.oshai.kotlinlogging.KLogging
import java.time.LocalTime
import java.time.OffsetDateTime
import java.time.ZoneOffset
import java.time.temporal.ChronoUnit
data class ParsedTimeExpression(val base: TimeBase, val adjustments: MutableList<Adjustment<TimeOffsetType>>)
object TimeExpression : KLogging() {
@Suppress("ComplexMethod")
fun executeTimeExpression(base: OffsetDateTime, expression: String?): Result<OffsetDateTime, String> {
return if (!expression.isNullOrEmpty()) {
return when (val result = parseTimeExpression(expression)) {
is Result.Err -> result
is Result.Ok -> {
val midnight = OffsetDateTime.of(base.toLocalDate(), LocalTime.MIDNIGHT, ZoneOffset.from(base))
val noon = OffsetDateTime.of(base.toLocalDate(), LocalTime.NOON, ZoneOffset.from(base))
var time = when (val valBase = result.value.base) {
TimeBase.Now -> base
TimeBase.Midnight -> midnight
TimeBase.Noon -> noon
is TimeBase.Am -> midnight.plusHours(valBase.hour.toLong())
is TimeBase.Pm -> noon.plusHours(valBase.hour.toLong())
is TimeBase.Next -> if (base.isBefore(noon))
noon.plusHours(valBase.hour.toLong())
else midnight.plusHours(valBase.hour.toLong())
}
result.value.adjustments.forEach {
when (it.operation) {
Operation.PLUS -> {
time = when (it.type) {
TimeOffsetType.HOUR -> time.plusHours(it.value.toLong())
TimeOffsetType.MINUTE -> time.plusMinutes(it.value.toLong())
TimeOffsetType.SECOND -> time.plusSeconds(it.value.toLong())
TimeOffsetType.MILLISECOND -> time.plus(it.value.toLong(), ChronoUnit.MILLIS)
}
}
Operation.MINUS -> {
time = when (it.type) {
TimeOffsetType.HOUR -> time.minusHours(it.value.toLong())
TimeOffsetType.MINUTE -> time.minusMinutes(it.value.toLong())
TimeOffsetType.SECOND -> time.minusSeconds(it.value.toLong())
TimeOffsetType.MILLISECOND -> time.minus(it.value.toLong(), ChronoUnit.MILLIS)
}
}
}
}
Result.Ok(time)
}
}
} else {
Result.Ok(base)
}
}
private fun parseTimeExpression(expression: String): Result<ParsedTimeExpression, String> {
val lexer = TimeExpressionLexer(expression)
val parser = TimeExpressionParser(lexer)
return when (val result = parser.expression()) {
is Result.Err -> Result.Err("Error parsing expression: ${result.error}")
is Result.Ok -> Result.Ok(ParsedTimeExpression(result.value.first, result.value.second.toMutableList()))
}
}
}
| 336 | Kotlin | 476 | 1,040 | b52f5a7c5c1b0eddc2fb4e80e0d8c5b48be46552 | 3,377 | pact-jvm | Apache License 2.0 |
app/src/main/java/openfoodfacts/github/scrachx/openfood/models/ProductIngredient.kt | VaiTon | 188,716,737 | true | {"Kotlin": 1447072, "Java": 124476, "Ruby": 13166, "Shell": 543, "Makefile": 241} | package openfoodfacts.github.scrachx.openfood.models
import com.fasterxml.jackson.annotation.JsonAnyGetter
import com.fasterxml.jackson.annotation.JsonAnySetter
import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.annotation.JsonPropertyOrder
import java.io.Serializable
/**
* Represents an ingredient of the product
*
* @param rank The rank, set -1 if no rank returned
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder("text", "id", "rank", "percent")
data class ProductIngredient(
@JsonProperty("text") val text: String,
@JsonProperty("id") val id: String,
@JsonProperty("rank") val rank: Long = 0,
@JsonProperty("percent") val percent: String? = null,
) : Serializable {
@get:JsonAnyGetter
val additionalProperties = HashMap<String, Any>()
@JsonAnySetter
fun setAdditionalProperty(name: String, value: Any) {
additionalProperties[name] = value
}
companion object {
private const val serialVersionUID = 1L
}
} | 11 | Kotlin | 0 | 1 | cd08ebc35205289436ad5e5f12c280aa80b71ab8 | 1,077 | openfoodfacts-androidapp | Apache License 2.0 |
app/src/main/java/org/metabrainz/android/ui/screens/label/LabelInfoFragment.kt | metabrainz | 166,439,000 | false | {"Kotlin": 286143, "HTML": 2497, "Ruby": 423} | package org.metabrainz.android.ui.screens.label
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.SavedStateViewModelFactory
import org.metabrainz.android.databinding.FragmentLabelInfoBinding
import org.metabrainz.android.ui.screens.base.MusicBrainzFragment
import org.metabrainz.android.util.Resource
class LabelInfoFragment : Fragment() {
private var binding: FragmentLabelInfoBinding? = null
private val labelViewModel: LabelViewModel by activityViewModels {
SavedStateViewModelFactory(requireActivity().application, this)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
binding = FragmentLabelInfoBinding.inflate(inflater, container, false)
labelViewModel.data.observe(viewLifecycleOwner) { setLabelInfo(it) }
return binding!!.root
}
override fun onDestroyView() {
super.onDestroyView()
binding = null
}
private fun setLabelInfo(resource: Resource<org.metabrainz.android.model.mbentity.Label>) {
if (resource.status == Resource.Status.SUCCESS) {
val label = resource.data
if (label!!.type != null && label.type!!.isNotEmpty())
binding!!.labelType.text = label.type
if (label.lifeSpan != null && label.lifeSpan!!.begin!!.isNotEmpty())
binding!!.labelFounded.text = label.lifeSpan!!.begin
if (label.area != null && label.area!!.name!!.isNotEmpty())
binding!!.labelArea.text = label.area!!.name
if (label.code != null && label.code!!.isNotEmpty())
binding!!.labelCode.text = label.code
}
}
companion object : MusicBrainzFragment {
override fun newInstance(): Fragment {
return LabelInfoFragment()
}
}
} | 2 | Kotlin | 30 | 117 | 382b29b5ec2b8040303045e6d21651b7662d1be9 | 2,012 | musicbrainz-android | Apache License 2.0 |
platform/platform-impl/src/com/intellij/ui/layout/Cell.kt | lots0logs | 177,212,454 | true | null | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ui.layout
import com.intellij.BundleBase
import com.intellij.icons.AllIcons
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.actionSystem.DefaultActionGroup
import com.intellij.openapi.actionSystem.PlatformDataKeys
import com.intellij.openapi.fileChooser.FileChooserDescriptor
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.ComboBox
import com.intellij.openapi.ui.TextFieldWithBrowseButton
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.ui.*
import com.intellij.ui.components.*
import com.intellij.ui.layout.migLayout.*
import com.intellij.util.ui.UIUtil
import java.awt.Component
import java.awt.event.ActionEvent
import java.awt.event.ActionListener
import java.awt.event.MouseEvent
import java.util.function.Consumer
import java.util.function.Supplier
import javax.swing.*
import kotlin.reflect.KMutableProperty0
import kotlin.reflect.KProperty0
@DslMarker
annotation class CellMarker
interface CellBuilder<T : JComponent> {
val component: T
fun focused(): CellBuilder<T>
fun withValidation(callback: (T) -> ValidationInfo?): CellBuilder<T>
fun onApply(callback: () -> Unit): CellBuilder<T>
fun enabled(isEnabled: Boolean)
fun enableIfSelected(button: AbstractButton)
fun withErrorIf(message: String, callback: (T) -> Boolean): CellBuilder<T> {
withValidation { if (callback(it)) ValidationInfo(message, it) else null }
return this
}
}
interface CheckboxCellBuilder {
fun actsAsLabel()
}
fun CellBuilder<out JComponent>.enableIfSelected(builder: CellBuilder<out AbstractButton>) {
enableIfSelected(builder.component)
}
fun <T : JCheckBox> CellBuilder<T>.actsAsLabel(): CellBuilder<T> {
(this as CheckboxCellBuilder).actsAsLabel()
return this
}
// separate class to avoid row related methods in the `cell { } `
@CellMarker
abstract class Cell {
/**
* Sets how keen the component should be to grow in relation to other component **in the same cell**. Use `push` in addition if need.
* If this constraint is not set the grow weight is set to 0 and the component will not grow (unless some automatic rule is not applied (see [com.intellij.ui.layout.panel])).
* Grow weight will only be compared against the weights for the same cell.
*/
val growX = CCFlags.growX
@Suppress("unused")
val growY = CCFlags.growY
val grow = CCFlags.grow
/**
* Makes the column that the component is residing in grow with `weight`.
*/
val pushX = CCFlags.pushX
/**
* Makes the row that the component is residing in grow with `weight`.
*/
@Suppress("unused")
val pushY = CCFlags.pushY
val push = CCFlags.push
fun link(text: String, style: UIUtil.ComponentStyle? = null, action: () -> Unit) {
val result = Link(text, action = action)
style?.let { UIUtil.applyStyle(it, result) }
result()
}
fun browserLink(text: String, url: String) {
val result = HyperlinkLabel()
result.setHyperlinkText(text)
result.setHyperlinkTarget(url)
result()
}
fun button(text: String, vararg constraints: CCFlags, actionListener: (event: ActionEvent) -> Unit) {
val button = JButton(BundleBase.replaceMnemonicAmpersand(text))
button.addActionListener(actionListener)
button(*constraints)
}
inline fun checkBox(text: String,
isSelected: Boolean = false,
comment: String? = null,
propertyUiManager: BooleanPropertyUiManager? = null,
vararg constraints: CCFlags,
crossinline actionListener: (event: ActionEvent, component: JCheckBox) -> Unit): JCheckBox {
val component = checkBox(text, isSelected, comment, propertyUiManager, *constraints)
component.addActionListener(ActionListener {
actionListener(it, component)
})
return component
}
@JvmOverloads
fun checkBox(text: String, isSelected: Boolean = false, comment: String? = null, propertyUiManager: BooleanPropertyUiManager? = null, vararg constraints: CCFlags = emptyArray()): JCheckBox {
val component = JCheckBox(text)
component.isSelected = isSelected
propertyUiManager?.registerCheckBox(component)
component(*constraints, comment = comment)
return component
}
fun checkBox(text: String, prop: KMutableProperty0<Boolean>): CellBuilder<JBCheckBox> {
val component = JBCheckBox(text, prop.get())
return component()
.onApply { prop.set(component.isSelected) }
}
inline fun <T> comboBox(propertyUiManager: BooleanPropertyWithListUiManager<T, out ComboBoxModel<T>>, growPolicy: GrowPolicy? = null, crossinline renderer: ListCellRendererWrapper<T?>.(value: T, index: Int, isSelected: Boolean) -> Unit) {
comboBox(propertyUiManager.listModel, propertyUiManager, growPolicy, object : ListCellRendererWrapper<T?>() {
override fun customize(list: JList<*>, value: T?, index: Int, isSelected: Boolean, hasFocus: Boolean) {
if (value != null) {
renderer(value, index, isSelected)
}
}
})
}
fun <T> comboBox(model: ComboBoxModel<T>, propertyUiManager: BooleanPropertyWithListUiManager<*, *>? = null, growPolicy: GrowPolicy? = null, renderer: ListCellRenderer<T?>? = null) {
val component = ComboBox(model)
propertyUiManager?.manage(component)
if (renderer != null) {
component.renderer = renderer
}
component(growPolicy = growPolicy)
}
fun textField(prop: KMutableProperty0<String>, columns: Int? = null): CellBuilder<JTextField> {
val component = JTextField(prop.get(),columns ?: 0)
val builder = component()
builder.onApply { prop.set(component.text) }
return builder
}
fun intTextField(prop: KMutableProperty0<Int>, columns: Int? = null): CellBuilder<JTextField> {
return textField(Supplier { prop.get().toString() }, Consumer { value -> value.toIntOrNull()?.let { prop.set(it) } }, columns)
}
fun textField(getter: Supplier<String>, setter: Consumer<String>, columns: Int? = null): CellBuilder<JTextField> {
val component = JTextField(getter.get(),columns ?: 0)
val builder = component()
builder.onApply { setter.accept(component.text) }
return builder
}
fun spinner(prop: KMutableProperty0<Int>, minValue: Int, maxValue: Int, step: Int = 1): CellBuilder<JBIntSpinner> {
val component = JBIntSpinner(prop.get(), minValue, maxValue, step)
return component().onApply { prop.set(component.number) }
}
fun textFieldWithHistoryWithBrowseButton(browseDialogTitle: String,
value: String? = null,
project: Project? = null,
fileChooserDescriptor: FileChooserDescriptor = FileChooserDescriptorFactory.createSingleFileNoJarsDescriptor(),
historyProvider: (() -> List<String>)? = null,
fileChosen: ((chosenFile: VirtualFile) -> String)? = null,
comment: String? = null): TextFieldWithHistoryWithBrowseButton {
val component = textFieldWithHistoryWithBrowseButton(project, browseDialogTitle, fileChooserDescriptor, historyProvider, fileChosen)
value?.let { component.text = it }
component(comment = comment)
return component
}
fun textFieldWithBrowseButton(browseDialogTitle: String,
value: String? = null,
project: Project? = null,
fileChooserDescriptor: FileChooserDescriptor = FileChooserDescriptorFactory.createSingleFileNoJarsDescriptor(),
fileChosen: ((chosenFile: VirtualFile) -> String)? = null,
comment: String? = null): TextFieldWithBrowseButton {
val component = textFieldWithBrowseButton(project, browseDialogTitle, fileChooserDescriptor, fileChosen)
value?.let { component.text = it }
component(comment = comment)
return component
}
fun gearButton(vararg actions: AnAction) {
val label = JLabel(AllIcons.General.GearPlain)
object : ClickListener() {
override fun onClick(e: MouseEvent, clickCount: Int): Boolean {
JBPopupFactory.getInstance()
.createActionGroupPopup(null, DefaultActionGroup(*actions), DataContext { dataId ->
when (dataId) {
PlatformDataKeys.CONTEXT_COMPONENT.name -> label
else -> null
}
}, true, null, 10)
.showUnderneathOf(label)
return true
}
}.installOn(label)
label()
}
/**
* @see LayoutBuilder.titledRow
*/
fun panel(title: String, wrappedComponent: Component, vararg constraints: CCFlags) {
val panel = Panel(title)
panel.add(wrappedComponent)
panel(*constraints)
}
fun scrollPane(component: Component, vararg constraints: CCFlags) {
JBScrollPane(component)(*constraints)
}
abstract operator fun <T : JComponent> T.invoke(
vararg constraints: CCFlags,
gapLeft: Int = 0,
growPolicy: GrowPolicy? = null,
comment: String? = null
): CellBuilder<T>
}
| 0 | null | 0 | 1 | 3dd717a44039d5592619331857621c17baae490a | 9,545 | intellij-community | Apache License 2.0 |
src/test/kotlin/spark/examples/instance/InstanceApiDslInitializationExample.kt | perwendel | 92,269,915 | false | null | package spark.examples.instance
import spark.examples.testutil.keyStoreLocation
import spark.examples.testutil.keystorePass
import spark.examples.testutil.trustStoreLocation
import spark.examples.testutil.trustStorePassword
import spark.kotlin.halt
import spark.kotlin.ignite
import spark.kotlin.seconds
/**
* Example usage of spark-kotlin via instance API. YOU SHOULD NAME THE SPARK INSTANCE 'http' FOR EXPRESSIVE/DECLARATIVE PURPOSES.
* If you don't it's blasphemy.
*/
fun main(args: Array<String>) {
val http = ignite {
port = 5500
ipAddress = "0.0.0.0"
threadPool {
maxThreads = 10
minThreads = 5
idleTimeoutMillis = 1000
}
secure {
keystore {
file = keyStoreLocation()
password = <PASSWORD>
}
truststore {
file = trustStoreLocation()
password = <PASSWORD>
}
needsClientCert = false
}
staticFiles {
location = "/public"
expiryTime = 36000.seconds
headers(
"description" to "static content",
"licence" to "free to use"
)
mimeTypes(
"cxt" to "text/html"
)
}
}
http.get("/hello") {
"Hello Spark Kotlin"
}
http.get("/halt") {
halt(201, "created!")
}
http.get("/nothing") {
status(404)
"Oops, we couldn't find what you're looking for"
}
http.get("/saymy/:name") {
params(":name")
}
http.get("/redirect") {
redirect("/hello");
}
http.before("/hello") {
println("Before Hello")
}
http.after("/hello") {
println("After Hello")
}
http.finally {
println("At last")
}
http.redirect {
any("/from" to "/hello")
}
http.get("/exception") {
throw AuthException("You are lost my friend")
}
http.exception(AuthException::class) {
status(401)
response.body(exception.message)
}
}
| 22 | Kotlin | 48 | 974 | d6ac9cbb3a6d9841581424e41c50be927e4ced72 | 2,157 | spark-kotlin | Apache License 2.0 |
app/src/main/kotlin/com/tezov/lib/adapterJavaToKotlin/async/IteratorBufferAsync_K.kt | tezov | 640,329,100 | false | null | package com.tezov.lib.adapterJavaToKotlin.async
import com.tezov.lib_java.debug.DebugLog
import com.tezov.lib_java.debug.DebugException
import com.tezov.lib_java.debug.DebugTrack
import com.tezov.lib_java.async.Handler
import com.tezov.lib_java.type.runnable.RunnableGroup
import com.tezov.lib_java.util.UtilsList.NULL_INDEX
import com.tezov.lib_java.wrapperAnonymous.PredicateW
import kotlinx.coroutines.*
import com.tezov.lib.adapterJavaToKotlin.async.Completable.notifyComplete
import com.tezov.lib.adapterJavaToKotlin.async.Completable.notifyException
import com.tezov.lib.adapterJavaToKotlin.async.Completable.onComplete
import com.tezov.lib.adapterJavaToKotlin.async.Handler.postRun
import com.tezov.lib.adapterJavaToKotlin.runnable.RunnableGroup_Kext.addRun
import com.tezov.lib.adapterJavaToKotlin.runnable.RunnableGroup_Kext.setOnDoneRun
import com.tezov.lib.adapterJavaToKotlin.runnable.RunnableGroup_Kext.build
import okhttp3.internal.notify
import okhttp3.internal.wait
import java.util.*
class IteratorBufferAsync_K<T : Any> constructor(
private var handlerUpdate: Handler,
private var dataProvider: defProviderAsync_K<T>?,
) : MutableListIterator<T> {
private var setCurrentIndexJob: Deferred<Int?>? = null
private var updateTailJob: Deferred<Unit>? = null
private var updateHeadJob: Deferred<Unit>? = null
private var dataList: MutableList<T>? = null
private var lastIndex: Int? = null
private var firstIndex: Int? = null
private var currentIndex: Int? = null
private var triggerSizeBeforeDownload = 5
private var sizeToDownload = 20
init {
/*#-debug-> DebugTrack.start().create(this).end() <-debug-#*/
}
private fun me(): IteratorBufferAsync_K<T> {
return this
}
private enum class LockState{
NONE, LOCAL, LOCAL_FROM_GLOBAL, GLOBAL
}
private var lock = LockState.NONE
private fun lockAll(){
// DebugLog.start().send("-------"+ Thread.getName() + ":: request lock:All from " + lock).end()
synchronized(me()){
while(lock != LockState.NONE){
me().wait()
}
lock = LockState.LOCAL_FROM_GLOBAL
// DebugLog.start().send("-------"+Thread.getName() + ":: " + "locked:" + lock).end()
}
}
private fun lock(state: LockState){
// DebugLog.start().send("-------"+ Thread.getName() + ":: request lock:" + state + " from " + lock).end()
if((state == LockState.LOCAL_FROM_GLOBAL)||(state == LockState.NONE)){
/*#-debug-> DebugException.start().log("forbidden request state " + state).end() <-debug-#*/
}
synchronized(me()){
if((state == LockState.LOCAL)&&(lock == LockState.GLOBAL)){
lock = LockState.LOCAL_FROM_GLOBAL
// DebugLog.start().send("-------"+Thread.getName() + ":: " + "locked:" + lock).end()
return@synchronized
}
while(lock != LockState.NONE){
me().wait()
}
lock = state
// DebugLog.start().send("-------"+Thread.getName() + ":: " + "locked:" + lock).end()
}
}
private fun unlock(){
// DebugLog.start().send("-------"+Thread.getName() + ":: " + "request unlock from " + lock).end()
synchronized(me()){
if(lock == LockState.LOCAL_FROM_GLOBAL){
lock = LockState.GLOBAL
// DebugLog.start().send("-------"+Thread.getName() + ":: " + "unlocked:" + lock).end()
return@synchronized
}
if(lock != LockState.NONE){
lock = LockState.NONE
// DebugLog.start().send("-------"+Thread.getName() + ":: " + "unlocked:" + lock).end()
me().notify()
}
else{
/*#-debug-> DebugException.start().log("was not locked").end() <-debug-#*/
}
}
}
private fun unlockAll(){
// DebugLog.start().send("-------"+Thread.getName() + ":: " + "request unlock All from " + lock).end()
synchronized(me()){
if(lock == LockState.LOCAL_FROM_GLOBAL){
lock = LockState.NONE
// DebugLog.start().send("-------"+Thread.getName() + ":: " + "unlocked:" + lock).end()
me().notify()
}
else{
/*#-debug-> DebugException.start().log("was not All locked").end() <-debug-#*/
}
}
}
fun setTriggerSizeBeforeDownload(size: Int) {
triggerSizeBeforeDownload = size
}
fun setSizeToDownload(size: Int) {
sizeToDownload = size
}
fun setDataProvider(dataProvider: defProviderAsync_K<T>){
this.dataProvider = dataProvider
}
fun getDataProvider(): defProviderAsync_K<T> {
return dataProvider!!
}
private fun setNextIndex(index: Int?, waitCompletion: Boolean): Deferred<Int?> {
synchronized(me()){setCurrentIndexJob}?.let { deferred ->
if (waitCompletion) {
runBlocking(Dispatchers.Unconfined) {
deferred.join()
}
}
return deferred
}
?: let {
val deferred:CompletableDeferred<Int?> = CompletableDeferred()
handlerUpdate.postRun(this){
//NOW should cancel all progressing update head and tail
if (index == null) {
dataProvider!!.getFirstIndex().onComplete {
val completed = it.getCompleted()
if (completed != null) {
lock(LockState.LOCAL)
firstIndex = completed
lastIndex = firstIndex!! - 1
currentIndex = lastIndex
dataList = newDataList()
unlock()
updateHeadAndTail().onComplete {
deferred.notifyComplete(index)
}
}
else {
lock(LockState.LOCAL)
firstIndex = null
lastIndex = null
currentIndex = null
dataList = null
unlock()
deferred.notifyComplete(index)
}
}
}
else {
dataProvider!!.size().onComplete {
val size = it.getCompleted()
if (index >= size) {
deferred.notifyException(IndexOutOfBoundsException("index:" + index + " size" + ":" + size))
return@onComplete
}
lock(LockState.LOCAL)
firstIndex = index
lastIndex = firstIndex!! - 1
currentIndex = lastIndex
dataList = newDataList()
unlock()
updateHeadAndTail().onComplete {
deferred.notifyComplete(index)
}
}
}
}
with(deferred) {
setCurrentIndexJob = deferred
onComplete {
setCurrentIndexJob = null
}
}
if(waitCompletion) {
runBlocking(Dispatchers.Unconfined) {
deferred.join()
}
}
return deferred
}
}
fun setCurrentIndex(index: Int) {
lockAll()
val direction = currentIndex?.let { index - it }
if(isLoadedNoLock(index)) {
currentIndex = index
unlockAll()
direction?.let {
if(it > 0){
updateTail(false)
}
else{
updateHead(false)
}
}
return
}
unlock()
direction?.takeIf{Math.abs(direction) < triggerSizeBeforeDownload}?.let {
if(it>0){
updateTail(true)
}
else{
updateHead(true)
}
}
lock(LockState.LOCAL)
if(isLoadedNoLock(index)){
currentIndex = index
unlockAll()
return
}
unlock()
runBlocking(Dispatchers.Unconfined) {
while(setNextIndex(index, false).await() != index){}
lock(LockState.LOCAL)
currentIndex = index
unlockAll()
}
}
fun initIndex():Deferred<Unit> {
return RunnableGroup(this, handlerUpdate).build { deferred ->
addRun {
setNextIndex(null, false).onComplete {
if(it.getCompleted() == null){
next()
}
else{
repeat()
}
}
}
setOnDoneRun {
deferred.notifyComplete()
}
start()
}
}
private fun updateHeadAndTail(): Deferred<Unit> {
val deferred = RunnableGroup(this, handlerUpdate).name("updateHeadAndTailNoSync")
.build<Unit> { deferred ->
addRun {
updateTail( false)
?.onComplete {
next()
}
?: next()
}
addRun {
updateHead( false)
?.onComplete {
next()
}
?: next()
}
setOnDoneRun {
deferred.notifyComplete()
}
start()
}
return deferred
}
private fun newDataList(): MutableList<T> {
return ArrayList()
}
private fun reduceHeadNoLock() {
if (currentIndex!! - firstIndex!! <= sizeToDownload) {
return
}
val sizeToRemove = currentIndex!! - firstIndex!! - sizeToDownload
dataList = dataList!!.subList(sizeToRemove, dataList!!.size)
/*#-debug-> DebugLog.start().send(me(), "reduce head from " + firstIndex + " to " + (firstIndex!! + sizeToRemove))
.end() <-debug-#*/
firstIndex = firstIndex!! + sizeToRemove
}
private fun updateTail(waitCompletion: Boolean): Deferred<Unit>? {
synchronized(me()){updateTailJob}?.let { deferred ->
if (waitCompletion) {
runBlocking(Dispatchers.Unconfined) {
deferred.join()
}
}
return deferred
}
?: let {
lock(LockState.LOCAL)
val result = lastIndex!! - currentIndex!! > triggerSizeBeforeDownload
unlock()
if (result) {
return null
}
val deferred:CompletableDeferred<Unit> = CompletableDeferred()
handlerUpdate.postRun(this){
lock(LockState.LOCAL)
val index = lastIndex!! + 1
unlock()
dataProvider!!.select(index, sizeToDownload).onComplete {
it.getCompleted()?.let select@{
var newDatas = it
if(newDatas.isEmpty()){
return@select
}
lock(LockState.LOCAL)
if (index <= lastIndex!!) {
val diff = lastIndex!! - index
if (index + diff > newDatas.size - 1) {
unlock()
return@select
}
newDatas = newDatas.subList(index + diff + 1, newDatas.size)
}
if(newDatas.isEmpty()) {
unlock()
return@select
}
/*#-debug-> DebugLog.start().send(me(),
"increase tail from " + (lastIndex!! + 1) + " to " + (lastIndex!! + newDatas.size)
).end() <-debug-#*/
lastIndex = lastIndex!! + newDatas.size
dataList!!.addAll(newDatas)
reduceHeadNoLock()
unlock()
}
deferred.notifyComplete()
}
with(deferred) {
updateTailJob = deferred
onComplete {
updateTailJob = null
}
}
}
if(waitCompletion) {
runBlocking(Dispatchers.Unconfined) {
deferred.join()
}
}
return deferred
}
}
override fun hasNext(): Boolean {
lockAll()
when {
currentIndex == null -> {
unlock()
setNextIndex(null, true)
lock(LockState.LOCAL)
}
currentIndex!! >= lastIndex!! -> {
unlock()
updateTail(true)
lock(LockState.LOCAL)
}
else -> {
updateTail(false)
}
}
val result = currentIndex != null && currentIndex!! < lastIndex!!
unlockAll()
return result
}
override fun next(): T {
lockAll()
currentIndex = currentIndex!! + 1
val item = dataList!![currentIndex!! - firstIndex!!]
unlockAll()
return item
}
private fun reduceTailNoLock() {
if (lastIndex!! - currentIndex!! <= sizeToDownload) {
return
}
val sizeToRemove = lastIndex!! - currentIndex!! - sizeToDownload - 1
dataList = dataList!!.subList(0, dataList!!.size - sizeToRemove)
/*#-debug-> DebugLog.start().send(me(), "reduce tail from " + lastIndex + " to " + (lastIndex!! - sizeToRemove))
.end() <-debug-#*/
lastIndex = lastIndex!! - sizeToRemove
}
private fun updateHead(waitCompletion: Boolean): Deferred<Unit>? {
synchronized(me()){updateHeadJob}?.let { deferred ->
if (waitCompletion) {
runBlocking(Dispatchers.Unconfined) {
deferred.join()
}
}
return deferred
} ?: let {
lock(LockState.LOCAL)
val result = currentIndex!! - firstIndex!! >= triggerSizeBeforeDownload
unlock()
if (result) {
return null
}
val deferred:CompletableDeferred<Unit> = CompletableDeferred()
handlerUpdate.postRun(this){
lock(LockState.LOCAL)
val finalIndex = firstIndex!! - sizeToDownload
unlock()
dataProvider!!.select(finalIndex, sizeToDownload).onComplete {
it.getCompleted()?.let select@{
var newDatas = it.toMutableList()
if (newDatas.isEmpty()) {
return@select
}
lock(LockState.LOCAL)
val index = finalIndex + (sizeToDownload - newDatas.size)
if (firstIndex!! < index + sizeToDownload) {
val diff = firstIndex!! - index
if (diff > 0) {
newDatas = newDatas.subList(0, diff)
} else {
newDatas.clear()
}
}
if (newDatas.isEmpty()) {
unlock()
return@select
}
/*#-debug-> DebugLog.start().send(me(),
"increase head from " + (firstIndex!! - 1) + " to " + (firstIndex!! - newDatas.size)
).end() <-debug-#*/
firstIndex = firstIndex!! - newDatas.size
newDatas.addAll(dataList!!)
dataList = newDatas
reduceTailNoLock()
unlock()
}
deferred.notifyComplete()
}
with(deferred) {
updateHeadJob = deferred
onComplete {
updateHeadJob = null
}
}
}
if (waitCompletion) {
runBlocking(Dispatchers.Unconfined) {
deferred.join()
}
}
return deferred
}
}
override fun hasPrevious(): Boolean {
lockAll()
when {
currentIndex == null -> {
unlock()
setNextIndex(null, true)
lock(LockState.LOCAL)
}
firstIndex!! >= currentIndex!! -> {
unlock()
updateHead(true)
lock(LockState.LOCAL)
}
else -> {
updateHead(false)
}
}
val result = currentIndex != null && firstIndex!! <= currentIndex!!
unlockAll()
return result
}
override fun previous(): T {
lockAll()
val item = dataList!![currentIndex!! - firstIndex!!]
currentIndex = currentIndex!! - 1
unlockAll()
return item
}
fun isLoadedNoLock(index: Int): Boolean {
return currentIndex != null && index >= firstIndex!! && index <= lastIndex!!
}
fun isLoaded(index: Int): Boolean {
lockAll()
val result = currentIndex != null && index >= firstIndex!! && index <= lastIndex!!
unlockAll()
return result
}
fun get(index: Int, setAsCurrentIndex:Boolean = false): T {
if(setAsCurrentIndex){
setCurrentIndex(index)
}
lock(LockState.LOCAL)
val item = dataList!![index - firstIndex!!]
unlock()
return item
}
fun getFromBuffer(predicate: PredicateW<T>): T? {
return dataList?.find {
predicate.test(it)
}
}
fun indexOfFromBuffer(predicate: PredicateW<T>): Int? {
dataList?.forEachIndexed { index, item ->
if (predicate.test(item)) {
return index + firstIndex!!
}
}
return null
}
override fun remove() {
/*#-debug-> DebugException.start().notImplemented().end() <-debug-#*/
}
override fun set(t: T) {
/*#-debug-> DebugException.start().notImplemented().end() <-debug-#*/
}
override fun add(t: T) {
/*#-debug-> DebugException.start().notImplemented().end() <-debug-#*/
}
override fun nextIndex(): Int {
/*#-debug-> DebugException.start().notImplemented().end() <-debug-#*/
return NULL_INDEX
}
override fun previousIndex(): Int {
/*#-debug-> DebugException.start().notImplemented().end() <-debug-#*/
return NULL_INDEX
}
fun notifyInsert(index: Int, t: T) {
lockAll()
when {
this.isLoadedNoLock(index) -> {
dataList!!.add(index - firstIndex!!, t)
lastIndex = lastIndex!! + 1
}
currentIndex != null -> {
if(index < firstIndex!!){
firstIndex = firstIndex!! + 1
lastIndex = lastIndex!! + 1
}
}
else -> {
firstIndex = index
lastIndex = firstIndex
currentIndex = lastIndex
dataList = newDataList()
dataList!!.add(t)
}
}
unlockAll()
}
fun notifyUpdate(index: Int, t: T) {
if (this.isLoadedNoLock(index)) {
dataList!!.removeAt(index - firstIndex!!)
dataList!!.add(index - firstIndex!!, t)
}
}
fun notifyUpdateAll() {
initIndex()
}
fun notifyRemove(t: T) {
lockAll()
dataList?.forEachIndexed { index, item ->
if (item == t) {
notifyRemoveNoLock(index + firstIndex!!)
return@forEachIndexed
}
}
unlockAll()
}
fun notifyRemove(index: Int) {
lockAll()
notifyRemoveNoLock(index)
unlockAll()
}
private fun notifyRemoveNoLock(index: Int) {
when {
this.isLoadedNoLock(index) -> {
dataList!!.removeAt(index - firstIndex!!)
if (index == lastIndex) {
currentIndex = currentIndex!! - 1
}
lastIndex = lastIndex!! - 1
if (lastIndex!! < firstIndex!!) {
firstIndex = null
currentIndex = null
lastIndex = null
dataList = null
}
}
currentIndex != null -> {
if(index < firstIndex!!){
firstIndex = firstIndex!! - 1
lastIndex = lastIndex!! - 1
}
}
}
}
protected fun finalize() {
/*#-debug-> DebugTrack.start().destroy(this).end() <-debug-#*/
}
} | 0 | Kotlin | 0 | 0 | 02d5d2125f6211e94410cda57af23469a4fa3a33 | 21,626 | gofo | MIT License |
plugins/git4idea/src/git4idea/ui/branch/dashboard/BranchesTreeModel.kt | hieuprogrammer | 284,920,751 | true | null | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package git4idea.ui.branch.dashboard
import com.intellij.openapi.actionSystem.DataKey
import com.intellij.util.ThreeState
import com.intellij.vcs.log.util.VcsLogUtil
import git4idea.i18n.GitBundle.message
import git4idea.repo.GitRepository
import java.util.*
import javax.swing.tree.DefaultMutableTreeNode
internal val GIT_BRANCHES = DataKey.create<Set<BranchInfo>>("GitBranchKey")
internal data class BranchInfo(val branchName: String,
val isLocal: Boolean,
val isCurrent: Boolean,
var isFavorite: Boolean,
val repositories: List<GitRepository>) {
var isMy: ThreeState = ThreeState.UNSURE
override fun toString() = branchName
}
internal data class BranchNodeDescriptor(val type: NodeType,
val branchInfo: BranchInfo? = null,
val displayName: String? = branchInfo?.branchName,
val parent: BranchNodeDescriptor? = null) {
override fun toString(): String {
val suffix = branchInfo?.branchName ?: displayName
return if (suffix != null) "$type:$suffix" else "$type"
}
fun getDisplayText() = displayName ?: branchInfo?.branchName
}
internal enum class NodeType {
ROOT, LOCAL_ROOT, REMOTE_ROOT, BRANCH, GROUP_NODE, HEAD_NODE
}
internal class BranchTreeNode(nodeDescriptor: BranchNodeDescriptor) : DefaultMutableTreeNode(nodeDescriptor) {
fun getTextRepresentation(): String {
val nodeDescriptor = userObject as? BranchNodeDescriptor ?: return super.toString()
return when (nodeDescriptor.type) {
NodeType.LOCAL_ROOT -> message("group.Git.Local.Branch.title")
NodeType.REMOTE_ROOT -> message("group.Git.Remote.Branch.title")
else -> nodeDescriptor.getDisplayText() ?: super.toString()
}
}
fun getNodeDescriptor() = userObject as BranchNodeDescriptor
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
if (other !is BranchTreeNode) return false
return Objects.equals(this.userObject, other.userObject)
}
override fun hashCode() = Objects.hash(userObject)
}
internal class NodeDescriptorsModel(private val localRootNodeDescriptor: BranchNodeDescriptor,
private val remoteRootNodeDescriptor: BranchNodeDescriptor) {
/**
* Parent node descriptor to direct children map
*/
private val branchNodeDescriptors = hashMapOf<BranchNodeDescriptor, MutableSet<BranchNodeDescriptor>>()
fun clear() = branchNodeDescriptors.clear()
fun getChildrenForParent(parent: BranchNodeDescriptor): Set<BranchNodeDescriptor> =
branchNodeDescriptors.getOrDefault(parent, emptySet())
fun populateFrom(branches: Sequence<BranchInfo>, useGrouping: Boolean) {
branches.forEach { branch -> populateFrom(branch, useGrouping) }
}
private fun populateFrom(br: BranchInfo, useGrouping: Boolean) {
val branch = with(br) { BranchInfo(branchName, isLocal, isCurrent, isFavorite, repositories) }
var curParent: BranchNodeDescriptor = if (branch.isLocal) localRootNodeDescriptor else remoteRootNodeDescriptor
if (!useGrouping) {
addChild(curParent, BranchNodeDescriptor(NodeType.BRANCH, branch, parent = curParent))
return
}
val iter = branch.branchName.split("/").iterator()
while (iter.hasNext()) {
val branchNamePart = iter.next()
val groupNode = iter.hasNext()
val nodeType = if (groupNode) NodeType.GROUP_NODE else NodeType.BRANCH
val branchInfo = if (nodeType == NodeType.BRANCH) branch else null
val branchNodeDescriptor = BranchNodeDescriptor(nodeType, branchInfo, displayName = branchNamePart, parent = curParent)
addChild(curParent, branchNodeDescriptor)
curParent = branchNodeDescriptor
}
}
private fun addChild(parent: BranchNodeDescriptor, child: BranchNodeDescriptor) {
val directChildren = branchNodeDescriptors.computeIfAbsent(parent) { sortedSetOf(BRANCH_TREE_NODE_COMPARATOR) }
directChildren.add(child)
branchNodeDescriptors[parent] = directChildren
}
}
internal val BRANCH_TREE_NODE_COMPARATOR = Comparator<BranchNodeDescriptor> { d1, d2 ->
val b1 = d1.branchInfo
val b2 = d2.branchInfo
val displayText1 = d1.getDisplayText()
val displayText2 = d2.getDisplayText()
val b1GroupNode = d1.type == NodeType.GROUP_NODE
val b2GroupNode = d2.type == NodeType.GROUP_NODE
val b1Current = b1 != null && b1.isCurrent
val b2Current = b2 != null && b2.isCurrent
val b1Favorite = b1 != null && b1.isFavorite
val b2Favorite = b2 != null && b2.isFavorite
fun compareByDisplayTextOrType() =
if (displayText1 != null && displayText2 != null) displayText1.compareTo(displayText2) else d1.type.compareTo(d2.type)
when {
b1Current && b2Current -> compareByDisplayTextOrType()
b1Current -> -1
b2Current -> 1
b1Favorite && b2Favorite -> compareByDisplayTextOrType()
b1Favorite -> -1
b2Favorite -> 1
b1GroupNode && b2GroupNode -> compareByDisplayTextOrType()
b1GroupNode -> -1
b2GroupNode -> 1
else -> compareByDisplayTextOrType()
}
}
| 12 | null | 2 | 2 | dc846ecb926c9d9589c1ed8a40fdb20e47874db9 | 5,379 | intellij-community | Apache License 2.0 |
src/main/kotlin/com/cout970/reactive/core/RContext.kt | cout970 | 121,807,275 | false | null | package com.cout970.reactive.core
import org.liquidengine.legui.component.Component
data class RContext(val mountPoint: Component, val app: RNode) {
internal val unmountedComponents = mutableSetOf<RComponent<*, *>>()
internal val mountedComponents = mutableSetOf<RComponent<*, *>>()
internal val updateListeners: MutableList<(Pair<Component, RNode>) -> Unit> = mutableListOf()
fun registerUpdateListener(func: (Pair<Component, RNode>) -> Unit) {
updateListeners.add(func)
}
} | 0 | Kotlin | 0 | 2 | 40cc6b38c57ca249c50aa7359a7afe0da041fa36 | 508 | Reactive | MIT License |
mobile_app1/module1153/src/main/java/module1153packageKt0/Foo24.kt | uber-common | 294,831,672 | false | null | package module1153packageKt0;
annotation class Foo24Fancy
@Foo24Fancy
class Foo24 {
fun foo0(){
module1153packageKt0.Foo23().foo5()
}
fun foo1(){
foo0()
}
fun foo2(){
foo1()
}
fun foo3(){
foo2()
}
fun foo4(){
foo3()
}
fun foo5(){
foo4()
}
} | 6 | Java | 6 | 72 | 9cc83148c1ca37d0f2b2fcb08c71ac04b3749e5e | 295 | android-build-eval | Apache License 2.0 |
tl/src/main/kotlin/com/github/badoualy/telegram/tl/api/messages/TLAffectedMessages.kt | Miha-x64 | 436,587,061 | true | {"Kotlin": 3919807, "Java": 75352} | package com.github.badoualy.telegram.tl.api.messages
import com.github.badoualy.telegram.tl.TLObjectUtils.SIZE_CONSTRUCTOR_ID
import com.github.badoualy.telegram.tl.TLObjectUtils.SIZE_INT32
import com.github.badoualy.telegram.tl.core.TLObject
import com.github.badoualy.telegram.tl.serialization.TLDeserializer
import com.github.badoualy.telegram.tl.serialization.TLSerializer
import java.io.IOException
/**
* messages.affectedHistory#b45c69d1
*
* @author <NAME> <EMAIL>
* @see <a href="http://github.com/badoualy/kotlogram">http://github.com/badoualy/kotlogram</a>
*/
class TLAffectedHistory() : TLObject() {
var pts: Int = 0
var ptsCount: Int = 0
var offset: Int = 0
private val _constructor: String = "messages.affectedHistory#b45c69d1"
override val constructorId: Int = CONSTRUCTOR_ID
constructor(
pts: Int,
ptsCount: Int,
offset: Int
) : this() {
this.pts = pts
this.ptsCount = ptsCount
this.offset = offset
}
@Throws(IOException::class)
override fun serializeBody(tlSerializer: TLSerializer) = with (tlSerializer) {
writeInt(pts)
writeInt(ptsCount)
writeInt(offset)
}
@Throws(IOException::class)
override fun deserializeBody(tlDeserializer: TLDeserializer) = with (tlDeserializer) {
pts = readInt()
ptsCount = readInt()
offset = readInt()
}
override fun computeSerializedSize(): Int {
var size = SIZE_CONSTRUCTOR_ID
size += SIZE_INT32
size += SIZE_INT32
size += SIZE_INT32
return size
}
override fun toString() = _constructor
override fun equals(other: Any?): Boolean {
if (other !is TLAffectedHistory) return false
if (other === this) return true
return pts == other.pts
&& ptsCount == other.ptsCount
&& offset == other.offset
}
companion object {
const val CONSTRUCTOR_ID: Int = 0xb45c69d1.toInt()
}
}
| 1 | Kotlin | 2 | 3 | 1a8963dce921c1e9ef05b9d1e56d8fbcb1ea1c4b | 2,051 | kotlogram-resurrected | MIT License |
app/src/main/java/app/lawnchair/lawnicons/Lawnicons.kt | wrongway213 | 424,343,804 | true | {"Kotlin": 11776, "Python": 2514} | package app.lawnchair.lawnicons
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.Surface
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
@Composable
@ExperimentalFoundationApi
fun Lawnicons() {
var searchTerm by remember { mutableStateOf(value = "") }
LawniconsTheme {
SystemUi {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
Column {
SearchBar(
value = searchTerm,
onValueChange = { searchTerm = it }
)
IconPreviewGrid(searchTerm = searchTerm)
}
}
}
}
} | 0 | Kotlin | 0 | 0 | 3f9466739c27f54e7d873c18353558d28c99db1f | 957 | lawnicons | Apache License 2.0 |
src/main/kotlin/com/github/pawelkowalski92/aoc/day04/LotteryScratchcardOrganizer.kt | pawelkowalski92 | 726,175,728 | false | {"Kotlin": 77190} | package com.github.pawelkowalski92.aoc.day04
import com.github.pawelkowalski92.aoc.day04.card.CardParser
import com.github.pawelkowalski92.aoc.day04.card.CardStackGenerator
class LotteryScratchcardOrganizer(
private val parser: CardParser,
private val stackGenerator: CardStackGenerator
) {
fun organizeAllScratchcards(input: Collection<String>): Int = input.map(parser::parseCard)
.let(stackGenerator::buildWinningStack)
.size
} | 0 | Kotlin | 0 | 0 | 96879809e9175073ac1d19a93db8d76d90686500 | 461 | advent-of-code-2023 | Apache License 2.0 |
ui/src/main/java/es/marcrdz/ui/composables/Characters.kt | marcRDZ | 556,833,664 | false | {"Kotlin": 64018} | package es.marcrdz.ui.composables
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.skydoves.landscapist.ImageOptions
import com.skydoves.landscapist.glide.GlideImage
import es.marcrdz.presentation.domain.CharacterVO
import es.marcrdz.ui.R
import es.marcrdz.ui.theme.MarvelArchivesTheme
import es.marcrdz.ui.theme.MarvelGray
import es.marcrdz.ui.theme.Shapes
@Composable
fun CharacterList(
characters: List<CharacterVO>,
onEndReached: () -> Unit,
modifier: Modifier = Modifier,
state: LazyListState = rememberLazyListState()
) {
val endReached = remember {
derivedStateOf {
state.layoutInfo.visibleItemsInfo.lastOrNull()?.index == state.layoutInfo.totalItemsCount -1
}
}
LazyColumn(
state = state,
modifier = modifier
.fillMaxSize()
.background(color = MarvelGray)
) {
characters.takeIf { it.isNotEmpty() }?.let {
items(count = it.size) { index ->
CharacterItem(item = it[index], modifier)
}
} ?: run {
item {
Text(
text = stringResource(id = R.string.nothing_found_here),
modifier = modifier.padding(all = 12.dp),
color = Color.DarkGray
)
}
}
}
if (endReached.value) onEndReached.invoke()
}
@Composable
fun CharacterItem(item: CharacterVO, modifier: Modifier = Modifier) {
val randomColor: Int = android.graphics.Color.rgb(
(30..200).random(),
(30..200).random(),
(30..200).random()
)
Column(
modifier = modifier
.wrapContentHeight()
.fillMaxWidth()
.padding(horizontal = 8.dp, vertical = 4.dp)
.background(
color = Color.White,
shape = Shapes.medium
),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
) {
Column(
modifier = modifier
.padding(start = 12.dp, top = 4.dp, end = 12.dp, bottom = 2.dp)
.wrapContentHeight()
.fillMaxWidth(),
verticalArrangement = Arrangement.SpaceBetween,
horizontalAlignment = Alignment.Start
) {
Text(
text = item.name,
color = Color(randomColor)
)
item.description.takeIf { it.isNotEmpty() }?.let {
Text(
text = stringResource(id = R.string.description_double_dot),
color = Color.LightGray
)
Text(
text = item.description,
color = Color.DarkGray
)
}
}
Row(
modifier = modifier
.padding(start = 12.dp, top = 2.dp, end = 12.dp, bottom = 4.dp)
.wrapContentHeight()
.fillMaxWidth(),
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically
) {
GlideImage(
imageModel = { item.thumbnail },
imageOptions = ImageOptions(
contentScale = ContentScale.FillWidth
)
)
}
}
}
@Preview(showBackground = true, widthDp = 300, heightDp = 300)
@Composable
fun DefaultPreview() {
MarvelArchivesTheme {
CharacterItem(
item = CharacterVO(
name = "3-D Man",
description = "The unique man in 3D in the world!",
thumbnail = "http://i.annihil.us/u/prod/marvel/i/mg/c/e0/535fecbbb9784.jpg",
)
)
}
} | 0 | Kotlin | 0 | 0 | d85a758d9798b33affc3a70be14f246283017361 | 4,448 | MarvelArchives | Apache License 2.0 |
src/main/kotlin/org/rust/lang/core/psi/RsFileViewProviderFactory.kt | intellij-rust | 42,619,487 | false | {"Kotlin": 11390660, "Rust": 176571, "Python": 109964, "HTML": 23157, "Lex": 12605, "ANTLR": 3304, "Java": 688, "Shell": 377, "RenderScript": 343} | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.psi
import com.intellij.lang.Language
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.FileViewProvider
import com.intellij.psi.FileViewProviderFactory
import com.intellij.psi.PsiManager
import com.intellij.psi.SingleRootFileViewProvider
/**
* Hacky adjust the file limit for Rust file.
* Coupled with [org.rust.lang.core.resolve.indexes.RsAliasIndex.getFileTypesWithSizeLimitNotApplicable].
*
* @see SingleRootFileViewProvider.isTooLargeForIntelligence
*/
class RsFileViewProviderFactory : FileViewProviderFactory {
override fun createFileViewProvider(
file: VirtualFile,
language: Language,
manager: PsiManager,
eventSystemEnabled: Boolean
): FileViewProvider {
val shouldAdjustFileLimit = SingleRootFileViewProvider.isTooLargeForIntelligence(file)
&& file.length <= RUST_FILE_SIZE_LIMIT_FOR_INTELLISENSE
if (shouldAdjustFileLimit) {
SingleRootFileViewProvider.doNotCheckFileSizeLimit(file)
}
return SingleRootFileViewProvider(manager, file, eventSystemEnabled)
}
}
// Experimentally verified that 8Mb works with the default IDEA -Xmx768M. Larger values may
// lead to OOM, please verify before adjusting
private const val RUST_FILE_SIZE_LIMIT_FOR_INTELLISENSE: Int = 8 * 1024 * 1024
| 1,843 | Kotlin | 392 | 4,524 | c6657c02bb62075bf7b7ceb84d000f93dda34dc1 | 1,450 | intellij-rust | MIT License |
buildSrc/src/main/kotlin/BuildConstants.kt | SickMC | 450,823,022 | false | {"Kotlin": 48786, "Java": 14148} | object BuildConstants {
const val version = "1.0.0"
val projectName = "SickCore"
val authors = listOf("btwonion")
val contributors = listOf("btwonion")
const val githubRepo = "SickMC/SickCore"
val isSnapshot = false
const val sickAPIVersion = "1.0.11"
// Kotlin
const val kotlinVersion = "1.7.21"
const val serializationVersion = "1.4.1"
const val coroutinesVersion = "1.6.4"
const val ktorVersion = "2.1.3"
// Database
const val kmongoVersion = "4.7.2"
// Fabric
const val minecraftVersion = "1.19.2"
const val quiltMappingsVersion = "1.19.2+build.21:v2"
const val fabricLoaderVersion = "0.14.10"
const val fabricAPIVersion = "0.66.0+1.19.2"
const val fabricLanguageKotlinVersion = "1.8.6+kotlin.1.7.21"
const val silkVersion = "1.9.2"
// Velocity
const val velocityVersion = "4.0.0-SNAPSHOT"
} | 2 | Kotlin | 0 | 2 | f09ecb79c38bab89fa435061a4b3810ccef9e70d | 892 | SickCore | MIT License |
local_component/src/main/java/com/xyoye/local_component/ui/activities/bilibili_danmu/BilibiliDanmuViewModel.kt | ThaiCao | 652,559,535 | true | {"Kotlin": 1396162, "Java": 393541, "Shell": 17996} | package com.xyoye.local_component.ui.activities.bilibili_danmu
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.xyoye.common_component.base.BaseViewModel
import com.xyoye.common_component.network.Retrofit
import com.xyoye.common_component.utils.DanmuUtils
import com.xyoye.common_component.utils.IOUtils
import com.xyoye.common_component.utils.JsonHelper
import com.xyoye.common_component.utils.PathHelper
import com.xyoye.data_component.data.CidBungumiData
import com.xyoye.data_component.data.CidVideoBean
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import org.jsoup.Jsoup
import java.io.File
import java.io.InputStream
import java.util.*
import java.util.regex.Pattern
import java.util.zip.Inflater
import java.util.zip.InflaterInputStream
class BilibiliDanmuViewModel : BaseViewModel() {
val downloadMessageLiveData = MutableLiveData<String>()
val clearMessageLiveData = MutableLiveData<Boolean>()
fun downloadByCode(code: String, isAvCode: Boolean) {
viewModelScope.launch(Dispatchers.IO) {
clearDownloadMessage()
val message = if (isAvCode) "以AV号模式下载, AV号:$code" else "以BV号模式下载, BV号:$code"
sendDownloadMessage("$message\n\n开始获取CID")
val cidInfo = getCodeCid(isAvCode, code)
if (cidInfo == null) {
sendDownloadMessage("获取CID失败")
return@launch
}
sendDownloadMessage("获取CID成功\n\n开始获取弹幕内容")
val xmlContent = getXmlContentByCid(cidInfo.first)
if (xmlContent.isNullOrEmpty()) {
sendDownloadMessage("获取弹幕内容失败")
return@launch
}
sendDownloadMessage("获取弹幕内容成功\n\n开始保存弹幕内容")
val danmuFileName = cidInfo.second + ".xml"
val danmuPath = DanmuUtils.saveDanmu(danmuFileName, null, xmlContent)
if (danmuPath.isNullOrEmpty()) {
sendDownloadMessage("保存弹幕内容失败")
return@launch
}
sendDownloadMessage("保存弹幕内容成功\n\n文件已保存至:$danmuPath")
}
}
fun downloadByUrl(url: String) {
viewModelScope.launch(Dispatchers.IO) {
clearDownloadMessage()
val message = "以视频链接模式下载, 视频链接:$url"
if (isBangumiUrl(url)) {
sendDownloadMessage("$message\n\n开始获取番剧列表CID")
val cidInfo = getBungumiCid(url)
if (cidInfo == null) {
sendDownloadMessage("获取番剧列表CID失败")
return@launch
}
sendDownloadMessage("获取番剧列表CID成功, CID数量:${cidInfo.first.size}\n\n开始下载弹幕")
for ((index, cid) in cidInfo.first.withIndex()) {
var downloadMessage = "第${index + 1}集 "
val xmlContent = getXmlContentByCid(cid)
if (xmlContent == null) {
downloadMessage += "获取弹幕内容失败"
sendDownloadMessage(downloadMessage)
continue
}
downloadMessage += "获取弹幕内容成功 "
val fileName = "${index + 1}.xml"
val danmuPath = DanmuUtils.saveDanmu(fileName, cidInfo.second, xmlContent)
if (danmuPath == null) {
downloadMessage += "保存弹幕失败"
sendDownloadMessage(downloadMessage)
continue
}
downloadMessage += "保存弹幕成功"
sendDownloadMessage(downloadMessage)
}
val danmuFolder = File(PathHelper.getDanmuDirectory(), cidInfo.second).absolutePath
sendDownloadMessage("\n番剧列表弹幕下载完成\n文件已保存至:$danmuFolder\"")
} else {
sendDownloadMessage("$message\n\n开始获取视频CID")
val cidInfo = getVideoCid(url)
if (cidInfo == null) {
sendDownloadMessage("获取视频CID失败")
return@launch
}
sendDownloadMessage("获取视频CID成功\n\n开始获取弹幕内容")
val xmlContent = getXmlContentByCid(cidInfo.first)
if (xmlContent.isNullOrEmpty()) {
sendDownloadMessage("获取弹幕内容失败")
return@launch
}
sendDownloadMessage("获取弹幕内容成功\n\n开始保存弹幕内容")
val danmuFileName = cidInfo.second + ".xml"
val danmuPath = DanmuUtils.saveDanmu(danmuFileName, null, xmlContent)
if (danmuPath.isNullOrEmpty()) {
sendDownloadMessage("保存弹幕内容失败")
return@launch
}
sendDownloadMessage("保存弹幕内容成功\n\n文件已保存至:$danmuPath")
}
}
}
private suspend fun getVideoCid(url: String): Pair<Long, String>? {
return viewModelScope.async(Dispatchers.IO) {
try {
val htmlElement = Jsoup.connect(url).timeout(10 * 1000).get().toString()
//匹配java script里的json数据
val pattern = Pattern.compile("(__INITIAL_STATE__=).*(;\\(function)")
val matcher = pattern.matcher(htmlElement)
if (matcher.find()) {
var jsonText = matcher.group(0) ?: return@async null
if (jsonText.isNotEmpty()) {
jsonText = jsonText.substring(18)
jsonText = jsonText.substring(0, jsonText.length - 10)
val cidBean =
JsonHelper.parseJson<CidVideoBean>(jsonText) ?: return@async null
//只需要标题和cid
return@async Pair(cidBean.videoData.cid, cidBean.videoData.title)
}
}
} catch (t: Throwable) {
sendDownloadMessage("错误:${t.message}")
t.printStackTrace()
}
null
}.await()
}
private suspend fun getBungumiCid(url: String): Pair<MutableList<Long>, String>? {
return viewModelScope.async(Dispatchers.IO, start = CoroutineStart.LAZY) {
try {
val htmlElement = Jsoup.connect(url).timeout(10 * 1000).get().toString()
val pattern = Pattern.compile("(__INITIAL_STATE__=).*(;\\(function)")
val matcher = pattern.matcher(htmlElement)
if (matcher.find()) {
var jsonText = matcher.group(0) ?: return@async null
if (jsonText.isNotEmpty()) {
jsonText = jsonText.substring(18)
jsonText = jsonText.substring(0, jsonText.length - 10)
val cidBean =
JsonHelper.parseJson<CidBungumiData>(jsonText) ?: return@async null
//只需要标题和cid
val cidList = mutableListOf<Long>()
cidBean.epList.forEach {
cidList.add(it.cid)
}
return@async Pair(cidList, cidBean.mediaInfo.title)
}
}
} catch (t: Throwable) {
sendDownloadMessage("错误:${t.message}")
t.printStackTrace()
}
null
}.await()
}
private suspend fun getCodeCid(isAvCode: Boolean, value: String): Pair<Long, String>? {
return viewModelScope.async(Dispatchers.IO, start = CoroutineStart.LAZY) {
val key = if (isAvCode) "aid" else "bvid"
val apiUrl = "https://api.bilibili.com/x/web-interface/view?$key=$value"
try {
val cidData = Retrofit.extService.getCidInfo(apiUrl)
if (cidData.code == 0 && cidData.data != null) {
val videoTitle = cidData.data!!.title ?: "未知弹幕"
return@async Pair(cidData.data!!.cid, videoTitle)
}
} catch (t: Throwable) {
sendDownloadMessage("错误:${t.message}")
t.printStackTrace()
}
null
}.await()
}
private suspend fun getXmlContentByCid(cid: Long): String? {
return viewModelScope.async(Dispatchers.IO, start = CoroutineStart.LAZY) {
val url = "http://comment.bilibili.com/$cid.xml"
val header = mapOf(Pair("Accept-Encoding", "gzip,deflate"))
var inputStream: InputStream? = null
var inflaterInputStream: InflaterInputStream? = null
var scanner: Scanner? = null
var xmlContent: String? = null
try {
val responseBody = Retrofit.extService.downloadResource(url, header)
inputStream = responseBody.byteStream()
inflaterInputStream = InflaterInputStream(inputStream, Inflater(true))
scanner = Scanner(inflaterInputStream, Charsets.UTF_8.name())
val contentBuilder = StringBuilder()
while (scanner.hasNext()) {
contentBuilder.append(scanner.nextLine())
}
xmlContent = contentBuilder.toString()
} catch (e: Throwable) {
sendDownloadMessage("错误:${e.message}")
e.printStackTrace()
} finally {
IOUtils.closeIO(scanner)
IOUtils.closeIO(inflaterInputStream)
IOUtils.closeIO(inputStream)
}
xmlContent
}.await()
}
private fun isBangumiUrl(url: String): Boolean {
return url.contains("www.bilibili.com/bangumi") || url.contains("m.bilibili.com/bangumi")
}
private fun sendDownloadMessage(message: String) {
downloadMessageLiveData.postValue(message)
}
private fun clearDownloadMessage() {
clearMessageLiveData.postValue(true)
}
} | 0 | Kotlin | 0 | 0 | c57197985cc1766d98107d4a6d2d87ab47746dbc | 10,587 | DanDanPlayForAndroid | Apache License 2.0 |
src/nl/hannahsten/texifyidea/inspections/bibtex/BibtexDuplicateBibliographystyleInspection.kt | Hannah-Sten | 62,398,769 | false | {"Kotlin": 2620101, "TeX": 71133, "Lex": 28995, "HTML": 23487, "Python": 967, "Perl": 39} | package nl.hannahsten.texifyidea.inspections.bibtex
import com.intellij.codeInspection.InspectionManager
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiFile
import nl.hannahsten.texifyidea.inspections.InsightGroup
import nl.hannahsten.texifyidea.inspections.TexifyInspectionBase
import nl.hannahsten.texifyidea.lang.LatexPackage
import nl.hannahsten.texifyidea.psi.LatexCommands
import nl.hannahsten.texifyidea.util.files.commandsInFile
import nl.hannahsten.texifyidea.util.files.commandsInFileSet
import nl.hannahsten.texifyidea.util.findAtLeast
import nl.hannahsten.texifyidea.util.includedPackages
/**
* @author <NAME>
*/
open class BibtexDuplicateBibliographystyleInspection : TexifyInspectionBase() {
// Manual override to match short name in plugin.xml
override fun getShortName() = InsightGroup.BIBTEX.prefix + inspectionId
override val inspectionGroup = InsightGroup.LATEX
override val inspectionId = "DuplicateBibliographystyle"
override fun getDisplayName() = "Duplicate bibliography style commands"
override fun inspectFile(file: PsiFile, manager: InspectionManager, isOntheFly: Boolean): MutableList<ProblemDescriptor> {
// Chapterbib allows multiple bibliographies
if (file.includedPackages().any { it == LatexPackage.CHAPTERBIB }) {
return mutableListOf()
}
val descriptors = descriptorList()
// Check if a bibliography is present.
val commands = file.commandsInFileSet()
commands.find { it.name == "\\bibliography" } ?: return descriptors
if (commands.findAtLeast(2) { it.name == "\\bibliographystyle" }) {
file.commandsInFile().asSequence()
.filter { it.name == "\\bibliographystyle" }
.forEach {
descriptors.add(
manager.createProblemDescriptor(
it,
TextRange(0, it.commandToken.textLength),
"\\bibliographystyle is already used elsewhere",
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
isOntheFly,
RemoveOtherCommandsFix
)
)
}
}
return descriptors
}
/**
* @author <NAME>
*/
object RemoveOtherCommandsFix : LocalQuickFix {
override fun getFamilyName(): String {
return "Remove other \\bibliographystyle commands"
}
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val command = descriptor.psiElement as LatexCommands
val file = command.containingFile
file.commandsInFileSet().asSequence()
.filter { it.name == "\\bibliographystyle" && it != command }
.forEach {
it.delete()
}
}
}
} | 38 | Kotlin | 77 | 836 | 4999e4393dbfaa69207328b77c859135d759e380 | 3,195 | TeXiFy-IDEA | MIT License |
codeSnippets/snippets/tutorial-website-interactive/src/main/kotlin/com/example/plugins/Routing.kt | ktorio | 278,572,893 | false | {"Kotlin": 289680, "FreeMarker": 10163, "HTML": 6550, "JavaScript": 5361, "Shell": 1537, "Dockerfile": 1020, "Swift": 811, "CSS": 470, "Handlebars": 75, "Pug": 51} | package com.example.plugins
import com.example.models.*
import io.ktor.server.application.*
import io.ktor.server.freemarker.*
import io.ktor.server.http.content.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import io.ktor.server.util.*
fun Application.configureRouting() {
routing {
static("/static") {
resources("files")
}
get("/") {
call.respondRedirect("articles")
}
route("articles") {
get {
call.respond(FreeMarkerContent("index.ftl", mapOf("articles" to articles)))
}
get("new") {
call.respond(FreeMarkerContent("new.ftl", model = null))
}
post {
val formParameters = call.receiveParameters()
val title = formParameters.getOrFail("title")
val body = formParameters.getOrFail("body")
val newEntry = Article.newEntry(title, body)
articles.add(newEntry)
call.respondRedirect("/articles/${newEntry.id}")
}
get("{id}") {
val id = call.parameters.getOrFail<Int>("id").toInt()
call.respond(FreeMarkerContent("show.ftl", mapOf("article" to articles.find { it.id == id })))
}
get("{id}/edit") {
val id = call.parameters.getOrFail<Int>("id").toInt()
call.respond(FreeMarkerContent("edit.ftl", mapOf("article" to articles.find { it.id == id })))
}
post("{id}") {
val id = call.parameters.getOrFail<Int>("id").toInt()
val formParameters = call.receiveParameters()
when (formParameters.getOrFail("_action")) {
"update" -> {
val index = articles.indexOf(articles.find { it.id == id })
val title = formParameters.getOrFail("title")
val body = formParameters.getOrFail("body")
articles[index].title = title
articles[index].body = body
call.respondRedirect("/articles/$id")
}
"delete" -> {
articles.removeIf { it.id == id }
call.respondRedirect("/articles")
}
}
}
}
}
}
| 13 | Kotlin | 260 | 355 | 45a6c505d6232b2f4405adc0cbcfd96135c4a2a0 | 2,468 | ktor-documentation | Apache License 2.0 |
CleanArqDemo/app/src/main/java/com/brunonavarro/cleanarqdemo/presentation/Productos/view/adapter/ProductoAdapter.kt | brunonavarro | 250,851,054 | false | null | package com.brunonavarro.cleanarqdemo.presentation.Productos.view.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.brunonavarro.cleanarqdemo.data.entidades.Productos
import com.brunonavarro.cleanarqdemo.R
class ProductoAdapter {
} | 0 | Kotlin | 0 | 1 | bcdec0448f41d8a08ceb5beb26a68600b0452bb9 | 437 | MVPKotlinClean | MIT License |
src/nl/hannahsten/texifyidea/completion/LatexXColorProvider.kt | solonovamax | 387,531,279 | true | {"Kotlin": 2099387, "TeX": 60960, "Java": 27300, "HTML": 21963, "Lex": 21837, "JavaScript": 3044, "Python": 967} | package nl.hannahsten.texifyidea.completion
import com.intellij.codeInsight.completion.CompletionParameters
import com.intellij.codeInsight.completion.CompletionProvider
import com.intellij.codeInsight.completion.CompletionResultSet
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.psi.PsiFile
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.util.ProcessingContext
import com.intellij.util.ui.ColorIcon
import nl.hannahsten.texifyidea.index.LatexCommandsIndex
import nl.hannahsten.texifyidea.gutter.LatexElementColorProvider
import nl.hannahsten.texifyidea.util.Kindness
import nl.hannahsten.texifyidea.util.files.referencedFileSet
import nl.hannahsten.texifyidea.util.getRequiredArgumentValueByName
import nl.hannahsten.texifyidea.util.isColorDefinition
import nl.hannahsten.texifyidea.util.magic.ColorMagic
import java.awt.Color
import java.util.*
import java.util.stream.Collectors
object LatexXColorProvider : CompletionProvider<CompletionParameters>() {
override fun addCompletions(parameters: CompletionParameters, context: ProcessingContext, result: CompletionResultSet) {
addDefaultColors(result)
addCustomColors(parameters, result)
}
private fun addDefaultColors(result: CompletionResultSet) {
result.addAllElements(
ColorMagic.defaultXcolors.map {
LookupElementBuilder.create(it.key)
.withIcon(ColorIcon(12, Color(it.value)))
}
)
}
private fun addCustomColors(parameters: CompletionParameters, result: CompletionResultSet) {
val project = parameters.editor.project ?: return
val file = parameters.originalFile
val files: MutableSet<PsiFile> = HashSet(file.referencedFileSet())
val searchFiles = files.stream()
.map { obj: PsiFile -> obj.virtualFile }
.collect(Collectors.toSet())
searchFiles.add(file.virtualFile)
val scope = GlobalSearchScope.filesScope(project, searchFiles)
val cmds = LatexCommandsIndex.getItems(project, scope)
for (cmd in cmds) {
if (!cmd.isColorDefinition()) {
continue
}
val colorName = cmd.getRequiredArgumentValueByName("name") ?: continue
val color = LatexElementColorProvider.findColor(colorName, file)
val lookupElement = if (color != null) {
LookupElementBuilder.create(colorName).withIcon(ColorIcon(12, color))
}
else LookupElementBuilder.create(colorName)
result.addElement(lookupElement)
}
result.addLookupAdvertisement(Kindness.getKindWords())
}
} | 0 | Kotlin | 0 | 0 | ddb3790dd4eadf482caa511bbee1039dc4367d0a | 2,697 | TeXiFy-IDEA | MIT License |
app/src/main/java/eu/kanade/tachiyomi/data/library/LibraryUpdateJob.kt | nzoba | 359,022,210 | true | {"Kotlin": 3254688} | package eu.kanade.tachiyomi.data.library
import android.content.Context
import android.content.pm.ServiceInfo
import android.os.Build
import androidx.work.Constraints
import androidx.work.CoroutineWorker
import androidx.work.Data
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.ExistingWorkPolicy
import androidx.work.ForegroundInfo
import androidx.work.NetworkType
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.PeriodicWorkRequestBuilder
import androidx.work.WorkInfo
import androidx.work.WorkManager
import androidx.work.WorkQuery
import androidx.work.WorkerParameters
import coil.Coil
import coil.request.CachePolicy
import coil.request.ImageRequest
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.cache.CoverCache
import eu.kanade.tachiyomi.data.database.DatabaseHelper
import eu.kanade.tachiyomi.data.database.models.Category
import eu.kanade.tachiyomi.data.database.models.Chapter
import eu.kanade.tachiyomi.data.database.models.LibraryManga
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.data.download.DownloadJob
import eu.kanade.tachiyomi.data.download.DownloadManager
import eu.kanade.tachiyomi.data.notification.Notifications
import eu.kanade.tachiyomi.data.preference.DEVICE_BATTERY_NOT_LOW
import eu.kanade.tachiyomi.data.preference.DEVICE_CHARGING
import eu.kanade.tachiyomi.data.preference.DEVICE_ONLY_ON_WIFI
import eu.kanade.tachiyomi.data.preference.MANGA_HAS_UNREAD
import eu.kanade.tachiyomi.data.preference.MANGA_NON_COMPLETED
import eu.kanade.tachiyomi.data.preference.MANGA_NON_READ
import eu.kanade.tachiyomi.data.preference.PreferencesHelper
import eu.kanade.tachiyomi.data.track.EnhancedTrackService
import eu.kanade.tachiyomi.data.track.TrackManager
import eu.kanade.tachiyomi.extension.ExtensionUpdateJob
import eu.kanade.tachiyomi.source.SourceManager
import eu.kanade.tachiyomi.source.UnmeteredSource
import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.source.model.UpdateStrategy
import eu.kanade.tachiyomi.source.online.HttpSource
import eu.kanade.tachiyomi.util.chapter.syncChaptersWithSource
import eu.kanade.tachiyomi.util.chapter.syncChaptersWithTrackServiceTwoWay
import eu.kanade.tachiyomi.util.manga.MangaShortcutManager
import eu.kanade.tachiyomi.util.shouldDownloadNewChapters
import eu.kanade.tachiyomi.util.storage.getUriCompat
import eu.kanade.tachiyomi.util.system.createFileInCacheDir
import eu.kanade.tachiyomi.util.system.isConnectedToWifi
import eu.kanade.tachiyomi.util.system.localeContext
import eu.kanade.tachiyomi.util.system.tryToSetForeground
import eu.kanade.tachiyomi.util.system.withIOContext
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Semaphore
import kotlinx.coroutines.sync.withPermit
import timber.log.Timber
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
import java.io.File
import java.lang.ref.WeakReference
import java.util.Date
import java.util.concurrent.CancellationException
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicInteger
class LibraryUpdateJob(private val context: Context, workerParams: WorkerParameters) :
CoroutineWorker(context, workerParams) {
private val db: DatabaseHelper = Injekt.get()
private val coverCache: CoverCache = Injekt.get()
private val sourceManager: SourceManager = Injekt.get()
private val preferences: PreferencesHelper = Injekt.get()
private val downloadManager: DownloadManager = Injekt.get()
private val trackManager: TrackManager = Injekt.get()
private val mangaShortcutManager: MangaShortcutManager = Injekt.get()
private var extraDeferredJobs = mutableListOf<Deferred<Any>>()
private val extraScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
private val emitScope = MainScope()
private val mangaToUpdate = mutableListOf<LibraryManga>()
private val mangaToUpdateMap = mutableMapOf<Long, List<LibraryManga>>()
private val categoryIds = mutableSetOf<Int>()
// List containing new updates
private val newUpdates = mutableMapOf<LibraryManga, Array<Chapter>>()
// List containing failed updates
private val failedUpdates = mutableMapOf<Manga, String?>()
// List containing skipped updates
private val skippedUpdates = mutableMapOf<Manga, String?>()
val count = AtomicInteger(0)
// Boolean to determine if user wants to automatically download new chapters.
private val downloadNew: Boolean = preferences.downloadNewChapters().get()
// Boolean to determine if DownloadManager has downloads
private var hasDownloads = false
private val requestSemaphore = Semaphore(5)
// For updates delete removed chapters if not preference is set as well
private val deleteRemoved by lazy { preferences.deleteRemovedChapters().get() != 1 }
private val notifier = LibraryUpdateNotifier(context.localeContext)
override suspend fun doWork(): Result {
if (tags.contains(WORK_NAME_AUTO)) {
val preferences = Injekt.get<PreferencesHelper>()
val restrictions = preferences.libraryUpdateDeviceRestriction().get()
if ((DEVICE_ONLY_ON_WIFI in restrictions) && !context.isConnectedToWifi()) {
return Result.failure()
}
// Find a running manual worker. If exists, try again later
if (instance != null) {
return Result.retry()
}
}
tryToSetForeground()
instance = WeakReference(this)
val target = inputData.getString(KEY_TARGET)?.let { Target.valueOf(it) } ?: Target.CHAPTERS
// If this is a chapter update, set the last update time to now
if (target == Target.CHAPTERS) {
preferences.libraryUpdateLastTimestamp().set(Date().time)
}
val savedMangasList = inputData.getLongArray(KEY_MANGAS)?.asList()?.plus(extraManga)
extraManga = emptyList()
val mangaList = (
if (savedMangasList != null) {
val mangas = db.getLibraryMangas().executeAsBlocking().filter {
it.id in savedMangasList
}.distinctBy { it.id }
val categoryId = inputData.getInt(KEY_CATEGORY, -1)
if (categoryId > -1) categoryIds.add(categoryId)
mangas
} else {
getMangaToUpdate()
}
).sortedBy { it.title }
return withIOContext {
try {
launchTarget(target, mangaList)
Result.success()
} catch (e: Exception) {
if (e is CancellationException) {
// Assume success although cancelled
finishUpdates(true)
Result.success()
} else {
Timber.e(e)
Result.failure()
}
} finally {
instance = null
sendUpdate(null)
notifier.cancelProgressNotification()
}
}
}
private suspend fun launchTarget(target: Target, mangaToAdd: List<LibraryManga>) {
if (target == Target.CHAPTERS) {
sendUpdate(STARTING_UPDATE_SOURCE)
}
when (target) {
Target.CHAPTERS -> updateChaptersJob(filterMangaToUpdate(mangaToAdd))
Target.DETAILS -> updateDetails(mangaToAdd)
else -> updateTrackings(mangaToAdd)
}
}
private suspend fun sendUpdate(mangaId: Long?) {
if (isStopped) {
updateMutableFlow.tryEmit(mangaId)
} else {
emitScope.launch { updateMutableFlow.emit(mangaId) }
}
}
private suspend fun updateChaptersJob(mangaToAdd: List<LibraryManga>) {
// Initialize the variables holding the progress of the updates.
mangaToUpdate.addAll(mangaToAdd)
mangaToUpdateMap.putAll(mangaToAdd.groupBy { it.source })
checkIfMassiveUpdate()
coroutineScope {
val list = mangaToUpdateMap.keys.map { source ->
async {
try {
requestSemaphore.withPermit { updateMangaInSource(source) }
} catch (e: Exception) {
Timber.e(e)
false
}
}
}
val results = list.awaitAll()
if (!hasDownloads) {
hasDownloads = results.any { it }
}
finishUpdates()
}
}
/**
* Method that updates the details of the given list of manga. It's called in a background
* thread, so it's safe to do heavy operations or network calls here.
*
* @param mangaToUpdate the list to update
*/
private suspend fun updateDetails(mangaToUpdate: List<LibraryManga>) = coroutineScope {
// Initialize the variables holding the progress of the updates.
val count = AtomicInteger(0)
val asyncList = mangaToUpdate.groupBy { it.source }.values.map { list ->
async {
requestSemaphore.withPermit {
list.forEach { manga ->
ensureActive()
val source = sourceManager.get(manga.source) as? HttpSource ?: return@async
notifier.showProgressNotification(
manga,
count.andIncrement,
mangaToUpdate.size,
)
ensureActive()
val networkManga = try {
source.getMangaDetails(manga.copy())
} catch (e: java.lang.Exception) {
Timber.e(e)
null
}
if (networkManga != null) {
val thumbnailUrl = manga.thumbnail_url
manga.copyFrom(networkManga)
manga.initialized = true
if (thumbnailUrl != manga.thumbnail_url) {
coverCache.deleteFromCache(thumbnailUrl)
// load new covers in background
val request =
ImageRequest.Builder(context).data(manga)
.memoryCachePolicy(CachePolicy.DISABLED).build()
Coil.imageLoader(context).execute(request)
} else {
val request =
ImageRequest.Builder(context).data(manga)
.memoryCachePolicy(CachePolicy.DISABLED)
.diskCachePolicy(CachePolicy.WRITE_ONLY)
.build()
Coil.imageLoader(context).execute(request)
}
db.insertManga(manga).executeAsBlocking()
}
}
}
}
}
asyncList.awaitAll()
notifier.cancelProgressNotification()
}
/**
* Method that updates the metadata of the connected tracking services. It's called in a
* background thread, so it's safe to do heavy operations or network calls here.
*/
private suspend fun updateTrackings(mangaToUpdate: List<LibraryManga>) {
// Initialize the variables holding the progress of the updates.
var count = 0
val loggedServices = trackManager.services.filter { it.isLogged }
mangaToUpdate.forEach { manga ->
notifier.showProgressNotification(manga, count++, mangaToUpdate.size)
val tracks = db.getTracks(manga).executeAsBlocking()
tracks.forEach { track ->
val service = trackManager.getService(track.sync_id)
if (service != null && service in loggedServices) {
try {
val newTrack = service.refresh(track)
db.insertTrack(newTrack).executeAsBlocking()
if (service is EnhancedTrackService) {
syncChaptersWithTrackServiceTwoWay(db, db.getChapters(manga).executeAsBlocking(), track, service)
}
} catch (e: Exception) {
Timber.e(e)
}
}
}
}
notifier.cancelProgressNotification()
}
private suspend fun finishUpdates(wasStopped: Boolean = false) {
if (!wasStopped && !isStopped) {
extraDeferredJobs.awaitAll()
}
if (newUpdates.isNotEmpty()) {
notifier.showResultNotification(newUpdates)
if (!wasStopped && preferences.refreshCoversToo().get() && !isStopped) {
updateDetails(newUpdates.keys.toList())
notifier.cancelProgressNotification()
if (downloadNew && hasDownloads) {
DownloadJob.start(context, runExtensionUpdatesAfter)
runExtensionUpdatesAfter = false
}
} else if (downloadNew && hasDownloads) {
DownloadJob.start(applicationContext, runExtensionUpdatesAfter)
runExtensionUpdatesAfter = false
}
}
newUpdates.clear()
if (skippedUpdates.isNotEmpty() && Notifications.isNotificationChannelEnabled(context, Notifications.CHANNEL_LIBRARY_SKIPPED)) {
val skippedFile = writeErrorFile(
skippedUpdates,
"skipped",
context.getString(R.string.learn_why) + " - " + LibraryUpdateNotifier.HELP_SKIPPED_URL,
).getUriCompat(context)
notifier.showUpdateSkippedNotification(skippedUpdates.map { it.key.title }, skippedFile)
}
if (failedUpdates.isNotEmpty() && Notifications.isNotificationChannelEnabled(context, Notifications.CHANNEL_LIBRARY_ERROR)) {
val errorFile = writeErrorFile(failedUpdates).getUriCompat(context)
notifier.showUpdateErrorNotification(failedUpdates.map { it.key.title }, errorFile)
}
mangaShortcutManager.updateShortcuts(context)
failedUpdates.clear()
notifier.cancelProgressNotification()
if (runExtensionUpdatesAfter && !DownloadJob.isRunning(context)) {
ExtensionUpdateJob.runJobAgain(context, NetworkType.CONNECTED)
runExtensionUpdatesAfter = false
}
}
private fun checkIfMassiveUpdate() {
val largestSourceSize = mangaToUpdate
.groupBy { it.source }
.filterKeys { sourceManager.get(it) !is UnmeteredSource }
.maxOfOrNull { it.value.size } ?: 0
if (largestSourceSize > MANGA_PER_SOURCE_QUEUE_WARNING_THRESHOLD) {
notifier.showQueueSizeWarningNotification()
}
}
private suspend fun updateMangaInSource(source: Long): Boolean {
if (mangaToUpdateMap[source] == null) return false
var count = 0
var hasDownloads = false
val httpSource = sourceManager.get(source) as? HttpSource ?: return false
while (count < mangaToUpdateMap[source]!!.size) {
val manga = mangaToUpdateMap[source]!![count]
val shouldDownload = manga.shouldDownloadNewChapters(db, preferences)
if (updateMangaChapters(manga, this.count.andIncrement, httpSource, shouldDownload)) {
hasDownloads = true
}
count++
}
mangaToUpdateMap[source] = emptyList()
return hasDownloads
}
private suspend fun updateMangaChapters(
manga: LibraryManga,
progress: Int,
source: HttpSource,
shouldDownload: Boolean,
): Boolean = coroutineScope {
try {
var hasDownloads = false
ensureActive()
notifier.showProgressNotification(manga, progress, mangaToUpdate.size)
val fetchedChapters = source.getChapterList(manga)
if (fetchedChapters.isNotEmpty()) {
val newChapters = syncChaptersWithSource(db, fetchedChapters, manga, source)
if (newChapters.first.isNotEmpty()) {
if (shouldDownload) {
downloadChapters(
manga,
newChapters.first.sortedBy { it.chapter_number },
)
hasDownloads = true
}
newUpdates[manga] =
newChapters.first.sortedBy { it.chapter_number }.toTypedArray()
}
if (deleteRemoved && newChapters.second.isNotEmpty()) {
val removedChapters = newChapters.second.filter {
downloadManager.isChapterDownloaded(it, manga) &&
newChapters.first.none { newChapter ->
newChapter.chapter_number == it.chapter_number && it.scanlator.isNullOrBlank()
}
}
if (removedChapters.isNotEmpty()) {
downloadManager.deleteChapters(removedChapters, manga, source)
}
}
if (newChapters.first.size + newChapters.second.size > 0) {
sendUpdate(manga.id)
}
}
return@coroutineScope hasDownloads
} catch (e: Exception) {
if (e !is CancellationException) {
failedUpdates[manga] = e.message
Timber.e("Failed updating: ${manga.title}: $e")
}
return@coroutineScope false
}
}
private fun downloadChapters(manga: Manga, chapters: List<Chapter>) {
// We don't want to start downloading while the library is updating, because websites
// may don't like it and they could ban the user.
downloadManager.downloadChapters(manga, chapters, false)
}
private fun filterMangaToUpdate(mangaToAdd: List<LibraryManga>): List<LibraryManga> {
val restrictions = preferences.libraryUpdateMangaRestriction().get()
return mangaToAdd.filter { manga ->
when {
MANGA_NON_COMPLETED in restrictions && manga.status == SManga.COMPLETED -> {
skippedUpdates[manga] = context.getString(R.string.skipped_reason_completed)
}
MANGA_HAS_UNREAD in restrictions && manga.unread != 0 -> {
skippedUpdates[manga] = context.getString(R.string.skipped_reason_not_caught_up)
}
MANGA_NON_READ in restrictions && manga.totalChapters > 0 && !manga.hasRead -> {
skippedUpdates[manga] = context.getString(R.string.skipped_reason_not_started)
}
manga.update_strategy != UpdateStrategy.ALWAYS_UPDATE -> {
skippedUpdates[manga] = context.getString(R.string.skipped_reason_not_always_update)
}
else -> {
return@filter true
}
}
return@filter false
}
}
private fun getMangaToUpdate(): List<LibraryManga> {
val categoryId = inputData.getInt(KEY_CATEGORY, -1)
return getMangaToUpdate(categoryId)
}
/**
* Returns the list of manga to be updated.
*
* @param categoryId the category to update
* @return a list of manga to update
*/
private fun getMangaToUpdate(categoryId: Int): List<LibraryManga> {
val libraryManga = db.getLibraryMangas().executeAsBlocking()
val listToUpdate = if (categoryId != -1) {
categoryIds.add(categoryId)
libraryManga.filter { it.category == categoryId }
} else {
val categoriesToUpdate =
preferences.libraryUpdateCategories().get().map(String::toInt)
if (categoriesToUpdate.isNotEmpty()) {
categoryIds.addAll(categoriesToUpdate)
libraryManga.filter { it.category in categoriesToUpdate }.distinctBy { it.id }
} else {
categoryIds.addAll(db.getCategories().executeAsBlocking().mapNotNull { it.id } + 0)
libraryManga.distinctBy { it.id }
}
}
val categoriesToExclude =
preferences.libraryUpdateCategoriesExclude().get().map(String::toInt)
val listToExclude = if (categoriesToExclude.isNotEmpty() && categoryId == -1) {
libraryManga.filter { it.category in categoriesToExclude }.toSet()
} else {
emptySet()
}
return listToUpdate.minus(listToExclude)
}
override suspend fun getForegroundInfo(): ForegroundInfo {
val notification = notifier.progressNotificationBuilder.build()
val id = Notifications.ID_LIBRARY_PROGRESS
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
ForegroundInfo(id, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC)
} else {
ForegroundInfo(id, notification)
}
}
/**
* Writes basic file of update errors to cache dir.
*/
private fun writeErrorFile(errors: Map<Manga, String?>, fileName: String = "errors", additionalInfo: String? = null): File {
try {
if (errors.isNotEmpty()) {
val file = context.createFileInCacheDir("tachiyomi_update_$fileName.txt")
file.bufferedWriter().use { out ->
additionalInfo?.let { out.write("$it\n\n") }
// Error file format:
// ! Error
// # Source
// - Manga
errors.toList().groupBy({ it.second }, { it.first }).forEach { (error, mangas) ->
out.write("! ${error}\n")
mangas.groupBy { it.source }.forEach { (srcId, mangas) ->
val source = sourceManager.getOrStub(srcId)
out.write(" # $source\n")
mangas.forEach {
out.write(" - ${it.title}\n")
}
}
}
}
return file
}
} catch (e: Exception) {
// Empty
}
return File("")
}
private fun addMangaToQueue(categoryId: Int, manga: List<LibraryManga>) {
val mangas = filterMangaToUpdate(manga).sortedBy { it.title }
categoryIds.add(categoryId)
addManga(mangas)
}
private fun addCategory(categoryId: Int) {
val mangas = filterMangaToUpdate(getMangaToUpdate(categoryId)).sortedBy { it.title }
categoryIds.add(categoryId)
addManga(mangas)
}
private fun addManga(mangaToAdd: List<LibraryManga>) {
val distinctManga = mangaToAdd.filter { it !in mangaToUpdate }
mangaToUpdate.addAll(distinctManga)
checkIfMassiveUpdate()
distinctManga.groupBy { it.source }.forEach {
// if added queue items is a new source not in the async list or an async list has
// finished running
if (mangaToUpdateMap[it.key].isNullOrEmpty()) {
mangaToUpdateMap[it.key] = it.value
extraScope.launch {
extraDeferredJobs.add(
async(Dispatchers.IO) {
val hasDLs = try {
requestSemaphore.withPermit { updateMangaInSource(it.key) }
} catch (e: Exception) {
false
}
if (!hasDownloads) {
hasDownloads = hasDLs
}
},
)
}
} else {
val list = mangaToUpdateMap[it.key] ?: emptyList()
mangaToUpdateMap[it.key] = (list + it.value)
}
}
}
enum class Target {
CHAPTERS, // Manga chapters
DETAILS, // Manga metadata
TRACKING, // Tracking metadata
}
companion object {
private const val TAG = "LibraryUpdate"
private const val WORK_NAME_AUTO = "LibraryUpdate-auto"
private const val WORK_NAME_MANUAL = "LibraryUpdate-manual"
private const val ERROR_LOG_HELP_URL = "https://tachiyomi.org/help/guides/troubleshooting"
private const val MANGA_PER_SOURCE_QUEUE_WARNING_THRESHOLD = 60
/**
* Key for category to update.
*/
private const val KEY_CATEGORY = "category"
const val STARTING_UPDATE_SOURCE = -5L
/**
* Key that defines what should be updated.
*/
private const val KEY_TARGET = "target"
private const val KEY_MANGAS = "mangas"
private var instance: WeakReference<LibraryUpdateJob>? = null
private var extraManga = emptyList<Long>()
val updateMutableFlow = MutableSharedFlow<Long?>(
extraBufferCapacity = 10,
onBufferOverflow = BufferOverflow.DROP_OLDEST,
)
val updateFlow = updateMutableFlow.asSharedFlow()
private var runExtensionUpdatesAfter = false
fun runExtensionUpdatesAfterJob() { runExtensionUpdatesAfter = true }
fun setupTask(context: Context, prefInterval: Int? = null) {
val preferences = Injekt.get<PreferencesHelper>()
val interval = prefInterval ?: preferences.libraryUpdateInterval().get()
if (interval > 0) {
val restrictions = preferences.libraryUpdateDeviceRestriction().get()
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.setRequiresCharging(DEVICE_CHARGING in restrictions)
.setRequiresBatteryNotLow(DEVICE_BATTERY_NOT_LOW in restrictions)
.build()
val request = PeriodicWorkRequestBuilder<LibraryUpdateJob>(
interval.toLong(),
TimeUnit.HOURS,
10,
TimeUnit.MINUTES,
)
.addTag(TAG)
.addTag(WORK_NAME_AUTO)
.setConstraints(constraints)
.build()
WorkManager.getInstance(context).enqueueUniquePeriodicWork(
WORK_NAME_AUTO,
ExistingPeriodicWorkPolicy.CANCEL_AND_REENQUEUE,
request,
)
} else {
WorkManager.getInstance(context).cancelAllWorkByTag(WORK_NAME_AUTO)
}
}
fun cancelAllWorks(context: Context) {
WorkManager.getInstance(context).cancelAllWorkByTag(TAG)
}
fun isRunning(context: Context): Boolean {
val list = WorkManager.getInstance(context).getWorkInfosByTag(TAG).get()
return list.any { it.state == WorkInfo.State.RUNNING }
}
fun categoryInQueue(id: Int?) = instance?.get()?.categoryIds?.contains(id) ?: false
fun startNow(
context: Context,
category: Category? = null,
target: Target = Target.CHAPTERS,
mangaToUse: List<LibraryManga>? = null,
): Boolean {
if (isRunning(context)) {
if (target == Target.CHAPTERS) {
category?.id?.let {
if (mangaToUse != null) {
instance?.get()?.addMangaToQueue(it, mangaToUse)
} else {
instance?.get()?.addCategory(it)
}
}
}
// Already running either as a scheduled or manual job
return false
}
val builder = Data.Builder()
builder.putString(KEY_TARGET, target.name)
category?.id?.let { id ->
builder.putInt(KEY_CATEGORY, id)
if (mangaToUse != null) {
builder.putLongArray(
KEY_MANGAS,
mangaToUse.firstOrNull()?.id?.let { longArrayOf(it) } ?: longArrayOf(),
)
extraManga = mangaToUse.subList(1, mangaToUse.size).mapNotNull { it.id }
}
}
val inputData = builder.build()
val request = OneTimeWorkRequestBuilder<LibraryUpdateJob>()
.addTag(TAG)
.addTag(WORK_NAME_MANUAL)
.setInputData(inputData)
.build()
WorkManager.getInstance(context)
.enqueueUniqueWork(WORK_NAME_MANUAL, ExistingWorkPolicy.KEEP, request)
return true
}
fun stop(context: Context) {
val wm = WorkManager.getInstance(context)
val workQuery = WorkQuery.Builder.fromTags(listOf(TAG))
.addStates(listOf(WorkInfo.State.RUNNING))
.build()
wm.getWorkInfos(workQuery).get()
// Should only return one work but just in case
.forEach {
wm.cancelWorkById(it.id)
// Re-enqueue cancelled scheduled work
if (it.tags.contains(WORK_NAME_AUTO)) {
setupTask(context)
}
}
}
}
}
| 0 | Kotlin | 1 | 1 | 8946395f78d22e44471497d3b76de661e9b4166e | 30,440 | tachiyomiJ2K | Apache License 2.0 |
core/src/main/java/at/shockbytes/dante/core/network/google/GoogleBooksDownloader.kt | shockbytes | 92,944,830 | false | {"Kotlin": 790879} | package at.shockbytes.dante.core.network.google
import at.shockbytes.dante.core.book.BookSuggestion
import at.shockbytes.dante.core.network.BookDownloader
import at.shockbytes.dante.util.scheduler.SchedulerFacade
import io.reactivex.Observable
/**
* Author: <NAME>
* Date: 13.02.2017
*/
class GoogleBooksDownloader(
private val api: GoogleBooksApi,
private val schedulerFacade: SchedulerFacade
) : BookDownloader {
override fun downloadBook(isbn: String): Observable<BookSuggestion> {
return api
.downloadBookSuggestion(isbn)
.observeOn(schedulerFacade.ui)
.subscribeOn(schedulerFacade.io)
}
}
| 21 | Kotlin | 7 | 73 | 8b5b1043adac8360226628fac4114203605c1965 | 674 | Dante | Apache License 2.0 |
features/feature_search_photo_shared/src/commonMain/kotlin/com/hoc081098/compose_multiplatform_kmpviewmodel_sample/search_photo/presentation/SearchPhotoScreen.kt | hoc081098 | 675,918,221 | false | {"Kotlin": 125046, "Shell": 228} | package com.hoc081098.compose_multiplatform_kmpviewmodel_sample.search_photo.presentation
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.consumeWindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyGridState
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.lazy.grid.rememberLazyGridState
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.hoc081098.compose_multiplatform_kmpviewmodel_sample.common_ui.components.EmptyView
import com.hoc081098.compose_multiplatform_kmpviewmodel_sample.common_ui.components.ErrorMessageAndRetryButton
import com.hoc081098.compose_multiplatform_kmpviewmodel_sample.common_ui.components.LoadingIndicator
import com.hoc081098.compose_multiplatform_kmpviewmodel_sample.coroutines_utils.AppCoroutineDispatchers
import com.hoc081098.compose_multiplatform_kmpviewmodel_sample.search_photo.domain.SearchPhotoError
import com.hoc081098.compose_multiplatform_kmpviewmodel_sample.search_photo.presentation.SearchPhotoUiState.PhotoUiItem
import com.hoc081098.compose_multiplatform_kmpviewmodel_sample.search_photo.presentation.components.PhotoGridCell
import com.hoc081098.kmp.viewmodel.koin.compose.koinKmpViewModel
import com.hoc081098.solivagant.lifecycle.compose.collectAsStateWithLifecycle
import org.koin.compose.koinInject
@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class)
@Composable
internal fun SearchPhotoScreen(
modifier: Modifier = Modifier,
viewModel: SearchPhotoViewModel = koinKmpViewModel(),
appCoroutineDispatchers: AppCoroutineDispatchers = koinInject(),
) {
val state by viewModel.stateFlow.collectAsStateWithLifecycle()
val searchTerm by viewModel
.searchTermStateFlow
.collectAsStateWithLifecycle(context = appCoroutineDispatchers.immediateMain)
Scaffold(
modifier = modifier
.fillMaxSize(),
topBar = {
CenterAlignedTopAppBar(
title = { Text(text = "Unsplash") },
)
},
) { padding ->
Column(
modifier = Modifier
.padding(padding)
.consumeWindowInsets(padding),
) {
Spacer(modifier = Modifier.height(16.dp))
TextField(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp),
value = searchTerm,
onValueChange = remember(viewModel) { viewModel::search },
label = { Text(text = "Search term") },
)
Spacer(modifier = Modifier.height(8.dp))
Text(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp),
text = "Submitted term: ${state.submittedTerm.orEmpty()}",
)
Spacer(modifier = Modifier.height(16.dp))
Box(
modifier = Modifier
.fillMaxWidth()
.weight(1f),
contentAlignment = Alignment.Center,
) {
ListContent(
modifier = Modifier.matchParentSize(),
state = state,
onItemClick = remember(viewModel) { viewModel::navigateToPhotoDetail },
)
}
}
}
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun ListContent(
state: SearchPhotoUiState,
onItemClick: (PhotoUiItem) -> Unit,
modifier: Modifier = Modifier,
lazyGridState: LazyGridState = rememberLazyGridState(),
) {
if (state.isLoading) {
LoadingIndicator(
modifier = modifier,
)
return
}
state.error?.let { error ->
ErrorMessageAndRetryButton(
modifier = modifier,
onRetry = { },
errorMessage = when (error) {
SearchPhotoError.NetworkError -> "Network error"
SearchPhotoError.ServerError -> "Server error"
SearchPhotoError.TimeoutError -> "Timeout error"
SearchPhotoError.Unexpected -> "Unexpected error"
},
)
return
}
if (state.photoUiItems.isEmpty()) {
EmptyView(
modifier = modifier,
)
} else {
LazyVerticalGrid(
modifier = modifier,
columns = GridCells.Adaptive(minSize = 128.dp),
state = lazyGridState,
verticalArrangement = Arrangement.spacedBy(16.dp),
horizontalArrangement = Arrangement.spacedBy(16.dp),
contentPadding = PaddingValues(16.dp),
) {
items(
items = state.photoUiItems,
key = { it.id },
) {
PhotoGridCell(
modifier = Modifier
.animateItemPlacement()
.fillMaxWidth()
.aspectRatio(1f),
photo = it,
onClick = { onItemClick(it) },
)
}
}
}
}
| 7 | Kotlin | 4 | 13 | 2fb2895130077ae79e4df28fad81f6886db9e157 | 5,658 | Compose-Multiplatform-KmpViewModel-Unsplash-Sample | Apache License 2.0 |
shared/src/commonMain/kotlin/com/keller/yourpet/shared/database/DatabaseDriverFactory.kt | RafaO | 336,518,775 | false | {"Kotlin": 76795, "Swift": 27080} | package com.keller.yourpet.shared.database
import com.squareup.sqldelight.db.SqlDriver
expect class DatabaseDriverFactory {
fun createDriver(): SqlDriver
}
| 0 | Kotlin | 0 | 1 | 4f2a90dcb7023ee875c1ca3fe4d588d16fae34f6 | 162 | yourpet | MIT License |
src/main/kotlin/sid/applications/tutorial/miscallaneous/LazyInitializationLateInit.kt | sidcool1234 | 277,104,284 | false | null | package sid.applications.tutorial.miscallaneous
import sid.applications.tutorial.models.ComplexNumber
import java.io.File
import java.util.*
val initValue: Double by lazy { expensiveOperation("initValue") }
fun lateInit(){ // avoids nullable types
lateinit var lateComer: ComplexNumber
expensiveOperation()
// println(lateComer) // compiler error
lateComer = ComplexNumber(expensiveOperation("lateComer"), expensiveOperation("lateComer"))
println(lateComer)
lateComer = ComplexNumber(expensiveOperation(), expensiveOperation()) // duplicate intialization possible®
println(lateComer)
}
fun lazyInit(){
val lazyInit: Double by lazy { expensiveOperation("lazyInit") } // function scoped method, hence values not persisted across method calls
val secondLazy: String by lazy { lazyInit.plus(11).toString() }
println("An Inexpensive operation") // executes inline since eager evaluation
// Methods not called till variables are used here
if(lazyInit > 13) {
println(secondLazy) // It also initializes `lazyInt` because of the dependency
println(lazyInit)
}
}
fun expensiveOperation(identifier: String = "Default"): Double {
println("expensive operation starts for $identifier")
Thread.sleep(1000)
println("expensive operation stops for $identifier")
return Math.random() * 25
}
fun lateInitializations(){ // Measuring memory usage
val lazyString: List<String> by lazy { readFileAsLinesUsingUseLines("/usr/local/Cellar/ansible/2.9.10/libexec/lib/python3.8/site-packages/netaddr/eui/oui.txt") }
val init = Runtime.getRuntime().freeMemory()
lazyString[12]
lazyString[12]
val last = Runtime.getRuntime().freeMemory()
println("${(init - last)/ 1e+6} Mb")
}
fun readFileAsLinesUsingUseLines(fileName: String): List<String> = File(fileName).useLines { it.toList() } + File(fileName).useLines { it.toList() } + File(fileName).useLines { it.toList() }
fun main(){
// lazyInit()
// lateInit()
lateInitializations()
}
| 0 | Kotlin | 0 | 1 | bd9a15f65872338b5ff732aecd8c1223b026abf2 | 2,038 | OfCourse_I_StillLoveYou | The Unlicense |
service/src/test/kotlin/shoppingCart/domain/AmountTest.kt | DarkToast | 129,854,688 | false | null | package shoppingCart.domain
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertDoesNotThrow
import org.junit.jupiter.api.assertThrows
/*
* Aufgabe 3:
* Entfernen Sie bitte die @Disabled annotation von der hier drunter liegenden Klasse und implementieren Sie in der Datei
* `shoppingCart/domain/Money.kt` die Klasse Amount und ihre Methoden.
*
* Das Ziel ist, eine Kotlinklasse mit Vor- und Nachbedingungen zu implementieren, welche auch ändernde Methoden
* enthält. Folgende Anforderungen sollen umgesetzt sein:
*
* - Ein Amount kann 0 sein
* - Ein Amount kann nicht negativ sein
* - Ein Amount kann nicht größer als 300,00€ sein. -> MaximumShoppingCardAmountExceededException
* - Ein Amount muss seinen Wert in Cents ausdrücken können
* - Zwei Amounts können über `plus` addiert werden.
*/
class AmountTest() {
@Test
fun `can be zero`() {
assertDoesNotThrow { Amount(0, 0) }
}
@Test
fun `can be 300,00 €`() {
assertDoesNotThrow { Amount(300, 0) }
}
@Test
fun `are equals`() {
assertTrue(Amount(300, 0) == Amount(300, 0))
}
@Test
fun `can be 0,01 €`() {
assertDoesNotThrow { Amount(0, 1) }
}
@Test
fun `has a value in cent`() {
assertEquals(1011, Amount(10, 11).valueInCent)
}
@Test
fun `can not be negative`() {
assertThrows<IllegalArgumentException> { Amount(10, -1) }
assertThrows<IllegalArgumentException> { Amount(-1, 10) }
assertThrows<IllegalArgumentException> { Amount(-1, -1) }
}
@Test
fun `Cent can not exceed 99 cents`() {
assertThrows<IllegalArgumentException> { Amount(10, 100) }
}
@Test
fun `A amounts can not exceed 300,00`() {
assertThrows<MaximumShoppingCardAmountExceededException> { Amount(300, 1) }
}
@Test
fun `two amounts can not exceed 300,00 €`() {
assertThrows<MaximumShoppingCardAmountExceededException> { Amount(150, 0).plus(Amount(150, 1)) }
}
@Test
fun `an amount can be added to another`() {
assertEquals(1388, Amount(10, 99).plus(Amount(2, 89)).valueInCent)
assertEquals(198, Amount(0, 99).plus(Amount(0, 99)).valueInCent)
assertEquals(11200, Amount(111, 59).plus(Amount(0, 41)).valueInCent)
}
@Test
fun `a zero amount added to another does not have any effect`() {
assertEquals(1099, Amount(10, 99).plus(Amount(0, 0)).valueInCent)
}
}
| 0 | Kotlin | 2 | 2 | 727bdb071dd9ca7504fb0a084fc2b726706f4052 | 2,581 | kotlin-workshop | MIT License |
app/src/androidTest/java/com/example/movilmisodreamteam2022/testListarColeccionistas.kt | jsanchezl12 | 673,161,589 | false | null | package com.example.movilmisodreamteam2022
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import androidx.test.internal.runner.junit4.statement.UiThreadStatement.runOnUiThread
import androidx.test.rule.ActivityTestRule
import com.example.movilmisodreamteam2022.ui.MainActivity
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@LargeTest
@RunWith(AndroidJUnit4::class)
class testListarColeccionistas {
@get:Rule
val activityRuleMain = ActivityTestRule(MainActivity::class.java)
@Test
fun testListarColeccionistas() {
Thread.sleep(3000)
onView(withId(R.id.button_coleccionista_m)).perform(click())
Thread.sleep(3000)
onView(withId(R.id.coleccionistasRv)).check(matches(isDisplayed()));
onView(withId(R.id.coleccionistasRv))
val recyclerView =
activityRuleMain.activity.findViewById<RecyclerView>(R.id.coleccionistasRv)
val itemCount = recyclerView.adapter?.itemCount
Thread.sleep(3000)
check(itemCount!! > 0)
runOnUiThread {
// Stuff that updates the UI
val item1_view = recyclerView.findViewHolderForAdapterPosition(1)?.itemView
val it1_Titulo = item1_view?.findViewById<TextView>(R.id.tv_collec_title)
//val it1_Desc = item1_view?.findViewById<TextView>(R.id.tv_collec_desc)
//val it1_Tel = item1_view?.findViewById<TextView>(R.id.tv_collec_phone)
check(!it1_Titulo?.text.isNullOrEmpty())
//check(!it1_Desc?.text.isNullOrEmpty())
//check(!it1_Tel?.text.isNullOrEmpty())
recyclerView.findViewHolderForAdapterPosition(1)?.itemView?.performClick()
}
Thread.sleep(5000)
}
} | 0 | Kotlin | 0 | 0 | a0774afbcd9038b154fd99105fe1b47ff4e2c5d4 | 2,080 | desarrollo_movil_miso | MIT License |
src/main/kotlin/com/asbeaulieu/scopeFunctions/ExploreScopeFunctions.kt | as-beaulieu | 503,905,874 | false | {"Kotlin": 22363} | package com.asbeaulieu.scopeFunctions
import com.asbeaulieu.classes.Course
import com.asbeaulieu.classes.CourseCategory
fun main() {
exploreApply()
exploreAlso()
exploreLet()
exploreWith()
exploreRun()
}
fun exploreRun() {
var numbers: MutableList<Int>? = null
val result = numbers.run {
numbers = mutableListOf(1, 2, 3, 4, 5)
numbers?.sum()
}
println("result is $result")
val resultLength = run {
val name = "bob"
println(name)
name.length
}
println("run length is $resultLength")
}
fun exploreWith() {
val numbers = mutableListOf(1, 2, 3, 4, 5)
val result = with(numbers) {
println("size is $size") //remember with this, don't have to call it to use the .size function on it
val list = plus(4)
list.sum()
}
println("result is $result")
}
fun exploreLet() {
val numbers = mutableListOf(1, 2, 3, 4, 5)
val result = numbers.map {
it * 2
}.filter {
it > 5
}.let {
println(it)
it.sum()
}
println(result)
var name: String? = null
var result1 = name?.let {
println(it)
it.uppercase()
}
println(result1)
}
fun exploreAlso() {
val course = Course(
id = 6,
name = "Introduction to scoping functions",
author = "bob"
).also {
it.courseCategory = CourseCategory.DESIGN //Have to explicitly call it
println("course: $it") //But also is encouraged for additional effects, such as calling the print inside
}
}
fun exploreApply() {
val course = Course(
id = 6,
name = "Introduction to scoping functions",
author = "bob"
).apply {
courseCategory = CourseCategory.DESIGN
}.also {
println("course: $it")
}
}
| 0 | Kotlin | 0 | 0 | 3cfaf3288ebf985999d183e409b33215d9a7af96 | 1,827 | KotlinSpringToolbox | Apache License 2.0 |
mobile_app1/module994/src/main/java/module994packageKt0/Foo120.kt | uber-common | 294,831,672 | false | null | package module994packageKt0;
annotation class Foo120Fancy
@Foo120Fancy
class Foo120 {
fun foo0(){
module994packageKt0.Foo119().foo3()
}
fun foo1(){
foo0()
}
fun foo2(){
foo1()
}
fun foo3(){
foo2()
}
} | 6 | Java | 6 | 72 | 9cc83148c1ca37d0f2b2fcb08c71ac04b3749e5e | 237 | android-build-eval | Apache License 2.0 |
python/src/com/jetbrains/python/sdk/add/PyAddSdkPanel.kt | hieuprogrammer | 284,920,751 | true | null | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.python.sdk.add
import com.intellij.CommonBundle
import com.intellij.openapi.application.AppUIExecutor
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.module.Module
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.ui.TextFieldWithBrowseButton
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.openapi.util.UserDataHolder
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.text.StringUtil
import com.jetbrains.python.PyBundle
import com.jetbrains.python.newProject.steps.PyAddNewEnvironmentPanel
import com.jetbrains.python.sdk.*
import com.jetbrains.python.sdk.add.PyAddSdkDialogFlowAction.OK
import icons.PythonIcons
import java.awt.Component
import java.io.File
import javax.swing.Icon
import javax.swing.JComponent
import javax.swing.JPanel
/**
* @author vlan
*/
abstract class PyAddSdkPanel : JPanel(), PyAddSdkView {
override val actions: Map<PyAddSdkDialogFlowAction, Boolean>
get() = mapOf(OK.enabled())
override val component: Component
get() = this
/**
* [component] is permanent. [PyAddSdkStateListener.onComponentChanged] won't
* be called anyway.
*/
override fun addStateListener(stateListener: PyAddSdkStateListener): Unit = Unit
override fun previous(): Nothing = throw UnsupportedOperationException()
override fun next(): Nothing = throw UnsupportedOperationException()
override fun complete(): Unit = Unit
abstract override val panelName: String
override val icon: Icon = PythonIcons.Python.Python
open val sdk: Sdk? = null
open val nameExtensionComponent: JComponent? = null
open var newProjectPath: String? = null
override fun getOrCreateSdk(): Sdk? = sdk
override fun onSelected(): Unit = Unit
override fun validateAll(): List<ValidationInfo> = emptyList()
open fun addChangeListener(listener: Runnable) {}
companion object {
@JvmStatic
protected fun validateEnvironmentDirectoryLocation(field: TextFieldWithBrowseButton): ValidationInfo? {
val text = field.text
val file = File(text)
val message = when {
StringUtil.isEmptyOrSpaces(text) -> "Environment location field is empty"
file.exists() && !file.isDirectory -> "Environment location field path is not a directory"
file.isNotEmptyDirectory -> "Environment location directory is not empty"
else -> return null
}
return ValidationInfo(message, field)
}
@JvmStatic
protected fun validateSdkComboBox(field: PySdkPathChoosingComboBox, view: PyAddSdkView): ValidationInfo? {
return when (val sdk = field.selectedSdk) {
null -> ValidationInfo(PyBundle.message("python.sdk.interpreter.field.is.empty"), field)
is PySdkToInstall -> {
val message = sdk.getInstallationWarning(getDefaultButtonName(view))
ValidationInfo(message).asWarning().withOKEnabled()
}
else -> null
}
}
private fun getDefaultButtonName(view: PyAddSdkView): String {
return if (view.component.parent?.parent is PyAddNewEnvironmentPanel) {
"Create" // ProjectSettingsStepBase.createActionButton
}
else {
CommonBundle.getOkButtonText() // DialogWrapper.createDefaultActions
}
}
}
}
/**
* Obtains a list of sdk on a pool using [sdkObtainer], then fills [sdkComboBox] on the EDT.
*/
fun addInterpretersAsync(sdkComboBox: PySdkPathChoosingComboBox, sdkObtainer: () -> List<Sdk>) {
addInterpretersAsync(sdkComboBox, sdkObtainer, {})
}
/**
* Obtains a list of sdk on a pool using [sdkObtainer], then fills [sdkComboBox] and calls [onAdded] on the EDT.
*/
fun addInterpretersAsync(sdkComboBox: PySdkPathChoosingComboBox,
sdkObtainer: () -> List<Sdk>,
onAdded: () -> Unit) {
ApplicationManager.getApplication().executeOnPooledThread {
val executor = AppUIExecutor.onUiThread(ModalityState.any())
executor.execute { sdkComboBox.setBusy(true) }
var sdks = emptyList<Sdk>()
try {
sdks = sdkObtainer()
}
finally {
executor.execute {
sdkComboBox.setBusy(false)
sdks.forEach(sdkComboBox.childComponent::addItem)
onAdded()
}
}
}
}
/**
* Obtains a list of sdk to be used as a base for a virtual environment on a pool,
* then fills the [sdkComboBox] on the EDT and chooses [PySdkSettings.preferredVirtualEnvBaseSdk] or prepends it.
*/
fun addBaseInterpretersAsync(sdkComboBox: PySdkPathChoosingComboBox,
existingSdks: List<Sdk>,
module: Module?,
context: UserDataHolder) {
addInterpretersAsync(
sdkComboBox,
{ findBaseSdks(existingSdks, module, context).takeIf { it.isNotEmpty() } ?: getSdksToInstall() },
{
sdkComboBox.apply {
val preferredSdkPath = PySdkSettings.instance.preferredVirtualEnvBaseSdk.takeIf(FileUtil::exists)
val detectedPreferredSdk = items.find { it.homePath == preferredSdkPath }
selectedSdk = when {
detectedPreferredSdk != null -> detectedPreferredSdk
preferredSdkPath != null -> PyDetectedSdk(preferredSdkPath).apply {
childComponent.insertItemAt(this, 0)
}
else -> items.getOrNull(0)
}
}
}
)
}
| 1 | null | 0 | 2 | dc846ecb926c9d9589c1ed8a40fdb20e47874db9 | 6,025 | intellij-community | Apache License 2.0 |
src/chapter1/section4/PermutationAndCombination.kt | w1374720640 | 265,536,015 | false | {"Kotlin": 1373556} | package chapter1.section4
/**
* 计算从total数量数据中取select个数据的排列数
* 从n个数中取m个数排列的公式为 P(n,m)=n*(n-1)*(n-2)*...*(n-m+1)=n!/(n-m)! (规定0!=1)
* n个数的全排列公式(m=n) P(n)=n*(n-1)*(n-2)*...*1=n!
*/
fun permutation(total: Int, select: Int): Long {
require(select in 0..total)
var count = 1L
repeat(select) {
count *= total - it
}
return count
}
/**
* 计算从total数量数据中取select个数据的组合数
* 从n个数中取m个数组合的公式为 C(n,m)=P(n,m)/m!
*/
fun combination(total: Int, select: Int): Long {
require(select in 0..total)
return permutation(total, select) / factorial(select)
}
/**
* 计算n的阶乘
*/
fun factorial(n: Int): Long {
require(n >= 0)
return permutation(n, n)
}
| 0 | Kotlin | 1 | 6 | 879885b82ef51d58efe578c9391f04bc54c2531d | 824 | Algorithms-4th-Edition-in-Kotlin | MIT License |
app/src/main/java/com/xinto/overlappingpanelscompose/component/ScrollItem.kt | X1nto | 410,539,641 | false | {"Kotlin": 21976} | package com.xinto.overlappingpanelscompose.component
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Card
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.xinto.overlappingpanelscompose.R
@Composable
fun ScrollItem(
modifier: Modifier = Modifier,
itemNumber: Int
) {
Card(
modifier = modifier,
backgroundColor = MaterialTheme.colors.surface,
shape = MaterialTheme.shapes.medium,
elevation = 0.dp
) {
Text(
modifier = Modifier.padding(8.dp),
text = stringResource(R.string.scroll_item, itemNumber)
)
}
}
| 0 | Kotlin | 3 | 12 | 450cb3d82adaaa8b4861588c31c9b35f53abde99 | 839 | OverlappingPanelsCompose | Apache License 2.0 |
app/src/main/java/archiveasia/jp/co/hakenman/model/OldWorksheet.kt | ohjjoa | 267,284,332 | true | {"Kotlin": 62696} | package archiveasia.jp.co.hakenman.model
import java.util.*
data class OldWorksheet (
var workDate: Date, // 勤務日時
var workTimeSum: Double, // 勤務時間合計
var workDaySum: Int, // 勤務日合計
var detailWorkList: MutableList<OldDetailWork> // 詳細勤務情報
)
data class OldDetailWork (
val workYear: Int, // 年
val workMonth: Int, // 月
val workDay: Int, // 日
val workWeek: String, // 週
var workFlag: Boolean, // 勤務フラグ
var beginTime: Date? = null, // 出社時間
var endTime: Date? = null, // 退社時間
var breakTime: Date? = null, // 休憩時間
var duration: Double? = null, // 勤務時間
var note: String? = null // 備考
) | 0 | Kotlin | 0 | 0 | f30dce1bfebb4bc6afab487a27fc716d12b34175 | 943 | Hakenman_Android | MIT License |
app/src/main/java/ai/travel/app/dto/getPhotoId/AddressComponent.kt | thekaailashsharma | 732,565,646 | false | {"Kotlin": 455850} | package ai.travel.app.dto.getPhotoId
import com.google.gson.annotations.SerializedName
import kotlinx.serialization.Serializable
@Serializable
data class AddressComponent(
@SerializedName("long_name")
val longName: String?,
@SerializedName("short_name")
val shortName: String?,
@SerializedName("types")
val types: List<String?>?
) | 1 | Kotlin | 1 | 0 | 8400e0989520f0d5aa4ddd23e8d94cfb5acbcecd | 357 | AI-Travel-Planner | MIT License |
exoplayer/src/main/java/com/github/satoshun/reactivex/exoplayer2/source/RxMediaSourceEvent.kt | satoshun | 116,258,385 | false | null | package com.github.satoshun.reactivex.exoplayer2.source
import android.os.Handler
import androidx.annotation.CheckResult
import com.github.satoshun.reactivex.exoplayer2.source.internal.MediaSourceEventObservable
import com.google.android.exoplayer2.source.MediaSource
import io.reactivex.Observable
/**
* Create an observable for MediaSource from MediaSourceEventListener.
*/
@CheckResult
fun MediaSource.events(handler: Handler = Handler()): Observable<MediaSourceEvent> {
return MediaSourceEventObservable(this, handler)
}
| 3 | Kotlin | 0 | 3 | d544f76a7107db15bb81ec19f8938e6476f8b4c9 | 531 | RxExoPlayer | Apache License 2.0 |
koleton-base/src/main/kotlin/koleton/util/RandomUtils.kt | ericktijerou | 267,768,682 | false | null | package koleton.util
private const val RANDOM_ALPHANUMERIC_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz0123456789"
internal fun getRandomAlphaNumericString(length: Int): String {
return (1..length)
.map { RANDOM_ALPHANUMERIC_CHARS.random() }
.joinToString(EMPTY_STRING)
}
| 12 | Kotlin | 21 | 202 | 58b7a54674ee3bf0c2351f21101181ca203a3d06 | 318 | koleton | Apache License 2.0 |
src/main/kotlin/skhu/msg/global/jwt/TokenProvider.kt | MetroSmartGuide | 670,908,006 | false | {"Kotlin": 283806, "Shell": 5227, "Dockerfile": 859} | package skhu.msg.global.jwt
import io.jsonwebtoken.Claims
import io.jsonwebtoken.ExpiredJwtException
import io.jsonwebtoken.Jwts
import io.jsonwebtoken.SignatureAlgorithm
import io.jsonwebtoken.io.Decoders
import io.jsonwebtoken.security.Keys
import jakarta.servlet.http.HttpServletRequest
import org.springframework.beans.factory.annotation.Value
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.security.core.authority.SimpleGrantedAuthority
import org.springframework.security.core.userdetails.User
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.stereotype.Component
import org.springframework.util.StringUtils
import skhu.msg.domain.auth.dto.response.ResponseToken
import skhu.msg.global.exception.ErrorCode
import skhu.msg.global.exception.GlobalException
import java.security.Key
import java.util.*
@Component
class TokenProvider(
@Value("\${jwt.secret}") secretKey: String?,
@Value("\${jwt.access-token-validity-in-milliseconds}") accessTokenValidityTime: Long,
@Value("\${jwt.refresh-token-validity-in-milliseconds}") refreshTokenValidityTime: Long,
) {
private final val key: Key
private final val accessTokenValidityTime: Long
private final val refreshTokenValidityTime: Long
init {
val keyBytes: ByteArray = Decoders.BASE64.decode(secretKey)
key = Keys.hmacShaKeyFor(keyBytes)
this.accessTokenValidityTime = accessTokenValidityTime
this.refreshTokenValidityTime = refreshTokenValidityTime
}
fun createToken(email: String): ResponseToken {
return try {
val now = Date()
val tokenExpiredTime = Date(now.time + accessTokenValidityTime)
val accessToken = Jwts.builder()
.setSubject(email)
.claim("role", "ROLE_MEMBER")
.setIssuedAt(now)
.setExpiration(tokenExpiredTime)
.signWith(key, SignatureAlgorithm.HS256)
.compact()
val refreshTokenExpiredTime = Date(now.time + refreshTokenValidityTime)
val refreshToken = Jwts.builder()
.setExpiration(refreshTokenExpiredTime)
.signWith(key, SignatureAlgorithm.HS256)
.compact()
ResponseToken.create(accessToken, refreshToken)
} catch (ex: Exception) {
throw GlobalException(ErrorCode.INTERNAL_SERVER_ERROR_JWT)
}
}
fun refreshAccessTokenByRefreshToken(request: HttpServletRequest, refreshToken: String): ResponseToken {
return try {
val accessToken = resolveToken(request) ?: throw GlobalException(ErrorCode.INVALID_JWT)
val now = Date()
val tokenExpiredTime = Date(now.time + accessTokenValidityTime)
val newAccessToken = Jwts.builder()
.setSubject(parseClaims(accessToken).subject)
.claim("role", "ROLE_MEMBER")
.setIssuedAt(now)
.setExpiration(tokenExpiredTime)
.signWith(key, SignatureAlgorithm.HS256)
.compact()
ResponseToken.create(newAccessToken, refreshToken)
} catch (ex: Exception) {
throw GlobalException(ErrorCode.INTERNAL_SERVER_ERROR_JWT)
}
}
fun getAuthentication(accessToken: String): UsernamePasswordAuthenticationToken {
return try {
val claims = parseClaims(accessToken)
val role = claims["role"] as? String
?: throw GlobalException(ErrorCode.FORBIDDEN_TOKEN)
val authorities = role.split(",").map { SimpleGrantedAuthority(it) }
val principal: UserDetails = User(claims.subject, "", authorities)
UsernamePasswordAuthenticationToken(principal, "", authorities)
} catch (ex: Exception) {
throw GlobalException(ErrorCode.FORBIDDEN_TOKEN)
}
}
fun resolveToken(request: HttpServletRequest): String? {
val bearerToken: String? = request.getHeader("Authorization")
return if (StringUtils.hasText(bearerToken) && bearerToken?.startsWith("Bearer ") == true) {
bearerToken.substring(7)
} else null
}
fun validateToken(token: String?): Boolean {
return try {
token?.let {
Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(it)
true
} ?: false
} catch (e: Exception) {
false
}
}
private fun parseClaims(accessToken: String): Claims {
return try {
Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(accessToken).body
} catch (e: ExpiredJwtException) {
e.claims
}
}
fun getExpirationTime(token: String): Long {
val expirationTime = Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token).body.expiration.time
val now = Date().time
return expirationTime - now
}
} | 0 | Kotlin | 0 | 0 | 2e7c601feab7f5429d46b8b988e392550f7f1d09 | 5,062 | msg-server | MIT License |
app/src/main/java/com/starry/myne/MainActivity.kt | Pool-Of-Tears | 568,700,970 | false | {"Kotlin": 366426} | /*
Copyright 2022 - 2023 <NAME>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.starry.myne
import android.Manifest.permission.READ_EXTERNAL_STORAGE
import android.Manifest.permission.WRITE_EXTERNAL_STORAGE
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.util.Log
import androidx.activity.compose.setContent
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.Surface
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.core.app.ActivityCompat
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import androidx.lifecycle.ViewModelProvider
import coil.annotation.ExperimentalCoilApi
import com.starry.myne.ui.screens.main.MainScreen
import com.starry.myne.ui.screens.settings.viewmodels.SettingsViewModel
import com.starry.myne.ui.screens.settings.viewmodels.ThemeMode
import com.starry.myne.ui.theme.MyneTheme
import com.starry.myne.utils.NetworkObserver
import dagger.hilt.android.AndroidEntryPoint
@ExperimentalMaterialApi
@ExperimentalCoilApi
@ExperimentalMaterial3Api
@ExperimentalComposeUiApi
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
private lateinit var networkObserver: NetworkObserver
lateinit var settingsViewModel: SettingsViewModel
private lateinit var mainViewModel: MainViewModel
@ExperimentalAnimationApi
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
networkObserver = NetworkObserver(applicationContext)
settingsViewModel = ViewModelProvider(this)[SettingsViewModel::class.java]
mainViewModel = ViewModelProvider(this)[MainViewModel::class.java]
ThemeMode.entries.find { it.ordinal == settingsViewModel.getThemeValue() }
?.let { settingsViewModel.setTheme(it) }
settingsViewModel.setMaterialYou(settingsViewModel.getMaterialYouValue())
// Install splash screen before setting content.
installSplashScreen().setKeepOnScreenCondition {
mainViewModel.isLoading.value
}
setContent {
MyneTheme(settingsViewModel = settingsViewModel) {
val status by networkObserver.observe().collectAsState(
initial = NetworkObserver.Status.Unavailable
)
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
val startDestination by mainViewModel.startDestination
MainScreen(
startDestination = startDestination,
networkStatus = status,
settingsViewModel = settingsViewModel
)
}
}
}
checkStoragePermission()
}
fun checkStoragePermission(): Boolean {
return if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
if (checkSelfPermission(WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
Log.d("MainActivity::Storage", "Permission is granted"); true
} else {
Log.d("MainActivity::Storage", "Permission is revoked")
ActivityCompat.requestPermissions(
this, arrayOf(WRITE_EXTERNAL_STORAGE, READ_EXTERNAL_STORAGE), 1
); false
}
} else {
true
}
}
} | 7 | Kotlin | 50 | 752 | 9f4c560069efab6c48b83b0a33585181dc130ef7 | 4,401 | Myne | Apache License 2.0 |
persistence/src/androidTest/kotlin/com/cesarvaliente/kunidirectional/persistence/handler/UpdateHandlerTest.kt | CesarValiente | 88,026,476 | false | null | /**
* Copyright (C) 2017 <NAME> & <NAME>
*
* https://github.com/CesarValiente
* https://github.com/coshaw
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.cesarvaliente.kunidirectional.persistence.handler
import android.support.test.InstrumentationRegistry
import android.support.test.runner.AndroidJUnit4
import com.cesarvaliente.kunidirectional.persistence.createPersistenceItem
import com.cesarvaliente.kunidirectional.persistence.insertOrUpdate
import com.cesarvaliente.kunidirectional.persistence.queryAllItemsSortedByPosition
import com.cesarvaliente.kunidirectional.persistence.queryByLocalId
import com.cesarvaliente.kunidirectional.persistence.toPersistenceColor
import com.cesarvaliente.kunidirectional.persistence.toStoreItem
import com.cesarvaliente.kunidirectional.store.UpdateAction
import com.cesarvaliente.kunidirectional.store.UpdateAction.ReorderItemsAction
import io.realm.Realm
import io.realm.RealmConfiguration
import org.hamcrest.CoreMatchers.not
import org.hamcrest.CoreMatchers.nullValue
import org.hamcrest.MatcherAssert.assertThat
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import com.cesarvaliente.kunidirectional.persistence.Color as PersistenceColor
import com.cesarvaliente.kunidirectional.persistence.Item as PersistenceItem
import com.cesarvaliente.kunidirectional.store.Color as StoreColor
import com.cesarvaliente.kunidirectional.store.Item as StoreItem
import org.hamcrest.core.Is.`is` as iz
@RunWith(AndroidJUnit4::class)
class UpdateHandlerTest {
lateinit var config: RealmConfiguration
lateinit var db: Realm
@Before
fun setup() {
Realm.init(InstrumentationRegistry.getTargetContext())
config = RealmConfiguration.Builder()
.name("test.realm")
.inMemory()
.build()
Realm.setDefaultConfiguration(config)
db = Realm.getInstance(config)
}
@After
fun clean() {
db.close()
Realm.deleteRealm(config)
}
@Test
fun should_reorder_Items() {
val item1 = createPersistenceItem(1)
val item2 = createPersistenceItem(2)
val item3 = createPersistenceItem(3)
item1.insertOrUpdate(db)
item2.insertOrUpdate(db)
item3.insertOrUpdate(db)
item1.position = 4L
item2.position = 1L
item3.position = 2L
val listOfStoreItems = listOf(item1.toStoreItem(), item2.toStoreItem(), item3.toStoreItem())
val reorderItemsAction = ReorderItemsAction(listOfStoreItems)
UpdateHandler.handle(reorderItemsAction, {})
val itemsCollection = db.queryAllItemsSortedByPosition()
assertThat(itemsCollection, iz(not(nullValue())))
assertThat(itemsCollection.component1().localId, iz(item2.localId))
assertThat(itemsCollection.component2().localId, iz(item3.localId))
assertThat(itemsCollection.component3().localId, iz(item1.localId))
}
@Test
fun should_update_Item() {
val item1 = createPersistenceItem(1)
item1.insertOrUpdate(db)
val NEW_TEXT = "new text"
val NEW_COLOR = StoreColor.YELLOW
val updateItemAction = UpdateAction.UpdateItemAction(
localId = item1.localId, text = NEW_TEXT, color = NEW_COLOR)
UpdateHandler.handle(updateItemAction, {})
val managedItem = db.queryByLocalId(item1.localId)
assertThat(managedItem, iz(not(nullValue())))
assertThat(managedItem!!.text, iz(NEW_TEXT))
assertThat(managedItem.getColorAsEnum(), iz(NEW_COLOR.toPersistenceColor()))
}
@Test
fun should_update_favorite_field() {
val item1 = createPersistenceItem(1)
item1.insertOrUpdate(db)
val NEW_FAVORITE = true
val updateFavoriteAction = UpdateAction.UpdateFavoriteAction(
localId = item1.localId, favorite = NEW_FAVORITE)
UpdateHandler.handle(updateFavoriteAction, {})
val managedItem = db.queryByLocalId(item1.localId)
assertThat(managedItem, iz(not(nullValue())))
assertThat(managedItem!!.favorite, iz(NEW_FAVORITE))
}
@Test
fun should_update_color_field() {
val item1 = createPersistenceItem(1)
item1.insertOrUpdate(db)
val NEW_COLOR = StoreColor.WHITE
val updateColorAction = UpdateAction.UpdateColorAction(
localId = item1.localId, color = NEW_COLOR)
UpdateHandler.handle(updateColorAction, {})
val managedItem = db.queryByLocalId(item1.localId)
assertThat(managedItem, iz(not(nullValue())))
assertThat(managedItem!!.getColorAsEnum(), iz(NEW_COLOR.toPersistenceColor()))
}
} | 2 | Kotlin | 30 | 313 | 81706091f1700165a63eba310a12cedc136ded1f | 5,256 | KUnidirectional | Apache License 2.0 |
domain/src/main/java/com/example/bos/Comic.kt | artjimlop | 96,988,205 | false | null | package com.example.bos
data class Comic(val id: Int,
val title: String,
val description: String,
val pageCount: Int,
val thumbnailUrl: String,
val imageUrls: MutableList<String>)
| 0 | Kotlin | 0 | 1 | e12c3df7736be0f28d1b2d9dd523129aaf817f98 | 291 | clean-architecture-kotlin | Apache License 2.0 |
src/main/kotlin/gg/octave/bot/music/radio/RadioSource.kt | lucas178 | 270,852,455 | false | null | package gg.octave.bot.music.radio
import com.sedmelluq.discord.lavaplayer.track.AudioTrack
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.DataInputStream
import java.util.concurrent.CompletableFuture
interface RadioSource {
val name: String
fun nextTrack(context: RadioTrackContext): CompletableFuture<AudioTrack?>
fun serialize(stream: ByteArrayOutputStream)
companion object {
fun deserialize(stream: ByteArrayInputStream): RadioSource {
if (stream.available() == 0) {
throw IllegalStateException("Cannot parse RadioSource with no remaining bytes")
}
val reader = DataInputStream(stream)
val ctx = when (val sourceType = reader.readInt()) {
1 -> DiscordRadio(reader.readUTF())
2 -> PlaylistRadio(reader.readUTF(), reader.readUTF())
else -> throw IllegalArgumentException("Invalid contextType $sourceType!")
}
reader.close()
return ctx
}
}
}
| 0 | Kotlin | 0 | 1 | 6cac8521ef42490fa8b80682d6b447d7b6ddcacd | 1,075 | Octave-development | MIT License |
src/main/kotlin/io/reactiverse/kotlin/pgclient/PgNotification.kt | vietj | 184,532,002 | false | null | /*
* Copyright 2019 Red Hat, Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* The Apache License v2.0 is available at
* http://www.opensource.org/licenses/apache2.0.php
*
* You may elect to redistribute this code under either of these licenses.
*/
package io.reactiverse.kotlin.pgclient
import io.reactiverse.pgclient.PgNotification
/**
* A function providing a DSL for building [io.reactiverse.pgclient.PgNotification] objects.
*
* A notification emited by Postgres.
*
* @param channel Set the channel value.
* @param payload Set the payload value.
* @param processId Set the process id.
*
* <p/>
* NOTE: This function has been automatically generated from the [io.reactiverse.pgclient.PgNotification original] using Vert.x codegen.
*/
fun pgNotificationOf(
channel: String? = null,
payload: String? = null,
processId: Int? = null): PgNotification = io.reactiverse.pgclient.PgNotification().apply {
if (channel != null) {
this.setChannel(channel)
}
if (payload != null) {
this.setPayload(payload)
}
if (processId != null) {
this.setProcessId(processId)
}
}
/**
* A function providing a DSL for building [io.reactiverse.pgclient.PgNotification] objects.
*
* A notification emited by Postgres.
*
* @param channel Set the channel value.
* @param payload Set the payload value.
* @param processId Set the process id.
*
* <p/>
* NOTE: This function has been automatically generated from the [io.reactiverse.pgclient.PgNotification original] using Vert.x codegen.
*/
@Deprecated(
message = "This function will be removed in a future version",
replaceWith = ReplaceWith("pgNotificationOf(channel, payload, processId)")
)
fun PgNotification(
channel: String? = null,
payload: String? = null,
processId: Int? = null): PgNotification = io.reactiverse.pgclient.PgNotification().apply {
if (channel != null) {
this.setChannel(channel)
}
if (payload != null) {
this.setPayload(payload)
}
if (processId != null) {
this.setProcessId(processId)
}
}
| 12 | Java | 6 | 73 | 5250ef2a67f3d9c45ccdd37d93ca50f378218f18 | 2,301 | reactive-pg-client | Apache License 2.0 |
falkon-dao-extn/src/main/kotlin/com/jayrave/falkon/dao/DaoForUpdates.kt | jayrave | 65,279,209 | false | null | package com.jayrave.falkon.dao
import com.jayrave.falkon.engine.CompiledStatement
import com.jayrave.falkon.mapper.Column
/**
* Updates a record if possible based on the primary key of [t] according to
* the table it is connected to
*
* @return number of rows updated by this operation
*/
fun <T : Any, ID : Any> Dao<T, ID>.update(t: T): Int {
return update(listOf(t))
}
/**
* Updates a record if possible based on the primary keys of each of [ts] according to
* the table it is connected to
*
* @return number of rows updated by this operation
* @see [update]
*/
fun <T : Any, ID : Any> Dao<T, ID>.update(vararg ts: T): Int {
return update(ts.asList())
}
/**
* Updates a record if possible based on the primary keys of each of [ts] according to
* the table it is connected to
*
* @return number of rows updated by this operation
*/
fun <T : Any, ID : Any> Dao<T, ID>.update(ts: Iterable<T>): Int {
var numberOfRowsUpdated = 0
val idColumns = table.idColumns
val nonIdColumns = table.nonIdColumns
throwIfColumnCollectionIsEmpty(idColumns, "id")
if (nonIdColumns.isNotEmpty()) {
table.configuration.engine.executeInTransaction {
var compiledStatementForUpdate: CompiledStatement<Int>? = null
try {
for (item in ts) {
compiledStatementForUpdate = when (compiledStatementForUpdate) {
// First item. Build CompiledStatement for update
null -> buildCompiledStatementForUpdate(item, idColumns, nonIdColumns)
// Not the first item. Clear bindings, rebind required columns & set id
else -> {
compiledStatementForUpdate.clearBindings()
compiledStatementForUpdate.bindColumns(nonIdColumns, item)
compiledStatementForUpdate.bindColumns(
idColumns, item, nonIdColumns.size + 1
)
compiledStatementForUpdate
}
}
numberOfRowsUpdated += compiledStatementForUpdate.execute()
}
} finally {
// No matter what happens, CompiledStatement must be closed
// to prevent resource leakage
compiledStatementForUpdate?.close()
}
}
}
return numberOfRowsUpdated
}
/**
* @param item Item to build [CompiledStatement] for
* @param idColumns list of id, non empty columns with deterministic iteration order
* @param nonIdColumns list of non-id, non empty columns with deterministic iteration order
*
* @return [CompiledStatement] corresponding to the passed in [item]
* @throws IllegalArgumentException if the passed in [nonIdColumns] is empty
*/
private fun <T : Any> Dao<T, *>.buildCompiledStatementForUpdate(
item: T, idColumns: Collection<Column<T, *>>, nonIdColumns: Collection<Column<T, *>>):
CompiledStatement<Int> {
throwIfColumnCollectionIsEmpty(idColumns, "id")
throwIfColumnCollectionIsEmpty(nonIdColumns, "non-id")
// Set all non-id columns
val builder = updateBuilder().values {
nonIdColumns.forEach {
@Suppress("UNCHECKED_CAST")
val column = it as Column<T, Any?>
set(column, column.extractPropertyFrom(item))
}
}
// Add predicates for id columns & compile
return builder.where().and {
idColumns.forEach { idColumn ->
@Suppress("UNCHECKED_CAST")
eq(idColumn as Column<T, Any?>, idColumn.extractPropertyFrom(item))
}
}.compile()
}
private fun throwIfColumnCollectionIsEmpty(columns: Collection<*>, kind: String) {
if (columns.isEmpty()) {
throw IllegalArgumentException("$kind columns can't be empty for updates")
}
} | 6 | Kotlin | 2 | 12 | ce42d553c578cd8e509bbfd7effc5d56bf3cdedd | 3,933 | falkon | Apache License 2.0 |