path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/main/kotlin/com/s3ich4n/theater/domain/Seat.kt | s3ich4n | 611,847,333 | false | null | package com.s3ich4n.theater.domain
import jakarta.persistence.Entity
import jakarta.persistence.GeneratedValue
import jakarta.persistence.GenerationType
import jakarta.persistence.Id
import java.math.BigDecimal
@Entity
class Seat(
@Id @GeneratedValue(strategy = GenerationType.AUTO)
val id: Long,
val row: Char,
val num: Int,
val price: BigDecimal,
val description: String, ) {
override fun toString(): String = "Seat $row-$num $$price ($description)"
}
| 0 | Kotlin | 0 | 0 | aea28cb9ca773ca1151602166e169021ffe9b171 | 484 | kotlin-spring-101-1 | MIT License |
plugins/kotlin/idea/tests/testData/multiModuleQuickFix/addThrowAnnotation/jvm/jvm_dep(stdlib)/jvm.kt | JetBrains | 2,489,216 | false | null | // "Add '@Throws' annotation" "true"
// IGNORE_K2
fun test() {
<caret>throw Throwable()
} | 284 | null | 5162 | 16,707 | def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0 | 94 | intellij-community | Apache License 2.0 |
app/src/main/java/dev/esnault/bunpyro/android/screen/start/StartViewModel.kt | esnaultdev | 242,479,002 | false | null | package dev.esnault.bunpyro.android.screen.start
import androidx.lifecycle.viewModelScope
import dev.esnault.bunpyro.android.screen.base.BaseViewModel
import dev.esnault.bunpyro.data.repository.apikey.IApiKeyRepository
import dev.esnault.bunpyro.data.repository.sync.ISyncRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
class StartViewModel(
private val apiKeyRepo: IApiKeyRepository,
private val syncRepo: ISyncRepository
) : BaseViewModel() {
init {
viewModelScope.launch(Dispatchers.IO) {
val hasApiKey = apiKeyRepo.hasApiKey()
if (!hasApiKey) {
navigate(StartFragmentDirections.actionStartToApiKey())
return@launch
}
val firstSyncCompleted = syncRepo.getFirstSyncCompleted()
if (!firstSyncCompleted) {
navigate(StartFragmentDirections.actionStartToFirstSync())
} else {
navigate(StartFragmentDirections.actionStartToHome())
}
}
}
}
| 2 | Kotlin | 1 | 9 | 89b3c7dad2c37c22648c26500016d6503d27019e | 1,058 | BunPyro | Intel Open Source License |
YasuoRVAdapter/src/main/java/com/fusion_nex_gen/yasuorvadapter/viewPager/YasuoNormalVPAdapter.kt | q876625596 | 333,317,871 | false | null | package com.fusion_nex_gen.yasuorvadapter.viewPager
import android.view.ViewGroup
import androidx.core.util.set
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.OnLifecycleEvent
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.fusion_nex_gen.yasuorvadapter.bean.YasuoItemNormalConfigForVP
import com.fusion_nex_gen.yasuorvadapter.bean.YasuoList
import com.fusion_nex_gen.yasuorvadapter.holder.YasuoNormalVH
import kotlin.reflect.KClass
/**
* 快速获取已绑定的[YasuoNormalVPAdapter]
* Quickly obtain the bound [YasuoNormalVPAdapter]
*/
fun ViewPager2.getNormalAdapter(): YasuoNormalVPAdapter {
return this.adapter as YasuoNormalVPAdapter
}
/**
* 绑定adapter
* Binding adapter
* @param life LifecycleOwner object
* @param itemList [YasuoBaseVPAdapter.itemList]
* @param headerList [YasuoBaseVPAdapter.headerList]
* @param footerList [YasuoBaseVPAdapter.footerList]
* @param rvListener 绑定Adapter实体之前需要做的操作
* @param rvListener What to do before binding adapter entity
*/
inline fun ViewPager2.adapterBinding(
life: LifecycleOwner,
itemList: YasuoList<Any>,
headerList: YasuoList<Any> = YasuoList(),
footerList: YasuoList<Any> = YasuoList(),
rvListener: YasuoNormalVPAdapter.() -> YasuoNormalVPAdapter
): YasuoNormalVPAdapter {
return YasuoNormalVPAdapter(life, itemList, headerList, footerList).bindLife().rvListener().attach(this)
}
/**
* 绑定adapter
* Binding adapter
* @param adapter Adapter实体
* @param adapter Adapter entity
* @param vpListener 绑定Adapter实体之前需要做的操作
* @param vpListener What to do before binding adapter entity
*/
inline fun ViewPager2.adapterBinding(
adapter: YasuoNormalVPAdapter,
vpListener: YasuoNormalVPAdapter.() -> YasuoNormalVPAdapter
): YasuoNormalVPAdapter {
return adapter.bindLife().vpListener().attach(this)
}
open class YasuoNormalVPAdapter(
val life: LifecycleOwner,
itemList: YasuoList<Any> = YasuoList(),
headerItemList: YasuoList<Any> = YasuoList(),
footerItemList: YasuoList<Any> = YasuoList(),
) : YasuoBaseVPAdapter<YasuoNormalVH, YasuoItemNormalConfigForVP<Any, YasuoNormalVH>>(itemList), LifecycleObserver {
init {
this.itemList.addOnListChangedCallback(itemListListener)
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
fun itemsRemoveListener() {
this.itemList.removeOnListChangedCallback(itemListListener)
}
/**
* 绑定生命周期,初始化adapter之后必须调用
* Binding life cycle, which must be called after initializing adapter
*/
fun bindLife(): YasuoNormalVPAdapter {
life.lifecycle.addObserver(this)
return this
}
override fun onDetachedFromRecyclerView(recyclerView: RecyclerView) {
super.onDetachedFromRecyclerView(recyclerView)
life.lifecycle.removeObserver(this)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): YasuoNormalVH {
initInflater(parent.context)
val holder = YasuoNormalVH(inflater!!.inflate(viewType, parent, false))
itemIdTypes[viewType]?.holderCreateListener?.invoke(holder)
return holder
}
override fun onBindViewHolder(holder: YasuoNormalVH, position: Int) {
itemIdTypes[holder.itemViewType]?.holderBindListener?.invoke(holder, getItem(position))
}
}
/**
* 建立数据类与布局文件之间的匹配关系
* Establish the matching relationship between data class and layout file
* @param itemLayoutId itemView布局id
* itemLayoutId
* @param itemClass 对应实体类的Class
* Class corresponding to entity class
* @param execute 后续对[YasuoItemNormalConfigForVP]的执行操作
* Subsequent operations on [YasuoItemNormalConfigForVP]
*/
fun <T : Any, Adapter : YasuoNormalVPAdapter> Adapter.holderConfigVP(
itemLayoutId: Int,
itemClass: KClass<T>,
execute: (YasuoItemNormalConfigForVP<T, YasuoNormalVH>.() -> Unit)? = null
): Adapter {
val itemType = YasuoItemNormalConfigForVP<T, YasuoNormalVH>(itemLayoutId)
execute?.invoke(itemType)
itemClassTypes[itemClass] = itemType as YasuoItemNormalConfigForVP<Any, YasuoNormalVH>
itemIdTypes[itemLayoutId] = itemType
return this
}
| 1 | null | 4 | 52 | 6c9f90b650b6bf6e0fdf914d5c9d05cd95454ce1 | 4,209 | YasuoRecyclerViewAdapter | Apache License 2.0 |
zircon.core/src/commonMain/kotlin/org/hexworks/zircon/internal/component/impl/DefaultPanel.kt | Hexworks | 94,116,947 | false | null | package org.hexworks.zircon.internal.component.impl
import org.hexworks.zircon.api.behavior.TitleOverride
import org.hexworks.zircon.api.component.ColorTheme
import org.hexworks.zircon.api.component.Panel
import org.hexworks.zircon.api.component.data.ComponentMetadata
import org.hexworks.zircon.api.component.renderer.ComponentRenderingStrategy
open class DefaultPanel(
componentMetadata: ComponentMetadata,
initialTitle: String,
renderingStrategy: ComponentRenderingStrategy<Panel>
) : Panel, DefaultContainer(
componentMetadata = componentMetadata,
renderer = renderingStrategy
), TitleOverride by TitleOverride.create(initialTitle) {
override fun convertColorTheme(colorTheme: ColorTheme) = colorTheme.toContainerStyle()
}
| 42 | null | 138 | 738 | 55a0ccc19a3f1b80aecd5f1fbe859db94ba9c0c6 | 755 | zircon | Apache License 2.0 |
common/src/main/kotlin/dev/jaims/mcutils/common/Common.kt | Jaimss | 278,483,163 | false | null | package dev.jaims.mcutils.common
import khttp.post
import java.util.*
/**
* Post a [String] to https://paste.jaims.dev. Useful for sending console logs or error messages.
*/
fun String.toPastebin(): String {
val url = "https://paste.jaims.dev/documents"
val r = post(
url,
mapOf(
"Content-Type" to "text/plain; charset=utf-8",
"Content-Length" to this.encodeToByteArray().size.toString()
),
data = this,
)
return "https://paste.jaims.dev/${r.jsonObject["key"]}"
}
/**
* Turn an int into a Roman Numeral String
*
* @return the correct roman numeral string
*/
fun Int.toRomanNumeral(): String {
val map = mapOf(
1000 to "M",
900 to "CM",
500 to "D",
400 to "CD",
100 to "C",
90 to "XC",
50 to "L",
40 to "XL",
10 to "X",
9 to "IX",
5 to "V",
4 to "IV",
1 to "I"
)
var remainder = this
var output = ""
for ((int, str) in map) {
while (remainder / int > 0) {
remainder -= int
output += str
}
}
return output
}
/**
* Get the different hours, minutes, seconds, etc. from a Integer in seconds
*
* @return a map of times and ints where time is the [Times] and [Int] is the amount of that time
*/
fun Int.toTimeFormatted(): Map<Times, Int> {
var remainder = this
val years = remainder / 31536000
remainder -= years * 31536000
val months = remainder / 2592000
remainder -= months * 2592000
val weeks = remainder / 604800
remainder -= weeks * 604800
val days = remainder / 86400
remainder -= days * 86400
val hours = remainder / 3600
remainder -= hours * 3600
val minutes = remainder / 60
remainder -= minutes * 60
val seconds = remainder
return mapOf(
Times.YEARS to years,
Times.MONTHS to months,
Times.WEEKS to weeks,
Times.DAYS to days,
Times.HOURS to hours,
Times.MINUTES to minutes,
Times.SECONDS to seconds
)
}
/**
* Get the difference in time (seconds) between two [java.util.Date]
*
* @param date the old date
* @return the seconds difference between two dates.
*/
fun Date.getSecondsDifference(date: Date): Int {
return ((date.time - time) / 1000).toInt()
}
/**
* @return what type of [InputType] a certain string is
*/
fun String.getInputType(): InputType {
if (matches("[A-Za-z0-9]{8}[-][A-Za-z0-9]{4}[-][A-Za-z0-9]{4}[-][A-Za-z0-9]{4}[-][A-Za-z0-9]{12}".toRegex()))
return InputType.UUID
if (matches("[A-Za-z0-9]{32}".toRegex())) return InputType.SHORTUUID
return InputType.NAME
}
/**
* A simple enum class for input types
* Useful when getting user inputs to see if it is a UUID or a username
*/
enum class InputType {
UUID,
SHORTUUID,
NAME;
}
/**
* @param placeholder is the name that you can use in placeholders for lang filesa. its also just a lowercase version
* of the name
* A simple enum for the names of different time specs.
*/
enum class Times(val placeholder: String) {
YEARS("years"),
MONTHS("months"),
WEEKS("weeks"),
DAYS("days"),
HOURS("hours"),
MINUTES("minutes"),
SECONDS("seconds");
override fun toString(): String {
return placeholder
}
} | 1 | Kotlin | 0 | 1 | db4dda2b504e6057fab93b2683c2ee301df035ca | 3,339 | mcutils | MIT License |
fluent-icons-extended/src/commonMain/kotlin/com/konyaco/fluent/icons/regular/PersonClock.kt | Konyaco | 574,321,009 | false | null |
package com.konyaco.fluent.icons.regular
import androidx.compose.ui.graphics.vector.ImageVector
import com.konyaco.fluent.icons.Icons
import com.konyaco.fluent.icons.fluentIcon
import com.konyaco.fluent.icons.fluentPath
public val Icons.Regular.PersonClock: ImageVector
get() {
if (_personClock != null) {
return _personClock!!
}
_personClock = fluentIcon(name = "Regular.PersonClock") {
fluentPath {
moveTo(11.31f, 15.5f)
curveToRelative(0.18f, -0.53f, 0.42f, -1.04f, 0.71f, -1.5f)
lineTo(4.25f, 14.0f)
curveTo(3.01f, 14.0f, 2.0f, 15.0f, 2.0f, 16.25f)
verticalLineToRelative(0.58f)
curveToRelative(0.0f, 0.89f, 0.32f, 1.75f, 0.9f, 2.43f)
curveTo(4.47f, 21.1f, 6.85f, 22.0f, 10.0f, 22.0f)
curveToRelative(0.93f, 0.0f, 1.8f, -0.08f, 2.6f, -0.24f)
arcToRelative(6.52f, 6.52f, 0.0f, false, true, -0.92f, -1.36f)
curveToRelative(-0.52f, 0.07f, -1.08f, 0.1f, -1.68f, 0.1f)
curveToRelative(-2.74f, 0.0f, -4.7f, -0.74f, -5.96f, -2.21f)
curveToRelative(-0.34f, -0.4f, -0.54f, -0.93f, -0.54f, -1.46f)
verticalLineToRelative(-0.58f)
curveToRelative(0.0f, -0.41f, 0.34f, -0.75f, 0.75f, -0.75f)
horizontalLineToRelative(7.06f)
close()
moveTo(10.0f, 2.0f)
arcToRelative(5.0f, 5.0f, 0.0f, true, true, 0.0f, 10.0f)
arcToRelative(5.0f, 5.0f, 0.0f, false, true, 0.0f, -10.0f)
close()
moveTo(10.0f, 3.5f)
arcToRelative(3.5f, 3.5f, 0.0f, true, false, 0.0f, 7.0f)
arcToRelative(3.5f, 3.5f, 0.0f, false, false, 0.0f, -7.0f)
close()
moveTo(17.5f, 12.0f)
arcToRelative(5.5f, 5.5f, 0.0f, true, true, 0.0f, 11.0f)
arcToRelative(5.5f, 5.5f, 0.0f, false, true, 0.0f, -11.0f)
close()
moveTo(19.5f, 17.5f)
horizontalLineToRelative(-2.0f)
lineTo(17.5f, 15.0f)
arcToRelative(0.5f, 0.5f, 0.0f, true, false, -1.0f, 0.0f)
verticalLineToRelative(3.0f)
curveToRelative(0.0f, 0.28f, 0.22f, 0.5f, 0.5f, 0.5f)
horizontalLineToRelative(2.5f)
arcToRelative(0.5f, 0.5f, 0.0f, false, false, 0.0f, -1.0f)
close()
}
}
return _personClock!!
}
private var _personClock: ImageVector? = null
| 1 | Kotlin | 3 | 83 | 9e86d93bf1f9ca63a93a913c990e95f13d8ede5a | 2,624 | compose-fluent-ui | Apache License 2.0 |
feature/collection/src/main/java/com/mrl/pixiv/collection/viewmodel/CollectionMiddleware.kt | master-lzh | 656,227,310 | false | {"Kotlin": 500860} | package com.mrl.pixiv.collection.viewmodel
import com.mrl.pixiv.common.viewmodel.Middleware
import com.mrl.pixiv.data.Restrict
import com.mrl.pixiv.data.user.UserBookmarkTagsQuery
import com.mrl.pixiv.repository.CollectionRepository
import kotlinx.collections.immutable.toImmutableList
import org.koin.core.annotation.Factory
@Factory
class CollectionMiddleware(
private val collectionRepository: CollectionRepository
) : Middleware<CollectionState, CollectionAction>() {
override suspend fun process(state: CollectionState, action: CollectionAction) {
when (action) {
is CollectionAction.LoadUserBookmarksTagsIllust -> loadUserBookmarkTagsIllust(
action.restrict,
state.userId
)
else -> Unit
}
}
private fun loadUserBookmarkTagsIllust(@Restrict restrict: String, userId: Long) {
launchNetwork {
requestHttpDataWithFlow(
request = collectionRepository.getUserBookmarkTagsIllust(
UserBookmarkTagsQuery(
userId = if (userId == Long.MIN_VALUE) collectionRepository.getUserInfo().uid else userId,
restrict = restrict
)
)
) {
dispatch(
CollectionAction.UpdateUserBookmarkTagsIllust(
userBookmarkTagsIllust = it.bookmarkTags.toImmutableList()
)
)
}
}
}
} | 1 | Kotlin | 0 | 21 | ec9f9fa1508971dd34dd968affe82d023d05a942 | 1,525 | PiPixiv | Apache License 2.0 |
authlibrary/src/test/java/com/koma/authlibrary/data/source/AuthRepositoryTest.kt | komamj | 244,861,092 | false | null | package com.koma.authlibrary.data.source
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
class AuthRepositoryTest {
} | 0 | Kotlin | 0 | 0 | 8b25061848bc7302877ccf25f964ad63ee15d185 | 160 | CAC | Apache License 2.0 |
dsl/common/lang-common/src/main/kotlin/io/kotless/dsl/lang/Permissions.kt | cienijr | 273,365,740 | true | {"Kotlin": 290861} | package io.kotless.dsl.lang
import io.kotless.PermissionLevel
/** Delegates permissions to specified bucket to entity with annotation */
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.CLASS, AnnotationTarget.PROPERTY)
annotation class S3Bucket(val bucket: String, val level: PermissionLevel)
/** Delegates permissions to specified parameters' prefix in SSM to entity with annotation */
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.CLASS, AnnotationTarget.PROPERTY)
annotation class SSMParameters(val prefix: String, val level: PermissionLevel)
/** Delegates permissions to specified DynamoDB table to entity with annotation */
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.CLASS, AnnotationTarget.PROPERTY)
annotation class DynamoDBTable(val table: String, val level: PermissionLevel, val indexes: Array<String> = [])
/** Delegates permissions to specified SNS topic to entity with annotation */
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.CLASS, AnnotationTarget.PROPERTY)
annotation class SNSTopic(val topic: String, val level: PermissionLevel)
| 0 | Kotlin | 0 | 0 | 90e13fe0593a318143865e7987f3529b83ea7d9b | 1,078 | kotless | Apache License 2.0 |
feature/schedule/src/main/java/little/goose/schedule/ui/ScheduleHomeViewModel.kt | MReP1 | 525,822,587 | false | null | package little.goose.schedule.ui
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import little.goose.schedule.data.entities.Schedule
import little.goose.schedule.logic.DeleteSchedulesUseCase
import little.goose.schedule.logic.GetAllScheduleFlowUseCase
import little.goose.schedule.logic.UpdateScheduleUseCase
import javax.inject.Inject
@HiltViewModel
class ScheduleHomeViewModel @Inject constructor(
private val updateScheduleUseCase: UpdateScheduleUseCase,
private val deleteSchedulesUseCase: DeleteSchedulesUseCase,
getAllScheduleFlow: GetAllScheduleFlowUseCase
) : ViewModel() {
sealed class Event {
data class DeleteSchedules(val schedules: List<Schedule>) : Event()
}
private val _event = MutableSharedFlow<Event>()
val event = _event.asSharedFlow()
private val multiSelectedSchedules = MutableStateFlow<Set<Schedule>>(emptySet())
val schedules = getAllScheduleFlow().stateIn(
scope = viewModelScope, SharingStarted.WhileSubscribed(5000L),
initialValue = emptyList()
)
val scheduleColumnState = combine(
multiSelectedSchedules, schedules
) { multiSelectedSchedules, schedules ->
ScheduleColumnState(
schedules = schedules,
isMultiSelecting = multiSelectedSchedules.isNotEmpty(),
multiSelectedSchedules = multiSelectedSchedules,
onSelectSchedule = ::selectSchedule,
selectAllSchedules = ::selectAllSchedules,
cancelMultiSelecting = ::cancelMultiSelecting,
onCheckedChange = ::checkSchedule,
deleteSchedules = ::deleteSchedules
)
}.stateIn(
scope = viewModelScope, SharingStarted.WhileSubscribed(5000L),
initialValue = ScheduleColumnState(
schedules = schedules.value,
isMultiSelecting = multiSelectedSchedules.value.isNotEmpty(),
multiSelectedSchedules = multiSelectedSchedules.value,
onSelectSchedule = ::selectSchedule,
selectAllSchedules = ::selectAllSchedules,
cancelMultiSelecting = ::cancelMultiSelecting,
onCheckedChange = ::checkSchedule,
deleteSchedules = ::deleteSchedules
)
)
init {
deleteSchedulesUseCase.deleteSchedulesEvent.onEach {
_event.emit(Event.DeleteSchedules(it))
}.launchIn(viewModelScope)
}
private fun deleteSchedules(schedules: List<Schedule>) {
viewModelScope.launch {
deleteSchedulesUseCase(schedules)
}
}
private fun updateSchedule(schedule: Schedule) {
viewModelScope.launch {
updateScheduleUseCase(schedule)
cancelMultiSelecting()
}
}
private fun checkSchedule(schedule: Schedule, checked: Boolean) {
updateSchedule(schedule = schedule.copy(isfinish = checked))
}
private fun selectSchedule(schedule: Schedule, select: Boolean) {
multiSelectedSchedules.value = multiSelectedSchedules.value.toMutableSet().apply {
if (select) add(schedule) else remove(schedule)
}
}
private fun selectAllSchedules() {
multiSelectedSchedules.value = schedules.value.toSet()
}
private fun cancelMultiSelecting() {
multiSelectedSchedules.value = emptySet()
}
} | 1 | null | 27 | 94 | 4b5c62cec0913b198ddd7c8df25a403bc6eda9f8 | 3,459 | LittleGooseOffice | MIT License |
custom-komapper-jdbc-change/src/main/kotlin/momosetkn/liquibase/kotlin/change/CustomKomapperJdbcChange.kt | momosetkn | 844,062,460 | false | {"Kotlin": 361938} | package momosetkn.liquibase.kotlin.change
import liquibase.change.custom.CustomChange
import liquibase.change.custom.CustomChangeWrapper
import liquibase.change.custom.setCustomChange
import liquibase.exception.ValidationErrors
import momosetkn.liquibase.kotlin.dsl.ChangeSetDsl
fun ChangeSetDsl.customKomapperJdbcChange(
confirmationMessage: String = "Executed CustomKomapperChange.",
rollback: ((org.komapper.jdbc.JdbcDatabase) -> Unit)? = null,
validate: (org.komapper.jdbc.JdbcDatabase) -> ValidationErrors = { ValidationErrors() },
execute: (org.komapper.jdbc.JdbcDatabase) -> Unit,
) {
val change = if (rollback != null) {
val define = CustomRollbackableTaskChangeDefineImpl(
execute,
validate,
rollback,
confirmationMessage,
)
RollbackTaskCustomChange(define)
} else {
val define = CustomTaskChangeDefineImpl(
execute,
validate,
confirmationMessage,
)
ForwardOnlyTaskCustomChange(define)
}
addChange(change)
}
private fun ChangeSetDsl.addChange(change: CustomChange) {
val customChangeWrapper = this.changeSetSupport.createChange("customChange") as CustomChangeWrapper
customChangeWrapper.setCustomChange(change)
changeSetSupport.addChange(customChangeWrapper)
}
| 2 | Kotlin | 1 | 3 | 283589789d8baa7b1e06489811c8bd548fc611a1 | 1,349 | liquibase-kotlin | Apache License 2.0 |
router/src/main/kotlin/com/kamijoucen/cenim/router/service/UserChatService.kt | Kamijoucen | 282,948,242 | false | null | package com.kamijoucen.cenim.router.service
import com.kamijoucen.cenim.common.util.MappingKeyGenerator
import com.kamijoucen.cenim.message.msg.Message
import com.kamijoucen.cenim.router.domain.UserImpl
import com.kamijoucen.cenim.router.exception.HistoryNotFoundException
import com.kamijoucen.cenim.router.manager.RouterContext
import com.kamijoucen.cenim.router.util.MsgUtil
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
@Component
class UserChatService {
@Autowired
private lateinit var routerContext: RouterContext
/**
* 发送消息
* @param msg 待发送的消息
*/
fun senMsg(msg: Message) {
val user = routerContext.userManager.get(msg.header.fromId)
if (user?.isConnect() == false) {
TODO("put offline msg")
}
routerContext.chatHistoryManager.setHistory(msg.header.fromId, msg)
val destUser = routerContext.userManager.get(msg.header.destId)
// 如果目标用户登陆在本节点则不进行转发消息
if (destUser != null) {
receiveMsg(msg)
return
}
val conn = routerContext.routerToServiceServerConnManager.getConn()
if (conn != null) {
MsgUtil.sendMsg(msg, conn)
} else {
// log.error("router to service conn not fount!")
}
}
/**
* @param msg 待接收的消息
*/
fun receiveMsg(msg: Message) {
try {
routerContext.chatHistoryManager.setHistory(msg.header.destId, msg)
} catch (ex: HistoryNotFoundException) {
TODO("offline")
}
val netId = routerContext.cacheManager.get(
MappingKeyGenerator.clientToUser(msg.header.destId.toString())) ?: return
val conn = routerContext.clientToRouterConnManager.getConn(netId)
if (conn != null) {
MsgUtil.sendMsg(msg, conn)
} else {
TODO("offline")
}
}
} | 0 | Kotlin | 0 | 1 | 834b7e433f54ed856c9f17590eb7d877c85cc043 | 1,946 | CenIM | Apache License 2.0 |
BaseExtend/src/main/java/com/chen/baseextend/bean/project/AppealImageBean.kt | chen397254698 | 268,411,455 | false | null | package com.chen.baseextend.bean.project
import com.chen.basemodule.basem.BaseBean
/**
* Created by chen on 2019/8/23
**/
data class AppealImageBean(
val index: Int? = null,//排序
val image : String? = null//步骤类型 1.网址 2.二维码 3.数据复制 4.图文说明 5.验证图 6.收集信息 ,
):BaseBean() | 1 | null | 14 | 47 | 85ffc5e307c6171767e14bbfaf992b8d62ec1cc6 | 284 | EasyAndroid | Apache License 2.0 |
ackpine-splits/src/main/kotlin/ru/solrudev/ackpine/splits/parsing/AndroidManifest.kt | solrudev | 641,599,463 | false | null | package ru.solrudev.ackpine.splits.parsing
import androidx.annotation.RestrictTo
private const val ANDROID_NAMESPACE = "http://schemas.android.com/apk/res/android"
@RestrictTo(RestrictTo.Scope.LIBRARY)
internal class AndroidManifest internal constructor(private val manifest: Map<String, String>) {
@get:JvmSynthetic
internal val splitName: String
get() = manifest["split"].orEmpty()
@get:JvmSynthetic
internal val packageName: String
get() = manifest.getValue("package")
@get:JvmSynthetic
internal val versionCode: Long
get() = manifest.getValue("$ANDROID_NAMESPACE:versionCode").toLong()
@get:JvmSynthetic
internal val versionName: String
get() = manifest["$ANDROID_NAMESPACE:versionName"].orEmpty()
@get:JvmSynthetic
internal val isFeatureSplit: Boolean
get() = manifest["$ANDROID_NAMESPACE:isFeatureSplit"]?.toBooleanStrict() ?: false
@get:JvmSynthetic
internal val configForSplit: String
get() = manifest["configForSplit"].orEmpty()
} | 0 | Kotlin | 0 | 0 | 99a814e62aed4e6614868878cf383014866180d1 | 972 | Ackpine | Apache License 2.0 |
app/src/main/java/org/coepi/android/repo/reportsupdate/NewAlertsNotificationShower.kt | Co-Epi | 249,138,523 | false | null | package org.coepi.android.repo.reportsupdate
import org.coepi.android.R.drawable
import org.coepi.android.R.plurals
import org.coepi.android.R.string
import org.coepi.android.system.Resources
import org.coepi.android.system.intent.IntentKey.NOTIFICATION_INFECTION_ARGS
import org.coepi.android.system.intent.IntentNoValue
import org.coepi.android.system.log.log
import org.coepi.android.ui.notifications.AppNotificationChannels
import org.coepi.android.ui.notifications.NotificationConfig
import org.coepi.android.ui.notifications.NotificationIntentArgs
import org.coepi.android.ui.notifications.NotificationPriority.HIGH
import org.coepi.android.ui.notifications.NotificationsShower
interface NewAlertsNotificationShower {
fun showNotification(newAlertsCount: Int, notificationId: Int)
fun cancelNotification(notificationId: Int)
}
class NewAlertsNotificationShowerImpl(
private val notificationsShower: NotificationsShower,
private val notificationChannelsInitializer: AppNotificationChannels,
private val resources: Resources
) : NewAlertsNotificationShower {
override fun showNotification(newAlertsCount: Int, notificationId: Int) {
log.d("Showing notification...")
notificationsShower.showNotification(notificationConfiguration(newAlertsCount, notificationId))
}
override fun cancelNotification(notificationId: Int) {
log.d("Canceling notification $notificationId")
notificationsShower.cancelNotification(notificationId)
}
private fun notificationConfiguration(newAlertsCount: Int, noticationId: Int): NotificationConfig =
NotificationConfig(
drawable.ic_launcher_foreground,
noticationId,
resources.getString(string.infection_notification_title),
resources.getQuantityString(plurals.alerts_new_notifications_count, newAlertsCount),
HIGH,
notificationChannelsInitializer.reportsChannelId,
NotificationIntentArgs(NOTIFICATION_INFECTION_ARGS, IntentNoValue())
)
} | 14 | Kotlin | 20 | 32 | 54cffa441d27d18ba33d7719a34dc9b5c9125262 | 2,044 | app-android | MIT License |
app/src/main/java/org/coepi/android/repo/reportsupdate/NewAlertsNotificationShower.kt | Co-Epi | 249,138,523 | false | null | package org.coepi.android.repo.reportsupdate
import org.coepi.android.R.drawable
import org.coepi.android.R.plurals
import org.coepi.android.R.string
import org.coepi.android.system.Resources
import org.coepi.android.system.intent.IntentKey.NOTIFICATION_INFECTION_ARGS
import org.coepi.android.system.intent.IntentNoValue
import org.coepi.android.system.log.log
import org.coepi.android.ui.notifications.AppNotificationChannels
import org.coepi.android.ui.notifications.NotificationConfig
import org.coepi.android.ui.notifications.NotificationIntentArgs
import org.coepi.android.ui.notifications.NotificationPriority.HIGH
import org.coepi.android.ui.notifications.NotificationsShower
interface NewAlertsNotificationShower {
fun showNotification(newAlertsCount: Int, notificationId: Int)
fun cancelNotification(notificationId: Int)
}
class NewAlertsNotificationShowerImpl(
private val notificationsShower: NotificationsShower,
private val notificationChannelsInitializer: AppNotificationChannels,
private val resources: Resources
) : NewAlertsNotificationShower {
override fun showNotification(newAlertsCount: Int, notificationId: Int) {
log.d("Showing notification...")
notificationsShower.showNotification(notificationConfiguration(newAlertsCount, notificationId))
}
override fun cancelNotification(notificationId: Int) {
log.d("Canceling notification $notificationId")
notificationsShower.cancelNotification(notificationId)
}
private fun notificationConfiguration(newAlertsCount: Int, noticationId: Int): NotificationConfig =
NotificationConfig(
drawable.ic_launcher_foreground,
noticationId,
resources.getString(string.infection_notification_title),
resources.getQuantityString(plurals.alerts_new_notifications_count, newAlertsCount),
HIGH,
notificationChannelsInitializer.reportsChannelId,
NotificationIntentArgs(NOTIFICATION_INFECTION_ARGS, IntentNoValue())
)
} | 14 | Kotlin | 20 | 32 | 54cffa441d27d18ba33d7719a34dc9b5c9125262 | 2,044 | app-android | MIT License |
sdk-gigya/src/main/java/com/ownid/sdk/internal/OwnIdGigyaIntegration.kt | OwnID | 414,235,878 | false | {"Kotlin": 564879, "Java": 13542} | package com.ownid.sdk.internal
import androidx.annotation.RestrictTo
import androidx.core.os.LocaleListCompat
import com.gigya.android.sdk.Gigya
import com.gigya.android.sdk.GigyaLoginCallback
import com.gigya.android.sdk.account.models.GigyaAccount
import com.gigya.android.sdk.api.GigyaApiResponse
import com.gigya.android.sdk.network.GigyaError
import com.gigya.android.sdk.session.SessionInfo
import com.ownid.sdk.GigyaRegistrationParameters
import com.ownid.sdk.InternalOwnIdAPI
import com.ownid.sdk.OwnIdCallback
import com.ownid.sdk.OwnIdCore
import com.ownid.sdk.OwnIdCoreImpl
import com.ownid.sdk.OwnIdGigya
import com.ownid.sdk.OwnIdResponse
import com.ownid.sdk.RegistrationParameters
import com.ownid.sdk.event.LoginData
import com.ownid.sdk.exception.GigyaException
import com.ownid.sdk.exception.OwnIdException
import com.ownid.sdk.internal.events.Metadata
import com.ownid.sdk.internal.events.Metric
import com.ownid.sdk.internal.flow.OwnIdFlowType
import org.json.JSONObject
import java.util.Locale
/**
* Class extends [OwnIdCore], holds [Gigya] instance and implements Register/Login flows with Gigya.
*
* Recommended to be a single instance per-application per-configuration.
*/
@InternalOwnIdAPI
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
internal class OwnIdGigyaImpl<A : GigyaAccount>(
override val ownIdCore: OwnIdCore,
private val gigya: Gigya<A>,
) : OwnIdGigya {
/**
* Performs OwnID Registration flow and register new user in Gigya. User password will be generated automatically.
*
* @param loginId User email for Gigya account.
* @param params [GigyaRegistrationParameters] (optional) Additional parameters for registration.
* @param ownIdResponse [OwnIdResponse] from OwnID Register flow.
* @param callback [OwnIdCallback] with `null` value of Registration flow result or with [OwnIdException] cause value if Registration flow failed.
*/
override fun register(loginId: String, params: RegistrationParameters?, ownIdResponse: OwnIdResponse, callback: OwnIdCallback<LoginData?>) {
OwnIdInternalLogger.logD(this, "register", "Invoked")
val paramsWithOwnIdData = runCatching {
val gigyaParams = (params as? GigyaRegistrationParameters)?.params ?: emptyMap()
val dataJson = if (gigyaParams.containsKey("data").not()) JSONObject()
else JSONObject(java.lang.String.valueOf(gigyaParams["data"]))
val ownIdDataFieldName = JSONObject(ownIdResponse.payload.metadata).getString("dataField")
dataJson.put(ownIdDataFieldName, JSONObject(ownIdResponse.payload.data))
val paramsWithOwnIdData = gigyaParams.toMutableMap().apply { put("data", dataJson.toString()) }
val profileJson = if (gigyaParams.containsKey("profile").not()) JSONObject()
else JSONObject(java.lang.String.valueOf(gigyaParams["profile"]))
if (profileJson.has("locale")) return@runCatching paramsWithOwnIdData
val localeList = LocaleListCompat.forLanguageTags(ownIdResponse.languageTag)
if (localeList.isEmpty) return@runCatching paramsWithOwnIdData
val language = Locale(localeList.get(0)?.language ?: Locale.ENGLISH.language).toLanguageTag()
if (language.isBlank() || language == "und") return@runCatching paramsWithOwnIdData
profileJson.put("locale", language)
paramsWithOwnIdData.apply { put("profile", profileJson.toString()) }
}.getOrElse {
callback(Result.failure(OwnIdException("Register: Error creating gigya params", it)))
return
}
val password = <PASSWORD>(20)
gigya.register(loginId, password, paramsWithOwnIdData, object : GigyaLoginCallback<A>() {
override fun onSuccess(account: A?) {
callback(Result.success(null))
}
override fun onError(error: GigyaError?) {
if (error == null) {
callback(Result.failure(OwnIdException("Register.onError: null")))
} else {
if (error.errorCode in listOf(206001, 206002, 206006, 403102, 403101)) {
(ownIdCore as OwnIdCoreImpl).eventsService.sendMetric(
OwnIdFlowType.REGISTER, Metric.EventType.Track, "User is Registered",
Metadata(authType = ownIdResponse.flowInfo.authType), this::class.java.simpleName, error.localizedMessage
)
}
callback(Result.failure(GigyaException(error, "Register: [${error.errorCode}] ${error.data}")))
}
}
})
}
/**
* Performs OwnID Login flow and Login new user in Gigya.
*
* @param ownIdResponse [OwnIdResponse] from OwnID Login flow.
* @param callback [OwnIdCallback] with `null` value of Login flow result or with [OwnIdException] cause value if Login flow failed.
*/
override fun login(ownIdResponse: OwnIdResponse, callback: OwnIdCallback<LoginData?>) {
OwnIdInternalLogger.logD(this, "login", "Invoked")
runCatching {
val dataJson = JSONObject(ownIdResponse.payload.data)
when {
dataJson.has("sessionInfo") -> {
val payloadJson = dataJson.getJSONObject("sessionInfo")
val sessionSecret = payloadJson.getString("sessionSecret")
val sessionToken = payloadJson.getString("sessionToken")
val expiresInValue = payloadJson.optLong("expires_in")
val expirationTimeValue = payloadJson.optLong("expirationTime")
val expirationTime = when {
expiresInValue > 0L -> expiresInValue
expirationTimeValue > 0L -> expirationTimeValue
else -> 0L
}
gigya.setSession(SessionInfo(sessionSecret, sessionToken, expirationTime))
}
dataJson.has("errorJson") -> {
val errorJsonObject = JSONObject(dataJson.getString("errorJson"))
val gigyaError = GigyaError.fromResponse(GigyaApiResponse(errorJsonObject.toString()))
throw GigyaException(gigyaError, "Login: [${gigyaError.errorCode}] ${gigyaError.localizedMessage}")
}
else -> throw OwnIdException("Unexpected payload data")
}
}
.onSuccess { callback(Result.success(null)) }
.onFailure {
OwnIdInternalLogger.logD(this, "login", "Payload data: ${ownIdResponse.payload.data}")
if (it is GigyaException && it.gigyaError.errorCode in listOf(206001, 206002, 206006, 403102, 403101)) {
(ownIdCore as OwnIdCoreImpl).eventsService.sendMetric(
OwnIdFlowType.LOGIN, Metric.EventType.Track, "User is Logged in",
Metadata(authType = ownIdResponse.flowInfo.authType), this::class.java.simpleName, it.gigyaError.localizedMessage
)
}
if (it is OwnIdException) callback(Result.failure(it))
else callback(Result.failure(OwnIdException("Login: Error in JSON", it)))
}
}
} | 0 | Kotlin | 1 | 1 | e49b09660dc1a4fd012e4c0eb2c2bf855912ae1d | 7,379 | ownid-android-sdk | Apache License 2.0 |
sources/Currency.kt | fluidsonic | 289,522,609 | false | null | package io.fluidsonic.currency
public class Currency private constructor(
public val code: CurrencyCode,
public val defaultFractionDigits: Int,
public val numericCode: Int,
) {
override fun toString(): String =
code.toString()
public companion object {
// https://www.currency-iso.org/en/home/tables/table-a1.html
public val all: Set<Currency> = hashSetOf(
make(code = "AED", defaultFractionDigits = 2, numericCode = 784),
make(code = "AFN", defaultFractionDigits = 2, numericCode = 971),
make(code = "ALL", defaultFractionDigits = 2, numericCode = 8),
make(code = "AMD", defaultFractionDigits = 2, numericCode = 51),
make(code = "ANG", defaultFractionDigits = 2, numericCode = 532),
make(code = "AOA", defaultFractionDigits = 2, numericCode = 973),
make(code = "ARS", defaultFractionDigits = 2, numericCode = 32),
make(code = "AUD", defaultFractionDigits = 2, numericCode = 36),
make(code = "AWG", defaultFractionDigits = 2, numericCode = 533),
make(code = "AZN", defaultFractionDigits = 2, numericCode = 944),
make(code = "BAM", defaultFractionDigits = 2, numericCode = 977),
make(code = "BBD", defaultFractionDigits = 2, numericCode = 52),
make(code = "BDT", defaultFractionDigits = 2, numericCode = 50),
make(code = "BGN", defaultFractionDigits = 2, numericCode = 975),
make(code = "BHD", defaultFractionDigits = 3, numericCode = 48),
make(code = "BIF", defaultFractionDigits = 0, numericCode = 108),
make(code = "BMD", defaultFractionDigits = 2, numericCode = 60),
make(code = "BND", defaultFractionDigits = 2, numericCode = 96),
make(code = "BOB", defaultFractionDigits = 2, numericCode = 68),
make(code = "BOV", defaultFractionDigits = 2, numericCode = 984),
make(code = "BRL", defaultFractionDigits = 2, numericCode = 986),
make(code = "BSD", defaultFractionDigits = 2, numericCode = 44),
make(code = "BTN", defaultFractionDigits = 2, numericCode = 64),
make(code = "BWP", defaultFractionDigits = 2, numericCode = 72),
make(code = "BYN", defaultFractionDigits = 2, numericCode = 933),
make(code = "BZD", defaultFractionDigits = 2, numericCode = 84),
make(code = "CAD", defaultFractionDigits = 2, numericCode = 124),
make(code = "CDF", defaultFractionDigits = 2, numericCode = 976),
make(code = "CHE", defaultFractionDigits = 2, numericCode = 947),
make(code = "CHF", defaultFractionDigits = 2, numericCode = 756),
make(code = "CHW", defaultFractionDigits = 2, numericCode = 948),
make(code = "CLF", defaultFractionDigits = 4, numericCode = 990),
make(code = "CLP", defaultFractionDigits = 0, numericCode = 152),
make(code = "CNY", defaultFractionDigits = 2, numericCode = 156),
make(code = "COP", defaultFractionDigits = 2, numericCode = 170),
make(code = "COU", defaultFractionDigits = 2, numericCode = 970),
make(code = "CRC", defaultFractionDigits = 2, numericCode = 188),
make(code = "CUC", defaultFractionDigits = 2, numericCode = 931),
make(code = "CUP", defaultFractionDigits = 2, numericCode = 192),
make(code = "CVE", defaultFractionDigits = 2, numericCode = 132),
make(code = "CZK", defaultFractionDigits = 2, numericCode = 203),
make(code = "DJF", defaultFractionDigits = 0, numericCode = 262),
make(code = "DKK", defaultFractionDigits = 2, numericCode = 208),
make(code = "DOP", defaultFractionDigits = 2, numericCode = 214),
make(code = "DZD", defaultFractionDigits = 2, numericCode = 12),
make(code = "EGP", defaultFractionDigits = 2, numericCode = 818),
make(code = "ERN", defaultFractionDigits = 2, numericCode = 232),
make(code = "ETB", defaultFractionDigits = 2, numericCode = 230),
make(code = "EUR", defaultFractionDigits = 2, numericCode = 978),
make(code = "FJD", defaultFractionDigits = 2, numericCode = 242),
make(code = "FKP", defaultFractionDigits = 2, numericCode = 238),
make(code = "GBP", defaultFractionDigits = 2, numericCode = 826),
make(code = "GEL", defaultFractionDigits = 2, numericCode = 981),
make(code = "GHS", defaultFractionDigits = 2, numericCode = 936),
make(code = "GIP", defaultFractionDigits = 2, numericCode = 292),
make(code = "GMD", defaultFractionDigits = 2, numericCode = 270),
make(code = "GNF", defaultFractionDigits = 0, numericCode = 324),
make(code = "GTQ", defaultFractionDigits = 2, numericCode = 320),
make(code = "GYD", defaultFractionDigits = 2, numericCode = 328),
make(code = "HKD", defaultFractionDigits = 2, numericCode = 344),
make(code = "HNL", defaultFractionDigits = 2, numericCode = 340),
make(code = "HRK", defaultFractionDigits = 2, numericCode = 191),
make(code = "HTG", defaultFractionDigits = 2, numericCode = 332),
make(code = "HUF", defaultFractionDigits = 2, numericCode = 348),
make(code = "IDR", defaultFractionDigits = 2, numericCode = 360),
make(code = "ILS", defaultFractionDigits = 2, numericCode = 376),
make(code = "INR", defaultFractionDigits = 2, numericCode = 356),
make(code = "IQD", defaultFractionDigits = 3, numericCode = 368),
make(code = "IRR", defaultFractionDigits = 2, numericCode = 364),
make(code = "ISK", defaultFractionDigits = 0, numericCode = 352),
make(code = "JMD", defaultFractionDigits = 2, numericCode = 388),
make(code = "JOD", defaultFractionDigits = 3, numericCode = 400),
make(code = "JPY", defaultFractionDigits = 0, numericCode = 392),
make(code = "KES", defaultFractionDigits = 2, numericCode = 404),
make(code = "KGS", defaultFractionDigits = 2, numericCode = 417),
make(code = "KHR", defaultFractionDigits = 2, numericCode = 116),
make(code = "KMF", defaultFractionDigits = 0, numericCode = 174),
make(code = "KPW", defaultFractionDigits = 2, numericCode = 408),
make(code = "KRW", defaultFractionDigits = 0, numericCode = 410),
make(code = "KWD", defaultFractionDigits = 3, numericCode = 414),
make(code = "KYD", defaultFractionDigits = 2, numericCode = 136),
make(code = "KZT", defaultFractionDigits = 2, numericCode = 398),
make(code = "LAK", defaultFractionDigits = 2, numericCode = 418),
make(code = "LBP", defaultFractionDigits = 2, numericCode = 422),
make(code = "LKR", defaultFractionDigits = 2, numericCode = 144),
make(code = "LRD", defaultFractionDigits = 2, numericCode = 430),
make(code = "LSL", defaultFractionDigits = 2, numericCode = 426),
make(code = "LYD", defaultFractionDigits = 3, numericCode = 434),
make(code = "MAD", defaultFractionDigits = 2, numericCode = 504),
make(code = "MDL", defaultFractionDigits = 2, numericCode = 498),
make(code = "MGA", defaultFractionDigits = 2, numericCode = 969),
make(code = "MKD", defaultFractionDigits = 2, numericCode = 807),
make(code = "MMK", defaultFractionDigits = 2, numericCode = 104),
make(code = "MNT", defaultFractionDigits = 2, numericCode = 496),
make(code = "MOP", defaultFractionDigits = 2, numericCode = 446),
make(code = "MRU", defaultFractionDigits = 2, numericCode = 929),
make(code = "MUR", defaultFractionDigits = 2, numericCode = 480),
make(code = "MVR", defaultFractionDigits = 2, numericCode = 462),
make(code = "MWK", defaultFractionDigits = 2, numericCode = 454),
make(code = "MXN", defaultFractionDigits = 2, numericCode = 484),
make(code = "MXV", defaultFractionDigits = 2, numericCode = 979),
make(code = "MYR", defaultFractionDigits = 2, numericCode = 458),
make(code = "MZN", defaultFractionDigits = 2, numericCode = 943),
make(code = "NAD", defaultFractionDigits = 2, numericCode = 516),
make(code = "NGN", defaultFractionDigits = 2, numericCode = 566),
make(code = "NIO", defaultFractionDigits = 2, numericCode = 558),
make(code = "NOK", defaultFractionDigits = 2, numericCode = 578),
make(code = "NPR", defaultFractionDigits = 2, numericCode = 524),
make(code = "NZD", defaultFractionDigits = 2, numericCode = 554),
make(code = "OMR", defaultFractionDigits = 3, numericCode = 512),
make(code = "PAB", defaultFractionDigits = 2, numericCode = 590),
make(code = "PEN", defaultFractionDigits = 2, numericCode = 604),
make(code = "PGK", defaultFractionDigits = 2, numericCode = 598),
make(code = "PHP", defaultFractionDigits = 2, numericCode = 608),
make(code = "PKR", defaultFractionDigits = 2, numericCode = 586),
make(code = "PLN", defaultFractionDigits = 2, numericCode = 985),
make(code = "PYG", defaultFractionDigits = 0, numericCode = 600),
make(code = "QAR", defaultFractionDigits = 2, numericCode = 634),
make(code = "RON", defaultFractionDigits = 2, numericCode = 946),
make(code = "RSD", defaultFractionDigits = 2, numericCode = 941),
make(code = "RUB", defaultFractionDigits = 2, numericCode = 643),
make(code = "RWF", defaultFractionDigits = 0, numericCode = 646),
make(code = "SAR", defaultFractionDigits = 2, numericCode = 682),
make(code = "SBD", defaultFractionDigits = 2, numericCode = 90),
make(code = "SCR", defaultFractionDigits = 2, numericCode = 690),
make(code = "SDG", defaultFractionDigits = 2, numericCode = 938),
make(code = "SEK", defaultFractionDigits = 2, numericCode = 752),
make(code = "SGD", defaultFractionDigits = 2, numericCode = 702),
make(code = "SHP", defaultFractionDigits = 2, numericCode = 654),
make(code = "SLL", defaultFractionDigits = 2, numericCode = 694),
make(code = "SOS", defaultFractionDigits = 2, numericCode = 706),
make(code = "SRD", defaultFractionDigits = 2, numericCode = 968),
make(code = "SSP", defaultFractionDigits = 2, numericCode = 728),
make(code = "STN", defaultFractionDigits = 2, numericCode = 930),
make(code = "SVC", defaultFractionDigits = 2, numericCode = 222),
make(code = "SYP", defaultFractionDigits = 2, numericCode = 760),
make(code = "SZL", defaultFractionDigits = 2, numericCode = 748),
make(code = "THB", defaultFractionDigits = 2, numericCode = 764),
make(code = "TJS", defaultFractionDigits = 2, numericCode = 972),
make(code = "TMT", defaultFractionDigits = 2, numericCode = 934),
make(code = "TND", defaultFractionDigits = 3, numericCode = 788),
make(code = "TOP", defaultFractionDigits = 2, numericCode = 776),
make(code = "TRY", defaultFractionDigits = 2, numericCode = 949),
make(code = "TTD", defaultFractionDigits = 2, numericCode = 780),
make(code = "TWD", defaultFractionDigits = 2, numericCode = 901),
make(code = "TZS", defaultFractionDigits = 2, numericCode = 834),
make(code = "UAH", defaultFractionDigits = 2, numericCode = 980),
make(code = "UGX", defaultFractionDigits = 0, numericCode = 800),
make(code = "USD", defaultFractionDigits = 2, numericCode = 840),
make(code = "USN", defaultFractionDigits = 2, numericCode = 997),
make(code = "UYI", defaultFractionDigits = 0, numericCode = 940),
make(code = "UYU", defaultFractionDigits = 2, numericCode = 858),
make(code = "UYW", defaultFractionDigits = 4, numericCode = 927),
make(code = "UZS", defaultFractionDigits = 2, numericCode = 860),
make(code = "VES", defaultFractionDigits = 2, numericCode = 928),
make(code = "VND", defaultFractionDigits = 0, numericCode = 704),
make(code = "VUV", defaultFractionDigits = 0, numericCode = 548),
make(code = "WST", defaultFractionDigits = 2, numericCode = 882),
make(code = "XAF", defaultFractionDigits = 0, numericCode = 950),
make(code = "XAG", defaultFractionDigits = -1, numericCode = 961),
make(code = "XAU", defaultFractionDigits = -1, numericCode = 959),
make(code = "XBA", defaultFractionDigits = -1, numericCode = 955),
make(code = "XBB", defaultFractionDigits = -1, numericCode = 956),
make(code = "XBC", defaultFractionDigits = -1, numericCode = 957),
make(code = "XBD", defaultFractionDigits = -1, numericCode = 958),
make(code = "XCD", defaultFractionDigits = 2, numericCode = 951),
make(code = "XDR", defaultFractionDigits = -1, numericCode = 960),
make(code = "XOF", defaultFractionDigits = 0, numericCode = 952),
make(code = "XPD", defaultFractionDigits = -1, numericCode = 964),
make(code = "XPF", defaultFractionDigits = 0, numericCode = 953),
make(code = "XPT", defaultFractionDigits = -1, numericCode = 962),
make(code = "XSU", defaultFractionDigits = -1, numericCode = 994),
make(code = "XTS", defaultFractionDigits = -1, numericCode = 963),
make(code = "XUA", defaultFractionDigits = -1, numericCode = 965),
make(code = "XXX", defaultFractionDigits = -1, numericCode = 999),
make(code = "YER", defaultFractionDigits = 2, numericCode = 886),
make(code = "ZAR", defaultFractionDigits = 2, numericCode = 710),
make(code = "ZMW", defaultFractionDigits = 2, numericCode = 967),
make(code = "ZWL", defaultFractionDigits = 2, numericCode = 932),
)
private val allByCode: Map<CurrencyCode, Currency> = all.associateByTo(hashMapOf()) { it.code }
private fun make(code: String, defaultFractionDigits: Int, numericCode: Int): Currency =
Currency(
code = CurrencyCode(code),
defaultFractionDigits = defaultFractionDigits,
numericCode = numericCode
)
public fun forCode(code: CurrencyCode): Currency =
forCodeOrNull(code) ?: error("Invalid ISO 4217 currency code: $code")
public fun forCodeOrNull(code: CurrencyCode): Currency? =
allByCode[code]
public fun forCode(code: String): Currency =
forCodeOrNull(CurrencyCode.parse(code)) ?: error("Invalid ISO 4217 currency code: $code")
public fun forCodeOrNull(code: String): Currency? =
CurrencyCode.parseOrNull(code)?.let(::forCodeOrNull)
}
}
| 0 | Kotlin | 2 | 6 | 5f3147484a514dfd20565614e2be8d077e5ebe04 | 13,516 | fluid-currency | Apache License 2.0 |
Log/src/main/java/com/chatwaifu/log/IChatLogDbApi.kt | Voine | 603,770,379 | false | null | package com.chatwaifu.log
import com.chatwaifu.log.room.ChatMessage
/**
* Description: ChatLogApi
* Author: Voine
* Date: 2023/3/13
*/
interface IChatLogDbApi {
fun insertChatLog(
characterName: String,
isFromMe: Boolean,
chatMessage: String,
completionToken: Int = -1,
promptTokens: Int = -1
) {}
fun insertChatLog(chatMessage: ChatMessage) {}
fun getAllChatLog(characterName: String) = emptyList<ChatMessage>()
fun getChatLogWithLimit(characterName: String, limit: Int) = emptyList<ChatMessage>()
fun onLoadMoreChatLog(characterName: String, lastMessageId: Long, limit: Int) = emptyList<ChatMessage>()
} | 8 | C++ | 100 | 951 | 14092ac66c2afd51de06bb126fd102cec869eb8e | 679 | ChatWaifu_Mobile | MIT License |
src/test/kotlin/no/nav/pensjon/kalkulator/tjenestepensjon/client/esb/EsbTjenestepensjonClientTest.kt | navikt | 596,104,195 | false | null | package no.nav.pensjon.kalkulator.tjenestepensjon.client.esb
import no.nav.pensjon.kalkulator.mock.MockSecurityConfiguration.Companion.arrangeSecurityContext
import no.nav.pensjon.kalkulator.mock.PersonFactory.pid
import no.nav.pensjon.kalkulator.mock.WebClientTest
import no.nav.pensjon.kalkulator.mock.XmlMapperFactory.xmlMapper
import no.nav.pensjon.kalkulator.tech.security.egress.token.unt.client.UsernameTokenClient
import no.nav.pensjon.kalkulator.tech.security.egress.token.unt.client.fssgw.dto.UsernameTokenDto
import no.nav.pensjon.kalkulator.tech.trace.CallIdGenerator
import no.nav.pensjon.kalkulator.tech.web.EgressException
import no.nav.pensjon.kalkulator.tech.web.WebClientConfig
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.mockito.Mock
import org.mockito.Mockito.`when`
import org.springframework.http.HttpStatus
import org.springframework.test.context.junit.jupiter.SpringExtension
import java.time.LocalDate
/**
* ESB = Enterprise Service Bus (tjenestebuss)
*/
@ExtendWith(SpringExtension::class)
class EsbTjenestepensjonClientTest : WebClientTest() {
private lateinit var client: EsbTjenestepensjonClient
@Mock
private lateinit var usernameTokenClient: UsernameTokenClient
@Mock
private lateinit var callIdGenerator: CallIdGenerator
@BeforeEach
fun initialize() {
`when`(usernameTokenClient.fetchUsernameToken()).thenReturn(UsernameTokenDto(WS_SECURITY_ELEMENT))
`when`(callIdGenerator.newId()).thenReturn("id1")
client = EsbTjenestepensjonClient(
baseUrl(),
usernameTokenClient,
WebClientConfig().webClientForSoapRequests(),
xmlMapper(),
callIdGenerator,
RETRY_ATTEMPTS.toString()
)
}
@Test
fun `harTjenestepensjonsforhold returns true when forhold exists`() {
arrangeSecurityContext()
arrange(ettForholdResponse())
val forholdExists = client.harTjenestepensjonsforhold(pid, dato)
assertTrue(forholdExists)
}
@Test
fun `harTjenestepensjonsforhold returns false when ingen forhold`() {
arrangeSecurityContext()
arrange(ingenForholdResponse())
val forholdExists = client.harTjenestepensjonsforhold(pid, dato)
assertFalse(forholdExists)
}
@Test
fun `harTjenestepensjonsforhold retries in case of server error`() {
arrangeSecurityContext()
arrange(jsonResponse(HttpStatus.INTERNAL_SERVER_ERROR).setBody("Feil"))
arrange(ingenForholdResponse())
val forholdExists = client.harTjenestepensjonsforhold(pid, dato)
assertFalse(forholdExists)
}
@Test
fun `harTjenestepensjonsforhold does not retry in case of client error`() {
arrangeSecurityContext()
arrange(jsonResponse(HttpStatus.BAD_REQUEST).setBody("My bad"))
// No 2nd response arranged, since no retry
val exception = assertThrows(EgressException::class.java) { client.harTjenestepensjonsforhold(pid, dato) }
assertEquals("My bad", exception.message)
}
@Test
fun `harTjenestepensjonsforhold handles server error`() {
arrangeSecurityContext()
arrange(jsonResponse(HttpStatus.INTERNAL_SERVER_ERROR).setBody("Feil"))
arrange(jsonResponse(HttpStatus.INTERNAL_SERVER_ERROR).setBody("Feil")) // for retry
val exception = assertThrows(EgressException::class.java) { client.harTjenestepensjonsforhold(pid, dato) }
assertEquals(
"Failed calling ${baseUrl()}/nav-cons-pen-pselv-tjenestepensjonWeb/sca/PSELVTjenestepensjonWSEXP",
exception.message
)
assertEquals("Feil", (exception.cause as EgressException).message)
}
private companion object {
private const val RETRY_ATTEMPTS = 1
private val dato = LocalDate.of(2023, 1, 1)
private const val WS_SECURITY_ELEMENT =
"""<wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" soapenv:mustUnderstand="1">
<wsse:UsernameToken>
<wsse:Username>srvpselv</wsse:Username>
<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">&secret</wsse:Password>
</wsse:UsernameToken>
</wsse:Security>"""
private const val TJENESTEPENSJONSFORHOLD_XML =
"""<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Body>
<inf:finnTjenestepensjonForholdResponse xmlns:inf="http://nav-cons-pen-pselv-tjenestepensjon/no/nav/inf">
<finnTjenestepensjonForholdResponse>
<fnr>12906498357</fnr>
<tjenestepensjonForholdene>
<forholdId>22598178</forholdId>
<tssEksternId>80000470761</tssEksternId>
<navn>Statens pensjonskasse</navn>
<tpNr>3010</tpNr>
<harUtlandPensjon>false</harUtlandPensjon>
<samtykkeSimuleringKode>N</samtykkeSimuleringKode>
<harSimulering>false</harSimulering>
<tjenestepensjonYtelseListe>
<ytelseId>22587180</ytelseId>
<innmeldtFom>2014-04-01</innmeldtFom>
<ytelseKode>ALDER</ytelseKode>
<ytelseBeskrivelse>ALDER</ytelseBeskrivelse>
<iverksattFom>2022-09-20</iverksattFom>
</tjenestepensjonYtelseListe>
<endringsInfo>
<endretAvId>srvpensjon</endretAvId>
<opprettetAvId>srvpensjon</opprettetAvId>
<endretDato>2022-10-20</endretDato>
<opprettetDato>2022-10-20</opprettetDato>
<kildeId>PP01</kildeId>
</endringsInfo>
<avdelingType>TPOF</avdelingType>
</tjenestepensjonForholdene>
<endringsInfo>
<endretAvId>UNKNOWN</endretAvId>
<opprettetAvId>UNKNOWN</opprettetAvId>
<endretDato>2022-04-20</endretDato>
<opprettetDato>2022-04-20</opprettetDato>
</endringsInfo>
</finnTjenestepensjonForholdResponse>
</inf:finnTjenestepensjonForholdResponse>
</soapenv:Body>
</soapenv:Envelope>"""
private const val INGEN_TJENESTEPENSJONSFORHOLD_XML =
"""<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Body>
<inf:finnTjenestepensjonForholdResponse xmlns:inf="http://nav-cons-pen-pselv-tjenestepensjon/no/nav/inf">
<finnTjenestepensjonForholdResponse>
<fnr>24815797236</fnr>
<endringsInfo>
<endretAvId>srvpensjon</endretAvId>
<opprettetAvId>srvpensjon</opprettetAvId>
<endretDato>2022-11-09</endretDato>
<opprettetDato>2022-11-09</opprettetDato>
</endringsInfo>
</finnTjenestepensjonForholdResponse>
</inf:finnTjenestepensjonForholdResponse>
</soapenv:Body>
</soapenv:Envelope>"""
private const val FAULT_XML = """<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Body>
<soapenv:Fault xmlns:m="http://schemas.xmlsoap.org/soap/envelope/">
<faultcode>m:Server</faultcode>
<faultstring>ServerException</faultstring>
<detail>
<inf:finnTjenestepensjonForhold_faultPenGenerisk xmlns:inf="http://nav-cons-pen-pselv-tjenestepensjon/no/nav/inf">
<errorMessage>Pid validation failed</errorMessage>
<errorSource>Interaction: [invoke,hentTjenestepensjonInfo]</errorSource>
<errorType>Runtime</errorType>
<rootCause>65915200188 is not a valid personal identification number</rootCause>
<dateTimeStamp>Tue Jun 13 15:41:29 CEST 2023</dateTimeStamp>
</inf:finnTjenestepensjonForhold_faultPenGenerisk>
</detail>
</soapenv:Fault>
</soapenv:Body>
</soapenv:Envelope>"""
private fun ettForholdResponse() = xmlResponse().setBody(TJENESTEPENSJONSFORHOLD_XML)
private fun ingenForholdResponse() = xmlResponse().setBody(INGEN_TJENESTEPENSJONSFORHOLD_XML)
private fun faultResponse() = xmlResponse().setBody(FAULT_XML) //TODO fault handling
}
}
| 1 | Kotlin | 0 | 0 | a642602ae4997fb9d88f97464a85a6c3d9c33a89 | 8,891 | pensjonskalkulator-backend | MIT License |
example/android/app/src/main/kotlin/com/share/and/open/url/share_and_open_url_example/MainActivity.kt | bedirhanssaglam | 793,221,095 | false | {"Kotlin": 4911, "Dart": 4644, "Swift": 3521, "Ruby": 2396, "Objective-C": 38} | package com.share.and.open.url.share_and_open_url_example
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity()
| 0 | Kotlin | 0 | 0 | beed895a89aa84ae231c288e0adb409bd12feb85 | 150 | share_and_open_url_plugin | MIT License |
generator-integration-test/src/test/kotlin/com/lsdconsulting/stub/integration/post/AdvancedPostRestControllerIT.kt | lsd-consulting | 592,675,346 | false | null | package com.lsdconsulting.stub.integration.post
import com.fasterxml.jackson.databind.ObjectMapper
import com.github.tomakehurst.wiremock.client.VerificationException
import com.lsdconsulting.stub.integration.BaseRestControllerIT
import com.lsdconsulting.stub.integration.POST_CONTROLLER_URL
import com.lsdconsulting.stub.integration.controller.post.AdvancedPostRestControllerStub
import com.lsdconsulting.stub.integration.model.GreetingRequest
import com.lsdconsulting.stub.integration.model.GreetingResponse
import org.apache.commons.lang3.RandomStringUtils.randomAlphabetic
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.Matchers.`is`
import org.hamcrest.Matchers.notNullValue
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import org.springframework.http.HttpEntity
import org.springframework.http.HttpStatus.NOT_FOUND
import org.springframework.web.client.HttpClientErrorException
class AdvancedPostRestControllerIT : BaseRestControllerIT() {
private val underTest = AdvancedPostRestControllerStub(ObjectMapper())
@Test
fun `should handle post mapping with request body`() {
underTest.verifyPostResourceWithBodyNoInteraction(greetingRequest)
underTest.verifyPostResourceWithBodyNoInteractionWithUrl()
underTest.postResourceWithBody(greetingResponse)
val request = HttpEntity(greetingRequest)
val response =
restTemplate.postForEntity("$POST_CONTROLLER_URL/resourceWithBody", request, GreetingResponse::class.java)
assertThat(response.body, notNullValue())
assertThat(response.body?.name, `is`(name))
underTest.verifyPostResourceWithBody(1, greetingRequest)
underTest.verifyPostResourceWithBody(greetingRequest)
underTest.verifyPostResourceWithBodyAndPathVariableNoInteraction(param, greetingRequest)
assertThrows<VerificationException> { underTest.verifyPostResourceWithBodyNoInteraction(greetingRequest) }
assertThrows<VerificationException> { underTest.verifyPostResourceWithBodyNoInteractionWithUrl() }
}
@Test
fun `should stub a post method with a mapping matching the request body`() {
val additionalGreetingRequest = GreetingRequest(name = randomAlphabetic(10))
underTest.verifyPostResourceWithBodyNoInteraction(greetingRequest)
underTest.verifyPostResourceWithBodyNoInteraction(additionalGreetingRequest)
underTest.verifyPostResourceWithBodyNoInteractionWithUrl()
underTest.postResourceWithBody(greetingRequest, greetingResponse)
val response1 = restTemplate.postForEntity(
"$POST_CONTROLLER_URL/resourceWithBody",
HttpEntity(greetingRequest),
GreetingResponse::class.java
)
assertThat(response1.body, notNullValue())
assertThat(response1.body?.name, `is`(name))
val exception = assertThrows<HttpClientErrorException> {
restTemplate.postForEntity(
"$POST_CONTROLLER_URL/resourceWithBody",
HttpEntity(additionalGreetingRequest),
GreetingResponse::class.java
)
}
assertThat(exception.statusCode, `is`(NOT_FOUND))
underTest.verifyPostResourceWithBody(1, greetingRequest)
underTest.verifyPostResourceWithBody(1, additionalGreetingRequest)
underTest.verifyPostResourceWithBody(greetingRequest)
underTest.verifyPostResourceWithBody(additionalGreetingRequest)
}
@Test
fun `should handle post mapping with request body and path variable`() {
underTest.verifyPostResourceWithBodyAndPathVariableNoInteraction(param, greetingRequest)
underTest.verifyPostResourceWithBodyAndPathVariableNoInteractionWithUrl(param)
underTest.postResourceWithBodyAndPathVariable(GreetingResponse(name = name), param)
val request = HttpEntity(greetingRequest)
val response = restTemplate.postForEntity(
"$POST_CONTROLLER_URL/resourceWithBody/$param",
request,
GreetingResponse::class.java
)
assertThat(response.body, notNullValue())
assertThat(response.body?.name, `is`(name))
underTest.verifyPostResourceWithBodyAndPathVariable(1, param, greetingRequest)
underTest.verifyPostResourceWithBodyAndPathVariable(param, greetingRequest)
underTest.verifyPostResourceWithBodyNoInteraction(greetingRequest)
assertThrows<VerificationException> {
underTest.verifyPostResourceWithBodyAndPathVariableNoInteraction(param, greetingRequest)
}
assertThrows<VerificationException> {
underTest.verifyPostResourceWithBodyAndPathVariableNoInteractionWithUrl(param)
}
}
@Test
fun `should handle post mapping with request body and multiple path variable`() {
underTest.verifyPostResourceWithBodyAndMultiplePathVariablesNoInteraction(param1, param2, greetingRequest)
underTest.verifyPostResourceWithBodyAndMultiplePathVariablesNoInteractionWithUrl(param1, param2)
underTest.postResourceWithBodyAndMultiplePathVariables(GreetingResponse(name = name), param1, param2)
val request = HttpEntity(greetingRequest)
val response = restTemplate.postForEntity(
"$POST_CONTROLLER_URL/resourceWithBodyAndMultiplePathVariables/$param1/$param2",
request,
GreetingResponse::class.java
)
assertThat(response.body, notNullValue())
assertThat(response.body?.name, `is`(name))
underTest.verifyPostResourceWithBodyAndMultiplePathVariables(1, param1, param2, greetingRequest)
underTest.verifyPostResourceWithBodyAndMultiplePathVariables(param1, param2, greetingRequest)
assertThrows<VerificationException> {
underTest.verifyPostResourceWithBodyAndMultiplePathVariablesNoInteraction(param1, param2, greetingRequest)
}
assertThrows<VerificationException> {
underTest.verifyPostResourceWithBodyAndMultiplePathVariablesNoInteractionWithUrl(param1, param2)
}
}
}
| 4 | Kotlin | 0 | 0 | 32e4fe4955ed62eef72c8a89528161a2d43e334e | 6,099 | spring-wiremock-stub-generator | MIT License |
tilbakekreving/application/src/main/kotlin/tilbakekreving/application/service/vurder/BrevTilbakekrevingsbehandlingService.kt | navikt | 227,366,088 | false | {"Kotlin": 10119509, "Shell": 4388, "TSQL": 1233, "Dockerfile": 1209} | package tilbakekreving.application.service.vurder
import arrow.core.Either
import arrow.core.getOrElse
import arrow.core.left
import arrow.core.right
import no.nav.su.se.bakover.domain.sak.SakService
import no.nav.su.se.bakover.domain.sak.oppdaterVedtaksbrev
import org.slf4j.LoggerFactory
import tilbakekreving.application.service.tilgang.TilbakekrevingsbehandlingTilgangstyringService
import tilbakekreving.domain.UnderBehandling
import tilbakekreving.domain.opprett.TilbakekrevingsbehandlingRepo
import tilbakekreving.domain.vurdert.KunneIkkeLagreBrevtekst
import tilbakekreving.domain.vurdert.OppdaterBrevtekstCommand
import java.time.Clock
class BrevTilbakekrevingsbehandlingService(
private val tilgangstyring: TilbakekrevingsbehandlingTilgangstyringService,
private val sakService: SakService,
private val tilbakekrevingsbehandlingRepo: TilbakekrevingsbehandlingRepo,
private val clock: Clock,
) {
private val log = LoggerFactory.getLogger(this::class.java)
fun lagreBrevtekst(
command: OppdaterBrevtekstCommand,
): Either<KunneIkkeLagreBrevtekst, UnderBehandling.Utfylt> {
val sakId = command.sakId
tilgangstyring.assertHarTilgangTilSak(sakId).onLeft {
return KunneIkkeLagreBrevtekst.IkkeTilgang(it).left()
}
val sak = sakService.hentSak(sakId).getOrElse {
throw IllegalStateException("Kunne ikke oppdatere vedtaksbrev for tilbakekrevingsbehandling, fant ikke sak. Kommandoen var: $command")
}
if (sak.versjon != command.klientensSisteSaksversjon) {
log.info("Vedtaksbrev for tilbakekreving - Sakens versjon (${sak.versjon}) er ulik saksbehandlers versjon. Command: $command")
}
return sak.oppdaterVedtaksbrev(command, clock).let { pair ->
pair.second.right().onRight {
tilbakekrevingsbehandlingRepo.lagre(pair.first, command.toDefaultHendelsesMetadata())
}
}
}
}
| 9 | Kotlin | 1 | 1 | f187a366e1b4ec73bf18f4ebc6a68109494f1c1b | 1,965 | su-se-bakover | MIT License |
analysis/analysis-api-providers/src/org/jetbrains/kotlin/analysis/providers/impl/KotlinStaticDeclarationProvider.kt | JetBrains | 3,432,266 | false | null | /*
* Copyright 2010-2022 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.analysis.providers.impl
import com.intellij.psi.PsiElement
import com.intellij.psi.search.GlobalSearchScope
import org.jetbrains.kotlin.analysis.providers.KotlinDeclarationProvider
import org.jetbrains.kotlin.analysis.providers.KotlinDeclarationProviderFactory
import org.jetbrains.kotlin.fileClasses.javaFileFacadeFqName
import org.jetbrains.kotlin.name.CallableId
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
public class KotlinStaticDeclarationIndex {
internal val facadeFileMap: MutableMap<FqName, MutableSet<KtFile>> = mutableMapOf()
internal val classMap: MutableMap<FqName, MutableSet<KtClassOrObject>> = mutableMapOf()
internal val typeAliasMap: MutableMap<FqName, MutableSet<KtTypeAlias>> = mutableMapOf()
internal val topLevelFunctionMap: MutableMap<FqName, MutableSet<KtNamedFunction>> = mutableMapOf()
internal val topLevelPropertyMap: MutableMap<FqName, MutableSet<KtProperty>> = mutableMapOf()
}
public class KotlinStaticDeclarationProvider internal constructor(
private val index: KotlinStaticDeclarationIndex,
private val scope: GlobalSearchScope,
) : KotlinDeclarationProvider() {
private val KtElement.inScope: Boolean
get() = containingKtFile.virtualFile in scope
override fun getClassLikeDeclarationByClassId(classId: ClassId): KtClassLikeDeclaration? {
return getAllClassesByClassId(classId).firstOrNull()
?: getAllTypeAliasesByClassId(classId).firstOrNull()
}
override fun getAllClassesByClassId(classId: ClassId): Collection<KtClassOrObject> =
index.classMap[classId.packageFqName]
?.filter { ktClassOrObject ->
ktClassOrObject.getClassId() == classId && ktClassOrObject.inScope
}
?: emptyList()
override fun getAllTypeAliasesByClassId(classId: ClassId): Collection<KtTypeAlias> =
index.typeAliasMap[classId.packageFqName]
?.filter { ktTypeAlias ->
ktTypeAlias.getClassId() == classId && ktTypeAlias.inScope
}
?: emptyList()
override fun getTopLevelKotlinClassLikeDeclarationNamesInPackage(packageFqName: FqName): Set<Name> {
val classifiers = index.classMap[packageFqName].orEmpty() + index.typeAliasMap[packageFqName].orEmpty()
return classifiers.filter { it.inScope }
.mapNotNullTo(mutableSetOf()) { it.nameAsName }
}
override fun getTopLevelCallableNamesInPackage(packageFqName: FqName): Set<Name> {
val callables = index.topLevelPropertyMap[packageFqName].orEmpty() + index.topLevelFunctionMap[packageFqName].orEmpty()
return callables
.filter { it.inScope }
.mapNotNullTo(mutableSetOf()) { it.nameAsName }
}
override fun findFilesForFacadeByPackage(packageFqName: FqName): Collection<KtFile> =
index.facadeFileMap[packageFqName]
?.filter { ktFile ->
ktFile.virtualFile in scope
}
?: emptyList()
override fun findFilesForFacade(facadeFqName: FqName): Collection<KtFile> {
if (facadeFqName.shortNameOrSpecial().isSpecial) return emptyList()
return findFilesForFacadeByPackage(facadeFqName.parent()) //TODO Not work correctly for classes with JvmPackageName
.filter { it.javaFileFacadeFqName == facadeFqName }
}
override fun getTopLevelProperties(callableId: CallableId): Collection<KtProperty> =
index.topLevelPropertyMap[callableId.packageName]
?.filter { ktProperty ->
ktProperty.nameAsName == callableId.callableName && ktProperty.inScope
}
?: emptyList()
override fun getTopLevelFunctions(callableId: CallableId): Collection<KtNamedFunction> =
index.topLevelFunctionMap[callableId.packageName]
?.filter { ktNamedFunction ->
ktNamedFunction.nameAsName == callableId.callableName && ktNamedFunction.inScope
}
?: emptyList()
}
public class KotlinStaticDeclarationProviderFactory(
files: Collection<KtFile>
) : KotlinDeclarationProviderFactory() {
private val index = KotlinStaticDeclarationIndex()
private class KtDeclarationRecorder(private val index: KotlinStaticDeclarationIndex) : KtVisitorVoid() {
override fun visitElement(element: PsiElement) {
element.acceptChildren(this)
}
override fun visitKtFile(file: KtFile) {
if (file.hasTopLevelCallables()) {
index.facadeFileMap.computeIfAbsent(file.packageFqName) {
mutableSetOf()
}.add(file)
}
super.visitKtFile(file)
}
override fun visitClassOrObject(classOrObject: KtClassOrObject) {
classOrObject.getClassId()?.let { classId ->
index.classMap.computeIfAbsent(classId.packageFqName) {
mutableSetOf()
}.add(classOrObject)
}
super.visitClassOrObject(classOrObject)
}
override fun visitTypeAlias(typeAlias: KtTypeAlias) {
typeAlias.getClassId()?.let { classId ->
index.typeAliasMap.computeIfAbsent(classId.packageFqName) {
mutableSetOf()
}.add(typeAlias)
}
super.visitTypeAlias(typeAlias)
}
override fun visitNamedFunction(function: KtNamedFunction) {
if (function.isTopLevel) {
val packageFqName = (function.parent as KtFile).packageFqName
index.topLevelFunctionMap.computeIfAbsent(packageFqName) {
mutableSetOf()
}.add(function)
}
super.visitNamedFunction(function)
}
override fun visitProperty(property: KtProperty) {
if (property.isTopLevel) {
val packageFqName = (property.parent as KtFile).packageFqName
index.topLevelPropertyMap.computeIfAbsent(packageFqName) {
mutableSetOf()
}.add(property)
}
super.visitProperty(property)
}
}
init {
val recorder = KtDeclarationRecorder(index)
files.forEach {
it.accept(recorder)
}
}
override fun createDeclarationProvider(searchScope: GlobalSearchScope): KotlinDeclarationProvider {
return KotlinStaticDeclarationProvider(index, searchScope)
}
}
| 157 | null | 5209 | 42,102 | 65f712ab2d54e34c5b02ffa3ca8c659740277133 | 6,808 | kotlin | Apache License 2.0 |
src/test/kotlin/com/dg/watcher/watching/loading/ApkLoadingTest.kt | scottdweber | 102,811,791 | true | {"Kotlin": 34986, "Java": 1215, "HTML": 423} | package com.dg.watcher.watching.loading
import com.dg.watcher.base.Build
import com.nhaarman.mockito_kotlin.doReturn
import com.nhaarman.mockito_kotlin.mock
import hudson.FilePath
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import java.io.File.separator
class ApkLoadingTest {
@Rule @JvmField
val tempDir = TemporaryFolder()
@Test
fun `Should return null when the specified folder is non existent`() =
assertNull(loadApk(mockBuild(), "temp_apk_folder"))
@Test
fun `Should return null when the apk in the specified folder is non existent`() {
// GIVEN
createApkFolder("temp_apk_folder")
// THEN
assertNull(loadApk(mockBuild(), "temp_apk_folder"))
}
@Test
fun `Should load the apk from the specified folder`() {
// GIVEN
createApkFolder("temp_apk_folder")
createApkFile("temp_apk_folder", "debug.apk")
// THEN
assertNotNull(loadApk(mockBuild(), "temp_apk_folder"))
}
@Test
fun `Should return null when the default folder is non existent`() =
assertNull(loadApk(mockBuild()))
@Test
fun `Should return null when the apk in the default folder is non existent`() {
// GIVEN
createApkFolder("app", "build", "outputs", "apk")
// THEN
assertNull(loadApk(mockBuild()))
}
@Test
fun `Should load the apk from the default folder`() {
// GIVEN
createApkFolder("app", "build", "outputs", "apk")
createApkFile("app/build/outputs/apk", "debug.apk")
// THEN
assertNotNull(loadApk(mockBuild()))
}
@Test
fun `Should never load the apk from a nested folder`() {
// GIVEN
createApkFolder("apk_folder", "nested_folder")
createApkFile("apk_folder/nested_folder", "debug.apk")
// THEN
assertNull(loadApk(mockBuild(), "apk_folder"))
}
private fun createApkFolder(vararg folders: String) = tempDir.newFolder(*folders)
private fun createApkFile(folder: String, fileName: String) = tempDir.newFile("$folder$separator$fileName")
private fun mockBuild() = mock<Build> {
on { getWorkspace() } doReturn FilePath(tempDir.root)
}
} | 0 | Kotlin | 0 | 0 | b8600065054e7dcc950a2b9b2be12d7807166e77 | 2,343 | android-apk-size-watcher-plugin | MIT License |
bbfgradle/tmp/results/diffABI/qsiopad_FILE.kt | DaniilStepanov | 346,008,310 | false | null | // Bug happens on JVM , JVM -Xuse-ir
// FILE: tmp0.kt
package qsiopad
import kotlin.collections.*
import kotlin.text.*
import kotlin.sequences.*
import kotlin.reflect.*
class StrList : List<String?> {
override val size: Int
get() = throw UnsupportedOperationException()
override fun isEmpty(): Boolean =TODO()
override fun contains(o: String?):Boolean = TODO()
override fun iterator(): Iterator<String> =TODO()
override fun containsAll(c: Collection<String?>):Boolean = TODO()
override fun get(index: Int): String =TODO()
override fun indexOf(o: String?): Int =TODO()
override fun lastIndexOf(o: String?): Int =TODO()
override fun listIterator(): ListIterator<String?> =TODO()
override fun listIterator(index: Int): ListIterator<String?> =TODO()
override fun subList(fromIndex: Int, toIndex: Int): List<String?> =TODO()
}
fun <E> Collection<E>.forceContains(x: Any?): Boolean = TODO()
fun box(): String =TODO()
private final class Och (var crh: Triple<Long, StrList, Short> = Triple<Long, StrList, Short>(-9024035136862659434, StrList(), 21663), xxr: ArrayDeque<StrList>, val rrf: Collection<LinkedHashMap<Byte, Short>>, var wwf: HashMap<UShort, StrList> = linkedMapOf<UShort, StrList>(), wov: UInt = 1438241026.toUInt()): MutableList <StrList>{
override val size: kotlin.Int
get() = TODO()
override fun add(element: StrList): kotlin.Boolean = TODO()
override fun add(index: kotlin.Int, element: StrList): kotlin.Unit = TODO()
override fun addAll(index: kotlin.Int, elements: kotlin.collections.Collection<StrList>): kotlin.Boolean = TODO()
override fun addAll(elements: kotlin.collections.Collection<StrList>): kotlin.Boolean = TODO()
override fun clear(): kotlin.Unit = TODO()
override fun contains(element: StrList): kotlin.Boolean = TODO()
override fun containsAll(elements: kotlin.collections.Collection<StrList>): kotlin.Boolean = TODO()
override fun get(index: kotlin.Int): StrList = TODO()
override fun indexOf(element: StrList): kotlin.Int = TODO()
override fun isEmpty(): kotlin.Boolean = TODO()
override fun iterator(): kotlin.collections.MutableIterator<StrList> = TODO()
override fun lastIndexOf(element: StrList): kotlin.Int = TODO()
override fun listIterator(): kotlin.collections.MutableListIterator<StrList> = TODO()
override fun listIterator(index: kotlin.Int): kotlin.collections.MutableListIterator<StrList> = TODO()
override fun remove(element: StrList): kotlin.Boolean = TODO()
override fun removeAll(elements: kotlin.collections.Collection<StrList>): kotlin.Boolean = TODO()
override fun removeAt(index: kotlin.Int): StrList = TODO()
override fun retainAll(elements: kotlin.collections.Collection<StrList>): kotlin.Boolean = TODO()
override fun set(index: kotlin.Int, element: StrList): StrList = TODO()
override fun subList(fromIndex: kotlin.Int, toIndex: kotlin.Int): kotlin.collections.MutableList<StrList> = TODO()
var ljtv: Triple<Pair<UShort, StrList>, Char, StrList> = Triple<Pair<UShort, StrList>, Char, StrList>(Pair<UShort, StrList>(823.toUShort(), StrList()), 'ቕ', StrList())
var eorx: StrList = StrList()
var Long.qyay: Byte
get() = TODO()
set(value) = TODO()
var esua: Byte = TODO()
val Set<StrList>.tiqc: MutableMap<Boolean, Char>
get() = mutableMapOf<Boolean, Char>(Pair<Boolean, Char>(true, '릏'))
val jwql: ULong = 7209187283677972140.toULong()
var mavf: StrList = StrList()
val hzrz: String = TODO()
val bbsm: Collection<StrList> = listOf<StrList>(StrList())
}
private interface Upk : KProperty2<LinkedHashMap<Char, Boolean>, Double, List<StrList>>, MutableMap<String, StrList>{
override fun invoke(p1: kotlin.collections.LinkedHashMap<kotlin.Char, kotlin.Boolean>, p2: kotlin.Double): kotlin.collections.List<StrList> = TODO()
override val entries: kotlin.collections.MutableSet<kotlin.collections.MutableMap.MutableEntry<kotlin.String, StrList>>
override fun clear(): kotlin.Unit = TODO()
override fun containsKey(key: kotlin.String): kotlin.Boolean = TODO()
override fun get(key: kotlin.String): StrList? = TODO()
val mhoz: String
val LinkedHashMap<UByte, Int>.qnym: StrList
get() = TODO()
var wcyv: StrList
val khif: StrList
val aclf: Short
var ouzz: Boolean
val kufa: LinkedHashSet<StrList>
var dkuh: Pair<List<List<String>>, StrList>
}
private interface Ajd : Upk, MatchResult{
override fun clear(): kotlin.Unit = TODO()
override fun containsKey(key: kotlin.String): kotlin.Boolean = TODO()
override fun get(key: kotlin.String): StrList? = TODO()
override val mhoz: kotlin.String
override var dkuh: kotlin.Pair<kotlin.collections.List<kotlin.collections.List<kotlin.String>>, StrList>
override fun putAll(from: kotlin.collections.Map<out kotlin.String, StrList>): kotlin.Unit = TODO()
override fun remove(key: kotlin.String): StrList? = TODO()
override val groups: kotlin.text.MatchGroupCollection
override val range: kotlin.ranges.IntRange
val fzjn: Triple<StrList, Byte, UInt>
val foob: Char
val ypnp: Float
val ruum: UInt
val StrList.ycvr: Triple<StrList, StrList, HashSet<Int>>
get() = TODO()
var wjsh: Double
var ockq: Triple<Int, StrList, Int>
}
| 1 | null | 1 | 1 | e772ef1f8f951873ebe7d8f6d73cf19aead480fa | 5,164 | kotlinWithFuzzer | Apache License 2.0 |
wrapper/Android/AutoE2E/app/src/main/java/com/example/autoe2e/lib/resolver/Query.kt | CreeJee | 230,300,137 | false | {"TypeScript": 74284, "Kotlin": 21352, "HTML": 3814, "JavaScript": 1319, "Java": 625, "CSS": 366} | package com.example.autoe2e.lib.resolver
import com.example.autoe2e.lib.mock.findProject
import com.example.autoe2e.lib.mock.projectList
import com.example.autoe2e.lib.types.IQuery
import com.example.autoe2e.lib.types.Project
class Query: IQuery {
override fun project(id: String): Project? {
return findProject(id)
}
override fun projects(): Iterable<Project> {
return projectList().values
}
} | 9 | TypeScript | 0 | 1 | 1a8706d3c2c8b30f514e719e41cfb8bcd878ad2d | 430 | AutoE2E | MIT License |
android-adb/src/com/android/tools/idea/ui/AbstractDialogWrapper.kt | JetBrains | 60,701,247 | false | null | /*
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.idea.ui
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
import javax.swing.JComponent
import javax.swing.JPanel
/**
* Abstraction over [DialogWrapper] that is compatible with unit testing.
*
* Instead of deriving from [DialogWrapper], consumers should create an instance of [AbstractDialogWrapper]
* via the [factory] property, which can be customized for unit tests. That is, consumers should
* use composition instead of inheritance.
*
* The API surface area is by design much smaller than [DialogWrapper] so that it is compatible with
* unit testing.
*/
abstract class AbstractDialogWrapper {
/**
* Function that creates the center panel of the dialog. This property should be set by the consumer
* before calling [init]
*/
var centerPanelProvider: () -> JComponent = { JPanel() }
/**
* The title of the dialog
*/
abstract var title: String
/**
* `true` if the dialog should be modal
*/
abstract var isModal: Boolean
/**
* The text of the `OK` button (default is "ok")
*/
abstract var okButtonText: String?
abstract fun show()
abstract fun init()
companion object {
private var defaultFactory = object : DialogWrapperFactory {
override fun createDialogWrapper(project: Project,
canBeParent: Boolean,
ideModalityType: DialogWrapper.IdeModalityType): AbstractDialogWrapper {
return DefaultDialogWrapper(project, canBeParent, ideModalityType)
}
}
var factory = defaultFactory
}
} | 0 | Java | 187 | 751 | 16d17317f2c44ec46e8cd2180faf9c349d381a06 | 2,243 | android | Apache License 2.0 |
app/src/main/java/com/akhbulatov/wordkeeper/features/wordcategory/selectwordcategory/SelectWordCategoryFactory.kt | akhbulatov | 65,332,258 | false | {"Kotlin": 99560} | package com.akhbulatov.wordkeeper.features.wordcategory.selectwordcategory
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.akhbulatov.wordkeeper.WordKeeperApp
class SelectWordCategoryFactory {
fun createViewModelFactory() = object : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
val appFactory = WordKeeperApp.appFactory
@Suppress("UNCHECKED_CAST")
return SelectWordCategoryViewModel(
getWordCategoriesUseCase = appFactory.wordCategoryDomainFactory.getWordCategoriesUseCase
) as T
}
}
}
| 0 | Kotlin | 0 | 2 | ce13456349e91020f5ff64cc16d6595f52cdef9c | 666 | wordkeeper | Apache License 2.0 |
app/src/main/java/com/kkyy_96/controlmywindow/MainActivity.kt | CYL96 | 845,893,031 | false | {"Kotlin": 35428} | package com.kkyy_96.controlmywindow
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.fragment.app.FragmentActivity
import com.kkyy_96.controlmywindow.src.config.MyControlConfig
import com.kkyy_96.controlmywindow.src.log.MyLog
import com.kkyy_96.controlmywindow.src.page.NavGraph
import com.kkyy_96.controlmywindow.src.page.permission.requestPermission
class MainActivity : FragmentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
MyControlConfig.readConfig(this)
MyLog.activity = this
requestPermission(this)
setContent {
NavGraph(activity =this)
}
}
}
| 0 | Kotlin | 0 | 0 | b14d0c7650c9c49c7696239a48ddbf2ecf44273a | 712 | ControlMyWindowForAndroid | Apache License 2.0 |
tilbakekreving/domain/src/main/kotlin/tilbakekreving/domain/Tilbakekrevingsbehandling.kt | navikt | 227,366,088 | false | {"Kotlin": 9216308, "Shell": 4369, "TSQL": 1233, "Dockerfile": 800} | package tilbakekreving.domain
import dokument.domain.brev.Brevvalg
import no.nav.su.se.bakover.common.domain.NonBlankString
import no.nav.su.se.bakover.common.domain.attestering.Attesteringshistorikk
import no.nav.su.se.bakover.common.ident.NavIdentBruker
import no.nav.su.se.bakover.common.tid.Tidspunkt
import no.nav.su.se.bakover.hendelse.domain.HendelseId
import no.nav.su.se.bakover.hendelse.domain.Hendelsesversjon
import tilbakekreving.domain.forhåndsvarsel.ForhåndsvarselMetaInfo
import tilbakekreving.domain.kravgrunnlag.Kravgrunnlag
import tilbakekreving.domain.vurdert.VurderingerMedKrav
import java.util.UUID
/**
* Starter som [OpprettetTilbakekrevingsbehandling] & aksepterer kun 1 åpen behandling om gangen
* Deretter tar de stilling til om hver måned i kravgrunnlaget skal tilbakekreves, eller ikke.
* Vi får deretter en tilstand [UnderBehandling]
*
* @property versjon versjonen til den siste hendelsen knyttet til denne tilbakekrevingsbehandlingen
* @property hendelseId hendelses iden til den siste hendelsen knyttet til denne tilbakekrevingsbehandlingen
*/
sealed interface Tilbakekrevingsbehandling {
val id: TilbakekrevingsbehandlingId
val sakId: UUID
val opprettet: Tidspunkt
val opprettetAv: NavIdentBruker.Saksbehandler
val kravgrunnlag: Kravgrunnlag
val erKravgrunnlagUtdatert: Boolean
val vurderingerMedKrav: VurderingerMedKrav?
// TODO jah: Brevvalg.SaksbehandlersValg er for generell. Vi trenger en mer spesifikk type for tilbakekreving.
val vedtaksbrevvalg: Brevvalg.SaksbehandlersValg?
val attesteringer: Attesteringshistorikk
val versjon: Hendelsesversjon
val hendelseId: HendelseId
val forhåndsvarselsInfo: List<ForhåndsvarselMetaInfo>
val notat: NonBlankString?
fun erÅpen(): Boolean
}
| 4 | Kotlin | 1 | 1 | bcfe10b28af8a9a8592c0cf8422d19b6892ee872 | 1,790 | su-se-bakover | MIT License |
lib/src/main/java/com/kotlin/inaction/chapter_5/5_3_1_4_ExecutingSequenceOperations.kt | jhwsx | 167,022,805 | false | {"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 3, "Proguard": 1, "Kotlin": 426, "XML": 14, "Java": 86, "desktop": 1} | package com.kotlin.inaction.chapter_5
/**
*
* @author wzc
* @date 2019/2/14
*/
fun main(args: Array<String>) {
val people = listOf<Person>(
Person("Alice",29),
Person("Bob",31),
Person("Charles",31),
Person("Dan",21)
)
// 先 map 再 filter,需要执行 4 次map,4 次filter
println(people.asSequence().map(Person::name)
.filter { it.length < 4 }.toList()
)
// 先 filter 再 map,需要执行 4 次filter,2 次map
println(people.asSequence().filter { it.name.length < 4 }
.map(Person::name).toList())
}
/**
* 总结:
* 1, 在集合上执行操作的顺序也会影响性能;
* 2,Kotlin 中的序列就是 Java8 中流的翻版,但是 Java8 的流不支持那些基于 Java 老版本的平台。
*/ | 1 | null | 1 | 1 | 1cdb279920c229fa4e00a09a8165f32e71cadd3e | 649 | KotlinInAction | MIT License |
domain/src/main/java/com/no1/taiwan/newsbasket/domain/usecases/token/KeepNewsTokenRespCase.kt | SmashKs | 157,812,125 | false | null | package com.no1.taiwan.newsbasket.domain.usecases.token
import com.no1.taiwan.newsbasket.domain.BaseUsecase.RequestValues
import com.no1.taiwan.newsbasket.domain.parameters.params.TokenParams
import com.no1.taiwan.newsbasket.domain.repositories.TokenRepository
import com.no1.taiwan.newsbasket.domain.usecases.KeepNewsTokenCase
import com.no1.taiwan.newsbasket.domain.usecases.KeepNewsTokenReq
class KeepNewsTokenRespCase(
private val tokenRepo: TokenRepository
) : KeepNewsTokenCase() {
/** Provide a common parameter variable for the children class. */
override var requestValues: KeepNewsTokenReq? = null
override suspend fun acquireCase() = attachParameter {
tokenRepo.keepNewsToken(it.parameters)
}
class Request(val parameters: TokenParams = TokenParams()) : RequestValues
}
| 0 | Kotlin | 0 | 2 | 8f8a0f31c3781007a5fd78c284f44f0ec71b89d0 | 817 | NewsBascket | MIT License |
app/src/main/java/com/alok/dailynews/api/responsemodel/CollegeListResponse.kt | alokbharti | 266,596,782 | false | null | package com.alok.dailynews.api.responsemodel
import com.google.gson.annotations.SerializedName
data class CollegeListResponse(
@SerializedName("id")
var id: String,
@SerializedName("name")
var name: String
) | 0 | Kotlin | 2 | 5 | d57529683006accb85c21916d5463dfe39f58307 | 225 | DailyNews-Kotlin | Apache License 2.0 |
core/src/commonMain/kotlin/dev/kryptonreborn/blockfrost/base/ErrorResponse.kt | KryptonReborn | 803,884,694 | false | {"Kotlin": 608832, "Swift": 594, "HTML": 323} | package dev.kryptonreborn.blockfrost.base
import dev.kryptonreborn.blockfrost.ktor.Ktor
import io.ktor.http.HttpStatusCode
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.decodeFromJsonElement
/**
* The `ErrorResponse` class represents an error response from the Blockfrost API.
*
* @property statusCode The HTTP status code of the error response.
* @property error The error message of the error response.
* @property message The detailed message of the error response.
*/
@Serializable
internal data class ErrorResponse(
@SerialName("status_code")
val statusCode: Int? = null,
private val error: String? = null,
private val message: String? = null,
) {
fun isClientError() = statusCode in 400..499
fun isServerError() = statusCode in 500..599
fun message(): String = message ?: "Unknown message"
fun error() = error ?: "Unknown error"
}
internal inline fun <reified T> handleResponseFromString(jsonString: String): T {
when (val jsonElement = Ktor.json.parseToJsonElement(jsonString)) {
is JsonArray -> {
return Ktor.json.decodeFromJsonElement(jsonElement)
}
is JsonObject -> {
if (jsonElement.containsKey("status_code")) {
val errorResponse = Ktor.json.decodeFromJsonElement<ErrorResponse>(jsonElement)
throw getExceptionFromResponse(errorResponse)
}
return Ktor.json.decodeFromJsonElement(jsonElement)
}
else -> throw IllegalArgumentException("Unexpected JSON format")
}
}
internal inline fun getExceptionFromResponse(res: ErrorResponse): BlockfrostException {
return when {
res.statusCode == HttpStatusCode.BadRequest.value ->
BadRequestException(
res.message(),
res.error(),
)
res.statusCode == HttpStatusCode.Forbidden.value ->
ForbiddenException(
res.message(),
res.error(),
)
res.statusCode == HttpStatusCode.NotFound.value ->
NotFoundException(
res.message(),
res.error(),
)
res.statusCode == 418 -> BannedException(res.message(), res.error())
res.statusCode == HttpStatusCode.TooManyRequests.value ->
RateLimitedException(
res.message(),
res.error(),
)
res.isClientError() ->
ClientException(
res.statusCode!!,
res.message(),
res.error(),
)
res.isServerError() ->
ServerException(
res.statusCode!!,
res.message(),
res.error(),
)
else ->
BlockfrostException(
res.message(),
res.error(),
)
}
}
| 0 | Kotlin | 1 | 1 | f04fa182b1599042702f6ab36047c9a1826d4522 | 3,038 | blockfrost-kotlin-sdk | Apache License 2.0 |
app/src/main/java/com/flight/app/view/map/MapsActivity.kt | NalediMadlopha | 173,349,872 | false | null | package com.flight.app.view.map
import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.lifecycle.ViewModelProviders
import com.flight.app.R
import com.flight.app.viewmodel.MapActivityViewModel
import com.flight.app.viewmodel.ViewModelFactory
import com.google.android.gms.common.GoogleApiAvailability
import kotlinx.android.synthetic.main.maps_activity.*
class MapsActivity : AppCompatActivity(), MapActivityView {
private lateinit var viewModel: MapActivityViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(com.flight.app.R.layout.maps_activity)
viewModel = ViewModelProviders.of(
this,
ViewModelFactory { MapActivityViewModel(this, application) }
).get(MapActivityViewModel::class.java)
viewModel.checkForGooglePlayServices()
}
override fun displayUserResolvableError(googleApiAvailability: GoogleApiAvailability, resultCode: Int) {
googleApiAvailability.getErrorDialog(this, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST).show()
}
override fun displayNotSupportedError() {
mapContainer.visibility = View.GONE
deviceNotSupportedErrorTextView.visibility = View.VISIBLE
}
override fun requestLocationPermission() {
ActivityCompat.requestPermissions(this,
arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), LOCATION_PERMISSIONS_REQUEST_CODE)
}
override fun displayMap() {
val fragmentManager = supportFragmentManager
fragmentManager.beginTransaction()
.replace(R.id.mapContainer, MapFragment())
.commit()
deviceNotSupportedErrorTextView.visibility = View.GONE
locationPermissionNotGrantedErrorTextView.visibility = View.GONE
mapContainer.visibility = View.VISIBLE
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
when (requestCode) {
LOCATION_PERMISSIONS_REQUEST_CODE -> {
if ( ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED ) {
displayMap()
} else {
mapContainer.visibility = View.GONE
deviceNotSupportedErrorTextView.visibility = View.GONE
locationPermissionNotGrantedErrorTextView.visibility = View.VISIBLE
}
}
}
}
companion object {
private const val LOCATION_PERMISSIONS_REQUEST_CODE = 0
private const val PLAY_SERVICES_RESOLUTION_REQUEST = 9000
}
}
| 2 | Kotlin | 0 | 0 | 4e920a3d51a79c7fbb88c65fa42e9d923436efbb | 2,976 | flight | MIT License |
src/test/kotlin/Main.kt | volta2030 | 712,138,104 | false | {"Kotlin": 12518} | import kuda.*
import kuda.type.Error
import kuda.type.FunctionCache
import kuda.type.Limit
fun main(args: Array<String>) {
val runtimeAPI = RuntimeAPI()
val driverAPI = DriverAPI()
val cudaVersion = runtimeAPI.getRuntimeVersion()
val driverVersion = driverAPI.getDriverVersion()
val device = runtimeAPI.getDevice()
val driverDevice = driverAPI.getDevice(0)
val deviceCount = driverAPI.getDeviceCount()
driverAPI.init(0)
println("CUDA Version : $cudaVersion")
println("CUDA Driver version : $driverVersion")
println("CUDA Device: $device")
println("CUDA Device count : $deviceCount")
println(driverDevice)
println(runtimeAPI.getLimit(Limit.PRINT_FIFO_SIZE))
println(runtimeAPI.getLimit(Limit.MALLOC_HEAP_SIZE))
println(runtimeAPI.getLimit(Limit.STACK_SIZE))
println(runtimeAPI.getLimit(Limit.DEV_RUNTIME_SYNC_DEPTH))
println(runtimeAPI.getLimit(Limit.MAX_L2_FETCH_GRANULARITY))
println(runtimeAPI.getLimit(Limit.DEV_RUNTIME_PENDING_LAUNCH_COUNT))
println(runtimeAPI.getLimit(Limit.PERSISTING_L2_CACHE_SIZE))
println(runtimeAPI.getPCIBusId(device))
println(runtimeAPI.getStreamPriorityRange())
println(runtimeAPI.setCacheConfig(FunctionCache.PREFER_NONE))
println(runtimeAPI.getErrorName(Error.ERROR_UNKNOWN))
println(runtimeAPI.getErrorString(Error.INITIALIZATION_ERROR))
} | 0 | Kotlin | 0 | 0 | 7bc419e514a94205d9906a6f52f25dd2cb5023c0 | 1,380 | kuda | MIT License |
src/main/java/uk/gov/justice/digital/hmpps/whereabouts/services/AttendanceService.kt | ministryofjustice | 141,123,113 | false | {"Kotlin": 849414, "Java": 99907, "Shell": 2877, "Dockerfile": 1368} | package uk.gov.justice.digital.hmpps.whereabouts.services
import com.microsoft.applicationinsights.TelemetryClient
import jakarta.transaction.Transactional
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.data.domain.Page
import org.springframework.data.domain.Pageable
import org.springframework.stereotype.Service
import uk.gov.justice.digital.hmpps.whereabouts.config.DisabledPrisonsConfig
import uk.gov.justice.digital.hmpps.whereabouts.dto.OffenderDetails
import uk.gov.justice.digital.hmpps.whereabouts.dto.PrisonerScheduleDto
import uk.gov.justice.digital.hmpps.whereabouts.dto.attendance.AbsenceDto
import uk.gov.justice.digital.hmpps.whereabouts.dto.attendance.AttendAllDto
import uk.gov.justice.digital.hmpps.whereabouts.dto.attendance.AttendanceChangeDto
import uk.gov.justice.digital.hmpps.whereabouts.dto.attendance.AttendanceDto
import uk.gov.justice.digital.hmpps.whereabouts.dto.attendance.AttendanceHistoryDto
import uk.gov.justice.digital.hmpps.whereabouts.dto.attendance.AttendanceSummary
import uk.gov.justice.digital.hmpps.whereabouts.dto.attendance.AttendancesDto
import uk.gov.justice.digital.hmpps.whereabouts.dto.attendance.CreateAttendanceDto
import uk.gov.justice.digital.hmpps.whereabouts.dto.attendance.UpdateAttendanceDto
import uk.gov.justice.digital.hmpps.whereabouts.dto.prisonapi.OffenderAttendance
import uk.gov.justice.digital.hmpps.whereabouts.model.AbsentReason
import uk.gov.justice.digital.hmpps.whereabouts.model.Attendance
import uk.gov.justice.digital.hmpps.whereabouts.model.AttendanceChange
import uk.gov.justice.digital.hmpps.whereabouts.model.AttendanceChangeValues
import uk.gov.justice.digital.hmpps.whereabouts.model.TimePeriod
import uk.gov.justice.digital.hmpps.whereabouts.repository.AttendanceChangesRepository
import uk.gov.justice.digital.hmpps.whereabouts.repository.AttendanceRepository
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.temporal.ChronoUnit
import java.util.function.Predicate
import java.util.stream.Collectors
class ForbiddenException(message: String) : RuntimeException(message)
@Service
class AttendanceService(
private val disabledPrisonsConfig: DisabledPrisonsConfig,
private val attendanceRepository: AttendanceRepository,
private val attendanceChangesRepository: AttendanceChangesRepository,
private val prisonApiService: PrisonApiService,
private val iepWarningService: IEPWarningService,
private val nomisEventOutcomeMapper: NomisEventOutcomeMapper,
private val telemetryClient: TelemetryClient,
) {
private companion object {
private val log: Logger = LoggerFactory.getLogger(this::class.java)
}
fun getAttendanceForEventLocation(
prisonId: String?,
eventLocationId: Long?,
date: LocalDate?,
period: TimePeriod?,
): Set<AttendanceDto> {
val attendance = attendanceRepository
.findByPrisonIdAndEventLocationIdAndEventDateAndPeriod(prisonId, eventLocationId, date, period)
return attendance.map(this::toAttendanceDto).toSet()
}
fun getAbsencesForReason(prisonId: String?, date: LocalDate?, period: TimePeriod?): Set<AttendanceDto> {
val attendance = attendanceRepository
.findByPrisonIdAndEventDateAndPeriodAndAbsentReasonNotNull(prisonId, date, period)
return attendance.map(this::toAttendanceDto).toSet()
}
fun getAttendanceForBookings(
prisonId: String?,
bookings: Set<Long?>?,
date: LocalDate?,
period: TimePeriod?,
): Set<AttendanceDto> {
val attendance = attendanceRepository
.findByPrisonIdAndBookingIdInAndEventDateAndPeriod(prisonId, bookings, date, period)
return attendance.map(this::toAttendanceDto).toSet()
}
fun getAttendanceForBookingsOverDateRange(
prisonId: String,
bookings: Set<Long>,
fromDate: LocalDate,
toDate: LocalDate?,
period: TimePeriod?,
): Set<AttendanceDto> {
val periods = if (period == null) setOf(TimePeriod.AM, TimePeriod.PM) else setOf(period)
val endDate = toDate ?: fromDate
val attendances = attendanceRepository
.findByPrisonIdAndBookingIdInAndEventDateBetweenAndPeriodIn(prisonId, bookings, fromDate, endDate, periods)
return attendances.map(this::toAttendanceDto).toSet()
}
@Transactional
@Throws(AttendanceExists::class)
fun createAttendance(attendanceDto: CreateAttendanceDto): AttendanceDto {
if (disabledPrisonsConfig.getPrisons().contains(attendanceDto.prisonId)) throw ForbiddenException("whereabouts is no longer active - use A+A")
val provisionalAttendance = toAttendance(attendanceDto)
val existing = attendanceRepository.findByPrisonIdAndBookingIdAndEventIdAndEventDateAndPeriod(
provisionalAttendance.prisonId,
provisionalAttendance.bookingId,
provisionalAttendance.eventId,
provisionalAttendance.eventDate,
provisionalAttendance.period,
)
if (existing.size > 0) {
log.info("Attendance already created")
throw AttendanceExists()
}
val attendance = attendanceRepository.save(toAttendance(attendanceDto))
postNomisAttendance(attendance)
iepWarningService.postIEPWarningIfRequired(
bookingId = attendance.bookingId,
caseNoteId = attendance.caseNoteId,
reason = attendance.absentReason,
subReason = attendance.absentSubReason,
text = attendance.comments,
eventDate = attendance.eventDate,
).ifPresent { caseNoteId: Long? -> attendance.caseNoteId = caseNoteId }
log.info("attendance created {}", attendance.toBuilder().comments(null))
return toAttendanceDto(attendance)
}
@Transactional
@Throws(AttendanceNotFound::class, AttendanceLocked::class)
fun updateAttendance(id: Long, newAttendanceDetails: UpdateAttendanceDto) {
val attendance = attendanceRepository.findById(id).orElseThrow { AttendanceNotFound() }
if (disabledPrisonsConfig.getPrisons().contains(attendance.prisonId)) throw ForbiddenException("whereabouts is no longer active - use A+A")
if (isAttendanceLocked(attendance)) {
log.info("Update attempted on locked attendance, attendance id {}", id)
throw AttendanceLocked()
}
iepWarningService.handleIEPWarningScenarios(attendance, newAttendanceDetails)
.ifPresent { caseNoteId: Long? -> attendance.caseNoteId = caseNoteId }
val changedFrom = if (attendance.attended) {
AttendanceChangeValues.Attended
} else {
AttendanceChangeValues.valueOf(attendance.absentReason.toString())
}
val changedTo = if (newAttendanceDetails.absentReason != null) {
AttendanceChangeValues.valueOf(newAttendanceDetails.absentReason.toString())
} else {
AttendanceChangeValues.Attended
}
attendance.comments = newAttendanceDetails.comments
attendance.attended = newAttendanceDetails.attended
attendance.paid = newAttendanceDetails.paid
attendance.absentReason = newAttendanceDetails.absentReason
attendance.absentSubReason = newAttendanceDetails.absentSubReason
attendanceRepository.save(attendance)
postNomisAttendance(attendance)
attendanceChangesRepository.save(
AttendanceChange(
attendance = attendance,
changedFrom = changedFrom,
changedTo = changedTo,
),
)
}
@Transactional
fun attendAll(attendAll: AttendAllDto): Set<AttendanceDto> {
val eventOutcome = nomisEventOutcomeMapper.getEventOutcome(
reason = null,
subReason = null,
attended = true,
paid = true,
comment = "",
)
prisonApiService.putAttendanceForMultipleBookings(attendAll.bookingActivities, eventOutcome)
val attendances = attendAll.bookingActivities.map { (bookingId, activityId) ->
Attendance.builder()
.attended(true)
.paid(true)
.bookingId(bookingId)
.eventId(activityId)
.eventDate(attendAll.eventDate)
.eventLocationId(attendAll.eventLocationId)
.period(attendAll.period)
.prisonId(attendAll.prisonId)
.build()
}.toSet()
attendanceRepository.saveAll(attendances)
return attendances.stream().map(this::toAttendanceDto).collect(Collectors.toSet())
}
private fun postNomisAttendance(attendance: Attendance) {
val eventOutcome = nomisEventOutcomeMapper.getEventOutcome(
reason = attendance.absentReason,
subReason = attendance.absentSubReason,
attended = attendance.attended,
paid = attendance.paid,
comment = attendance.comments,
)
log.info("Updating attendance on NOMIS {} {}", attendance.toBuilder().comments(null).build(), eventOutcome)
prisonApiService.putAttendance(attendance.bookingId, attendance.eventId, eventOutcome)
}
private fun isAttendanceLocked(attendance: Attendance): Boolean {
if (attendance.createDateTime == null) return false
val dateOfChange =
if (attendance.modifyDateTime == null) attendance.createDateTime.toLocalDate() else attendance.modifyDateTime.toLocalDate()
val dateDifference = ChronoUnit.DAYS.between(dateOfChange, LocalDate.now())
return if (attendance.paid) dateDifference >= 1 else dateDifference >= 7
}
fun getPrisonersUnaccountedFor(
prisonId: String,
date: LocalDate,
period: TimePeriod,
): List<PrisonerScheduleDto> {
// grab all scheduled activities
val scheduledActivities = prisonApiService.getScheduledActivities(prisonId, date, period)
// grab all the attendances that have taken place
val attendances = attendanceRepository.findByPrisonIdAndPeriodAndEventDateBetween(prisonId, period, date, date)
.map { Pair(it.bookingId, it.eventId) }.toSet()
// filter to leave the scheduled activities
return scheduledActivities.filter { !attendances.contains(Pair(it.bookingId, it.eventId)) }
}
@Transactional
fun createAttendances(attendancesDto: AttendancesDto): Set<AttendanceDto> {
if (disabledPrisonsConfig.getPrisons().contains(attendancesDto.prisonId)) throw ForbiddenException("whereabouts is no longer active - use A+A")
val attendances = attendancesDto.bookingActivities
.map { (bookingId, activityId) ->
Attendance.builder()
.bookingId(bookingId)
.eventId(activityId)
.attended(attendancesDto.attended)
.paid(attendancesDto.paid)
.absentReason(attendancesDto.reason)
.comments(attendancesDto.comments)
.eventDate(attendancesDto.eventDate)
.eventLocationId(attendancesDto.eventLocationId)
.period(attendancesDto.period)
.prisonId(attendancesDto.prisonId)
.build()
}
.toSet()
attendanceRepository.saveAll(attendances)
val eventOutcome = nomisEventOutcomeMapper.getEventOutcome(
reason = attendancesDto.reason,
// for creating multiple attendances can only specify reasons where sub reason not required
subReason = null,
attended = attendancesDto.attended,
paid = attendancesDto.paid,
comment = attendancesDto.comments,
)
prisonApiService.putAttendanceForMultipleBookings(attendancesDto.bookingActivities, eventOutcome)
return attendances.stream().map(this::toAttendanceDto).collect(Collectors.toSet())
}
fun getAbsencesForReason(
prisonId: String?,
absentReason: AbsentReason?,
fromDate: LocalDate,
toDate: LocalDate?,
period: TimePeriod?,
): List<AbsenceDto> {
val periods = period?.let { setOf(it) } ?: setOf(TimePeriod.PM, TimePeriod.AM)
val endDate = toDate ?: fromDate
val attendances = attendanceRepository
.findByPrisonIdAndEventDateBetweenAndPeriodInAndAbsentReason(prisonId, fromDate, endDate, periods, absentReason)
val attendanceMap = attendances.associateBy({ it.eventId }, { it })
val offenderDetails = if (attendanceMap.isNotEmpty()) {
prisonApiService.getScheduleActivityOffenderData(prisonId, attendanceMap.keys)
} else {
emptyList()
}
return offenderDetails.map { toAbsenceDto2(it, attendanceMap[it.eventId]!!) }
}
@Transactional
fun deleteAttendancesForOffenderDeleteEvent(offenderNo: String, bookingIds: List<Long>) {
var totalAttendances = 0
bookingIds.map { bookingId ->
val attendances = attendanceRepository.findByBookingId(bookingId)
log.info("Deleting the following attendance records ${attendances.map { it.id }.joinToString(",")}")
attendanceRepository.deleteAll(attendances)
totalAttendances += attendances.size
}
telemetryClient.trackEvent(
"OffenderDelete",
mapOf("offenderNo" to offenderNo, "count" to totalAttendances.toString()),
null,
)
}
fun getAttendanceChanges(fromDateTime: LocalDateTime, toDateTime: LocalDateTime?, agencyId: String? = null): Set<AttendanceChangeDto> {
val changes =
if (toDateTime == null) {
attendanceChangesRepository.findAttendanceChangeByCreateDateTime(fromDateTime, agencyId)
} else {
attendanceChangesRepository.findAttendanceChangeByCreateDateTimeBetween(fromDateTime, toDateTime, agencyId)
}
return changes
.map {
AttendanceChangeDto(
id = it.id!!,
attendanceId = it.attendance.id,
bookingId = it.attendance.bookingId,
eventId = it.attendance.eventId,
eventLocationId = it.attendance.eventLocationId,
changedFrom = it.changedFrom,
changedTo = it.changedTo,
changedOn = it.createDateTime,
changedBy = it.createUserId,
prisonId = it.attendance.prisonId,
)
}.toSet()
}
private fun countAttendances(offenderAttendances: List<OffenderAttendance>): AttendanceSummary {
val summary = AttendanceSummary()
offenderAttendances.forEach { offenderAttendance ->
when (offenderAttendance.outcome) {
"UNACAB" -> {
summary.unacceptableAbsence++
summary.total++
}
"ATT", "UNBEH" -> summary.total++
"", null -> {}
else -> {
summary.acceptableAbsence++
summary.total++
}
}
}
return summary
}
fun getAttendanceAbsenceSummaryForOffender(
offenderNo: String,
fromDate: LocalDate,
toDate: LocalDate,
): AttendanceSummary {
val attendances =
prisonApiService.getAttendanceForOffender(offenderNo, fromDate, toDate, null, Pageable.unpaged())
return countAttendances(attendances.content)
}
fun getAttendanceDetailsForOffender(
offenderNo: String,
fromDate: LocalDate,
toDate: LocalDate,
pageable: Pageable,
): Page<AttendanceHistoryDto> =
prisonApiService.getAttendanceForOffender(offenderNo, fromDate, toDate, "UNACAB", pageable)
.map {
AttendanceHistoryDto(
eventDate = LocalDate.parse(it.eventDate),
activity = it.activity,
activityDescription = it.description,
location = it.prisonId,
comments = it.comment,
)
}
private fun offenderDetailsWithPeriod(details: OffenderDetails, period: TimePeriod): OffenderDetails =
details.copy(
bookingId = details.bookingId,
offenderNo = details.offenderNo,
eventId = details.eventId,
cellLocation = details.cellLocation,
eventDate = details.eventDate,
timeSlot = period.toString(),
firstName = details.firstName,
lastName = details.lastName,
comment = details.comment,
suspended = details.suspended,
)
private fun toAbsenceDto(details: OffenderDetails, attendance: Attendance): AbsenceDto =
AbsenceDto(
attendanceId = attendance.id,
bookingId = attendance.bookingId,
offenderNo = details.offenderNo,
eventId = attendance.eventId,
eventLocationId = attendance.eventLocationId,
eventDate = attendance.eventDate,
period = TimePeriod.valueOf(details.timeSlot!!),
reason = attendance.absentReason,
subReason = attendance.absentSubReason,
subReasonDescription = attendance.absentSubReason?.label,
eventDescription = details.comment,
comments = attendance.comments,
cellLocation = details.cellLocation,
firstName = details.firstName,
lastName = details.lastName,
suspended = details.suspended,
)
private fun toAbsenceDto2(details: OffenderDetails, attendance: Attendance): AbsenceDto =
AbsenceDto(
attendanceId = attendance.id,
bookingId = attendance.bookingId,
offenderNo = details.offenderNo,
eventId = attendance.eventId,
eventLocationId = attendance.eventLocationId,
eventDate = attendance.eventDate,
period = attendance.period,
reason = attendance.absentReason,
subReason = attendance.absentSubReason,
subReasonDescription = attendance.absentSubReason?.label,
eventDescription = details.comment,
comments = attendance.comments,
cellLocation = details.cellLocation,
firstName = details.firstName,
lastName = details.lastName,
suspended = details.suspended,
)
private fun findAttendance(bookingId: Long, eventId: Long?, period: TimePeriod): Predicate<in OffenderDetails> {
return Predicate { (bookingId1, _, eventId1, _, _, timeSlot) ->
bookingId1 == bookingId && eventId1 == eventId && TimePeriod.valueOf(timeSlot!!) == period
}
}
private fun toAttendance(attendanceDto: CreateAttendanceDto): Attendance =
Attendance
.builder()
.eventLocationId(attendanceDto.eventLocationId)
.eventDate(attendanceDto.eventDate)
.eventId(attendanceDto.eventId)
.bookingId(attendanceDto.bookingId)
.period(attendanceDto.period)
.paid(attendanceDto.paid)
.attended(attendanceDto.attended)
.prisonId(attendanceDto.prisonId)
.absentReason(attendanceDto.absentReason)
.absentSubReason(attendanceDto.absentSubReason)
.comments(attendanceDto.comments)
.build()
private fun toAttendanceDto(attendanceData: Attendance): AttendanceDto =
AttendanceDto.builder()
.id(attendanceData.id)
.eventDate(attendanceData.eventDate)
.eventId(attendanceData.eventId)
.bookingId(attendanceData.bookingId)
.period(attendanceData.period)
.paid(attendanceData.paid)
.attended(attendanceData.attended)
.prisonId(attendanceData.prisonId)
.absentReason(attendanceData.absentReason)
.absentSubReason(attendanceData.absentSubReason)
.eventLocationId(attendanceData.eventLocationId)
.comments(attendanceData.comments)
.createUserId(attendanceData.createUserId)
.createDateTime(attendanceData.createDateTime)
.caseNoteId(attendanceData.caseNoteId)
.locked(isAttendanceLocked(attendanceData))
.modifyDateTime(attendanceData.modifyDateTime)
.modifyUserId(attendanceData.modifyUserId)
.build()
}
| 6 | Kotlin | 1 | 1 | daf794b5997acfdc9e5364603d936fabe2d735e7 | 18,777 | whereabouts-api | Apache License 2.0 |
projects/ComposeConstraintLayout/app/src/main/java/com/example/constraintlayout/motion/dsl/ExtendingConstraintSets.kt | androidx | 212,409,034 | false | null | /*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.constraintlayout.motion.dsl
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.layoutId
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.constraintlayout.compose.ConstraintSet
import androidx.constraintlayout.compose.Dimension
import androidx.constraintlayout.compose.MotionLayout
import com.example.constraintlayout.R
@Preview
@Composable
private fun DslStartWithJsonEndExample() {
val start = ConstraintSet {
val image1 = createRefFor("image1")
val image2 = createRefFor("image2")
createVerticalChain(image1, image2)
constrain(image1) {
width = Dimension.value(200.dp)
height = Dimension.value(200.dp)
centerHorizontallyTo(parent)
rotationZ = 45f
}
constrain(image2) {
width = Dimension.value(200.dp)
height = Dimension.value(200.dp)
centerHorizontallyTo(parent)
}
}
val end = ConstraintSet(start, jsonContent = """
{
image1: {
// Other constraints are derived from the start ConstraintSet in DSL
rotationZ: -45
}
}
""".trimIndent())
CommonMotionLayout(start = start, end = end)
}
@Preview
@Composable
private fun JsonStartWithDslEndExample() {
val start = ConstraintSet(jsonContent = """
{
Helpers: [
['vChain', ['image1','image2'], {
top: ['parent', 'top'],
bottom: ['parent', 'bottom'],
style: 'spread'
}]],
image1: {
width: 200, height: 200,
centerHorizontally: 'parent',
rotationZ: 90,
},
image2: {
width: 200, height: 200,
centerHorizontally: 'parent'
}
}
""".trimIndent())
val end = ConstraintSet(start) {
constrain(createRefFor("image1")) {
rotationZ = -90f
}
}
CommonMotionLayout(start = start, end = end)
}
@Composable
private fun CommonMotionLayout(
start: ConstraintSet,
end: ConstraintSet
) {
var animateToEnd by remember { mutableStateOf(false) }
val progress by animateFloatAsState(
targetValue = if (animateToEnd) 1f else 0f,
animationSpec = tween(2000)
)
Column {
MotionLayout(
modifier = Modifier
.fillMaxWidth()
.height(500.dp),
start = start,
end = end,
progress = progress) {
Image(
modifier = Modifier.layoutId("image1"),
painter = painterResource(id = R.drawable.intercom_snooze),
contentDescription = null
)
Image(
modifier = Modifier.layoutId("image2"),
painter = painterResource(id = R.drawable.intercom_snooze),
contentDescription = null
)
}
Button(onClick = { animateToEnd = !animateToEnd }) {
Text("Run")
}
}
} | 83 | Java | 164 | 986 | de916779a3065bd23e21f9180bf6af62468b5518 | 4,209 | constraintlayout | Apache License 2.0 |
src/org/jetbrains/r/visualization/inlays/components/InlayTablePage.kt | JetBrains | 214,212,060 | false | {"Kotlin": 2717574, "Java": 559646, "R": 37082, "Lex": 14307, "HTML": 10063, "Rez": 70, "Rebol": 47} | /*
* 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 org.jetbrains.plugins.notebooks.visualization.r.inlays.components
import com.intellij.icons.AllIcons
import com.intellij.ide.CopyProvider
import com.intellij.ide.DataManager
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.fileChooser.FileChooserFactory
import com.intellij.openapi.fileChooser.FileSaverDescriptor
import com.intellij.openapi.fileChooser.FileSaverDialog
import com.intellij.openapi.ide.CopyPasteManager
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.DumbAwareToggleAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.ui.IdeBorderFactory
import com.intellij.ui.SideBorder
import com.intellij.ui.components.JBScrollPane
import com.intellij.ui.table.JBTable
import com.intellij.util.ui.TextTransferable
import org.jetbrains.plugins.notebooks.visualization.NotebooksVisualizationIcons
import org.jetbrains.plugins.notebooks.visualization.r.VisualizationBundle
import org.jetbrains.plugins.notebooks.visualization.r.inlays.ClipboardUtils
import org.jetbrains.plugins.notebooks.visualization.r.inlays.dataframe.DataFrame
import org.jetbrains.plugins.notebooks.visualization.r.inlays.dataframe.columns.DoubleType
import org.jetbrains.plugins.notebooks.visualization.r.inlays.dataframe.columns.IntType
import org.jetbrains.plugins.notebooks.visualization.r.inlays.table.*
import org.jetbrains.plugins.notebooks.visualization.r.inlays.table.filters.gui.TableFilterHeader
import org.jetbrains.plugins.notebooks.visualization.r.inlays.table.paging.TablePaginator
import org.jetbrains.plugins.notebooks.visualization.r.ui.MaterialTable
import org.jetbrains.plugins.notebooks.visualization.r.ui.MaterialTableUtils
import java.awt.BorderLayout
import java.awt.Event
import java.awt.event.ActionEvent
import java.awt.event.KeyAdapter
import java.awt.event.KeyEvent
import java.io.BufferedWriter
import java.io.File
import javax.swing.*
import javax.swing.table.TableRowSorter
/**
* Table page of notebook inlay component. Hold and serve table.
* By default table has a context menu with "copy selection" action and toolbar with action "Save as tsv".
*/
class InlayTablePage : JPanel(BorderLayout()), ToolBarProvider {
var onChange: (() -> Unit)? = null
private val table = MaterialTable()
val scrollPane = JBScrollPane(table)
private var filterHeader: TableFilterHeader? = null
private var paginator: TablePaginator? = null
val preferredHeight: Int
get() {
return table.preferredSize.height
}
class TableCopyProvider(private val table: JBTable) : CopyProvider {
override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.EDT
override fun performCopy(dataContext: DataContext) {
val copySelectedToString: CharSequence = ClipboardUtils.copySelectedToString(table)
CopyPasteManager.getInstance().setContents(TextTransferable(copySelectedToString))
}
override fun isCopyEnabled(dataContext: DataContext): Boolean {
return table.selectedRowCount > 0
}
override fun isCopyVisible(dataContext: DataContext): Boolean {
return true
}
}
init {
// Disposer.register(parent, disposable)
table.putClientProperty("AuxEditorComponent", true)
scrollPane.border = IdeBorderFactory.createBorder(SideBorder.RIGHT)
scrollPane.viewportBorder = IdeBorderFactory.createBorder(SideBorder.BOTTOM or SideBorder.LEFT or SideBorder.RIGHT)
setupTablePopupMenu(table)
// setupCopySelectedAction(table)
setupSelectAllAction(table)
table.addKeyListener(object : KeyAdapter() {
override fun keyPressed(e: KeyEvent) {
if (filterHeader == null && e.keyChar.isLetterOrDigit()) {
addTableFilterHeader()
}
}
})
DataManager.registerDataProvider(table) { dataId ->
if (PlatformDataKeys.COPY_PROVIDER.`is`(dataId)) TableCopyProvider(table) else null
}
add(scrollPane, BorderLayout.CENTER)
}
private fun setupTablePopupMenu(table: JTable) {
val copyAll = JMenuItem(VisualizationBundle.message("inlay.table.copy.all"))
copyAll.addActionListener { ClipboardUtils.copyAllToClipboard(table) }
val copySelected = JMenuItem(VisualizationBundle.message("inlay.table.copy.selected"))
copySelected.addActionListener { ClipboardUtils.copySelectedToClipboard(table) }
val popupMenu = JPopupMenu()
popupMenu.add(copyAll)
popupMenu.add(copySelected)
table.componentPopupMenu = popupMenu
}
private fun setupSelectAllAction(table: JTable) {
val actionName = VisualizationBundle.message("action.name.table.select.all")
val action = object : AbstractAction(actionName) {
override fun actionPerformed(e: ActionEvent) {
table.setRowSelectionInterval(0, table.rowCount - 1)
table.setColumnSelectionInterval(0, table.columnCount - 1)
}
}
table.actionMap.put(actionName, action)
table.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_A, Event.CTRL_MASK), actionName)
}
private inner class NumberComparator<T : Comparable<*>> : Comparator<T> {
override fun compare(o1: T, o2: T): Int {
return compareValues(o1, o2)
}
}
/**
* Sets the data frame for displaying in table.
* also setups tableRowSorter with natural comparators for Int and double columns
*/
fun setDataFrame(dataFrame: DataFrame) {
table.columnModel = DataFrameColumnModel(dataFrame)
table.model = DataFrameTableModel(dataFrame)
for (i in dataFrame.getColumns().indices) {
table.columnModel.getColumn(i).cellRenderer = when (dataFrame[i].type) {
IntType -> IntegerTableCellRenderer()
DoubleType -> DoubleTableCellRenderer()
else -> StringTableCellRenderer()
}
}
MaterialTableUtils.fitColumnsWidth(table)
val tableRowSorter = TableRowSorter(table.model)
tableRowSorter.sortsOnUpdates = true
for ((i, column) in dataFrame.getColumns().withIndex()) {
if (column.type is IntType) {
tableRowSorter.setComparator(i, NumberComparator<Int>())
}
else if (column.type is DoubleType) {
tableRowSorter.setComparator(i, NumberComparator<Double>())
}
}
table.rowSorter = tableRowSorter
}
private fun addTableFilterHeader() {
filterHeader = TableFilterHeader()
filterHeader!!.installTable(table)
}
override fun createActions(): List<AnAction> {
val actionSaveAsCsv = object : DumbAwareAction(VisualizationBundle.message("inlay.table.export.as.text"),
VisualizationBundle.message("inlay.table.export.as.description"),
AllIcons.ToolbarDecorator.Export) {
override fun actionPerformed(e: AnActionEvent) {
saveAsCsv(e.project ?: return)
}
}
val filterTable = object : DumbAwareToggleAction(VisualizationBundle.message("inlay.table.filter.text"),
VisualizationBundle.message("inlay.table.filter.description"),
AllIcons.Actions.Find) {
override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.EDT
override fun isSelected(e: AnActionEvent): Boolean {
return filterHeader != null
}
override fun setSelected(e: AnActionEvent, state: Boolean) {
if (state) {
addTableFilterHeader()
}
else {
filterHeader?.installTable(null)
filterHeader = null
}
}
}
val paginateTable = object : DumbAwareToggleAction(VisualizationBundle.message("inlay.table.pagination.text"),
null,
NotebooksVisualizationIcons.Table.Pagination) {
override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.EDT
override fun isSelected(e: AnActionEvent): Boolean {
return paginator != null
}
override fun setSelected(e: AnActionEvent, state: Boolean) {
if (state) {
paginator = TablePaginator()
paginator!!.table = table
}
else {
paginator?.table = null
paginator = null
}
}
}
return listOf(actionSaveAsCsv, filterTable, paginateTable)
}
/** Save the file as tsv (tab separated values) via intellij SaveFileDialog. */
private fun saveAsCsv(project: Project) {
val descriptor = FileSaverDescriptor(VisualizationBundle.message("inlay.table.export.as.csv.text"),
VisualizationBundle.message("inlay.table.export.as.csv.description"), "csv",
"tsv")
val chooser: FileSaverDialog = FileChooserFactory.getInstance().createSaveFileDialog(descriptor, this)
val basePath = project.basePath ?: return
val virtualBaseDir = LocalFileSystem.getInstance().findFileByIoFile(File(basePath))
val fileWrapper = chooser.save(virtualBaseDir, "table.csv") ?: return
fun saveSelection(out: BufferedWriter, cellBreak: String) {
val selectedColumnCount = table.selectedColumnCount
val selectedRowCount = table.selectedRowCount
val selectedRows = table.selectedRows
val selectedColumns = table.selectedColumns
for (i in 0 until selectedRowCount) {
for (j in 0 until selectedColumnCount) {
out.write(ClipboardUtils.escape(table.getValueAt(selectedRows[i], selectedColumns[j])))
if (j < selectedColumnCount - 1) {
out.write(cellBreak)
}
}
if (i < table.rowCount - 1) {
out.append(ClipboardUtils.LINE_BREAK)
}
}
}
fun saveAll(out: BufferedWriter, cellBreak: String) {
for (i in 0 until table.rowCount) {
for (j in 0 until table.columnCount) {
out.write(ClipboardUtils.escape(table.getValueAt(i, j)))
if (j < table.columnCount - 1) {
out.write(cellBreak)
}
}
if (i < table.rowCount - 1) {
out.append(ClipboardUtils.LINE_BREAK)
}
}
}
fileWrapper.file.bufferedWriter().use { out ->
val cellBreak = if (fileWrapper.file.extension == "csv") ";" else "\t"
if (table.selectedColumnCount == 0 || table.selectedRowCount == 0) {
saveAll(out, cellBreak)
}
else {
saveSelection(out, cellBreak)
}
}
}
} | 284 | Kotlin | 5162 | 61 | dc931d6d51748c265b53fbd76c4e9f8a6996bb1b | 10,720 | Rplugin | Apache License 2.0 |
vuesaxicons/src/commonMain/kotlin/moe/tlaster/icons/vuesax/vuesaxicons/broken/Brush3.kt | Tlaster | 560,394,734 | false | {"Kotlin": 25133302} | package moe.tlaster.icons.vuesax.vuesaxicons.broken
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeCap.Companion.Round
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import moe.tlaster.icons.vuesax.vuesaxicons.BrokenGroup
public val BrokenGroup.Brush3: ImageVector
get() {
if (_brush3 != null) {
return _brush3!!
}
_brush3 = Builder(name = "Brush3", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF292D32)),
strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(18.0198f, 3.0101f)
curveTo(18.6898f, 2.6501f, 19.3498f, 2.3401f, 19.9598f, 2.1001f)
curveTo(20.5498f, 1.8801f, 21.1198f, 2.0401f, 21.4798f, 2.4101f)
curveTo(21.8598f, 2.7901f, 22.0398f, 3.3601f, 21.7998f, 3.9501f)
curveTo(20.2598f, 7.7901f, 16.3998f, 13.0101f, 13.1698f, 15.6001f)
lineTo(11.1998f, 17.1801f)
curveTo(10.9498f, 17.3601f, 10.6998f, 17.5201f, 10.4198f, 17.6301f)
curveTo(10.4198f, 17.4501f, 10.4098f, 17.2501f, 10.3798f, 17.0601f)
curveTo(10.2698f, 16.2201f, 9.8898f, 15.4401f, 9.2198f, 14.7701f)
curveTo(8.5398f, 14.0901f, 7.7098f, 13.6901f, 6.8598f, 13.5801f)
curveTo(6.6598f, 13.5701f, 6.4598f, 13.5501f, 6.2598f, 13.5701f)
curveTo(6.3698f, 13.2601f, 6.5398f, 12.9701f, 6.7498f, 12.7301f)
lineTo(8.3098f, 10.7601f)
curveTo(9.6598f, 9.0701f, 11.7498f, 7.2001f, 13.9698f, 5.5801f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF292D32)),
strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(10.4293f, 17.6198f)
curveTo(10.4293f, 18.7198f, 10.0093f, 19.7698f, 9.2193f, 20.5698f)
curveTo(8.6093f, 21.1798f, 7.7793f, 21.5998f, 6.7893f, 21.7298f)
lineTo(4.3293f, 21.9998f)
curveTo(2.9893f, 22.1498f, 1.8393f, 21.0098f, 1.9993f, 19.6498f)
lineTo(2.2693f, 17.1898f)
curveTo(2.5093f, 14.9998f, 4.3393f, 13.5998f, 6.2793f, 13.5598f)
curveTo(6.4793f, 13.5498f, 6.6893f, 13.5598f, 6.8793f, 13.5698f)
curveTo(7.7293f, 13.6798f, 8.5593f, 14.0698f, 9.2393f, 14.7598f)
curveTo(9.9093f, 15.4298f, 10.2893f, 16.2098f, 10.3993f, 17.0498f)
curveTo(10.4093f, 17.2398f, 10.4293f, 17.4298f, 10.4293f, 17.6198f)
close()
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF292D32)),
strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(14.2398f, 14.4702f)
curveTo(14.2398f, 11.8602f, 12.1198f, 9.7402f, 9.5098f, 9.7402f)
}
}
.build()
return _brush3!!
}
private var _brush3: ImageVector? = null
| 0 | Kotlin | 0 | 2 | b8a8231e6637c2008f675ae76a3423b82ee53950 | 3,888 | VuesaxIcons | MIT License |
kbip44/src/test/kotlin/org/komputing/kbip44/TheBIP44.kt | komputing | 221,162,647 | false | null | package org.komputing.kbip44
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Assertions.assertThrows
import org.junit.jupiter.api.Test
class TheBIP44 {
@Test
fun parsingFailsForBadInput() {
assertThrows(IllegalArgumentException::class.java){
BIP44("abc")
}
}
@Test
fun parsingFailsForEmptyInput() {
assertThrows(IllegalArgumentException::class.java){
BIP44("")
}
}
@Test
fun parsingFailsForMissingNumber() {
assertThrows(IllegalArgumentException::class.java){
BIP44("m/0/")
}
}
val stringProbes = mapOf(
"m" to listOf(),
"m/0" to listOf(BIP44Element(false, 0)),
"m/0/1" to listOf(BIP44Element(false, 0), BIP44Element(false, 1)),
"m/44'" to listOf(BIP44Element(true, 44)),
"m/44'/1" to listOf(BIP44Element(true, 44), BIP44Element(false, 1))
)
val intProbes = mapOf(
"m" to listOf(),
"m/0" to listOf(0),
"m/0/1" to listOf(0, 1),
"m/0'" to listOf(0x80000000.toInt()),
"m/1'/1" to listOf(0x80000001.toInt(), 1)
)
val dirtyStringProbes = mapOf(
"m/44 ' " to listOf(BIP44Element(true, 44)),
"m/0 /1 ' " to listOf(BIP44Element(false, 0), BIP44Element(true, 1))
)
@Test
fun fromPathWork() {
for ((key, value) in (stringProbes + dirtyStringProbes)) {
assertThat(BIP44(key).path).isEqualTo(value)
}
}
@Test
fun toStringFromIntoWorks() {
for ((path, ints) in (intProbes)) {
assertThat(BIP44(path).path.map { it.numberWithHardeningFlag }).isEqualTo(ints)
}
}
@Test
fun toStringWorks() {
for ((key, value) in (stringProbes)) {
assertThat(key).isEqualTo(BIP44(value).toString())
}
}
@Test
fun incrementWorks() {
assertThat(BIP44("m/0/1/2").increment())
.isEqualTo(BIP44("m/0/1/3"))
}
} | 4 | null | 0 | 2 | d68ec7c42993926e3b81a524864f683447893c9e | 2,063 | KBIP44 | MIT License |
taxi-cli/src/main/java/lang/taxi/cli/config/TaxiProjectLoader.kt | taxilang | 601,101,781 | false | {"Kotlin": 1614057, "ANTLR": 66122, "TypeScript": 7231, "JavaScript": 4324, "Shell": 1468, "Java": 1454, "MDX": 425} | package lang.taxi.cli.config
import com.typesafe.config.Config
import com.typesafe.config.ConfigFactory
import com.typesafe.config.ConfigRenderOptions
import io.github.config4k.extract
import lang.taxi.packages.TaxiPackageProject
import org.apache.commons.lang3.SystemUtils
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.nio.file.Path
class TaxiProjectLoader(searchPaths: List<Path> = DEFAULT_PATHS) {
private val pathsToSearch: MutableList<Path> = mutableListOf()
init {
pathsToSearch.addAll(searchPaths)
}
companion object {
fun noDefaults():TaxiProjectLoader = TaxiProjectLoader(emptyList())
val DEFAULT_PATHS = listOf(
SystemUtils.getUserHome().toPath().resolve(".taxi/taxi.conf")
)
val log: Logger = LoggerFactory.getLogger(TaxiProjectLoader::class.java)
}
fun withConfigFileAt(path: Path): TaxiProjectLoader {
pathsToSearch.add(path)
return this
}
fun load(): TaxiPackageProject {
log.debug("Searching for config files at {}", pathsToSearch.joinToString(" , "))
val configs: MutableList<Config> = pathsToSearch.filter { path -> path.toFile().exists() }
.map { path ->
log.debug("Reading config at {}", path.toString())
val config: Config = ConfigFactory.parseFile(path.toFile())
config
}.toMutableList()
configs.add(ConfigFactory.load())
val config = configs.reduceRight(Config::withFallback)
log.debug("Effective config:")
log.debug(config.root().render(ConfigRenderOptions.defaults()))
return config.extract()
}
}
| 8 | Kotlin | 5 | 75 | b94c71c7c8751c05c4f466c58c4483dac3f2e421 | 1,624 | taxilang | Apache License 2.0 |
app/src/main/java/com/github2136/base/view/activity/login/LoginVM.kt | github2136 | 210,985,491 | false | {"Kotlin": 141857, "Java": 10614} | package com.github2136.base.view.activity.login
import android.app.Application
import androidx.lifecycle.MutableLiveData
import com.github2136.base.repository.UserRepository
import com.github2136.base.repository.WeatherRepository
import com.github2136.basemvvm.BaseVM
import com.github2136.basemvvm.ResultRepo
/**
* Created by YB on 2019/8/28
*/
class LoginVM(app: Application) : BaseVM(app) {
val userRepository by lazy { UserRepository(app) }
val weatherRepository by lazy { WeatherRepository(app) }
val userNameLD = MutableLiveData<String>()
val passWordLD = MutableLiveData<String>()
val userInfoLD = MutableLiveData<Any>()
val weatherLD = MutableLiveData<String>()
fun getWeather() {
launch {
val resultRepo = weatherRepository.getWeather()
when (resultRepo) {
is ResultRepo.Success -> {
resultRepo.data.weatherinfo
weatherLD.value = resultRepo.toString()
}
is ResultRepo.Error -> {
weatherLD.value = resultRepo.msg
}
}
}
}
fun getWeather2() {
launch {
val resultRepo = weatherRepository.getWeather2()
when (resultRepo) {
is ResultRepo.Success -> {
}
is ResultRepo.Error -> {
if (resultRepo.code == 404) {
toastLD.value = "404"
}
}
}
}
}
fun login() {
launch {
dialogLD.value = DialogData(loadingStr)
val resultRepo = userRepository.loginFlow(userNameLD.value!!, passWordLD.value!!)
dialogLD.value = null
when (resultRepo) {
is ResultRepo.Success -> userInfoLD.value = resultRepo.data
is ResultRepo.Error -> userInfoLD.value = resultRepo.msg
}
}
}
} | 0 | Kotlin | 0 | 2 | 8ec63d87d4a25c599704ced72bb842513f16975e | 1,974 | Base | Apache License 2.0 |
src/nl/hannahsten/texifyidea/structure/latex/LatexFilePresentation.kt | sundermann | 325,311,190 | true | {"Gradle Kotlin DSL": 2, "Java Properties": 1, "Markdown": 7, "Shell": 1, "Text": 2, "Ignore List": 1, "Batchfile": 1, "EditorConfig": 1, "YAML": 3, "Kotlin": 592, "Java": 93, "TeX": 38, "BibTeX": 3, "INI": 1, "XML": 5, "JFlex": 2, "CODEOWNERS": 1, "SVG": 74, "HTML": 98, "Python": 1} | package nl.hannahsten.texifyidea.structure.latex
import com.intellij.navigation.ItemPresentation
import com.intellij.psi.PsiFile
import nl.hannahsten.texifyidea.TexifyIcons
import nl.hannahsten.texifyidea.util.Magic
/**
* @author <NAME>
*/
open class LatexFilePresentation(private val file: PsiFile) : ItemPresentation {
private val presentableText = Magic.Pattern.fileExtension.matcher(file.name).replaceAll("")
override fun getPresentableText() = presentableText!!
override fun getLocationString() = file.virtualFile.path
override fun getIcon(b: Boolean) = TexifyIcons.DOT_LATEX!!
} | 1 | null | 0 | 0 | afb253cfce2159660097792682e05c147851afe9 | 608 | TeXiFy-IDEA | MIT License |
src/main/java/ir/rkr/kariz2/main.kt | silkenpy | 180,726,939 | false | null | package ir.rkr.kariz2
import com.typesafe.config.ConfigFactory
import ir.rkr.kariz2.kafka.KafkaConnector
import ir.rkr.kariz2.netty.NettyServer
import ir.rkr.kariz2.redis.RedisConnector
import ir.rkr.kariz2.rest.JettyRestServer
import ir.rkr.kariz2.util.KarizMetrics
import mu.KotlinLogging
const val version = 0.1
/**
* Kariz main entry point.
*/
fun main(args: Array<String>) {
val logger = KotlinLogging.logger {}
val config = ConfigFactory.defaultApplication()
val karizMetrics = KarizMetrics()
val kafka = KafkaConnector(config.getString("kafka.topic"), config, karizMetrics,"default")
val redis = RedisConnector( config, karizMetrics)
NettyServer(kafka, redis, config, karizMetrics)
JettyRestServer(redis, config,karizMetrics)
logger.info { "Kariz V$version is ready :D" }
} | 3 | Kotlin | 0 | 0 | 51d938e5c548734b2564201774c3f761f6d82f5c | 825 | kariz2 | MIT License |
cpg-core/src/main/kotlin/de/fraunhofer/aisec/cpg/graph/statements/expressions/InitializerListExpression.kt | Fraunhofer-AISEC | 225,386,107 | false | null | /*
* Copyright (c) 2020, Fraunhofer AISEC. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* $$$$$$\ $$$$$$$\ $$$$$$\
* $$ __$$\ $$ __$$\ $$ __$$\
* $$ / \__|$$ | $$ |$$ / \__|
* $$ | $$$$$$$ |$$ |$$$$\
* $$ | $$ ____/ $$ |\_$$ |
* $$ | $$\ $$ | $$ | $$ |
* \$$$$$ |$$ | \$$$$$ |
* \______/ \__| \______/
*
*/
package de.fraunhofer.aisec.cpg.graph.statements.expressions
import de.fraunhofer.aisec.cpg.graph.*
import de.fraunhofer.aisec.cpg.graph.edge.PropertyEdge
import de.fraunhofer.aisec.cpg.graph.edge.PropertyEdge.Companion.propertyEqualsList
import de.fraunhofer.aisec.cpg.graph.edge.PropertyEdgeDelegate
import de.fraunhofer.aisec.cpg.graph.types.HasType
import de.fraunhofer.aisec.cpg.graph.types.PointerType
import de.fraunhofer.aisec.cpg.graph.types.Type
import java.util.*
import org.apache.commons.lang3.builder.ToStringBuilder
import org.neo4j.ogm.annotation.Relationship
/**
* This node represents the initialization of an "aggregate" object, such as an array or a struct or
* object. The actual use can greatly differ by the individual language frontends. In order to be as
* accurate as possible when propagating types, the [InitializerListExpression.type] property MUST
* be set before adding any values to [InitializerListExpression.initializers].
*/
// TODO Merge and/or refactor
class InitializerListExpression : Expression(), ArgumentHolder, HasType.TypeObserver {
/** The list of initializers. */
@Relationship(value = "INITIALIZERS", direction = Relationship.Direction.OUTGOING)
@AST
var initializerEdges = mutableListOf<PropertyEdge<Expression>>()
set(value) {
field.forEach { it.end.unregisterTypeObserver(this) }
field = value
value.forEach { it.end.registerTypeObserver(this) }
}
/** Virtual property to access [initializerEdges] without property edges. */
var initializers by PropertyEdgeDelegate(InitializerListExpression::initializerEdges)
override fun toString(): String {
return ToStringBuilder(this, TO_STRING_STYLE)
.appendSuper(super.toString())
.append("initializers", initializers)
.toString()
}
override fun addArgument(expression: Expression) {
this.initializers += expression
}
override fun replaceArgument(old: Expression, new: Expression): Boolean {
val idx = initializerEdges.indexOfFirst { it.end == old }
if (idx != -1) {
old.unregisterTypeObserver(this)
initializerEdges[idx].end = new
new.registerTypeObserver(this)
return true
}
return false
}
override fun hasArgument(expression: Expression): Boolean {
return expression in this.initializers
}
override fun typeChanged(newType: Type, src: HasType) {
// Normally, we would check, if the source comes from our initializers, but we want to limit
// the iteration of the initializer list (which can potentially contain tens of thousands of
// entries in generated code), we skip it here.
//
// So we just have to look what kind of object we are initializing (its type is stored in
// our "type"), to see whether we need to propagate something at all. If it has an array
// type, we need to propagate an array version of the incoming type. If our "target" is a
// regular object type, we do NOT propagate anything at all, because in this case we get the
// types of individual fields, and we are not interested in those (yet).
val type = type
if (type is PointerType && type.pointerOrigin == PointerType.PointerOrigin.ARRAY) {
addAssignedType(newType.array())
}
}
override fun assignedTypeChanged(assignedTypes: Set<Type>, src: HasType) {
// Same as above, we can just propagate the incoming assigned types to us (in array form),
// if we are initializing an array
val type = type
if (type is PointerType && type.pointerOrigin == PointerType.PointerOrigin.ARRAY) {
addAssignedTypes(assignedTypes.map { it.array() }.toSet())
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is InitializerListExpression) return false
return super.equals(other) &&
initializers == other.initializers &&
propertyEqualsList(initializerEdges, other.initializerEdges)
}
override fun hashCode(): Int {
// Including initializerEdges directly is a HUGE performance loss in the calculation of each
// hash code. Therefore, we only include the array's size, which should hopefully be sort of
// unique to avoid too many hash collisions.
return Objects.hash(super.hashCode(), initializerEdges.size)
}
}
| 96 | null | 61 | 268 | 9562371fd01a98614a1050dbf5927e3b19444067 | 5,583 | cpg | Apache License 2.0 |
shared/src/commonMain/kotlin/ui/screen/PreferenceScreen.kt | sdercolin | 708,470,210 | false | null | package ui.screen
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
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.size
import androidx.compose.material.AlertDialog
import androidx.compose.material.Divider
import androidx.compose.material.Icon
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Switch
import androidx.compose.material.SwitchDefaults
import androidx.compose.material.Text
import androidx.compose.material.TextButton
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowForwardIos
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.DialogProperties
import cafe.adriel.voyager.navigator.LocalNavigator
import cafe.adriel.voyager.navigator.currentOrThrow
import const.APP_NAME
import io.LocalFileInteractor
import io.Paths
import model.AppPreference
import repository.LocalAppPreferenceRepository
import repository.LocalGuideAudioRepository
import repository.LocalReclistRepository
import repository.LocalSessionRepository
import ui.common.DisabledMutableInteractionSource
import ui.common.ScrollableColumn
import ui.model.Screen
import ui.string.*
import util.Log
import util.appVersion
import util.isDesktop
import util.runIf
import util.runIfHave
import util.useIosStyle
object PreferenceScreen : Screen {
@Composable
override fun getTitle(): String = string(Strings.PreferenceScreenTitle)
@Composable
override fun Content() = ScreenContent()
}
@Composable
private fun ScreenContent() {
val repository = LocalAppPreferenceRepository.current
val navigator = LocalNavigator.currentOrThrow
val fileInteractor = LocalFileInteractor.current
val value by repository.flow.collectAsState()
ScrollableColumn(modifier = Modifier.fillMaxSize().background(MaterialTheme.colors.background)) {
Group(title = string(Strings.PreferenceGroupAppearance)) {
SelectionItem(
title = string(Strings.PreferenceLanguage),
value = value.language,
onValueChanged = { repository.update { copy(language = it) } },
options = AppPreference.Language.entries.toList(),
)
SelectionItem(
title = string(Strings.PreferenceTheme),
value = value.theme,
onValueChanged = { repository.update { copy(theme = it) } },
options = AppPreference.Theme.entries.toList().runIf(isDesktop) {
minus(AppPreference.Theme.System)
},
)
}
Group(title = string(Strings.PreferenceGroupRecording)) {
SwitchItem(
title = string(Strings.PreferenceContinuousRecording),
info = string(Strings.PreferenceContinuousRecordingDescription),
value = value.recording.continuous,
onValueChanged = { repository.update { copy(recording = recording.copy(continuous = it)) } },
)
SwitchItem(
title = string(Strings.PreferenceTrimRecording),
info = string(Strings.PreferenceTrimRecordingDescription),
value = value.recording.trim,
onValueChanged = { repository.update { copy(recording = recording.copy(trim = it)) } },
)
}
Group(title = string(Strings.PreferenceGroupMisc)) {
if (isDesktop) {
val guideAudioRepository = LocalGuideAudioRepository.current
val sessionRepository = LocalSessionRepository.current
val reclistRepository = LocalReclistRepository.current
key(value.customContentRootPath) {
Item(
title = string(Strings.PreferenceContentRootLocation),
info = Paths.contentRoot.parentFile?.absolutePath ?: "",
onClick = {
fileInteractor.pickFile(
title = stringStatic(Strings.PreferenceContentRootLocation),
allowedExtensions = listOf(""),
initialDirectory = Paths.contentRoot.parentFile,
onFinish = { file ->
file ?: return@pickFile
Log.i("Setting custom content root: ${file.absolutePath}")
repository.update { copy(customContentRootPath = file.absolutePath) }
Paths.moveContentRoot(file)
guideAudioRepository.init()
sessionRepository.init()
reclistRepository.init()
},
)
},
)
}
}
Item(
title = string(Strings.PreferenceAbout),
info = "$APP_NAME $appVersion",
onClick = { navigator push AboutScreen },
)
}
}
}
@Composable
private fun Group(
title: String,
content: @Composable ColumnScope.() -> Unit,
) {
Column(modifier = Modifier.fillMaxWidth().padding(vertical = 16.dp)) {
Text(
modifier = Modifier.padding(start = 40.dp, end = 40.dp, top = 8.dp, bottom = 16.dp),
text = title,
style = MaterialTheme.typography.subtitle2,
color = MaterialTheme.colors.primary,
maxLines = 1,
)
content()
Divider(modifier = Modifier.padding(start = 24.dp))
}
}
@Composable
private fun <T : LocalizedTest> SelectionItem(
title: String,
value: T,
onValueChanged: (T) -> Unit,
options: List<T>,
) {
var isShowingDialog by remember { mutableStateOf(false) }
Item(
title = title,
info = value.getText(),
onClick = { isShowingDialog = true },
)
if (isShowingDialog) {
AlertDialog(
onDismissRequest = { isShowingDialog = false },
title = {
Text(text = title, fontWeight = FontWeight.Bold)
},
text = {
Column {
Text("", modifier = Modifier.height(16.dp))
options.forEach { option ->
Text(
text = option.getText(),
modifier = Modifier.fillMaxWidth()
.clickable {
onValueChanged(option)
isShowingDialog = false
}
.padding(vertical = 12.dp),
color = MaterialTheme.colors.onSurface,
textAlign = TextAlign.Center,
)
}
}
},
confirmButton = {
TextButton(onClick = { isShowingDialog = false }) {
Text(text = string(Strings.CommonCancel))
}
},
properties = DialogProperties(dismissOnClickOutside = true),
)
}
}
@Composable
private fun SwitchItem(
title: String,
info: String?,
value: Boolean,
onValueChanged: (Boolean) -> Unit,
) {
Item(
title = title,
info = info,
subItem = {
Switch(
modifier = Modifier.size(32.dp),
checked = value,
onCheckedChange = null,
colors = MaterialTheme.colors.run {
SwitchDefaults.colors(
checkedThumbColor = primary,
checkedTrackColor = primary,
)
},
// disable interaction
interactionSource = remember { DisabledMutableInteractionSource() },
)
},
onClick = { onValueChanged(!value) },
)
}
@Composable
private fun Item(
title: String,
info: String? = null,
subItem: @Composable (() -> Unit)? = if (useIosStyle) {
{
Icon(
imageVector = Icons.Default.ArrowForwardIos,
contentDescription = null,
modifier = Modifier.size(16.dp),
tint = MaterialTheme.colors.onSurface.copy(alpha = 0.6f),
)
}
} else {
null
},
onClick: (() -> Unit)? = null,
) {
Row(
modifier = Modifier.fillMaxWidth()
.padding(start = 24.dp)
.runIfHave(onClick) { clickable(onClick = it) }
.padding(top = 16.dp, bottom = 16.dp, start = 16.dp, end = if (isDesktop) 40.dp else 16.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Column(modifier = Modifier.weight(1f)) {
Text(
text = title,
style = MaterialTheme.typography.body1,
maxLines = 1,
)
info?.let {
Spacer(modifier = Modifier.height(4.dp))
Text(
text = info,
style = MaterialTheme.typography.caption.copy(
color = MaterialTheme.colors.onSurface.copy(alpha = 0.6f),
),
maxLines = 1,
)
}
}
subItem?.let {
it()
}
}
}
| 1 | null | 2 | 9 | 8ed61865b56192b1e484f2e36ddc0a33ec79e8e5 | 10,398 | recstar | Apache License 2.0 |
still/src/main/java/com/darwin/viola/still/detector/FaceDetectorProcessor.kt | darwinfrancis | 278,868,009 | false | null | /*
* Copyright 2020 Google LLC. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.darwin.viola.still.detector
import android.graphics.Bitmap
import com.darwin.viola.still.FaceAnalyser
import com.darwin.viola.still.FaceDetectionListener
import com.darwin.viola.still.Util
import com.darwin.viola.still.model.FaceDetectionError
import com.darwin.viola.still.model.FaceOptions
import com.darwin.viola.still.model.Result
import com.google.android.gms.tasks.Task
import com.google.mlkit.vision.common.InputImage
import com.google.mlkit.vision.face.Face
import com.google.mlkit.vision.face.FaceDetection
import com.google.mlkit.vision.face.FaceDetector
import com.google.mlkit.vision.face.FaceDetectorOptions
internal class FaceDetectorProcessor(
detectorOptions: FaceDetectorOptions,
private val faceDetectionListener: FaceDetectionListener
) :
VisionProcessorBase<List<Face>>() {
lateinit var faceOptions: FaceOptions
private val detector: FaceDetector = FaceDetection.getClient(detectorOptions)
private val faceAnalyser = FaceAnalyser()
override fun stop() {
super.stop()
detector.close()
}
override fun detectInImage(image: InputImage): Task<List<Face>> {
Util.printLog("Face detection process started.")
return detector.process(image)
}
override fun onSuccess(results: List<Face>, originalImage: Bitmap) {
Util.printLog("Face detection process completed without exceptions.")
if (results.isEmpty()) {
Util.printLog("Face detector can't find any face on the given image.")
faceDetectionListener.onFaceDetectionFailed(
FaceDetectionError.NO_FACE_DETECTED,
FaceDetectionError.NO_FACE_DETECTED.message
)
} else {
Util.printLog("Detected ${results.size} face(s), starting face analysis.")
val portraitList = faceAnalyser.analyzeFaces(results, originalImage, faceOptions)
if (portraitList.isEmpty()) {
Util.printLog("Face analyser can't find any valid face with given configuration.")
faceDetectionListener.onFaceDetectionFailed(
FaceDetectionError.NO_VALID_FACE_DETECTED,
FaceDetectionError.NO_VALID_FACE_DETECTED.message
)
} else {
Util.printLog("Found ${portraitList.size} valid face(s) out of ${results.size} by the analyser.")
val result =
Result(portraitList.size, portraitList)
faceDetectionListener.onFaceDetected(result)
}
}
}
override fun onFailure(e: Exception) {
Util.printLog("Face detection process failed with following exception {${e.message}}.")
faceDetectionListener.onFaceDetectionFailed(FaceDetectionError.ERROR, e.message!!)
}
}
| 1 | null | 13 | 59 | 7cd64737d2e6f8f4d173d3430211264328dbd313 | 3,419 | viola-face-detection | MIT License |
server/src/main/kotlin/com/kamelia/hedera/websocket/Handlers.kt | Black-Kamelia | 492,280,011 | false | null | package com.kamelia.hedera.websocket
import com.kamelia.hedera.rest.auth.SessionManager
import com.kamelia.hedera.rest.user.UserEvents
import com.kamelia.hedera.rest.user.UserForcefullyLoggedOutDTO
import com.kamelia.hedera.rest.user.UserRepresentationDTO
import com.kamelia.hedera.util.defineEventListener
import com.kamelia.hedera.util.forcefullyClose
import com.kamelia.hedera.util.gracefullyClose
import com.kamelia.hedera.util.sendEvent
import io.ktor.server.websocket.*
import io.ktor.util.*
import io.ktor.websocket.*
import java.util.*
suspend fun WebSocketServerSession.handleSession(userId: UUID, sessionId: UUID) = keepAlive(userId,
// Define event listeners here
defineEventListener(UserEvents.userUpdatedEvent, sessionId) { onUserUpdate(userId, it) },
defineEventListener(UserEvents.userForcefullyLoggedOutEvent, sessionId) { onUserForcefullyLoggedOut(userId, it) },
)
private const val USER_UPDATED = "user-updated"
private suspend fun WebSocketServerSession.onUserUpdate(currentId: UUID, user: UserRepresentationDTO) {
if (user.id != currentId) return
sendEvent(USER_UPDATED, user)
}
private const val USER_FORCEFULLY_LOGGED_OUT = "user-forcefully-logged-out"
private suspend fun WebSocketServerSession.onUserForcefullyLoggedOut(currentId: UUID, payload: UserForcefullyLoggedOutDTO) {
if (payload.userId != currentId) return
sendEvent(USER_FORCEFULLY_LOGGED_OUT, payload)
forcefullyClose(USER_FORCEFULLY_LOGGED_OUT)
}
private const val INVALID_USER_ID = "invalid-user-id"
private const val USER_CONNECTED = "user-connected"
private const val CONNECTION_CLOSED_BY_CLIENT = "connection-closed-by-client"
private const val INVALID_FRAME = "invalid-frame"
private suspend fun WebSocketServerSession.keepAlive(userId: UUID, vararg closers: () -> Unit) {
val terminator: () -> Unit = { closers.forEach { it() } }
val user = SessionManager.getUserOrNull(userId) ?: return forcefullyClose(INVALID_USER_ID, terminator)
sendEvent(USER_CONNECTED, user.toUserRepresentationDTO())
pingPong(terminator)
gracefullyClose(CONNECTION_CLOSED_BY_CLIENT, terminator)
}
private suspend fun WebSocketServerSession.pingPong(terminator: () -> Unit) {
for (frame in incoming) when (frame) {
is Frame.Ping -> send(Frame.Pong(frame.buffer.copy()))
is Frame.Text -> {
val text = frame.readText()
when (text.lowercase()) {
"close" -> break
"ping" -> send(Frame.Text("pong"))
else -> forcefullyClose(INVALID_FRAME, terminator)
}
}
else -> forcefullyClose(INVALID_FRAME, terminator)
}
}
| 28 | null | 2 | 26 | 44fad92bb6c6c213ad876bbcd0cafb765259d48b | 2,653 | Hedera | Apache License 2.0 |
features/intro/src/main/java/com/metinkale/prayer/intro/LanguageFragment.kt | metinkale38 | 48,848,634 | false | null | /*
* Copyright (c) 2013-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.metinkale.prayer.intro
import android.content.Intent
import android.os.Bundle
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CompoundButton
import android.widget.RadioButton
import android.widget.RadioGroup
import androidx.core.content.ContextCompat
import com.metinkale.prayer.Preferences
import com.metinkale.prayer.times.MainActivity
import com.metinkale.prayer.utils.LocaleUtils
import com.metinkale.prayer.utils.LocaleUtils.getSupportedLanguages
/**
* Created by metin on 25.07.17.
*/
class LanguageFragment : IntroFragment(), CompoundButton.OnCheckedChangeListener {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val v = inflater.inflate(R.layout.intro_language, container, false)
val radioGroup = v.findViewById<RadioGroup>(R.id.radioGroup)
val langs = getSupportedLanguages(
requireActivity()
)
val currentLang: String = Preferences.LANGUAGE
var pos = 0
for (i in langs.indices) {
val lang = langs[i]
if (lang.language == currentLang) pos = i + 1
val button = RadioButton(context)
button.tag = lang.language
button.text = lang.displayText
button.setTextColor(ContextCompat.getColor(requireContext(), R.color.white))
button.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20f)
val padding = (button.textSize / 2).toInt()
button.setPadding(padding, padding, padding, padding)
button.setOnCheckedChangeListener(this)
radioGroup.addView(button)
}
if (pos != 0) (radioGroup.getChildAt(pos) as RadioButton).isChecked = true
return v
}
/*
Answers.getInstance().logCustom(new CustomEvent("Language")
.putCustomAttribute("lang", lang)
);
*/
override fun onSelect() {}
override fun onEnter() {}
override fun onExit() {}
override fun allowTouch(): Boolean {
return true
}
override fun shouldShow(): Boolean {
return Preferences.SHOW_INTRO
}
override fun onCheckedChanged(compoundButton: CompoundButton, b: Boolean) {
if (!b) return
val newlang = compoundButton.tag as String
if (Preferences.LANGUAGE == newlang) return
Preferences.LANGUAGE = newlang
LocaleUtils.init(requireActivity())
requireActivity().overridePendingTransition(0, 0)
startActivity(Intent(requireContext(), MainActivity::class.java))
requireActivity().overridePendingTransition(0, 0)
requireActivity().finish()
}
} | 25 | null | 108 | 232 | f16a719edab1d3d516accb42d6eee15743d78269 | 3,391 | prayer-times-android | Apache License 2.0 |
app/src/main/java/org/wikipedia/analytics/eventplatform/StreamConfig.kt | greatfire | 460,298,221 | false | null | package org.wikipedia.analytics.eventplatform
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import org.wikipedia.analytics.eventplatform.DestinationEventService.ANALYTICS
import java.lang.IllegalArgumentException
@Serializable
class StreamConfig {
constructor(streamName: String, samplingConfig: SamplingConfig?, destinationEventService: DestinationEventService?) {
this.streamName = streamName
this.samplingConfig = samplingConfig
this.destinationEventService = destinationEventService ?: ANALYTICS
}
@SerialName("stream")
var streamName = ""
@SerialName("canary_events_enabled")
var canaryEventsEnabled = false
@SerialName("destination_event_service")
val destinationEventServiceKey: String = "eventgate-analytics-external"
var destinationEventService: DestinationEventService = ANALYTICS
@SerialName("schema_title")
val schemaTitle: String = ""
@SerialName("topic_prefixes")
val topicPrefixes: List<String> = emptyList()
val topics: List<String> = emptyList()
@SerialName("sampling")
var samplingConfig: SamplingConfig? = null
init {
try {
destinationEventService = DestinationEventService.valueOf(destinationEventServiceKey)
} catch (e: IllegalArgumentException) {}
}
}
| 2 | null | 4 | 38 | 8c8de602274b0132fc5d22b394a2c47fcd0bf2eb | 1,345 | apps-android-wikipedia-envoy | Apache License 2.0 |
app/src/main/java/com/noname/firebasepagination/main/MainActivity.kt | kepler296e | 314,693,534 | false | {"Kotlin": 11761} | package com.noname.firebasepagination.main
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.paging.PagedList
import com.firebase.ui.firestore.paging.FirestorePagingOptions
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.FirebaseFirestore
import com.noname.firebasepagination.R
import com.noname.firebasepagination.auth.LoginActivity
import com.noname.firebasepagination.base.BaseActivity
import com.noname.firebasepagination.post.Post
import com.noname.firebasepagination.post.PostAdapter
import kotlinx.android.synthetic.main.activity_main.*
import kotlin.math.pow
class MainActivity : BaseActivity(), MainActivityInterface {
// Init paging configuration
private val config = PagedList.Config.Builder()
.setEnablePlaceholders(false)
.setPrefetchDistance(2)
.setPageSize(10)
.build()
private val auth = FirebaseAuth.getInstance()
private val database = FirebaseFirestore.getInstance()
private val mQuery = database.collection("posts")
// Init adapter options
private val options = FirestorePagingOptions.Builder<Post>()
.setLifecycleOwner(this)
.setQuery(mQuery, config, Post::class.java)
.build()
private var postAdapter = PostAdapter(options, this)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Setting main recycler view adapter
rview_main.adapter = postAdapter
// Setting add post fab button
fab_add_post.setOnClickListener {
val post = Post(
title = getRandomNumber(),
message = getRandomNumber(),
timestamp = System.currentTimeMillis()
)
addPost(post)
}
// Refresh adapter with swipe refresh
srlayout_main.setOnRefreshListener { postAdapter.refresh() }
}
override fun refreshLayout() {
srlayout_main.isRefreshing = true
}
override fun stopRefreshingLayout() {
srlayout_main.isRefreshing = false
}
private fun getRandomNumber(): String {
return (0..(10.0.pow(5).toInt())).random().toString()
}
private fun addPost(post: Post) {
mQuery.add(post)
.addOnSuccessListener { postAdapter.refresh() }
.addOnFailureListener { showToast(it.message.toString()) }
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.menu_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.item_sign_out -> signOut()
R.id.item_delete_all_posts -> deleteAllPosts()
}
return super.onOptionsItemSelected(item)
}
private fun signOut() {
auth.signOut()
startActivity(LoginActivity::class.java)
finish()
}
private fun deleteAllPosts() {
mQuery.get()
.addOnSuccessListener {
for (snapshot in it.documents)
deletePost(snapshot.id)
}
.addOnFailureListener { showToast(it.message.toString()) }
}
private fun deletePost(id: String) {
mQuery.document(id).delete()
.addOnSuccessListener { postAdapter.refresh() }
.addOnFailureListener { showToast(it.message.toString()) }
}
} | 0 | Kotlin | 0 | 0 | a8f28245fd71866c4c18865c71f529c787adb049 | 3,576 | android-firestore-pagination | MIT License |
src/factories/ClientFactoryTest.kt | TheWizardAndTheWyrd | 109,442,630 | false | null | package factories
import clients.BarClient
import clients.FooClient
import factories.ClientFactory.create
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
class ClientFactoryTest {
@Test
fun testBarClientCreate() {
val barClient = create<BarClient>()
Assertions.assertNotNull(barClient)
barClient!!.contractMethod()
}
@Test
fun testFooClientCreate() {
val fooClient = create<FooClient>()
Assertions.assertNotNull(fooClient)
fooClient!!.contractMethod()
}
} | 0 | Kotlin | 0 | 2 | 46a803e85528483e98c8d20de3c8affbf024cb47 | 559 | kotlin-reified-factory | MIT License |
src/main/kotlin/com/wanggaowan/tools/utils/TranslateUtils.kt | wanggaowan | 599,862,484 | false | {"Kotlin": 561441} | package com.wanggaowan.tools.utils
import ai.grazie.text.TextRange
import ai.grazie.text.replace
import com.google.gson.Gson
import com.google.gson.JsonObject
import com.intellij.openapi.diagnostic.logger
import io.ktor.client.*
import io.ktor.client.engine.cio.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import java.io.UnsupportedEncodingException
import java.net.URLEncoder
import java.nio.charset.StandardCharsets
import java.text.SimpleDateFormat
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
private val LOG = logger<TranslateUtils>()
/**
* 语言翻译工具
*
* @author Created by wanggaowan on 2024/1/5 08:44
*/
object TranslateUtils {
suspend fun translate(
text: String,
targetLanguage: String,
): String? {
val uuid = UUID.randomUUID().toString()
val dateformat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'")
dateformat.timeZone = TimeZone.getTimeZone("UTC")
val time = dateformat.format(Date())
var accessKeyId = "TFRBSTV0UnFrbzY3QThVeFZDOGt4dHNu"
accessKeyId = String(mapValue(accessKeyId))
val queryMap = mutableMapOf<String, String>()
queryMap["AccessKeyId"] = accessKeyId
queryMap["Action"] = "TranslateGeneral"
queryMap["Format"] = "JSON"
queryMap["FormatType"] = "text"
queryMap["RegionId"] = "cn-hangzhou"
queryMap["Scene"] = "general"
queryMap["SignatureVersion"] = "1.0"
queryMap["SignatureMethod"] = "HMAC-SHA1"
queryMap["Status"] = "Available"
queryMap["SignatureNonce"] = uuid
queryMap["SourceLanguage"] = "zh"
queryMap["SourceText"] = text
queryMap["TargetLanguage"] = targetLanguage
queryMap["Timestamp"] = time
queryMap["Version"] = "2018-10-12"
var queryString = getCanonicalizedQueryString(queryMap, queryMap.keys.toTypedArray())
val stringToSign = "GET" + "&" + encodeURI("/") + "&" + encodeURI(queryString)
val signature = encodeURI(Base64.getEncoder().encodeToString(signatureMethod(stringToSign)))
queryString += "&Signature=$signature"
try {
val response = HttpClient(CIO) {
engine {
requestTimeout = 5000
endpoint {
connectTimeout = 5000
}
}
}.get("https://mt.cn-hangzhou.aliyuncs.com/?$queryString")
val body = response.bodyAsText()
if (body.isEmpty()) {
return null
}
// {"RequestId":"A721413A-7DCD-51B0-8AEE-FCE433CEACA2","Data":{"WordCount":"4","Translated":"Test Translation"},"Code":"200"}
val jsonObject = Gson().fromJson(body, JsonObject::class.java)
val code = jsonObject.getAsJsonPrimitive("Code").asString
if (code != "200") {
LOG.error("阿里翻译失败,响应结果:$body,翻译失败文本:$text")
return null
}
val data = jsonObject.getAsJsonObject("Data") ?: return null
return data.getAsJsonPrimitive("Translated").asString
} catch (e: Exception) {
LOG.error("阿里翻译失败,异常内容:${e.message},翻译失败文本:$text")
return null
}
}
@Throws(java.lang.Exception::class)
private fun signatureMethod(stringToSign: String?): ByteArray? {
val secret = "V3FWRGI3c210UW9rOGJUOXF2VHhENnYzbmF1bjU1Jg=="
if (stringToSign == null) {
return null
}
val sha256Hmac = Mac.getInstance("HmacSHA1")
val secretKey = SecretKeySpec(mapValue(secret), "HmacSHA1")
sha256Hmac.init(secretKey)
return sha256Hmac.doFinal(stringToSign.toByteArray())
}
@Throws(java.lang.Exception::class)
private fun getCanonicalizedQueryString(
query: Map<String, String?>,
keys: Array<String>
): String {
if (query.isEmpty()) {
return ""
}
if (keys.isEmpty()) {
return ""
}
Arrays.sort(keys)
var key: String?
var value: String?
val sb = StringBuilder()
for (i in keys.indices) {
key = keys[i]
sb.append(encodeURI(key))
value = query[key]
sb.append("=")
if (!value.isNullOrEmpty()) {
sb.append(encodeURI(value))
}
sb.append("&")
}
return sb.deleteCharAt(sb.length - 1).toString()
}
private fun mapValue(value: String): ByteArray {
return Base64.getDecoder().decode(value)
}
private fun encodeURI(content: String): String {
// 字符 A~Z、a~z、0~9 以及字符-、_、.、~不编码
// 空格编码成%20,而不是加号(+)
return try {
URLEncoder.encode(content, StandardCharsets.UTF_8.name()).replace("+", "%20")
.replace("%7E", "~")
.replace("*", "%2A")
} catch (var2: UnsupportedEncodingException) {
content
}
}
fun mapStrToKey(str: String?, isFormat: Boolean): String? {
var value = fixNewLineFormatError(str)?.replace("\\n", "_")
if (value.isNullOrEmpty()) {
return null
}
// \pP:中的小写p是property的意思,表示Unicode属性,用于Unicode正则表达式的前缀。
//
// P:标点字符
//
// L:字母;
//
// M:标记符号(一般不会单独出现);
//
// Z:分隔符(比如空格、换行等);
//
// S:符号(比如数学符号、货币符号等);
//
// N:数字(比如阿拉伯数字、罗马数字等);
//
// C:其他字符
// \pP:中的小写p是property的意思,表示Unicode属性,用于Unicode正表达式的前缀。
//
// P:标点字符
//
// L:字母;
//
// M:标记符号(一般不会单独出现);
//
// Z:分隔符(比如空格、换行等);
//
// S:符号(比如数学符号、货币符号等);
//
// N:数字(比如阿拉伯数字、罗马数字等);
//
// C:其他字符
value = value.lowercase().replace(Regex("[\\pP\\pS]"), "_")
.replace(" ", "_")
if (isFormat) {
value += "_format"
}
value = value.replace("_____", "_")
.replace("____", "_")
.replace("___", "_")
.replace("__", "_")
if (value.startsWith("_")) {
value = value.substring(1, value.length)
}
if (value.endsWith("_")) {
value = value.substring(0, value.length - 1)
}
return value
}
/// 修复翻译错误,如占位符为大写,\n,%s翻译后被分开成 \ n,% s等错误
fun fixTranslateError(
translate: String?,
targetLanguage: String,
useEscaping: Boolean = false,
placeHolderCount: Int? = null
): String? {
var translateStr = fixTranslatePlaceHolderStr(translate, useEscaping, placeHolderCount)
translateStr = fixNewLineFormatError(translateStr)
translateStr = translateStr?.replace("\"","\\\"")
return translateStr
}
/// 修复因翻译,导致占位符被翻译为大写的问题
private fun fixTranslatePlaceHolderStr(
translate: String?,
useEscaping: Boolean = false,
placeHolderCount: Int? = null
): String? {
if (translate.isNullOrEmpty()) {
return null
}
if (placeHolderCount == null || placeHolderCount <= 0) {
return translate
}
var start = 0
var newValue = translate
for (i in 0 until placeHolderCount) {
val param = "{Param$i}"
val index = translate.indexOf(param, start)
if (index != -1) {
if (useEscaping) {
val index2 = translate.indexOf("'$param'", start)
if (index2 != -1) {
if (index2 == index - 1) {
continue
}
newValue = newValue?.replace(TextRange(index, index + param.length), "{param$i}")
} else {
newValue = newValue?.replace(TextRange(index, index + param.length), "{param$i}")
}
} else {
newValue = newValue?.replace(TextRange(index, index + param.length), "{param$i}")
}
start = index + param.length
}
}
return newValue
}
// 修复格式错误,如\n,翻译成 \ n
private fun fixNewLineFormatError(text: String?): String? {
if (text.isNullOrEmpty()) {
return text
}
val regex = Regex("\\\\\\s+n") // \\\s+n
return fixFormatError(regex, text, "\\n")
}
private tailrec fun fixFormatError(
regex: Regex,
text: String,
placeHolder: String,
oldRange: IntRange? = null
): String {
if (text.isEmpty()) {
return text
}
val matchResult = regex.find(text) ?: return text
if (matchResult.range == oldRange) {
return text
}
return fixFormatError(regex, text.replaceRange(matchResult.range, placeHolder), placeHolder, matchResult.range)
}
}
| 0 | Kotlin | 0 | 0 | be51aae1392fb6492c107d10deae9191eca5a0a5 | 9,010 | FlutterDevTools | Apache License 2.0 |
uikit-kotlin/src/main/java/utils/PreferenceUtil.kt | samad-nkarimi | 332,771,551 | true | {"Kotlin": 1217711, "Java": 1544} | package utils
import android.content.Context
import android.content.SharedPreferences
public class PreferenceUtil {
private var sharedPreference: SharedPreferences? = null
constructor(appContext: Context) {
context = appContext
}
companion object {
private val PREFERENCE_NAME = "UI KIT"
private var INSTANCE: PreferenceUtil? = null
private var context: Context? = null
fun getInstance(appContext: Context?): PreferenceUtil? {
if (INSTANCE == null) INSTANCE = PreferenceUtil(appContext!!)
return INSTANCE
}
}
fun saveStringWithConfirmation(key: String?, value: String?): Boolean {
sharedPreference = context!!.getSharedPreferences(PREFERENCE_NAME, 0)
var sharedPreferences = sharedPreference!!
val editor: SharedPreferences.Editor = sharedPreferences.edit()
editor.putString(key, value)
return editor.commit()
}
fun saveString(key: String?, value: String?) {
sharedPreference = context!!.getSharedPreferences(PREFERENCE_NAME, 0)
var sharedPreferences = sharedPreference!!
val editor: SharedPreferences.Editor = sharedPreferences.edit()
editor.putString(key, value)
editor.apply()
}
fun getString(key: String?): String? {
sharedPreference = context!!.getSharedPreferences(PREFERENCE_NAME, 0)
var sharedPreferences = sharedPreference!!
return sharedPreferences.getString(key, "")
}
} | 0 | null | 0 | 0 | 7d7f0ed1e41870235ed4ec4ca5ea5f5f5fcfbec1 | 1,514 | android-kotlin-chat-app | MIT License |
utilk_android/src/main/java/com/mozhimen/kotlin/lintk/optins/permission/OPermission_POST_NOTIFICATIONS.kt | mozhimen | 798,079,717 | false | {"Kotlin": 1377638, "Java": 3920} | package com.mozhimen.kotlin.lintk.optins.permission
import androidx.annotation.RequiresApi
import com.mozhimen.kotlin.elemk.android.os.cons.CVersCode
import com.mozhimen.kotlin.lintk.annors.AManifestRequire
import com.mozhimen.kotlin.elemk.android.cons.CPermission
/**
* @ClassName OPermission_REQUEST_INSTALL_PACKAGES
* @Description TODO
* @Author Mozhimen & Kolin Zhao
* @Date 2024/2/4
* @Version 1.0
*/
@RequiresApi(CVersCode.V_33_13_T)
@AManifestRequire(CPermission.POST_NOTIFICATIONS)
@RequiresOptIn("The api is must add this permission to yout AndroidManifest.xml or dynamic call requestPermission. 需要声明此权限到你的AndroidManifest.xml或动态申请权限", RequiresOptIn.Level.ERROR)
annotation class OPermission_POST_NOTIFICATIONS
| 0 | Kotlin | 0 | 0 | 56a732a4333002e61a553495a8e5a2c3dd6255f3 | 727 | KUtilKit | MIT License |
posthog/src/main/java/com/posthog/PostHogEvent.kt | PostHog | 259,885,092 | false | null | package com.posthog
import com.google.gson.annotations.SerializedName
import java.util.Date
import java.util.UUID
// should this be internal as well?
// if we'd ever allow users to inspect and mutate the event, it should be a public API
/**
* The PostHog event data structure accepted by the batch API
* @property event The event name
* @property distinctId The distinct Id
* @property properties All the event properties
* @property timestamp The timestamp is automatically generated
* @property uuid the UUID v4 is automatically generated and used for deduplication
*/
public data class PostHogEvent(
val event: String,
@SerializedName("distinct_id")
val distinctId: String,
val properties: Map<String, Any>? = null,
// refactor to use PostHogDateProvider
val timestamp: Date = Date(),
val uuid: UUID? = UUID.randomUUID(),
@Deprecated("Do not use")
val type: String? = null,
@Deprecated("Do not use it, prefer [uuid]")
@SerializedName("message_id")
val messageId: UUID? = null,
@Deprecated("Do not use it, prefer [properties]")
@SerializedName("\$set")
val set: Map<String, Any>? = null,
// Only used for Replay
@SerializedName("api_key")
var apiKey: String? = null,
)
| 6 | null | 17 | 35 | 8013cccadfe52ad347eedcb492ce01690a1f7786 | 1,253 | posthog-android | MIT License |
app/src/main/java/com/townwang/yaohuo/di/modules.kt | Townwang | 230,221,979 | false | null | package com.townwang.yaohuo.di
import android.app.Application
import android.content.Context
import com.google.gson.GsonBuilder
import com.tencent.bugly.beta.Beta
import com.townwang.yaohuo.BuildConfig
import com.townwang.yaohuo.api.Api
import com.townwang.yaohuo.di.factory.DocumentConverterFactory
import com.townwang.yaohuo.di.interceptor.AddCookiesInterceptor
import com.townwang.yaohuo.di.interceptor.NetCookiesInterceptor
import com.townwang.yaohuo.di.interceptor.SaveCookiesInterceptor
import com.townwang.yaohuo.repo.Repo
//import com.townwang.yaohuo.repo.db.ApiCacheDB
import com.townwang.yaohuo.ui.fragment.pub.details.PubDetailsModel
import com.townwang.yaohuo.ui.fragment.home.HomeModel
import com.townwang.yaohuo.ui.fragment.login.LoginModel
import com.townwang.yaohuo.ui.fragment.me.MeModel
import com.townwang.yaohuo.ui.fragment.msg.MsgModel
import com.townwang.yaohuo.ui.fragment.msg.details.MsgDetailsModel
import com.townwang.yaohuo.ui.fragment.pub.PubListModel
import com.townwang.yaohuo.ui.fragment.search.SearchModel
import com.townwang.yaohuo.ui.fragment.send.SendModel
import com.townwang.yaohuo.ui.fragment.send.UploadFileModel
import com.townwang.yaohuo.ui.fragment.splash.SplashModel
import com.townwang.yaohuo.ui.fragment.theme.ThemeModel
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import org.koin.androidx.viewmodel.dsl.viewModel
import org.koin.core.qualifier.named
import org.koin.dsl.module
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.text.DateFormat
import java.util.concurrent.TimeUnit
private val netModule = module {
single {
GsonBuilder()
.serializeNulls()
.setDateFormat(DateFormat.LONG)
.setPrettyPrinting()
.create()
}
single {
Retrofit.Builder()
.baseUrl(BuildConfig.BASE_YAOHUO_URL)
.client(OkHttpClient.Builder()
.addInterceptor {
it.proceed(
it.request().newBuilder()
.build()
)
}
.retryOnConnectionFailure(true)
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.writeTimeout(20, TimeUnit.SECONDS)
.addInterceptor(NetCookiesInterceptor())
.addInterceptor(HttpLoggingInterceptor().apply {
level = HttpLoggingInterceptor.Level.BODY
})
.addInterceptor(AddCookiesInterceptor(get()))
.addInterceptor(SaveCookiesInterceptor(get()))
.build()
)
.addConverterFactory(DocumentConverterFactory())
.addConverterFactory(
GsonConverterFactory.create(
GsonBuilder()
.setLenient()
.create()
)
)
.build()
}
single {
get<Retrofit>().create(Api::class.java)
}
single {
Beta.init(get(), false)
}
}
private val storageModule = module {
// single {
// Room.databaseBuilder(get(), ApiCacheDB::class.java, "persist.db")
// .addMigrations(
// object : Migration(1, 2) {
// override fun migrate(database: SupportSQLiteDatabase) {
// database.execSQL("ALTER TABLE UserInfo ADD COLUMN `id` TEXT")
// }
// },
// object : Migration(2, 3) {
// override fun migrate(database: SupportSQLiteDatabase) {
// database.execSQL("DROP TABLE IF EXISTS UserInfo")
//
// }
// })
// .build()
// }
//
// single {
// get<ApiCacheDB>().apiCacheDAO()
// }
single(named("config")) {
get<Application>().getSharedPreferences("config", Context.MODE_PRIVATE)
}
}
private val repoModule = module {
single { Repo(get()) }
}
private val viewModelModule = module {
viewModel { PubListModel(get()) }
viewModel { SearchModel(get()) }
viewModel { LoginModel(get()) }
viewModel { ThemeModel() }
viewModel { PubDetailsModel(get()) }
viewModel { SplashModel(get()) }
viewModel { MeModel(get()) }
viewModel { HomeModel(get()) }
viewModel { SendModel(get()) }
viewModel { MsgModel(get()) }
viewModel { UploadFileModel(get()) }
viewModel { MsgDetailsModel(get()) }
}
val koinModules = viewModelModule + repoModule + netModule | 0 | Kotlin | 1 | 5 | fbacd5d13791b1a69345bac4f97fd9307e080860 | 4,608 | yaohuo | Apache License 2.0 |
geo/d2v-geo-common/src/main/kotlin/io/data2viz/geo/path/PathMeasure.kt | wbuchanan | 131,614,774 | true | {"Kotlin": 1388605, "HTML": 41196, "JavaScript": 36763} | package io.data2viz.geo.path
import io.data2viz.geo.noop2
import io.data2viz.geo.projection.Stream
import kotlin.math.sqrt
class PathMeasure : Stream {
private var lengthSum = .0
private var lengthRing = false
private var x00 = Double.NaN
private var y00 = Double.NaN
private var x0 = Double.NaN
private var y0 = Double.NaN
private var currentPoint: (Double, Double) -> Unit = noop2
fun result(): Double {
val result = lengthSum
lengthSum = .0
return result
}
override fun point(x: Double, y: Double, z: Double) = currentPoint(x, y)
override fun lineStart() {
currentPoint = ::lengthPointFirst
}
override fun lineEnd() {
if (lengthRing) lengthPoint(x00, y00)
currentPoint = noop2
}
override fun polygonStart() {
lengthRing = true
}
override fun polygonEnd() {
lengthRing = false
}
private fun lengthPointFirst(x: Double, y: Double) {
currentPoint = ::lengthPoint
x0 = x
x00 = x
y0 = y
y00 = y
}
private fun lengthPoint(x: Double, y: Double) {
x0 -= x
y0 -= y
lengthSum += sqrt(x0 * x0 + y0 * y0)
x0 = x
y0 = y
}
} | 0 | Kotlin | 0 | 0 | 1e34ed8863f3c104363a58be45d738571429be3a | 1,256 | data2viz | Apache License 2.0 |
geoIP/src/main/kotlin/hal/spel/rest/ipify.kt | C06A | 209,458,027 | false | null | package hal.spel.rest
import hal.spel.*
import io.micronaut.http.HttpStatus
fun main(vararg args: String) {
halSpeL("https://api.ipify.org{?format}"
, templated = true
).apply {
GET("format" to "json"
).apply {
println("URL: ${request.url}")
println(status.code)
println(body?.invoke())
println(body?.let { it["ip"]() })
}
GET("format" to "text"
).apply {
println("URL: ${request.url}")
println(status.code)
println("body: ${result}")
}
}
halSpeL("https://api6.ipify.org{?format}"
, templated = true
).GET("format" to "json").apply {
println("URL: ${request.url}")
println(status.code)
println(body?.invoke())
println(body?.let { it["ip"]() })
}
}
| 0 | Kotlin | 0 | 1 | 200b93c95c59dba8dbed77ffb8fb8f360f28185a | 864 | HALSpeL | MIT License |
src/main/kotlin/main/utils/json/themes/ThemesConfigField.kt | bombies | 411,889,109 | false | {"Kotlin": 814438, "Dockerfile": 355, "Shell": 131} | package main.utils.json.themes
enum class ThemesConfigField(private val str: String) {
THEME("theme");
override fun toString(): String = str
} | 4 | Kotlin | 0 | 4 | b78da295de11e787d426e0284028d23884d4c571 | 152 | Robertify-Bot | MIT License |
src/main/kotlin/uk/gov/justice/digital/hmpps/createandvaryalicenceapi/service/probation/CommunityOrPrisonOffenderManager.kt | ministryofjustice | 384,371,667 | false | {"Kotlin": 2353988, "Shell": 12714, "Dockerfile": 1384, "PLpgSQL": 863} | package uk.gov.justice.digital.hmpps.createandvaryalicenceapi.service.probation
data class CommunityOrPrisonOffenderManager(
val code: String,
val id: Long,
val team: TeamDetail,
val provider: Detail,
)
| 3 | Kotlin | 0 | 1 | ae9181175209750dce38856a53fa1d86bbe224d7 | 212 | create-and-vary-a-licence-api | MIT License |
app/src/main/java/com/endcodev/myinvoice/presentation/compose/components/DocSelection.kt | EndikaCo | 693,000,667 | false | {"Kotlin": 227181} | package com.endcodev.myinvoice.presentation.compose.components
import android.content.res.Configuration
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.OutlinedTextFieldDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.endcodev.myinvoice.presentation.theme.MyInvoiceTheme
@Composable
fun DocSelection(onSelection: (String) -> Unit, docs: List<String>) {
val text = remember { mutableStateOf(docs[0]) } // initial value
val isOpen = remember { mutableStateOf(false) } // initial value
val openCloseOfDropDownList: (Boolean) -> Unit = {
isOpen.value = it
}
Box(modifier = Modifier.width(100.dp)) {
Column {
OutlinedTextField(
value = text.value,
onValueChange = { text.value = it },
label = { Text(text = "Doc type") },
colors = OutlinedTextFieldDefaults.colors(
focusedTextColor = MaterialTheme.colorScheme.onBackground
)
)
DropDownList(
requestToOpen = isOpen.value,
list = docs,
request = openCloseOfDropDownList,
selectedString = {
text.value = it
onSelection(it)
}
)
}
Spacer(
modifier = Modifier
.matchParentSize()
.background(Color.Transparent)
.padding(10.dp)
.clickable(
onClick = { isOpen.value = true }
)
)
}
}
@Preview(name = "Light Mode")
@Preview(name = "Dark Mode", uiMode = Configuration.UI_MODE_NIGHT_YES)
@Composable
fun DocSelectionPreview() {
MyInvoiceTheme {
DocSelection(onSelection = {}, listOf("a", "b", "c"))
}
}
| 0 | Kotlin | 0 | 0 | 022387a62e029804855808e5124bfa2fe6baba24 | 2,526 | app_my_invoice | MIT License |
src/main/kotlin/me/fzzyhmstrs/amethyst_imbuement/entity/spell/BallLightningEntity.kt | fzzyhmstrs | 461,338,617 | false | null | package me.fzzyhmstrs.amethyst_imbuement.entity.spell
import me.fzzyhmstrs.amethyst_core.entity_util.MissileEntity
import me.fzzyhmstrs.amethyst_core.modifier_util.AugmentEffect
import me.fzzyhmstrs.amethyst_core.scepter_util.CustomDamageSources
import me.fzzyhmstrs.amethyst_core.scepter_util.augments.ScepterAugment
import me.fzzyhmstrs.amethyst_imbuement.config.AiConfig
import me.fzzyhmstrs.amethyst_imbuement.registry.RegisterEnchantment
import me.fzzyhmstrs.amethyst_imbuement.registry.RegisterEntity
import me.fzzyhmstrs.fzzy_core.registry.EventRegistry
import net.minecraft.entity.EntityType
import net.minecraft.entity.LivingEntity
import net.minecraft.particle.ParticleEffect
import net.minecraft.particle.ParticleTypes
import net.minecraft.server.world.ServerWorld
import net.minecraft.sound.SoundCategory
import net.minecraft.sound.SoundEvents
import net.minecraft.util.hit.BlockHitResult
import net.minecraft.util.hit.EntityHitResult
import net.minecraft.util.math.Box
import net.minecraft.util.math.MathHelper
import net.minecraft.world.World
class BallLightningEntity(entityType: EntityType<BallLightningEntity>, world: World): MissileEntity(entityType, world) {
constructor(world: World,owner: LivingEntity, speed: Float, divergence: Float, x: Double, y: Double, z: Double) : this(RegisterEntity.BALL_LIGHTNING_ENTITY,world){
this.owner = owner
this.setVelocity(owner,
owner.pitch,
owner.yaw,
0.0f,
speed,
divergence)
this.setPosition(x,y,z)
this.setRotation(owner.yaw, owner.pitch)
}
override var entityEffects: AugmentEffect = AugmentEffect()
.withDamage(5.4F,0.2F,0.0F)
.withDuration(19,-1)
.withRange(3.0,.25)
override val maxAge: Int
get() = 600
var ticker = EventRegistry.ticker_20
var initialBeam = false
override fun passEffects(ae: AugmentEffect, level: Int) {
super.passEffects(ae, level)
entityEffects.setDuration(ae.duration(level))
entityEffects.setRange(ae.range(level))
ticker = EventRegistry.Ticker(ae.duration(level))
EventRegistry.registerTickUppable(ticker)
}
private var augment: ScepterAugment = RegisterEnchantment.BALL_LIGHTNING
fun setAugment(aug: ScepterAugment){
this.augment = aug
}
override fun tick() {
super.tick()
if (world !is ServerWorld) return
if (!ticker.isReady() && initialBeam) return
if (owner == null || owner !is LivingEntity) return
val box = Box(this.pos.add(entityEffects.range(0),entityEffects.range(0),entityEffects.range(0)),this.pos.subtract(entityEffects.range(0),entityEffects.range(0),entityEffects.range(0)))
val entities = world.getOtherEntities(owner, box)
for (entity in entities){
if ( AiConfig.entities.isEntityPvpTeammate(owner as LivingEntity, entity,augment)) continue
if (entity !is LivingEntity) continue
entity.damage(CustomDamageSources.lightningBolt(world,this,owner),entityEffects.damage(0))
beam(world as ServerWorld,entity)
world.playSound(null,this.blockPos, SoundEvents.ITEM_TRIDENT_THUNDER, SoundCategory.NEUTRAL,0.3f,2.0f + world.random.nextFloat() * 0.4f - 0.2f)
}
initialBeam = true
}
private fun beam(serverWorld: ServerWorld, entity: LivingEntity){
val startPos = this.pos.add(0.0,0.25,0.0)
val endPos = entity.pos.add(0.0,entity.height/2.0,0.0)
val vec = endPos.subtract(startPos).multiply(0.1)
var pos = startPos
for (i in 1..10){
serverWorld.spawnParticles(ParticleTypes.ELECTRIC_SPARK,pos.x,pos.y,pos.z,2,vec.x,vec.y,vec.z,0.0)
pos = pos.add(vec)
}
}
override fun onEntityHit(entityHitResult: EntityHitResult) {
}
override fun onMissileBlockHit(blockHitResult: BlockHitResult) {
if (world !is ServerWorld) return
if (owner == null || owner !is LivingEntity) return
val box = Box(this.pos.add(entityEffects.range(0),entityEffects.range(0),entityEffects.range(0)),this.pos.subtract(entityEffects.range(0),entityEffects.range(0),entityEffects.range(0)))
val entities = world.getOtherEntities(owner, box)
for (entity in entities){
if ( AiConfig.entities.isEntityPvpTeammate(owner as LivingEntity, entity,augment)) continue
if (entity !is LivingEntity) continue
entity.damage(CustomDamageSources.lightningBolt(world,this,owner),entityEffects.damage(0))
beam(world as ServerWorld,entity)
world.playSound(null,this.blockPos, SoundEvents.ITEM_TRIDENT_THUNDER, SoundCategory.NEUTRAL,0.3f,2.0f + world.random.nextFloat() * 0.4f - 0.2f)
}
world.playSound(null,this.blockPos, SoundEvents.ENTITY_GENERIC_EXPLODE, SoundCategory.NEUTRAL,0.3f,2.0f + world.random.nextFloat() * 0.4f - 0.2f)
super.onMissileBlockHit(blockHitResult)
}
override fun onRemoved() {
EventRegistry.removeTickUppable(ticker)
}
override fun getParticleType(): ParticleEffect {
return ParticleTypes.ELECTRIC_SPARK
}
companion object{
fun createBallLightning(world: World, user: LivingEntity, speed: Float, div: Float, effects: AugmentEffect, level: Int, augment: ScepterAugment): BallLightningEntity {
val fbe = BallLightningEntity(
world, user, speed, div,
user.x - (user.width + 0.5f) * 0.5 * MathHelper.sin(user.bodyYaw * (Math.PI.toFloat() / 180)) * MathHelper.cos(
user.pitch * (Math.PI.toFloat() / 180)
),
user.eyeY - 0.6 - 0.8 * MathHelper.sin(user.pitch * (Math.PI.toFloat() / 180)),
user.z + (user.width + 0.5f) * 0.5 * MathHelper.cos(user.bodyYaw * (Math.PI.toFloat() / 180)) * MathHelper.cos(
user.pitch * (Math.PI.toFloat() / 180)
),
)
fbe.passEffects(effects, level)
fbe.setAugment(augment)
return fbe
}
}
}
| 9 | null | 8 | 4 | 361e9c97ce8ad61b5397d2baea5ece55240112f5 | 6,130 | ai | MIT License |
core/src/commonTest/kotlin/org/kobjects/parserlib/expressionparser/ParserTest.kt | kobjects | 455,979,563 | false | {"Kotlin": 17001, "Ruby": 1596} | package org.kobjects.parserlib.expressionparser
import org.kobjects.parserlib.expressionparser.ConfigurableExpressionParser.Companion.infix
import org.kobjects.parserlib.tokenizer.Lexer
import org.kobjects.parserlib.tokenizer.RegularExpressions
import org.kobjects.parserlib.tokenizer.Scanner
import kotlin.test.Test
import kotlin.test.assertEquals
class ParserTest {
// A parser that evaluates the expression directly (opposed to building a tree).
private val parser = ConfigurableExpressionParser<Scanner<TokenType>, Unit, Double>(
{ tokenizer, _ -> parsePrimary(tokenizer) },
infix(2, "*") { _, _, _, left, right -> left * right },
infix(2, "/") { _, _, _, left, right -> left / right },
infix(1, "+") { _, _, _, left, right -> left + right },
infix(1, "-") { _, _, _, left, right -> left - right }
)
fun parsePrimary(tokenizer: Scanner<TokenType>): Double =
when (tokenizer.current.type) {
TokenType.NUMBER -> tokenizer.consume().text.toDouble()
TokenType.SYMBOL ->
if (tokenizer.current.text == "(") {
val result = parser.parseExpression(tokenizer, Unit)
tokenizer.consume(")")
result
} else {
throw tokenizer.exception("Number or group expected.")
}
else -> throw tokenizer.exception("Number or group expected.")
}
fun evaluate(expr: String): Double {
val scanner = createScanner(expr)
return parser.parseExpression(scanner, Unit)
}
@Test
fun testParser() {
assertEquals(-4.0, evaluate("4 - 4 - 4"))
assertEquals(5.0, evaluate("3 + 2"))
assertEquals(11.0, evaluate("3 + 2 * 4"))
}
companion object {
enum class TokenType {
NUMBER, IDENTIFIER, SYMBOL, EOF
}
fun createScanner(input: String): Scanner<TokenType> =
Scanner(
Lexer(
input,
RegularExpressions.WHITESPACE to { null },
RegularExpressions.SYMBOL to { TokenType.SYMBOL },
RegularExpressions.IDENTIFIER to { TokenType.IDENTIFIER },
RegularExpressions.NUMBER to { TokenType.NUMBER },
),
TokenType.EOF)
}
} | 0 | Kotlin | 0 | 3 | 7b6ee24232321162074a9c2f597817c742ba30a0 | 2,377 | parsek | Apache License 2.0 |
core-v4/core-v4-airplane/src/main/java/com/github/teracy/odpt/core/v4/airplane/response/OdptFlightInformationArrival.kt | teracy | 193,032,147 | false | null | package com.github.teracy.odpt.core.v4.airplane.response
import com.github.teracy.odpt.model.*
import com.squareup.moshi.Json
/**
* v4版フライト到着情報APIレスポンス
*/
data class OdptFlightInformationArrival(
/**
* 固有識別子(ucode)
*/
@field:Json(name = "@id")
val id: String,
/**
* データ生成日時(ISO8601 日付時刻形式)
*/
@field:Json(name = "dc:date")
val date: String,
/**
* データ保証期限(ISO8601 日付時刻形式)
*/
@field:Json(name = "dct:valid")
val valid: String?,
/**
* 固有識別(フライト到着情報ID)
*/
@field:Json(name = "owl:sameAs")
val sameAs: String,
/**
* フライト到着情報を提供する空港事業者または航空事業者を示すID
*/
@field:Json(name = "odpt:operator")
val operator: String,
/**
* エアラインの運行会社のID
*/
@field:Json(name = "odpt:airline")
val airline: String?,
/**
* フライト番号のリスト。共同運航便では複数となる
*/
@field:Json(name = "odpt:flightNumber")
val flightNumberList: List<String>,
/**
* フライト状況を表すID
* @see OdptFlightStatus.sameAs
*/
@field:Json(name = "odpt:flightStatus")
val flightStatus: String?,
/**
* 運行障害発生時など、特記すべき情報がある場合に記載する、自然言語による情報の要約(多言語対応)
*/
@field:Json(name = "odpt:flightInformationSummary")
val summaryMap: Map<String, String>?,
/**
* 運行障害発生時など、特記すべき情報がある場合に記載する、自然言語による情報の記述(多言語対応)
*/
@field:Json(name = "odpt:flightInformationText")
val textMap: Map<String, String>?,
/**
* 定刻の到着時刻(ISO8601 時刻形式)
*/
@field:Json(name = "odpt:scheduledArrivalTime")
val scheduledArrivalTime: String?,
/**
* 変更後到着時刻(ISO8601 時刻形式)、到着以降は[actualArrivalTime]が生成され、本項目はnullとなる
*/
@field:Json(name = "odpt:estimatedArrivalTime")
val estimatedArrivalTime: String?,
/**
* 実際の到着時刻(ISO8601 時刻形式)、到着するまではnull
*/
@field:Json(name = "odpt:actualArrivalTime")
val actualArrivalTime: String?,
/**
* 到着空港のID
* @see OdptAirport.sameAs
*/
@field:Json(name = "odpt:arrivalAirport")
val arrivalAirport: String,
/**
* 到着空港のターミナルのID
* @see OdptAirportTerminal.sameAs
*/
@field:Json(name = "odpt:arrivalAirportTerminal")
val arrivalAirportTerminal: String?,
/**
* 到着空港のゲート番号
*/
@field:Json(name = "odpt:arrivalGate")
val arrivalGate: String?,
/**
* 到着空港の預け手荷物受取所
*/
@field:Json(name = "odpt:baggageClaim")
val baggageClaim: String?,
/**
* 出発地の空港のID
* @see OdptAirport.sameAs
*/
@field:Json(name = "odpt:originAirport")
val originAirport: String?,
/**
* 経由地の空港のIDのリスト
* @see OdptAirport.sameAs
*/
@field:Json(name = "odpt:viaAirport")
val viaAirportList: List<String>?,
/**
* 航空機の機種
*/
@field:Json(name = "odpt:aircraftType")
val aircraftType: String?
) {
/**
* 固有識別子を表すフライト到着情報ID
*/
val flightInformationArrivalId: FlightInformationArrivalId
get() = FlightInformationArrivalId(sameAs)
/**
* フライト到着情報を提供する空港事業者または航空事業者のID
*/
val operatorId: OperatorId
get() = OperatorId(operator)
/**
* エアラインの運行会社の事業者ID
*/
val airlineOperatorId: OperatorId?
get() = airline?.let { OperatorId(it) }
/**
* フライト状況ID
*/
val flightStatusId: FlightStatusId?
get() = flightStatus?.let { FlightStatusId(it) }
/**
* 到着地の空港ID
*/
val arrivalAirportId: AirportId
get() = AirportId(arrivalAirport)
/**
* 到着地の空港ターミナルID
*/
val arrivalAirportTerminalId: AirportTerminalId?
get() = arrivalAirportTerminal?.let { AirportTerminalId(it) }
/**
* 出発地の空港ID
*/
val originAirportId: AirportId?
get() = originAirport?.let { AirportId(it) }
/**
* 経由地の空港ID
*/
val viaAirportIdList: List<AirportId>?
get() = viaAirportList?.map { AirportId(it) }
}
| 0 | Kotlin | 0 | 1 | 002554e4ca6e2f460207cfd1cb8265c2267f149d | 3,868 | odpt | Apache License 2.0 |
koshian-core/src/main/java/koshian/_viewSwitchers.kt | wcaokaze | 241,953,004 | false | null | /*
* Copyright 2020 wcaokaze
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("UNUSED")
package koshian
import android.content.Context
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ViewSwitcher
import kotlin.contracts.*
object ViewSwitcherConstructor : KoshianViewGroupConstructor<ViewSwitcher, FrameLayout.LayoutParams> {
override fun instantiate(context: Context?) = ViewSwitcher(context)
override fun instantiateLayoutParams() = FrameLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT)
}
/**
* adds Views into this ViewSwitcher.
*/
@KoshianMarker
@ExperimentalContracts
inline fun <R> ViewSwitcher.addView(
creatorAction: ViewGroupCreator<ViewSwitcher, Nothing, FrameLayout.LayoutParams>.() -> R
): R {
contract { callsInPlace(creatorAction, InvocationKind.EXACTLY_ONCE) }
return addView(ViewSwitcherConstructor, creatorAction)
}
/**
* creates a new ViewSwitcher and adds it into this ViewGroup.
*/
@ExperimentalContracts
@Suppress("FunctionName")
inline fun <L> CreatorParent<L>.ViewSwitcher(
creatorAction: ViewGroupCreator<ViewSwitcher, L, FrameLayout.LayoutParams>.() -> Unit
): ViewSwitcher {
contract { callsInPlace(creatorAction, InvocationKind.EXACTLY_ONCE) }
return create(ViewSwitcherConstructor, creatorAction)
}
/**
* creates a new ViewSwitcher with name, and adds it into this ViewGroup.
*
* The name can be referenced in [applyKoshian]
*/
@ExperimentalContracts
@Suppress("FunctionName")
inline fun <L> CreatorParent<L>.ViewSwitcher(
name: String,
creatorAction: ViewGroupCreator<ViewSwitcher, L, FrameLayout.LayoutParams>.() -> Unit
): ViewSwitcher {
contract { callsInPlace(creatorAction, InvocationKind.EXACTLY_ONCE) }
return create(name, ViewSwitcherConstructor, creatorAction)
}
/**
* finds Views that are already added in this ViewSwitcher,
* and applies Koshian DSL to them.
*
* 
*
* The following 2 snippets are equivalent.
*
* 1.
* ```kotlin
* val contentView = koshian(context) {
* LinearLayout {
* TextView {
* view.text = "hello"
* view.textColor = 0xffffff opacity 0.8
* }
* }
* }
* ```
*
* 2.
* ```kotlin
* val contentView = koshian(context) {
* LinearLayout {
* TextView {
* view.text = "hello"
* }
* }
* }
*
* contentView.applyKoshian {
* TextView {
* view.textColor = 0xffffff opacity 0.8
* }
* }
* ```
*
* When mismatched View is specified, Koshian creates a new View and inserts it.
*
* 
*
* Also, naming View is a good way.
*
* 
*
* Koshian specifying a name doesn't affect the cursor.
* Koshian not specifying a name ignores named Views.
* Named Views and non-named Views are simply in other worlds.
*
* 
*
* For readability, it is recommended to put named Views
* as synchronized with the cursor.
*
* 
*/
@KoshianMarker
inline fun ViewSwitcher.applyKoshian(
applierAction: ViewGroupApplier<ViewSwitcher, ViewGroup.LayoutParams, FrameLayout.LayoutParams, Nothing>.() -> Unit
) {
applyKoshian(ViewSwitcherConstructor, applierAction)
}
/**
* finds Views that are already added in this ViewSwitcher,
* and applies Koshian DSL to them.
*
* 
*
* The following 2 snippets are equivalent.
*
* 1.
* ```kotlin
* val contentView = koshian(context) {
* LinearLayout {
* TextView {
* view.text = "hello"
* view.textColor = 0xffffff opacity 0.8
* }
* }
* }
* ```
*
* 2.
* ```kotlin
* val contentView = koshian(context) {
* LinearLayout {
* TextView {
* view.text = "hello"
* }
* }
* }
*
* contentView.applyKoshian {
* TextView {
* view.textColor = 0xffffff opacity 0.8
* }
* }
* ```
*
* When mismatched View is specified, Koshian creates a new View and inserts it.
*
* 
*
* Also, naming View is a good way.
*
* 
*
* Koshian specifying a name doesn't affect the cursor.
* Koshian not specifying a name ignores named Views.
* Named Views and non-named Views are simply in other worlds.
*
* 
*
* For readability, it is recommended to put named Views
* as synchronized with the cursor.
*
* 
*/
@KoshianMarker
inline fun <S : KoshianStyle> ViewSwitcher.applyKoshian(
style: S,
applierAction: ViewGroupApplier<ViewSwitcher, ViewGroup.LayoutParams, FrameLayout.LayoutParams, S>.() -> Unit
) {
applyKoshian(style, ViewSwitcherConstructor, applierAction)
}
/**
* If the next View is a ViewSwitcher, applies Koshian to it.
*
* Otherwise, creates a new ViewSwitcher and inserts it to the current position.
*
* @see applyKoshian
*/
@Suppress("FunctionName")
inline fun <L, S : KoshianStyle>
ApplierParent<L, S>.ViewSwitcher(
applierAction: ViewGroupApplier<ViewSwitcher, L, FrameLayout.LayoutParams, S>.() -> Unit
)
{
apply(ViewSwitcherConstructor, applierAction)
}
/**
* If the next View is a ViewSwitcher, applies Koshian to it.
*
* Otherwise, creates a new ViewSwitcher and inserts it to the current position.
*
* @see applyKoshian
*/
@Suppress("FunctionName")
inline fun <L, S : KoshianStyle>
ApplierParent<L, S>.ViewSwitcher(
styleElement: KoshianStyle.StyleElement<ViewSwitcher>,
applierAction: ViewGroupApplier<ViewSwitcher, L, FrameLayout.LayoutParams, S>.() -> Unit
)
{
apply(ViewSwitcherConstructor, styleElement, applierAction)
}
/**
* Applies Koshian to all ViewSwitchers that are named the specified in this ViewGroup.
* If there are no ViewSwitchers named the specified, do nothing.
*
* @see applyKoshian
*/
@Suppress("FunctionName")
inline fun <L, S : KoshianStyle>
ApplierParent<L, S>.ViewSwitcher(
name: String,
applierAction: ViewGroupApplier<ViewSwitcher, L, FrameLayout.LayoutParams, S>.() -> Unit
)
{
apply(name, ViewSwitcherConstructor, applierAction)
}
/**
* Applies Koshian to all ViewSwitchers that are named the specified in this ViewGroup.
* If there are no ViewSwitchers named the specified, do nothing.
*
* @see applyKoshian
*/
@Suppress("FunctionName")
inline fun <L, S : KoshianStyle>
ApplierParent<L, S>.ViewSwitcher(
name: String,
styleElement: KoshianStyle.StyleElement<ViewSwitcher>,
applierAction: ViewGroupApplier<ViewSwitcher, L, FrameLayout.LayoutParams, S>.() -> Unit
)
{
apply(name, ViewSwitcherConstructor, styleElement, applierAction)
}
/**
* registers a style applier function into this [KoshianStyle].
*
* Styles can be applied via [applyKoshian]
*/
@Suppress("FunctionName")
inline fun KoshianStyle.ViewSwitcher(
crossinline styleAction: ViewStyle<ViewSwitcher>.() -> Unit
): KoshianStyle.StyleElement<ViewSwitcher> {
return createStyleElement(styleAction)
}
| 9 | Kotlin | 0 | 2 | db503f9bbbc3bcedfaaff2faaed0deaf0fdfdf41 | 8,457 | Koshian | Apache License 2.0 |
app/src/test/java/com/guard/ui/activities/CallBack.kt | jackli688 | 132,226,850 | false | {"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Proguard": 2, "Kotlin": 83, "XML": 105, "Java": 5, "AIDL": 3} | package com.guard.ui.activities
/**
* @author: jackli
* @version: V1.0
* @project: My360
* @package: com.guard.ui.activities
* @description: description
* @date: 2018/5/19
* @time: 0:37
*/
interface CallBack {
fun succeeded(result: Int)
fun failure()
} | 1 | null | 1 | 1 | 8e87aebf1eee088428ca598d0bc238a9d3887786 | 269 | My360 | Apache License 2.0 |
src/main/kotlin/entity/Content.kt | giacomoaccursi | 717,007,118 | false | {"Kotlin": 47272, "JavaScript": 1187, "Dockerfile": 103} | /*
* Copyright (c) 2023. <NAME>
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
package entity
import flow.AwaitableMutableStateFlow
/**
* A container of values.
*/
interface Content {
/**
* The flow of the value.
*/
var value: AwaitableMutableStateFlow<Int>
/**
* Sets the value with the provided one.
* @param value the new value.
*/
suspend fun setValue(value: Int)
}
| 1 | Kotlin | 0 | 1 | 44eb690fd83bcc526f5da63754cd4afd84785236 | 528 | Reactive-DES | MIT License |
Kernl.Consumer/src/test/kotlin/singlememorycache/impl/MultiSameParamPrimitiveReturnTest.kt | mattshoe | 825,957,770 | false | {"Kotlin": 344588, "Shell": 1045} | package singlememorycache.impl
import org.mattshoe.shoebox.kernl.runtime.cache.singlecache.SingleCacheKernl
import kernl.org.mattshoe.shoebox.kernl.singlememorycache.MultiSameParamPrimitiveReturnKernl
import singlememorycache.SingleMemoryCacheScenariosTest
class MultiSameParamPrimitiveReturnTest : SingleMemoryCacheScenariosTest<MultiSameParamPrimitiveReturnKernl.Params, Int>() {
override fun repository(): SingleCacheKernl<MultiSameParamPrimitiveReturnKernl.Params, Int> {
return MultiSameParamPrimitiveReturnKernl.Factory { id, bar ->
id.toInt() + bar.toInt()
}
}
override suspend fun fetchUnwrapped(
repository: SingleCacheKernl<MultiSameParamPrimitiveReturnKernl.Params, Int>,
params: MultiSameParamPrimitiveReturnKernl.Params,
response: Int
) {
(subject as MultiSameParamPrimitiveReturnKernl).fetch(params.id, params.bar)
}
override val testData = mapOf(
MultiSameParamPrimitiveReturnKernl.Params("42", "58") to 100,
MultiSameParamPrimitiveReturnKernl.Params("96", "4") to 100,
MultiSameParamPrimitiveReturnKernl.Params("1", "2") to 3
)
} | 19 | Kotlin | 1 | 9 | 72110575d93274e990ebf92bb90ed49e35a96d9a | 1,161 | kernl | Apache License 2.0 |
save-frontend/src/main/kotlin/org/cqfn/save/frontend/components/basic/SelectForm.kt | cqfn | 300,279,336 | false | null | @file:Suppress("FILE_NAME_MATCH_CLASS", "HEADER_MISSING_IN_NON_SINGLE_CLASS_FILE")
package org.cqfn.save.frontend.components.basic
import org.cqfn.save.entities.Organization
import org.cqfn.save.frontend.utils.*
import org.w3c.dom.events.Event
import org.w3c.fetch.Headers
import react.Props
import react.dom.*
import react.fc
import react.useState
import kotlinx.html.js.onChangeFunction
/**
* SelectFormRequired component props
*/
external interface SelectFormRequiredProps : Props {
/**
* Type of 'select'
*/
var form: InputTypes?
/**
* Flag to valid select
*/
var validInput: Boolean?
/**
* classes of 'select'
*/
var classes: String?
/**
* select name
*/
var text: String?
}
/**
* @param onChangeFun
* @return div with an input form
*/
@Suppress(
"TOO_MANY_PARAMETERS",
"TOO_LONG_FUNCTION",
"LongParameterList",
"TYPE_ALIAS",
)
fun selectFormRequired(
onChangeFun: (form: InputTypes, organization: Event, isProject: Boolean) -> Unit
) = fc<SelectFormRequiredProps> { props ->
val (elements, setElements) = useState(listOf<String>())
useRequest(arrayOf(), isDeferred = false) {
val organizations =
get(
url = "$apiUrl/organization/get/list",
headers = Headers().also {
it.set("Accept", "application/json")
},
)
.unsafeMap {
it.decodeFromJsonString<List<Organization>>()
}
setElements(organizations.map { it.name })
}()
div("${props.classes} mt-1") {
label("form-label") {
props.form?.let { attrs.set("for", it.name) }
+"${props.text}"
}
div("input-group has-validation") {
span("input-group-text") {
attrs["id"] = "${props.form?.name}Span"
+"*"
}
select("form-control") {
attrs["id"] = "${props.form?.name}"
attrs["required"] = true
if (props.validInput == true) {
attrs["class"] = "form-control"
} else {
attrs["class"] = "form-control is-invalid"
}
val newElements = elements.toMutableList()
newElements.add(0, "")
newElements.forEach { element ->
option {
+element
}
}
attrs.onChangeFunction = {
onChangeFun(props.form!!, it, true)
}
}
if (elements.isEmpty()) {
div("invalid-feedback d-block") {
+"You don't have access to any organizations"
}
} else if (props.validInput == false) {
div("invalid-feedback d-block") {
+"Please input a valid ${props.form?.str}"
}
}
}
}
}
| 97 | Kotlin | 0 | 15 | c381c6fd4d9c12178de79da4818220b724a15596 | 3,085 | save-cloud | MIT License |
ktoken/src/commonTest/kotlin/Assert.kt | aallam | 700,547,449 | false | {"Kotlin": 43033} | import kotlin.test.assertTrue
fun <T> assertNotContains(list: Collection<T>, vararg elements: T) {
val elementsList = elements.toList()
assertTrue("the collection $list is not expected to contain $elementsList") { !list.containsAll(elementsList) }
}
fun <T> assertContains(list: Collection<T>, vararg elements: T) {
val elementsList = elements.toList()
assertTrue("the collection $list is expected to contain $elementsList") { list.containsAll(elementsList) }
}
| 0 | Kotlin | 0 | 5 | 1e84948d3ecb3f56b1717ae7961346a66da7cddd | 480 | ktoken | MIT License |
ktor-features/ktor-websockets/src/io/ktor/websocket/WebSocketServerSession.kt | lukehuang | 143,022,166 | true | {"Kotlin": 1817357, "Java": 62081, "HTML": 30993, "FreeMarker": 6484, "CSS": 5444, "JavaScript": 3679, "Lua": 280} | package io.ktor.websocket
import io.ktor.application.*
import io.ktor.http.cio.websocket.*
interface WebSocketServerSession : WebSocketSession {
val call: ApplicationCall
}
interface DefaultWebSocketServerSession : DefaultWebSocketSession, WebSocketServerSession
val WebSocketServerSession.application: Application get() = call.application
internal fun WebSocketSession.toServerSession(call: ApplicationCall): WebSocketServerSession =
DelegatedWebSocketServerSession(call, this)
internal fun DefaultWebSocketSession.toServerSession(call: ApplicationCall): DefaultWebSocketServerSession =
DelegatedDefaultWebSocketServerSession(call, this)
private class DelegatedWebSocketServerSession(
override val call: ApplicationCall,
val delegate: WebSocketSession
) : WebSocketServerSession, WebSocketSession by delegate
private class DelegatedDefaultWebSocketServerSession(
override val call: ApplicationCall,
val delegate: DefaultWebSocketSession
) : DefaultWebSocketServerSession, DefaultWebSocketSession by delegate
| 0 | Kotlin | 0 | 0 | afa45ccd42011ff5f73e639aca12795cd7f267b0 | 1,045 | ktor | Apache License 2.0 |
src/test/kotlin/com/terraformation/backend/tracking/db/ObservationResultsStoreTest.kt | terraware | 323,722,525 | false | null | package com.terraformation.backend.tracking.db
import com.opencsv.CSVReader
import com.terraformation.backend.RunsAsUser
import com.terraformation.backend.TestClock
import com.terraformation.backend.db.DatabaseTest
import com.terraformation.backend.db.OrganizationNotFoundException
import com.terraformation.backend.db.default_schema.SpeciesId
import com.terraformation.backend.db.tracking.MonitoringPlotId
import com.terraformation.backend.db.tracking.ObservationPlotPosition
import com.terraformation.backend.db.tracking.ObservationState
import com.terraformation.backend.db.tracking.PlantingSiteId
import com.terraformation.backend.db.tracking.PlantingSubzoneId
import com.terraformation.backend.db.tracking.PlantingZoneId
import com.terraformation.backend.db.tracking.RecordedPlantStatus
import com.terraformation.backend.db.tracking.RecordedSpeciesCertainty
import com.terraformation.backend.db.tracking.tables.pojos.RecordedPlantsRow
import com.terraformation.backend.mockUser
import com.terraformation.backend.point
import com.terraformation.backend.tracking.model.ObservationMonitoringPlotPhotoModel
import com.terraformation.backend.tracking.model.ObservationResultsModel
import com.terraformation.backend.tracking.model.ObservationSpeciesResultsModel
import com.terraformation.backend.tracking.model.ObservedPlotCoordinatesModel
import io.ktor.utils.io.core.use
import io.mockk.every
import java.io.InputStreamReader
import java.math.BigDecimal
import java.nio.file.NoSuchFileException
import java.time.Instant
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertAll
import org.junit.jupiter.api.assertThrows
class ObservationResultsStoreTest : DatabaseTest(), RunsAsUser {
override val user = mockUser()
private lateinit var plantingSiteId: PlantingSiteId
private lateinit var plotIds: Map<String, MonitoringPlotId>
private lateinit var subzoneIds: Map<String, PlantingSubzoneId>
private lateinit var zoneIds: Map<String, PlantingZoneId>
private val allSpeciesNames = mutableSetOf<String>()
private val permanentPlotNames = mutableSetOf<String>()
private val speciesIds = mutableMapOf<String, SpeciesId>()
private val speciesNames: Map<SpeciesId, String> by lazy {
speciesIds.entries.associate { it.value to it.key }
}
private val zoneNames: Map<PlantingZoneId, String> by lazy {
zoneIds.entries.associate { it.value to it.key }
}
private val clock = TestClock()
private val observationStore by lazy {
ObservationStore(
clock,
dslContext,
observationsDao,
observationPlotConditionsDao,
observationPlotsDao,
recordedPlantsDao)
}
private val resultsStore by lazy { ObservationResultsStore(dslContext) }
@BeforeEach
fun setUp() {
insertUser()
insertOrganization()
plantingSiteId = insertPlantingSite(areaHa = BigDecimal(2500))
every { user.canReadObservation(any()) } returns true
every { user.canReadOrganization(organizationId) } returns true
every { user.canReadPlantingSite(plantingSiteId) } returns true
every { user.canUpdateObservation(any()) } returns true
}
@Nested
inner class FetchByOrganizationId {
@Test
fun `results are in descending completed time order`() {
val completedObservationId1 = insertObservation(completedTime = Instant.ofEpochSecond(1))
val completedObservationId2 = insertObservation(completedTime = Instant.ofEpochSecond(2))
val inProgressObservationId = insertObservation(state = ObservationState.InProgress)
val upcomingObservationId = insertObservation(state = ObservationState.Upcoming)
val results = resultsStore.fetchByOrganizationId(organizationId)
assertEquals(
listOf(
completedObservationId2,
completedObservationId1,
upcomingObservationId,
inProgressObservationId,
),
results.map { it.observationId },
"Observation IDs")
}
@Test
fun `returns photo metadata`() {
val gpsCoordinates = point(2, 3)
val position = ObservationPlotPosition.NortheastCorner
insertPlantingZone()
insertPlantingSubzone()
insertMonitoringPlot()
insertObservation(completedTime = Instant.EPOCH)
insertObservationPlot(claimedBy = user.userId, completedBy = user.userId)
insertFile()
insertObservationPhoto(gpsCoordinates = gpsCoordinates, position = position)
val results = resultsStore.fetchByOrganizationId(organizationId)
assertEquals(
listOf(ObservationMonitoringPlotPhotoModel(inserted.fileId, gpsCoordinates, position)),
results[0].plantingZones[0].plantingSubzones[0].monitoringPlots[0].photos)
}
@Test
fun `throws exception if no permission to read organization`() {
every { user.canReadOrganization(organizationId) } returns false
assertThrows<OrganizationNotFoundException> {
resultsStore.fetchByOrganizationId(organizationId)
}
}
}
@Nested
inner class FetchByPlantingSiteId {
@Test
fun `limit of 1 returns most recently completed observation`() {
insertObservation(completedTime = Instant.ofEpochSecond(1))
val mostRecentlyCompletedObservationId =
insertObservation(completedTime = Instant.ofEpochSecond(3))
insertObservation(completedTime = Instant.ofEpochSecond(2))
val results = resultsStore.fetchByPlantingSiteId(plantingSiteId, limit = 1)
assertEquals(
listOf(mostRecentlyCompletedObservationId),
results.map { it.observationId },
"Observation IDs")
}
@Test
fun `returns observed coordinates in counterclockwise position order`() {
insertPlantingZone()
insertPlantingSubzone()
insertMonitoringPlot()
insertObservation(completedTime = Instant.EPOCH)
insertObservationPlot(claimedBy = user.userId, completedBy = user.userId)
val northwest = point(1)
val northeast = point(2)
val southwest = point(3)
val id1 =
insertObservedCoordinates(
position = ObservationPlotPosition.NorthwestCorner, gpsCoordinates = northwest)
val id2 =
insertObservedCoordinates(
position = ObservationPlotPosition.SouthwestCorner, gpsCoordinates = southwest)
val id3 =
insertObservedCoordinates(
position = ObservationPlotPosition.NortheastCorner, gpsCoordinates = northeast)
val results = resultsStore.fetchByPlantingSiteId(plantingSiteId)
val actualCoordinates =
results[0].plantingZones[0].plantingSubzones[0].monitoringPlots[0].coordinates
assertEquals(
listOf(
ObservedPlotCoordinatesModel(id2, southwest, ObservationPlotPosition.SouthwestCorner),
ObservedPlotCoordinatesModel(id3, northeast, ObservationPlotPosition.NortheastCorner),
ObservedPlotCoordinatesModel(id1, northwest, ObservationPlotPosition.NorthwestCorner),
),
actualCoordinates)
}
@Test
fun `throws exception if no permission to read planting site`() {
every { user.canReadPlantingSite(plantingSiteId) } returns false
assertThrows<PlantingSiteNotFoundException> {
resultsStore.fetchByPlantingSiteId(plantingSiteId)
}
}
}
@Nested
inner class Scenarios {
@Test
fun `site with two observations`() {
runScenario("/tracking/observation/TwoObservations", 2)
}
@Test
fun `permanent plots being added and removed`() {
runScenario("/tracking/observation/PermanentPlotChanges", 3)
}
private fun runScenario(prefix: String, numObservations: Int) {
importFromCsvFiles(prefix, numObservations)
val allResults =
resultsStore.fetchByPlantingSiteId(plantingSiteId).sortedBy { it.observationId.value }
assertResults(prefix, allResults)
}
private fun assertResults(prefix: String, allResults: List<ObservationResultsModel>) {
assertAll(
{ assertSiteResults(prefix, allResults) },
{ assertSiteSpeciesResults(prefix, allResults) },
{ assertZoneResults(prefix, allResults) },
{ assertZoneSpeciesResults(prefix, allResults) },
{ assertPlotResults(prefix, allResults) },
{ assertPlotSpeciesResults(prefix, allResults) },
)
}
private fun assertSiteResults(prefix: String, allResults: List<ObservationResultsModel>) {
val actual =
makeActualCsv(allResults, listOf(emptyList())) { _, results ->
listOf(
results.plantingDensity.toStringOrBlank(),
results.estimatedPlants.toStringOrBlank(),
results.totalSpecies.toStringOrBlank(),
results.mortalityRate.toStringOrBlank("%"),
)
}
assertResultsMatchCsv("$prefix/SiteStats.csv", actual)
}
private fun assertZoneResults(prefix: String, allResults: List<ObservationResultsModel>) {
val rowKeys = zoneIds.keys.map { listOf(it) }
val actual =
makeActualCsv(allResults, rowKeys) { (zoneName), results ->
val zone = results.plantingZones.first { it.plantingZoneId == zoneIds[zoneName] }
listOf(
zone.totalPlants.toStringOrBlank(),
zone.plantingDensity.toStringOrBlank(),
zone.totalSpecies.toStringOrBlank(),
zone.mortalityRate.toStringOrBlank("%"),
zone.estimatedPlants.toStringOrBlank(),
)
}
assertResultsMatchCsv("$prefix/ZoneStats.csv", actual)
}
private fun assertPlotResults(prefix: String, allResults: List<ObservationResultsModel>) {
val rowKeys = plotIds.keys.map { listOf(it) }
val actual =
makeActualCsv(allResults, rowKeys) { (plotName), results ->
results.plantingZones
.flatMap { zone -> zone.plantingSubzones }
.flatMap { subzone -> subzone.monitoringPlots }
.firstOrNull { it.monitoringPlotName == plotName }
?.let { plot ->
listOf(
plot.totalPlants.toStringOrBlank(),
plot.totalSpecies.toStringOrBlank(),
plot.mortalityRate.toStringOrBlank("%"),
// Live and existing plants columns are in spreadsheet but not included in
// calculated
// results; it will be removed by the filter function below.
plot.plantingDensity.toStringOrBlank(),
)
} ?: listOf("", "", "", "")
}
assertResultsMatchCsv("$prefix/PlotStats.csv", actual) { row ->
row.filterIndexed { index, _ ->
val positionInColumnGroup = (index - 1) % 6
positionInColumnGroup != 3 && positionInColumnGroup != 4
}
}
}
private fun assertSiteSpeciesResults(
prefix: String,
allResults: List<ObservationResultsModel>
) {
val rowKeys = allSpeciesNames.map { listOf(it) }
val actual =
makeActualCsv(allResults, rowKeys) { (speciesName), results ->
results.species
.filter { it.certainty != RecordedSpeciesCertainty.Unknown }
.firstOrNull { getSpeciesNameValue(it) == speciesName }
?.let { species ->
listOf(
species.totalPlants.toStringOrBlank(),
species.mortalityRate.toStringOrBlank("%"),
)
} ?: listOf("", "")
}
assertResultsMatchCsv("$prefix/SiteStatsPerSpecies.csv", actual)
}
private fun assertZoneSpeciesResults(
prefix: String,
allResults: List<ObservationResultsModel>
) {
val rowKeys =
zoneIds.keys.flatMap { zoneName ->
allSpeciesNames.map { speciesName -> listOf(zoneName, speciesName) }
}
val actual =
makeActualCsv(allResults, rowKeys) { (zoneName, speciesName), results ->
results.plantingZones
.firstOrNull { zoneNames[it.plantingZoneId] == zoneName }
?.species
?.filter { it.certainty != RecordedSpeciesCertainty.Unknown }
?.firstOrNull { getSpeciesNameValue(it) == speciesName }
?.let { species ->
listOf(
species.totalPlants.toStringOrBlank(),
species.mortalityRate.toStringOrBlank("%"),
)
} ?: listOf("", "")
}
assertResultsMatchCsv("$prefix/ZoneStatsPerSpecies.csv", actual)
}
private fun assertPlotSpeciesResults(
prefix: String,
allResults: List<ObservationResultsModel>
) {
val rowKeys =
plotIds.keys.flatMap { plotName ->
allSpeciesNames.map { speciesName -> listOf(plotName, speciesName) }
}
val actual =
makeActualCsv(allResults, rowKeys) { (plotName, speciesName), results ->
results.plantingZones
.flatMap { zone -> zone.plantingSubzones }
.flatMap { subzone -> subzone.monitoringPlots }
.firstOrNull { it.monitoringPlotName == plotName }
?.species
?.filter { it.certainty != RecordedSpeciesCertainty.Unknown }
?.firstOrNull { getSpeciesNameValue(it) == speciesName }
?.let {
listOf(it.totalPlants.toStringOrBlank(), it.mortalityRate.toStringOrBlank("%"))
} ?: listOf("", "")
}
assertResultsMatchCsv("$prefix/PlotStatsPerSpecies.csv", actual)
}
private fun importFromCsvFiles(prefix: String, numObservations: Int) {
zoneIds = importZonesCsv(prefix)
subzoneIds = importSubzonesCsv(prefix)
plotIds = importPlotsCsv(prefix)
importPlantsCsv(prefix, numObservations)
}
private fun importZonesCsv(prefix: String): Map<String, PlantingZoneId> {
return associateCsv("$prefix/Zones.csv", 2) { cols ->
val zoneName = cols[1]
val areaHa = BigDecimal(cols[2])
zoneName to insertPlantingZone(areaHa = areaHa, name = zoneName)
}
}
private fun importSubzonesCsv(prefix: String): Map<String, PlantingSubzoneId> {
return associateCsv("$prefix/Subzones.csv", 2) { cols ->
val zoneName = cols[0]
val subzoneName = cols[1]
val zoneId = zoneIds[zoneName]!!
// Find the first observation where the subzone is marked as completed planting, if any.
val plantingCompletedColumn = cols.drop(2).indexOfFirst { it == "Yes" }
val plantingCompletedTime =
if (plantingCompletedColumn >= 0) {
Instant.ofEpochSecond(plantingCompletedColumn.toLong())
} else {
null
}
subzoneName to
insertPlantingSubzone(
plantingCompletedTime = plantingCompletedTime,
fullName = subzoneName,
name = subzoneName,
plantingZoneId = zoneId)
}
}
private fun importPlotsCsv(prefix: String): Map<String, MonitoringPlotId> {
return associateCsv("$prefix/Plots.csv") { cols ->
val subzoneName = cols[0]
val plotName = cols[1]
val subzoneId = subzoneIds[subzoneName]!!
val plotId =
insertMonitoringPlot(
fullName = plotName, name = plotName, plantingSubzoneId = subzoneId)
if (cols[2] == "Permanent") {
permanentPlotNames.add(plotName)
}
plotName to plotId
}
}
private fun importPlantsCsv(prefix: String, numObservations: Int) {
repeat(numObservations) { observationNum ->
clock.instant = Instant.ofEpochSecond(observationNum.toLong())
val observationId = insertObservation()
val observedPlotNames = mutableSetOf<String>()
val plantsRows =
mapCsv("$prefix/Plants-${observationNum+1}.csv") { cols ->
val plotName = cols[0]
val certainty = RecordedSpeciesCertainty.forJsonValue(cols[1])
val speciesName = cols[2].ifBlank { null }
val status = RecordedPlantStatus.forJsonValue(cols[3])
val plotId = plotIds[plotName]!!
if (speciesName != null) {
allSpeciesNames.add(speciesName)
}
val speciesId =
if (speciesName != null && certainty == RecordedSpeciesCertainty.Known) {
speciesIds.computeIfAbsent(speciesName) { _ ->
insertSpecies(scientificName = speciesName)
}
} else {
null
}
val speciesNameIfOther =
if (certainty == RecordedSpeciesCertainty.Other) {
speciesName
} else {
null
}
if (plotName !in observedPlotNames) {
insertObservationPlot(
claimedBy = user.userId,
claimedTime = Instant.EPOCH,
isPermanent = plotName in permanentPlotNames,
observationId = observationId,
monitoringPlotId = plotId,
)
observedPlotNames.add(plotName)
}
RecordedPlantsRow(
certaintyId = certainty,
gpsCoordinates = point(1),
observationId = observationId,
monitoringPlotId = plotId,
speciesId = speciesId,
speciesName = speciesNameIfOther,
statusId = status,
)
}
// This would normally happen in ObservationService.startObservation after plot selection;
// do it explicitly since we're specifying our own plots in the test data.
observationStore.populateCumulativeDead(observationId)
plantsRows
.groupBy { it.monitoringPlotId!! }
.forEach { (plotId, plants) ->
observationStore.completePlot(
observationId, plotId, emptySet(), "Notes", Instant.EPOCH, plants)
}
}
}
/** Maps each data row of a CSV to a value. */
private fun <T> mapCsv(path: String, skipRows: Int = 1, func: (Array<String>) -> T): List<T> {
val stream = javaClass.getResourceAsStream(path) ?: throw NoSuchFileException(path)
return stream.use { inputStream ->
CSVReader(InputStreamReader(inputStream)).use { csvReader ->
// We never care about the header rows.
csvReader.skip(skipRows)
csvReader.map(func)
}
}
}
/** For each data row of a CSV, associates a string identifier with a value. */
private fun <T> associateCsv(
path: String,
skipRows: Int = 1,
func: (Array<String>) -> Pair<String, T>
): Map<String, T> {
return mapCsv(path, skipRows, func).toMap()
}
/**
* Returns a CSV representation of the results of one or more observations.
*
* @param rowKeys The leftmost column(s) of all the rows that could appear in the CSV. The
* values in these columns act as unique keys: they identify which specific set of numbers are
* included in the rest of the row. For example, for the "per zone per species" CSV, the key
* would be a zone name column and a species name column, with one element for each possible
* permutation of zone name and species name.
* @param columnsFromResult Returns a group of columns for the row with a particular key from a
* particular observation. If the observation doesn't have any data for the row, this must
* return a list of empty strings. If none of the observations have any data for the row,
* e.g., it's a "per zone per species" CSV and a particular species wasn't present in a
* particular zone, the row is not included in the generated CSV.
*/
private fun makeActualCsv(
allResults: List<ObservationResultsModel>,
rowKeys: List<List<String>>,
columnsFromResult: (List<String>, ObservationResultsModel) -> List<String>
): List<List<String>> {
return rowKeys.mapNotNull { initialRow ->
val dataColumns = allResults.flatMap { results -> columnsFromResult(initialRow, results) }
if (dataColumns.any { it.isNotEmpty() }) {
initialRow + dataColumns
} else {
null
}
}
}
/**
* Asserts that an expected-output CSV matches the CSV representation of the actual calculation
* results. The two header rows in the expected-output CSV are discarded.
*/
private fun assertResultsMatchCsv(
path: String,
actual: List<List<String>>,
mapCsvRow: (List<String>) -> List<String> = { it }
) {
val actualRendered = actual.map { it.joinToString(",") }.sorted().joinToString("\n")
val expected =
mapCsv(path, 2) { mapCsvRow(it.toList()).joinToString(",") }.sorted().joinToString("\n")
assertEquals(expected, actualRendered, path)
}
private fun getSpeciesNameValue(species: ObservationSpeciesResultsModel): String =
species.speciesName ?: species.speciesId?.let { speciesNames[it] } ?: ""
private fun Int?.toStringOrBlank(suffix: String = "") = this?.let { "$it$suffix" } ?: ""
}
}
| 9 | null | 1 | 9 | ab6fbb71381d0eda0684e9d06aa68004d9718b05 | 21,753 | terraware-server | Apache License 2.0 |
src/main/kotlin/endytkn/randomEvents/CommandRegister.kt | EndyTknDev | 856,093,082 | false | {"Kotlin": 56201} | package endytkn.randomEvents.events
import endytkn.randomEvents.commands.RandomEventsCommands
import net.minecraftforge.common.MinecraftForge
import net.minecraftforge.event.RegisterCommandsEvent
import net.minecraftforge.eventbus.api.SubscribeEvent
import net.minecraftforge.fml.common.Mod
import org.apache.logging.log4j.Level
import org.apache.logging.log4j.LogManager
import org.apache.logging.log4j.Logger
@Mod.EventBusSubscriber
object CommandRegister {
private val LOGGER: Logger = LogManager.getLogger()
init {
MinecraftForge.EVENT_BUS.register(this)
}
@SubscribeEvent
fun onRegisterCommands(event: RegisterCommandsEvent) {
LOGGER.log(Level.INFO, "Registrando comandos...")
RandomEventsCommands.register(event.dispatcher)
}
}
| 0 | Kotlin | 0 | 0 | 86767020fd765fdff729f7ef6478fc2fd0f62c9c | 786 | Random-Events | MIT License |
app/src/main/java/com/wavesplatform/wallet/v2/ui/home/profile/settings/DevOptionsActivity.kt | inozemtsev-roman | 202,315,169 | true | {"Kotlin": 1334568, "Java": 306539, "HTML": 25816} | package com.wavesplatform.wallet.v2.ui.home.profile.settings
import android.os.Bundle
import com.arellomobile.mvp.presenter.InjectPresenter
import com.arellomobile.mvp.presenter.ProvidePresenter
import com.wavesplatform.wallet.R
import com.wavesplatform.wallet.v1.util.PrefsUtil
import com.wavesplatform.wallet.v2.ui.base.view.BaseActivity
import kotlinx.android.synthetic.main.activity_dev_options.*
import pers.victor.ext.click
import javax.inject.Inject
class DevOptionsActivity : BaseActivity(), DevOptionsView {
@Inject
@InjectPresenter
lateinit var presenter: DevOptionsPresenter
@ProvidePresenter
fun providePresenter(): DevOptionsPresenter = presenter
override fun configLayoutRes() = R.layout.activity_dev_options
override fun onViewReady(savedInstanceState: Bundle?) {
setupToolbar(toolbar_view, true, "Dev options", R.drawable.ic_toolbar_back_black)
useTestNewsSwitch.isChecked = presenter.preferenceHelper.useTestNews
useTestNewsSwitch.setOnCheckedChangeListener { _, isChecked ->
presenter.preferenceHelper.useTestNews = isChecked
}
resetShowedNewsButton.click {
prefsUtil.removeGlobalValue(PrefsUtil.SHOWED_NEWS_IDS)
}
}
} | 1 | Kotlin | 1 | 2 | 9359a88dfe96f9fbc78360fd22c17fce252a88ae | 1,248 | PZU-android | MIT License |
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/models/pojo/apiv2/models/AddLinkPreviewImage.kt | wigr11 | 132,491,533 | true | {"Kotlin": 932984, "Java": 251617} | package io.github.feelfreelinux.wykopmobilny.models.pojo.apiv2.models
import com.fasterxml.jackson.annotation.JsonProperty
data class AddLinkPreviewImage(
@JsonProperty("key")
val key : String,
@JsonProperty("type")
val type : String,
@JsonProperty("preview_url")
val previewUrl : String,
@JsonProperty("source_url")
val sourceUrl : String
) | 0 | Kotlin | 0 | 0 | ae3395fa96817628614b185e7cf84e81b4d44b47 | 410 | WykopMobilny | MIT License |
android/engine/src/androidTest/java/org/smartregister/fhircore/engine/ui/components/register/LoaderViewTest.kt | opensrp | 339,242,809 | false | null | /*
* Copyright 2021 Ona Systems, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.smartregister.fhircore.engine.ui.components.register
import android.app.Application
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.assertTextEquals
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithTag
import androidx.test.core.app.ApplicationProvider
import org.junit.Rule
import org.junit.Test
import org.smartregister.fhircore.engine.R
class LoaderViewKtTest {
@get:Rule val composeRule = createComposeRule()
@Test
fun testLoaderDialogView() {
composeRule.setContent { LoaderDialog() }
composeRule.onNodeWithTag(LOADER_DIALOG_PROGRESS_BAR_TAG).assertExists()
composeRule.onNodeWithTag(LOADER_DIALOG_PROGRESS_BAR_TAG).assertIsDisplayed()
composeRule.onNodeWithTag(LOADER_DIALOG_PROGRESS_MSG_TAG).assertExists()
composeRule.onNodeWithTag(LOADER_DIALOG_PROGRESS_MSG_TAG).assertIsDisplayed()
composeRule
.onNodeWithTag(LOADER_DIALOG_PROGRESS_MSG_TAG)
.assertTextEquals(
ApplicationProvider.getApplicationContext<Application>().getString(R.string.syncing)
)
}
}
| 192 | null | 8 | 56 | 64a55e6920cb6280cf02a0d68152d9c03266518d | 1,723 | fhircore | Apache License 2.0 |
feature/src/main/java/br/com/sticup/mvvm/viewmodel/data/UiData.kt | PimentaPeps | 128,840,952 | false | null | package br.com.sticup.mvvm.viewmodel.data
import br.com.sticup.mvvm.repository.data.User
data class UsersList(val users: List<User>, val message: String, val error: Throwable? = null)
| 0 | Kotlin | 0 | 0 | f71f3aa930f2a410f4bf8cc573804f272cacda9c | 186 | Sticup | MIT License |
app/src/main/java/fr/acinq/phoenix/lnurl/LNUrl.kt | thepkbadger | 306,600,339 | true | {"C": 8823912, "Kotlin": 407570, "C++": 305951, "Java": 42253, "Dockerfile": 3321, "CMake": 3039} | /*
* Copyright 2020 ACINQ SAS
*
* 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 fr.acinq.phoenix.lnurl
import android.os.Parcelable
import fr.acinq.bitcoin.Bech32
import fr.acinq.eclair.MilliSatoshi
import fr.acinq.phoenix.utils.Wallet
import kotlinx.android.parcel.Parcelize
import okhttp3.HttpUrl
import okhttp3.Request
import okhttp3.Response
import org.json.JSONException
import org.json.JSONObject
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.util.concurrent.TimeUnit
import kotlin.math.max
class LNUrlUnhandledTag(tag: String) : RuntimeException("unhandled LNURL tag=$tag")
sealed class LNUrlRemoteFailure : java.lang.RuntimeException() {
object Generic : LNUrlRemoteFailure()
object CouldNotConnect: LNUrlRemoteFailure()
object Unreadable : LNUrlRemoteFailure()
data class Detailed(val reason: String) : LNUrlRemoteFailure()
data class Code(val code: Int) : LNUrlRemoteFailure()
}
class LNUrlAuthMissingK1 : RuntimeException("missing parameter k1 in LNURL-auth url")
class LNUrlWithdrawAtLeastMinSat(val min: MilliSatoshi) : RuntimeException()
class LNUrlWithdrawAtMostMaxSat(val max: MilliSatoshi) : RuntimeException()
interface LNUrl {
companion object Util {
private val log: Logger = LoggerFactory.getLogger(this::class.java)
val httpClient = Wallet.httpClient.newBuilder()
.connectTimeout(5, TimeUnit.SECONDS)
.writeTimeout(5, TimeUnit.SECONDS)
.readTimeout(5, TimeUnit.SECONDS)
.build()
/**
* Decodes a Bech32 string and transform it into a https request.
*/
private fun decodeUrl(source: String): HttpUrl {
val res = Bech32.decode(source)
val payload = String(Bech32.five2eight(res._2), Charsets.UTF_8)
log.info("reading serialized lnurl with hrp=${res._1} and payload=$payload")
val url = HttpUrl.get(payload)
require(url.isHttps) { "invalid url=${url}, should be https" }
return url
}
fun extractLNUrl(source: String): LNUrl {
val url = decodeUrl(source)
// special flow for login: do not send GET to url just yet
return if (url.queryParameter("tag") == "login") {
val k1 = url.queryParameter("k1")
if (k1 == null) {
throw LNUrlAuthMissingK1()
} else {
LNUrlAuth(url.host()!!, url.toString(), k1)
}
} else {
// otherwise execute GET to url to retrieve details from remote server
val json = executeMetadataQuery(url)
val tag = json.getString("tag")
val callback = HttpUrl.get(json.getString("callback"))
require(callback.isHttps) { "invalid callback=${url}, should be https" }
return when (tag) {
"withdrawRequest" -> {
val walletIdentifier = json.getString("k1")
val maxWithdrawable = MilliSatoshi(json.getLong("maxWithdrawable"))
val minWithdrawable = MilliSatoshi(max(maxWithdrawable.toLong(), if (json.has("minWithdrawable")) json.getLong("minWithdrawable") else 1))
val desc = json.getString("defaultDescription")
LNUrlWithdraw(url.toString(), callback.toString(), walletIdentifier, desc, minWithdrawable, maxWithdrawable)
}
else -> throw LNUrlUnhandledTag(tag)
}
}
}
private fun executeMetadataQuery(url: HttpUrl): JSONObject {
log.info("retrieving metadata from LNURL=$url")
val request = Request.Builder().url(url).build()
return httpClient.newCall(request).execute().use { handleLNUrlRemoteResponse(it) }
}
fun handleLNUrlRemoteResponse(response: Response): JSONObject {
val body = response.body()
return if (response.isSuccessful && body != null) {
try {
val json = JSONObject(body.string())
log.debug("remote lnurl service responded with: $json")
if (json.has("status") && json.getString("status").trim().equals("error", true)) {
log.error("lnurl service responded with error: $json")
val message = if (json.has("reason")) json.getString("reason") else "N/A"
throw LNUrlRemoteFailure.Detailed(message)
} else {
json
}
} catch (e: JSONException) {
log.error("failed to read LNUrl response: ", e)
throw LNUrlRemoteFailure.Unreadable
}
} else if (!response.isSuccessful) {
throw LNUrlRemoteFailure.Code(response.code())
} else {
throw LNUrlRemoteFailure.Generic
}
}
}
}
@Parcelize
class LNUrlAuth(val host: String, val authEndpoint: String, val k1: String) : LNUrl, Parcelable
@Parcelize
class LNUrlWithdraw(val origin: String, val callback: String, val walletIdentifier: String,
val description: String, val minWithdrawable: MilliSatoshi, val maxWithdrawable: MilliSatoshi) : LNUrl, Parcelable
| 0 | null | 0 | 0 | 386c56dafe82e89a87a323169344fe22ee10fb19 | 5,339 | phoenix | Apache License 2.0 |
app/src/main/java/com/example/noteappcompose/presentation/noteDetailsScreen/uiStates/InputFieldUiState.kt | adelayman1 | 576,770,488 | false | null | package com.example.noteappcompose.presentation.noteDetailsScreen.uiStates
data class InputFieldUiState(var text:String = "", var errorMessage:String? = null) | 0 | Kotlin | 0 | 5 | ebad8b1dc62c5523d25270fa5f237f9246791afa | 159 | ComposeNotesAppKtor-Client | MIT License |
koin-core/src/test/kotlin/org/koin/test/koin/example/all_modules.kt | arnis71 | 105,808,830 | true | {"Kotlin": 97953, "Java": 352} | package org.koin.test.koin.example
import org.koin.dsl.context.Context
import org.koin.dsl.context.Scope
import org.koin.dsl.module.Module
/**
* Created by arnaud on 09/06/2017.
*/
class SampleModuleA_C : Module() {
override fun context() =
declareContext {
provide { ServiceA(get()) }
provide { ServiceC(get(), get()) }
}
}
class SampleModuleB : Module() {
override fun context() =
declareContext {
provide { ServiceB() }
}
}
class SampleModuleD : Module() {
override fun context() =
declareContext {
provide { ServiceD(getProperty("myVal")) }
}
}
class ScopedModuleB : Module() {
override fun context() =
declareContext(ServiceB::class) {
// scope { ServiceB::class }
provide { ServiceB() }
}
}
class MultiDeclareA : Module() {
override fun context() =
declareContext {
provide { ServiceB() }
provide("A1") { ServiceA(get()) }
provide("A2") { ServiceA(get()) }
}
}
class ConflictingModule : Module() {
override fun context() =
declareContext {
provide { ServiceB() }
provide { ServiceB() }
}
}
class ConflictingDependency : Module() {
override fun context() =
declareContext {
provide("B1") { ServiceB() }
provide("B2") { ServiceB() }
provide { ServiceA(get()) }
}
}
class CleanMultiDependency : Module() {
override fun context() =
declareContext {
provide("B1") { ServiceB() }
provide("B2") { ServiceB() }
provide { ServiceA(get("B1")) }
}
}
class ScopedModuleA : Module() {
override fun context() =
declareContext(ServiceA::class) {
// scope { ServiceA::class }
provide { ServiceA(get()) }
}
}
class SampleModuleC : Module() {
override fun context(): Context = declareContext {
provide { ServiceC(get(), get()) }
}
}
class SampleModuleOA : Module() {
override fun context() = declareContext {
provide { OtherServiceA(get()) }
}
}
class BindModuleB : Module() {
override fun context() = declareContext {
provide { ServiceB() } bind Processor::class
}
} | 0 | Kotlin | 0 | 0 | 6fe0144dda9b3d4ce4dcf931155c301124c3dcce | 2,474 | koin | Apache License 2.0 |
litho-zoomable/src/main/kotlin/com/facebook/litho/widget/zoomable/LithoZoomableController.kt | facebook | 80,179,724 | false | null | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* 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.facebook.litho.widget.zoomable
import android.content.Context
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.Drawable
import android.view.ViewGroup
import com.facebook.litho.LithoRenderTreeView
import com.facebook.litho.findComponentActivity
import com.facebook.rendercore.zoomable.ZoomableViewBaseController
class LithoZoomableController(
context: Context,
backgroundDrawable: Drawable = ColorDrawable(BLACK_TRANSPARENT_80)
) :
ZoomableViewBaseController<LithoZoomableView>(
context = context, backgroundDrawable = backgroundDrawable, isRemoteZoomEnabled = true) {
override val decorView: ViewGroup =
checkNotNull(context.findComponentActivity()).window.decorView as ViewGroup
override fun getRenderTreeView(): LithoRenderTreeView = requireRootView().renderTreeView
}
| 88 | null | 765 | 7,703 | 8bde23649ae0b1c594b9bdfcb4668feb7d8a80c0 | 1,468 | litho | Apache License 2.0 |
server-core/src/main/kotlin/com/lightningkite/lightningserver/db/ModelRestUpdatesWebsocket.kt | lightningkite | 512,032,499 | false | {"Kotlin": 2189721, "TypeScript": 38628, "Ruby": 873, "JavaScript": 118} | @file:UseContextualSerialization(Instant::class)
package com.lightningkite.lightningserver.db
import com.lightningkite.prepareModelsServerCore
import com.lightningkite.lightningdb.*
import com.lightningkite.serialization.*
import com.lightningkite.lightningserver.auth.*
import com.lightningkite.lightningserver.core.ServerPath
import com.lightningkite.lightningserver.exceptions.NotFoundException
import com.lightningkite.lightningserver.serialization.Serialization
import com.lightningkite.lightningserver.tasks.startup
import com.lightningkite.lightningserver.tasks.task
import com.lightningkite.lightningserver.typed.*
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.toList
import kotlinx.coroutines.launch
import kotlinx.serialization.UseContextualSerialization
import kotlinx.datetime.Instant
import com.lightningkite.serialization.SerializableProperty
import com.lightningkite.lightningserver.core.ServerPathGroup
import com.lightningkite.lightningserver.schedule.schedule
import com.lightningkite.lightningserver.websocket.WebSocketIdentifier
import com.lightningkite.now
import com.lightningkite.serialization.notNull
import kotlinx.serialization.Contextual
import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
import kotlin.time.Duration.Companion.days
import kotlin.time.Duration.Companion.hours
import kotlin.time.Duration.Companion.minutes
class ModelRestUpdatesWebsocket<USER: HasId<*>?, T : HasId<ID>, ID : Comparable<ID>>(
path: ServerPath,
database: () -> Database,
info: ModelInfo<USER, T, ID>,
key: SerializableProperty<T, *>? = null,
): ServerPathGroup(path) {
init {
prepareModelsServerCore()
}
private val modelName = info.serialization.serializer.descriptor.serialName.substringBefore('<').substringAfterLast('.')
private val modelIdentifier = info.serialization.serializer.descriptor.serialName
private val helper = ModelRestUpdatesWebsocketHelper[database]
private val interfaceName = Documentable.InterfaceInfo(path, "ClientModelRestEndpointsPlusUpdatesWebsocket", listOf(
info.serialization.serializer,
info.serialization.idSerializer
))
val websocket = path.apiWebsocket<USER, Condition<T>, CollectionUpdates<T, ID>>(
authOptions = info.authOptions,
inputType = Condition.serializer(info.serialization.serializer),
outputType = CollectionUpdates.serializer(info.serialization.serializer, info.serialization.idSerializer),
belongsToInterface = interfaceName,
summary = "Updates",
description = "Gets updates to items in the database matching a certain condition.",
errorCases = listOf(),
connect = {
val auth = this.authOrNull
val user = auth?.serializable(now().plus(1.days))
val collection = info.collection(this)
helper.subscriptionDb().insertOne(
__WebSocketDatabaseUpdatesSubscription(
_id = event.id,
databaseId = modelIdentifier,
condition = "",
user = user,
mask = Serialization.json.encodeToString(
Mask.serializer(info.serialization.serializer),
collection.mask()
),
relevant = setOf(),
establishedAt = now()
)
)
},
message = { condition ->
val existing = helper.subscriptionDb().get(socketId) ?: throw NotFoundException()
@Suppress("UNCHECKED_CAST") val auth = existing.user?.real() as? RequestAuth<USER & Any>
val p = info.collection(AuthAccessor(auth, null))
val fullCondition = p.fullCondition(condition).simplify()
val fullConditionSerialized = Serialization.json.encodeToString(Condition.serializer(info.serialization.serializer), fullCondition)
helper.subscriptionDb().updateOne(
condition = condition { it._id eq socketId },
modification = modification {
it.condition assign fullConditionSerialized
if (key != null)
it.relevant assign fullCondition.relevantHashCodesForKey(key)
else
it.relevant assign null
},
)
send(CollectionUpdates(condition = condition))
},
disconnect = {
helper.subscriptionDb().deleteMany(condition { it._id eq socketId })
}
)
val sendWsChanges = task(
"$modelIdentifier.sendWsUpdates",
CollectionChanges.serializer(info.serialization.serializer)
) { changes: CollectionChanges<T> ->
val jobs = ArrayList<Job>()
val targets = if (key != null) {
val relevantValues = changes.changes.asSequence().flatMap { listOfNotNull(it.old, it.new) }
.map { key.get(it).hashCode() }
.toSet()
helper.subscriptionDb().find(condition {
(it.databaseId eq modelIdentifier) and ((it.relevant eq null) or (it.relevant.notNull.any { it inside relevantValues }))
})
} else {
helper.subscriptionDb().find(condition { it.databaseId eq modelIdentifier })
}
targets.collect {
if (it.condition.isEmpty()) return@collect
val m =
try {
Serialization.json.decodeFromString(Mask.serializer(info.serialization.serializer), it.mask)
} catch (e: Exception) {
return@collect
}
val c = try {
Serialization.json.decodeFromString(
Query.serializer(info.serialization.serializer),
it.condition
)
} catch (e: Exception) {
return@collect
}
val toSend = changes.changes.map { entry ->
ListChange(
old = entry.old?.takeIf { c.condition(it) }?.let { m(it) },
new = entry.new?.takeIf { c.condition(it) }?.let { m(it) },
)
}.filter { it.old != null || it.new != null }
jobs.add(launch {
val updates = CollectionUpdates(
updates = toSend.mapNotNull { it.new }.toSet(),
remove = toSend.mapNotNull { it.old.takeIf { _ -> it.new == null }?._id }.toSet()
)
val size = Serialization.json.encodeToString(CollectionUpdates.serializer(info.serialization.serializer, info.serialization.idSerializer), updates).length
if (size >= 24000) {
websocket.send(it._id, CollectionUpdates(overload = true))
} else {
websocket.send(it._id, updates)
}
})
}
jobs.forEach { it.join() }
}
suspend fun sendUpdates(changes: CollectionChanges<T>) {
changes.changes.chunked(200).forEach {
sendWsChanges(CollectionChanges(changes = it))
}
}
init {
startup {
info.registerChangeListener(::sendUpdates)
}
}
}
class ModelRestUpdatesWebsocketHelper private constructor(val database: () -> Database) {
companion object {
private val existing = HashMap<() -> Database, ModelRestUpdatesWebsocketHelper>()
operator fun get(database: () -> Database) = existing.getOrPut(database) { ModelRestUpdatesWebsocketHelper(database) }
}
fun subscriptionDb() = database().collection<__WebSocketDatabaseUpdatesSubscription>()
val schedule = schedule("ModelRestUpdatesWebsocketHelper.cleanup", 5.minutes) {
val now = now()
val db =
subscriptionDb().deleteMany(condition<__WebSocketDatabaseUpdatesSubscription> {
(it.condition eq "") and
(it.establishedAt lt now.minus(5.minutes))
} or condition<__WebSocketDatabaseUpdatesSubscription> {
it.establishedAt lt now.minus(1.hours)
})
for (changeSub in db) {
try {
changeSub._id.close()
} catch (_: Exception) {
// We don't really care. We just want to shut down as many of these as we can.
/*squish*/
}
}
}
}
@Serializable
@GenerateDataClassPaths
@Suppress("ClassName")
@IndexSet(["databaseId", "relevant"])
data class __WebSocketDatabaseUpdatesSubscription(
override val _id: WebSocketIdentifier,
val databaseId: String,
val user: RequestAuthSerializable?, //USER
val condition: String, //Condition<T>
val mask: String, //Mask<T>
@Contextual val establishedAt: Instant,
val relevant: Set<Int>? = null,
) : HasId<WebSocketIdentifier>
fun <T, V> Condition<T>.relevantHashCodesForKey(key: SerializableProperty<T, V>): Set<Int>? = when(this) {
is Condition.And<T> -> conditions
.asSequence()
.mapNotNull { it.relevantHashCodesForKey(key) }
.reduceOrNull { a, b -> a.intersect(b) }
is Condition.Or<T> -> conditions
.asSequence()
.map { it.relevantHashCodesForKey(key) }
.reduceOrNull { a, b -> if (a == null || b == null) null else a.union(b) }
is Condition.OnField<*, *> -> if (this.key == key) condition.relevantHashCodes() else null
else -> null
}
fun <T> Condition<T>.relevantHashCodes(): Set<Int>? = when (this) {
is Condition.And<T> -> conditions
.asSequence()
.mapNotNull { it.relevantHashCodes() }
.reduceOrNull { a, b -> a.intersect(b) }
is Condition.Or<T> -> conditions
.asSequence()
.map { it.relevantHashCodes() }
.reduceOrNull { a, b -> if (a == null || b == null) null else a.union(b) }
is Condition.Equal -> setOf(value.hashCode())
is Condition.Inside -> values.map { it.hashCode() }.toSet()
else -> null
} | 3 | Kotlin | 1 | 5 | f404cc57cbdbe2a90b4e59d4ecd5ad22e008a730 | 10,031 | lightning-server | MIT License |
app/src/main/java/com/example/myapplication/ui/page/feedback/FeedbackFragment.kt | yo-lolo | 660,058,834 | false | {"Kotlin": 403451, "Java": 59574, "HTML": 13393} | package com.example.myapplication.ui.page.feedback
import android.content.Intent
import android.os.Bundle
import android.provider.MediaStore
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.core.widget.doOnTextChanged
import androidx.fragment.app.viewModels
import androidx.navigation.NavController
import androidx.navigation.fragment.findNavController
import com.blankj.utilcode.util.ToastUtils
import com.ctq.sphone.market.base.BaseFragment
import com.example.myapplication.R
import com.example.myapplication.config.AppConfig
import com.example.myapplication.databinding.FragmentFeedbackBinding
import com.example.myapplication.isLogin
import com.example.myapplication.vm.FeedbackViewModel
/**
* @Copyright : China Telecom Quantum Technology Co.,Ltd
* @ProjectName : My Application
* @Package : com.example.myapplication.ui.page.feedback
* @ClassName : FeedbackFragment
* @Description : 文件描述
* @Author : yulu
* @CreateDate : 2023/6/29 13:45
* @UpdateUser : yulu
* @UpdateDate : 2023/6/29 13:45
* @UpdateRemark : 更新说明
*/
class FeedbackFragment : BaseFragment() {
private lateinit var binding: FragmentFeedbackBinding
private val feedbackViewModel by viewModels<FeedbackViewModel>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentFeedbackBinding.inflate(layoutInflater)
val view = binding.root
initView(view)
return view
}
private fun initView(view: View) {
binding.include.headLayout.apply {
setBackgroundResource(R.color.color_activity_bg)
setBackListener() {
findNavController().popBackStack()
}
setTitle("问题反馈")
}
binding.feedbackPDetail.doOnTextChanged { text, start, count, after ->
binding.pDetailCount.text = "${text!!.length}/200"
}
binding.imageDisplayView.apply {
addImageListener = {
openPhoto()
}
}
binding.feedbackSubmit.setOnClickListener {
val pictureItems = binding.imageDisplayView.getPhotos().filter { !it.isNullOrBlank() }
val detail = binding.feedbackPDetail.text.toString().trim()
if (isLogin()){
feedbackViewModel.onSubmit(pictureItems, detail)
}else{
ToastUtils.showShort("请先登录")
}
}
binding.apply {
qualityProblem.setOnClickListener {
feedbackViewModel.typeChange(it.tag as String)
}
useProblem.setOnClickListener {
feedbackViewModel.typeChange(it.tag as String)
}
otherProblem.setOnClickListener {
feedbackViewModel.typeChange(it.tag as String)
}
}
feedbackViewModel.type.observe(viewLifecycleOwner) {
changeStyle(it)
}
feedbackViewModel.commentSuccess.observe(viewLifecycleOwner) {
if (it) {
findNavController().popBackStack()
}
}
}
/**
* 实现单选问题类型,点击改变组件样式
*/
private fun changeStyle(data: String) {
binding.qualityProblem.apply {
setBackgroundResource(if (data == this.tag) R.drawable.type_button_true_bg else R.drawable.type_button_false_bg)
setTextColor(resources.getColor(if (data == this.tag) R.color.color_e7e7e7 else R.color.color_3c3c3c))
}
binding.useProblem.apply {
setBackgroundResource(if (data == this.tag) R.drawable.type_button_true_bg else R.drawable.type_button_false_bg)
setTextColor(resources.getColor(if (data == this.tag) R.color.color_e7e7e7 else R.color.color_3c3c3c))
}
binding.otherProblem.apply {
setBackgroundResource(if (data == this.tag) R.drawable.type_button_true_bg else R.drawable.type_button_false_bg)
setTextColor(resources.getColor(if (data == this.tag) R.color.color_e7e7e7 else R.color.color_3c3c3c))
}
}
/**
* 打开相册选择图片
* 调用startActivityForResult方法向系统选择器请求数据 第二个参数是请求码
*/
private fun openPhoto() {
if (binding.imageDisplayView.getPhotos().size > 5) {
Toast.makeText(context, "最多添加5张图片", Toast.LENGTH_SHORT).show()
} else {
val intent = Intent(
Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI
)
startActivityForResult(intent, AppConfig.IMAGE_OPEN)
}
}
/**
* 解析系统选择器返回的结果
*/
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
binding.imageDisplayView.onActivityResult(requestCode, resultCode, data)
}
} | 0 | Kotlin | 0 | 0 | cf7ff1bc88a11637165720e528b271bbe9bb829c | 5,066 | yolo | Apache License 2.0 |
app/src/main/java/com/example/weatherprophet/WeatherProphetApplication.kt | Arrayflow | 531,760,849 | false | null | package com.example.weatherprophet
import android.annotation.SuppressLint
import android.app.Application
import android.content.Context
class WeatherProphetApplication : Application() {
companion object {
@SuppressLint("StaticFieldLeak")
lateinit var context: Context
const val TOKEN = "ijA8NlbWaxdzQd8i"
}
override fun onCreate() {
super.onCreate()
context = this.applicationContext
}
} | 0 | Kotlin | 0 | 0 | 67bc6f52e6580a619c4930e514843a47fa3ad01a | 446 | WeatherProphet | Apache License 2.0 |
components/bridge/synchronization/impl/src/main/java/com/flipperdevices/bridge/synchronization/impl/repository/flipper/KeysListingRepository.kt | flipperdevices | 288,258,832 | false | null | package com.flipperdevices.bridge.synchronization.impl.repository.flipper
import com.flipperdevices.bridge.api.manager.FlipperRequestApi
import com.flipperdevices.bridge.api.model.FlipperRequestPriority
import com.flipperdevices.bridge.api.model.wrapToRequest
import com.flipperdevices.bridge.api.utils.Constants
import com.flipperdevices.bridge.dao.api.model.FlipperFileType
import com.flipperdevices.bridge.dao.api.model.FlipperKeyPath
import com.flipperdevices.bridge.synchronization.impl.model.ResultWithProgress
import com.flipperdevices.core.log.LogTagProvider
import com.flipperdevices.core.log.debug
import com.flipperdevices.core.log.info
import com.flipperdevices.protobuf.main
import com.flipperdevices.protobuf.storage.Storage
import com.flipperdevices.protobuf.storage.listRequest
import java.io.File
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.toList
const val SIZE_BYTES_LIMIT = 10 * 1024 * 1024 // 10MiB
class KeysListingRepository : LogTagProvider {
override val TAG = "KeysListingRepository"
fun getAllKeys(
requestApi: FlipperRequestApi
) = callbackFlow<ResultWithProgress<List<FlipperKeyPath>>> {
info { "Start request keys listing" }
val allKeys = mutableListOf<FlipperKeyPath>()
FlipperFileType.values().forEachIndexed { index, fileType ->
send(ResultWithProgress.InProgress(index, FlipperFileType.values().size))
allKeys.addAll(getKeysForFileType(requestApi, fileType))
}
send(ResultWithProgress.Completed(allKeys))
close()
}
private suspend fun getKeysForFileType(
requestApi: FlipperRequestApi,
fileType: FlipperFileType
): List<FlipperKeyPath> {
val fileTypePath = File(Constants.KEYS_DEFAULT_STORAGE, fileType.flipperDir).path
return requestApi.request(
main {
storageListRequest = listRequest {
path = fileTypePath
}
}.wrapToRequest(FlipperRequestPriority.BACKGROUND)
).toList().map { it.storageListResponse.fileList }.flatten()
.filter { isValidFile(it, fileType) }
.map {
FlipperKeyPath(
folder = fileType.flipperDir,
name = it.name
)
}
}
private fun isValidFile(file: Storage.File, requestedType: FlipperFileType): Boolean {
if (file.type != Storage.File.FileType.FILE) {
debug {
"File ${file.name} is not file. This is folder. Ignore it"
}
return false
}
if (file.size > SIZE_BYTES_LIMIT) {
debug {
"File ${file.name} skip, because current size limit is $SIZE_BYTES_LIMIT, " +
"but file size is ${file.size}"
}
return false
}
val extension = file.name.substringAfterLast(".")
val fileTypeByExtension = FlipperFileType.getByExtension(extension)
if (fileTypeByExtension == null) {
debug {
"File ${file.name} skip, because we don't support this file extension ($extension)"
}
return false
}
if (fileTypeByExtension != requestedType) {
debug {
"File ${file.name} skip, because folder type ($requestedType) " +
"and extension type ($fileTypeByExtension) is not equals"
}
return false
}
return true
}
}
| 3 | null | 31 | 293 | 522f873d6dcf09a8f1907c1636fb0c3a996f5b44 | 3,542 | Flipper-Android-App | MIT License |
app/src/main/java/space/taran/arknavigator/utils/extensions/ViewExt.kt | ARK-Builders | 394,855,699 | false | null | package space.taran.arknavigator.utils.extensions
import android.view.View
import android.widget.TextView
import kotlin.coroutines.Continuation
import kotlin.coroutines.ContinuationInterceptor
import kotlin.coroutines.CoroutineContext
import kotlinx.coroutines.CompletionHandler
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import space.taran.arknavigator.R
fun View.changeEnabledStatus(isEnabledStatus: Boolean) {
isEnabled = isEnabledStatus
isClickable = isEnabledStatus
isFocusable = isEnabledStatus
}
fun View.makeGone() {
visibility = View.GONE
}
fun View.makeVisible() {
visibility = View.VISIBLE
}
fun View.makeVisibleAndSetOnClickListener(action: () -> Unit) {
setOnClickListener { action() }
visibility = View.VISIBLE
}
fun TextView?.textOrGone(string: String?) {
if (string.isNullOrEmpty()) this?.makeGone()
else {
this?.text = string
this?.makeVisible()
}
}
val View.autoDisposeScope: CoroutineScope
get() {
val exist = getTag(R.id.view_tag) as? CoroutineScope
if (exist != null) {
return exist
}
val newScope = CoroutineScope(
SupervisorJob() +
Dispatchers.Main +
autoDisposeInterceptor()
)
setTag(R.id.view_tag, newScope)
return newScope
}
fun ViewAutoDisposeInterceptor(view: View): ContinuationInterceptor =
ViewAutoDisposeInterceptorImpl(view)
/**
* Create a ContinuationInterceptor that follows attach/detach lifecycle of [View].
*/
fun View.autoDisposeInterceptor(): ContinuationInterceptor =
ViewAutoDisposeInterceptor(this)
private class ViewAutoDisposeInterceptorImpl(
private val view: View
) : ContinuationInterceptor {
override val key: CoroutineContext.Key<*>
get() = ContinuationInterceptor
override fun <T> interceptContinuation(continuation: Continuation<T>):
Continuation<T> {
val job = continuation.context[Job]
if (job != null) {
view.autoDispose(job)
}
return continuation
}
}
fun View.autoDispose(job: Job) {
val listener = ViewListener(this, job)
this.addOnAttachStateChangeListener(listener)
}
private class ViewListener(
private val view: View,
private val job: Job
) : View.OnAttachStateChangeListener, CompletionHandler {
override fun onViewDetachedFromWindow(v: View) {
view.removeOnAttachStateChangeListener(this)
job.cancel()
}
override fun onViewAttachedToWindow(v: View) {
// do nothing
}
override fun invoke(cause: Throwable?) {
view.removeOnAttachStateChangeListener(this)
job.cancel()
}
}
| 97 | null | 8 | 8 | 886c7da36af73cc9235452d3b03412cc4c01e607 | 2,797 | ARK-Navigator | MIT License |
app/src/main/java/org/p2p/wallet/intercom/IntercomService.kt | p2p-org | 306,035,988 | false | null | package org.p2p.wallet.intercom
import android.app.Application
import io.intercom.android.sdk.Intercom
import io.intercom.android.sdk.identity.Registration
object IntercomService {
fun setup(app: Application, apiKey: String, appId: String) {
Intercom.initialize(app, apiKey, appId)
// Hide in app messages
Intercom.client().setInAppMessageVisibility(Intercom.Visibility.GONE)
}
fun signIn(userId: String) {
if (userId.isNotEmpty()) {
val registration = Registration.create().withUserId(userId)
Intercom.client().registerIdentifiedUser(registration)
} else {
Intercom.client().registerUnidentifiedUser()
}
}
fun logout() {
Intercom.client().logout()
}
fun showMessenger() {
Intercom.client().displayMessenger()
}
}
| 16 | Kotlin | 6 | 14 | 9cf97a5edd8be594ed301c88788d71ea20483571 | 852 | p2p-wallet-android | MIT License |
sip-permission/src/main/kotlin/com/basicfu/sip/permission/model/vo/ResourceVo.kt | tidehc | 189,163,300 | true | {"Kotlin": 382525, "JavaScript": 6535, "HTML": 4170, "Dockerfile": 1708, "Java": 104} | package com.basicfu.sip.permission.model.vo
class ResourceVo {
var id: Long? = null
var serviceId: Long? = null
var url: String? = null
var name: String? = null
var method: String? = null
var q: String? = null
/**1为预览更新资源详情,2为真的要更新操作*/
var type: Int? = null
}
| 0 | Kotlin | 0 | 0 | dd9dc2ebb7aba2432197888cc3040317eb506118 | 294 | sip | MIT License |
app/src/main/java/com/coinninja/coinkeeper/ui/market/ChartStats.kt | coinninjadev | 175,276,289 | false | null | package com.coinninja.coinkeeper.ui.market
data class ChartStats(val high: Float, val low: Float, val first: Float, val last: Float) {
val priceDifference get() = last - first
val percentageDifference get() = priceDifference / first * 100
} | 2 | null | 0 | 6 | d67d7c0b9cad27db94470231073c5d6cdda83cd0 | 249 | dropbit-android | MIT License |
app/src/main/java/com/furkansubasiay/googlemaps_sample_mvvvm/model/PlacesResponce.kt | furkansubasiay | 273,860,643 | false | null | package com.furkansubasiay.googlemaps_sample_mvvvm.model
import com.google.gson.annotations.SerializedName
/**
* Created by FURKAN SUBAŞIAY on 2020-06-20.
*/
data class PlacesResponce(
@SerializedName("status") var status:String?,
@SerializedName("results") var places :ArrayList<PlaceItem>?
) | 0 | Kotlin | 0 | 0 | 3b80da32c6f456bda8479f0a4d2d927164ec1ecb | 305 | GoogleMapsSample-MVVM | Apache License 2.0 |
app/src/main/java/wannabit/io/cosmostaion/network/res/neutron/ResVaultData.kt | cosmostation | 418,314,439 | false | null | package wannabit.io.cosmostaion.network.res.neutron
data class ResVaultData(
val name: String?,
val description: String?,
val address: String?,
)
data class ResVotingData(val power: String?)
| 0 | null | 51 | 66 | 4a89189b1f7f053a1cd97a1e0371940bad52bd05 | 205 | cosmostation-android | MIT License |
app/src/main/java/com/google/samples/apps/sunflower/data/UnsplashPhoto.kt | tadashi0713 | 435,394,266 | false | null | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.mygarden.data
import com.google.gson.annotations.SerializedName
/**
* Data class that represents a photo from Unsplash.
*
* Not all of the fields returned from the API are represented here; only the ones used in this
* project are listed below. For a full list of fields, consult the API documentation
* [here](https://unsplash.com/documentation#get-a-photo).
*/
data class UnsplashPhoto(
@field:SerializedName("id") val id: String,
@field:SerializedName("urls") val urls: UnsplashPhotoUrls,
@field:SerializedName("user") val user: UnsplashUser
)
| 8 | null | 9 | 5 | 864b7e1cc85876cfb58da9b7986f8a69602646a3 | 1,195 | circleci-demo-android | Apache License 2.0 |
server/src/main/kotlin/br/com/devsrsouza/kotlinbukkitapi/server/Server.kt | Stanicc | 201,663,593 | true | {"Kotlin": 383292} | package br.com.devsrsouza.kotlinbukkitapi.server
import br.com.devsrsouza.kotlinbukkitapi.server.api.chat.ServerChat
import br.com.devsrsouza.kotlinbukkitapi.server.api.item.ServerItem
import br.com.devsrsouza.kotlinbukkitapi.server.api.nbt.ServerNBT
import br.com.devsrsouza.kotlinbukkitapi.server.api.chat.ServerTitle
import br.com.devsrsouza.kotlinbukkitapi.server.api.player.ServerTabList
import br.com.devsrsouza.kotlinbukkitapi.server.bukkit.v1_10.chat.ServerChatImpl as ServerChatImplBukkit
import br.com.devsrsouza.kotlinbukkitapi.server.bukkit.v1_11.chat.ServerTitleImpl as ServerTitleImplBukkit
import br.com.devsrsouza.kotlinbukkitapi.server.nms.v1_8_R1.nbt.ServerNBTImpl as ServerNBTImpl1_8_R1
import br.com.devsrsouza.kotlinbukkitapi.server.nms.v1_8_R1.player.ServerTabListImpl as ServerTabListImpl1_8_R1
import br.com.devsrsouza.kotlinbukkitapi.server.nms.v1_8_R1.chat.ServerTitleImpl as ServerTitleImpl1_8_R1
import br.com.devsrsouza.kotlinbukkitapi.server.nms.v1_8_R1.chat.ServerChatImpl as ServerChatImpl1_8_R1
import br.com.devsrsouza.kotlinbukkitapi.server.nms.v1_8_R1.item.ServerItemImpl as ServerItemImpl1_8_R1
import br.com.devsrsouza.kotlinbukkitapi.server.nms.v1_8_R2.nbt.ServerNBTImpl as ServerNBTImpl1_8_R2
import br.com.devsrsouza.kotlinbukkitapi.server.nms.v1_8_R2.player.ServerTabListImpl as ServerTabListImpl1_8_R2
import br.com.devsrsouza.kotlinbukkitapi.server.nms.v1_8_R2.chat.ServerTitleImpl as ServerTitleImpl1_8_R2
import br.com.devsrsouza.kotlinbukkitapi.server.nms.v1_8_R2.chat.ServerChatImpl as ServerChatImpl1_8_R2
import br.com.devsrsouza.kotlinbukkitapi.server.nms.v1_8_R2.item.ServerItemImpl as ServerItemImpl1_8_R2
import br.com.devsrsouza.kotlinbukkitapi.server.nms.v1_8_R3.nbt.ServerNBTImpl as ServerNBTImpl1_8_R3
import br.com.devsrsouza.kotlinbukkitapi.server.nms.v1_8_R3.player.ServerTabListImpl as ServerTabListImpl1_8_R3
import br.com.devsrsouza.kotlinbukkitapi.server.nms.v1_8_R3.chat.ServerTitleImpl as ServerTitleImpl1_8_R3
import br.com.devsrsouza.kotlinbukkitapi.server.nms.v1_8_R3.chat.ServerChatImpl as ServerChatImpl1_8_R3
import br.com.devsrsouza.kotlinbukkitapi.server.nms.v1_8_R3.item.ServerItemImpl as ServerItemImpl1_8_R3
import br.com.devsrsouza.kotlinbukkitapi.server.nms.v1_9_R1.nbt.ServerNBTImpl as ServerNBTImpl1_9_R1
import br.com.devsrsouza.kotlinbukkitapi.server.nms.v1_9_R1.player.ServerTabListImpl as ServerTabListImpl1_9_R1
import br.com.devsrsouza.kotlinbukkitapi.server.nms.v1_9_R1.chat.ServerTitleImpl as ServerTitleImpl1_9_R1
import br.com.devsrsouza.kotlinbukkitapi.server.nms.v1_9_R1.chat.ServerChatImpl as ServerChatImpl1_9_R1
import br.com.devsrsouza.kotlinbukkitapi.server.nms.v1_9_R1.item.ServerItemImpl as ServerItemImpl1_9_R1
import br.com.devsrsouza.kotlinbukkitapi.server.nms.v1_9_R2.nbt.ServerNBTImpl as ServerNBTImpl1_9_R2
import br.com.devsrsouza.kotlinbukkitapi.server.nms.v1_9_R2.player.ServerTabListImpl as ServerTabListImpl1_9_R2
import br.com.devsrsouza.kotlinbukkitapi.server.nms.v1_9_R2.chat.ServerTitleImpl as ServerTitleImpl1_9_R2
import br.com.devsrsouza.kotlinbukkitapi.server.nms.v1_9_R2.chat.ServerChatImpl as ServerChatImpl1_9_R2
import br.com.devsrsouza.kotlinbukkitapi.server.nms.v1_9_R2.item.ServerItemImpl as ServerItemImpl1_9_R2
import br.com.devsrsouza.kotlinbukkitapi.server.nms.v1_10_R1.chat.ServerTitleImpl as ServerTitleImpl1_10_R1
import br.com.devsrsouza.kotlinbukkitapi.server.nms.v1_10_R1.nbt.ServerNBTImpl as ServerNBTImpl1_10_R1
import br.com.devsrsouza.kotlinbukkitapi.server.nms.v1_10_R1.player.ServerTabListImpl as ServerTabListImpl1_10_R1
import br.com.devsrsouza.kotlinbukkitapi.server.nms.v1_10_R1.item.ServerItemImpl as ServerItemImpl1_10_R1
import br.com.devsrsouza.kotlinbukkitapi.server.nms.v1_11_R1.nbt.ServerNBTImpl as ServerNBTImpl1_11_R1
import br.com.devsrsouza.kotlinbukkitapi.server.nms.v1_11_R1.player.ServerTabListImpl as ServerTabListImpl1_11_R1
import br.com.devsrsouza.kotlinbukkitapi.server.nms.v1_11_R1.item.ServerItemImpl as ServerItemImpl1_11_R1
import br.com.devsrsouza.kotlinbukkitapi.server.nms.v1_12_R1.nbt.ServerNBTImpl as ServerNBTImpl1_12_R1
import br.com.devsrsouza.kotlinbukkitapi.server.nms.v1_12_R1.player.ServerTabListImpl as ServerTabListImpl1_12_R1
import br.com.devsrsouza.kotlinbukkitapi.server.nms.v1_12_R1.item.ServerItemImpl as ServerItemImpl1_12_R1
import br.com.devsrsouza.kotlinbukkitapi.server.nms.v1_13_R1.nbt.ServerNBTImpl as ServerNBTImpl1_13_R1
import br.com.devsrsouza.kotlinbukkitapi.server.nms.v1_13_R1.player.ServerTabListImpl as ServerTabListImpl1_13_R1
import br.com.devsrsouza.kotlinbukkitapi.server.nms.v1_13_R1.item.ServerItemImpl as ServerItemImpl1_13_R1
import br.com.devsrsouza.kotlinbukkitapi.server.nms.v1_13_R2.nbt.ServerNBTImpl as ServerNBTImpl1_13_R2
import br.com.devsrsouza.kotlinbukkitapi.server.nms.v1_13_R2.player.ServerTabListImpl as ServerTabListImpl1_13_R2
import br.com.devsrsouza.kotlinbukkitapi.server.nms.v1_13_R2.item.ServerItemImpl as ServerItemImpl1_13_R2
import br.com.devsrsouza.kotlinbukkitapi.server.nms.v1_14_R1.nbt.ServerNBTImpl as ServerNBTImpl1_14_R1
import br.com.devsrsouza.kotlinbukkitapi.server.nms.v1_14_R1.player.ServerTabListImpl as ServerTabListImpl1_14_R1
import br.com.devsrsouza.kotlinbukkitapi.server.nms.v1_14_R1.item.ServerItemImpl as ServerItemImpl1_14_R1
import br.com.devsrsouza.kotlinbukkitapi.utils.server.ServerImplementation
import br.com.devsrsouza.kotlinbukkitapi.utils.server.apiVersion
import br.com.devsrsouza.kotlinbukkitapi.utils.server.implementation
import org.bukkit.Bukkit
object Server {
private val server = Bukkit.getServer()
private val impl = server.implementation
private val api = server.apiVersion
// chat
object Chat {
val chat: ServerChat by lazy {
if (api.minor >= 10) {
ServerChatImplBukkit
} else {
when (impl) {
is ServerImplementation.BukkitImplementation -> {
when (impl.nms) {
"v1_8_R1" -> ServerChatImpl1_8_R1
"v1_8_R2" -> ServerChatImpl1_8_R2
"v1_8_R3" -> ServerChatImpl1_8_R3
"v1_9_R1" -> ServerChatImpl1_9_R1
"v1_9_R2" -> ServerChatImpl1_9_R2
else -> throw NotImplementedError("${impl.nms} not implemented.")
}
}
is ServerImplementation.Glowstone ->
TODO("Glowstone not implemented yet.")
is ServerImplementation.UnknownImplementation ->
TODO("${impl.name} not implemented yet.")
}
}
}
val title: ServerTitle by lazy {
if (api.minor >= 11) {
ServerTitleImplBukkit
} else {
when (impl) {
is ServerImplementation.BukkitImplementation -> {
when (impl.nms) {
"v1_8_R1" -> ServerTitleImpl1_8_R1
"v1_8_R2" -> ServerTitleImpl1_8_R2
"v1_8_R3" -> ServerTitleImpl1_8_R3
"v1_9_R1" -> ServerTitleImpl1_9_R1
"v1_9_R2" -> ServerTitleImpl1_9_R2
"v1_10_R1" -> ServerTitleImpl1_10_R1
else -> throw NotImplementedError("${impl.nms} not implemented.")
}
}
is ServerImplementation.Glowstone ->
TODO("Glowstone not implemented yet.")
is ServerImplementation.UnknownImplementation ->
TODO("${impl.name} not implemented yet.")
}
}
}
}
// tab list
val tabList: ServerTabList by lazy {
when (impl) {
is ServerImplementation.BukkitImplementation -> {
when (impl.nms) {
"v1_8_R1" -> ServerTabListImpl1_8_R1
"v1_8_R2" -> ServerTabListImpl1_8_R2
"v1_8_R3" -> ServerTabListImpl1_8_R3
"v1_9_R1" -> ServerTabListImpl1_9_R1
"v1_9_R2" -> ServerTabListImpl1_9_R2
"v1_10_R1" -> ServerTabListImpl1_10_R1
"v1_11_R1" -> ServerTabListImpl1_11_R1
"v1_12_R1" -> ServerTabListImpl1_12_R1
"v1_13_R1" -> ServerTabListImpl1_13_R1
"v1_13_R2" -> ServerTabListImpl1_13_R2
"v1_14_R1" -> ServerTabListImpl1_14_R1
else -> throw NotImplementedError("${impl.nms} not implemented.")
}
}
is ServerImplementation.Glowstone ->
TODO("Glowstone not implemented yet.")
is ServerImplementation.UnknownImplementation ->
TODO("${impl.name} not implemented yet.")
}
}
// item
val item: ServerItem by lazy {
when (impl) {
is ServerImplementation.BukkitImplementation -> {
when (impl.nms) {
"v1_8_R1" -> ServerItemImpl1_8_R1
"v1_8_R2" -> ServerItemImpl1_8_R2
"v1_8_R3" -> ServerItemImpl1_8_R3
"v1_9_R1" -> ServerItemImpl1_9_R1
"v1_9_R2" -> ServerItemImpl1_9_R2
"v1_10_R1" -> ServerItemImpl1_10_R1
"v1_11_R1" -> ServerItemImpl1_11_R1
"v1_12_R1" -> ServerItemImpl1_12_R1
"v1_13_R1" -> ServerItemImpl1_13_R1
"v1_13_R2" -> ServerItemImpl1_13_R2
"v1_14_R1" -> ServerItemImpl1_14_R1
else -> throw NotImplementedError("${impl.nms} not implemented.")
}
}
is ServerImplementation.Glowstone ->
TODO("Glowstone not implemented yet.")
is ServerImplementation.UnknownImplementation ->
TODO("${impl.name} not implemented yet.")
}
}
// nbt
val nbt: ServerNBT<*, *> by lazy {
when (impl) {
is ServerImplementation.BukkitImplementation -> {
when (impl.nms) {
"v1_8_R1" -> ServerNBTImpl1_8_R1
"v1_8_R2" -> ServerNBTImpl1_8_R2
"v1_8_R3" -> ServerNBTImpl1_8_R3
"v1_9_R1" -> ServerNBTImpl1_9_R1
"v1_9_R2" -> ServerNBTImpl1_9_R2
"v1_10_R1" -> ServerNBTImpl1_10_R1
"v1_11_R1" -> ServerNBTImpl1_11_R1
"v1_12_R1" -> ServerNBTImpl1_12_R1
"v1_13_R1" -> ServerNBTImpl1_13_R1
"v1_13_R2" -> ServerNBTImpl1_13_R2
"v1_14_R1" -> ServerNBTImpl1_14_R1
else -> throw NotImplementedError("${impl.nms} not implemented.")
}
}
is ServerImplementation.Glowstone ->
TODO("Glowstone not implemented yet.")
is ServerImplementation.UnknownImplementation ->
TODO("${impl.name} not implemented yet.")
}
}
} | 0 | Kotlin | 0 | 1 | 0c0ea64fc553cc3152376e3eaa52a24b409d1754 | 11,248 | KotlinBukkitAPI | MIT License |
app/src/main/java/com/greenart7c3/nostrsigner/service/IntentUtils.kt | greenart7c3 | 671,206,453 | false | null | package com.greenart7c3.nostrsigner.service
import android.content.Intent
import android.net.Uri
import android.provider.Browser
import android.util.Log
import androidx.compose.runtime.mutableStateOf
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.greenart7c3.nostrsigner.LocalPreferences
import com.greenart7c3.nostrsigner.models.Account
import com.greenart7c3.nostrsigner.models.CompressionType
import com.greenart7c3.nostrsigner.models.IntentData
import com.greenart7c3.nostrsigner.models.Permission
import com.greenart7c3.nostrsigner.models.ReturnType
import com.greenart7c3.nostrsigner.models.SignerType
import com.greenart7c3.nostrsigner.models.TimeUtils
import com.greenart7c3.nostrsigner.nostrsigner
import com.greenart7c3.nostrsigner.relays.Client
import com.greenart7c3.nostrsigner.relays.Relay
import com.greenart7c3.nostrsigner.relays.RelayPool
import com.greenart7c3.nostrsigner.service.model.AmberEvent
import com.greenart7c3.nostrsigner.ui.BunkerResponse
import com.greenart7c3.nostrsigner.ui.NotificationType
import com.vitorpamplona.quartz.crypto.KeyPair
import com.vitorpamplona.quartz.encoders.toHexKey
import com.vitorpamplona.quartz.encoders.toNpub
import com.vitorpamplona.quartz.events.Event
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.net.URLDecoder
import java.util.UUID
import java.util.concurrent.ConcurrentHashMap
data class BunkerMetada(
val name: String,
val url: String,
val description: String
)
object IntentUtils {
val bunkerRequests = ConcurrentHashMap<String, BunkerRequest>()
private fun getIntentDataWithoutExtras(data: String, intent: Intent, packageName: String?, route: String?): IntentData {
val localData = URLDecoder.decode(data.replace("nostrsigner:", "").split("?").first().replace("+", "%2b"), "utf-8")
val parameters = data.replace("nostrsigner:", "").split("?").toMutableList()
parameters.removeFirst()
if (parameters.isEmpty() || parameters.toString() == "[]") {
return getIntentDataFromIntent(intent, packageName, route)
}
var type = SignerType.SIGN_EVENT
var pubKey = ""
var compressionType = CompressionType.NONE
var callbackUrl = ""
var returnType = ReturnType.SIGNATURE
parameters.joinToString("?").split("&").forEach {
val params = it.split("=").toMutableList()
val parameter = params.removeFirst()
val parameterData = params.joinToString("=")
if (parameter == "type") {
type = when (parameterData) {
"sign_event" -> SignerType.SIGN_EVENT
"get_public_get" -> SignerType.GET_PUBLIC_KEY
"nip04_encrypt" -> SignerType.NIP04_ENCRYPT
"nip04_decrypt" -> SignerType.NIP04_DECRYPT
"nip44_encrypt" -> SignerType.NIP44_ENCRYPT
"nip44_decrypt" -> SignerType.NIP44_DECRYPT
else -> SignerType.SIGN_EVENT
}
}
if (parameter == "pubkey") {
pubKey = parameterData
}
if (parameter == "compressionType") {
if (parameterData == "gzip") {
compressionType = CompressionType.GZIP
}
}
if (parameter == "callbackUrl") {
callbackUrl = parameterData
}
if (parameter == "returnType") {
if (parameterData == "event") {
returnType = ReturnType.EVENT
}
}
}
return IntentData(
localData,
"",
type,
pubKey,
"",
callbackUrl,
compressionType,
returnType,
listOf(),
"",
mutableStateOf(true),
mutableStateOf(false),
null,
route
)
}
fun getTypeFromBunker(bunkerRequest: BunkerRequest): SignerType {
return when (bunkerRequest.method) {
"connect" -> SignerType.CONNECT
"sign_event" -> SignerType.SIGN_EVENT
"get_public_get" -> SignerType.GET_PUBLIC_KEY
"nip04_encrypt" -> SignerType.NIP04_ENCRYPT
"nip04_decrypt" -> SignerType.NIP04_DECRYPT
"nip44_encrypt" -> SignerType.NIP44_ENCRYPT
"nip44_decrypt" -> SignerType.NIP44_DECRYPT
else -> SignerType.SIGN_EVENT
}
}
fun getDataFromBunker(bunkerRequest: BunkerRequest): String {
return when (bunkerRequest.method) {
"connect" -> "ack"
"sign_event" -> {
val amberEvent = AmberEvent.fromJson(bunkerRequest.params.first())
AmberEvent.toEvent(amberEvent).toJson()
}
"nip04_encrypt", "nip04_decrypt", "nip44_encrypt", "nip44_decrypt" -> bunkerRequest.params.getOrElse(1) { "" }
else -> ""
}
}
@OptIn(DelicateCoroutinesApi::class)
fun sendBunkerResponse(
account: Account,
localKey: String,
bunkerResponse: BunkerResponse,
relays: List<Relay>,
onLoading: (Boolean) -> Unit,
onSign: (() -> Unit)? = null,
onDone: () -> Unit
) {
account.signer.nip04Encrypt(
ObjectMapper().writeValueAsString(bunkerResponse),
localKey
) { encryptedContent ->
account.signer.sign<Event>(
TimeUtils.now(),
24133,
arrayOf(arrayOf("p", localKey)),
encryptedContent
) {
if (onSign != null) {
onSign()
}
GlobalScope.launch(Dispatchers.IO) {
if (RelayPool.getAll().isEmpty()) {
val database = nostrsigner.instance.getDatabase(account.keyPair.pubKey.toNpub())
val savedRelays = mutableListOf<Relay>()
database.applicationDao().getAllApplications().forEach {
it.application.relays.forEach { url ->
if (url.isNotBlank()) {
if (!savedRelays.any { it.url == url }) {
savedRelays.add(Relay(url))
}
}
}
}
Client.addRelays(relays.toTypedArray())
if (LocalPreferences.getNotificationType() == NotificationType.DIRECT) {
Client.reconnect(relays.toTypedArray())
}
delay(1000)
}
Client.send(it, relayList = relays, onDone = onDone, onLoading = onLoading)
}
}
}
}
private fun getIntentDataFromBunkerRequest(intent: Intent, bunkerRequest: BunkerRequest, route: String?): IntentData {
val type = getTypeFromBunker(bunkerRequest)
val data = getDataFromBunker(bunkerRequest)
val pubKey = if (bunkerRequest.method.endsWith("encrypt") || bunkerRequest.method.endsWith("decrypt")) {
bunkerRequest.params.first()
} else {
""
}
val id = bunkerRequest.id
val permissions = mutableListOf<Permission>()
if (type == SignerType.CONNECT && bunkerRequest.params.size > 2) {
val split = bunkerRequest.params[2].split(",")
split.forEach {
val split2 = it.split(":")
val permissionType = split2.first()
val kind = try {
split2[1].toInt()
} catch (_: Exception) {
null
}
permissions.add(
Permission(
permissionType,
kind
)
)
}
}
return IntentData(
data,
"",
type,
pubKey,
id,
intent.extras?.getString("callbackUrl"),
CompressionType.NONE,
ReturnType.EVENT,
permissions,
intent.extras?.getString("current_user") ?: "",
mutableStateOf(true),
mutableStateOf(false),
bunkerRequest,
route
)
}
private fun getIntentDataFromIntent(intent: Intent, packageName: String?, route: String?): IntentData {
val type = when (intent.extras?.getString("type")) {
"sign_event" -> SignerType.SIGN_EVENT
"nip04_encrypt" -> SignerType.NIP04_ENCRYPT
"nip04_decrypt" -> SignerType.NIP04_DECRYPT
"nip44_decrypt" -> SignerType.NIP44_DECRYPT
"nip44_encrypt" -> SignerType.NIP44_ENCRYPT
"get_public_key" -> SignerType.GET_PUBLIC_KEY
"decrypt_zap_event" -> SignerType.DECRYPT_ZAP_EVENT
else -> SignerType.SIGN_EVENT
}
val data = try {
if (packageName == null) {
URLDecoder.decode(intent.data?.toString()?.replace("+", "%2b") ?: "", "utf-8").replace("nostrsigner:", "")
} else {
intent.data?.toString()?.replace("nostrsigner:", "") ?: ""
}
} catch (e: Exception) {
intent.data?.toString()?.replace("nostrsigner:", "") ?: ""
}
val callbackUrl = intent.extras?.getString("callbackUrl") ?: ""
val name = if (callbackUrl.isNotBlank()) Uri.parse(callbackUrl).host ?: "" else ""
val pubKey = intent.extras?.getString("pubKey") ?: ""
val id = intent.extras?.getString("id") ?: ""
val compressionType = if (intent.extras?.getString("compression") == "gzip") CompressionType.GZIP else CompressionType.NONE
val returnType = if (intent.extras?.getString("returnType") == "event") ReturnType.EVENT else ReturnType.SIGNATURE
val listType = object : TypeToken<List<Permission>>() {}.type
val permissions = Gson().fromJson<List<Permission>?>(intent.extras?.getString("permissions"), listType)
permissions?.forEach {
it.checked = true
}
return IntentData(
data,
name,
type,
pubKey,
id,
intent.extras?.getString("callbackUrl"),
compressionType,
returnType,
permissions,
intent.extras?.getString("current_user") ?: "",
mutableStateOf(true),
mutableStateOf(false),
null,
route
)
}
private fun metaDataFromJson(json: String): BunkerMetada {
val objectMapper = jacksonObjectMapper()
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
return objectMapper.readValue(json, BunkerMetada::class.java)
}
private fun getIntentFromNostrConnect(intent: Intent, route: String?): IntentData? {
try {
val data = intent.dataString.toString().replace("nostrconnect://", "")
val split = data.split("?")
val relays: MutableList<String> = mutableListOf()
var name = ""
val pubKey = split.first()
val parsedData = URLDecoder.decode(split.drop(1).joinToString { it }.replace("+", "%2b"), "utf-8")
val splitParsedData = parsedData.split("&")
splitParsedData.forEach {
val internalSplit = it.split("=")
if (internalSplit.first() == "relay") {
relays.add(internalSplit[1])
}
if (internalSplit.first() == "name") {
name = internalSplit[1]
}
if (internalSplit.first() == "metadata") {
val bunkerMetada = metaDataFromJson(internalSplit[1])
name = bunkerMetada.name
}
}
return IntentData(
"ack",
name,
SignerType.CONNECT,
pubKey,
"",
null,
CompressionType.NONE,
ReturnType.EVENT,
listOf(),
"",
mutableStateOf(true),
mutableStateOf(false),
BunkerRequest(
UUID.randomUUID().toString().substring(0, 4),
"connect",
arrayOf(pubKey),
pubKey,
relays,
""
),
route
)
} catch (e: Exception) {
Log.e("nostrconnect", e.message, e)
return null
}
}
fun getIntentData(intent: Intent, packageName: String?, route: String?): IntentData? {
if (intent.data == null) {
return null
}
val bunkerRequest = if (intent.getStringExtra("bunker") != null) {
BunkerRequest.mapper.readValue(
intent.getStringExtra("bunker"),
BunkerRequest::class.java
)
} else {
null
}
return if (intent.dataString?.startsWith("nostrconnect:") == true) {
return getIntentFromNostrConnect(intent, route)
} else if (bunkerRequest != null) {
getIntentDataFromBunkerRequest(intent, bunkerRequest, route)
} else if (intent.extras?.getString(Browser.EXTRA_APPLICATION_ID) == null) {
getIntentDataFromIntent(intent, packageName, route)
} else {
getIntentDataWithoutExtras(intent.data?.toString() ?: "", intent, packageName, route)
}
}
fun getIntent(data: String, keyPair: KeyPair): Event {
val event = AmberEvent.fromJson(data)
if (event.pubKey.isEmpty()) {
event.pubKey = keyPair.pubKey.toHexKey()
}
if (event.id.isEmpty()) {
event.id = Event.generateId(
event.pubKey,
event.createdAt,
event.kind,
event.tags,
event.content
).toHexKey()
}
return AmberEvent.toEvent(event)
}
}
| 7 | null | 3 | 75 | ec478e65bf7801f904b7490c592f9b8669b1da40 | 14,715 | Amber | MIT License |
grpc-kotlin-test/src/test/kotlin/io/rouz/greeter/ExceptionPropagationTest.kt | wfhartford | 149,170,017 | true | {"Kotlin": 15004, "HTML": 12722, "Java": 10724} | /*-
* -\-\-
* grpc-kotlin-test
* --
* Copyright (C) 2016 - 2018 rouz.io
* --
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* -/-/-
*/
package io.rouz.greeter
import io.grpc.Status
import io.grpc.StatusRuntimeException
import kotlinx.coroutines.experimental.CoroutineExceptionHandler
import kotlinx.coroutines.experimental.Dispatchers
import kotlinx.coroutines.experimental.channels.ReceiveChannel
import kotlinx.coroutines.experimental.channels.produce
import kotlinx.coroutines.experimental.runBlocking
import org.junit.Rule
import org.junit.Test
import org.junit.rules.ExpectedException
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
class ExceptionPropagationTest : GrpcTestBase() {
@Rule
@JvmField
val expect = ExpectedException.none()
@Test
fun unaryStatus() {
val stub = startServer(StatusThrowingGreeter())
expect.expect(StatusRuntimeException::class.java)
expect.expectMessage("NOT_FOUND: neh")
runBlocking {
stub.greet(req("joe"))
}
}
@Test
fun serverStreamingStatus() {
val stub = startServer(StatusThrowingGreeter())
expect.expect(StatusRuntimeException::class.java)
expect.expectMessage("NOT_FOUND: neh")
runBlocking {
stub.greetServerStream(req("joe")).receive()
}
}
@Test
fun clientStreamingStatus() {
val stub = startServer(StatusThrowingGreeter())
expect.expect(StatusRuntimeException::class.java)
expect.expectMessage("NOT_FOUND: neh")
runBlocking {
stub.greetClientStream().await()
}
}
@Test
fun bidirectionalStatus() {
val stub = startServer(StatusThrowingGreeter())
expect.expect(StatusRuntimeException::class.java)
expect.expectMessage("NOT_FOUND: neh")
runBlocking {
stub.greetBidirectional().receive()
}
}
@Test
fun unaryException() {
val stub = startServer(GenericThrowingGreeter())
expect.expect(StatusRuntimeException::class.java)
expect.expectMessage("UNKNOWN")
runBlocking {
stub.greet(req("joe"))
}
}
@Test
fun serverStreamingException() {
val stub = startServer(GenericThrowingGreeter())
expect.expect(StatusRuntimeException::class.java)
expect.expectMessage("UNKNOWN")
runBlocking {
stub.greetServerStream(req("joe")).receive()
}
}
@Test
fun clientStreamingException() {
val stub = startServer(GenericThrowingGreeter())
expect.expect(StatusRuntimeException::class.java)
expect.expectMessage("UNKNOWN")
runBlocking {
stub.greetClientStream().await()
}
}
@Test
fun bidirectionalException() {
val stub = startServer(GenericThrowingGreeter())
expect.expect(StatusRuntimeException::class.java)
expect.expectMessage("UNKNOWN")
runBlocking {
stub.greetBidirectional().receive()
}
}
private class StatusThrowingGreeter : GreeterGrpcKt.GreeterImplBase() {
override suspend fun greet(request: GreetRequest): GreetReply {
throw notFound()
}
override suspend fun greetServerStream(request: GreetRequest) = produce<GreetReply> {
throw notFound()
}
override suspend fun greetClientStream(requestChannel: ReceiveChannel<GreetRequest>): GreetReply {
throw notFound()
}
override suspend fun greetBidirectional(requestChannel: ReceiveChannel<GreetRequest>) = produce<GreetReply> {
throw notFound()
}
private fun notFound(): StatusRuntimeException {
return Status.NOT_FOUND.withDescription("neh").asRuntimeException()
}
}
private class GenericThrowingGreeter : GreeterGrpcKt.GreeterImplBase(
Dispatchers.Default + CoroutineExceptionHandler { _, _ -> /* shh */ }
) {
override suspend fun greet(request: GreetRequest): GreetReply {
throw broke()
}
override suspend fun greetServerStream(request: GreetRequest) = produce<GreetReply> {
throw broke()
}
override suspend fun greetClientStream(requestChannel: ReceiveChannel<GreetRequest>): GreetReply {
throw broke()
}
override suspend fun greetBidirectional(requestChannel: ReceiveChannel<GreetRequest>) = produce<GreetReply> {
throw broke()
}
private fun broke(): Exception {
return Exception("my app broke")
}
}
}
| 0 | Kotlin | 0 | 0 | 6207f66b7331169180542a29f647246d780abc91 | 5,206 | grpc-kotlin-1 | Apache License 2.0 |
app/src/main/java/com/radityalabs/android/corona/di/module/DispatcherModule.kt | radityagumay | 246,593,536 | false | null | package com.radityalabs.android.corona.di.module
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.components.ApplicationComponent
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import javax.inject.Named
import javax.inject.Singleton
internal const val IO = "DISPATCHER_IO"
internal const val MAIN = "DISPATCHER_MAIN"
internal const val DEFAULT = "DISPATCHER_DEFAULT"
@Module
@InstallIn(ApplicationComponent::class)
internal object DispatcherModule {
@Provides
@Singleton
@Named(IO)
internal fun providesIODispatcher(): CoroutineDispatcher = Dispatchers.IO
@Provides
@Singleton
@Named(MAIN)
internal fun providesMainDispatcher(): CoroutineDispatcher = Dispatchers.Main
@Provides
@Singleton
@Named(DEFAULT)
internal fun providesDefaultDispatcher(): CoroutineDispatcher = Dispatchers.Default
}
| 6 | Kotlin | 8 | 22 | 9a08321d7f1c71d156e5ee4937393acc4f891aa9 | 932 | COVID-19-ANDROID | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.