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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
z2-kotlin-plugin/src/hu/simplexion/z2/kotlin/services/ir/impl/NewInstance.kt | spxbhuhb | 788,711,010 | false | {"Kotlin": 884891, "CSS": 20110, "Java": 16501, "HTML": 1364, "JavaScript": 975} | /*
* Copyright ยฉ 2022-2023, Simplexion, Hungary and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package hu.simplexion.z2.kotlin.services.ir.impl
import hu.simplexion.z2.kotlin.services.Strings
import hu.simplexion.z2.kotlin.services.ir.ServicesPluginContext
import org.jetbrains.kotlin.backend.common.lower.DeclarationIrBuilder
import org.jetbrains.kotlin.ir.builders.declarations.addValueParameter
import org.jetbrains.kotlin.ir.builders.irBlockBody
import org.jetbrains.kotlin.ir.builders.irReturn
import org.jetbrains.kotlin.ir.declarations.IrSimpleFunction
import org.jetbrains.kotlin.ir.expressions.impl.IrConstructorCallImpl
import org.jetbrains.kotlin.ir.types.makeNullable
import org.jetbrains.kotlin.ir.util.SYNTHETIC_OFFSET
import org.jetbrains.kotlin.ir.util.defaultType
class NewInstance(
pluginContext: ServicesPluginContext,
implClassTransform: ImplClassTransform,
) : AbstractFun(
pluginContext,
implClassTransform,
Strings.NEW_INSTANCE,
pluginContext.serviceImplNewInstance
) {
override fun IrSimpleFunction.addParameters() {
addValueParameter("serviceContext", pluginContext.serviceContextType.makeNullable())
}
override fun IrSimpleFunction.buildBody() {
body = DeclarationIrBuilder(irContext, this.symbol).irBlockBody {
+ irReturn(
IrConstructorCallImpl(
SYNTHETIC_OFFSET, SYNTHETIC_OFFSET,
transformedClass.defaultType,
implClassTransform.constructor.symbol,
0, 0, 1
).also {
it.putValueArgument(0, irGet(valueParameters.first()))
}
)
}
}
} | 0 | Kotlin | 0 | 0 | 58338f60edcfcc839ad4d08cbb6d70cdea48554d | 1,739 | z2 | Apache License 2.0 |
app/src/main/java/com/example/bmta/repository/NoteRepository.kt | returnT0 | 598,981,598 | false | null | package com.example.bmta.repository
import com.example.bmta.model.Note
import com.example.bmta.room.NoteDao
class NoteRepository(private val noteDao: NoteDao) {
suspend fun getNote() = noteDao.getNote()
suspend fun insertNote(note : Note) = noteDao.insertNote(note)
suspend fun deleteNote(ids : ArrayList<Note>) {
val list : ArrayList<Int> = ArrayList()
ids.forEach { list.add(it.id) }
noteDao.deleteNote(list)
}
} | 0 | Kotlin | 0 | 0 | 6300886c6ba9914bc0e683009d0865093ee2529a | 456 | BMTA-project | MIT License |
app/src/main/java/com/menesdurak/appterncasestudy/data/local/FavoriteTrackRepository.kt | menesdurak | 637,885,226 | false | null | package com.menesdurak.appterncasestudy.data.local
import com.menesdurak.appterncasestudy.data.model.FavoriteTrack
import javax.inject.Inject
class FavoriteTrackRepository @Inject constructor(private val favoriteTrackDao: FavoriteTrackDao) {
suspend fun addFavoriteTrack(favoriteTrack: FavoriteTrack) {
favoriteTrackDao.addFavoriteTrack(favoriteTrack)
}
suspend fun deleteFavoriteTrackWithId(favoriteTrackId: Long) {
favoriteTrackDao.deleteFavoriteTrackWithId(favoriteTrackId)
}
suspend fun getAllFavoriteTracks(): List<FavoriteTrack> =
favoriteTrackDao.getAllFavoriteTracks()
} | 0 | Kotlin | 0 | 0 | 8fde125e5f2d6bd0bff3254d12cbda83b46d44f8 | 627 | Deezer | Apache License 2.0 |
app/src/main/java/com/douglasalipio/luasforecasts/data/AppDataSource.kt | douglasalipio | 191,641,687 | false | null | package com.douglasalipio.luasforecasts.data
import com.douglasalipio.luasforecasts.data.ForecastsResponse
import io.reactivex.Flowable
interface AppDataSource {
fun requestData(stop : String): Flowable<ForecastsResponse>
} | 0 | Kotlin | 0 | 0 | 90629f544d2e06f524a6a9cc8bbc6edfff0ee745 | 231 | retail-in-motion-code-challenge | MIT License |
app/src/main/java/com/myth/ticketmasterapp/presentation/di/RepositoryModule.kt | MichaelGift | 634,539,469 | false | {"Kotlin": 93804} | package com.myth.ticketmasterapp.presentation.di
import com.myth.ticketmasterapp.data.EventRepositoryImplementation
import com.myth.ticketmasterapp.data.datasource.EventCacheDataSource
import com.myth.ticketmasterapp.data.datasource.EventLocalDataSource
import com.myth.ticketmasterapp.data.datasource.EventRemoteDataSource
import com.myth.ticketmasterapp.data.datasource.SpotifyRemoteDataSource
import com.myth.ticketmasterapp.domain.repository.EventRepository
import dagger.Module
import dagger.Provides
import javax.inject.Singleton
@Module
class RepositoryModule {
@Singleton
@Provides
fun providesEventRepository(
eventRemoteDataSource: EventRemoteDataSource,
eventLocalDataSource: EventLocalDataSource,
eventCacheDataSource: EventCacheDataSource,
spotifyRemoteDataSource: SpotifyRemoteDataSource
): EventRepository {
return EventRepositoryImplementation(
eventRemoteDataSource,
eventLocalDataSource,
eventCacheDataSource,
spotifyRemoteDataSource
)
}
} | 0 | Kotlin | 0 | 0 | 16c9662777df64db41da7ed554e0312832363c68 | 1,075 | Event-Finder-App | MIT License |
Android/app/src/main/java/xyz/janficko/apphub/model/Job.kt | JanFicko | 174,291,580 | false | {"CSS": 266964, "Kotlin": 72364, "JavaScript": 50798, "TypeScript": 36319, "HTML": 28239, "Swift": 13023, "Ruby": 340} | package xyz.janficko.apphub.model
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
import java.util.*
data class Job(
@SerializedName("_id")
@Expose
val _id : String,
@SerializedName("title")
@Expose
val title : String,
@SerializedName("changeLog")
@Expose
val changeLog : String? = null,
@SerializedName("jobId")
@Expose
val jobId : Int,
@SerializedName("fullDisplayName")
@Expose
val fullDisplayName : String,
@SerializedName("name")
@Expose
var name : String,
@SerializedName("finishTime")
@Expose
val finishTime : Date
) | 33 | CSS | 0 | 0 | 9218b848098b1d7e0e7f839f31ec738bc0454ca9 | 653 | app-hub | MIT License |
areminder/src/main/java/ir/awlrhm/areminder/view/reminder/AddReminderFragment.kt | Ali-Kazemii | 361,654,444 | false | null | package ir.awlrhm.areminder.view.reminder
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.lifecycle.Lifecycle
import com.google.android.material.chip.Chip
import ir.awlrhm.areminder.R
import ir.awlrhm.areminder.data.network.model.request.*
import ir.awlrhm.areminder.data.network.model.response.UserActivityInviteResponse
import ir.awlrhm.areminder.data.network.model.response.UserActivityResponse
import ir.awlrhm.areminder.utils.customerJson
import ir.awlrhm.areminder.utils.initialViewModel
import ir.awlrhm.areminder.utils.userActivityInviteJson
import ir.awlrhm.areminder.view.base.BaseFragment
import ir.awlrhm.modules.enums.MessageStatus
import ir.awlrhm.modules.extentions.*
import ir.awlrhm.modules.models.ItemModel
import ir.awlrhm.modules.view.ActionDialog
import ir.awlrhm.modules.view.ChooseDialog
import kotlinx.android.synthetic.main.contain_add_reminder.*
import kotlinx.android.synthetic.main.fragment_add_reminder.*
internal class AddReminderFragment(
private val callback: () -> Unit
) : BaseFragment() {
constructor(
model: UserActivityResponse.Result? = null,
callback: () -> Unit
) : this(callback) {
this.model = model
}
private lateinit var viewModel: ReminderViewModel
private var model: UserActivityResponse.Result? = null
private var listReminderType: MutableList<ItemModel> = mutableListOf()
private var listMeetingLocation: MutableList<ItemModel> = mutableListOf()
private var listCustomer: MutableList<ItemModel> = mutableListOf()
private var reminderTypeId: Long = -1
private var meetingLocationId: Long = -1
private var _uaId: Long = 0
private var addPerson = false
private var isOnEditMode: Boolean = false
override fun setup() {
val activity = activity ?: return
viewModel = activity.initialViewModel{
(activity as ReminderActivity).handleError(it)
}
txtStartDate.text = viewModel.currentDate
txtEndDate.text = viewModel.currentDate
txtReminderDate.text = viewModel.currentDate
txtStartTime.text = viewModel.currentTime
txtEndTime.text = viewModel.currentTime
txtReminderTime.text = viewModel.currentTime
getReminderTypeList()
getLocationList()
getCustomerList()
model?.let { model ->
isOnEditMode = true
_uaId = model.uaId ?: 0
viewModel.getUserActivityInviteList(
UserActivityInviteRequest().also { request ->
request.uaiId = model.uaId ?: 0
request.userId = viewModel.userId
request.typeOperation = 101
request.jsonParameters = userActivityInviteJson(model.uaId ?: 0)
}
)
txtStartDate.text = model.startDate
txtStartTime.text = model.startTime
txtEndDate.text = model.endDate
txtEndTime.text = model.endTime
txtReminderDate.text = model.alarmDate
txtReminderTime.text = model.alarmTime
txtLocation.text = model.meetingLocation
txtEventType.text = model.activityType
edtReminderTitle.setText(model.title ?: "")
reminderTypeId = model.activityId ?: 0
meetingLocationId = model.meetingLocationId ?: 0
btnDelete.isVisible = true
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_add_reminder, container, false)
}
override fun handleOnClickListeners() {
val activity = activity ?: return
btnClose.setOnClickListener { activity.onBackPressed() }
btnDelete.setOnClickListener {
ActionDialog.Builder()
.setTitle(getString(R.string.warning))
.setDescription(getString(R.string.are_you_sure_delete))
.setPositive(getString(R.string.ok)) {
showLoading(true)
viewModel.deleteUserActivity(
DeleteUserRequest().also { request->
request.uaId = model?.uaId
request.financialYearId = viewModel.financialYear
request.userId = viewModel.userId
}
)
}
.setNegative(getString(R.string.no)) {}
.build()
.show(activity.supportFragmentManager, ActionDialog.TAG)
}
btnSave.setOnClickListener {
if (isValid) {
showLoading(true)
if (isOnEditMode)
viewModel.updateUserActivity(request)
else
viewModel.insertUserActivity(request)
} else {
showLoading(false)
activity.hideKeyboard(edtReminderTitle)
activity.yToast(
getString(R.string.fill_all_blanks),
MessageStatus.ERROR
)
if (!addPerson)
txtAddPeople.isVisible = true
if (edtReminderTitle.text.toString().isEmpty())
edtReminderTitle.error = getString(R.string.fill_event_title)
if (reminderTypeId == -1L) {
txtEventType.setTextColor(ContextCompat.getColor(activity, R.color.red_500))
txtEventType.text = getString(R.string.choose_event_type)
}
if (meetingLocationId == -1L) {
txtLocation.setTextColor(ContextCompat.getColor(activity, R.color.red_500))
txtLocation.text = getString(R.string.choose_location)
}
}
}
txtStartDate.setOnClickListener {
activity.showDateDialog {
txtStartDate.text = formatDate(it)
}
}
txtEndDate.setOnClickListener {
activity.showDateDialog {
txtEndDate.text = formatDate(it)
}
}
txtReminderDate.setOnClickListener {
activity.showDateDialog {
txtReminderDate.text = formatDate(it)
}
}
txtStartTime.setOnClickListener {
activity.showTimePickerDialog {
txtStartTime.text = formatTime(it)
}
}
txtEndTime.setOnClickListener {
activity.showTimePickerDialog {
txtEndTime.text = formatTime(it)
}
}
txtReminderTime.setOnClickListener {
activity.showTimePickerDialog {
txtReminderTime.text = formatTime(it)
}
}
layoutLocation.setOnClickListener {
getLocationList()
}
layoutEventType.setOnClickListener {
getReminderTypeList()
}
btnAddPeople.setOnClickListener {
getCustomerList()
}
}
private val request: PostUserActivityRequest
get() {
return PostUserActivityRequest().also { request ->
request.uaId = _uaId
request.activityTypeId = reminderTypeId
request.title = edtReminderTitle.text.toString()
request.startDate = txtStartDate.text.toString()
request.endDate = txtEndDate.text.toString()
request.startTime = txtStartTime.text.toString()
request.endTime = txtEndTime.text.toString()
request.locationId = meetingLocationId
request.alarmDate = txtReminderDate.text.toString()
request.alarmTime = txtReminderTime.text.toString()
request.financialYearId = viewModel.financialYear
request.userId = viewModel.userId
request.registerDate = viewModel.currentDate
request.utt = convertUTTModelToJson(uttList)
}
}
private val uttList: MutableList<UTTUserActivity>
get() {
val list = mutableListOf<UTTUserActivity>()
for (i in 1 until chipGroup.childCount)
list.add(
UTTUserActivity().also { request ->
request.customerId = chipGroup.getChildAt(i).tag as Long
request.financialYearId = viewModel.financialYear
}
)
return list
}
private fun showLoading(visible: Boolean) {
loading.isVisible = visible
}
override fun handleObservers() {
val activity = activity ?: return
viewModel.listReminderType.observe(viewLifecycleOwner, { response ->
if (viewLifecycleOwner.lifecycle.currentState == Lifecycle.State.RESUMED) {
listReminderType = mutableListOf<ItemModel>().apply {
response.result?.forEachIndexed { index, result ->
add(
index,
ItemModel(
result.baseId ?: 0,
result.title ?: ""
)
)
}
}
}
})
viewModel.listMeetingLocationResponse.observe(viewLifecycleOwner, { response ->
if (viewLifecycleOwner.lifecycle.currentState == Lifecycle.State.RESUMED) {
showLoading(false)
listMeetingLocation = mutableListOf<ItemModel>().apply {
response.result?.forEachIndexed { index, result ->
add(
index,
ItemModel(
result.mlId ?: 0,
result.title ?: ""
)
)
}
}
}
})
viewModel.listCustomerResponse.observe(viewLifecycleOwner, { response ->
if (viewLifecycleOwner.lifecycle.currentState == Lifecycle.State.RESUMED) {
listCustomer = mutableListOf<ItemModel>().apply {
response.result?.forEachIndexed { index, result ->
add(
index,
ItemModel(
result.valueMember?.toLong() ?: 0,
result.textMember ?: ""
)
)
}
}
}
})
viewModel.listUserActivityInvite.observe(viewLifecycleOwner, { response ->
if (viewLifecycleOwner.lifecycle.currentState == Lifecycle.State.RESUMED) {
response.result?.let {
it.forEach { item ->
initInviteCustomer(item)
}
}
}
})
viewModel.addSuccessful.observe(viewLifecycleOwner, { response ->
showLoading(false)
if (viewLifecycleOwner.lifecycle.currentState == Lifecycle.State.RESUMED) {
response.result?.let {
if (it != 0L) {
activity.successOperation(response.message)
activity.onBackPressed()
} else
activity.showError(response.message)
}
}
})
viewModel.responseId.observe(viewLifecycleOwner, { response ->
if (viewLifecycleOwner.lifecycle.currentState == Lifecycle.State.RESUMED) {
response.result?.let {
if (it != 0L) {
activity.successOperation(response.message)
callback.invoke()
}else
activity.failureOperation(response.message)
}?: kotlin.run {
activity.failureOperation(response.message)
}
}
})
}
private fun getLocationList() {
if (listMeetingLocation.size > 0)
showLocationList()
else
viewModel.getMeetingLocationList(
MeetingLocationRequest().also { request ->
request.userId = viewModel.userId
request.typeOperation = 15
}
)
}
private fun showLocationList() {
val activity = activity ?: return
if (listMeetingLocation.size > 0)
ChooseDialog(listMeetingLocation) {
meetingLocationId = it.id
txtLocation.setTextColor(ContextCompat.getColor(activity, R.color.black))
txtLocation.text = it.title
}.show(activity.supportFragmentManager, ChooseDialog.TAG)
}
private fun getCustomerList() {
if (listCustomer.size > 0)
showCustomerList()
else
viewModel.getCustomerList(
CustomerListRequest().also { request ->
request.userId = viewModel.userId
request.typeOperation = 20
request.jsonParameters = customerJson("")
}
)
}
private fun showCustomerList() {
val activity = activity ?: return
if (listCustomer.size > 0)
ChooseDialog(listCustomer) {
addCustomer(it)
}.show(activity.supportFragmentManager, ChooseDialog.TAG)
}
private fun addCustomer(model: ItemModel) {
val activity = activity ?: return
val view =
LayoutInflater.from(activity)
.inflate(R.layout.awlrhm_item_chip, chipGroup, false) as Chip
view.text = model.title
view.tag = model.id
view.isCheckable = false
view.setOnClickListener {
chipGroup.removeViewAt(chipGroup.indexOfChild(view))
}
txtAddPeople.isVisible = false
addPerson = true
chipGroup.addView(view)
}
private fun initInviteCustomer(model: UserActivityInviteResponse.Result) {
val activity = activity ?: return
val view =
LayoutInflater.from(activity)
.inflate(R.layout.awlrhm_item_chip, chipGroup, false) as Chip
view.text = model.name
view.tag = model.customerId
view.isCheckable = false
view.setOnClickListener {
chipGroup.removeViewAt(chipGroup.indexOfChild(view))
}
addPerson = true
chipGroup.addView(view)
}
private fun getReminderTypeList() {
if (listReminderType.size > 0)
showReminderTypeList()
else
viewModel.getReminderType(
ReminderTypeRequest().also { request ->
request.userId = viewModel.userId
request.typeOperation = 16
}
)
}
private fun showReminderTypeList() {
val activity = activity ?: return
if (listReminderType.size > 0)
ChooseDialog(listReminderType) {
reminderTypeId = it.id
txtEventType.setTextColor(ContextCompat.getColor(activity, R.color.black))
txtEventType.text = it.title
}.show(activity.supportFragmentManager, ChooseDialog.TAG)
}
private val isValid: Boolean
get() {
return reminderTypeId != -1L
&& meetingLocationId != -1L
&& edtReminderTitle.text.toString().isNotEmpty()
&& addPerson
}
override fun handleError() {
val activity = activity ?: return
viewModel.error.observe(viewLifecycleOwner, {
activity.showError(it.message)
})
viewModel.addFailure.observe(viewLifecycleOwner, {
if (viewLifecycleOwner.lifecycle.currentState == Lifecycle.State.RESUMED) {
showLoading(false)
activity.showError(it.message)
}
})
}
companion object {
val TAG = "automation: ${AddReminderFragment::class.java.simpleName}"
}
} | 0 | null | 0 | 1 | 7191e0269308aee9cc7ed754c3d676ea8fe075f9 | 16,463 | AReminder | MIT License |
FluentUI.Demo/src/main/java/com/microsoft/fluentuidemo/V2DesignTokensActivity.kt | microsoft | 257,221,908 | false | null | package com.microsoft.fluentuidemo
import android.os.Bundle
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import com.microsoft.fluentui.theme.FluentTheme
import com.microsoft.fluentui.theme.token.FluentAliasTokens
import com.microsoft.fluentui.theme.token.FluentColor
import com.microsoft.fluentui.theme.token.FluentGlobalTokens
import com.microsoft.fluentui.theme.token.FluentGlobalTokens.cornerRadius
import com.microsoft.fluentui.theme.token.FluentGlobalTokens.elevation
import com.microsoft.fluentui.theme.token.FluentGlobalTokens.fontSize
import com.microsoft.fluentui.theme.token.FluentGlobalTokens.fontWeight
import com.microsoft.fluentui.theme.token.FluentGlobalTokens.iconSize
import com.microsoft.fluentui.theme.token.FluentGlobalTokens.lineHeight
import com.microsoft.fluentui.theme.token.FluentGlobalTokens.neutralColor
import com.microsoft.fluentui.theme.token.FluentGlobalTokens.size
import com.microsoft.fluentui.theme.token.FluentGlobalTokens.strokeWidth
import com.microsoft.fluentui.theme.token.Icon
import com.microsoft.fluentui.theme.token.TokenSet
import com.microsoft.fluentui.theme.token.controlTokens.BasicCardInfo
import com.microsoft.fluentui.theme.token.controlTokens.BasicCardTokens
import com.microsoft.fluentui.theme.token.controlTokens.CardType
import com.microsoft.fluentui.tokenized.controls.BasicCard
import com.microsoft.fluentui.tokenized.controls.Label
import com.microsoft.fluentui.tokenized.listitem.ChevronOrientation
import com.microsoft.fluentui.tokenized.listitem.ListItem
import com.microsoft.fluentui.tokenized.segmentedcontrols.PillMetaData
import com.microsoft.fluentui.tokenized.segmentedcontrols.PillTabs
enum class Tokens {
GlobalTokens,
AliasTokens
}
class V2DesignTokensActivity : V2DemoActivity() {
init {
setupActivity(this)
}
override val designTokensUrl =
"https://github.com/microsoft/fluentui-android/wiki/Design-Tokens#overview"
override val globalTokensUrl =
"https://github.com/microsoft/fluentui-android/wiki/Design-Tokens#global-tokens"
override val aliasTokensUrl =
"https://github.com/microsoft/fluentui-android/wiki/Design-Tokens#alias-token"
override val controlTokensUrl =
"https://github.com/microsoft/fluentui-android/wiki/Design-Tokens#control-token"
private fun previewShadowToken(selectedToken: FluentGlobalTokens.ShadowTokens): BasicCardTokens {
return object : BasicCardTokens() {
@Composable
override fun elevation(basicCardInfo: BasicCardInfo): Dp {
return when (basicCardInfo.cardType) {
CardType.Elevated -> elevation(selectedToken)
CardType.Outlined -> 0.dp
}
}
}
}
private fun previewCornerRadiusToken(selectedToken: FluentGlobalTokens.CornerRadiusTokens): BasicCardTokens {
return object : BasicCardTokens() {
@Composable
override fun cornerRadius(basicCardInfo: BasicCardInfo): Dp {
return cornerRadius(selectedToken)
}
}
}
private fun previewStrokeWidthToken(selectedToken: FluentGlobalTokens.StrokeWidthTokens): BasicCardTokens {
return object : BasicCardTokens() {
@Composable
override fun borderStrokeWidth(basicCardInfo: BasicCardInfo): Dp {
return strokeWidth(selectedToken)
}
}
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun PreviewToken(tokenName: Int, tokensList: Array<out Enum<*>>) {
val tabsList = mutableListOf<PillMetaData>()
var selectedTokenIndex by remember { mutableStateOf(0) }
tokensList.forEach {
tabsList.add(
PillMetaData(
text = "$it",
onClick = { selectedTokenIndex = tokensList.indexOf(it) }
)
)
}
Column(
horizontalAlignment = Alignment.CenterHorizontally
) {
BasicCard(
modifier = Modifier
.size(width = 180.dp, height = 130.dp)
.padding(bottom = size(FluentGlobalTokens.SizeTokens.Size160)),
basicCardTokens = if (tokenName == R.string.shadow_tokens) previewShadowToken(
tokensList[selectedTokenIndex] as FluentGlobalTokens.ShadowTokens
)
else if (tokenName == R.string.corner_radius_tokens) previewCornerRadiusToken(
tokensList[selectedTokenIndex] as FluentGlobalTokens.CornerRadiusTokens
)
else if (tokenName == R.string.stroke_width_tokens) previewStrokeWidthToken(
tokensList[selectedTokenIndex] as FluentGlobalTokens.StrokeWidthTokens
) else null
) {
Box(contentAlignment = Alignment.Center, modifier = Modifier.fillMaxSize()) {
SetPreviewContent(tokenName, tokensList[selectedTokenIndex])
}
}
PillTabs(
metadataList = tabsList,
scrollable = true,
selectedIndex = selectedTokenIndex
)
}
}
@Composable
fun SetPreviewContent(tokenName: Int, selectedToken: Any) {
val textColor: Color = FluentColor(light = Color.Black, dark = Color.White).value()
when (tokenName) {
R.string.font_size_tokens ->
Text(
text = stringResource(id = R.string.sample_text),
color = textColor,
fontSize = fontSize(selectedToken as FluentGlobalTokens.FontSizeTokens)
)
R.string.line_height_tokens ->
Column {
Text(
text = "Text\nText",
color = textColor,
lineHeight = lineHeight(selectedToken as FluentGlobalTokens.LineHeightTokens)
)
}
R.string.font_weight_tokens ->
Text(
text = stringResource(id = R.string.sample_text),
color = textColor,
fontSize = fontSize(FluentGlobalTokens.FontSizeTokens.Size600),
fontWeight = fontWeight(selectedToken as FluentGlobalTokens.FontWeightTokens)
)
R.string.icon_size_tokens ->
Icon(
painter = painterResource(id = R.drawable.ic_fluent_home_24_regular),
contentDescription = stringResource(id = R.string.sample_icon),
tint = FluentTheme.aliasTokens.neutralForegroundColor[FluentAliasTokens.NeutralForegroundColorTokens.Foreground2].value(
FluentTheme.themeMode
),
modifier = Modifier.size(iconSize(selectedToken as FluentGlobalTokens.IconSizeTokens))
)
R.string.size_tokens ->
Row(horizontalArrangement = Arrangement.spacedBy(size(selectedToken as FluentGlobalTokens.SizeTokens))) {
Text(
text = stringResource(id = R.string.sample_text),
color = textColor,
fontSize = fontSize(FluentGlobalTokens.FontSizeTokens.Size600),
)
Text(
text = stringResource(id = R.string.sample_text),
color = textColor,
fontSize = fontSize(FluentGlobalTokens.FontSizeTokens.Size600),
)
}
R.string.typography_tokens -> Label(
text = stringResource(id = R.string.sample_text),
textStyle = selectedToken as FluentAliasTokens.TypographyTokens
)
}
}
@OptIn(ExperimentalFoundationApi::class)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
var buttonBarList: MutableList<PillMetaData>
lateinit var selectedTokens: MutableState<Tokens>
lateinit var tokensMap: MutableState<Map<Int, Pair<Array<out Enum<*>>, Any>>>
setBottomAppBar {
val globalTokensMap = mapOf(
R.string.neutral_color_tokens to Pair(
FluentGlobalTokens.NeutralColorTokens.values(),
::neutralColor
),
R.string.font_size_tokens to Pair(
FluentGlobalTokens.FontSizeTokens.values(),
::fontSize
),
R.string.line_height_tokens to Pair(
FluentGlobalTokens.LineHeightTokens.values(),
::lineHeight
),
R.string.font_weight_tokens to Pair(
FluentGlobalTokens.FontWeightTokens.values(),
::fontWeight
),
R.string.icon_size_tokens to Pair(
FluentGlobalTokens.IconSizeTokens.values(),
::iconSize
),
R.string.size_tokens to Pair(
FluentGlobalTokens.SizeTokens.values(),
::size
),
R.string.shadow_tokens to Pair(
FluentGlobalTokens.ShadowTokens.values(),
::elevation
),
R.string.corner_radius_tokens to Pair(
FluentGlobalTokens.CornerRadiusTokens.values(),
::cornerRadius
),
R.string.stroke_width_tokens to Pair(
FluentGlobalTokens.StrokeWidthTokens.values(),
::strokeWidth
),
)
val aliasTokensMap = mapOf(
R.string.brand_color_tokens to Pair(
FluentAliasTokens.BrandColorTokens.values(),
FluentTheme.aliasTokens.brandColor
),
R.string.neutral_background_color_tokens to Pair(
FluentAliasTokens.NeutralBackgroundColorTokens.values(),
FluentTheme.aliasTokens.neutralBackgroundColor
),
R.string.neutral_foreground_color_tokens to Pair(
FluentAliasTokens.NeutralForegroundColorTokens.values(),
FluentTheme.aliasTokens.neutralForegroundColor
),
R.string.neutral_stroke_color_tokens to Pair(
FluentAliasTokens.NeutralStrokeColorTokens.values(),
FluentTheme.aliasTokens.neutralStrokeColor
),
R.string.brand_background_color_tokens to Pair(
FluentAliasTokens.BrandBackgroundColorTokens.values(),
FluentTheme.aliasTokens.brandBackgroundColor
),
R.string.brand_foreground_color_tokens to Pair(
FluentAliasTokens.BrandForegroundColorTokens.values(),
FluentTheme.aliasTokens.brandForegroundColor
),
R.string.brand_stroke_color_tokens to Pair(
FluentAliasTokens.BrandStrokeColorTokens.values(),
FluentTheme.aliasTokens.brandStroke
),
R.string.error_and_status_color_tokens to Pair(
FluentAliasTokens.ErrorAndStatusColorTokens.values(),
FluentTheme.aliasTokens.errorAndStatusColor
),
R.string.presence_tokens to Pair(
FluentAliasTokens.PresenceColorTokens.values(),
FluentTheme.aliasTokens.presenceColor
),
R.string.typography_tokens to Pair(
FluentAliasTokens.TypographyTokens.values(),
FluentTheme.aliasTokens.typography
)
)
selectedTokens = remember { mutableStateOf(Tokens.GlobalTokens) }
tokensMap = remember { mutableStateOf(globalTokensMap.toMutableMap()) }
buttonBarList = listOf(
PillMetaData(
text = stringResource(id = R.string.global_tokens),
enabled = true,
onClick = {
selectedTokens.value = Tokens.GlobalTokens
tokensMap.value = globalTokensMap.toMutableMap()
}
),
PillMetaData(
text = stringResource(id = R.string.alias_tokens),
enabled = true,
onClick = {
selectedTokens.value = Tokens.AliasTokens
tokensMap.value = aliasTokensMap.toMutableMap()
}
)
) as MutableList<PillMetaData>
PillTabs(
style = AppThemeViewModel.appThemeStyle.value,
metadataList = buttonBarList,
selectedIndex = selectedTokens.value.ordinal,
)
}
setActivityContent {
Column(modifier = Modifier.verticalScroll(rememberScrollState())) {
tokensMap.value.forEach { (tokenType, tokenGetter) ->
ListItem.SectionHeader(
title = stringResource(id = tokenType),
enableContentOpenCloseTransition = true,
chevronOrientation = ChevronOrientation(90f, 0f),
) {
if (stringResource(id = tokenType).contains(stringResource(id = R.string.color))) {
Column(
modifier = Modifier
.height(256.dp)
.verticalScroll(rememberScrollState())
) {
tokenGetter.first.forEach {
ListItem.Item(
text = "$it",
trailingAccessoryContent = {
when (tokenType) {
R.string.neutral_color_tokens ->
Icon(
painter = painterResource(id = R.drawable.ic_fluent_square_24_filled),
contentDescription = stringResource(id = R.string.neutral_color_tokens),
tint = (tokenGetter.second as (Enum<*>) -> Color).invoke(
it
)
)
R.string.brand_color_tokens ->
Icon(
painter = painterResource(id = R.drawable.ic_fluent_square_24_filled),
contentDescription = stringResource(id = R.string.brand_color_tokens),
tint = FluentTheme.aliasTokens.brandColor[it as FluentAliasTokens.BrandColorTokens]
)
R.string.neutral_background_color_tokens, R.string.neutral_foreground_color_tokens, R.string.neutral_stroke_color_tokens, R.string.error_and_status_color_tokens, R.string.presence_tokens ->
Icon(
painter = painterResource(id = R.drawable.ic_fluent_square_24_filled),
contentDescription = "",
tint = (tokenGetter.second as TokenSet<Enum<*>, FluentColor>)[it].value()
)
R.string.brand_background_color_tokens ->
if ((tokenGetter.second as TokenSet<Enum<*>, FluentColor>)[it].value() == Color.Unspecified) {
Label(
text = stringResource(id = R.string.unspecified),
textStyle = FluentAliasTokens.TypographyTokens.Caption1
)
} else {
Icon(
painter = painterResource(id = R.drawable.ic_fluent_square_24_filled),
contentDescription = stringResource(id = R.string.brand_background_color_tokens),
tint = FluentTheme.aliasTokens.brandBackgroundColor[it as FluentAliasTokens.BrandBackgroundColorTokens].value()
)
}
R.string.brand_foreground_color_tokens ->
Icon(
painter = painterResource(id = R.drawable.ic_fluent_square_24_filled),
contentDescription = stringResource(id = R.string.brand_foreground_color_tokens),
tint = FluentTheme.aliasTokens.brandForegroundColor[it as FluentAliasTokens.BrandForegroundColorTokens].value()
)
R.string.brand_stroke_color_tokens ->
Icon(
painter = painterResource(id = R.drawable.ic_fluent_square_24_filled),
contentDescription = stringResource(id = R.string.brand_stroke_color_tokens),
tint = FluentTheme.aliasTokens.brandStroke[it as FluentAliasTokens.BrandStrokeColorTokens].value()
)
}
}
)
}
}
} else PreviewToken(tokenType, tokenGetter.first)
}
}
}
}
}
} | 43 | null | 97 | 574 | 851a4989a4fce5db50a1818aa4121538c1fb4ad9 | 20,181 | fluentui-android | MIT License |
jvm/src/main/kotlin/org/ionproject/core/userApi/auth/Exceptions.kt | i-on-project | 242,369,946 | false | null | package org.ionproject.core.userApi.auth
import org.ionproject.core.userApi.auth.model.AuthError
import org.ionproject.core.userApi.auth.model.AuthErrorResponse
import java.lang.RuntimeException
abstract class AuthErrorException(message: String, val error: AuthError) : RuntimeException(message) {
fun getErrorResponse() = AuthErrorResponse(
error,
localizedMessage
)
}
// invalid_client
class AuthRequestInvalidClientException : AuthErrorException(
"The specified client_id/client_secret is invalid!",
AuthError.INVALID_CLIENT
)
// unauthorized_client
class AuthRequestUnauthorizedClientException : AuthErrorException(
"The specified client is unauthorized to access this resource",
AuthError.UNAUTHORIZED_CLIENT
)
// invalid_grant
open class AuthGrantException(message: String) : AuthErrorException(message, AuthError.INVALID_GRANT)
class GrantInvalidAuthRequestException : AuthGrantException("The specified auth request is invalid")
class GrantInvalidRefreshTokenException : AuthGrantException("The specified refresh token is invalid")
// unsupported grant type
class UnsupportedGrantTypeException : AuthErrorException(
"The specified grant type is not supported",
AuthError.UNSUPPORTED_GRANT_TYPE
)
// invalid_request
open class AuthRequestInvalidException(message: String) : AuthErrorException(message, AuthError.INVALID_REQUEST)
class AuthRequestAlreadyExistsException : AuthRequestInvalidException("An auth request is already in progress")
class AuthRequestNotFoundException : AuthRequestInvalidException("The specified auth request wasn't found")
class AuthRequestInvalidSecretException : AuthRequestInvalidException("The auth request has been cancelled because of an incorrect secret token")
class AuthRequestAlreadyVerifiedException : AuthRequestInvalidException("This auth request has already been validated")
class UserTokenNotFoundException : AuthRequestInvalidException("The specified user token wasn't found")
// expired_token
class AuthRequestExpiredException : AuthErrorException(
"The specified auth request has expired",
AuthError.EXPIRED_TOKEN
)
// authorization_pending
class AuthRequestPendingException : AuthErrorException(
"The auth request is still waiting for a response",
AuthError.AUTHORIZATION_PENDING
)
// invalid_scope
open class AuthRequestInvalidScope(message: String) : AuthErrorException(message, AuthError.INVALID_SCOPE)
class AuthRequestMissingOpenIdScopeException : AuthRequestInvalidScope("The openid scope is mandatory")
class AuthRequestInvalidScopesException(invalid: Iterable<String>) : AuthRequestInvalidScope("The scopes ${invalid.joinToString()} are invalid")
// slow_down
class RefreshTokenRateLimitException(rateMinutes: Long) : AuthErrorException(
"You can only refresh this token once each $rateMinutes minutes",
AuthError.SLOW_DOWN
)
| 14 | Kotlin | 0 | 3 | 339407d56e66ec164ecdc4172347272d97cc26b3 | 2,868 | core | Apache License 2.0 |
modules/alertdialog/src/androidMain/kotlin/splitties/alertdialog/AlertDialog.kt | LouisCAD | 65,558,914 | false | {"Kotlin": 682428, "Java": 1368, "Shell": 358} | /*
* Copyright 2019 <NAME>. Use of this source code is governed by the Apache 2.0 license.
*/
package splitties.alertdialog.appcompat
import android.app.Activity
import android.content.Context
import android.content.DialogInterface
import android.graphics.drawable.Drawable
import android.widget.Button
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import androidx.appcompat.app.AlertDialog
import kotlin.DeprecationLevel.HIDDEN
/**
* Instantiates an [AlertDialog.Builder] for the [Context], applies the [dialogConfig] lambda to
* it, then creates an [AlertDialog] from the builder, and returns it, so you can call
* [AlertDialog.show] on the created dialog.
*/
inline fun Context.alertDialog(dialogConfig: AlertDialog.Builder.() -> Unit): AlertDialog {
return AlertDialog.Builder(this)
.apply(dialogConfig)
.create()
}
/**
* Instantiates an [AlertDialog.Builder] for the [Context], sets the passed [title], [message] and
* [iconResource], applies the [dialogConfig] lambda to it, then creates an [AlertDialog] from
* the builder, and returns it, so you can call [AlertDialog.show] on the created dialog.
*/
inline fun Context.alertDialog(
title: CharSequence? = null,
message: CharSequence? = null,
@DrawableRes iconResource: Int = 0,
dialogConfig: AlertDialog.Builder.() -> Unit = {}
): AlertDialog {
return AlertDialog.Builder(this).apply {
this.title = title
this.message = message
setIcon(iconResource)
dialogConfig()
}.create()
}
/**
* Instantiates an [AlertDialog.Builder] for the [Context], sets the passed [title], [message] and
* [icon], applies the [dialogConfig] lambda to it, then creates an [AlertDialog] from
* the builder, and returns it, so you can call [AlertDialog.show] on the created dialog.
*/
inline fun Context.alertDialog(
title: CharSequence? = null,
message: CharSequence? = null,
icon: Drawable?,
dialogConfig: AlertDialog.Builder.() -> Unit = {}
): AlertDialog {
return AlertDialog.Builder(this).apply {
this.title = title
this.message = message
setIcon(icon)
dialogConfig()
}.create()
}
/**
* Instantiates an [AlertDialog.Builder] for the [Activity], applies the [dialogConfig] lambda to
* it, then creates an [AlertDialog] from the builder, and returns it, so you can call
* [AlertDialog.show] on the created dialog.
*/
@Deprecated(
message = "This function is limited to Activity only and its name is not explicit enough. " +
"Use the alertDialog function instead.",
replaceWith = ReplaceWith(
expression = "this.alertDialog(dialogConfig)",
imports = ["splitties.alertdialog.appcompat.alertDialog"]
)
)
inline fun Activity.alert(dialogConfig: AlertDialog.Builder.() -> Unit): AlertDialog {
return AlertDialog.Builder(this)
.apply(dialogConfig)
.create()
}
/**
* Sets the [AlertDialog]'s [DialogInterface.OnShowListener] so it calls the passed
* [onShowListener] lambda when the dialog is shown, and returns the same instance for chained
* calls.
*/
inline fun AlertDialog.onShow(crossinline onShowListener: AlertDialog.() -> Unit) = apply {
setOnShowListener { onShowListener() }
}
/**
* Sets the [AlertDialog]'s [DialogInterface.OnDismissListener] so it calls the passed [handler]
* lambda when the dialog is dismissed.
*/
inline fun AlertDialog.Builder.onDismiss(crossinline handler: (dialog: DialogInterface) -> Unit) {
setOnDismissListener { handler(it) }
}
/**
* Returns the positive button from the [AlertDialog], or throws an [IllegalArgumentException] if
* the dialog has no positive button, or has not been shown yet.
*
* You can use the [onShow] extension function to wait for the dialog to be shown and be able to
* access the button.
*/
inline val AlertDialog.positiveButton: Button
get() = requireNotNull(getButton(AlertDialog.BUTTON_POSITIVE)) {
"The dialog has no positive button or has not been shown yet."
}
/**
* Returns the neutral button from the [AlertDialog], or throws an [IllegalArgumentException] if
* the dialog has no neutral button, or has not been shown yet.
*
* You can use the [onShow] extension function to wait for the dialog to be shown and be able to
* access the button.
*/
inline val AlertDialog.neutralButton: Button
get() = requireNotNull(getButton(AlertDialog.BUTTON_NEUTRAL)) {
"The dialog has no neutral button or has not been shown yet."
}
/**
* Returns the negative button from the [AlertDialog], or throws an [IllegalArgumentException] if
* the dialog has no negative button, or has not been shown yet.
*
* You can use the [onShow] extension function to wait for the dialog to be shown and be able to
* access the button.
*/
inline val AlertDialog.negativeButton: Button
get() = requireNotNull(getButton(AlertDialog.BUTTON_NEGATIVE)) {
"The dialog has no negative button or has not been shown yet."
}
/** Write only property that sets the dialog title from the passed string resource. */
var AlertDialog.Builder.titleResource: Int
@Deprecated(NO_GETTER, level = HIDDEN) get() = noGetter
set(value) {
setTitle(value)
}
/** Write only property that sets the dialog title. */
var AlertDialog.Builder.title: CharSequence?
@Deprecated(NO_GETTER, level = HIDDEN) get() = noGetter
set(value) {
setTitle(value)
}
/** Write only property that sets the dialog message from the passed string resource. */
var AlertDialog.Builder.messageResource: Int
@Deprecated(NO_GETTER, level = HIDDEN) get() = noGetter
set(value) {
setMessage(value)
}
/** Write only property that sets the dialog message. */
var AlertDialog.Builder.message: CharSequence?
@Deprecated(NO_GETTER, level = HIDDEN) get() = noGetter
set(value) {
setMessage(value)
}
/**
* Sets a positive button with [android.R.string.ok] ("OK", with translations) as its text, and
* calls the passed [handler] lambda when it is clicked.
*/
inline fun AlertDialog.Builder.okButton(crossinline handler: (dialog: DialogInterface) -> Unit) {
setPositiveButton(android.R.string.ok) { dialog: DialogInterface, _: Int -> handler(dialog) }
}
/**
* Sets a positive button with [android.R.string.ok] ("OK", with translations) as its text. A click
* on the button will have no effect apart from dismissing the dialog and having its
* [DialogInterface.OnDismissListener] called, if any was set (e.g. using [onDismiss]).
*/
@Suppress("NOTHING_TO_INLINE")
inline fun AlertDialog.Builder.okButton() {
setPositiveButton(android.R.string.ok, null)
}
/**
* Sets a negative button with [android.R.string.cancel] ("Cancel", with translations) as its text,
* and calls the passed [handler] lambda when it is clicked.
*/
inline fun AlertDialog.Builder.cancelButton(crossinline handler: (dialog: DialogInterface) -> Unit) {
setNegativeButton(android.R.string.cancel) { dialog: DialogInterface, _: Int -> handler(dialog) }
}
/**
* Sets a negative button with [android.R.string.cancel] ("Cancel", with translations) as its text.
* A click on the button will have no effect apart from dismissing the dialog and having its
* [DialogInterface.OnDismissListener] called, if any was set (e.g. using [onDismiss]).
*/
@Suppress("NOTHING_TO_INLINE")
inline fun AlertDialog.Builder.cancelButton() {
setNegativeButton(android.R.string.cancel, null)
}
/**
* Sets a positive button with the passed [textResId] text resource, and calls the passed [handler]
* lambda when it is clicked.
*/
inline fun AlertDialog.Builder.positiveButton(
@StringRes textResId: Int,
crossinline handler: (dialog: DialogInterface) -> Unit
) {
setPositiveButton(textResId) { dialog: DialogInterface, _: Int -> handler(dialog) }
}
/**
* Sets a neutral button with the passed [textResId] text resource, and calls the passed [handler]
* lambda when it is clicked.
*/
inline fun AlertDialog.Builder.neutralButton(
@StringRes textResId: Int,
crossinline handler: (dialog: DialogInterface) -> Unit
) {
setNeutralButton(textResId) { dialog: DialogInterface, _: Int -> handler(dialog) }
}
/**
* Sets a negative button with the passed [textResId] text resource, and calls the passed [handler]
* lambda when it is clicked.
*/
inline fun AlertDialog.Builder.negativeButton(
@StringRes textResId: Int,
crossinline handler: (dialog: DialogInterface) -> Unit
) {
setNegativeButton(textResId) { dialog: DialogInterface, _: Int -> handler(dialog) }
}
| 53 | Kotlin | 160 | 2,476 | 1ed56ba2779f31dbf909509c955fce7b9768e208 | 8,589 | Splitties | Apache License 2.0 |
src/test/kotlin/nl/jhvh/sudoku/grid/model/GridIT.kt | JanHendrikVanHeusden | 305,492,630 | false | null | package nl.jhvh.sudoku.grid.model
/* Copyright 2020 <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.
*/
import nl.jhvh.sudoku.grid.model.Grid.GridBuilder
import nl.jhvh.sudoku.grid.model.cell.Cell
import nl.jhvh.sudoku.grid.model.segment.Block
import nl.jhvh.sudoku.grid.model.segment.Col
import nl.jhvh.sudoku.grid.model.segment.Row
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
/**
* Tests for [Grid] initialization.
* Is a component integration test, as it tests the whole [Grid] being build with [GridBuilder],
* and with [Cell]s, [Row]s, [Col]s and [Block]s) correctly positioned within the [Grid].
*/
internal class GridIT {
/**
* Test that correct [Block] positions are assigned.
* <br></br>The
* [Grid] has a default grid size
*/
@Test
fun `test correctly initialized Block positions are assigned`() {
// Grid has DEFAULT_GRID_SIZE]
val grid = GridBuilder().build()
val blockList = grid.blockList
assertThat(blockList[0].leftColIndex).isEqualTo(0)
assertThat(blockList[1].leftColIndex).isEqualTo(3)
assertThat(blockList[2].leftColIndex).isEqualTo(6)
assertThat(blockList[3].leftColIndex).isEqualTo(0)
assertThat(blockList[4].leftColIndex).isEqualTo(3)
assertThat(blockList[5].leftColIndex).isEqualTo(6)
assertThat(blockList[6].leftColIndex).isEqualTo(0)
assertThat(blockList[7].leftColIndex).isEqualTo(3)
assertThat(blockList[8].leftColIndex).isEqualTo(6)
assertThat(blockList[0].rightColIndex).isEqualTo(2)
assertThat(blockList[1].rightColIndex).isEqualTo(5)
assertThat(blockList[2].rightColIndex).isEqualTo(8)
assertThat(blockList[3].rightColIndex).isEqualTo(2)
assertThat(blockList[4].rightColIndex).isEqualTo(5)
assertThat(blockList[5].rightColIndex).isEqualTo(8)
assertThat(blockList[6].rightColIndex).isEqualTo(2)
assertThat(blockList[7].rightColIndex).isEqualTo(5)
assertThat(blockList[8].rightColIndex).isEqualTo(8)
assertThat(blockList[0].topRowIndex).isEqualTo(0)
assertThat(blockList[1].topRowIndex).isEqualTo(0)
assertThat(blockList[2].topRowIndex).isEqualTo(0)
assertThat(blockList[3].topRowIndex).isEqualTo(3)
assertThat(blockList[4].topRowIndex).isEqualTo(3)
assertThat(blockList[5].topRowIndex).isEqualTo(3)
assertThat(blockList[6].topRowIndex).isEqualTo(6)
assertThat(blockList[7].topRowIndex).isEqualTo(6)
assertThat(blockList[8].topRowIndex).isEqualTo(6)
assertThat(blockList[0].bottomRowIndex).isEqualTo(2)
assertThat(blockList[1].bottomRowIndex).isEqualTo(2)
assertThat(blockList[2].bottomRowIndex).isEqualTo(2)
assertThat(blockList[3].bottomRowIndex).isEqualTo(5)
assertThat(blockList[4].bottomRowIndex).isEqualTo(5)
assertThat(blockList[5].bottomRowIndex).isEqualTo(5)
assertThat(blockList[6].bottomRowIndex).isEqualTo(8)
assertThat(blockList[7].bottomRowIndex).isEqualTo(8)
assertThat(blockList[8].bottomRowIndex).isEqualTo(8)
}
/**
* Test method for [GridBuilder.build] -> [Grid] constructor, with different [Grid.gridSize]s:
* test that [Cell.colIndex] and [Cell.rowIndex] correspond to the [Block] positions.
*/
@Test
fun `test correctly initialized Cell positions`() {
for (size in 2..4) {
val grid = GridBuilder(size).build()
val blockList = grid.blockList
for (block in blockList) {
for (x in 0 until grid.gridSize) {
val cell = block.cells.toList()[x]
assertThat(cell.rowIndex in block.topRowIndex..block.bottomRowIndex)
.`as`("Wrong rowIndex! Block: $block\t Cell:$cell")
.isTrue()
assertThat(cell.colIndex in block.leftColIndex..block.rightColIndex)
.`as`("Wrong rowIndex! Block: $block\t Cell:$cell")
.isTrue()
assertThat(cell.colIndex)
.`as`("Wrong X-index! Block: $block\t Cell:$cell")
.isEqualTo(block.leftColIndex + x % grid.blockSize)
assertThat(block.topRowIndex + x / grid.blockSize)
.`as`("Wrong Y-index! Block: $block\t Cell:$cell")
.isEqualTo(cell.rowIndex)
}
}
}
}
/**
* Test method for [GridBuilder.build] -> [Grid] constructor, with different [Grid.gridSize]s:
* test that correct [Col] positions are assigned.
*/
@Test
fun `test correctly initialized Column positions`() {
for (size in 2..4) {
val grid = GridBuilder(size).build()
val colList = grid.colList
for (x in 0 until grid.gridSize) {
assertThat(colList[x].colIndex).isEqualTo(x)
}
}
}
/**
* Test method for [GridBuilder.build] -> [Grid] constructor, with different [Grid.gridSize]s:
* test that correct [Row] positions are assigned.
*/
@Test
fun `test correctly initialized Row positions`() {
for (size in 2..4) {
val grid = GridBuilder(size).build()
val rowList = grid.rowList
for (y in 0 until grid.gridSize) {
assertThat(rowList[y].rowIndex).isEqualTo(y)
}
}
}
}
| 2 | Kotlin | 0 | 1 | 345516e1f5d35df9f5d362e633ea5d22f44dc08a | 6,065 | Sudoku | Apache License 2.0 |
compose/ui-layout-common/src/commonMain/kotlin/com/bselzer/ktx/compose/ui/layout/lazyrow/LazyRowProjector.kt | Woody230 | 388,189,330 | false | {"Kotlin": 3122765} | package com.bselzer.ktx.compose.ui.layout.lazyrow
import androidx.compose.foundation.lazy.LazyItemScope
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Modifier
import com.bselzer.ktx.compose.ui.layout.LayoutOrientation
import com.bselzer.ktx.compose.ui.layout.LocalLayoutOrientation
import com.bselzer.ktx.compose.ui.layout.divider.DividerProjector
import com.bselzer.ktx.compose.ui.layout.project.Projector
class LazyRowProjector<T>(
interactor: LazyRowInteractor<T>,
presenter: LazyRowPresenter = LazyRowPresenter.Default
) : Projector<LazyRowInteractor<T>, LazyRowPresenter>(interactor, presenter) {
@Composable
fun Projection(
modifier: Modifier = Modifier,
content: @Composable LazyItemScope.(Int, T) -> Unit
) = contextualize(modifier) { combinedModifier, interactor, presenter ->
LazyRow(
modifier = combinedModifier,
state = rememberSaveable(saver = LazyListState.Saver) { interactor.state },
contentPadding = presenter.contentPadding,
reverseLayout = presenter.reverseLayout.toBoolean(),
horizontalArrangement = presenter.horizontalArrangement,
verticalAlignment = presenter.verticalAlignment,
flingBehavior = presenter.flingBehavior,
) {
val dividerProjector = interactor.divider?.let { divider -> DividerProjector(divider, presenter.divider) }
itemsIndexed(interactor.items) { index, item ->
CompositionLocalProvider(
LocalLayoutOrientation provides LayoutOrientation.HORIZONTAL
) {
val isFirst = index == 0
val shouldPrepend = isFirst && presenter.prepend.toBoolean()
if (shouldPrepend) {
dividerProjector?.Projection()
}
content(index, item)
val isLast = index == interactor.items.lastIndex
val isIntermediate = !isLast
val shouldAppend = isLast && presenter.append.toBoolean()
if (isIntermediate || shouldAppend) {
dividerProjector?.Projection()
}
}
}
}
}
} | 2 | Kotlin | 0 | 7 | 5ad55d66bbb58a12bf3a8b436ea1ea4d8e9737bc | 2,569 | KotlinExtensions | Apache License 2.0 |
app/src/main/java/com/kproject/chatgpt/commom/error/ApiResponseError.kt | jsericksk | 581,359,749 | false | {"Kotlin": 150740} | package com.kproject.chatgpt.commom.error
sealed class ApiResponseError : Exception() {
object InvalidApiKey : ApiResponseError()
object MaxTokensReached : ApiResponseError()
object OverloadedServer : ApiResponseError()
object UnknownError : ApiResponseError()
} | 0 | Kotlin | 0 | 1 | 15561532c4836be546bd45d6b735b420c427e4ee | 279 | ChatGPT | MIT License |
kex-runner/src/main/kotlin/org/vorpal/research/kex/asm/analysis/symbolic/SymbolicTraverser.kt | vorpal-research | 204,454,367 | false | {"Kotlin": 2271251, "Java": 82857, "Python": 1696} | package org.vorpal.research.kex.asm.analysis.symbolic
import kotlinx.collections.immutable.PersistentList
import kotlinx.collections.immutable.PersistentMap
import kotlinx.collections.immutable.PersistentSet
import kotlinx.collections.immutable.persistentListOf
import kotlinx.collections.immutable.persistentMapOf
import kotlinx.collections.immutable.persistentSetOf
import kotlinx.collections.immutable.toPersistentMap
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.withContext
import kotlinx.coroutines.yield
import org.vorpal.research.kex.ExecutionContext
import org.vorpal.research.kex.asm.analysis.util.analyzeOrTimeout
import org.vorpal.research.kex.asm.analysis.util.checkAsync
import org.vorpal.research.kex.asm.analysis.util.checkAsyncIncremental
import org.vorpal.research.kex.compile.CompilationException
import org.vorpal.research.kex.compile.CompilerHelper
import org.vorpal.research.kex.descriptor.Descriptor
import org.vorpal.research.kex.descriptor.DescriptorContext
import org.vorpal.research.kex.descriptor.FullDescriptorContext
import org.vorpal.research.kex.descriptor.descriptor
import org.vorpal.research.kex.ktype.KexPointer
import org.vorpal.research.kex.ktype.KexRtManager.rtMapped
import org.vorpal.research.kex.ktype.KexType
import org.vorpal.research.kex.ktype.kexType
import org.vorpal.research.kex.parameters.FinalParameters
import org.vorpal.research.kex.parameters.Parameters
import org.vorpal.research.kex.parameters.extractFinalParameters
import org.vorpal.research.kex.reanimator.UnsafeGenerator
import org.vorpal.research.kex.reanimator.codegen.klassName
import org.vorpal.research.kex.state.predicate.inverse
import org.vorpal.research.kex.state.predicate.path
import org.vorpal.research.kex.state.predicate.state
import org.vorpal.research.kex.state.term.ConstClassTerm
import org.vorpal.research.kex.state.term.NullTerm
import org.vorpal.research.kex.state.term.StaticClassRefTerm
import org.vorpal.research.kex.state.term.Term
import org.vorpal.research.kex.state.term.TermBuilder
import org.vorpal.research.kex.state.term.term
import org.vorpal.research.kex.state.transformer.isThis
import org.vorpal.research.kex.trace.symbolic.PathClause
import org.vorpal.research.kex.trace.symbolic.PathClauseType
import org.vorpal.research.kex.trace.symbolic.PersistentSymbolicState
import org.vorpal.research.kex.trace.symbolic.StateClause
import org.vorpal.research.kex.trace.symbolic.SymbolicState
import org.vorpal.research.kex.trace.symbolic.persistentPathConditionOf
import org.vorpal.research.kex.trace.symbolic.persistentSymbolicState
import org.vorpal.research.kex.util.isSubtypeOfCached
import org.vorpal.research.kfg.ClassManager
import org.vorpal.research.kfg.arrayIndexOOBClass
import org.vorpal.research.kfg.classCastClass
import org.vorpal.research.kfg.ir.BasicBlock
import org.vorpal.research.kfg.ir.Method
import org.vorpal.research.kfg.ir.value.Constant
import org.vorpal.research.kfg.ir.value.Value
import org.vorpal.research.kfg.ir.value.ValueFactory
import org.vorpal.research.kfg.ir.value.instruction.ArrayLoadInst
import org.vorpal.research.kfg.ir.value.instruction.ArrayStoreInst
import org.vorpal.research.kfg.ir.value.instruction.BinaryInst
import org.vorpal.research.kfg.ir.value.instruction.BranchInst
import org.vorpal.research.kfg.ir.value.instruction.CallInst
import org.vorpal.research.kfg.ir.value.instruction.CastInst
import org.vorpal.research.kfg.ir.value.instruction.CatchInst
import org.vorpal.research.kfg.ir.value.instruction.CmpInst
import org.vorpal.research.kfg.ir.value.instruction.EnterMonitorInst
import org.vorpal.research.kfg.ir.value.instruction.ExitMonitorInst
import org.vorpal.research.kfg.ir.value.instruction.FieldLoadInst
import org.vorpal.research.kfg.ir.value.instruction.FieldStoreInst
import org.vorpal.research.kfg.ir.value.instruction.InstanceOfInst
import org.vorpal.research.kfg.ir.value.instruction.Instruction
import org.vorpal.research.kfg.ir.value.instruction.InvokeDynamicInst
import org.vorpal.research.kfg.ir.value.instruction.JumpInst
import org.vorpal.research.kfg.ir.value.instruction.NewArrayInst
import org.vorpal.research.kfg.ir.value.instruction.NewInst
import org.vorpal.research.kfg.ir.value.instruction.PhiInst
import org.vorpal.research.kfg.ir.value.instruction.ReturnInst
import org.vorpal.research.kfg.ir.value.instruction.SwitchInst
import org.vorpal.research.kfg.ir.value.instruction.TableSwitchInst
import org.vorpal.research.kfg.ir.value.instruction.TerminateInst
import org.vorpal.research.kfg.ir.value.instruction.ThrowInst
import org.vorpal.research.kfg.ir.value.instruction.UnaryInst
import org.vorpal.research.kfg.ir.value.instruction.UnaryOpcode
import org.vorpal.research.kfg.ir.value.instruction.UnknownValueInst
import org.vorpal.research.kfg.ir.value.instruction.UnreachableInst
import org.vorpal.research.kfg.negativeArrayClass
import org.vorpal.research.kfg.nullptrClass
import org.vorpal.research.kfg.type.Type
import org.vorpal.research.kfg.type.TypeFactory
import org.vorpal.research.kthelper.assert.unreachable
import org.vorpal.research.kthelper.logging.log
import java.util.concurrent.atomic.AtomicInteger
data class SymbolicStackTraceElement(
val method: Method,
val instruction: Instruction,
val valueMap: PersistentMap<Value, Term>
)
data class TraverserState(
val symbolicState: PersistentSymbolicState,
val valueMap: PersistentMap<Value, Term>,
val stackTrace: PersistentList<SymbolicStackTraceElement>,
val typeInfo: PersistentMap<Term, Type>,
val blockPath: PersistentList<BasicBlock>,
val nullCheckedTerms: PersistentSet<Term>,
val boundCheckedTerms: PersistentSet<Pair<Term, Term>>,
val typeCheckedTerms: PersistentMap<Term, Type>
) {
fun mkTerm(value: Value): Term = when (value) {
is Constant -> term { const(value) }
else -> valueMap.getValue(value)
}
fun copyTermInfo(from: Term, to: Term): TraverserState = this.copy(
nullCheckedTerms = when (from) {
in nullCheckedTerms -> nullCheckedTerms.add(to)
else -> nullCheckedTerms
},
typeCheckedTerms = when (from) {
in typeCheckedTerms -> typeCheckedTerms.put(to, typeCheckedTerms[from]!!)
else -> typeCheckedTerms
}
)
operator fun plus(state: PersistentSymbolicState): TraverserState = this.copy(
symbolicState = this.symbolicState + state
)
operator fun plus(clause: StateClause): TraverserState = this.copy(
symbolicState = this.symbolicState + clause
)
operator fun plus(clause: PathClause): TraverserState = this.copy(
symbolicState = this.symbolicState + clause
)
operator fun plus(basicBlock: BasicBlock): TraverserState = this.copy(
blockPath = this.blockPath.add(basicBlock)
)
}
@Suppress("MemberVisibilityCanBePrivate")
abstract class SymbolicTraverser(
val ctx: ExecutionContext,
val rootMethod: Method,
) : TermBuilder {
val cm: ClassManager
get() = ctx.cm
val types: TypeFactory
get() = ctx.types
val values: ValueFactory
get() = ctx.values
abstract val pathSelector: SymbolicPathSelector
abstract val callResolver: SymbolicCallResolver
abstract val invokeDynamicResolver: SymbolicInvokeDynamicResolver
protected var testIndex = AtomicInteger(0)
protected val compilerHelper = CompilerHelper(ctx)
protected val nullptrClass = cm.nullptrClass
protected val arrayIndexOOBClass = cm.arrayIndexOOBClass
protected val negativeArrayClass = cm.negativeArrayClass
protected val classCastClass = cm.classCastClass
protected val Type.symbolicType: KexType get() = kexType.rtMapped
protected val org.vorpal.research.kfg.ir.Class.symbolicClass: KexType get() = kexType.rtMapped
suspend fun analyze() = rootMethod.analyzeOrTimeout(ctx.accessLevel) {
processMethod(it)
}
protected open suspend fun processMethod(method: Method) {
val thisValue = values.getThis(method.klass)
val initialArguments = buildMap {
val values = [email protected]
if (!method.isStatic) {
this[thisValue] = `this`(method.klass.symbolicClass)
}
for ((index, type) in method.argTypes.withIndex()) {
this[values.getArgument(index, method, type)] = arg(type.symbolicType, index)
}
}
val initialState = when {
!method.isStatic -> {
val thisTerm = initialArguments[thisValue]!!
val thisType = method.klass.symbolicClass.getKfgType(types)
TraverserState(
symbolicState = persistentSymbolicState(
path = persistentPathConditionOf(
PathClause(
PathClauseType.NULL_CHECK,
method.body.entry.first(),
path { (thisTerm eq null) equality false }
)
)
),
valueMap = initialArguments.toPersistentMap(),
stackTrace = persistentListOf(),
typeInfo = persistentMapOf(thisTerm to thisType),
blockPath = persistentListOf(),
nullCheckedTerms = persistentSetOf(thisTerm),
boundCheckedTerms = persistentSetOf(),
typeCheckedTerms = persistentMapOf(thisTerm to thisType)
)
}
else -> TraverserState(
symbolicState = persistentSymbolicState(),
valueMap = initialArguments.toPersistentMap(),
stackTrace = persistentListOf(),
typeInfo = persistentMapOf(),
blockPath = persistentListOf(),
nullCheckedTerms = persistentSetOf(),
boundCheckedTerms = persistentSetOf(),
typeCheckedTerms = persistentMapOf()
)
}
withContext(currentCoroutineContext()) {
pathSelector += initialState to method.body.entry
while (pathSelector.hasNext()) {
val (currentState, currentBlock) = pathSelector.next()
traverseBlock(currentState, currentBlock)
yield()
}
}
}
protected open suspend fun traverseBlock(state: TraverserState, bb: BasicBlock, startIndex: Int = 0) {
var currentState: TraverserState? = state
for (index in startIndex..bb.instructions.lastIndex) {
if (currentState == null) return
val inst = bb.instructions[index]
currentState = traverseInstruction(currentState, inst)
}
}
protected open suspend fun traverseInstruction(state: TraverserState, inst: Instruction): TraverserState? =
when (inst) {
is ArrayLoadInst -> traverseArrayLoadInst(state, inst)
is ArrayStoreInst -> traverseArrayStoreInst(state, inst)
is BinaryInst -> traverseBinaryInst(state, inst)
is CallInst -> traverseCallInst(state, inst)
is CastInst -> traverseCastInst(state, inst)
is CatchInst -> traverseCatchInst(state, inst)
is CmpInst -> traverseCmpInst(state, inst)
is EnterMonitorInst -> traverseEnterMonitorInst(state, inst)
is ExitMonitorInst -> traverseExitMonitorInst(state, inst)
is FieldLoadInst -> traverseFieldLoadInst(state, inst)
is FieldStoreInst -> traverseFieldStoreInst(state, inst)
is InstanceOfInst -> traverseInstanceOfInst(state, inst)
is InvokeDynamicInst -> traverseInvokeDynamicInst(state, inst)
is NewArrayInst -> traverseNewArrayInst(state, inst)
is NewInst -> traverseNewInst(state, inst)
is PhiInst -> traversePhiInst(state, inst)
is UnaryInst -> traverseUnaryInst(state, inst)
is BranchInst -> traverseBranchInst(state, inst)
is JumpInst -> traverseJumpInst(state, inst)
is ReturnInst -> traverseReturnInst(state, inst)
is SwitchInst -> traverseSwitchInst(state, inst)
is TableSwitchInst -> traverseTableSwitchInst(state, inst)
is ThrowInst -> traverseThrowInst(state, inst)
is UnreachableInst -> traverseUnreachableInst(state, inst)
is UnknownValueInst -> traverseUnknownValueInst(state, inst)
else -> unreachable("Unknown instruction ${inst.print()}")
}
protected open suspend fun traverseArrayLoadInst(
traverserState: TraverserState,
inst: ArrayLoadInst
): TraverserState? {
val arrayTerm = traverserState.mkTerm(inst.arrayRef)
val indexTerm = traverserState.mkTerm(inst.index)
val res = generate(inst.type.symbolicType)
if (arrayTerm is NullTerm) {
checkReachabilityIncremental(traverserState, nullabilityCheckInc(traverserState, inst, arrayTerm))
return null
}
val clause = StateClause(inst, state { res equality arrayTerm[indexTerm].load() })
val nullQueries = nullabilityCheckInc(traverserState, inst, arrayTerm)
val boundQueries = boundsCheckInc(traverserState, inst, indexTerm, arrayTerm.length())
var result: TraverserState? = null
val fullQueries = (nullQueries + boundQueries.addExtraCondition(nullQueries.normalQuery))
.withHandler { state: TraverserState ->
state.copy(
symbolicState = state.symbolicState + clause,
valueMap = state.valueMap.put(inst, res)
).also { result = it }
}
checkReachabilityIncremental(traverserState, fullQueries)
return result
}
protected open suspend fun traverseArrayStoreInst(
traverserState: TraverserState,
inst: ArrayStoreInst
): TraverserState? {
val arrayTerm = traverserState.mkTerm(inst.arrayRef)
val indexTerm = traverserState.mkTerm(inst.index)
val valueTerm = traverserState.mkTerm(inst.value)
if (arrayTerm is NullTerm) {
checkReachabilityIncremental(traverserState, nullabilityCheckInc(traverserState, inst, arrayTerm))
return null
}
val clause = StateClause(inst, state { arrayTerm[indexTerm].store(valueTerm) })
val nullQueries = nullabilityCheckInc(traverserState, inst, arrayTerm)
val boundQueries = boundsCheckInc(traverserState, inst, indexTerm, arrayTerm.length())
var result: TraverserState? = null
val fullQueries = (nullQueries + boundQueries.addExtraCondition(nullQueries.normalQuery))
.withHandler { state: TraverserState ->
(state + clause).also { result = it }
}
checkReachabilityIncremental(traverserState, fullQueries)
return result
}
protected open suspend fun traverseBinaryInst(traverserState: TraverserState, inst: BinaryInst): TraverserState? {
val lhvTerm = traverserState.mkTerm(inst.lhv)
val rhvTerm = traverserState.mkTerm(inst.rhv)
val resultTerm = generate(inst.type.symbolicType)
val clause = StateClause(
inst,
state { resultTerm equality lhvTerm.apply(resultTerm.type, inst.opcode, rhvTerm) }
)
return traverserState.copy(
symbolicState = traverserState.symbolicState + clause,
valueMap = traverserState.valueMap.put(inst, resultTerm)
)
}
protected open suspend fun traverseBranchInst(traverserState: TraverserState, inst: BranchInst): TraverserState? {
val condTerm = traverserState.mkTerm(inst.cond)
val trueClause = PathClause(
PathClauseType.CONDITION_CHECK,
inst,
path { condTerm equality true }
)
val falseClause = trueClause.inverse()
val trueConstraints = persistentSymbolicState() + trueClause
val falseConstraints = persistentSymbolicState() + falseClause
checkReachabilityIncremental(
traverserState,
ConditionCheckQuery(
UpdateOnlyQuery(trueConstraints) { state ->
val newState = state + inst.parent
pathSelector += newState to inst.trueSuccessor
newState
},
UpdateOnlyQuery(falseConstraints) { state ->
val newState = state + inst.parent
pathSelector += newState to inst.falseSuccessor
newState
},
)
)
return null
}
protected open suspend fun traverseCallInst(traverserState: TraverserState, inst: CallInst): TraverserState? {
val callee = when {
inst.isStatic -> staticRef(inst.method.klass)
else -> traverserState.mkTerm(inst.callee)
}
val argumentTerms = inst.args.map { traverserState.mkTerm(it) }
val candidates = callResolver.resolve(traverserState, inst)
var result: TraverserState? = null
val handler: (UpdateAction) = { state ->
when {
candidates.isEmpty() -> {
var varState = state
val receiver = when {
inst.isNameDefined -> {
val res = generate(inst.type.symbolicType)
varState = varState.copy(
valueMap = traverserState.valueMap.put(inst, res)
)
res
}
else -> null
}
val callClause = StateClause(
inst, state {
val callTerm = callee.call(inst.method, argumentTerms)
receiver?.call(callTerm) ?: call(callTerm)
}
)
(varState + callClause).also {
result = it
}
}
else -> {
for (candidate in candidates) {
processMethodCall(state, inst, candidate, callee, argumentTerms)
}
state
}
}
}
val nullQuery = when {
inst.isStatic -> EmptyQuery()
else -> nullabilityCheckInc(traverserState, inst, callee)
}.withHandler(handler)
checkReachabilityIncremental(traverserState, nullQuery)
return result
}
protected open suspend fun traverseCastInst(traverserState: TraverserState, inst: CastInst): TraverserState? {
val operandTerm = traverserState.mkTerm(inst.operand)
val resultTerm = generate(inst.type.symbolicType)
val clause = StateClause(
inst,
state { resultTerm equality (operandTerm `as` resultTerm.type) }
)
var result: TraverserState? = null
val typeQuery = typeCheckInc(traverserState, inst, operandTerm, resultTerm.type).withHandler { state ->
state.copy(
symbolicState = state.symbolicState + clause,
valueMap = state.valueMap.put(inst, resultTerm)
).copyTermInfo(operandTerm, resultTerm).also { result = it }
}
checkReachabilityIncremental(traverserState, typeQuery)
return result
}
protected open suspend fun traverseCatchInst(traverserState: TraverserState, inst: CatchInst): TraverserState? {
return traverserState
}
protected open suspend fun traverseCmpInst(traverserState: TraverserState, inst: CmpInst): TraverserState? {
val lhvTerm = traverserState.mkTerm(inst.lhv)
val rhvTerm = traverserState.mkTerm(inst.rhv)
val resultTerm = generate(inst.type.symbolicType)
val clause = StateClause(
inst,
state { resultTerm equality lhvTerm.apply(inst.opcode, rhvTerm) }
)
return traverserState.copy(
symbolicState = traverserState.symbolicState + clause,
valueMap = traverserState.valueMap.put(inst, resultTerm)
)
}
protected open suspend fun traverseEnterMonitorInst(
traverserState: TraverserState,
inst: EnterMonitorInst
): TraverserState? {
val monitorTerm = traverserState.mkTerm(inst.owner)
val clause = StateClause(
inst,
state { enterMonitor(monitorTerm) }
)
var result: TraverserState? = null
val nullQuery = nullabilityCheckInc(traverserState, inst, monitorTerm).withHandler { state ->
(state + clause).also {
result = it
}
}
checkReachabilityIncremental(traverserState, nullQuery)
return result
}
protected open suspend fun traverseExitMonitorInst(
traverserState: TraverserState,
inst: ExitMonitorInst
): TraverserState? {
val monitorTerm = traverserState.mkTerm(inst.owner)
val clause = StateClause(
inst,
state { exitMonitor(monitorTerm) }
)
return traverserState + clause
}
protected open suspend fun traverseFieldLoadInst(
traverserState: TraverserState,
inst: FieldLoadInst
): TraverserState? {
val field = inst.field
val objectTerm = when {
inst.isStatic -> staticRef(field.klass)
else -> traverserState.mkTerm(inst.owner)
}
if (objectTerm is NullTerm) {
checkReachabilityIncremental(traverserState, nullabilityCheckInc(traverserState, inst, objectTerm))
return null
}
val res = generate(inst.type.symbolicType)
val clause = StateClause(
inst,
state { res equality objectTerm.field(field.type.symbolicType, field.name).load() }
)
var result: TraverserState? = null
val nullQuery = nullabilityCheckInc(traverserState, inst, objectTerm).withHandler { state ->
val newNullChecked = when {
field.isStatic && field.isFinal -> when (field.defaultValue) {
null -> state.nullCheckedTerms.add(res)
ctx.values.nullConstant -> state.nullCheckedTerms
else -> state.nullCheckedTerms.add(res)
}
else -> state.nullCheckedTerms
}
state.copy(
symbolicState = state.symbolicState + clause,
valueMap = state.valueMap.put(inst, res),
nullCheckedTerms = newNullChecked
).also { result = it }
}
checkReachabilityIncremental(traverserState, nullQuery)
return result
}
protected open suspend fun traverseFieldStoreInst(
traverserState: TraverserState,
inst: FieldStoreInst
): TraverserState? {
val objectTerm = when {
inst.isStatic -> staticRef(inst.field.klass)
else -> traverserState.mkTerm(inst.owner)
}
if (objectTerm is NullTerm) {
checkReachabilityIncremental(traverserState, nullabilityCheckInc(traverserState, inst, objectTerm))
return null
}
val valueTerm = traverserState.mkTerm(inst.value)
val clause = StateClause(
inst,
state { objectTerm.field(inst.field.type.symbolicType, inst.field.name).store(valueTerm) }
)
var result: TraverserState? = null
val nullQuery = nullabilityCheckInc(traverserState, inst, objectTerm).withHandler { state ->
state.copy(
symbolicState = state.symbolicState + clause,
valueMap = state.valueMap.put(inst, valueTerm)
).also { result = it }
}
checkReachabilityIncremental(traverserState, nullQuery)
return result
}
protected open suspend fun traverseInstanceOfInst(
traverserState: TraverserState,
inst: InstanceOfInst
): TraverserState? {
val operandTerm = traverserState.mkTerm(inst.operand)
val resultTerm = generate(inst.type.symbolicType)
val clause = StateClause(
inst,
state { resultTerm equality (operandTerm `is` inst.targetType.symbolicType) }
)
val previouslyCheckedType = traverserState.typeCheckedTerms[operandTerm]
val currentlyCheckedType = operandTerm.type.getKfgType(ctx.types)
return traverserState.copy(
symbolicState = traverserState.symbolicState + clause,
valueMap = traverserState.valueMap.put(inst, resultTerm),
typeCheckedTerms = when {
previouslyCheckedType != null && currentlyCheckedType.isSubtypeOfCached(previouslyCheckedType) ->
traverserState.typeCheckedTerms.put(operandTerm, inst.targetType)
else -> traverserState.typeCheckedTerms
}
)
}
protected open suspend fun traverseInvokeDynamicInst(
traverserState: TraverserState,
inst: InvokeDynamicInst
): TraverserState? {
return when (invokeDynamicResolver.resolve(traverserState, inst)) {
null -> traverserState.copy(
valueMap = traverserState.valueMap.put(inst, generate(inst.type.kexType))
)
else -> invokeDynamicResolver.resolve(traverserState, inst)
}
}
protected open suspend fun processMethodCall(
traverserState: TraverserState,
inst: Instruction,
candidate: Method,
callee: Term,
argumentTerms: List<Term>
) {
if (candidate.body.isEmpty()) return
var newValueMap = traverserState.valueMap.builder().let { builder ->
if (!candidate.isStatic) builder[values.getThis(candidate.klass)] = callee
for ((index, type) in candidate.argTypes.withIndex()) {
builder[values.getArgument(index, candidate, type)] = argumentTerms[index]
}
builder.build()
}
val checks = when {
candidate.isStatic -> EmptyQuery { state ->
state.copy(
valueMap = newValueMap,
stackTrace = state.stackTrace.add(
SymbolicStackTraceElement(inst.parent.method, inst, state.valueMap)
)
).also { pathSelector += it to candidate.body.entry }
}
else -> typeCheckInc(traverserState, inst, callee, candidate.klass.symbolicClass).withHandler { state ->
when {
candidate.klass.asType.isSubtypeOfCached(callee.type.getKfgType(types)) -> {
val newCalleeTerm = generate(candidate.klass.symbolicClass)
val convertClause = StateClause(inst, state {
newCalleeTerm equality (callee `as` candidate.klass.symbolicClass)
})
newValueMap = newValueMap.mapValues { (_, term) ->
when (term) {
callee -> newCalleeTerm
else -> term
}
}.toPersistentMap()
state.copy(
symbolicState = state.symbolicState + convertClause
).copyTermInfo(callee, newCalleeTerm)
}
else -> state
}.copy(
valueMap = newValueMap,
stackTrace = state.stackTrace.add(
SymbolicStackTraceElement(inst.parent.method, inst, state.valueMap)
)
).also { pathSelector += it to candidate.body.entry }
}
}
checkReachabilityIncremental(traverserState, checks)
}
protected open suspend fun traverseNewArrayInst(
traverserState: TraverserState,
inst: NewArrayInst
): TraverserState? {
val dimensions = inst.dimensions.map { traverserState.mkTerm(it) }
val resultTerm = generate(inst.type.symbolicType)
val clause = StateClause(inst, state { resultTerm.new(dimensions) })
var result: TraverserState? = null
val checks = dimensions.fold<Term, OptionalErrorCheckQuery>(EmptyQuery()) { acc, dimension ->
acc + newArrayBoundsCheckInc(traverserState, inst, dimension)
}.withHandler { state ->
state.copy(
symbolicState = state.symbolicState + clause,
typeInfo = state.typeInfo.put(resultTerm, inst.type.rtMapped),
valueMap = state.valueMap.put(inst, resultTerm),
nullCheckedTerms = state.nullCheckedTerms.add(resultTerm),
typeCheckedTerms = state.typeCheckedTerms.put(resultTerm, inst.type)
).also { result = it }
}
checkReachabilityIncremental(traverserState, checks)
return result
}
protected open suspend fun traverseNewInst(traverserState: TraverserState, inst: NewInst): TraverserState? {
val resultTerm = generate(inst.type.symbolicType)
val clause = StateClause(
inst,
state { resultTerm.new() }
)
return traverserState.copy(
symbolicState = traverserState.symbolicState + clause,
typeInfo = traverserState.typeInfo.put(resultTerm, inst.type.rtMapped),
valueMap = traverserState.valueMap.put(inst, resultTerm),
nullCheckedTerms = traverserState.nullCheckedTerms.add(resultTerm),
typeCheckedTerms = traverserState.typeCheckedTerms.put(resultTerm, inst.type)
)
}
protected open suspend fun traversePhiInst(traverserState: TraverserState, inst: PhiInst): TraverserState? {
val previousBlock = traverserState.blockPath.last { it.method == inst.parent.method }
val value = traverserState.mkTerm(inst.incomings.getValue(previousBlock))
return traverserState.copy(
valueMap = traverserState.valueMap.put(inst, value)
)
}
protected open suspend fun traverseUnaryInst(traverserState: TraverserState, inst: UnaryInst): TraverserState? {
val operandTerm = traverserState.mkTerm(inst.operand)
val resultTerm = generate(inst.type.symbolicType)
val clause = StateClause(
inst,
state { resultTerm equality operandTerm.apply(inst.opcode) }
)
var result: TraverserState? = null
val checks = when (inst.opcode) {
UnaryOpcode.LENGTH -> nullabilityCheckInc(traverserState, inst, operandTerm)
else -> EmptyQuery()
}.withHandler { state ->
state.copy(
symbolicState = state.symbolicState + clause,
valueMap = state.valueMap.put(inst, resultTerm)
).also { result = it }
}
checkReachabilityIncremental(traverserState, checks)
return result
}
protected open suspend fun traverseJumpInst(traverserState: TraverserState, inst: JumpInst): TraverserState? {
checkReachabilityIncremental(
traverserState,
ConditionCheckQuery(
UpdateOnlyQuery(persistentSymbolicState()) { state ->
pathSelector += (state + inst.parent) to inst.successor
state
}
)
)
return null
}
protected open suspend fun traverseReturnInst(traverserState: TraverserState, inst: ReturnInst): TraverserState? {
val stackTrace = traverserState.stackTrace
val stackTraceElement = stackTrace.lastOrNull()
val receiver = stackTraceElement?.instruction
val result = when {
receiver == null -> {
checkReachabilityIncremental(
traverserState,
ConditionCheckQuery(
UpdateAndReportQuery(
persistentSymbolicState(),
{ state -> state },
{ state, parameters -> retrieveFinalInfoAndReport(inst, parameters, state) }
)
)
)
return null
}
inst.hasReturnValue && receiver.isNameDefined -> {
val returnTerm = traverserState.mkTerm(inst.returnValue)
traverserState.copy(
valueMap = stackTraceElement.valueMap.put(receiver, returnTerm),
stackTrace = stackTrace.removeAt(stackTrace.lastIndex)
)
}
else -> traverserState.copy(
valueMap = stackTraceElement.valueMap,
stackTrace = stackTrace.removeAt(stackTrace.lastIndex)
)
}
val nextInst = receiver.parent.indexOf(receiver) + 1
traverseBlock(result, receiver.parent, nextInst)
return null
}
protected open suspend fun traverseSwitchInst(traverserState: TraverserState, inst: SwitchInst): TraverserState? {
val key = traverserState.mkTerm(inst.key)
checkReachabilityIncremental(
traverserState,
ConditionCheckQuery(buildList {
for ((value, branch) in inst.branches) {
val path = PathClause(
PathClauseType.CONDITION_CHECK,
inst,
path { (key eq traverserState.mkTerm(value)) equality true }
)
val pathState = persistentSymbolicState() + path
add(UpdateOnlyQuery(pathState) { state ->
val newState = state + inst.parent
pathSelector += newState to branch
newState
})
}
val defaultPath = PathClause(
PathClauseType.CONDITION_CHECK,
inst,
path { key `!in` inst.operands.map { traverserState.mkTerm(it) } }
)
val defaultState = persistentSymbolicState() + defaultPath
add(UpdateOnlyQuery(defaultState) { state ->
val newState = state + inst.parent
pathSelector += newState to inst.default
newState
})
})
)
return null
}
protected open suspend fun traverseTableSwitchInst(
traverserState: TraverserState,
inst: TableSwitchInst
): TraverserState? {
val key = traverserState.mkTerm(inst.index)
val min = inst.range.first
checkReachabilityIncremental(
traverserState,
ConditionCheckQuery(buildList {
for ((index, branch) in inst.branches.withIndex()) {
val path = PathClause(
PathClauseType.CONDITION_CHECK,
inst,
path { (key eq const(min + index)) equality true }
)
val pathState = persistentSymbolicState() + path
add(UpdateOnlyQuery(pathState) { state ->
val newState = state + inst.parent
pathSelector += newState to branch
newState
})
}
val defaultPath = PathClause(
PathClauseType.CONDITION_CHECK,
inst,
path { key `!in` inst.range.map { const(it) } }
)
val defaultState = persistentSymbolicState() + defaultPath
add(UpdateOnlyQuery(defaultState) { state ->
val newState = state + inst.parent
pathSelector += newState to inst.default
newState
})
})
)
return null
}
protected open suspend fun traverseThrowInst(traverserState: TraverserState, inst: ThrowInst): TraverserState? {
val throwableTerm = traverserState.mkTerm(inst.throwable)
val throwClause = StateClause(
inst,
state { `throw`(throwableTerm) }
)
val checks = nullabilityCheckInc(traverserState, inst, throwableTerm).withHandler { state, parameters ->
throwExceptionAndReport(
state + throwClause,
parameters,
inst,
throwableTerm
)
}
checkReachabilityIncremental(traverserState, checks)
return null
}
protected open suspend fun traverseUnreachableInst(
traverserState: TraverserState,
inst: UnreachableInst
): TraverserState? {
return null
}
protected open suspend fun traverseUnknownValueInst(
traverserState: TraverserState,
inst: UnknownValueInst
): TraverserState? {
return unreachable("Unexpected visit of $inst in symbolic traverser")
}
protected open suspend fun nullabilityCheckInc(
checkState: TraverserState,
inst: Instruction,
term: Term
): OptionalErrorCheckQuery {
if (term in checkState.nullCheckedTerms) return EmptyQuery()
if (term is ConstClassTerm) return EmptyQuery()
if (term is StaticClassRefTerm) return EmptyQuery()
if (term.isThis) return EmptyQuery()
val nullityClause = PathClause(
PathClauseType.NULL_CHECK,
inst,
path { (term eq null) equality true }
)
val noExceptionConstraints = persistentSymbolicState() + nullityClause.inverse()
val exceptionConstraints = persistentSymbolicState() + nullityClause
return ExceptionCheckQuery(
UpdateOnlyQuery(noExceptionConstraints) { noExceptionState ->
noExceptionState.copy(nullCheckedTerms = noExceptionState.nullCheckedTerms.add(term))
},
ReportQuery(exceptionConstraints) { exceptionState, parameters ->
throwExceptionAndReport(exceptionState, parameters, inst, generate(nullptrClass.symbolicClass))
}
)
}
protected open suspend fun boundsCheckInc(
state: TraverserState,
inst: Instruction,
index: Term,
length: Term
): OptionalErrorCheckQuery {
if (index to length in state.boundCheckedTerms) return EmptyQuery()
val zeroClause = PathClause(
PathClauseType.BOUNDS_CHECK,
inst,
path { (index ge 0) equality false }
)
val lengthClause = PathClause(
PathClauseType.BOUNDS_CHECK,
inst,
path { (index lt length) equality false }
)
val noExceptionConstraints = persistentSymbolicState() + zeroClause.inverse() + lengthClause.inverse()
val zeroCheckConstraints = persistentSymbolicState() + zeroClause
val lengthCheckConstraints = persistentSymbolicState() + lengthClause
return ExceptionCheckQuery(
UpdateOnlyQuery(noExceptionConstraints) { noExceptionState ->
noExceptionState.copy(boundCheckedTerms = noExceptionState.boundCheckedTerms.add(index to length))
},
ReportQuery(zeroCheckConstraints) { exceptionState, parameters ->
throwExceptionAndReport(exceptionState, parameters, inst, generate(arrayIndexOOBClass.symbolicClass))
},
ReportQuery(lengthCheckConstraints) { exceptionState, parameters ->
throwExceptionAndReport(exceptionState, parameters, inst, generate(arrayIndexOOBClass.symbolicClass))
}
)
}
protected open suspend fun newArrayBoundsCheckInc(
state: TraverserState,
inst: Instruction,
index: Term
): OptionalErrorCheckQuery {
if (index to index in state.boundCheckedTerms) return EmptyQuery()
val zeroClause = PathClause(
PathClauseType.BOUNDS_CHECK,
inst,
path { (index ge 0) equality false }
)
val noExceptionConstraints = persistentSymbolicState() + zeroClause.inverse()
val zeroCheckConstraints = persistentSymbolicState() + zeroClause
return ExceptionCheckQuery(
UpdateOnlyQuery(noExceptionConstraints) { noExceptionState ->
noExceptionState.copy(boundCheckedTerms = noExceptionState.boundCheckedTerms.add(index to index))
},
ReportQuery(zeroCheckConstraints) { exceptionState, parameters ->
throwExceptionAndReport(exceptionState, parameters, inst, generate(negativeArrayClass.symbolicClass))
}
)
}
protected open suspend fun typeCheckInc(
state: TraverserState,
inst: Instruction,
term: Term,
type: KexType
): OptionalErrorCheckQuery {
if (type !is KexPointer) return EmptyQuery()
val previouslyCheckedType = state.typeCheckedTerms[term]
val currentlyCheckedType = type.getKfgType(ctx.types)
if (previouslyCheckedType != null && currentlyCheckedType.isSubtypeOfCached(previouslyCheckedType)) {
return EmptyQuery()
}
val typeClause = PathClause(
PathClauseType.TYPE_CHECK,
inst,
path { (term `is` type) equality false }
)
val noExceptionConstraints = persistentSymbolicState() + typeClause.inverse()
val typeCheckConstraints = persistentSymbolicState() + typeClause
return ExceptionCheckQuery(
UpdateOnlyQuery(noExceptionConstraints) { noExceptionState ->
noExceptionState.copy(
typeCheckedTerms = noExceptionState.typeCheckedTerms.put(
term,
currentlyCheckedType
)
)
},
ReportQuery(typeCheckConstraints) { exceptionState, parameters ->
throwExceptionAndReport(exceptionState, parameters, inst, generate(classCastClass.symbolicClass))
}
)
}
@Suppress("DEPRECATION")
@Deprecated("Use incremental API")
protected open suspend fun nullabilityCheck(
state: TraverserState,
inst: Instruction,
term: Term
): TraverserState? {
if (term in state.nullCheckedTerms) return state
if (term is ConstClassTerm) return state
if (term is StaticClassRefTerm) return state
if (term.isThis) return state
val persistentState = state.symbolicState
val nullityClause = PathClause(
PathClauseType.NULL_CHECK,
inst,
path { (term eq null) equality true }
)
checkExceptionAndReport(
state + nullityClause,
inst,
generate(nullptrClass.symbolicClass)
)
return checkReachability(
state.copy(
symbolicState = persistentState + nullityClause.inverse(),
nullCheckedTerms = state.nullCheckedTerms.add(term)
), inst
)
}
@Suppress("DEPRECATION")
@Deprecated("Use incremental API")
protected open suspend fun boundsCheck(
state: TraverserState,
inst: Instruction,
index: Term,
length: Term
): TraverserState? {
if (index to length in state.boundCheckedTerms) return state
val persistentState = state.symbolicState
val zeroClause = PathClause(
PathClauseType.BOUNDS_CHECK,
inst,
path { (index ge 0) equality false }
)
val lengthClause = PathClause(
PathClauseType.BOUNDS_CHECK,
inst,
path { (index lt length) equality false }
)
checkExceptionAndReport(
state + zeroClause,
inst,
generate(arrayIndexOOBClass.symbolicClass)
)
checkExceptionAndReport(
state + lengthClause,
inst,
generate(arrayIndexOOBClass.symbolicClass)
)
return checkReachability(
state.copy(
symbolicState = persistentState + zeroClause.inverse() + lengthClause.inverse(),
boundCheckedTerms = state.boundCheckedTerms.add(index to length)
), inst
)
}
@Suppress("DEPRECATION")
@Deprecated("Use incremental API")
protected open suspend fun newArrayBoundsCheck(
state: TraverserState,
inst: Instruction,
index: Term
): TraverserState? {
if (index to index in state.boundCheckedTerms) return state
val persistentState = state.symbolicState
val zeroClause = PathClause(
PathClauseType.BOUNDS_CHECK,
inst,
path { (index ge 0) equality false }
)
checkExceptionAndReport(
state + zeroClause,
inst,
generate(negativeArrayClass.symbolicClass)
)
return checkReachability(
state.copy(
symbolicState = persistentState + zeroClause.inverse(),
boundCheckedTerms = state.boundCheckedTerms.add(index to index)
), inst
)
}
@Suppress("DEPRECATION")
@Deprecated("Use incremental API")
protected open suspend fun typeCheck(
state: TraverserState,
inst: Instruction,
term: Term,
type: KexType
): TraverserState? {
if (type !is KexPointer) return state
val previouslyCheckedType = state.typeCheckedTerms[term]
val currentlyCheckedType = type.getKfgType(ctx.types)
if (previouslyCheckedType != null && currentlyCheckedType.isSubtypeOfCached(previouslyCheckedType)) {
return state
}
val persistentState = state.symbolicState
val typeClause = PathClause(
PathClauseType.TYPE_CHECK,
inst,
path { (term `is` type) equality false }
)
checkExceptionAndReport(
state + typeClause,
inst,
generate(classCastClass.symbolicClass)
)
return checkReachability(
state.copy(
symbolicState = persistentState + typeClause.inverse(),
typeCheckedTerms = state.typeCheckedTerms.put(term, currentlyCheckedType)
), inst
)
}
protected open suspend fun checkReachabilityIncremental(
state: TraverserState,
checks: IncrementalQuery
) {
when (checks) {
is EmptyQuery -> checks.action(state)
is ExceptionCheckQuery -> {
val results = checkIncremental(rootMethod, state.symbolicState, buildList {
add(checks.noErrorQuery.query)
addAll(checks.errorQueries.map { it.query })
})
if (results[0] != null) {
checks.noErrorQuery.action(state + checks.noErrorQuery.query)
}
for (index in checks.errorQueries.indices) {
val currentResult = results[index + 1] ?: continue
val currentQuery = checks.errorQueries[index]
val newState = state + currentQuery.query
when (currentQuery) {
is UpdateOnlyQuery -> currentQuery.action(newState)
is UpdateAndReportQuery -> {
currentQuery.action(newState)
currentQuery.reportAction(newState, currentResult)
}
is ReportQuery -> currentQuery.action(newState, currentResult)
}
}
}
is ConditionCheckQuery -> {
val results = checkIncremental(rootMethod, state.symbolicState, checks.queries.map { it.query })
for ((result, query) in results.zip(checks.queries)) {
if (result != null) {
val newState = state + query.query
when (query) {
is UpdateOnlyQuery -> query.action(newState)
is UpdateAndReportQuery -> {
query.action(newState)
query.reportAction(newState, result)
}
}
}
}
}
}
}
@Suppress("DEPRECATION")
@Deprecated("Use incremental API")
protected open suspend fun checkReachability(
state: TraverserState,
inst: Instruction
): TraverserState? {
if (inst !is TerminateInst) return state
return check(rootMethod, state.symbolicState)?.let { state }
}
@Suppress("DEPRECATION")
@Deprecated("Use incremental API")
protected open suspend fun checkExceptionAndReport(
state: TraverserState,
inst: Instruction,
throwable: Term
) {
val params = check(rootMethod, state.symbolicState) ?: return
throwExceptionAndReport(state, FullDescriptorContext(params.toState(), null), inst, throwable)
}
@Suppress("UnusedReceiverParameter", "DeprecatedCallableAddReplaceWith")
@Deprecated("Use incremental API")
private fun Parameters<Descriptor>.toState(): DescriptorContext = unreachable {
log.error("`Parameters<Descriptor>.toState(): DescriptorContext` is not implemented, because it is only necessary for deprecated API")
}
protected open suspend fun throwExceptionAndReport(
state: TraverserState,
parameters: FullDescriptorContext,
inst: Instruction,
throwable: Term
) {
val throwableType = throwable.type.getKfgType(types)
val catchFrame: Pair<BasicBlock, PersistentMap<Value, Term>>? = state.run {
var catcher = inst.parent.handlers.firstOrNull { throwableType.isSubtypeOfCached(it.exception) }
if (catcher != null) return@run catcher to this.valueMap
for (i in stackTrace.indices.reversed()) {
val block = stackTrace[i].instruction.parent
catcher = block.handlers.firstOrNull { throwableType.isSubtypeOfCached(it.exception) }
if (catcher != null) return@run catcher to stackTrace[i].valueMap
}
null
}
when {
catchFrame != null -> {
val (catchBlock, catchValueMap) = catchFrame
val catchInst = catchBlock.instructions.first { it is CatchInst } as CatchInst
pathSelector += state.copy(
valueMap = catchValueMap.put(catchInst, throwable),
blockPath = state.blockPath.add(inst.parent),
stackTrace = state.stackTrace.builder().also {
while (it.isNotEmpty() && it.last().method != catchBlock.method) it.removeLast()
if (it.isNotEmpty()) it.removeLast()
}.build()
) to catchBlock
}
else -> report(
inst,
parameters.initial.parameters,
"_throw_${throwableType.toString().replace("[/$.]".toRegex(), "_")}",
parameters.final?.parameters?.extractFinalParameters(throwable.type.javaName)
)
}
}
protected open fun retrieveFinalInfoAndReport(
inst: Instruction,
parametersInfo: FullDescriptorContext,
state: TraverserState
) {
val retValue = when ((inst as? ReturnInst)?.hasReturnValue) {
true -> inst.returnValue
else -> null
}
val retDescriptor = when (retValue) {
is Constant -> descriptor { const(retValue) }
else -> state.valueMap[retValue]?.let {
parametersInfo.final?.termToDescriptor?.get(it)
}
}
report(
inst,
parametersInfo.initial.parameters,
finalParameters = parametersInfo.final?.parameters?.extractFinalParameters(retDescriptor)
)
}
protected open fun report(
inst: Instruction,
parameters: Parameters<Descriptor>,
testPostfix: String = "",
finalParameters: FinalParameters<Descriptor>? = null
): Boolean {
val generator = UnsafeGenerator(
ctx,
rootMethod,
rootMethod.klassName + testPostfix + testIndex.getAndIncrement()
)
generator.generate(parameters, finalParameters)
val testFile = generator.emit()
return try {
compilerHelper.compileFile(testFile)
true
} catch (e: CompilationException) {
log.error("Failed to compile test file $testFile")
false
}
}
@Suppress("DeprecatedCallableAddReplaceWith")
@Deprecated("Use incremental API")
protected open suspend fun check(method: Method, state: SymbolicState): Parameters<Descriptor>? =
method.checkAsync(ctx, state)
protected open suspend fun checkIncremental(
method: Method,
state: SymbolicState,
queries: List<SymbolicState>
): List<FullDescriptorContext?> =
method.checkAsyncIncremental(ctx, state, queries)
@Suppress("NOTHING_TO_INLINE")
protected inline fun PathClause.inverse(): PathClause = this.copy(
predicate = this.predicate.inverse(ctx.random)
)
}
| 9 | Kotlin | 20 | 28 | 459dd8cb1c5b1512b5a920260cd0ebe503861b3e | 53,949 | kex | Apache License 2.0 |
smali/src/main/kotlin/com/github/netomi/bat/smali/disassemble/LocalVariableCollector.kt | netomi | 265,488,804 | false | {"Kotlin": 1925501, "Smali": 713862, "ANTLR": 25494, "Shell": 12074, "Java": 2326} | /*
* Copyright (c) 2020-2022 Thomas Neidhart.
*
* 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.tinygears.bat.smali.disassemble
import org.tinygears.bat.dexfile.DexFile
import org.tinygears.bat.dexfile.NO_INDEX
import org.tinygears.bat.dexfile.debug.*
import org.tinygears.bat.dexfile.debug.visitor.DebugSequenceVisitor
internal class LocalVariableCollector(private val debugState: MutableMap<Int, MutableList<String>>,
private val localVariableInfos: Array<LocalVariableInfo?>,
private val registerPrinter: RegisterPrinter) : DebugSequenceVisitor {
private var codeOffset: Int = 0
override fun visitAnyDebugInstruction(dexFile: DexFile, debugInfo: DebugInfo, instruction: DebugInstruction) {}
override fun visitAdvanceLineAndPC(dexFile: DexFile, debugInfo: DebugInfo, instruction: DebugAdvanceLineAndPC) {
codeOffset += instruction.addrDiff
}
override fun visitAdvancePC(dexFile: DexFile, debugInfo: DebugInfo, instruction: DebugAdvancePC) {
codeOffset += instruction.addrDiff
}
override fun visitEndLocal(dexFile: DexFile, debugInfo: DebugInfo, instruction: DebugEndLocal) {
val info = buildString {
val registerNum = instruction.registerNum
append(".end local ")
append(registerPrinter.formatRegister(registerNum))
handleGenericLocal(registerNum, this)
}
addDebugInfo(codeOffset, info)
}
override fun visitRestartLocal(dexFile: DexFile, debugInfo: DebugInfo, instruction: DebugRestartLocal) {
val info = buildString {
val registerNum = instruction.registerNum
append(".restart local ")
append(registerPrinter.formatRegister(registerNum))
handleGenericLocal(registerNum, this)
}
addDebugInfo(codeOffset, info)
}
override fun visitStartLocal(dexFile: DexFile, debugInfo: DebugInfo, instruction: DebugStartLocal) {
handleStartLocal(dexFile, instruction.registerNum, instruction.nameIndex, instruction.typeIndex, NO_INDEX)
}
override fun visitStartLocalExtended(dexFile: DexFile, debugInfo: DebugInfo, instruction: DebugStartLocalExtended) {
handleStartLocal(dexFile, instruction.registerNum, instruction.nameIndex, instruction.typeIndex, instruction.sigIndex)
}
private fun handleStartLocal(dexFile: DexFile, registerNum: Int, nameIndex: Int, typeIndex: Int, sigIndex: Int) {
localVariableInfos[registerNum] = LocalVariableInfo(
dexFile.getStringNullable(nameIndex),
dexFile.getTypeOrNull(typeIndex)?.type,
dexFile.getStringNullable(sigIndex)
)
val info = buildString {
append(".local ")
append(registerPrinter.formatRegister(registerNum))
append(", ")
append("\"")
if (nameIndex != NO_INDEX) {
append(dexFile.getString(nameIndex))
}
append("\"")
if (typeIndex != NO_INDEX) {
append(":")
append(dexFile.getType(typeIndex))
}
if (sigIndex != NO_INDEX) {
append(", \"")
append(dexFile.getString(sigIndex))
append("\"")
}
}
addDebugInfo(codeOffset, info)
}
private fun handleGenericLocal(registerNum: Int, sb: StringBuilder) {
val localVariableInfo = localVariableInfos[registerNum]
localVariableInfo?.apply {
sb.append(" # ")
if (name != null) {
sb.append("\"")
sb.append(name)
sb.append("\"")
} else {
sb.append("null")
}
sb.append(":")
sb.append(type)
if (signature != null) {
sb.append(", \"")
sb.append(signature)
sb.append("\"")
}
}
}
private fun addDebugInfo(offset: Int, info: String) {
val infos = debugState.computeIfAbsent(offset) { ArrayList() }
infos.add(info)
}
}
internal class LocalVariableInfo internal constructor(val name: String?, val type: String?, val signature: String?)
| 1 | Kotlin | 3 | 10 | 5f5ec931c47dd34f14bd97230a29413ef1cf219c | 4,842 | bat | Apache License 2.0 |
sphinx/screens/dashboard/dashboard/src/main/java/chat/sphinx/dashboard/ui/adapter/ChatListAdapter.kt | stakwork | 340,103,148 | false | null | package chat.sphinx.dashboard.ui.adapter
import android.graphics.Color
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.ImageView
import androidx.lifecycle.*
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import app.cash.exhaustive.Exhaustive
import chat.sphinx.concept_image_loader.Disposable
import chat.sphinx.concept_image_loader.ImageLoader
import chat.sphinx.concept_image_loader.ImageLoaderOptions
import chat.sphinx.concept_image_loader.Transformation
import chat.sphinx.concept_user_colors_helper.UserColorsHelper
import chat.sphinx.dashboard.R
import chat.sphinx.dashboard.databinding.LayoutChatListChatHolderBinding
import chat.sphinx.dashboard.ui.ChatListViewModel
import chat.sphinx.dashboard.ui.collectChatViewState
import chat.sphinx.dashboard.ui.currentChatViewState
import chat.sphinx.resources.*
import chat.sphinx.wrapper_chat.*
import chat.sphinx.wrapper_common.DateTime
import chat.sphinx.wrapper_common.invite.*
import chat.sphinx.wrapper_common.lightning.asFormattedString
import chat.sphinx.wrapper_common.util.getInitials
import chat.sphinx.wrapper_message.*
import io.matthewnelson.android_feature_screens.util.gone
import io.matthewnelson.android_feature_screens.util.goneIfFalse
import io.matthewnelson.android_feature_screens.util.invisibleIfFalse
import io.matthewnelson.android_feature_screens.util.visible
import io.matthewnelson.android_feature_viewmodel.util.OnStopSupervisor
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.*
import kotlin.collections.ArrayList
internal class ChatListAdapter(
private val recyclerView: RecyclerView,
private val layoutManager: LinearLayoutManager,
private val imageLoader: ImageLoader<ImageView>,
private val lifecycleOwner: LifecycleOwner,
private val onStopSupervisor: OnStopSupervisor,
private val viewModel: ChatListViewModel,
private val userColorsHelper: UserColorsHelper
): RecyclerView.Adapter<ChatListAdapter.ChatViewHolder>(), DefaultLifecycleObserver {
private inner class Diff(
private val oldList: List<DashboardChat>,
private val newList: List<DashboardChat>,
): DiffUtil.Callback() {
override fun getOldListSize(): Int {
return oldList.size
}
override fun getNewListSize(): Int {
return newList.size
}
@Volatile
var sameList: Boolean = oldListSize == newListSize
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return try {
val old = oldList[oldItemPosition]
val new = newList[newItemPosition]
val same: Boolean = when {
old is DashboardChat.Active && new is DashboardChat.Active -> {
old.chat.id == new.chat.id &&
old.chat.latestMessageId == new.chat.latestMessageId
}
old is DashboardChat.Inactive.Invite && new is DashboardChat.Inactive.Invite -> {
old.invite?.status == new.invite?.status &&
old.invite?.id == new.invite?.id &&
old.contact.status == new.contact.status
}
old is DashboardChat.Inactive && new is DashboardChat.Inactive -> {
old.chatName == new.chatName
}
else -> {
false
}
}
if (sameList) {
sameList = same
}
same
} catch (e: IndexOutOfBoundsException) {
sameList = false
false
}
}
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return try {
val old = oldList[oldItemPosition]
val new = newList[newItemPosition]
val same: Boolean = when {
old is DashboardChat.Active && new is DashboardChat.Active -> {
old.chat.type == new.chat.type &&
old.chatName == new.chatName &&
old.chat.isMuted == new.chat.isMuted &&
old.chat.seen == new.chat.seen &&
old.chat.photoUrl == new.chat.photoUrl
}
old is DashboardChat.Inactive.Invite && new is DashboardChat.Inactive.Invite -> {
old.invite?.status == new.invite?.status &&
old.invite?.id == new.invite?.id &&
old.contact.status == new.contact.status
}
old is DashboardChat.Inactive && new is DashboardChat.Inactive -> {
old.chatName == new.chatName
}
else -> {
false
}
}
if (sameList) {
sameList = same
}
same
} catch (e: IndexOutOfBoundsException) {
sameList = false
false
}
}
}
private val dashboardChats = ArrayList<DashboardChat>(viewModel.currentChatViewState.list)
override fun onStart(owner: LifecycleOwner) {
super.onStart(owner)
onStopSupervisor.scope.launch(viewModel.mainImmediate) {
viewModel.collectChatViewState { viewState ->
if (dashboardChats.isEmpty()) {
dashboardChats.addAll(viewState.list)
[email protected]()
} else {
val diff = Diff(dashboardChats, viewState.list)
withContext(viewModel.dispatchers.default) {
DiffUtil.calculateDiff(diff)
}.let { result ->
if (!diff.sameList) {
val firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition()
dashboardChats.clear()
dashboardChats.addAll(viewState.list)
result.dispatchUpdatesTo(this@ChatListAdapter)
if (
firstVisibleItemPosition == 0 &&
recyclerView.scrollState == RecyclerView.SCROLL_STATE_IDLE
) {
recyclerView.scrollToPosition(0)
}
}
}
}
}
}
}
override fun getItemCount(): Int {
return dashboardChats.size
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ChatListAdapter.ChatViewHolder {
val binding = LayoutChatListChatHolderBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
return ChatViewHolder(binding)
}
override fun onBindViewHolder(holder: ChatListAdapter.ChatViewHolder, position: Int) {
holder.bind(position)
}
private val today00: DateTime by lazy {
DateTime.getToday00()
}
private val imageLoaderOptions: ImageLoaderOptions by lazy {
ImageLoaderOptions.Builder()
.placeholderResId(R.drawable.ic_profile_avatar_circle)
.transformation(Transformation.CircleCrop)
.build()
}
inner class ChatViewHolder(
private val binding: LayoutChatListChatHolderBinding
): RecyclerView.ViewHolder(binding.root), DefaultLifecycleObserver {
private var disposable: Disposable? = null
private var dChat: DashboardChat? = null
private var badgeJob: Job? = null
init {
binding.layoutConstraintChatHolder.setOnClickListener {
dChat?.let { dashboardChat ->
@Exhaustive
when (dashboardChat) {
is DashboardChat.Active.Conversation -> {
lifecycleOwner.lifecycleScope.launch {
viewModel.dashboardNavigator.toChatContact(
dashboardChat.chat.id,
dashboardChat.contact.id
)
}
}
is DashboardChat.Active.GroupOrTribe -> {
lifecycleOwner.lifecycleScope.launch {
if (dashboardChat.chat.type.isGroup()) {
viewModel.dashboardNavigator.toChatGroup(dashboardChat.chat.id)
} else if (dashboardChat.chat.type.isTribe()) {
viewModel.dashboardNavigator.toChatTribe(dashboardChat.chat.id)
}
}
}
is DashboardChat.Inactive.Conversation -> {
lifecycleOwner.lifecycleScope.launch {
viewModel.dashboardNavigator.toChatContact(
null,
dashboardChat.contact.id
)
}
}
is DashboardChat.Inactive.Invite -> {
dashboardChat.invite?.let { invite ->
lifecycleOwner.lifecycleScope.launch {
if (invite.status.isReady() || invite.status.isDelivered()) {
viewModel.dashboardNavigator.toQRCodeDetail(
invite.inviteString.value,
binding.root.context.getString(
R.string.invite_qr_code_header_name
)
)
} else if (invite.status.isPaymentPending()) {
viewModel.payForInvite(invite)
} else if (invite.status.isExpired()) {
viewModel.deleteInvite(invite)
}
}
}
}
}
}
}
}
fun bind(position: Int) {
binding.apply {
val dashboardChat: DashboardChat = dashboardChats.getOrNull(position) ?: let {
dChat = null
return
}
dChat = dashboardChat
disposable?.dispose()
badgeJob?.cancel()
// Set Defaults
layoutConstraintChatHolderBorder.goneIfFalse(position != dashboardChats.lastIndex)
textViewDashboardChatHolderName.setTextColorExt(android.R.color.white)
textViewChatHolderMessage.setTextColorExt(R.color.placeholderText)
textViewChatHolderMessage.setTextFont(R.font.roboto_regular)
textViewDashboardChatHolderBadgeCount.invisibleIfFalse(false)
// Image
dashboardChat.photoUrl.let { url ->
includeDashboardChatHolderInitial.apply {
imageViewChatPicture.goneIfFalse(url != null)
textViewInitials.goneIfFalse(url == null)
}
if (url != null) {
onStopSupervisor.scope.launch(viewModel.dispatchers.mainImmediate) {
imageLoader.load(
includeDashboardChatHolderInitial.imageViewChatPicture,
url.value,
imageLoaderOptions
)
}
} else {
includeDashboardChatHolderInitial.textViewInitials.text =
dashboardChat.chatName?.getInitials() ?: ""
onStopSupervisor.scope.launch(viewModel.mainImmediate) {
includeDashboardChatHolderInitial.textViewInitials
.setInitialsColor(
dashboardChat.getColorKey()?.let { colorKey ->
Color.parseColor(
userColorsHelper.getHexCodeForKey(
colorKey,
root.context.getRandomHexCode()
)
)
},
R.drawable.chat_initials_circle
)
}
}
}
// Name
val chatName = if (dashboardChat is DashboardChat.Inactive.Invite) {
dashboardChat.getChatName(root.context)
} else if (dashboardChat.chatName != null) {
dashboardChat.chatName
} else {
// Should never make it here, but just in case...
textViewDashboardChatHolderName.setTextColorExt(R.color.primaryRed)
textViewChatHolderCenteredName.setTextColorExt(R.color.primaryRed)
root.context.getString(R.string.null_name_error)
}
textViewDashboardChatHolderName.text = chatName
textViewChatHolderCenteredName.text = chatName
// Lock
val encryptedChat = dashboardChat.isEncrypted()
imageViewChatHolderLock.invisibleIfFalse(encryptedChat)
imageViewChatHolderCenteredLock.invisibleIfFalse(encryptedChat)
val chatHasMessages = (dashboardChat as? DashboardChat.Active)?.message != null
val activeChatOrInvite = ((dashboardChat is DashboardChat.Active && chatHasMessages) || dashboardChat is DashboardChat.Inactive.Invite)
layoutConstraintDashboardChatHolderMessage.invisibleIfFalse(activeChatOrInvite)
layoutConstraintDashboardChatNoMessageHolder.invisibleIfFalse(!activeChatOrInvite)
// Time
textViewChatHolderTime.text = dashboardChat.getDisplayTime(today00)
// Message
val messageText = dashboardChat.getMessageText(root.context)
val hasUnseenMessages = dashboardChat.hasUnseenMessages()
if (messageText == root.context.getString(R.string.decryption_error)) {
textViewChatHolderMessage.setTextColorExt(R.color.primaryRed)
} else {
textViewChatHolderMessage.setTextColorExt(if (hasUnseenMessages) R.color.text else R.color.placeholderText)
}
textViewChatHolderMessage.setTextFont(if (hasUnseenMessages) R.font.roboto_bold else R.font.roboto_regular)
textViewChatHolderMessage.text = messageText
handleInviteLayouts()
handleUnseenMessageCount()
// Notification
if (dashboardChat is DashboardChat.Active) {
imageViewChatHolderNotification.invisibleIfFalse(dashboardChat.chat.isMuted())
} else {
imageViewChatHolderNotification.invisibleIfFalse(false)
}
}
}
private fun handleInviteLayouts() {
dChat?.let { nnDashboardChat ->
binding.apply {
textViewChatHolderTime.visible
textViewChatHolderMessageIcon.gone
layoutConstraintDashboardChatHolderContact.visible
layoutConstraintDashboardChatHolderInvite.gone
layoutConstraintDashboardChatHolderInvitePrice.gone
if (nnDashboardChat is DashboardChat.Inactive.Invite) {
textViewChatHolderTime.gone
textViewChatHolderMessage.setTextFont(R.font.roboto_bold)
textViewChatHolderMessage.setTextColorExt(R.color.text)
layoutConstraintDashboardChatHolderContact.gone
layoutConstraintDashboardChatHolderInvite.visible
nnDashboardChat.getInviteIconAndColor()?.let { iconAndColor ->
textViewChatHolderMessageIcon.visible
textViewChatHolderMessageIcon.text = getString(iconAndColor.first)
textViewChatHolderMessageIcon.setTextColor(getColor(iconAndColor.second))
}
nnDashboardChat.getInvitePrice()?.let { price ->
val paymentPending = nnDashboardChat.invite?.status?.isPaymentPending() == true
layoutConstraintDashboardChatHolderInvitePrice.goneIfFalse(paymentPending)
textViewDashboardChatHolderInvitePrice.text = price.asFormattedString()
}
}
}
}
}
private fun handleUnseenMessageCount() {
dChat?.let { nnDashboardChat ->
badgeJob = onStopSupervisor.scope.launch(viewModel.mainImmediate) {
nnDashboardChat.unseenMessageFlow?.collect { unseen ->
binding.textViewDashboardChatHolderBadgeCount.apply {
if (unseen != null && unseen > 0) {
text = unseen.toString()
}
if (nnDashboardChat is DashboardChat.Active) {
alpha = if (nnDashboardChat.chat.isMuted()) 0.2f else 1.0f
backgroundTintList = binding.getColorStateList(if (nnDashboardChat.chat.isMuted()) {
R.color.washedOutReceivedText
} else {
R.color.primaryBlue
}
)
}
invisibleIfFalse(nnDashboardChat.hasUnseenMessages())
}
}
}
}
}
override fun onStart(owner: LifecycleOwner) {
super.onStart(owner)
badgeJob?.let {
if (!it.isActive) {
handleUnseenMessageCount()
}
}
}
init {
lifecycleOwner.lifecycle.addObserver(this)
}
}
init {
lifecycleOwner.lifecycle.addObserver(this)
}
}
| 90 | null | 7 | 18 | a28cbb8174ef7874d156f31e22023b014cba6029 | 19,828 | sphinx-kotlin | MIT License |
vtp-pensjon-application/src/main/kotlin/no/nav/pensjon/vtp/testmodell/load/StatsborgerskapTemplate.kt | navikt | 254,055,233 | false | null | package no.nav.pensjon.vtp.testmodell.load
import no.nav.pensjon.vtp.testmodell.kodeverk.Endringstype
import no.nav.pensjon.vtp.testmodell.personopplysning.Landkode
import java.time.LocalDate
data class StatsborgerskapTemplate(
val fom: LocalDate?,
val tom: LocalDate?,
val endringstype: Endringstype?,
val endringstidspunkt: LocalDate?,
val land: Landkode?
)
| 14 | Kotlin | 0 | 2 | cd270b5f698c78c1eee978cd24bd788163c06a0c | 382 | vtp-pensjon | MIT License |
VCL/src/main/java/io/velocitycareerlabs/api/entities/VCLOrganizationsSearchDescriptor.kt | velocitycareerlabs | 525,006,413 | false | null | /**
* Created by <NAME> on 24/06/2021.
*
* Copyright 2022 Velocity Career Labs inc.
* SPDX-License-Identifier: Apache-2.0
*/
package io.velocitycareerlabs.api.entities
import io.velocitycareerlabs.impl.extensions.encode
data class VCLOrganizationsSearchDescriptor(
val filter: VCLFilter? = null,
val page: VCLPage? = null,
/**
* A array of tuples indicating the field to sort by
*/
val sort: List<List<String>>? = null,
/**
* Full Text search for the name property of the organization
* Matches on partials strings
* Prefer results that are the first word of the name, or first letter of a word
*/
val query: String? = null
) {
val queryParams = generateQueryParams()
private fun generateQueryParams(): String? {
val pFilterDid = filter?.did?.let { "$KeyFilterDid=$it" }
val pFilterServiceTypes = filter?.serviceTypes?.let { serviceTypes ->
"$KeyFilterServiceTypes=${serviceTypes.joinToString(separator = ",") { it.toString() }}" }
val pFilterCredentialTypes = filter?.credentialTypes?.let { credentialTypes ->
"$KeyFilterCredentialTypes=${credentialTypes.map { it.encode() }.joinToString(separator = ",") { it }}"}
val pSort = sort?.mapIndexed{index, list -> "$KeySort[$index]=${list.joinToString(separator = ",")}" }?.joinToString(separator = "&")
val pPageSkip = page?.skip?.encode()?.let { "$KeyPageSkip=${it}" }
val pPageSize = page?.size?.encode()?.let { "$KeyPageSize=${it}" }
val pQuery = query?.encode()?.let { "$KeyQueryQ=${it}" }
val qParams = listOfNotNull(
pFilterDid,
pFilterServiceTypes,
pFilterCredentialTypes,
pSort,
pPageSkip,
pPageSize,
pQuery
)
return if(qParams.isNotEmpty()) qParams.joinToString("&") else null
}
companion object CodingKeys {
const val KeyQueryQ = "q"
const val KeySort = "sort"
const val KeyFilterDid = "filter.did"
const val KeyFilterServiceTypes = "filter.serviceTypes"
const val KeyFilterCredentialTypes = "filter.credentialTypes"
const val KeyPageSkip = "page.skip"
const val KeyPageSize = "page.size"
}
}
data class VCLFilter(
/**
* Filters organizations based on DIDs
*/
val did: String? = null,
/**
* Filters organizations based on Service Types e.g. [VCLServiceType]
*/
val serviceTypes: List<VCLServiceType>? = null,
/**
* Filters organizations based on credential types e.g. [EducationDegree]
*/
val credentialTypes: List<String>? = null
)
data class VCLPage(
/**
* The number of records to retrieve
*/
val size: String? = null,
/**
* The objectId to skip
*/
val skip: String? = null
)
| 0 | null | 0 | 2 | 160e938b2a3a676800e65aabec95c7badffbb4a6 | 2,860 | WalletAndroid | Apache License 2.0 |
web3lib/src/commonMain/kotlin/com/sonsofcrypto/web3lib/provider/utils/JsonElementExtensions.kt | sonsofcrypto | 454,978,132 | false | {"Kotlin": 1330889, "Swift": 970782, "Objective-C": 77663, "Jupyter Notebook": 20914, "Go": 20697, "C": 15793, "Java": 12789, "Shell": 4282, "JavaScript": 1718} | package com.sonsofcrypto.web3lib.provider.utils
import com.sonsofcrypto.web3lib.provider.model.QuantityHexString
import com.sonsofcrypto.web3lib.provider.model.toBigIntQnt
import com.sonsofcrypto.web3lib.provider.model.toIntQnt
import com.sonsofcrypto.web3lib.provider.model.toULongQnt
import com.sonsofcrypto.web3lib.utils.BigInt
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonPrimitive
fun JsonElement.stringValue(): String = (this as JsonPrimitive).content
fun JsonElement.toIntQnt(): Int = (this as JsonPrimitive)
.stringValue()
.toIntQnt()
fun JsonElement.toULongQnt(): ULong = (this as JsonPrimitive)
.stringValue()
.toULongQnt()
fun JsonElement.toBigIntQnt(): BigInt = (this as JsonPrimitive)
.stringValue()
.toBigIntQnt()
fun JsonPrimitiveQntHexStr(int: Int): JsonPrimitive = JsonPrimitive(QuantityHexString(int))
fun JsonPrimitiveQntHexStr(uint: UInt): JsonPrimitive = JsonPrimitive(QuantityHexString(uint))
fun JsonPrimitiveQntHexStr(long: Long): JsonPrimitive = JsonPrimitive(QuantityHexString(long))
fun JsonPrimitiveQntHexStr(ulong: ULong): JsonPrimitive = JsonPrimitive(QuantityHexString(ulong))
fun JsonPrimitiveQntHexStr(bigInt: BigInt): JsonPrimitive = JsonPrimitive(QuantityHexString(bigInt))
| 1 | Kotlin | 2 | 6 | d86df4845a1f60624dffa179ce6507ede3222186 | 1,279 | web3wallet | MIT License |
simplified-tests/src/test/java/org/nypl/simplified/tests/mocking/FakeAccountCredentialStorage.kt | ThePalaceProject | 367,082,997 | false | {"Kotlin": 3269830, "JavaScript": 853788, "Java": 374503, "CSS": 65407, "HTML": 49220, "Shell": 5017, "Ruby": 178} | package org.nypl.simplified.tests.mocking
import org.nypl.simplified.accounts.api.AccountAuthenticationCredentials
import org.nypl.simplified.accounts.api.AccountAuthenticationCredentialsStoreType
import org.nypl.simplified.accounts.api.AccountID
class FakeAccountCredentialStorage : AccountAuthenticationCredentialsStoreType {
private val store = mutableMapOf<AccountID, AccountAuthenticationCredentials>()
override fun get(account: AccountID): AccountAuthenticationCredentials? =
this.store[account]
override fun size(): Int =
this.store.size
override fun put(account: AccountID, credentials: AccountAuthenticationCredentials) {
this.store[account] = credentials
}
override fun delete(account: AccountID) {
this.store.remove(account)
}
}
| 1 | Kotlin | 4 | 8 | 330252fd69ba690962b87d5554f71f19a85df362 | 777 | android-core | Apache License 2.0 |
Corona-Warn-App/src/test/java/de/rki/coronawarnapp/ccl/dccwalletinfo/model/DccWalletInfoParserTest.kt | corona-warn-app | 268,027,139 | false | null | package de.rki.coronawarnapp.ccl.dccwalletinfo.model
import com.fasterxml.jackson.module.kotlin.readValue
import de.rki.coronawarnapp.util.serialization.SerializationModule
import io.kotest.matchers.shouldBe
import org.junit.jupiter.api.Test
import testhelpers.BaseTest
import testhelpers.extensions.toComparableJsonPretty
@Suppress("MaxLineLength")
internal class DccWalletInfoParserTest : BaseTest() {
private val mapper = SerializationModule.jacksonBaseMapper
@Test
fun `Deserialize DCCWalletInfo`() {
javaClass.classLoader!!.getResourceAsStream("ccl/dcc_wallet_info_output.json").use {
mapper.readValue<DccWalletInfo>(it) shouldBe dccWalletInfo
}
}
@Test
fun `Serialize DCCWalletInfo`() {
javaClass.classLoader!!.getResourceAsStream("ccl/dcc_wallet_info_output.json").bufferedReader().use {
mapper.writeValueAsString(dccWalletInfo).toComparableJsonPretty() shouldBe
it.readText().toComparableJsonPretty()
}
}
@Test
fun `Deserialize DCCWalletInfo with Reissuance`() {
javaClass.classLoader!!.getResourceAsStream("ccl/dcc_wallet_info_output_with_reissuance.json").use {
mapper.readValue<DccWalletInfo>(it) shouldBe dccWalletInfoWithReissuance
}
}
@Test
fun `Serialize DCCWalletInfo with Reissuance`() {
javaClass.classLoader!!.getResourceAsStream("ccl/dcc_wallet_info_output_with_reissuance.json").bufferedReader()
.use {
mapper.writeValueAsString(dccWalletInfoWithReissuance).toComparableJsonPretty() shouldBe
it.readText().toComparableJsonPretty()
}
}
@Test
fun `Deserialize DCCWalletInfo with Reissuance legacy`() {
javaClass.classLoader!!.getResourceAsStream("ccl/dcc_wallet_info_output_with_reissuance_legacy.json").use {
mapper.readValue<DccWalletInfo>(it) shouldBe dccWalletInfoWithReissuanceLegacy
}
}
@Test
fun `Serialize DCCWalletInfo with Reissuance legacy`() {
javaClass.classLoader!!.getResourceAsStream("ccl/dcc_wallet_info_output_with_reissuance_legacy.json").bufferedReader()
.use {
mapper.writeValueAsString(dccWalletInfoWithReissuanceLegacy).toComparableJsonPretty() shouldBe
it.readText().toComparableJsonPretty()
}
}
private val pluralTextIndexed = PluralText(
type = "plural",
quantity = null,
quantityParameterIndex = 0,
localizedText = mapOf(
"en" to QuantityText(
zero = "No time left",
one = "%u minute left",
two = "%u minutes left",
few = "%u minutes left",
many = "%u minutes left",
other = "%u minutes left"
)
),
parameters = listOf(
Parameters(
type = Parameters.Type.NUMBER,
value = 5.5
)
)
)
private val dccWalletInfoPluralIndexed = dccWalletInfo.copy(
vaccinationState = dccWalletInfo.vaccinationState.copy(
subtitleText = pluralTextIndexed
)
)
@Test
fun `Deserialize DCCWalletInfo - Plural Indexed`() {
javaClass.classLoader!!.getResourceAsStream("ccl/dcc_wallet_info_plural_indexed.json").use {
mapper.readValue<DccWalletInfo>(it) shouldBe dccWalletInfoPluralIndexed
}
}
@Test
fun `Serialize DCCWalletInfo - Plural Indexed`() {
javaClass.classLoader!!.getResourceAsStream("ccl/dcc_wallet_info_plural_indexed.json")
.bufferedReader().use {
mapper.writeValueAsString(dccWalletInfoPluralIndexed).toComparableJsonPretty() shouldBe
it.readText().toComparableJsonPretty()
}
}
@Test
fun `Deserialize DCCWalletInfo - CertificatesRevokedByInvalidationRules`() {
javaClass.classLoader!!.getResourceAsStream(certificatesRevokedByInvalidationRulesPath).use {
mapper.readValue<DccWalletInfo>(it) shouldBe dccWalletInfoWithCertificatesRevokedByInvalidationRules
}
}
@Test
fun `Serialize DCCWalletInfo - CertificatesRevokedByInvalidationRules`() {
javaClass.classLoader!!.getResourceAsStream(certificatesRevokedByInvalidationRulesPath).bufferedReader().use {
mapper.writeValueAsString(dccWalletInfoWithCertificatesRevokedByInvalidationRules)
.toComparableJsonPretty() shouldBe it.readText().toComparableJsonPretty()
}
}
}
private const val certificatesRevokedByInvalidationRulesPath =
"ccl/dcc_wallet_info_output_with_certificatesRevokedByInvalidationRules.json"
| 6 | null | 516 | 2,495 | d3833a212bd4c84e38a1fad23b282836d70ab8d5 | 4,736 | cwa-app-android | Apache License 2.0 |
app/src/main/java/ca/rovbot/flowtracker/repository/LogRepository.kt | spkdroid | 377,685,159 | false | null | package ca.rovbot.flowtracker.repository
import android.arch.persistence.room.Room
import android.content.Context
import ca.rovbot.flowtracker.model.PeriodLogTable
import ca.rovbot.flowtracker.repository.database.LogDatabase
class LogRepository(private val applicationContext: Context) {
private var database: LogDatabase? = null
val allLogs: List<PeriodLogTable>
get() = database!!.logDaoAccess.fetchAll()
init {
initDB()
}
private fun initDB() {
val DB_NAME = "LOGDATABASE"
database = Room.databaseBuilder(applicationContext, LogDatabase::class.java!!, DB_NAME)
.fallbackToDestructiveMigration()
.build()
}
fun addLog(logToBeAdded: PeriodLogTable) {
database!!.logDaoAccess.insertSingleSong(logToBeAdded)
}
fun deleteLog(logToBeDeleted: PeriodLogTable) {
database!!.logDaoAccess.deleteLog(logToBeDeleted)
}
fun clearTable() {
database!!.logDaoAccess.clearTable()
}
fun getLogById(Id: Int): PeriodLogTable {
return database!!.logDaoAccess.fetchLogByID(Id)
}
}
| 0 | Kotlin | 0 | 0 | 294f772e40bf3a036451cce1f3d9eeaacd7c6207 | 1,115 | FlowTracker | Apache License 2.0 |
src/main/java/no/nav/sbl/service/VeilederService.kt | navikt | 149,753,566 | false | {"Kotlin": 162825, "Dockerfile": 352, "Shell": 313} | package no.nav.sbl.service
import no.nav.common.client.nom.NomClient
import no.nav.common.client.nom.VeilederNavn
import no.nav.common.types.identer.NavIdent
import no.nav.sbl.rest.model.DecoratorDomain
import org.springframework.cache.annotation.Cacheable
open class VeilederService(private val nomClient: NomClient) {
@Cacheable("veilederCache")
open fun hentVeilederNavn(ident: String): DecoratorDomain.Saksbehandler {
val veilederNavn: VeilederNavn = nomClient.finnNavn(NavIdent(ident))
return DecoratorDomain.Saksbehandler(
ident,
veilederNavn.fornavn,
veilederNavn.etternavn
)
}
} | 2 | Kotlin | 0 | 0 | 05f5540079fb94f337ee56cdc0c45787645e6e76 | 662 | modiacontextholder | MIT License |
js/js.translator/testData/box/export/reservedModuleNameInExportedFile.kt | JetBrains | 3,432,266 | false | null | // IGNORE_BACKEND: JS
// EXPECTED_REACHABLE_NODES: 1270
// SKIP_MINIFICATION
// RUN_PLAIN_BOX_FUNCTION
// INFER_MAIN_MODULE
// MODULE: if
// FILE: lib.kt
@JsName("foo")
public fun foo(k: String): String = "O$k"
// FILE: test.js
function box() {
return this["if"].foo("K");
} | 184 | null | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 280 | kotlin | Apache License 2.0 |
app/src/main/java/com/bengisusahin/gallery/MainActivity.kt | bengisusaahin | 867,304,398 | false | {"Kotlin": 14638} | package com.bengisusahin.gallery
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.lifecycle.ViewModelProvider
import com.bengisusahin.gallery.presentation.GalleryScreen
import com.bengisusahin.gallery.presentation.GalleryViewModel
import com.bengisusahin.gallery.presentation.ui.theme.GalleryTheme
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
private val galleryViewModel: GalleryViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContent {
GalleryTheme {
GalleryScreen(galleryViewModel)
}
}
}
}
| 0 | Kotlin | 0 | 0 | 620de0e7ef11b0426e9daadcec96d45d56c260e7 | 1,231 | GeoGallery | Apache License 2.0 |
src/main/kotlin/me/nobaboy/nobaaddons/config/NobaConfig.kt | nobaboy | 867,566,026 | false | {"Kotlin": 197524, "Java": 4140} | package me.nobaboy.nobaaddons.config
import dev.isxander.yacl3.config.v2.api.SerialEntry
import me.nobaboy.nobaaddons.config.configs.*
class NobaConfig {
@SerialEntry
val version: Int = NobaConfigManager.CONFIG_VERSION
@SerialEntry
val general: GeneralConfig = GeneralConfig()
@SerialEntry
val uiAndVisuals: UIAndVisualsConfig = UIAndVisualsConfig()
@SerialEntry
val chat: ChatConfig = ChatConfig()
@SerialEntry
val crimsonIsle: CrimsonIsleConfig = CrimsonIsleConfig()
@SerialEntry
val dungeons: DungeonsConfig = DungeonsConfig()
} | 1 | Kotlin | 1 | 1 | 68410c38aa038c637fb0bdd9b6b8669eccf42f62 | 550 | NobaAddons | The Unlicense |
config/jacoco/jacocoConfig.kts | TW-Smart-CoE | 596,466,446 | false | null | apply plugin: 'jacoco'
jacoco {
toolVersion '0.8.7'
}
tasks.withType(Test) {
jacoco.includeNoLocationClasses = true
jacoco.excludes = ['jdk.internal.*']
}
def defaultFileFilter = [
// android
'**/R.class',
'**/R$*.class',
'**/BuildConfig.*',
'**/Manifest*.*',
'android/**/*.*',
'androidx/**/*.*',
'**/*Test*.*',
// dagger + hilt
'**/Hilt_*.*',
'**/*_HiltModules*.*',
'**/*_Provide*Factory*.*',
'**/*_Factory*.*',
'**/*_GeneratedInjector.*',
'dagger/hilt/**/codegen/*.*',
'hilt_aggregated_deps/*.*',
'**/AutoValue_*.*',
'**/*Directions$*',
'**/*Directions.*',
// custom
'**/ui/**',
'**/di/**',
'**/entity/**',
'**/model/**',
'**/developmenu/**',
'**/*Application*.*',
'**/MainActivity*.*',
]
def moduleFilter = [
'com/thoughtworks/car/core/*',
'com/thoughtworks/car/ui/*'
]
defaultFileFilter.addAll(moduleFilter)
project.ext.setProperty("jacocoFileFilter", defaultFileFilter)
| 3 | Kotlin | 0 | 3 | b7fa39bc5bf04f26e7572cca6d98135c8ffeed4d | 1,127 | Ark-Android-App-Template | Apache License 2.0 |
presentation/src/main/java/com/anytypeio/anytype/presentation/objects/LockedStateProvider.kt | anyproto | 647,371,233 | false | {"Kotlin": 10021359, "Java": 69306, "Shell": 11126, "Makefile": 1276} | package com.anytypeio.anytype.presentation.objects
import com.anytypeio.anytype.core_models.Id
import com.anytypeio.anytype.presentation.editor.Editor
interface LockedStateProvider {
fun isLocked(ctx: Id) : Boolean
class EditorLockedStateProvider(
private val storage: Editor.Storage
) : LockedStateProvider {
override fun isLocked(ctx: Id): Boolean {
val doc = storage.document.get().find { it.id == ctx }
return doc?.fields?.isLocked ?: false
}
}
object DataViewLockedStateProvider : LockedStateProvider {
// Sets or Collections can't be locked currently.
override fun isLocked(ctx: Id): Boolean = false
}
} | 34 | Kotlin | 26 | 309 | ca99b691a7d341931c232c7862ac469092f80657 | 699 | anytype-kotlin | RSA Message-Digest License |
play/plugin/src/main/kotlin/com/github/triplet/gradle/play/PlayPublisherExtension.kt | nicolas-raoul | 272,236,139 | true | {"Kotlin": 439175, "HTML": 390, "Java": 342} | package com.github.triplet.gradle.play
import com.android.build.gradle.api.ApkVariantOutput
import com.github.triplet.gradle.play.internal.PlayExtensionConfig
import com.github.triplet.gradle.play.internal.commitOrDefault
import com.github.triplet.gradle.play.internal.promoteTrackOrDefault
import com.github.triplet.gradle.play.internal.releaseStatusOrDefault
import com.github.triplet.gradle.play.internal.resolutionStrategyOrDefault
import com.github.triplet.gradle.play.internal.textToReleaseStatus
import com.github.triplet.gradle.play.internal.textToResolutionStrategy
import com.github.triplet.gradle.play.internal.trackOrDefault
import com.github.triplet.gradle.play.internal.updateProperty
import com.github.triplet.gradle.play.internal.userFractionOrDefault
import org.gradle.api.Action
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.InputFile
import org.gradle.api.tasks.Internal
import org.gradle.api.tasks.Nested
import org.gradle.api.tasks.Optional
import org.gradle.api.tasks.PathSensitive
import org.gradle.api.tasks.PathSensitivity
import java.io.File
import java.util.Collections
import java.util.IdentityHashMap
import kotlin.reflect.KMutableProperty1
/** The entry point for all GPP related configuration. */
open class PlayPublisherExtension @JvmOverloads constructor(
@get:Internal internal val name: String = "default" // Needed for Gradle
) {
@get:Internal
internal val _config = PlayExtensionConfig()
@get:Internal
internal val _children: MutableSet<PlayPublisherExtension> =
Collections.newSetFromMap(IdentityHashMap())
@get:Internal
internal val _callbacks = mutableListOf(
{ property: KMutableProperty1<PlayExtensionConfig, Any?>, value: Any? ->
property.set(_config, value)
}
)
/**
* Enables or disables GPP.
*
* Defaults to `true`.
*/
@get:Input
var isEnabled: Boolean
get() = _config.enabled ?: true
set(value) {
updateProperty(PlayExtensionConfig::enabled, value)
}
/**
* JSON Service Account authentication file. You can also specify credentials through the
* `ANDROID_PUBLISHER_CREDENTIALS` environment variable.
*/
@get:PathSensitive(PathSensitivity.RELATIVE)
@get:Optional
@get:InputFile
var serviceAccountCredentials: File?
get() = _config.serviceAccountCredentials
set(value) {
updateProperty(PlayExtensionConfig::serviceAccountCredentials, value)
}
/**
* Choose the default packaging method. Either App Bundles or APKs. Affects tasks like
* `publish`.
*
* Defaults to `false` because App Bundles require Google Play App Signing to be configured.
*/
@get:Input
var defaultToAppBundles: Boolean
get() = _config.defaultToAppBundles ?: false
set(value) {
updateProperty(PlayExtensionConfig::defaultToAppBundles, value)
}
/**
* Choose whether or not to apply the changes from this build. Defaults to true.
*/
@get:Input
var commit: Boolean
get() = _config.commitOrDefault
set(value) {
updateProperty(PlayExtensionConfig::commit, value)
}
/**
* Specify the track from which to promote a release. That is, the specified track will be
* promoted to [track].
*
* See [track] for valid values. The default is determined dynamically from the most unstable
* release available for promotion. That is, if there is a stable release and an alpha release,
* the alpha will be chosen.
*/
@get:Input
var fromTrack: String
get() = _config.fromTrack ?: track
set(value) {
updateProperty(PlayExtensionConfig::fromTrack, value)
}
/**
* Specify the track in which to upload your app.
*
* May be one of `internal`, `alpha`, `beta`, `production`, or a custom track. Defaults to
* `internal`.
*/
@get:Input
var track: String
get() = _config.trackOrDefault
set(value) {
updateProperty(PlayExtensionConfig::track, value)
}
/**
* Specify the track to promote a release to.
*
* See [track] for valid values. If no promote track is specified, [track] is used instead.
*/
@get:Input
var promoteTrack: String
get() = _config.promoteTrackOrDefault
set(value) {
updateProperty(PlayExtensionConfig::promoteTrack, value)
}
/**
* Specify the initial user fraction intended to receive an `inProgress` release. Defaults to
* 0.1 (10%).
*
* @see releaseStatus
*/
@get:Input
var userFraction: Double
get() = _config.userFractionOrDefault
set(value) {
updateProperty(PlayExtensionConfig::userFraction, value)
}
/**
* Specify the update priority for your release. For information on consuming this value, take
* a look at
* [Google's documentation](https://developer.android.com/guide/playcore/in-app-updates).
* Defaults to API value.
*/
@get:Optional
@get:Input
var updatePriority: Int?
get() = _config.updatePriority
set(value) {
updateProperty(PlayExtensionConfig::updatePriority, value)
}
/**
* Specify the resolution strategy to employ when a version conflict occurs.
*
* May be one of `auto`, `fail`, or `ignore`. Defaults to `fail`.
*/
@get:Input
var resolutionStrategy: String
get() = _config.resolutionStrategyOrDefault.publishedName
set(value) {
updateProperty(PlayExtensionConfig::resolutionStrategy, textToResolutionStrategy(value))
}
/**
* If the [resolutionStrategy] is auto, provide extra processing on top of what this plugin
* already does. For example, you could update each output's version name using the newly
* mutated version codes.
*
* Note: by the time the output is received, its version code will have been linearly shifted
* such that the smallest output's version code is 1 unit greater than the maximum version code
* found in the Play Store.
*/
@Suppress("unused") // Public API
fun outputProcessor(processor: Action<ApkVariantOutput>) {
updateProperty(PlayExtensionConfig::outputProcessor, processor)
}
/**
* Specify the status to apply to the uploaded app release.
*
* May be one of `completed`, `draft`, `halted`, or `inProgress`. Defaults to `completed`.
*/
@get:Input
var releaseStatus: String
get() = _config.releaseStatusOrDefault.publishedName
set(value) {
updateProperty(PlayExtensionConfig::releaseStatus, textToReleaseStatus(value))
}
/** Specify the Play Console developer facing release name. */
@get:Optional
@get:Input
var releaseName: String?
get() = _config.releaseName
set(value) {
updateProperty(PlayExtensionConfig::releaseName, value)
}
/**
* Specify a directory where prebuilt artifacts such as APKs or App Bundles may be found. The
* directory must exist and should contain only artifacts intended to be uploaded. If no
* directory is specified, your app will be built on-the-fly when you try to publish it.
*
* Defaults to null (i.e. your app will be built pre-publish).
*/
@get:Internal("Directory mapped to a useful set of files later")
var artifactDir: File?
get() = _config.artifactDir
set(value) {
updateProperty(PlayExtensionConfig::artifactDir, value)
}
/**
* @return the configuration for your app's retainable objects such as previous artifacts and
* OBB files.
*/
@get:Nested
val retain: Retain = Retain()
/** Configure your app's retainable objects such as previous artifacts and OBB files. */
@Suppress("unused") // Public API
fun retain(action: Action<Retain>) {
action.execute(retain)
}
override fun toString(): String = "PlayPublisherExtension(name=$name, config=$_config)"
/** Entry point for retainable artifact configuration. */
inner class Retain {
/** Specify the version code(s) of an APK or App Bundle to retain. Defaults to none. */
@get:Optional
@get:Input
var artifacts: List<Long>?
get() = _config.retainArtifacts
set(value) {
updateProperty(PlayExtensionConfig::retainArtifacts, value)
}
/**
* Specify the reference version of the main OBB file to attach to an APK.
*
* Defaults to none.
* @see patchObb
*/
@get:Optional
@get:Input
var mainObb: Int?
get() = _config.retainMainObb
set(value) {
updateProperty(PlayExtensionConfig::retainMainObb, value)
}
/**
* Specify the reference version of the patch OBB file to attach to an APK.
*
* Defaults to none.
* @see mainObb
*/
@get:Optional
@get:Input
var patchObb: Int?
get() = _config.retainPatchObb
set(value) {
updateProperty(PlayExtensionConfig::retainPatchObb, value)
}
}
}
| 0 | null | 0 | 0 | 88485d158b940bed40fa22f8dd9a6ae92b118d53 | 9,413 | gradle-play-publisher | MIT License |
idea/src/org/jetbrains/kotlin/idea/joinLines/JoinBlockIntoSingleStatementHandler.kt | JakeWharton | 99,388,807 | false | null | /*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.idea.joinLines
import com.intellij.codeInsight.editorActions.JoinRawLinesHandlerDelegate
import com.intellij.openapi.editor.Document
import com.intellij.psi.PsiFile
import org.jetbrains.kotlin.idea.inspections.UseExpressionBodyInspection
import org.jetbrains.kotlin.idea.intentions.MergeIfsIntention
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.startOffset
class JoinBlockIntoSingleStatementHandler : JoinRawLinesHandlerDelegate {
override fun tryJoinRawLines(document: Document, file: PsiFile, start: Int, end: Int): Int {
if (file !is KtFile) return -1
if (start == 0) return -1
val c = document.charsSequence[start]
val index = if (c == '\n') start - 1 else start
val brace = file.findElementAt(index)!!
if (brace.node!!.elementType != KtTokens.LBRACE) return -1
val block = brace.parent as? KtBlockExpression ?: return -1
val statement = block.statements.singleOrNull() ?: return -1
val parent = block.parent
val useExpressionBodyInspection = UseExpressionBodyInspection(convertEmptyToUnit = false)
val oneLineReturnFunction = (parent as? KtDeclarationWithBody)?.takeIf { useExpressionBodyInspection.isActiveFor(it) }
if (parent !is KtContainerNode && parent !is KtWhenEntry && oneLineReturnFunction == null) return -1
if (block.node.getChildren(KtTokens.COMMENTS).isNotEmpty()) return -1 // otherwise we will loose comments
// handle nested if's
val pparent = parent.parent
if (pparent is KtIfExpression) {
if (block == pparent.then && statement is KtIfExpression && statement.`else` == null) {
// if outer if has else-branch and inner does not have it, do not remove braces otherwise else-branch will belong to different if!
if (pparent.`else` != null) return -1
return MergeIfsIntention.applyTo(pparent)
}
if (block == pparent.`else`) {
val ifParent = pparent.parent
if (!(
ifParent is KtBlockExpression ||
ifParent is KtDeclaration ||
KtPsiUtil.isAssignment(ifParent))) {
return -1
}
}
}
return if (oneLineReturnFunction != null) {
useExpressionBodyInspection.simplify(oneLineReturnFunction, false)
oneLineReturnFunction.bodyExpression!!.startOffset
}
else {
val newStatement = block.replace(statement)
newStatement.textRange!!.startOffset
}
}
override fun tryJoinLines(document: Document, file: PsiFile, start: Int, end: Int) = -1
}
| 0 | null | 28 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 3,421 | kotlin | Apache License 2.0 |
vuesaxicons/src/commonMain/kotlin/moe/tlaster/icons/vuesax/vuesaxicons/twotone/Quotedownsquare.kt | Tlaster | 560,394,734 | false | {"Kotlin": 25133302} | package moe.tlaster.icons.vuesax.vuesaxicons.twotone
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.TwotoneGroup
public val TwotoneGroup.Quotedownsquare: ImageVector
get() {
if (_quotedownsquare != null) {
return _quotedownsquare!!
}
_quotedownsquare = Builder(name = "Quotedownsquare", 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(9.0f, 22.0f)
horizontalLineTo(15.0f)
curveTo(20.0f, 22.0f, 22.0f, 20.0f, 22.0f, 15.0f)
verticalLineTo(9.0f)
curveTo(22.0f, 4.0f, 20.0f, 2.0f, 15.0f, 2.0f)
horizontalLineTo(9.0f)
curveTo(4.0f, 2.0f, 2.0f, 4.0f, 2.0f, 9.0f)
verticalLineTo(15.0f)
curveTo(2.0f, 20.0f, 4.0f, 22.0f, 9.0f, 22.0f)
close()
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF292D32)),
fillAlpha = 0.4f, strokeAlpha = 0.4f, strokeLineWidth = 1.5f, strokeLineCap =
Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(7.0f, 12.1597f)
horizontalLineTo(9.68f)
curveTo(10.39f, 12.1597f, 10.87f, 12.6997f, 10.87f, 13.3497f)
verticalLineTo(14.8397f)
curveTo(10.87f, 15.4897f, 10.39f, 16.0297f, 9.68f, 16.0297f)
horizontalLineTo(8.19f)
curveTo(7.54f, 16.0297f, 7.0f, 15.4897f, 7.0f, 14.8397f)
verticalLineTo(12.1597f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF292D32)),
fillAlpha = 0.4f, strokeAlpha = 0.4f, strokeLineWidth = 1.5f, strokeLineCap =
Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(7.0f, 12.1597f)
curveTo(7.0f, 9.3697f, 7.52f, 8.8997f, 9.09f, 7.9697f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF292D32)),
fillAlpha = 0.4f, strokeAlpha = 0.4f, strokeLineWidth = 1.5f, strokeLineCap =
Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(13.1406f, 12.1597f)
horizontalLineTo(15.8206f)
curveTo(16.5306f, 12.1597f, 17.0106f, 12.6997f, 17.0106f, 13.3497f)
verticalLineTo(14.8397f)
curveTo(17.0106f, 15.4897f, 16.5306f, 16.0297f, 15.8206f, 16.0297f)
horizontalLineTo(14.3306f)
curveTo(13.6806f, 16.0297f, 13.1406f, 15.4897f, 13.1406f, 14.8397f)
verticalLineTo(12.1597f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF292D32)),
fillAlpha = 0.4f, strokeAlpha = 0.4f, strokeLineWidth = 1.5f, strokeLineCap =
Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(13.1406f, 12.1597f)
curveTo(13.1406f, 9.3697f, 13.6606f, 8.8997f, 15.2306f, 7.9697f)
}
}
.build()
return _quotedownsquare!!
}
private var _quotedownsquare: ImageVector? = null
| 0 | Kotlin | 0 | 2 | b8a8231e6637c2008f675ae76a3423b82ee53950 | 4,404 | VuesaxIcons | MIT License |
android-basics-kotlin-bus-schedule-app/app/src/main/java/com/example/busschedule/FullScheduleFragment.kt | luannguyen252 | 371,359,679 | false | null | package com.example.busschedule
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.coroutineScope
import androidx.navigation.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.busschedule.databinding.FullScheduleFragmentBinding
import com.example.busschedule.viewmodels.BusScheduleViewModel
import com.example.busschedule.viewmodels.BusScheduleViewModelFactory
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
class FullScheduleFragment: Fragment() {
private var _binding: FullScheduleFragmentBinding? = null
private val binding get() = _binding!!
private lateinit var recyclerView: RecyclerView
private val viewModel: BusScheduleViewModel by activityViewModels {
BusScheduleViewModelFactory(
(activity?.application as BusScheduleApplication).database.scheduleDao()
)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = FullScheduleFragmentBinding.inflate(inflater, container, false)
val view = binding.root
return view
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
recyclerView = binding.recyclerView
recyclerView.layoutManager = LinearLayoutManager(requireContext())
val busStopAdapter = BusStopAdapter({
val action = FullScheduleFragmentDirections
.actionFullScheduleFragmentToStopScheduleFragment(
stopName = it.stopName
)
view.findNavController().navigate(action)
})
recyclerView.adapter = busStopAdapter
lifecycle.coroutineScope.launch {
viewModel.fullSchedule().collect() {
busStopAdapter.submitList(it)
}
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
| 0 | null | 0 | 1 | a9b5aef8662a1808042c820c3dfac02e1efd5800 | 2,257 | my-android-journey | MIT License |
app/src/main/java/com/bossed/waej/eventbus/EBSelItem.kt | Ltow | 710,230,789 | false | {"Kotlin": 2304560, "Java": 395495, "HTML": 71364} | package com.bossed.waej.eventbus
import com.bossed.waej.javebean.ItemRow
data class EBSelItem(val sel: ArrayList<ItemRow>)
| 0 | Kotlin | 0 | 0 | 8c2e9928f6c47484bec7a5beca32ed4b10200f9c | 125 | wananexiu | Mulan Permissive Software License, Version 2 |
src/commonMain/kotlin/io/github/optimumcode/json/schema/internal/factories/object/PropertiesAssertionFactory.kt | OptimumCode | 665,024,908 | false | null | package io.github.optimumcode.json.schema.internal.factories.`object`
import io.github.optimumcode.json.schema.ErrorCollector
import io.github.optimumcode.json.schema.internal.AssertionContext
import io.github.optimumcode.json.schema.internal.AssertionFactory
import io.github.optimumcode.json.schema.internal.JsonSchemaAssertion
import io.github.optimumcode.json.schema.internal.LoadingContext
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonObject
@Suppress("unused")
internal object PropertiesAssertionFactory : AssertionFactory {
private const val propertiesProperty: String = "properties"
private const val patternPropertiesProperty: String = "patternProperties"
private const val additionalPropertiesProperty: String = "additionalProperties"
override fun isApplicable(element: JsonElement): Boolean {
return element is JsonObject && element.run {
containsKey(propertiesProperty) ||
containsKey(patternPropertiesProperty) ||
containsKey(additionalPropertiesProperty)
}
}
override fun create(element: JsonElement, context: LoadingContext): JsonSchemaAssertion {
require(element is JsonObject) { "cannot extract properties from ${element::class.simpleName}" }
val propertiesAssertions: Map<String, JsonSchemaAssertion> = extractPropertiesAssertions(element, context)
val patternAssertions: Map<Regex, JsonSchemaAssertion> = extractPatternAssertions(element, context)
val additionalProperties: JsonSchemaAssertion? = extractAdditionalProperties(element, context)
return PropertiesAssertion(
propertiesAssertions,
patternAssertions,
additionalProperties,
)
}
private fun extractAdditionalProperties(jsonObject: JsonObject, context: LoadingContext): JsonSchemaAssertion? {
if (jsonObject.isEmpty()) {
return null
}
val additionalElement = jsonObject[additionalPropertiesProperty] ?: return null
require(context.isJsonSchema(additionalElement)) { "$additionalPropertiesProperty must be a valid JSON schema" }
return context.at(additionalPropertiesProperty).schemaFrom(additionalElement)
}
private fun extractPatternAssertions(
jsonObject: JsonObject,
context: LoadingContext,
): Map<Regex, JsonSchemaAssertion> {
if (jsonObject.isEmpty()) {
return emptyMap()
}
val propertiesElement = jsonObject[patternPropertiesProperty] ?: return emptyMap()
require(propertiesElement is JsonObject) { "$patternPropertiesProperty must be an object" }
if (propertiesElement.isEmpty()) {
return emptyMap()
}
val propContext = context.at(patternPropertiesProperty)
return propertiesElement.map { (pattern, element) ->
require(propContext.isJsonSchema(element)) { "$pattern must be a valid JSON schema" }
val regex = try {
pattern.toRegex()
} catch (exOrJsError: Throwable) { // because of JsError
throw IllegalArgumentException("$pattern must be a valid regular expression", exOrJsError)
}
regex to propContext.at(pattern).schemaFrom(element)
}.toMap()
}
private fun extractPropertiesAssertions(
jsonObject: JsonObject,
context: LoadingContext,
): Map<String, JsonSchemaAssertion> {
if (jsonObject.isEmpty()) {
return emptyMap()
}
val propertiesElement = jsonObject[propertiesProperty] ?: return emptyMap()
require(propertiesElement is JsonObject) { "$propertiesProperty must be an object" }
if (propertiesElement.isEmpty()) {
return emptyMap()
}
val propertiesContext = context.at(propertiesProperty)
return propertiesElement.mapValues { (prop, element) ->
require(propertiesContext.isJsonSchema(element)) { "$prop must be a valid JSON schema" }
propertiesContext.at(prop).schemaFrom(element)
}
}
}
private class PropertiesAssertion(
private val propertiesAssertions: Map<String, JsonSchemaAssertion>,
private val patternAssertions: Map<Regex, JsonSchemaAssertion>,
private val additionalProperties: JsonSchemaAssertion?,
) : JsonSchemaAssertion {
override fun validate(element: JsonElement, context: AssertionContext, errorCollector: ErrorCollector): Boolean {
if (element !is JsonObject) {
return true
}
var valid = true
for ((prop, value) in element) {
val propContext = context.at(prop)
var triggered = false
var res = propertiesAssertions[prop]?.run {
triggered = true
validate(
value,
propContext,
errorCollector,
)
} ?: true
valid = valid and res
for ((pattern, assertion) in patternAssertions) {
if (pattern.find(prop) != null) {
triggered = true
res = assertion.validate(
value,
propContext,
errorCollector,
)
valid = valid and res
}
}
if (triggered) {
continue
}
res = additionalProperties?.validate(value, propContext, errorCollector) ?: true
valid = valid and res
}
return valid
}
} | 4 | Kotlin | 0 | 1 | 9bfbddf9b21731dd4aa7f96ca61b9e1ec68df49b | 5,079 | json-schema-validator | MIT License |
library/src/main/java/moe/feng/common/stepperview/VerticalStepperItemView.kt | jvitinger | 206,747,613 | true | {"Kotlin": 17520} | package moe.feng.common.stepperview
import android.animation.LayoutTransition
import android.animation.ObjectAnimator
import android.animation.ValueAnimator
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.widget.TextViewCompat
import kotlinx.android.synthetic.main.vertical_stepper_item_view_layout.view.*
import moe.feng.common.stepperview.VerticalStepperItemView.State.STATE_DONE
import moe.feng.common.stepperview.VerticalStepperItemView.State.STATE_NORMAL
private const val PROPERTY_BACKGROUND = "backgroundColor"
class VerticalStepperItemView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) :
FrameLayout(context, attrs, defStyleAttr) {
/**
* Internal Views
*/
private lateinit var pointBackground: View
private lateinit var verticalLine: View
private lateinit var pointNumber: TextView
private lateinit var titleText: TextView
private lateinit var customView: FrameLayout
private lateinit var pointFrame: FrameLayout
private lateinit var rightContainer: LinearLayout
private lateinit var doneIconView: ImageView
private lateinit var marginBottomView: View
private var pointColorAnimator: ValueAnimator? = null
private val oneDpInPixels = resources.getDimensionPixelSize(R.dimen.dp1)
private lateinit var parentStepperView: VerticalStepperView
init {
val lp: ViewGroup.LayoutParams = LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
layoutParams = lp
}
fun init(parentStepperView: VerticalStepperView) {
this.parentStepperView = parentStepperView
prepareViews(context)
}
override fun addView(child: View, index: Int, layoutParams: ViewGroup.LayoutParams) {
if (child.id == R.id.vertical_stepper_item_view_layout) {
super.addView(child, index, layoutParams)
} else {
customView.addView(child, index, layoutParams)
}
}
private fun prepareViews(context: Context) {
// Inflate and find views
val inflater: LayoutInflater = LayoutInflater.from(context)
val inflateView: View = inflater.inflate(R.layout.vertical_stepper_item_view_layout, null)
pointBackground = inflateView.stepper_point_background
verticalLine = inflateView.stepper_line
pointNumber = inflateView.stepper_number
titleText = inflateView.stepper_title
customView = inflateView.stepper_custom_view
pointFrame = inflateView.stepper_point_frame
rightContainer = inflateView.stepper_right_layout
doneIconView = inflateView.stepper_done_icon
marginBottomView = inflateView.stepper_margin_bottom
verticalLine.setBackgroundColor(parentStepperView.lineColor)
doneIconView.setImageDrawable(parentStepperView.doneIcon)
if (parentStepperView.isAnimationEnabled) {
rightContainer.layoutTransition = LayoutTransition()
} else {
rightContainer.layoutTransition = null
}
// Add view
val lp = LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
addView(inflateView, lp)
// Set title top margin
titleText.viewTreeObserver.addOnGlobalLayoutListener {
val singleLineHeight = titleText.measuredHeight
val topMargin = (pointFrame.measuredHeight - singleLineHeight) / 2
// Only update top margin when it is positive, preventing titles being truncated.
if (topMargin > 0) {
(titleText.layoutParams as MarginLayoutParams).topMargin = topMargin
}
}
}
private fun updateMarginBottom() {
marginBottomView.layoutParams.height = (if (!isLastStep) if (state != State.STATE_SELECTED) 28 else 36 else 12) * oneDpInPixels
}
@set:Synchronized
var state: State = STATE_NORMAL
set(state) {
val normalColor = parentStepperView.normalColor
val activatedColor = parentStepperView.activatedColor
val duration = parentStepperView.animationDuration
pointColorAnimator?.cancel()
if (state != STATE_NORMAL && field == STATE_NORMAL) {
pointColorAnimator = ObjectAnimator.ofArgb(pointBackground, PROPERTY_BACKGROUND, normalColor, activatedColor).apply {
setDuration(duration)
start()
}
} else if (state == STATE_NORMAL && field != STATE_NORMAL) {
pointColorAnimator = ObjectAnimator.ofArgb(pointBackground, PROPERTY_BACKGROUND, activatedColor, normalColor).apply {
setDuration(duration)
start()
}
} else {
pointBackground.setBackgroundColor(if (state == STATE_NORMAL) normalColor else activatedColor)
}
if (state == STATE_DONE && field != STATE_DONE) {
doneIconView.animate().alpha(1f).setDuration(duration).start()
pointNumber.animate().alpha(0f).setDuration(duration).start()
} else if (state != STATE_DONE && field == STATE_DONE) {
doneIconView.animate().alpha(0f).setDuration(duration).start()
pointNumber.animate().alpha(1f).setDuration(duration).start()
} else {
doneIconView.alpha = if (state == STATE_DONE) 1f else 0f
pointNumber.alpha = if (state == STATE_DONE) 0f else 1f
}
TextViewCompat.setTextAppearance(titleText, when (state) {
STATE_DONE -> R.style.TextAppearance_Widget_Stepper_Done
STATE_NORMAL -> R.style.TextAppearance_Widget_Stepper_Normal
else -> R.style.TextAppearance_Widget_Stepper_Selected
})
field = state
updateMarginBottom()
}
var title: CharSequence = ""
set(title) {
titleText.text = title
field = title
}
var index: Int = 1
set(index) {
field = index
pointNumber.text = index.toString()
}
var isLastStep = false
set(isLastStep) {
field = isLastStep
verticalLine.visibility = if (isLastStep) View.INVISIBLE else View.VISIBLE
updateMarginBottom()
}
fun canPrevStep(): Boolean {
return parentStepperView.canPrev()
}
fun prevStep(): Boolean {
return parentStepperView.prevStep()
}
fun canNextStep(): Boolean {
return parentStepperView.canNext()
}
fun nextStep(): Boolean {
return parentStepperView.nextStep()
}
enum class State {
STATE_NORMAL,
STATE_SELECTED,
STATE_DONE
}
} | 0 | Kotlin | 0 | 0 | 9845f712c4c2522dd717f6189b552260f4910ea3 | 7,092 | MaterialStepperView | MIT License |
src/commonMain/kotlin/net/dinkla/raytracer/materials/Transparent.kt | jdinkla | 38,753,756 | false | {"Kotlin": 467610, "Shell": 457} | package net.dinkla.raytracer.materials
import net.dinkla.raytracer.brdf.PerfectSpecular
import net.dinkla.raytracer.btdf.PerfectTransmitter
import net.dinkla.raytracer.colors.Color
import net.dinkla.raytracer.hits.IShade
import net.dinkla.raytracer.math.Ray
import net.dinkla.raytracer.utilities.equals
import net.dinkla.raytracer.utilities.hash
import net.dinkla.raytracer.world.IWorld
import kotlin.math.abs
class Transparent : Phong {
private var reflectiveBRDF = PerfectSpecular()
private var specularBTDF = PerfectTransmitter()
@SuppressWarnings("LongParameterList")
constructor(
color: Color = Color.WHITE,
ka: Double = 0.25,
kd: Double = 0.75,
exp: Double = 5.0,
ks: Double = 0.25,
cs: Color = Color.WHITE,
kt: Double = 0.0,
ior: Double = 0.0,
kr: Double = 0.0,
cr: Color = Color.WHITE
) : super(color, ka, kd, exp, ks, cs) {
this.kt = kt
this.ior = ior
this.kr = kr
this.cr = cr
}
var kt: Double
get() = specularBTDF.kt
set(v) {
specularBTDF.kt = v
}
var ior: Double
get() = specularBTDF.ior
set(v) {
specularBTDF.ior = v
}
var kr: Double
get() = reflectiveBRDF.kr
set(v) {
reflectiveBRDF.kr = v
}
var cr: Color
get() = reflectiveBRDF.cr
set(v) {
reflectiveBRDF.cr = v
}
override fun shade(world: IWorld, sr: IShade): Color {
var l = super.shade(world, sr)
val wo = sr.ray.direction.times(-1.0)
val brdf = reflectiveBRDF.sampleF(sr, wo)
// trace reflected ray
val reflectedRay = Ray(sr.hitPoint, brdf.wi)
val cr = world.tracer?.trace(reflectedRay, sr.depth + 1) ?: Color.BLACK
if (specularBTDF.isTir(sr)) {
l += cr
} else {
// reflected
val cfr = abs(sr.normal dot brdf.wi)
l += (brdf.color * cr) * cfr
// trace transmitted ray
val btdf = specularBTDF.sampleF(sr, wo)
val transmittedRay = Ray(sr.hitPoint, btdf.wt)
val ct = world.tracer?.trace(transmittedRay, sr.depth + 1) ?: Color.WHITE
val cft = abs(sr.normal dot btdf.wt)
l += (btdf.color * ct) * cft
}
return l
}
override fun equals(other: Any?): Boolean = this.equals<Transparent>(other) { a, b ->
a.diffuseBRDF == b.diffuseBRDF && a.ambientBRDF == b.ambientBRDF && a.specularBTDF == b.specularBTDF &&
a.reflectiveBRDF == b.reflectiveBRDF && a.specularBRDF == b.specularBRDF
}
override fun hashCode(): Int =
hash(super.diffuseBRDF, super.ambientBRDF, specularBRDF, reflectiveBRDF, specularBTDF)
override fun toString() = "Transparent(${super.toString()}, $reflectiveBRDF, $specularBTDF)"
}
| 0 | Kotlin | 2 | 5 | fdf196ff5370a5e64f27c6e7ea66141a25d17413 | 2,915 | from-the-ground-up-ray-tracer | Apache License 2.0 |
NLiteAVDemo-Android-Java/call-ui/src/main/java/com/netease/yunxin/nertc/ui/service/CallKitUIBridgeService.kt | netease-kit | 292,760,923 | false | null | /*
* Copyright (c) 2022 NetEase, Inc. All rights reserved.
* Use of this source code is governed by a MIT license that can be
* found in the LICENSE file.
*/
package com.netease.yunxin.nertc.ui.service
import android.content.Context
import android.text.TextUtils
import com.netease.nimlib.sdk.ResponseCode
import com.netease.yunxin.kit.alog.ALog
import com.netease.yunxin.kit.alog.ParameterMap
import com.netease.yunxin.kit.call.group.GroupCallHangupEvent
import com.netease.yunxin.kit.call.group.GroupCallLocalActionObserver
import com.netease.yunxin.kit.call.group.GroupCallMember
import com.netease.yunxin.kit.call.group.NEGroupCall
import com.netease.yunxin.kit.call.group.NEGroupCallActionObserver
import com.netease.yunxin.kit.call.group.NEGroupCallInfo
import com.netease.yunxin.kit.call.group.NEGroupCallbackMgr
import com.netease.yunxin.kit.call.group.NEGroupConstants
import com.netease.yunxin.kit.call.group.NEGroupIncomingCallReceiver
import com.netease.yunxin.kit.call.group.result.BaseActionResult
import com.netease.yunxin.kit.call.p2p.NECallEngine
import com.netease.yunxin.kit.call.p2p.extra.NECallLocalActionMgr
import com.netease.yunxin.kit.call.p2p.extra.NECallLocalActionObserver
import com.netease.yunxin.kit.call.p2p.model.NECallEndInfo
import com.netease.yunxin.kit.call.p2p.model.NECallEngineDelegate
import com.netease.yunxin.kit.call.p2p.model.NECallEngineDelegateAbs
import com.netease.yunxin.kit.call.p2p.model.NECallInfo
import com.netease.yunxin.kit.call.p2p.model.NECallType
import com.netease.yunxin.kit.call.p2p.model.NECallTypeChangeInfo
import com.netease.yunxin.kit.call.p2p.model.NEHangupReasonCode
import com.netease.yunxin.kit.call.p2p.model.NEInviteInfo
import com.netease.yunxin.nertc.nertcvideocall.model.CallErrorCode
import com.netease.yunxin.nertc.nertcvideocall.model.CallLocalAction
import com.netease.yunxin.nertc.nertcvideocall.model.SwitchCallState
import com.netease.yunxin.nertc.nertcvideocall.model.impl.state.CallState
import com.netease.yunxin.nertc.ui.CallKitUI
import com.netease.yunxin.nertc.ui.base.AVChatSoundPlayer
/**
* ้่ฏทๆถๆฏๅๅ
*
* ๅฝๆถๆฏ่ฟๆฅๆถ
*/
open class CallKitUIBridgeService @JvmOverloads constructor(
val context: Context,
val incomingCallEx: IncomingCallEx = DefaultIncomingCallEx()
) {
protected val logTag = "CallKitUIBridgeService"
/**
* ่ฎฐๅฝ app ๅจๅๅฐๆถๆถๅฐ็้่ฏทไฟกๆฏ๏ผ็นๅฏน็น
*/
protected var bgInvitedInfo: NEInviteInfo? = null
/**
* ่ฎฐๅฝ app ๅจๅๅฐๆถๆถๅฐ็้่ฏทไฟกๆฏ๏ผ็พค็ป
*/
protected var bgGroupInvitedInfo: NEGroupCallInfo? = null
/**
* ๆฏๅฆ่ฝๅๆญข้ณ้ขๆญๆพ
*/
protected var canStopAudioPlay = true
/**
* ๅผๅซๆน็จๆท accId
*/
protected var callerAccId: String? = null
/**
* ็พค็ปๆฅ็ต็ๅฌ
*/
private val groupCallReceiver = NEGroupIncomingCallReceiver { info ->
[email protected](info)
}
/**
* ็พค็ปๆฌๅฐ่กไธบ็ๅฌ
*/
private val groupLocalActionObserver = GroupCallLocalActionObserver { actionId, result ->
[email protected](actionId, result)
}
/**
* ็พค็ป้่ฏ่กไธบ็ๅฌ
*/
private val groupActionObserver = object : NEGroupCallActionObserver {
override fun onMemberChanged(callId: String, userList: MutableList<GroupCallMember>?) {
[email protected](callId, userList)
}
override fun onGroupCallHangup(hangupEvent: GroupCallHangupEvent) {
[email protected](hangupEvent)
}
}
/**
* ็นๅฏน็นๆฌๅฐ่กไธบ็ๅฌ
*/
private val localActionObserver = NECallLocalActionObserver { actionId, resultCode, _ ->
[email protected](actionId, resultCode)
}
/**
* ็นๅฏน็น้่ฏ่กไธบ็ๅฌ
*/
private val callEngineDelegate: NECallEngineDelegate = object : NECallEngineDelegateAbs() {
override fun onReceiveInvited(info: NEInviteInfo) {
[email protected](info)
}
override fun onCallConnected(info: NECallInfo) {
[email protected](info)
}
override fun onCallTypeChange(info: NECallTypeChangeInfo) {
[email protected](info)
}
override fun onCallEnd(info: NECallEndInfo) {
[email protected](info)
}
}
init {
/**
* ๅๅงๅๆณจๅ็ธๅ
ณ็ๅฌๅ
*/
NECallEngine.sharedInstance().addCallDelegate(callEngineDelegate)
NECallLocalActionMgr.getInstance().addCallback(localActionObserver)
NEGroupCall.instance().configGroupIncomingReceiver(groupCallReceiver, true)
NEGroupCall.instance().configGroupActionObserver(groupActionObserver, true)
NEGroupCallbackMgr.instance().addLocalActionObserver(groupLocalActionObserver)
}
// //////////////////////////////////// GroupCallLocalActionObserver ////////////////////////////
/**
* ็พค็ปๆฌๅฐ่กไธบ็ๅฌ
*/
open fun onLocalAction(actionId: Int, result: BaseActionResult?) {
ALog.dApi(
logTag,
ParameterMap("onLocalAction").append("actionId", actionId).append("result", result)
)
if (bgGroupInvitedInfo != null) {
incomingCallEx.onIncomingCallInvalid(bgGroupInvitedInfo)
bgGroupInvitedInfo = null
}
}
// //////////////////////////////////// NEGroupCallActionObserver ///////////////////////////////
/**
* ็พค็ป้่ฏไบบๅๅๆด
*/
open fun onMemberChanged(callId: String?, userList: MutableList<GroupCallMember>?) {
if (bgGroupInvitedInfo != null && TextUtils.equals(
callId,
bgGroupInvitedInfo!!.callId
) && userList != null
) {
val index = userList.indexOf(GroupCallMember(CallKitUI.currentUserAccId))
if (index < 0) {
return
}
if (userList[index].state == NEGroupConstants.UserState.LEAVING || userList[index].state == NEGroupConstants.UserState.JOINED) {
incomingCallEx.onIncomingCallInvalid(bgGroupInvitedInfo)
bgGroupInvitedInfo = null
}
}
}
/**
* ็พค็ป้่ฏ็ปๆๆๆญ
*/
open fun onGroupCallHangup(hangupEvent: GroupCallHangupEvent) {
if (bgGroupInvitedInfo != null && TextUtils.equals(
hangupEvent.callId,
bgGroupInvitedInfo!!.callId
)
) {
incomingCallEx.onIncomingCallInvalid(bgGroupInvitedInfo)
bgGroupInvitedInfo = null
}
}
// //////////////////////////////////// NEGroupIncomingCallReceiver /////////////////////////////
/**
* ็พค็ปๆฅ็ต็ๅฌ
*/
open fun onReceiveGroupInvitation(info: NEGroupCallInfo) {
ALog.dApi(logTag, ParameterMap("onReceiveGroupInvitation").append("info", info))
// ๆฃๆฅๅๆฐๅ็ๆง
if (!isValidParam(info)) {
ALog.d(logTag, "onIncomingCall for group, param is invalid.")
return
}
if (!incomingCallEx.onIncomingCall(info)) {
bgGroupInvitedInfo = info
}
}
// //////////////////////////////////// NECallLocalActionObserver ///////////////////////////////
/**
* ็นๅฏน็นๆฌๅฐ่กไธบ็ๅฌ
*/
open fun onLocalAction(actionId: Int, resultCode: Int) {
ALog.d(logTag, "onLocalAction actionId is $actionId, resultCode is $resultCode.")
if (actionId == CallLocalAction.ACTION_CALL && NECallEngine.sharedInstance().callInfo.callStatus == CallState.STATE_CALL_OUT) {
callerAccId = CallKitUI.currentUserAccId
canStopAudioPlay = true
AVChatSoundPlayer.play(context, AVChatSoundPlayer.RingerTypeEnum.CONNECTING)
} else if (canStopAudioPlay && callerAccId != null &&
actionId != CallLocalAction.ACTION_BEFORE_RESET &&
actionId != CallLocalAction.ACTION_SWITCH &&
(resultCode == CallErrorCode.SUCCESS || resultCode == ResponseCode.RES_SUCCESS.toInt())
) {
AVChatSoundPlayer.stop(context)
callerAccId = null
}
if (bgInvitedInfo != null) {
incomingCallEx.onIncomingCallInvalid(bgInvitedInfo)
bgInvitedInfo = null
}
}
// //////////////////////////////////// NECallEngineDelegateAbs /////////////////////////////////
/**
* ็นๅฏน็น้่ฏ่กไธบ็ๅฌ
*/
open fun onReceiveInvited(info: NEInviteInfo) {
ALog.dApi(logTag, ParameterMap("onReceiveInvited").append("info", info))
// ๆฃๆฅๅๆฐๅ็ๆง
if (!isValidParam(info)) {
ALog.d(logTag, "onIncomingCall, param is invalid.")
return
}
if (!incomingCallEx.onIncomingCall(info)) {
bgInvitedInfo = info
}
callerAccId = info.callerAccId
canStopAudioPlay = true
if (NECallEngine.sharedInstance().callInfo.callStatus == CallState.STATE_INVITED) {
AVChatSoundPlayer.play(context, AVChatSoundPlayer.RingerTypeEnum.RING)
}
}
/**
* ็นๅฏน็น้่ฏๅปบ็ซ
*/
open fun onCallConnected(info: NECallInfo) {
ALog.dApi(logTag, ParameterMap("onCallConnected").append("info", info))
incomingCallEx.onIncomingCallInvalid(bgInvitedInfo)
bgInvitedInfo = null
AVChatSoundPlayer.stop(context)
}
/**
* ็นๅฏน็น้่ฏ็ฑปๅๅๆด
*/
open fun onCallTypeChange(info: NECallTypeChangeInfo) {
if (info.state == SwitchCallState.ACCEPT && bgInvitedInfo != null) {
bgInvitedInfo = bgInvitedInfo?.run {
NEInviteInfo(callerAccId, info.callType, extraInfo, channelId)
}
}
}
/**
* ็นๅฏน็น้่ฏ็ปๆๅ่ฐ
*/
open fun onCallEnd(info: NECallEndInfo) {
ALog.dApi(logTag, ParameterMap("onCallEnd").append("info", info))
incomingCallEx.onIncomingCallInvalid(bgInvitedInfo)
when (info.reasonCode) {
NEHangupReasonCode.CALLER_REJECTED -> if (callerAccId == CallKitUI.currentUserAccId) {
playStopAudio(AVChatSoundPlayer.RingerTypeEnum.PEER_REJECT)
} else {
AVChatSoundPlayer.stop(context)
}
NEHangupReasonCode.BUSY -> if (callerAccId == CallKitUI.currentUserAccId) {
playStopAudio(AVChatSoundPlayer.RingerTypeEnum.PEER_BUSY)
} else {
AVChatSoundPlayer.stop(context)
}
NEHangupReasonCode.TIME_OUT -> if (callerAccId == CallKitUI.currentUserAccId) {
playStopAudio(AVChatSoundPlayer.RingerTypeEnum.NO_RESPONSE)
} else {
AVChatSoundPlayer.stop(context)
}
else -> AVChatSoundPlayer.stop(context)
}
bgInvitedInfo = null
callerAccId = null
}
/**
* ๅฐ่ฏๆขๅค่ขซๅซๅจๅๅฐๆ ๆณๅฑ็คบ็้กต้ขUI
*
* @return true ๆขๅคๆๅ๏ผfalse ๆขๅคๅคฑ่ดฅใ
*/
open fun tryResumeInvitedUI(): Boolean {
return bgInvitedInfo?.run {
val result = incomingCallEx.tryResumeInvitedUI(this)
if (result) {
bgInvitedInfo = null
}
result
} ?: bgGroupInvitedInfo?.run {
val result = incomingCallEx.tryResumeInvitedUI(this)
if (result) {
bgGroupInvitedInfo = null
}
result
} ?: run {
ALog.d(logTag, "no background inviteInfo, mContext or uiService is null.")
false
}
}
/**
* ๆญๆพๅๆญข้ณ้ขๅ
ๅฎน
*/
protected open fun playStopAudio(type: AVChatSoundPlayer.RingerTypeEnum) {
AVChatSoundPlayer.play(context, type)
canStopAudioPlay = false
}
/**
* ๅคๆญ็พค็ปๅผๅซๅๆฐๆฏๅฆๆๆ
*/
protected open fun isValidParam(invitedInfo: NEGroupCallInfo): Boolean {
if (TextUtils.isEmpty(invitedInfo.callId) ||
TextUtils.isEmpty(invitedInfo.callerAccId) ||
invitedInfo.memberList == null ||
invitedInfo.memberList.isEmpty()
) {
return false
}
val index = invitedInfo.memberList.indexOf(GroupCallMember(CallKitUI.currentUserAccId))
if (index < 0) {
return false
}
return true
}
/**
* ๅคๆญ็นๅฏน็นๅผๅซๆฏๅฆๆๆ
*/
protected open fun isValidParam(invitedInfo: NEInviteInfo): Boolean {
return invitedInfo.callType == NECallType.VIDEO || invitedInfo.callType == NECallType.AUDIO
}
/**
* ้ๆฏ
*/
internal open fun destroy() {
NECallEngine.sharedInstance().removeCallDelegate(callEngineDelegate)
NECallLocalActionMgr.getInstance().removeCallback(localActionObserver)
NEGroupCall.instance().configGroupIncomingReceiver(groupCallReceiver, false)
NEGroupCall.instance().configGroupActionObserver(groupActionObserver, false)
NEGroupCallbackMgr.instance().removeLocalActionObserver(groupLocalActionObserver)
}
}
| 2 | null | 27 | 38 | 9b2593a34179155cf2009124bec0e01944359d2d | 12,920 | NEVideoCall-1to1 | MIT License |
feature/topics/src/test/kotlin/uk/govuk/app/topics/TopicsViewModelTest.kt | alphagov | 788,896,208 | false | {"Kotlin": 222826} | package uk.govuk.app.topics
import io.mockk.coEvery
import io.mockk.mockk
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.test.setMain
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Before
import org.junit.Test
import uk.govuk.app.design.R
import uk.govuk.app.topics.data.remote.model.TopicItem
@OptIn(ExperimentalCoroutinesApi::class)
class TopicsViewModelTest {
private val dispatcher = UnconfinedTestDispatcher()
private val topicsRepo = mockk<TopicsRepo>(relaxed = true)
@Before
fun setup() {
Dispatchers.setMain(dispatcher)
}
@After
fun tearDown() {
Dispatchers.resetMain()
}
@Test
fun `Given topics are not null, When init, then emit topics`() {
coEvery { topicsRepo.getTopics() } returns listOf(TopicItem("benefits", "Benefits"))
val expected = listOf(
TopicUi(
ref = "benefits",
icon = R.drawable.ic_topic_benefits,
title = "Benefits"
)
)
val viewModel = TopicsViewModel(topicsRepo)
runTest {
val result = viewModel.uiState.first()
assertEquals(expected, result!!.topics)
}
}
@Test
fun `Given topics are not null, When init, then emit null`() {
coEvery { topicsRepo.getTopics() } returns null
val viewModel = TopicsViewModel(topicsRepo)
runTest {
val result = viewModel.uiState.first()
assertNull(result)
}
}
} | 2 | Kotlin | 0 | 1 | b9fff082f9834cd8c8dbc3c605c38c4fb2f67046 | 1,808 | govuk-mobile-android-app | MIT License |
src/controller/java/generated/java/matter/controller/cluster/clusters/RvcOperationalStateCluster.kt | project-chip | 244,694,174 | false | null | /*
*
* Copyright (c) 2023 Project CHIP Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package matter.controller.cluster.clusters
import java.time.Duration
import java.util.logging.Level
import java.util.logging.Logger
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.transform
import matter.controller.InvokeRequest
import matter.controller.InvokeResponse
import matter.controller.MatterController
import matter.controller.ReadData
import matter.controller.ReadRequest
import matter.controller.SubscribeRequest
import matter.controller.SubscriptionState
import matter.controller.UByteSubscriptionState
import matter.controller.UIntSubscriptionState
import matter.controller.UShortSubscriptionState
import matter.controller.cluster.structs.*
import matter.controller.model.AttributePath
import matter.controller.model.CommandPath
import matter.tlv.AnonymousTag
import matter.tlv.ContextSpecificTag
import matter.tlv.TlvReader
import matter.tlv.TlvWriter
class OvenCavityOperationalStateCluster(
private val controller: MatterController,
private val endpointId: UShort
) {
class OperationalCommandResponse(
val commandResponseState: OvenCavityOperationalStateClusterErrorStateStruct
)
class PhaseListAttribute(val value: List<String>?)
sealed class PhaseListAttributeSubscriptionState {
data class Success(val value: List<String>?) : PhaseListAttributeSubscriptionState()
data class Error(val exception: Exception) : PhaseListAttributeSubscriptionState()
object SubscriptionEstablished : PhaseListAttributeSubscriptionState()
}
class CurrentPhaseAttribute(val value: UByte?)
sealed class CurrentPhaseAttributeSubscriptionState {
data class Success(val value: UByte?) : CurrentPhaseAttributeSubscriptionState()
data class Error(val exception: Exception) : CurrentPhaseAttributeSubscriptionState()
object SubscriptionEstablished : CurrentPhaseAttributeSubscriptionState()
}
class CountdownTimeAttribute(val value: UInt?)
sealed class CountdownTimeAttributeSubscriptionState {
data class Success(val value: UInt?) : CountdownTimeAttributeSubscriptionState()
data class Error(val exception: Exception) : CountdownTimeAttributeSubscriptionState()
object SubscriptionEstablished : CountdownTimeAttributeSubscriptionState()
}
class OperationalStateListAttribute(
val value: List<OvenCavityOperationalStateClusterOperationalStateStruct>
)
sealed class OperationalStateListAttributeSubscriptionState {
data class Success(val value: List<OvenCavityOperationalStateClusterOperationalStateStruct>) :
OperationalStateListAttributeSubscriptionState()
data class Error(val exception: Exception) : OperationalStateListAttributeSubscriptionState()
object SubscriptionEstablished : OperationalStateListAttributeSubscriptionState()
}
class OperationalErrorAttribute(val value: OvenCavityOperationalStateClusterErrorStateStruct)
sealed class OperationalErrorAttributeSubscriptionState {
data class Success(val value: OvenCavityOperationalStateClusterErrorStateStruct) :
OperationalErrorAttributeSubscriptionState()
data class Error(val exception: Exception) : OperationalErrorAttributeSubscriptionState()
object SubscriptionEstablished : OperationalErrorAttributeSubscriptionState()
}
class GeneratedCommandListAttribute(val value: List<UInt>)
sealed class GeneratedCommandListAttributeSubscriptionState {
data class Success(val value: List<UInt>) : GeneratedCommandListAttributeSubscriptionState()
data class Error(val exception: Exception) : GeneratedCommandListAttributeSubscriptionState()
object SubscriptionEstablished : GeneratedCommandListAttributeSubscriptionState()
}
class AcceptedCommandListAttribute(val value: List<UInt>)
sealed class AcceptedCommandListAttributeSubscriptionState {
data class Success(val value: List<UInt>) : AcceptedCommandListAttributeSubscriptionState()
data class Error(val exception: Exception) : AcceptedCommandListAttributeSubscriptionState()
object SubscriptionEstablished : AcceptedCommandListAttributeSubscriptionState()
}
class EventListAttribute(val value: List<UInt>)
sealed class EventListAttributeSubscriptionState {
data class Success(val value: List<UInt>) : EventListAttributeSubscriptionState()
data class Error(val exception: Exception) : EventListAttributeSubscriptionState()
object SubscriptionEstablished : EventListAttributeSubscriptionState()
}
class AttributeListAttribute(val value: List<UInt>)
sealed class AttributeListAttributeSubscriptionState {
data class Success(val value: List<UInt>) : AttributeListAttributeSubscriptionState()
data class Error(val exception: Exception) : AttributeListAttributeSubscriptionState()
object SubscriptionEstablished : AttributeListAttributeSubscriptionState()
}
suspend fun pause(timedInvokeTimeout: Duration? = null): OperationalCommandResponse {
val commandId: UInt = 0u
val tlvWriter = TlvWriter()
tlvWriter.startStructure(AnonymousTag)
tlvWriter.endStructure()
val request: InvokeRequest =
InvokeRequest(
CommandPath(endpointId, clusterId = CLUSTER_ID, commandId),
tlvPayload = tlvWriter.getEncoded(),
timedRequest = timedInvokeTimeout
)
val response: InvokeResponse = controller.invoke(request)
logger.log(Level.FINE, "Invoke command succeeded: ${response}")
val tlvReader = TlvReader(response.payload)
tlvReader.enterStructure(AnonymousTag)
val TAG_COMMAND_RESPONSE_STATE: Int = 0
var commandResponseState_decoded: OvenCavityOperationalStateClusterErrorStateStruct? = null
while (!tlvReader.isEndOfContainer()) {
val tag = tlvReader.peekElement().tag
if (tag == ContextSpecificTag(TAG_COMMAND_RESPONSE_STATE)) {
commandResponseState_decoded =
OvenCavityOperationalStateClusterErrorStateStruct.fromTlv(tag, tlvReader)
} else {
tlvReader.skipElement()
}
}
if (commandResponseState_decoded == null) {
throw IllegalStateException("commandResponseState not found in TLV")
}
tlvReader.exitContainer()
return OperationalCommandResponse(commandResponseState_decoded)
}
suspend fun stop(timedInvokeTimeout: Duration? = null): OperationalCommandResponse {
val commandId: UInt = 1u
val tlvWriter = TlvWriter()
tlvWriter.startStructure(AnonymousTag)
tlvWriter.endStructure()
val request: InvokeRequest =
InvokeRequest(
CommandPath(endpointId, clusterId = CLUSTER_ID, commandId),
tlvPayload = tlvWriter.getEncoded(),
timedRequest = timedInvokeTimeout
)
val response: InvokeResponse = controller.invoke(request)
logger.log(Level.FINE, "Invoke command succeeded: ${response}")
val tlvReader = TlvReader(response.payload)
tlvReader.enterStructure(AnonymousTag)
val TAG_COMMAND_RESPONSE_STATE: Int = 0
var commandResponseState_decoded: OvenCavityOperationalStateClusterErrorStateStruct? = null
while (!tlvReader.isEndOfContainer()) {
val tag = tlvReader.peekElement().tag
if (tag == ContextSpecificTag(TAG_COMMAND_RESPONSE_STATE)) {
commandResponseState_decoded =
OvenCavityOperationalStateClusterErrorStateStruct.fromTlv(tag, tlvReader)
} else {
tlvReader.skipElement()
}
}
if (commandResponseState_decoded == null) {
throw IllegalStateException("commandResponseState not found in TLV")
}
tlvReader.exitContainer()
return OperationalCommandResponse(commandResponseState_decoded)
}
suspend fun start(timedInvokeTimeout: Duration? = null): OperationalCommandResponse {
val commandId: UInt = 2u
val tlvWriter = TlvWriter()
tlvWriter.startStructure(AnonymousTag)
tlvWriter.endStructure()
val request: InvokeRequest =
InvokeRequest(
CommandPath(endpointId, clusterId = CLUSTER_ID, commandId),
tlvPayload = tlvWriter.getEncoded(),
timedRequest = timedInvokeTimeout
)
val response: InvokeResponse = controller.invoke(request)
logger.log(Level.FINE, "Invoke command succeeded: ${response}")
val tlvReader = TlvReader(response.payload)
tlvReader.enterStructure(AnonymousTag)
val TAG_COMMAND_RESPONSE_STATE: Int = 0
var commandResponseState_decoded: OvenCavityOperationalStateClusterErrorStateStruct? = null
while (!tlvReader.isEndOfContainer()) {
val tag = tlvReader.peekElement().tag
if (tag == ContextSpecificTag(TAG_COMMAND_RESPONSE_STATE)) {
commandResponseState_decoded =
OvenCavityOperationalStateClusterErrorStateStruct.fromTlv(tag, tlvReader)
} else {
tlvReader.skipElement()
}
}
if (commandResponseState_decoded == null) {
throw IllegalStateException("commandResponseState not found in TLV")
}
tlvReader.exitContainer()
return OperationalCommandResponse(commandResponseState_decoded)
}
suspend fun resume(timedInvokeTimeout: Duration? = null): OperationalCommandResponse {
val commandId: UInt = 3u
val tlvWriter = TlvWriter()
tlvWriter.startStructure(AnonymousTag)
tlvWriter.endStructure()
val request: InvokeRequest =
InvokeRequest(
CommandPath(endpointId, clusterId = CLUSTER_ID, commandId),
tlvPayload = tlvWriter.getEncoded(),
timedRequest = timedInvokeTimeout
)
val response: InvokeResponse = controller.invoke(request)
logger.log(Level.FINE, "Invoke command succeeded: ${response}")
val tlvReader = TlvReader(response.payload)
tlvReader.enterStructure(AnonymousTag)
val TAG_COMMAND_RESPONSE_STATE: Int = 0
var commandResponseState_decoded: OvenCavityOperationalStateClusterErrorStateStruct? = null
while (!tlvReader.isEndOfContainer()) {
val tag = tlvReader.peekElement().tag
if (tag == ContextSpecificTag(TAG_COMMAND_RESPONSE_STATE)) {
commandResponseState_decoded =
OvenCavityOperationalStateClusterErrorStateStruct.fromTlv(tag, tlvReader)
} else {
tlvReader.skipElement()
}
}
if (commandResponseState_decoded == null) {
throw IllegalStateException("commandResponseState not found in TLV")
}
tlvReader.exitContainer()
return OperationalCommandResponse(commandResponseState_decoded)
}
suspend fun readPhaseListAttribute(): PhaseListAttribute {
val ATTRIBUTE_ID: UInt = 0u
val attributePath =
AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID)
val readRequest = ReadRequest(eventPaths = emptyList(), attributePaths = listOf(attributePath))
val response = controller.read(readRequest)
if (response.successes.isEmpty()) {
logger.log(Level.WARNING, "Read command failed")
throw IllegalStateException("Read command failed with failures: ${response.failures}")
}
logger.log(Level.FINE, "Read command succeeded")
val attributeData =
response.successes.filterIsInstance<ReadData.Attribute>().firstOrNull {
it.path.attributeId == ATTRIBUTE_ID
}
requireNotNull(attributeData) { "Phaselist attribute not found in response" }
// Decode the TLV data into the appropriate type
val tlvReader = TlvReader(attributeData.data)
val decodedValue: List<String>? =
if (!tlvReader.isNull()) {
buildList<String> {
tlvReader.enterArray(AnonymousTag)
while (!tlvReader.isEndOfContainer()) {
add(tlvReader.getString(AnonymousTag))
}
tlvReader.exitContainer()
}
} else {
tlvReader.getNull(AnonymousTag)
null
}
return PhaseListAttribute(decodedValue)
}
suspend fun subscribePhaseListAttribute(
minInterval: Int,
maxInterval: Int
): Flow<PhaseListAttributeSubscriptionState> {
val ATTRIBUTE_ID: UInt = 0u
val attributePaths =
listOf(
AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID)
)
val subscribeRequest: SubscribeRequest =
SubscribeRequest(
eventPaths = emptyList(),
attributePaths = attributePaths,
minInterval = Duration.ofSeconds(minInterval.toLong()),
maxInterval = Duration.ofSeconds(maxInterval.toLong())
)
return controller.subscribe(subscribeRequest).transform { subscriptionState ->
when (subscriptionState) {
is SubscriptionState.SubscriptionErrorNotification -> {
emit(
PhaseListAttributeSubscriptionState.Error(
Exception(
"Subscription terminated with error code: ${subscriptionState.terminationCause}"
)
)
)
}
is SubscriptionState.NodeStateUpdate -> {
val attributeData =
subscriptionState.updateState.successes
.filterIsInstance<ReadData.Attribute>()
.firstOrNull { it.path.attributeId == ATTRIBUTE_ID }
requireNotNull(attributeData) { "Phaselist attribute not found in Node State update" }
// Decode the TLV data into the appropriate type
val tlvReader = TlvReader(attributeData.data)
val decodedValue: List<String>? =
if (!tlvReader.isNull()) {
buildList<String> {
tlvReader.enterArray(AnonymousTag)
while (!tlvReader.isEndOfContainer()) {
add(tlvReader.getString(AnonymousTag))
}
tlvReader.exitContainer()
}
} else {
tlvReader.getNull(AnonymousTag)
null
}
decodedValue?.let { emit(PhaseListAttributeSubscriptionState.Success(it)) }
}
SubscriptionState.SubscriptionEstablished -> {
emit(PhaseListAttributeSubscriptionState.SubscriptionEstablished)
}
}
}
}
suspend fun readCurrentPhaseAttribute(): CurrentPhaseAttribute {
val ATTRIBUTE_ID: UInt = 1u
val attributePath =
AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID)
val readRequest = ReadRequest(eventPaths = emptyList(), attributePaths = listOf(attributePath))
val response = controller.read(readRequest)
if (response.successes.isEmpty()) {
logger.log(Level.WARNING, "Read command failed")
throw IllegalStateException("Read command failed with failures: ${response.failures}")
}
logger.log(Level.FINE, "Read command succeeded")
val attributeData =
response.successes.filterIsInstance<ReadData.Attribute>().firstOrNull {
it.path.attributeId == ATTRIBUTE_ID
}
requireNotNull(attributeData) { "Currentphase attribute not found in response" }
// Decode the TLV data into the appropriate type
val tlvReader = TlvReader(attributeData.data)
val decodedValue: UByte? =
if (!tlvReader.isNull()) {
tlvReader.getUByte(AnonymousTag)
} else {
tlvReader.getNull(AnonymousTag)
null
}
return CurrentPhaseAttribute(decodedValue)
}
suspend fun subscribeCurrentPhaseAttribute(
minInterval: Int,
maxInterval: Int
): Flow<CurrentPhaseAttributeSubscriptionState> {
val ATTRIBUTE_ID: UInt = 1u
val attributePaths =
listOf(
AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID)
)
val subscribeRequest: SubscribeRequest =
SubscribeRequest(
eventPaths = emptyList(),
attributePaths = attributePaths,
minInterval = Duration.ofSeconds(minInterval.toLong()),
maxInterval = Duration.ofSeconds(maxInterval.toLong())
)
return controller.subscribe(subscribeRequest).transform { subscriptionState ->
when (subscriptionState) {
is SubscriptionState.SubscriptionErrorNotification -> {
emit(
CurrentPhaseAttributeSubscriptionState.Error(
Exception(
"Subscription terminated with error code: ${subscriptionState.terminationCause}"
)
)
)
}
is SubscriptionState.NodeStateUpdate -> {
val attributeData =
subscriptionState.updateState.successes
.filterIsInstance<ReadData.Attribute>()
.firstOrNull { it.path.attributeId == ATTRIBUTE_ID }
requireNotNull(attributeData) { "Currentphase attribute not found in Node State update" }
// Decode the TLV data into the appropriate type
val tlvReader = TlvReader(attributeData.data)
val decodedValue: UByte? =
if (!tlvReader.isNull()) {
tlvReader.getUByte(AnonymousTag)
} else {
tlvReader.getNull(AnonymousTag)
null
}
decodedValue?.let { emit(CurrentPhaseAttributeSubscriptionState.Success(it)) }
}
SubscriptionState.SubscriptionEstablished -> {
emit(CurrentPhaseAttributeSubscriptionState.SubscriptionEstablished)
}
}
}
}
suspend fun readCountdownTimeAttribute(): CountdownTimeAttribute {
val ATTRIBUTE_ID: UInt = 2u
val attributePath =
AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID)
val readRequest = ReadRequest(eventPaths = emptyList(), attributePaths = listOf(attributePath))
val response = controller.read(readRequest)
if (response.successes.isEmpty()) {
logger.log(Level.WARNING, "Read command failed")
throw IllegalStateException("Read command failed with failures: ${response.failures}")
}
logger.log(Level.FINE, "Read command succeeded")
val attributeData =
response.successes.filterIsInstance<ReadData.Attribute>().firstOrNull {
it.path.attributeId == ATTRIBUTE_ID
}
requireNotNull(attributeData) { "Countdowntime attribute not found in response" }
// Decode the TLV data into the appropriate type
val tlvReader = TlvReader(attributeData.data)
val decodedValue: UInt? =
if (!tlvReader.isNull()) {
if (tlvReader.isNextTag(AnonymousTag)) {
tlvReader.getUInt(AnonymousTag)
} else {
null
}
} else {
tlvReader.getNull(AnonymousTag)
null
}
return CountdownTimeAttribute(decodedValue)
}
suspend fun subscribeCountdownTimeAttribute(
minInterval: Int,
maxInterval: Int
): Flow<CountdownTimeAttributeSubscriptionState> {
val ATTRIBUTE_ID: UInt = 2u
val attributePaths =
listOf(
AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID)
)
val subscribeRequest: SubscribeRequest =
SubscribeRequest(
eventPaths = emptyList(),
attributePaths = attributePaths,
minInterval = Duration.ofSeconds(minInterval.toLong()),
maxInterval = Duration.ofSeconds(maxInterval.toLong())
)
return controller.subscribe(subscribeRequest).transform { subscriptionState ->
when (subscriptionState) {
is SubscriptionState.SubscriptionErrorNotification -> {
emit(
CountdownTimeAttributeSubscriptionState.Error(
Exception(
"Subscription terminated with error code: ${subscriptionState.terminationCause}"
)
)
)
}
is SubscriptionState.NodeStateUpdate -> {
val attributeData =
subscriptionState.updateState.successes
.filterIsInstance<ReadData.Attribute>()
.firstOrNull { it.path.attributeId == ATTRIBUTE_ID }
requireNotNull(attributeData) { "Countdowntime attribute not found in Node State update" }
// Decode the TLV data into the appropriate type
val tlvReader = TlvReader(attributeData.data)
val decodedValue: UInt? =
if (!tlvReader.isNull()) {
if (tlvReader.isNextTag(AnonymousTag)) {
tlvReader.getUInt(AnonymousTag)
} else {
null
}
} else {
tlvReader.getNull(AnonymousTag)
null
}
decodedValue?.let { emit(CountdownTimeAttributeSubscriptionState.Success(it)) }
}
SubscriptionState.SubscriptionEstablished -> {
emit(CountdownTimeAttributeSubscriptionState.SubscriptionEstablished)
}
}
}
}
suspend fun readOperationalStateListAttribute(): OperationalStateListAttribute {
val ATTRIBUTE_ID: UInt = 3u
val attributePath =
AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID)
val readRequest = ReadRequest(eventPaths = emptyList(), attributePaths = listOf(attributePath))
val response = controller.read(readRequest)
if (response.successes.isEmpty()) {
logger.log(Level.WARNING, "Read command failed")
throw IllegalStateException("Read command failed with failures: ${response.failures}")
}
logger.log(Level.FINE, "Read command succeeded")
val attributeData =
response.successes.filterIsInstance<ReadData.Attribute>().firstOrNull {
it.path.attributeId == ATTRIBUTE_ID
}
requireNotNull(attributeData) { "Operationalstatelist attribute not found in response" }
// Decode the TLV data into the appropriate type
val tlvReader = TlvReader(attributeData.data)
val decodedValue: List<OvenCavityOperationalStateClusterOperationalStateStruct> =
buildList<OvenCavityOperationalStateClusterOperationalStateStruct> {
tlvReader.enterArray(AnonymousTag)
while (!tlvReader.isEndOfContainer()) {
add(
OvenCavityOperationalStateClusterOperationalStateStruct.fromTlv(AnonymousTag, tlvReader)
)
}
tlvReader.exitContainer()
}
return OperationalStateListAttribute(decodedValue)
}
suspend fun subscribeOperationalStateListAttribute(
minInterval: Int,
maxInterval: Int
): Flow<OperationalStateListAttributeSubscriptionState> {
val ATTRIBUTE_ID: UInt = 3u
val attributePaths =
listOf(
AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID)
)
val subscribeRequest: SubscribeRequest =
SubscribeRequest(
eventPaths = emptyList(),
attributePaths = attributePaths,
minInterval = Duration.ofSeconds(minInterval.toLong()),
maxInterval = Duration.ofSeconds(maxInterval.toLong())
)
return controller.subscribe(subscribeRequest).transform { subscriptionState ->
when (subscriptionState) {
is SubscriptionState.SubscriptionErrorNotification -> {
emit(
OperationalStateListAttributeSubscriptionState.Error(
Exception(
"Subscription terminated with error code: ${subscriptionState.terminationCause}"
)
)
)
}
is SubscriptionState.NodeStateUpdate -> {
val attributeData =
subscriptionState.updateState.successes
.filterIsInstance<ReadData.Attribute>()
.firstOrNull { it.path.attributeId == ATTRIBUTE_ID }
requireNotNull(attributeData) {
"Operationalstatelist attribute not found in Node State update"
}
// Decode the TLV data into the appropriate type
val tlvReader = TlvReader(attributeData.data)
val decodedValue: List<OvenCavityOperationalStateClusterOperationalStateStruct> =
buildList<OvenCavityOperationalStateClusterOperationalStateStruct> {
tlvReader.enterArray(AnonymousTag)
while (!tlvReader.isEndOfContainer()) {
add(
OvenCavityOperationalStateClusterOperationalStateStruct.fromTlv(
AnonymousTag,
tlvReader
)
)
}
tlvReader.exitContainer()
}
emit(OperationalStateListAttributeSubscriptionState.Success(decodedValue))
}
SubscriptionState.SubscriptionEstablished -> {
emit(OperationalStateListAttributeSubscriptionState.SubscriptionEstablished)
}
}
}
}
suspend fun readOperationalStateAttribute(): UByte {
val ATTRIBUTE_ID: UInt = 4u
val attributePath =
AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID)
val readRequest = ReadRequest(eventPaths = emptyList(), attributePaths = listOf(attributePath))
val response = controller.read(readRequest)
if (response.successes.isEmpty()) {
logger.log(Level.WARNING, "Read command failed")
throw IllegalStateException("Read command failed with failures: ${response.failures}")
}
logger.log(Level.FINE, "Read command succeeded")
val attributeData =
response.successes.filterIsInstance<ReadData.Attribute>().firstOrNull {
it.path.attributeId == ATTRIBUTE_ID
}
requireNotNull(attributeData) { "Operationalstate attribute not found in response" }
// Decode the TLV data into the appropriate type
val tlvReader = TlvReader(attributeData.data)
val decodedValue: UByte = tlvReader.getUByte(AnonymousTag)
return decodedValue
}
suspend fun subscribeOperationalStateAttribute(
minInterval: Int,
maxInterval: Int
): Flow<UByteSubscriptionState> {
val ATTRIBUTE_ID: UInt = 4u
val attributePaths =
listOf(
AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID)
)
val subscribeRequest: SubscribeRequest =
SubscribeRequest(
eventPaths = emptyList(),
attributePaths = attributePaths,
minInterval = Duration.ofSeconds(minInterval.toLong()),
maxInterval = Duration.ofSeconds(maxInterval.toLong())
)
return controller.subscribe(subscribeRequest).transform { subscriptionState ->
when (subscriptionState) {
is SubscriptionState.SubscriptionErrorNotification -> {
emit(
UByteSubscriptionState.Error(
Exception(
"Subscription terminated with error code: ${subscriptionState.terminationCause}"
)
)
)
}
is SubscriptionState.NodeStateUpdate -> {
val attributeData =
subscriptionState.updateState.successes
.filterIsInstance<ReadData.Attribute>()
.firstOrNull { it.path.attributeId == ATTRIBUTE_ID }
requireNotNull(attributeData) {
"Operationalstate attribute not found in Node State update"
}
// Decode the TLV data into the appropriate type
val tlvReader = TlvReader(attributeData.data)
val decodedValue: UByte = tlvReader.getUByte(AnonymousTag)
emit(UByteSubscriptionState.Success(decodedValue))
}
SubscriptionState.SubscriptionEstablished -> {
emit(UByteSubscriptionState.SubscriptionEstablished)
}
}
}
}
suspend fun readOperationalErrorAttribute(): OperationalErrorAttribute {
val ATTRIBUTE_ID: UInt = 5u
val attributePath =
AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID)
val readRequest = ReadRequest(eventPaths = emptyList(), attributePaths = listOf(attributePath))
val response = controller.read(readRequest)
if (response.successes.isEmpty()) {
logger.log(Level.WARNING, "Read command failed")
throw IllegalStateException("Read command failed with failures: ${response.failures}")
}
logger.log(Level.FINE, "Read command succeeded")
val attributeData =
response.successes.filterIsInstance<ReadData.Attribute>().firstOrNull {
it.path.attributeId == ATTRIBUTE_ID
}
requireNotNull(attributeData) { "Operationalerror attribute not found in response" }
// Decode the TLV data into the appropriate type
val tlvReader = TlvReader(attributeData.data)
val decodedValue: OvenCavityOperationalStateClusterErrorStateStruct =
OvenCavityOperationalStateClusterErrorStateStruct.fromTlv(AnonymousTag, tlvReader)
return OperationalErrorAttribute(decodedValue)
}
suspend fun subscribeOperationalErrorAttribute(
minInterval: Int,
maxInterval: Int
): Flow<OperationalErrorAttributeSubscriptionState> {
val ATTRIBUTE_ID: UInt = 5u
val attributePaths =
listOf(
AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID)
)
val subscribeRequest: SubscribeRequest =
SubscribeRequest(
eventPaths = emptyList(),
attributePaths = attributePaths,
minInterval = Duration.ofSeconds(minInterval.toLong()),
maxInterval = Duration.ofSeconds(maxInterval.toLong())
)
return controller.subscribe(subscribeRequest).transform { subscriptionState ->
when (subscriptionState) {
is SubscriptionState.SubscriptionErrorNotification -> {
emit(
OperationalErrorAttributeSubscriptionState.Error(
Exception(
"Subscription terminated with error code: ${subscriptionState.terminationCause}"
)
)
)
}
is SubscriptionState.NodeStateUpdate -> {
val attributeData =
subscriptionState.updateState.successes
.filterIsInstance<ReadData.Attribute>()
.firstOrNull { it.path.attributeId == ATTRIBUTE_ID }
requireNotNull(attributeData) {
"Operationalerror attribute not found in Node State update"
}
// Decode the TLV data into the appropriate type
val tlvReader = TlvReader(attributeData.data)
val decodedValue: OvenCavityOperationalStateClusterErrorStateStruct =
OvenCavityOperationalStateClusterErrorStateStruct.fromTlv(AnonymousTag, tlvReader)
emit(OperationalErrorAttributeSubscriptionState.Success(decodedValue))
}
SubscriptionState.SubscriptionEstablished -> {
emit(OperationalErrorAttributeSubscriptionState.SubscriptionEstablished)
}
}
}
}
suspend fun readGeneratedCommandListAttribute(): GeneratedCommandListAttribute {
val ATTRIBUTE_ID: UInt = 65528u
val attributePath =
AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID)
val readRequest = ReadRequest(eventPaths = emptyList(), attributePaths = listOf(attributePath))
val response = controller.read(readRequest)
if (response.successes.isEmpty()) {
logger.log(Level.WARNING, "Read command failed")
throw IllegalStateException("Read command failed with failures: ${response.failures}")
}
logger.log(Level.FINE, "Read command succeeded")
val attributeData =
response.successes.filterIsInstance<ReadData.Attribute>().firstOrNull {
it.path.attributeId == ATTRIBUTE_ID
}
requireNotNull(attributeData) { "Generatedcommandlist attribute not found in response" }
// Decode the TLV data into the appropriate type
val tlvReader = TlvReader(attributeData.data)
val decodedValue: List<UInt> =
buildList<UInt> {
tlvReader.enterArray(AnonymousTag)
while (!tlvReader.isEndOfContainer()) {
add(tlvReader.getUInt(AnonymousTag))
}
tlvReader.exitContainer()
}
return GeneratedCommandListAttribute(decodedValue)
}
suspend fun subscribeGeneratedCommandListAttribute(
minInterval: Int,
maxInterval: Int
): Flow<GeneratedCommandListAttributeSubscriptionState> {
val ATTRIBUTE_ID: UInt = 65528u
val attributePaths =
listOf(
AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID)
)
val subscribeRequest: SubscribeRequest =
SubscribeRequest(
eventPaths = emptyList(),
attributePaths = attributePaths,
minInterval = Duration.ofSeconds(minInterval.toLong()),
maxInterval = Duration.ofSeconds(maxInterval.toLong())
)
return controller.subscribe(subscribeRequest).transform { subscriptionState ->
when (subscriptionState) {
is SubscriptionState.SubscriptionErrorNotification -> {
emit(
GeneratedCommandListAttributeSubscriptionState.Error(
Exception(
"Subscription terminated with error code: ${subscriptionState.terminationCause}"
)
)
)
}
is SubscriptionState.NodeStateUpdate -> {
val attributeData =
subscriptionState.updateState.successes
.filterIsInstance<ReadData.Attribute>()
.firstOrNull { it.path.attributeId == ATTRIBUTE_ID }
requireNotNull(attributeData) {
"Generatedcommandlist attribute not found in Node State update"
}
// Decode the TLV data into the appropriate type
val tlvReader = TlvReader(attributeData.data)
val decodedValue: List<UInt> =
buildList<UInt> {
tlvReader.enterArray(AnonymousTag)
while (!tlvReader.isEndOfContainer()) {
add(tlvReader.getUInt(AnonymousTag))
}
tlvReader.exitContainer()
}
emit(GeneratedCommandListAttributeSubscriptionState.Success(decodedValue))
}
SubscriptionState.SubscriptionEstablished -> {
emit(GeneratedCommandListAttributeSubscriptionState.SubscriptionEstablished)
}
}
}
}
suspend fun readAcceptedCommandListAttribute(): AcceptedCommandListAttribute {
val ATTRIBUTE_ID: UInt = 65529u
val attributePath =
AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID)
val readRequest = ReadRequest(eventPaths = emptyList(), attributePaths = listOf(attributePath))
val response = controller.read(readRequest)
if (response.successes.isEmpty()) {
logger.log(Level.WARNING, "Read command failed")
throw IllegalStateException("Read command failed with failures: ${response.failures}")
}
logger.log(Level.FINE, "Read command succeeded")
val attributeData =
response.successes.filterIsInstance<ReadData.Attribute>().firstOrNull {
it.path.attributeId == ATTRIBUTE_ID
}
requireNotNull(attributeData) { "Acceptedcommandlist attribute not found in response" }
// Decode the TLV data into the appropriate type
val tlvReader = TlvReader(attributeData.data)
val decodedValue: List<UInt> =
buildList<UInt> {
tlvReader.enterArray(AnonymousTag)
while (!tlvReader.isEndOfContainer()) {
add(tlvReader.getUInt(AnonymousTag))
}
tlvReader.exitContainer()
}
return AcceptedCommandListAttribute(decodedValue)
}
suspend fun subscribeAcceptedCommandListAttribute(
minInterval: Int,
maxInterval: Int
): Flow<AcceptedCommandListAttributeSubscriptionState> {
val ATTRIBUTE_ID: UInt = 65529u
val attributePaths =
listOf(
AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID)
)
val subscribeRequest: SubscribeRequest =
SubscribeRequest(
eventPaths = emptyList(),
attributePaths = attributePaths,
minInterval = Duration.ofSeconds(minInterval.toLong()),
maxInterval = Duration.ofSeconds(maxInterval.toLong())
)
return controller.subscribe(subscribeRequest).transform { subscriptionState ->
when (subscriptionState) {
is SubscriptionState.SubscriptionErrorNotification -> {
emit(
AcceptedCommandListAttributeSubscriptionState.Error(
Exception(
"Subscription terminated with error code: ${subscriptionState.terminationCause}"
)
)
)
}
is SubscriptionState.NodeStateUpdate -> {
val attributeData =
subscriptionState.updateState.successes
.filterIsInstance<ReadData.Attribute>()
.firstOrNull { it.path.attributeId == ATTRIBUTE_ID }
requireNotNull(attributeData) {
"Acceptedcommandlist attribute not found in Node State update"
}
// Decode the TLV data into the appropriate type
val tlvReader = TlvReader(attributeData.data)
val decodedValue: List<UInt> =
buildList<UInt> {
tlvReader.enterArray(AnonymousTag)
while (!tlvReader.isEndOfContainer()) {
add(tlvReader.getUInt(AnonymousTag))
}
tlvReader.exitContainer()
}
emit(AcceptedCommandListAttributeSubscriptionState.Success(decodedValue))
}
SubscriptionState.SubscriptionEstablished -> {
emit(AcceptedCommandListAttributeSubscriptionState.SubscriptionEstablished)
}
}
}
}
suspend fun readEventListAttribute(): EventListAttribute {
val ATTRIBUTE_ID: UInt = 65530u
val attributePath =
AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID)
val readRequest = ReadRequest(eventPaths = emptyList(), attributePaths = listOf(attributePath))
val response = controller.read(readRequest)
if (response.successes.isEmpty()) {
logger.log(Level.WARNING, "Read command failed")
throw IllegalStateException("Read command failed with failures: ${response.failures}")
}
logger.log(Level.FINE, "Read command succeeded")
val attributeData =
response.successes.filterIsInstance<ReadData.Attribute>().firstOrNull {
it.path.attributeId == ATTRIBUTE_ID
}
requireNotNull(attributeData) { "Eventlist attribute not found in response" }
// Decode the TLV data into the appropriate type
val tlvReader = TlvReader(attributeData.data)
val decodedValue: List<UInt> =
buildList<UInt> {
tlvReader.enterArray(AnonymousTag)
while (!tlvReader.isEndOfContainer()) {
add(tlvReader.getUInt(AnonymousTag))
}
tlvReader.exitContainer()
}
return EventListAttribute(decodedValue)
}
suspend fun subscribeEventListAttribute(
minInterval: Int,
maxInterval: Int
): Flow<EventListAttributeSubscriptionState> {
val ATTRIBUTE_ID: UInt = 65530u
val attributePaths =
listOf(
AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID)
)
val subscribeRequest: SubscribeRequest =
SubscribeRequest(
eventPaths = emptyList(),
attributePaths = attributePaths,
minInterval = Duration.ofSeconds(minInterval.toLong()),
maxInterval = Duration.ofSeconds(maxInterval.toLong())
)
return controller.subscribe(subscribeRequest).transform { subscriptionState ->
when (subscriptionState) {
is SubscriptionState.SubscriptionErrorNotification -> {
emit(
EventListAttributeSubscriptionState.Error(
Exception(
"Subscription terminated with error code: ${subscriptionState.terminationCause}"
)
)
)
}
is SubscriptionState.NodeStateUpdate -> {
val attributeData =
subscriptionState.updateState.successes
.filterIsInstance<ReadData.Attribute>()
.firstOrNull { it.path.attributeId == ATTRIBUTE_ID }
requireNotNull(attributeData) { "Eventlist attribute not found in Node State update" }
// Decode the TLV data into the appropriate type
val tlvReader = TlvReader(attributeData.data)
val decodedValue: List<UInt> =
buildList<UInt> {
tlvReader.enterArray(AnonymousTag)
while (!tlvReader.isEndOfContainer()) {
add(tlvReader.getUInt(AnonymousTag))
}
tlvReader.exitContainer()
}
emit(EventListAttributeSubscriptionState.Success(decodedValue))
}
SubscriptionState.SubscriptionEstablished -> {
emit(EventListAttributeSubscriptionState.SubscriptionEstablished)
}
}
}
}
suspend fun readAttributeListAttribute(): AttributeListAttribute {
val ATTRIBUTE_ID: UInt = 65531u
val attributePath =
AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID)
val readRequest = ReadRequest(eventPaths = emptyList(), attributePaths = listOf(attributePath))
val response = controller.read(readRequest)
if (response.successes.isEmpty()) {
logger.log(Level.WARNING, "Read command failed")
throw IllegalStateException("Read command failed with failures: ${response.failures}")
}
logger.log(Level.FINE, "Read command succeeded")
val attributeData =
response.successes.filterIsInstance<ReadData.Attribute>().firstOrNull {
it.path.attributeId == ATTRIBUTE_ID
}
requireNotNull(attributeData) { "Attributelist attribute not found in response" }
// Decode the TLV data into the appropriate type
val tlvReader = TlvReader(attributeData.data)
val decodedValue: List<UInt> =
buildList<UInt> {
tlvReader.enterArray(AnonymousTag)
while (!tlvReader.isEndOfContainer()) {
add(tlvReader.getUInt(AnonymousTag))
}
tlvReader.exitContainer()
}
return AttributeListAttribute(decodedValue)
}
suspend fun subscribeAttributeListAttribute(
minInterval: Int,
maxInterval: Int
): Flow<AttributeListAttributeSubscriptionState> {
val ATTRIBUTE_ID: UInt = 65531u
val attributePaths =
listOf(
AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID)
)
val subscribeRequest: SubscribeRequest =
SubscribeRequest(
eventPaths = emptyList(),
attributePaths = attributePaths,
minInterval = Duration.ofSeconds(minInterval.toLong()),
maxInterval = Duration.ofSeconds(maxInterval.toLong())
)
return controller.subscribe(subscribeRequest).transform { subscriptionState ->
when (subscriptionState) {
is SubscriptionState.SubscriptionErrorNotification -> {
emit(
AttributeListAttributeSubscriptionState.Error(
Exception(
"Subscription terminated with error code: ${subscriptionState.terminationCause}"
)
)
)
}
is SubscriptionState.NodeStateUpdate -> {
val attributeData =
subscriptionState.updateState.successes
.filterIsInstance<ReadData.Attribute>()
.firstOrNull { it.path.attributeId == ATTRIBUTE_ID }
requireNotNull(attributeData) { "Attributelist attribute not found in Node State update" }
// Decode the TLV data into the appropriate type
val tlvReader = TlvReader(attributeData.data)
val decodedValue: List<UInt> =
buildList<UInt> {
tlvReader.enterArray(AnonymousTag)
while (!tlvReader.isEndOfContainer()) {
add(tlvReader.getUInt(AnonymousTag))
}
tlvReader.exitContainer()
}
emit(AttributeListAttributeSubscriptionState.Success(decodedValue))
}
SubscriptionState.SubscriptionEstablished -> {
emit(AttributeListAttributeSubscriptionState.SubscriptionEstablished)
}
}
}
}
suspend fun readFeatureMapAttribute(): UInt {
val ATTRIBUTE_ID: UInt = 65532u
val attributePath =
AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID)
val readRequest = ReadRequest(eventPaths = emptyList(), attributePaths = listOf(attributePath))
val response = controller.read(readRequest)
if (response.successes.isEmpty()) {
logger.log(Level.WARNING, "Read command failed")
throw IllegalStateException("Read command failed with failures: ${response.failures}")
}
logger.log(Level.FINE, "Read command succeeded")
val attributeData =
response.successes.filterIsInstance<ReadData.Attribute>().firstOrNull {
it.path.attributeId == ATTRIBUTE_ID
}
requireNotNull(attributeData) { "Featuremap attribute not found in response" }
// Decode the TLV data into the appropriate type
val tlvReader = TlvReader(attributeData.data)
val decodedValue: UInt = tlvReader.getUInt(AnonymousTag)
return decodedValue
}
suspend fun subscribeFeatureMapAttribute(
minInterval: Int,
maxInterval: Int
): Flow<UIntSubscriptionState> {
val ATTRIBUTE_ID: UInt = 65532u
val attributePaths =
listOf(
AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID)
)
val subscribeRequest: SubscribeRequest =
SubscribeRequest(
eventPaths = emptyList(),
attributePaths = attributePaths,
minInterval = Duration.ofSeconds(minInterval.toLong()),
maxInterval = Duration.ofSeconds(maxInterval.toLong())
)
return controller.subscribe(subscribeRequest).transform { subscriptionState ->
when (subscriptionState) {
is SubscriptionState.SubscriptionErrorNotification -> {
emit(
UIntSubscriptionState.Error(
Exception(
"Subscription terminated with error code: ${subscriptionState.terminationCause}"
)
)
)
}
is SubscriptionState.NodeStateUpdate -> {
val attributeData =
subscriptionState.updateState.successes
.filterIsInstance<ReadData.Attribute>()
.firstOrNull { it.path.attributeId == ATTRIBUTE_ID }
requireNotNull(attributeData) { "Featuremap attribute not found in Node State update" }
// Decode the TLV data into the appropriate type
val tlvReader = TlvReader(attributeData.data)
val decodedValue: UInt = tlvReader.getUInt(AnonymousTag)
emit(UIntSubscriptionState.Success(decodedValue))
}
SubscriptionState.SubscriptionEstablished -> {
emit(UIntSubscriptionState.SubscriptionEstablished)
}
}
}
}
suspend fun readClusterRevisionAttribute(): UShort {
val ATTRIBUTE_ID: UInt = 65533u
val attributePath =
AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID)
val readRequest = ReadRequest(eventPaths = emptyList(), attributePaths = listOf(attributePath))
val response = controller.read(readRequest)
if (response.successes.isEmpty()) {
logger.log(Level.WARNING, "Read command failed")
throw IllegalStateException("Read command failed with failures: ${response.failures}")
}
logger.log(Level.FINE, "Read command succeeded")
val attributeData =
response.successes.filterIsInstance<ReadData.Attribute>().firstOrNull {
it.path.attributeId == ATTRIBUTE_ID
}
requireNotNull(attributeData) { "Clusterrevision attribute not found in response" }
// Decode the TLV data into the appropriate type
val tlvReader = TlvReader(attributeData.data)
val decodedValue: UShort = tlvReader.getUShort(AnonymousTag)
return decodedValue
}
suspend fun subscribeClusterRevisionAttribute(
minInterval: Int,
maxInterval: Int
): Flow<UShortSubscriptionState> {
val ATTRIBUTE_ID: UInt = 65533u
val attributePaths =
listOf(
AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID)
)
val subscribeRequest: SubscribeRequest =
SubscribeRequest(
eventPaths = emptyList(),
attributePaths = attributePaths,
minInterval = Duration.ofSeconds(minInterval.toLong()),
maxInterval = Duration.ofSeconds(maxInterval.toLong())
)
return controller.subscribe(subscribeRequest).transform { subscriptionState ->
when (subscriptionState) {
is SubscriptionState.SubscriptionErrorNotification -> {
emit(
UShortSubscriptionState.Error(
Exception(
"Subscription terminated with error code: ${subscriptionState.terminationCause}"
)
)
)
}
is SubscriptionState.NodeStateUpdate -> {
val attributeData =
subscriptionState.updateState.successes
.filterIsInstance<ReadData.Attribute>()
.firstOrNull { it.path.attributeId == ATTRIBUTE_ID }
requireNotNull(attributeData) {
"Clusterrevision attribute not found in Node State update"
}
// Decode the TLV data into the appropriate type
val tlvReader = TlvReader(attributeData.data)
val decodedValue: UShort = tlvReader.getUShort(AnonymousTag)
emit(UShortSubscriptionState.Success(decodedValue))
}
SubscriptionState.SubscriptionEstablished -> {
emit(UShortSubscriptionState.SubscriptionEstablished)
}
}
}
}
companion object {
private val logger = Logger.getLogger(OvenCavityOperationalStateCluster::class.java.name)
const val CLUSTER_ID: UInt = 72u
}
}
| 5 | null | 57 | 6,671 | 420e6d424c00aed3ead4015eafd71a1632c5e540 | 50,228 | connectedhomeip | Apache License 2.0 |
app/src/test/java/com/teobaranga/monica/TestDispatcher.kt | teobaranga | 686,113,276 | false | {"Kotlin": 269714} | package com.teobaranga.monica
import com.teobaranga.monica.util.coroutines.Dispatcher
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.UnconfinedTestDispatcher
@OptIn(ExperimentalCoroutinesApi::class)
class TestDispatcher : Dispatcher {
override val main = UnconfinedTestDispatcher()
override val io = UnconfinedTestDispatcher()
}
| 1 | Kotlin | 1 | 8 | b14afe98fc1d5eb67782ad106aeee607ab267c80 | 375 | monica | Apache License 2.0 |
app/src/main/java/com/example/moviedatabase/allMovies/presentation/AllMoviesScreen.kt | ali-gevari | 838,166,478 | false | {"Kotlin": 150986} | package com.example.moviedatabase.allMovies.presentation
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.example.moviedatabase.compose.MovieCard
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import com.example.moviedatabase.R
import com.example.moviedatabase.allMovies.domain.entity.MovieProgram
@Composable
internal fun AllMoviesScreen(
viewModel: AllMoviesViewModel = hiltViewModel(),
onItemClick: (MovieProgram) -> Unit
) {
val state by viewModel.state.collectAsStateWithLifecycle()
AllMoviesContent(state = state, onItemClick)
}
@Composable
fun AllMoviesContent(
state: AllMoviesViewState,
onItemClick: (MovieProgram) -> Unit
) {
Column(
modifier = Modifier.padding(vertical = 8.dp)
) {
Text(
text = stringResource(R.string.movies_in_theaters),
style = MaterialTheme.typography.titleLarge,
color = MaterialTheme.colorScheme.primary,
modifier = Modifier
.padding(horizontal = 16.dp)
.padding(bottom = 8.dp)
)
LazyRow(
modifier = Modifier
.padding(vertical = 8.dp)
.height(360.dp),
horizontalArrangement = Arrangement.spacedBy(16.dp),
contentPadding = PaddingValues(horizontal = 16.dp)
) {
items(state.moviePrograms) { program ->
MovieCard(
modifier = Modifier.testTag("MovieCard"),
program = program,
onClick = onItemClick
)
}
}
}
} | 2 | Kotlin | 0 | 0 | d485ccf9e6fab0107155921d4b233af31346061a | 2,303 | MovieDatabase | Apache License 2.0 |
compiler/testData/codegen/boxInline/smap/resolve/inlineComponent.kt | JetBrains | 3,432,266 | false | null | // FILE: 1.kt
package zzz
public class A(val a: Int, val b: Int)
operator inline fun A.component1() = a
operator inline fun A.component2() = b
// FILE: 2.kt
import zzz.*
fun box(): String {
var (p, l) = A(1, 11)
return if (p == 1 && l == 11) "OK" else "fail: $p"
}
| 183 | null | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 281 | kotlin | Apache License 2.0 |
ybatis/src/main/kotlin/com/sununiq/handler/RefProcessor.kt | Sitrone | 155,659,453 | false | {"Text": 1, "Ignore List": 1, "Markdown": 1, "Maven POM": 3, "XML": 3, "Kotlin": 44, "Java": 12, "YAML": 1} | package com.sununiq.handler
import com.sununiq.entity.Table
import com.sununiq.handler.token.TokenParser
import com.sununiq.util.getResourceAsString
import org.w3c.dom.Element
import org.w3c.dom.Node
import java.io.File
/**
* ๅค็ๅค้จๅผ็จๆไปถ
*/
class RefProcessor : NodeProcessor {
override fun process(table: Table, node: Node, tokenParser: TokenParser): String {
val element = node as Element
val path = element.getAttribute("path")
val parseResult = tokenParser.parse(table, path)
val refFilePath = parseResult.replace("classpath:", "")
// TODO ๅ ๅคๆญ
// if (!File(refFilePath).exists()) {
// return ""
// }
return getResourceAsString(refFilePath)
}
} | 1 | null | 1 | 1 | e06616a6f541f45ec7f61707667eda6af04d15e1 | 731 | mybatis-enhancer | MIT License |
kotlin-plugin/src/main/kotlin/io/github/kyay10/kotlinlambdareturninliner/LambdaReturnInlinerIrGenerationExtension.kt | kyay10 | 345,163,139 | false | null | /*
* Copyright (C) 2020 <NAME>
* Copyright (C) 2021 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("unused", "MemberVisibilityCanBePrivate", "ReplaceNotNullAssertionWithElvisReturn")
package io.github.kyay10.kotlinlambdareturninliner
import io.github.kyay10.kotlinlambdareturninliner.internal.inline
import io.github.kyay10.kotlinlambdareturninliner.utils.*
import io.github.kyay10.kotlinlambdareturninliner.utils.deepCopyWithSymbols
import org.jetbrains.kotlin.backend.common.extensions.IrGenerationExtension
import org.jetbrains.kotlin.backend.common.extensions.IrPluginContext
import org.jetbrains.kotlin.backend.common.lower.DeclarationIrBuilder
import org.jetbrains.kotlin.backend.common.lower.at
import org.jetbrains.kotlin.backend.jvm.ir.erasedUpperBound
import org.jetbrains.kotlin.cli.common.messages.MessageCollector
import org.jetbrains.kotlin.com.intellij.openapi.project.Project
import org.jetbrains.kotlin.config.CompilerConfiguration
import org.jetbrains.kotlin.contracts.parsing.isContractCallDescriptor
import org.jetbrains.kotlin.ir.IrStatement
import org.jetbrains.kotlin.ir.ObsoleteDescriptorBasedAPI
import org.jetbrains.kotlin.ir.builders.*
import org.jetbrains.kotlin.ir.builders.declarations.buildFun
import org.jetbrains.kotlin.ir.builders.declarations.buildTypeParameter
import org.jetbrains.kotlin.ir.builders.declarations.buildValueParameter
import org.jetbrains.kotlin.ir.declarations.*
import org.jetbrains.kotlin.ir.expressions.*
import org.jetbrains.kotlin.ir.expressions.IrTypeOperator.*
import org.jetbrains.kotlin.ir.expressions.impl.IrFunctionExpressionImpl
import org.jetbrains.kotlin.ir.symbols.IrReturnableBlockSymbol
import org.jetbrains.kotlin.ir.symbols.IrValueSymbol
import org.jetbrains.kotlin.ir.types.*
import org.jetbrains.kotlin.ir.util.*
import org.jetbrains.kotlin.ir.visitors.IrElementTransformerVoid
import org.jetbrains.kotlin.ir.visitors.transformChildrenVoid
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.resolve.jvm.annotations.JVM_SYNTHETIC_ANNOTATION_FQ_NAME
import org.jetbrains.kotlin.types.typeUtil.isNothingOrNullableNothing
import org.jetbrains.kotlin.util.OperatorNameConventions
import org.jetbrains.kotlin.utils.addToStdlib.cast
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull
val INLINE_INVOKE_FQNAME = FqName(BuildConfig.INLINE_INVOKE_FQNAME)
val CONTAINS_COPIED_DECLARATIONS_ANNOTATION_FQNAME = FqName(BuildConfig.CONTAINS_COPIED_DECLARATIONS_ANNOTATION_FQNAME)
class LambdaReturnInlinerIrGenerationExtension(
private val project: Project,
private val messageCollector: MessageCollector,
private val compilerConfig: CompilerConfiguration,
private val renamesMap: MutableMap<String, String>
) : IrGenerationExtension {
var shadowsContext: IrPluginContext? = null
@OptIn(ExperimentalStdlibApi::class, ObsoleteDescriptorBasedAPI::class)
override fun generate(moduleFragment: IrModuleFragment, pluginContext: IrPluginContext) {
if (compilerConfig[IS_GENERATING_SHADOWED_DECLARATIONS] == true) {
shadowsContext = pluginContext
}
//println(moduleFragment.dump())
//println(moduleFragment.dumpKotlinLike())
val tempsToAdd: MutableMap<IrFunction, MutableList<IrVariable>> = mutableMapOf()
val deferredAddedFunctions: MutableMap<IrFunction, IrFile> = mutableMapOf()
val transformer = InlineHigherOrderFunctionsAndVariablesTransformer(pluginContext, renamesMap, shadowsContext)
moduleFragment.lowerWith(transformer)
moduleFragment.lowerWith(
CollapseContainerExpressionsReturningFunctionExpressionsTransformer(
pluginContext
)
)
moduleFragment.lowerWith(CoercionToUnitWithUselessFunctionObjectTransformer(pluginContext))
// Reinterpret WhenWithMapper
moduleFragment.lowerWith(object :
IrFileTransformerVoidWithContext(pluginContext) {
override fun visitWhen(expression: IrWhen): IrExpression {
var returnExpression: IrExpression = expression
if (expression is IrWhenWithMapper) {
val elseBranch = expression.branches.firstIsInstanceOrNull<IrElseBranch>()
returnExpression = (if (elseBranch != null) declarationIrBuilder.createWhenAccessForLambda(
expression.type,
expression.tempInt,
expression.mapper,
context,
elseBranch
) else declarationIrBuilder.createWhenAccessForLambda(
expression.type,
expression.tempInt,
expression.mapper,
context,
)).takeIf { it !is IrWhenWithMapper }
?: expression // Only reinterpret the IrWhenWithMapper if it would become a different kind of IrExpression
}
super.visitExpression(returnExpression)
return returnExpression
}
})
// Some reinterpreted whens will now contain run calls that have their block argument surrounded with
// an IrContainerExpression, and so just ensure that they're collapsed so that they get inlined property
moduleFragment.lowerWith(
CollapseContainerExpressionsReturningFunctionExpressionsTransformer(
pluginContext
)
)
val variableToConstantValue = mutableMapOf<IrValueSymbol, IrExpression>()
moduleFragment.lowerWith(object : IrFileTransformerVoidWithContext(pluginContext) {
override fun visitSetValue(expression: IrSetValue): IrExpression {
val result = super.visitSetValue(expression)
if (expression.symbol.owner.isImmutable) {
val trueValue = expression.value.lastElement().safeAs<IrExpression>()?.extractFromReturnIfNeeded()
if (trueValue is IrGetEnumValue) {
variableToConstantValue[expression.symbol] = trueValue
}
if (trueValue is IrConst<*>) {
variableToConstantValue[expression.symbol] = trueValue
}
}
return result
}
override fun visitVariable(declaration: IrVariable): IrStatement {
val result = super.visitVariable(declaration)
if (!declaration.isVar) {
val trueValue = declaration.initializer?.lastElement()?.safeAs<IrExpression>()?.extractFromReturnIfNeeded()
if (trueValue is IrGetEnumValue) {
variableToConstantValue[declaration.symbol] = trueValue
}
if (trueValue is IrConst<*>) {
variableToConstantValue[declaration.symbol] = trueValue
}
}
return result
}
override fun visitGetValue(expression: IrGetValue): IrExpression {
return variableToConstantValue[expression.symbol]?.deepCopyWithSymbols(
currentDeclarationParent,
::WhenWithMapperAwareDeepCopyIrTreeWithSymbols
) ?: super.visitGetValue(expression)
}
override fun visitFunctionAccess(expression: IrFunctionAccessExpression): IrExpression {
if (expression.isInvokeCall) {
expression.dispatchReceiver.safeAs<IrFunctionExpression>()?.function?.let { function ->
for (parameterIndex in 0 until expression.valueArgumentsCount) {
val argument = expression.getValueArgument(parameterIndex)
val parameterSymbol = function.valueParameters[parameterIndex].symbol
val trueValue = argument?.lastElement()?.safeAs<IrExpression>()?.extractFromReturnIfNeeded()
if (trueValue is IrGetEnumValue) {
variableToConstantValue[parameterSymbol] = trueValue
}
if (trueValue is IrConst<*>) {
variableToConstantValue[parameterSymbol] = trueValue
}
}
}
}
return super.visitFunctionAccess(expression)
}
})
moduleFragment.lowerWith(object : IrFileTransformerVoidWithContext(pluginContext) {
override fun visitGetValue(expression: IrGetValue): IrExpression {
return variableToConstantValue[expression.symbol]?.deepCopyWithSymbols(
currentDeclarationParent,
::WhenWithMapperAwareDeepCopyIrTreeWithSymbols
) ?: super.visitGetValue(expression)
}
override fun visitWhen(expression: IrWhen): IrExpression {
val result = super.visitWhen(expression)
val branchIndicesToDelete = mutableListOf<Int>()
val singlePossibleBranch = run {
var previousBranchesAllFalse = true
expression.branches.forEachIndexed { index, branch ->
branch.condition.calculatePredeterminedEqualityIfPossible(
context
)?.let { predeterminedEquality ->
if (predeterminedEquality) {
if (previousBranchesAllFalse) {
return@run branch.result
} else Unit
} else branchIndicesToDelete.add(index)
} ?: run { previousBranchesAllFalse = false }
}
null
}
if (singlePossibleBranch != null)
return singlePossibleBranch
for (branchIndexToDelete in branchIndicesToDelete) expression.branches.removeAt(branchIndexToDelete)
return result
}
})
moduleFragment.lowerWith(CoercionToUnitWithUselessFunctionObjectTransformer(pluginContext))
moduleFragment.lowerWith(object :
IrFileTransformerVoidWithContext(pluginContext) {
override fun visitFunctionNew(declaration: IrFunction): IrStatement {
tempsToAdd[declaration] = tempsToAdd[declaration] ?: mutableListOf()
return super.visitFunctionNew(declaration)
}
override fun visitVariable(declaration: IrVariable): IrStatement {
if (declaration.type.isFunctionTypeOrSubtype) {
declaration.initializer?.replaceLastElementAndIterateBranches({ replacer, statement ->
declaration.initializer = replacer(statement).cast()
}, declaration.type) {
if (it is IrFunctionExpression)
declarationIrBuilder.irNull() // TODO: add configuration option for this and allow its usage for non-inline usages
else it
}
}
return if (declaration.origin == IrDeclarationOrigin.IR_TEMPORARY_VARIABLE || declaration.isVar) {
super.visitVariable(declaration)
declarationIrBuilder.irBlock {
tempsToAdd[allScopes.first { it.irElement is IrFunction }.irElement.cast()]?.add(declaration)
declaration.initializer?.let {
+irSet(declaration.symbol, it)
declaration.initializer = null
}
}
} else super.visitVariable(declaration)
}
})
moduleFragment.lowerWith(object :
IrFileTransformerVoidWithContext(pluginContext) {
override fun visitFunctionNew(declaration: IrFunction): IrStatement {
tempsToAdd[declaration]?.takeIf { it.isNotEmpty() }
?.let {
declaration.body.cast<IrBlockBody>().statements.addAll(0, it)
declaration.body?.patchDeclarationParents(declaration)
}
return super.visitFunctionNew(declaration)
}
})
moduleFragment.lowerWith(InlineInvokeTransformer(pluginContext, deferredAddedFunctions))
for ((deferredAddedFunction, file) in deferredAddedFunctions) {
file.declarations.add(deferredAddedFunction)
deferredAddedFunction.parent = file
}
moduleFragment.files.removeIf { file ->
file.annotations.any { it.isAnnotationWithEqualFqName(CONTAINS_COPIED_DECLARATIONS_ANNOTATION_FQNAME) }
}
// println(moduleFragment.dump()) //TODO: only dump in debug mode
// println(moduleFragment.dumpKotlinLike())
}
}
fun IrExpression.extractFromReturnIfNeeded(): IrExpression =
if (this is IrReturn && this.returnTargetSymbol is IrReturnableBlockSymbol) value.lastElement().cast<IrExpression>()
.extractFromReturnIfNeeded() else this
fun IrExpression.calculatePredeterminedEqualityIfPossible(context: IrPluginContext): Boolean? {
val trueElement = lastElement().cast<IrExpression>().extractFromReturnIfNeeded()
if (trueElement is IrConst<*> && trueElement.kind == IrConstKind.Boolean) return trueElement.cast<IrConst<Boolean>>().value
if (trueElement is IrCall && (trueElement.symbol == context.irBuiltIns.eqeqSymbol || trueElement.symbol == context.irBuiltIns.eqeqeqSymbol)) {
val lhs = trueElement.getValueArgument(0)?.extractCompileTimeConstantFromIrGetIfPossible()
val rhs = trueElement.getValueArgument(1)?.extractCompileTimeConstantFromIrGetIfPossible()
if (lhs is IrGetEnumValue && rhs is IrGetEnumValue) return lhs.symbol == rhs.symbol
if (lhs is IrConst<*> && rhs is IrConst<*>) return lhs.value == rhs.value
}
return null
}
fun IrExpression.extractCompileTimeConstantFromIrGetIfPossible(): IrExpression =
safeAs<IrGetValue>()?.symbol?.owner?.safeAs<IrVariable>()
?.takeIf { !it.isVar && it.origin == IrDeclarationOrigin.IR_TEMPORARY_VARIABLE }?.initializer?.lastElement()
?.safeAs<IrExpression>()?.extractFromReturnIfNeeded()?.extractCompileTimeConstantFromIrGetIfPossible() ?: this
class CollapseContainerExpressionsReturningFunctionExpressionsTransformer(pluginContext: IrPluginContext) :
IrFileTransformerVoidWithContext(pluginContext) {
val functionAccesses = mutableListOf<IrExpression>()
@OptIn(ExperimentalStdlibApi::class)
override fun visitFunctionAccess(expression: IrFunctionAccessExpression): IrExpression {
val result = expression.run {
if (expression in functionAccesses)
return@run expression
val params = buildList(valueArgumentsCount + 2) {
add(dispatchReceiver)
add(extensionReceiver)
for (i in 0 until valueArgumentsCount) add(getValueArgument(i))
}
declarationIrBuilder.irBlock {
var lambdaBlockArgumentFound = false
params.forEachIndexed { index, value ->
if (value != null && value.type.isFunctionTypeOrSubtype && value !is IrFunctionExpression) {
lambdaBlockArgumentFound = true
val accumulatedStatements = accumulateStatements(value)
val newArgumentValue = accumulatedStatements.last() as IrExpression
accumulatedStatements.apply { removeLast() }
.forEach { +it }
expression.changeArgument(index, newArgumentValue)
}
}
if (!lambdaBlockArgumentFound)
return@run expression
+expression
functionAccesses.add(expression)
}
}
return super.visitExpression(result)
}
}
class InlineInvokeTransformer(
pluginContext: IrPluginContext,
private val deferredAddedFunctions: MutableMap<IrFunction, IrFile>
) : IrFileTransformerVoidWithContext(pluginContext) {
// Basically just searches for this function:
// ```
// inline fun <R> inlineInvoke(block: () -> R): R {
// return block()
//}
//```
private val inlineInvoke0 = context.referenceFunctions(INLINE_INVOKE_FQNAME)
.first {
it.owner.let { irFunction ->
irFunction.valueParameters.size == 1 &&
irFunction.typeParameters.size == 1 &&
irFunction.returnType.cast<IrSimpleType>().classifier.owner == irFunction.typeParameters.first() &&
irFunction.isInline &&
irFunction.valueParameters.first().type.isFunctionTypeOrSubtype
}
}.owner
// Initialize with the magic number 22 since those are the most common arities.
private val inlineInvokeDefs = ArrayList<IrSimpleFunction?>(22)
@OptIn(ExperimentalStdlibApi::class)
override fun visitFunctionAccess(expression: IrFunctionAccessExpression): IrExpression {
var returnExpression: IrExpression = expression
val irFunction = expression.symbol.owner
// Only replace invoke calls
if (expression.isInvokeCall) {
val replacementInlineInvokeFunction =
inlineInvokeDefs.getOrNull(expression.valueArgumentsCount)
?: inlineInvoke0.parent.cast<IrDeclaration>().factory.buildFun {
updateFrom(inlineInvoke0)
name = inlineInvoke0.name
returnType = inlineInvoke0.returnType
containerSource = null
}.apply {
annotations = listOf(
declarationIrBuilder.irCallConstructor(
context.referenceConstructors(
JVM_SYNTHETIC_ANNOTATION_FQ_NAME
).first(), emptyList()
)
)
val initialTypeParameter = inlineInvoke0.typeParameters[0].deepCopyWithSymbols(this)
typeParameters = buildList(expression.valueArgumentsCount) {
add(initialTypeParameter)
for (i in 1..expression.valueArgumentsCount) {
add(buildTypeParameter(this@apply) {
updateFrom(initialTypeParameter)
index = i
name = Name.identifier(
currentScope!!.scope.inventNameForTemporary(
prefix = "type",
nameHint = i.toString()
)
)
superTypes.addAll(initialTypeParameter.superTypes)
})
}
}
val initialValueParameter = inlineInvoke0.valueParameters[0].deepCopyWithSymbols(this).apply {
type = context.irBuiltIns.functionN(expression.valueArgumentsCount)
.typeWith(
typeParameters.drop(1).map { it.createSimpleType() } + initialTypeParameter.createSimpleType())
}
valueParameters = buildList(expression.valueArgumentsCount) {
add(initialValueParameter)
for (i in 1..expression.valueArgumentsCount)
add(buildValueParameter(this@apply) {
index = i
name = Name.identifier(
currentScope!!.scope.inventNameForTemporary(
prefix = "param",
nameHint = i.toString()
)
)
type = typeParameters[i].createSimpleType()
})
}
body = declarationIrBuilder(symbol = symbol).irBlockBody {
+irReturn(irCall(irFunction).apply {
dispatchReceiver = irGet(valueParameters[0])
for (valueParameter in valueParameters.drop(1))
putValueArgument(valueParameter.index - 1, irGet(valueParameter))
})
}
}
.also {
inlineInvokeDefs.ensureCapacity(expression.valueArgumentsCount + 1)
while (inlineInvokeDefs.size <= expression.valueArgumentsCount) inlineInvokeDefs.add(null)
inlineInvokeDefs[expression.valueArgumentsCount] = it
deferredAddedFunctions[it] = file
}
// Without this implicit cast certain intrinsic replacement functions don't get replaced.
// For example, this happened while initially testing inlining for ScopingFunctionsAndNulls because one of the
// calls was adding the string result of an invoke to another string which caused the compiler to not replace that
// String.plus(Object) with the Intrinsics.stringPlus call (which caused a very unique NoSuchMethodException that
// was nowhere else to be found on the internet). I figured out the idea of using an implicit cast because
// .apply{} on the string result caused the code to work, which (if you look at what FunctionInlining does) makes
// an implicit cast if the real return type of the function isn't the same as the expected one.
// TL;DR: Don't delete this implicit cast no matter what!
returnExpression = declarationIrBuilder.run {
typeOperator(
expression.type, irCall(
replacementInlineInvokeFunction
).apply {
putValueArgument(0, expression.dispatchReceiver)
putTypeArgument(0, expression.type)
for (i in 1..expression.valueArgumentsCount) {
val currentValueArgument = expression.getValueArgument(i - 1)
putValueArgument(i, currentValueArgument)
putTypeArgument(i, currentValueArgument?.type)
}
}, IMPLICIT_CAST, expression.type
)
}
}
return super.visitExpression(returnExpression)
}
}
class InlineHigherOrderFunctionsAndVariablesTransformer(
context: IrPluginContext,
private val renamesMap: MutableMap<String, String>,
val shadowsContext: IrPluginContext?
) : IrFileTransformerVoidWithContext(context) {
private val varMap: MutableMap<IrVariable, IrExpression> = mutableMapOf()
override fun visitVariable(declaration: IrVariable): IrStatement {
val result = super.visitVariable(declaration)
val initializerLastElement = declaration.initializer?.lastElement()
if (declaration.type.isFunctionTypeOrSubtype && (initializerLastElement is IrWhenWithMapper || initializerLastElement is IrFunctionExpression)) declaration.initializer?.let {
varMap.put(
declaration,
it
)
}
return result
}
override fun visitTypeOperator(expression: IrTypeOperatorCall): IrExpression {
val argument = expression.argument
val initializer = argument.safeAs<IrGetValue>()?.symbol?.owner?.safeAs<IrVariable>()?.initializer?.lastElement()
if ((argument is IrGetValue && varMap[argument.symbol.owner.safeAs()] != null && initializer is IrWhenWithMapper) || argument is IrWhenWithMapper) {
with(declarationIrBuilder) {
val irWhenWithMapper: IrWhenWithMapper = when (argument) {
is IrGetValue -> initializer.cast()
is IrWhenWithMapper -> argument
else -> throw IllegalStateException() // literally will never happen
}
val elseBranch: IrElseBranch
val newMapper: MutableList<IrExpression?> = ArrayList(irWhenWithMapper.mapper.size)
when (val operator = expression.operator) {
CAST, IMPLICIT_CAST, IMPLICIT_DYNAMIC_CAST, REINTERPRET_CAST, SAFE_CAST, IMPLICIT_NOTNULL -> {
irWhenWithMapper.mapper.forEachIndexed { index, value ->
// We erase the types params because, to be honest, it really doesn't matter whether we're invoking
// a Function0<String?>, a Function0<String> or even a Function0<Any> at the same exact time.
// The type checking should be taken care of by the previous compilation steps,
// and so we're just trying to ensure that we have the same function type that's all
newMapper.add(
index,
value?.takeIf { it.type.erasedUpperBound.isSubclassOf(expression.typeOperand.erasedUpperBound) })
}
elseBranch = irElseBranch(
when (operator) {
SAFE_CAST -> irNull()
IMPLICIT_NOTNULL -> irCall(
context.irBuiltIns.checkNotNullSymbol // Throwing an NPE isn't directly exposed, and so instead we "check" if null is not null, therefore always throwing an NPE
).apply {
putTypeArgument(0, context.irBuiltIns.nothingType)
putValueArgument(0, irNull())
}
else -> irCall(context.irBuiltIns.throwCceSymbol)
}
)
}
INSTANCEOF, NOT_INSTANCEOF -> {
val valueIfInstance = irBoolean(operator == INSTANCEOF)
val valueIfNotInstance: IrExpression = irBoolean(!valueIfInstance.value)
irWhenWithMapper.mapper.forEachIndexed { index, value ->
newMapper.add(
index,
value?.takeIf { it.type.erasedUpperBound.isSubclassOf(expression.typeOperand.erasedUpperBound) }
?.let { valueIfInstance })
}
elseBranch = irElseBranch(valueIfNotInstance)
}
else -> {
return super.visitTypeOperator(expression)
}
}
return createWhenAccessForLambda(
expression.type,
irWhenWithMapper.tempInt,
newMapper,
[email protected],
elseBranch
)
}
} else {
return super.visitTypeOperator(expression)
}
}
override fun visitGetValue(expression: IrGetValue): IrExpression {
expression.symbol.owner.safeAs<IrVariable>()?.let { requestedVar ->
varMap[requestedVar]?.let { initializer ->
return declarationIrBuilder.irComposite {
+(initializer.lastElement().deepCopyWithSymbols(parent, ::WhenWithMapperAwareDeepCopyIrTreeWithSymbols))
}//.also { super.visitExpression(it) }
}
}
return super.visitGetValue(expression)
}
private val inlinedFunctionAccesses = mutableListOf<IrExpression>()
@OptIn(ExperimentalStdlibApi::class, ObsoleteDescriptorBasedAPI::class)
override fun visitFunctionAccess(expression: IrFunctionAccessExpression): IrExpression {
if (expression.symbol.descriptor.isContractCallDescriptor())
return declarationIrBuilder.irUnit() // Just don't bother at all with any contract call
val result = run {
if (expression in inlinedFunctionAccesses) return@run expression
var returnExpression: IrExpression = expression
val originalFunction = expression.symbol.owner
val allParams =
buildList(2 + expression.valueArgumentsCount) {
add(expression.dispatchReceiver)
add(expression.extensionReceiver)
for (i in 0 until expression.valueArgumentsCount) add(expression.getValueArgument(i))
}
val paramsNeedInlining = allParams.filter {
(it?.type?.isFunctionTypeOrSubtype ?: false)
}.any {
val index = allParams.indexOf(it)
index < 2 || originalFunction.valueParameters[index - 2].type.let { type -> type is IrDynamicType || type.isNullable() }
}
if (originalFunction.isInline && (paramsNeedInlining || expression.type.isFunctionTypeOrSubtype)) {
val mapper = mutableListOf<IrExpression>()
var isFirstReturn = true
returnExpression =
declarationIrBuilder.irBlock {
at(expression)
val inlinedVersion = inline(
expression,
[email protected],
this@InlineHigherOrderFunctionsAndVariablesTransformer.currentScope!!,
[email protected],
this@InlineHigherOrderFunctionsAndVariablesTransformer.shadowsContext,
renamesMap
)
if (expression.type.isFunctionTypeOrSubtype) {
lateinit var originalType: IrType
val temp = irTemporary(
nameHint = "inlinedHigherOrderFunction${expression.symbol.owner.name}",
irType = context.irBuiltIns.intType,
value = irComposite {
inlinedVersion.also {
originalType = it.type
it.type = context.irBuiltIns.intType
it.safeAs<IrReturnableBlock>()?.let {
@OptIn(ObsoleteDescriptorBasedAPI::class)
@Suppress("NestedLambdaShadowedImplicitParameter") // Intentional
it.transformChildrenVoid(object : IrElementTransformerVoid() {
override fun visitReturn(expression: IrReturn): IrExpression {
if (expression.returnTargetSymbol != it.symbol)
return super.visitReturn(expression)
if (isFirstReturn) {
isFirstReturn = false
}
expression.value.replaceLastElementAndIterateBranches({ replacer, irStatement ->
expression.value = replacer(irStatement).cast()
}, newWhenType = context.irBuiltIns.intType) {
val lambdaNumber = mapper.size
mapper.add(it.cast())
irInt(lambdaNumber)
}
expression.value.type = context.irBuiltIns.intType
return super.visitReturn(expression)
}
})
+inlinedVersion
} ?: it.let {
it.type = originalType
val lambdaNumber = mapper.size
val returnedValueTemporary = irTemporary(
nameHint = "returnedValue$lambdaNumber",
value = it,
irType = originalType
)
mapper.add(irGet(returnedValueTemporary))
+irInt(lambdaNumber)
}
}
})
+createWhenAccessForLambda(
originalType,
temp,
mapper.map {
it.transform(this@InlineHigherOrderFunctionsAndVariablesTransformer, null)
},
[email protected]
)
} else {
+inlinedVersion
}
inlinedFunctionAccesses.add(inlinedVersion)
}
} else if (expression.type == context.irBuiltIns.booleanType && (originalFunction.symbol == context.irBuiltIns.eqeqSymbol || originalFunction.symbol == context.irBuiltIns.eqeqeqSymbol)) {
val constArgument = allParams.firstIsInstanceOrNull<IrConst<*>>()
val irWhenWithMapperArgument: IrWhenWithMapper? = allParams.firstOrNull { argument ->
val initializer =
argument.safeAs<IrGetValue>()?.symbol?.owner?.safeAs<IrVariable>()?.initializer?.lastElement()
(argument is IrGetValue && varMap[argument.symbol.owner.safeAs()] != null && initializer is IrWhenWithMapper) || argument is IrWhenWithMapper
}?.let { argument ->
val initializer =
argument.safeAs<IrGetValue>()?.symbol?.owner?.safeAs<IrVariable>()?.initializer?.lastElement()
when (argument) {
is IrGetValue -> initializer.cast()
is IrWhenWithMapper -> argument
else -> throw IllegalStateException() // literally will never happen
}
}
if (constArgument != null && irWhenWithMapperArgument != null) {
val newMapper = irWhenWithMapperArgument.mapper.map {
val realValue = it?.lastElement()
if (realValue is IrConst<*>)
declarationIrBuilder.irBoolean(realValue.value == constArgument.value)
else if (realValue is IrExpression && (constArgument.type.isSubtypeOf(
realValue.type,
IrTypeSystemContextImpl(context.irBuiltIns)
) || (constArgument.type.isNullable() && realValue.type.isNullable()))
)
declarationIrBuilder.irEquals(realValue, constArgument)
else declarationIrBuilder.irFalse()
}
returnExpression = declarationIrBuilder.createWhenAccessForLambda(
context.irBuiltIns.booleanType,
irWhenWithMapperArgument.tempInt,
newMapper,
[email protected],
)
}
}
return@run returnExpression
}
super.visitExpression(result)
return result
}
}
@OptIn(ExperimentalStdlibApi::class, ObsoleteDescriptorBasedAPI::class)
private fun IrBuilderWithScope.createWhenAccessForLambda(
originalType: IrType,
tempInt: IrVariable,
mapper: List<IrExpression?>,
context: IrPluginContext,
elseBranch: IrElseBranch = irElseBranch(irCall(context.irBuiltIns.noWhenBranchMatchedExceptionSymbol))
): IrExpression {
val copiedMapper = mapper.map {
it?.deepCopyWithSymbols(
parent,
createCopier = ::WhenWithMapperAwareDeepCopyIrTreeWithSymbols
)
}
val fallBackWhenImpl by lazy {
irWhenWithMapper(originalType, tempInt, copiedMapper, buildMutableList(copiedMapper.size) {
copiedMapper.forEachIndexed { index, irExpression ->
if (irExpression != null) {
add(
irBranchWithMapper(
irEquals(irGet(tempInt), irInt(index)),
irExpression
)
)
}
}
add(elseBranch)
})
}
if (!originalType.isFunctionTypeOrSubtype)
return fallBackWhenImpl
val firstFunctionExpression =
copiedMapper.map { it?.lastElement() }.filterIsInstance<IrFunctionExpression>().takeIf { functionExpressions ->
functionExpressions.firstOrNull()?.let { firstFunctionExpression ->
functionExpressions.all { functionExpression -> functionExpression.function.valueParameters.size == firstFunctionExpression.function.valueParameters.size }
} == true
}?.first()
val originalFun =
firstFunctionExpression?.function ?: return fallBackWhenImpl
if (copiedMapper.any {
// Not erasing the type parameters caused some issues specifically in ComplexLogic where a Function0<String>
// was deemed incompatible with a Function0<String?> simply because the latter isn't strictly a subtype of
// the former, but like that really does not matter since we just care about them both having the same function
// arity and that's it, and so erasing the type params does the job well!
it?.type?.erasedUpperBound?.isSubclassOf(
firstFunctionExpression.type.erasedUpperBound
) == false && !it.type.toKotlinType().isNothingOrNullableNothing()
}) {
return fallBackWhenImpl
}
// Now we're sure that all the expressions in mapper are the same function type or an expression returning Nothing
// or null, and so we can now safely assume that they all have the same number of arguments for invoke
val createdFunction = context.irFactory.buildFun {
updateFrom(originalFun)
name = originalFun.name
returnType = originalFun.returnType
}
createdFunction.apply {
patchDeclarationParents(originalFun.parent)
origin = IrDeclarationOrigin.LOCAL_FUNCTION_FOR_LAMBDA
originalFun.valueParameters.map { it.deepCopyWithSymbols(this) }
.let { valueParameters = it }
originalFun.extensionReceiverParameter?.deepCopyWithSymbols(this)
.let { extensionReceiverParameter = it }
originalFun.dispatchReceiverParameter?.deepCopyWithSymbols(this)
.let { dispatchReceiverParameter = it }
body = DeclarationIrBuilder([email protected], createdFunction.symbol).irBlockBody {
+irReturn(
irWhenWithMapper(
originalFun.returnType,
tempInt,
copiedMapper,
buildMutableList(copiedMapper.size + 1) {
copiedMapper.forEachIndexed { index, irExpression ->
if (irExpression != null) {
irExpression.patchDeclarationParents(createdFunction)
add(irBranchWithMapper(irEquals(irGet(tempInt), irInt(index)),
if (irExpression is IrFunctionExpression) {
irCall(context.referenceFunctions(kotlinPackageFqn.child(Name.identifier("run")))
.first { it.owner.dispatchReceiverParameter == null }).apply {
val lambdaReturnType = originalFun.returnType
putTypeArgument(0, lambdaReturnType)
putValueArgument(
0,
irExpression.safeAs<IrFunctionExpression>()?.apply {
type = context.irBuiltIns.functionN(0).typeWith(lambdaReturnType)
function.body?.transformChildrenVoid(object : IrElementTransformerVoid() {
override fun visitGetValue(expression: IrGetValue): IrExpression {
function.valueParameters.indexOfOrNull(expression.symbol.owner)?.let {
return irGet(createdFunction.valueParameters[it])
}
return super.visitGetValue(expression)
}
})
function.valueParameters = listOf()
} ?: irExpression)
}
} else {
irCall(
originalType.classOrNull?.functions?.filter { it.owner.name == OperatorNameConventions.INVOKE && it.owner.extensionReceiverParameter == null && it.owner.valueParameters.size == originalFun.valueParameters.size }!!
.first()
).apply {
dispatchReceiver = irExpression
valueParameters.map { irGet(it) }.forEachIndexed { index, irGetValue ->
putValueArgument(index, irGetValue)
}
}
}
))
}
}
add(elseBranch)
})
)
}
}
return IrFunctionExpressionImpl(
startOffset,
endOffset,
originalType,
createdFunction,
IrStatementOrigin.LAMBDA
)
}
class CoercionToUnitWithUselessFunctionObjectTransformer(pluginContext: IrPluginContext) :
IrFileTransformerVoidWithContext(pluginContext) {
override fun visitTypeOperator(expression: IrTypeOperatorCall): IrExpression {
if (expression.operator == IMPLICIT_COERCION_TO_UNIT && expression.argument.type.isFunctionTypeOrSubtype) {
expression.argument.replaceLastElementAndIterateBranches({ replacer, statement ->
expression.argument = replacer(statement).cast()
}, expression.argument.type) {
if (it is IrFunctionExpression)
declarationIrBuilder.irNull()
else it
}
}
return super.visitTypeOperator(expression)
}
}
| 1 | null | 1 | 7 | ce21199d0ab3d31fa4c67917317ac7ad751848c0 | 38,400 | kotlin-lambda-return-inliner | Apache License 2.0 |
core/src/main/java/io/github/thanosfisherman/gasket/Framerate.kt | ThanosFisherman | 803,474,948 | false | {"Kotlin": 79116, "GLSL": 22476, "Shell": 2608, "HTML": 2082} | package io.github.thanosfisherman.game.utils
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.graphics.Texture
import com.badlogic.gdx.graphics.g2d.BitmapFont
import com.badlogic.gdx.graphics.g2d.SpriteBatch
import com.badlogic.gdx.utils.Disposable
import ktx.assets.disposeSafely
class FrameRate : Disposable {
var isRendered = false
private var sinceChange = 0f
private var frameRate: Float
private val font: BitmapFont
init {
frameRate = Gdx.graphics.framesPerSecond.toFloat()
font = BitmapFont()
font.region.texture.setFilter(Texture.TextureFilter.Nearest, Texture.TextureFilter.Nearest)
}
fun update(delta: Float) {
if (!isRendered) return
sinceChange += delta
if (sinceChange >= 1f) {
sinceChange = 0f
frameRate = Gdx.graphics.framesPerSecond.toFloat()
}
}
fun render(batch: SpriteBatch, width: Float = 0f, height: Float = 16f) {
if (!isRendered) return
font.draw(batch, frameRate.toInt().toString() + " fps", width, height)
}
override fun dispose() {
font.disposeSafely()
}
} | 0 | Kotlin | 2 | 1 | e7c3809fbaca06f383930966c16f545b06a3076f | 1,147 | ApollonianGasket | Apache License 2.0 |
app/src/main/java/com/auth0/android/lock/app/DemoActivity.kt | auth0 | 27,456,226 | false | null | /*
* DemoActivity.java
*
* Copyright (c) 2022 Authok (http://authok.cn)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package cn.authok.android.lock.app
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.CheckBox
import android.widget.LinearLayout
import android.widget.RadioGroup
import androidx.appcompat.app.AppCompatActivity
import cn.authok.android.Authok
import cn.authok.android.authentication.AuthenticationException
import cn.authok.android.callback.Callback
import cn.authok.android.lock.*
import cn.authok.android.provider.WebAuthProvider.login
import cn.authok.android.provider.WebAuthProvider.logout
import cn.authok.android.result.Credentials
import com.google.android.material.snackbar.Snackbar
class DemoActivity : AppCompatActivity() {
// Configured instances
private var lock: Lock? = null
private var passwordlessLock: PasswordlessLock? = null
// Views
private lateinit var rootLayout: View
private lateinit var groupSubmitMode: RadioGroup
private lateinit var checkboxClosable: CheckBox
private lateinit var groupPasswordlessChannel: RadioGroup
private lateinit var groupPasswordlessMode: RadioGroup
private lateinit var checkboxConnectionsDB: CheckBox
private lateinit var checkboxConnectionsEnterprise: CheckBox
private lateinit var checkboxConnectionsSocial: CheckBox
private lateinit var checkboxConnectionsPasswordless: CheckBox
private lateinit var checkboxHideMainScreenTitle: CheckBox
private lateinit var groupDefaultDB: RadioGroup
private lateinit var groupUsernameStyle: RadioGroup
private lateinit var checkboxLoginAfterSignUp: CheckBox
private lateinit var checkboxScreenLogIn: CheckBox
private lateinit var checkboxScreenSignUp: CheckBox
private lateinit var checkboxScreenReset: CheckBox
private lateinit var groupInitialScreen: RadioGroup
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.demo_activity)
rootLayout = findViewById(R.id.scrollView)
//Basic
groupSubmitMode = findViewById(R.id.group_submitmode)
checkboxClosable = findViewById(R.id.checkbox_closable)
checkboxHideMainScreenTitle = findViewById(R.id.checkbox_hide_title)
checkboxConnectionsDB = findViewById(R.id.checkbox_connections_db)
checkboxConnectionsEnterprise = findViewById(R.id.checkbox_connections_enterprise)
checkboxConnectionsSocial = findViewById(R.id.checkbox_connections_social)
checkboxConnectionsPasswordless = findViewById(R.id.checkbox_connections_Passwordless)
groupPasswordlessChannel = findViewById(R.id.group_passwordless_channel)
groupPasswordlessMode = findViewById(R.id.group_passwordless_mode)
//Advanced
groupDefaultDB = findViewById(R.id.group_default_db)
groupUsernameStyle = findViewById(R.id.group_username_style)
checkboxLoginAfterSignUp = findViewById(R.id.checkbox_login_after_signup)
checkboxScreenLogIn = findViewById(R.id.checkbox_enable_login)
checkboxScreenSignUp = findViewById(R.id.checkbox_enable_signup)
checkboxScreenReset = findViewById(R.id.checkbox_enable_reset)
groupInitialScreen = findViewById(R.id.group_initial_screen)
//Buttons
val advancedContainer = findViewById<LinearLayout>(R.id.advanced_container)
val checkboxShowAdvanced = findViewById<CheckBox>(R.id.checkbox_show_advanced)
checkboxShowAdvanced.setOnCheckedChangeListener { _, b -> advancedContainer.visibility = if (b) View.VISIBLE else View.GONE }
val btnShowLockClassic = findViewById<Button>(R.id.btn_show_lock_classic)
btnShowLockClassic.setOnClickListener { showClassicLock() }
val btnShowLockPasswordless = findViewById<Button>(R.id.btn_show_lock_passwordless)
btnShowLockPasswordless.setOnClickListener { showPasswordlessLock() }
val btnShowUniversalLogin = findViewById<Button>(R.id.btn_show_universal_login)
btnShowUniversalLogin.setOnClickListener { showWebAuth() }
val btnClearSession = findViewById<Button>(R.id.btn_clear_session)
btnClearSession.setOnClickListener { clearSession() }
}
private fun showWebAuth() {
login(account)
.withScheme("demo")
.withAudience(String.format("https://%s/userinfo", getString(R.string.cn_authok_domain)))
.start(this, loginCallback)
}
private fun clearSession() {
logout(account)
.withScheme("demo")
.start(this, logoutCallback)
}
private fun showClassicLock() {
val builder = Lock.newBuilder(account, callback)
.withScheme("demo")
.closable(checkboxClosable.isChecked)
.useLabeledSubmitButton(groupSubmitMode.checkedRadioButtonId == R.id.radio_use_label)
.loginAfterSignUp(checkboxLoginAfterSignUp.isChecked)
.allowLogIn(checkboxScreenLogIn.isChecked)
.allowSignUp(checkboxScreenSignUp.isChecked)
.allowForgotPassword(checkboxScreenReset.isChecked)
.allowedConnections(generateConnections())
.hideMainScreenTitle(checkboxHideMainScreenTitle.isChecked)
when (groupUsernameStyle.checkedRadioButtonId) {
R.id.radio_username_style_email -> {
builder.withUsernameStyle(UsernameStyle.EMAIL)
}
R.id.radio_username_style_username -> {
builder.withUsernameStyle(UsernameStyle.USERNAME)
}
}
when (groupInitialScreen.checkedRadioButtonId) {
R.id.radio_initial_reset -> {
builder.initialScreen(InitialScreen.FORGOT_PASSWORD)
}
R.id.radio_initial_signup -> {
builder.initialScreen(InitialScreen.SIGN_UP)
}
else -> {
builder.initialScreen(InitialScreen.LOG_IN)
}
}
if (checkboxConnectionsDB.isChecked) {
when (groupDefaultDB.checkedRadioButtonId) {
R.id.radio_default_db_policy -> {
builder.setDefaultDatabaseConnection("with-strength")
}
R.id.radio_default_db_mfa -> {
builder.setDefaultDatabaseConnection("mfa-connection")
}
else -> {
builder.setDefaultDatabaseConnection("database")
}
}
}
// For demo purposes because options change dynamically, we release the resources of Lock here.
// In a real app, you will have a single instance and release its resources in Activity#OnDestroy.
lock?.onDestroy(this)
// Create a new instance with the updated configuration
lock = builder.build(this)
startActivity(lock!!.newIntent(this))
}
private fun showPasswordlessLock() {
val builder = PasswordlessLock.newBuilder(account, callback)
.withScheme("demo")
.closable(checkboxClosable.isChecked)
.allowedConnections(generateConnections())
.hideMainScreenTitle(checkboxHideMainScreenTitle.isChecked)
if (groupPasswordlessMode.checkedRadioButtonId == R.id.radio_use_link) {
builder.useLink()
} else {
builder.useCode()
}
// For demo purposes because options change dynamically, we release the resources of Lock here.
// In a real app, you will have a single instance and release its resources in Activity#OnDestroy.
passwordlessLock?.onDestroy(this)
// Create a new instance with the updated configuration
passwordlessLock = builder.build(this)
startActivity(passwordlessLock!!.newIntent(this))
}
private val account: Authok by lazy {
Authok(getString(R.string.cn_authok_client_id), getString(R.string.cn_authok_domain))
}
private fun generateConnections(): List<String> {
val connections: MutableList<String> = ArrayList()
if (checkboxConnectionsDB.isChecked) {
connections.add("database")
connections.add("mfa-connection")
connections.add("with-strength")
}
if (checkboxConnectionsEnterprise.isChecked) {
connections.add("ad")
connections.add("another")
connections.add("fake-saml")
connections.add("contoso-ad")
}
if (checkboxConnectionsSocial.isChecked) {
connections.add("google-oauth2")
connections.add("twitter")
connections.add("facebook")
connections.add("paypal-sandbox")
}
if (checkboxConnectionsPasswordless.isChecked) {
connections.add(if (groupPasswordlessChannel.checkedRadioButtonId == R.id.radio_use_sms) "sms" else "email")
}
if (connections.isEmpty()) {
connections.add("no-connection")
}
return connections
}
public override fun onDestroy() {
super.onDestroy()
lock?.onDestroy(this)
passwordlessLock?.onDestroy(this)
}
internal fun showResult(message: String) {
Snackbar.make(rootLayout, message, Snackbar.LENGTH_LONG).show()
}
private val callback: LockCallback = object : AuthenticationCallback() {
override fun onAuthentication(credentials: Credentials) {
showResult("OK > " + credentials.accessToken)
}
override fun onError(error: AuthenticationException) {
if (error.isCanceled) {
showResult("User pressed back.")
} else {
showResult(error.getDescription())
}
}
}
private val loginCallback: Callback<Credentials, AuthenticationException> = object : Callback<Credentials, AuthenticationException> {
override fun onFailure(error: AuthenticationException) {
showResult("Failed > " + error.getDescription())
}
override fun onSuccess(result: Credentials) {
showResult("OK > " + result.accessToken)
}
}
private val logoutCallback: Callback<Void?, AuthenticationException> = object : Callback<Void?, AuthenticationException> {
override fun onFailure(error: AuthenticationException) {
showResult("Log out cancelled")
}
override fun onSuccess(result: Void?) {
showResult("Logged out!")
}
}
} | 5 | null | 82 | 145 | dc00916d2ff541171897940ee8c8664fadbaa6d8 | 11,670 | Lock.Android | MIT License |
api/src/main/kotlin/io/sparkled/api/PlaylistController.kt | sparkled | 53,776,686 | false | {"Kotlin": 321814, "TypeScript": 141619, "JavaScript": 133004, "CSS": 5012, "HTML": 353} | package io.sparkled.api
import io.micronaut.http.HttpResponse
import io.micronaut.http.annotation.Body
import io.micronaut.http.annotation.Controller
import io.micronaut.http.annotation.Delete
import io.micronaut.http.annotation.Get
import io.micronaut.http.annotation.PathVariable
import io.micronaut.http.annotation.Post
import io.micronaut.http.annotation.Put
import io.micronaut.scheduling.TaskExecutors
import io.micronaut.scheduling.annotation.ExecuteOn
import io.micronaut.security.annotation.Secured
import io.micronaut.security.rules.SecurityRule
import io.micronaut.transaction.annotation.Transactional
import io.sparkled.model.PlaylistModel
import io.sparkled.model.UniqueId
import io.sparkled.model.util.IdUtils.uniqueId
import io.sparkled.persistence.DbService
import io.sparkled.persistence.repository.findByIdOrNull
import io.sparkled.viewmodel.PlaylistEditViewModel
import io.sparkled.viewmodel.PlaylistSummaryViewModel
import io.sparkled.viewmodel.PlaylistViewModel
import io.sparkled.viewmodel.error.ApiErrorCode
import io.sparkled.viewmodel.exception.HttpResponseException
import java.time.Instant
@ExecuteOn(TaskExecutors.BLOCKING)
@Secured(SecurityRule.IS_ANONYMOUS)
@Controller("/api/playlists")
class PlaylistController(
private val db: DbService,
) {
@Get("/")
@Transactional
fun getAllPlaylists(): HttpResponse<Any> {
val playlists = db.playlists.findAll().sortedBy { it.name }
val playlistSequences = db.playlistSequences.findAll().groupBy { it.playlistId }
val sequences = db.sequences.findAll().toList()
val songs = db.songs.findAll().toList()
val playlistSummaries = playlists.map {
PlaylistSummaryViewModel.fromModel(
it,
playlistSequences[it.id] ?: emptyList(),
sequences,
songs,
)
}
return HttpResponse.ok(playlistSummaries)
}
@Get("/{id}")
@Transactional
fun getPlaylist(id: UniqueId): HttpResponse<Any> {
val playlist = getPlaylistById(id)
?: throw HttpResponseException(ApiErrorCode.ERR_NOT_FOUND)
return HttpResponse.ok(playlist)
}
@Post("/")
@Transactional
fun createPlaylist(
@Body body: PlaylistEditViewModel,
): HttpResponse<Any> {
val playlist = PlaylistModel(id = uniqueId(), name = body.name)
db.playlists.save(playlist)
val playlistSequences = body.sequences.map { it.toModel(playlistId = playlist.id) }
db.playlistSequences.saveAll(playlistSequences)
return HttpResponse.created(getPlaylistById(playlist.id))
}
private fun getPlaylistById(id: UniqueId): PlaylistViewModel? {
val playlist = db.playlists.findByIdOrNull(id)
val playlistSequences = db.playlistSequences.getPlaylistSequencesByPlaylistId(id)
return playlist?.let { PlaylistViewModel.fromModel(it, playlistSequences) }
}
@Put("/{id}")
@Transactional
fun updatePlaylist(
@PathVariable id: UniqueId,
@Body body: PlaylistEditViewModel,
): HttpResponse<Any> {
val existing = db.playlists.findByIdOrNull(id)
?: throw HttpResponseException(ApiErrorCode.ERR_NOT_FOUND)
val updated = db.playlists.update(existing.copy(name = body.name, updatedAt = Instant.now()))
val sequences = body.sequences.map { it.toModel(updated.id) }
val existingSequences = db.playlistSequences.getPlaylistSequencesByPlaylistId(id).associateBy { it.id }
val newSequences = sequences.map { it.copy(playlistId = id) }.associateBy { it.id }
// Delete playlist sequences that no longer exist.
(existingSequences.keys - newSequences.keys).forEach { db.playlistSequences.delete(existingSequences.getValue(it)) }
// Insert playlist sequences that didn't exist previously.
(newSequences.keys - existingSequences.keys).forEach { db.playlistSequences.save(newSequences.getValue(it)) }
// Update playlist sequences that exist
(newSequences.keys.intersect(existingSequences.keys)).forEach {
db.playlistSequences.update(
newSequences.getValue(it)
)
}
return HttpResponse.ok()
}
@Delete("/{id}")
@Transactional
fun deletePlaylist(id: UniqueId): HttpResponse<Any> {
db.playlists.deleteById(id)
return HttpResponse.noContent()
}
}
| 20 | Kotlin | 21 | 71 | d4a0a94d69440914d6e34484a8d5387b37c64718 | 4,440 | sparkled | MIT License |
common/src/main/kotlin/com/scurab/kuproxy/processor/KtorProcessor.kt | jbruchanov | 359,263,583 | false | null | package com.scurab.kuproxy.processor
import io.ktor.application.ApplicationCall
interface Processor<I, O> {
suspend fun process(item: I): O
}
interface KtorProcessor : Processor<ApplicationCall, Unit> {
override suspend fun process(item: ApplicationCall)
}
| 0 | Kotlin | 0 | 1 | 2e10d85e7e318850679be3a21fe4406645f88811 | 268 | kuproxy | Apache License 2.0 |
app/src/testInternal/java/com/kickstarter/viewmodels/FeatureFlagsViewModelTest.kt | proAhmed | 119,650,202 | false | null | package com.kickstarter.viewmodels
import com.kickstarter.KSRobolectricTestCase
import com.kickstarter.libs.preferences.MockStringPreference
import com.kickstarter.libs.utils.ConfigFeatureName.SEGMENT_ENABLED
import com.kickstarter.mock.MockCurrentConfig
import com.kickstarter.mock.MockExperimentsClientType
import com.kickstarter.mock.factories.ConfigFactory
import com.kickstarter.model.FeatureFlagsModel
import com.kickstarter.models.User
import org.junit.Test
import rx.observers.TestSubscriber
class FeatureFlagsViewModelTest : KSRobolectricTestCase() {
private lateinit var vm: FeatureFlagsViewModel.ViewModel
private val configFeatures = TestSubscriber<List<FeatureFlagsModel>>()
private val optimizelyFeatures = TestSubscriber<List<FeatureFlagsModel>>()
val mockConfig = MockCurrentConfig()
private fun setUpEnvironment(features: Map<String, Boolean>?, optimizelyFeatures: List<String>) {
mockConfig.config(
ConfigFactory.config().toBuilder()
.features(features)
.build()
)
val environment = environment()
.toBuilder()
.currentConfig(mockConfig)
.optimizely(object : MockExperimentsClientType() {
override fun enabledFeatures(user: User?): List<String> {
return optimizelyFeatures
}
})
.build()
this.vm = FeatureFlagsViewModel.ViewModel(environment)
this.vm.outputs.configFeatures().subscribe(this.configFeatures)
this.vm.outputs.optimizelyFeatures().subscribe(this.optimizelyFeatures)
}
@Test
fun testConfigFeatures_whenFeaturesMapIsNull() {
setUpEnvironment(null, emptyList())
this.configFeatures.assertValue(listOf())
}
@Test
fun testConfigFeatures_whenFeaturesMapIsNotNull() {
val features = mapOf(
Pair("ios_feature_one", true),
Pair("ios_feature_two", false),
Pair("android_feature_one", true),
Pair("android_feature_two", false)
)
setUpEnvironment(features, emptyList())
this.configFeatures.assertValue(
listOf(
FeatureFlagsModel("android_feature_one", true),
FeatureFlagsModel("android_feature_two", false)
)
)
}
@Test
fun testOptimizelyFeatures() {
setUpEnvironment(null, listOf("android_optimizely_feature"))
this.optimizelyFeatures.assertValue(listOf(FeatureFlagsModel("android_optimizely_feature", true)))
}
@Test
fun testSegmentFeatureFlagValueChanged() {
var segmentFlagValue = true
val features = hashMapOf(
Pair(SEGMENT_ENABLED.configFeatureName, segmentFlagValue)
)
setUpEnvironment(features, emptyList())
this.configFeatures.assertValue(
listOf(
FeatureFlagsModel(SEGMENT_ENABLED.configFeatureName, segmentFlagValue, true)
)
)
mockConfig.observable().subscribe {
segmentFlagValue = it.features()?.get(SEGMENT_ENABLED.configFeatureName)!!
}
val featuresFlagPreference = MockStringPreference()
this.vm.inputs.updateSegmentFlag(false, featuresFlagPreference)
assertEquals(segmentFlagValue, false)
this.vm.inputs.updateSegmentFlag(true, featuresFlagPreference)
assertEquals(segmentFlagValue, true)
}
}
| 1 | null | 1 | 1 | b42ede4faa0dad575bbd78c8fdd65c97519e13fb | 3,463 | android-oss | Apache License 2.0 |
subprojects/configuration-cache/src/main/kotlin/org/gradle/configurationcache/ConfigurationCacheState.kt | gradle | 302,322 | false | null | /*
* Copyright 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.configurationcache
import org.gradle.api.Project
import org.gradle.api.artifacts.component.BuildIdentifier
import org.gradle.api.file.FileCollection
import org.gradle.api.internal.BuildDefinition
import org.gradle.api.internal.GradleInternal
import org.gradle.api.internal.artifacts.DefaultBuildIdentifier
import org.gradle.api.provider.Provider
import org.gradle.api.services.internal.BuildServiceProvider
import org.gradle.api.services.internal.BuildServiceRegistryInternal
import org.gradle.caching.configuration.BuildCache
import org.gradle.configuration.BuildOperationFiringProjectsPreparer
import org.gradle.configuration.project.LifecycleProjectEvaluator
import org.gradle.configurationcache.CachedProjectState.Companion.computeCachedState
import org.gradle.configurationcache.CachedProjectState.Companion.configureProjectFromCachedState
import org.gradle.configurationcache.extensions.serviceOf
import org.gradle.configurationcache.extensions.unsafeLazy
import org.gradle.configurationcache.problems.DocumentationSection.NotYetImplementedSourceDependencies
import org.gradle.configurationcache.serialization.DefaultReadContext
import org.gradle.configurationcache.serialization.DefaultWriteContext
import org.gradle.configurationcache.serialization.codecs.Codecs
import org.gradle.configurationcache.serialization.codecs.WorkNodeCodec
import org.gradle.configurationcache.serialization.logNotImplemented
import org.gradle.configurationcache.serialization.readCollection
import org.gradle.configurationcache.serialization.readFile
import org.gradle.configurationcache.serialization.readList
import org.gradle.configurationcache.serialization.readNonNull
import org.gradle.configurationcache.serialization.readStrings
import org.gradle.configurationcache.serialization.runReadOperation
import org.gradle.configurationcache.serialization.withDebugFrame
import org.gradle.configurationcache.serialization.withGradleIsolate
import org.gradle.configurationcache.serialization.writeCollection
import org.gradle.configurationcache.serialization.writeFile
import org.gradle.configurationcache.serialization.writeStrings
import org.gradle.execution.plan.Node
import org.gradle.initialization.BuildOperationFiringSettingsPreparer
import org.gradle.initialization.BuildOperationSettingsProcessor
import org.gradle.initialization.NotifyingBuildLoader
import org.gradle.initialization.RootBuildCacheControllerSettingsProcessor
import org.gradle.initialization.SettingsLocation
import org.gradle.internal.Actions
import org.gradle.internal.build.BuildStateRegistry
import org.gradle.internal.build.IncludedBuildState
import org.gradle.internal.build.PublicBuildPath
import org.gradle.internal.build.RootBuildState
import org.gradle.internal.build.event.BuildEventListenerRegistryInternal
import org.gradle.internal.buildtree.BuildTreeWorkGraph
import org.gradle.internal.composite.IncludedBuildInternal
import org.gradle.internal.enterprise.core.GradleEnterprisePluginAdapter
import org.gradle.internal.enterprise.core.GradleEnterprisePluginManager
import org.gradle.internal.execution.BuildOutputCleanupRegistry
import org.gradle.internal.operations.BuildOperationContext
import org.gradle.internal.operations.BuildOperationDescriptor
import org.gradle.internal.operations.BuildOperationExecutor
import org.gradle.internal.operations.RunnableBuildOperation
import org.gradle.internal.serialize.Decoder
import org.gradle.internal.serialize.Encoder
import org.gradle.plugin.management.internal.PluginRequests
import org.gradle.vcs.internal.VcsMappingsStore
import java.io.File
import java.io.InputStream
import java.io.OutputStream
import kotlin.contracts.InvocationKind
import kotlin.contracts.contract
internal
enum class StateType {
Work, Model
}
internal
interface ConfigurationCacheStateFile {
fun outputStream(): OutputStream
fun inputStream(): InputStream
fun stateFileForIncludedBuild(build: BuildDefinition): ConfigurationCacheStateFile
}
internal
class ConfigurationCacheState(
private val codecs: Codecs,
private val stateFile: ConfigurationCacheStateFile
) {
/**
* Writes the state for the whole build starting from the given root [build] and returns the set
* of stored included build directories.
*/
suspend fun DefaultWriteContext.writeRootBuildState(build: VintageGradleBuild): HashSet<File> =
writeRootBuild(build).also {
writeInt(0x1ecac8e)
}
suspend fun DefaultReadContext.readRootBuildState(graph: BuildTreeWorkGraph, createBuild: (File?, String) -> ConfigurationCacheBuild) {
val buildState = readRootBuild(createBuild)
require(readInt() == 0x1ecac8e) {
"corrupt state file"
}
configureBuild(buildState)
calculateRootTaskGraph(buildState, graph)
}
private
fun configureBuild(state: CachedBuildState) {
val gradle = state.build.gradle
val buildOperationExecutor = gradle.serviceOf<BuildOperationExecutor>()
fireConfigureBuild(buildOperationExecutor, gradle) {
fireLoadProjects(buildOperationExecutor, gradle)
state.children.forEach(::configureBuild)
fireConfigureProject(buildOperationExecutor, gradle)
}
}
private
fun calculateRootTaskGraph(state: CachedBuildState, graph: BuildTreeWorkGraph) {
graph.scheduleWork { builder ->
builder.withWorkGraph(state.build.state) {
it.addNodes(state.workGraph)
}
for (child in state.children) {
addNodesForChildBuilds(child, builder)
}
}
}
private
fun addNodesForChildBuilds(state: CachedBuildState, builder: BuildTreeWorkGraph.Builder) {
builder.withWorkGraph(state.build.state) {
it.addNodes(state.workGraph)
}
for (child in state.children) {
addNodesForChildBuilds(child, builder)
}
}
private
suspend fun DefaultWriteContext.writeRootBuild(build: VintageGradleBuild): HashSet<File> {
require(build.gradle.owner is RootBuildState)
val gradle = build.gradle
withDebugFrame({ "Gradle" }) {
write(gradle.settings.settingsScript.resource.file)
writeString(gradle.rootProject.name)
writeBuildTreeState(gradle)
}
val buildEventListeners = buildEventListenersOf(gradle)
val storedBuilds = storedBuilds()
writeBuildState(
build,
StoredBuildTreeState(
storedBuilds,
buildEventListeners
.filterIsInstance<BuildServiceProvider<*, *>>()
.groupBy { it.buildIdentifier }
)
)
writeRootEventListenerSubscriptions(gradle, buildEventListeners)
return storedBuilds.buildRootDirs
}
private
suspend fun DefaultReadContext.readRootBuild(
createBuild: (File?, String) -> ConfigurationCacheBuild
): CachedBuildState {
val settingsFile = read() as File?
val rootProjectName = readString()
val build = createBuild(settingsFile, rootProjectName)
val gradle = build.gradle
readBuildTreeState(gradle)
val rootBuildState = readBuildState(build)
readRootEventListenerSubscriptions(gradle)
return rootBuildState
}
internal
suspend fun DefaultWriteContext.writeBuildState(build: VintageGradleBuild, buildTreeState: StoredBuildTreeState) {
val gradle = build.gradle
withDebugFrame({ "Gradle" }) {
writeGradleState(gradle, buildTreeState)
}
withDebugFrame({ "Work Graph" }) {
val scheduledNodes = build.scheduledWork
val relevantProjects = getRelevantProjectsFor(scheduledNodes, gradle.serviceOf())
writeRelevantProjects(relevantProjects)
writeProjectStates(gradle, relevantProjects)
writeRequiredBuildServicesOf(gradle, buildTreeState)
writeWorkGraphOf(gradle, scheduledNodes)
}
}
internal
suspend fun DefaultReadContext.readBuildState(build: ConfigurationCacheBuild): CachedBuildState {
val gradle = build.gradle
lateinit var children: List<CachedBuildState>
withLoadBuildOperation(gradle) {
fireEvaluateSettings(gradle)
runReadOperation {
children = readGradleState(build)
}
}
readRelevantProjects(build)
build.registerProjects()
initProjectProvider(build::getProject)
readProjectStates(gradle)
readRequiredBuildServicesOf(gradle)
val workGraph = readWorkGraph(gradle)
return CachedBuildState(build, workGraph, children)
}
data class CachedBuildState(
val build: ConfigurationCacheBuild,
val workGraph: List<Node>,
val children: List<CachedBuildState>
)
private
fun withLoadBuildOperation(gradle: GradleInternal, preparer: () -> Unit) {
contract {
callsInPlace(preparer, InvocationKind.EXACTLY_ONCE)
}
fireLoadBuild(preparer, gradle)
}
private
suspend fun DefaultWriteContext.writeWorkGraphOf(gradle: GradleInternal, scheduledNodes: List<Node>) {
WorkNodeCodec(gradle, internalTypesCodec).run {
writeWork(scheduledNodes)
}
}
private
suspend fun DefaultReadContext.readWorkGraph(gradle: GradleInternal) =
WorkNodeCodec(gradle, internalTypesCodec).run {
readWork()
}
private
suspend fun DefaultWriteContext.writeRequiredBuildServicesOf(gradle: GradleInternal, buildTreeState: StoredBuildTreeState) {
withGradleIsolate(gradle, userTypesCodec) {
write(buildTreeState.requiredBuildServicesPerBuild[buildIdentifierOf(gradle)])
}
}
private
suspend fun DefaultReadContext.readRequiredBuildServicesOf(gradle: GradleInternal) {
withGradleIsolate(gradle, userTypesCodec) {
read()
}
}
private
suspend fun DefaultWriteContext.writeProjectStates(gradle: GradleInternal, relevantProjects: List<Project>) {
withGradleIsolate(gradle, userTypesCodec) {
// Do not serialize trivial states to speed up deserialization.
val nonTrivialProjectStates = relevantProjects.asSequence()
.map { project -> project.computeCachedState() }
.filterNotNull()
.toList()
writeCollection(nonTrivialProjectStates)
}
}
private
suspend fun DefaultReadContext.readProjectStates(gradle: GradleInternal) {
withGradleIsolate(gradle, userTypesCodec) {
readCollection {
configureProjectFromCachedState(read() as CachedProjectState)
}
}
}
private
suspend fun DefaultWriteContext.writeBuildTreeState(gradle: GradleInternal) {
withGradleIsolate(gradle, userTypesCodec) {
withDebugFrame({ "build cache" }) {
writeBuildCacheConfiguration(gradle)
}
writeGradleEnterprisePluginManager(gradle)
}
}
private
suspend fun DefaultReadContext.readBuildTreeState(gradle: GradleInternal) {
withGradleIsolate(gradle, userTypesCodec) {
readBuildCacheConfiguration(gradle)
readGradleEnterprisePluginManager(gradle)
}
}
private
suspend fun DefaultWriteContext.writeRootEventListenerSubscriptions(gradle: GradleInternal, listeners: List<Provider<*>>) {
withGradleIsolate(gradle, userTypesCodec) {
withDebugFrame({ "listener subscriptions" }) {
writeBuildEventListenerSubscriptions(listeners)
}
}
}
private
suspend fun DefaultReadContext.readRootEventListenerSubscriptions(gradle: GradleInternal) {
withGradleIsolate(gradle, userTypesCodec) {
readBuildEventListenerSubscriptions(gradle)
}
}
private
suspend fun DefaultWriteContext.writeGradleState(gradle: GradleInternal, buildTreeState: StoredBuildTreeState) {
withGradleIsolate(gradle, userTypesCodec) {
// per build
writeStartParameterOf(gradle)
withDebugFrame({ "included builds" }) {
writeChildBuilds(gradle, buildTreeState)
}
withDebugFrame({ "cleanup registrations" }) {
writeBuildOutputCleanupRegistrations(gradle)
}
}
}
private
suspend fun DefaultReadContext.readGradleState(
build: ConfigurationCacheBuild
): List<CachedBuildState> {
val gradle = build.gradle
withGradleIsolate(gradle, userTypesCodec) {
// per build
readStartParameterOf(gradle)
val children = readChildBuildsOf(build)
readBuildOutputCleanupRegistrations(gradle)
return children
}
}
private
fun DefaultWriteContext.writeStartParameterOf(gradle: GradleInternal) {
val startParameterTaskNames = gradle.startParameter.taskNames
writeStrings(startParameterTaskNames)
}
private
fun DefaultReadContext.readStartParameterOf(gradle: GradleInternal) {
// Restore startParameter.taskNames to enable `gradle.startParameter.setTaskNames(...)` idiom in included build scripts
// See org/gradle/caching/configuration/internal/BuildCacheCompositeConfigurationIntegrationTest.groovy:134
val startParameterTaskNames = readStrings()
gradle.startParameter.setTaskNames(startParameterTaskNames)
}
private
suspend fun DefaultWriteContext.writeChildBuilds(gradle: GradleInternal, buildTreeState: StoredBuildTreeState) {
writeCollection(gradle.includedBuilds()) {
writeIncludedBuildState(it, buildTreeState)
}
if (gradle.serviceOf<VcsMappingsStore>().asResolver().hasRules()) {
logNotImplemented(
feature = "source dependencies",
documentationSection = NotYetImplementedSourceDependencies
)
writeBoolean(true)
} else {
writeBoolean(false)
}
}
private
suspend fun DefaultReadContext.readChildBuildsOf(
parentBuild: ConfigurationCacheBuild
): List<CachedBuildState> {
val includedBuilds = readList {
readIncludedBuildState(parentBuild)
}
if (readBoolean()) {
logNotImplemented(
feature = "source dependencies",
documentationSection = NotYetImplementedSourceDependencies
)
}
parentBuild.gradle.setIncludedBuilds(includedBuilds.map { it.first.model })
return includedBuilds.mapNotNull { it.second }
}
private
suspend fun DefaultWriteContext.writeIncludedBuildState(
reference: IncludedBuildInternal,
buildTreeState: StoredBuildTreeState
) {
val target = reference.target
if (target is IncludedBuildState) {
val includedGradle = target.configuredBuild
val buildDefinition = includedGradle.serviceOf<BuildDefinition>()
writeBuildDefinition(buildDefinition)
when {
buildTreeState.storedBuilds.store(buildDefinition) -> {
writeBoolean(true)
includedGradle.serviceOf<ConfigurationCacheIO>().writeIncludedBuildStateTo(
stateFileFor(buildDefinition),
buildTreeState
)
}
else -> {
writeBoolean(false)
}
}
}
}
private
suspend fun DefaultReadContext.readIncludedBuildState(
parentBuild: ConfigurationCacheBuild
): Pair<IncludedBuildState, CachedBuildState?> {
val buildDefinition = readIncludedBuildDefinition(parentBuild)
val includedBuild = parentBuild.addIncludedBuild(buildDefinition)
val stored = readBoolean()
val cachedBuildState =
if (stored) {
val confCacheBuild = includedBuild.withState { includedGradle ->
includedGradle.serviceOf<ConfigurationCacheHost>().createBuild(null, includedBuild.name)
}
confCacheBuild.gradle.serviceOf<ConfigurationCacheIO>().readIncludedBuildStateFrom(
stateFileFor(buildDefinition),
confCacheBuild
)
} else null
return includedBuild to cachedBuildState
}
private
suspend fun DefaultWriteContext.writeBuildDefinition(buildDefinition: BuildDefinition) {
buildDefinition.run {
writeString(name!!)
writeFile(buildRootDir)
write(fromBuild)
writeBoolean(isPluginBuild)
}
}
private
suspend fun DefaultReadContext.readIncludedBuildDefinition(parentBuild: ConfigurationCacheBuild): BuildDefinition {
val includedBuildName = readString()
val includedBuildRootDir = readFile()
val fromBuild = readNonNull<PublicBuildPath>()
val pluginBuild = readBoolean()
return BuildDefinition.fromStartParameterForBuild(
parentBuild.gradle.startParameter,
includedBuildName,
includedBuildRootDir,
PluginRequests.EMPTY,
Actions.doNothing(),
fromBuild,
pluginBuild
)
}
private
suspend fun DefaultWriteContext.writeBuildCacheConfiguration(gradle: GradleInternal) {
gradle.settings.buildCache.let { buildCache ->
write(buildCache.local)
write(buildCache.remote)
}
}
private
suspend fun DefaultReadContext.readBuildCacheConfiguration(gradle: GradleInternal) {
gradle.settings.buildCache.let { buildCache ->
buildCache.local = readNonNull()
buildCache.remote = read() as BuildCache?
}
RootBuildCacheControllerSettingsProcessor.process(gradle)
}
private
suspend fun DefaultWriteContext.writeBuildEventListenerSubscriptions(listeners: List<Provider<*>>) {
writeCollection(listeners) { listener ->
when (listener) {
is BuildServiceProvider<*, *> -> {
writeBoolean(true)
write(listener.buildIdentifier)
writeString(listener.name)
}
else -> {
writeBoolean(false)
write(listener)
}
}
}
}
private
suspend fun DefaultReadContext.readBuildEventListenerSubscriptions(gradle: GradleInternal) {
val eventListenerRegistry by unsafeLazy {
gradle.serviceOf<BuildEventListenerRegistryInternal>()
}
val buildStateRegistry by unsafeLazy {
gradle.serviceOf<BuildStateRegistry>()
}
readCollection {
when (readBoolean()) {
true -> {
val buildIdentifier = readNonNull<BuildIdentifier>()
val serviceName = readString()
val provider = buildStateRegistry.buildServiceRegistrationOf(buildIdentifier).getByName(serviceName)
eventListenerRegistry.subscribe(provider.service)
}
else -> {
val provider = readNonNull<Provider<*>>()
eventListenerRegistry.subscribe(provider)
}
}
}
}
private
suspend fun DefaultWriteContext.writeBuildOutputCleanupRegistrations(gradle: GradleInternal) {
val buildOutputCleanupRegistry = gradle.serviceOf<BuildOutputCleanupRegistry>()
writeCollection(buildOutputCleanupRegistry.registeredOutputs)
}
private
suspend fun DefaultReadContext.readBuildOutputCleanupRegistrations(gradle: GradleInternal) {
val buildOutputCleanupRegistry = gradle.serviceOf<BuildOutputCleanupRegistry>()
readCollection {
val files = readNonNull<FileCollection>()
buildOutputCleanupRegistry.registerOutputs(files)
}
}
private
suspend fun DefaultWriteContext.writeGradleEnterprisePluginManager(gradle: GradleInternal) {
val manager = gradle.serviceOf<GradleEnterprisePluginManager>()
val adapter = manager.adapter
val writtenAdapter = adapter?.takeIf {
it.shouldSaveToConfigurationCache()
}
write(writtenAdapter)
}
private
suspend fun DefaultReadContext.readGradleEnterprisePluginManager(gradle: GradleInternal) {
val adapter = read() as GradleEnterprisePluginAdapter?
if (adapter != null) {
adapter.onLoadFromConfigurationCache()
val manager = gradle.serviceOf<GradleEnterprisePluginManager>()
manager.registerAdapter(adapter)
}
}
private
fun getRelevantProjectsFor(nodes: List<Node>, relevantProjectsRegistry: RelevantProjectsRegistry): List<Project> {
return fillTheGapsOf(relevantProjectsRegistry.relevantProjects(nodes))
}
private
fun Encoder.writeRelevantProjects(relevantProjects: List<Project>) {
writeCollection(relevantProjects) { project ->
writeString(project.path)
writeFile(project.projectDir)
writeFile(project.buildDir)
}
}
private
fun Decoder.readRelevantProjects(build: ConfigurationCacheBuild) {
readCollection {
val projectPath = readString()
val projectDir = readFile()
val buildDir = readFile()
build.createProject(projectPath, projectDir, buildDir)
}
}
private
fun stateFileFor(buildDefinition: BuildDefinition) =
stateFile.stateFileForIncludedBuild(buildDefinition)
private
val internalTypesCodec
get() = codecs.internalTypesCodec
private
val userTypesCodec
get() = codecs.userTypesCodec
private
fun storedBuilds() = object : StoredBuilds {
val buildRootDirs = hashSetOf<File>()
override fun store(build: BuildDefinition): Boolean =
buildRootDirs.add(build.buildRootDir!!)
}
private
fun buildIdentifierOf(gradle: GradleInternal) =
gradle.owner.buildIdentifier
private
fun buildEventListenersOf(gradle: GradleInternal) =
gradle.serviceOf<BuildEventListenerRegistryInternal>().subscriptions
private
fun BuildStateRegistry.buildServiceRegistrationOf(buildId: BuildIdentifier) =
gradleOf(buildId).serviceOf<BuildServiceRegistryInternal>().registrations
private
fun BuildStateRegistry.gradleOf(buildIdentifier: BuildIdentifier) =
when (buildIdentifier) {
DefaultBuildIdentifier.ROOT -> rootBuild.build
else -> getIncludedBuild(buildIdentifier).configuredBuild
}
private
fun fireConfigureBuild(buildOperationExecutor: BuildOperationExecutor, gradle: GradleInternal, function: (gradle: GradleInternal) -> Unit) {
BuildOperationFiringProjectsPreparer(function, buildOperationExecutor).prepareProjects(gradle)
}
/**
* Fire build operation required by build scans to determine the root path.
**/
private
fun fireConfigureProject(buildOperationExecutor: BuildOperationExecutor, gradle: GradleInternal) {
buildOperationExecutor.run(object : RunnableBuildOperation {
override fun run(context: BuildOperationContext) = Unit
override fun description(): BuildOperationDescriptor.Builder =
LifecycleProjectEvaluator.configureProjectBuildOperationBuilderFor(gradle.rootProject)
})
}
/**
* Fire _Load projects_ build operation required by build scans to determine the build's project structure (and build load time).
**/
private
fun fireLoadProjects(buildOperationExecutor: BuildOperationExecutor, gradle: GradleInternal) {
NotifyingBuildLoader({ _, _ -> }, buildOperationExecutor).load(gradle.settings, gradle)
}
/**
* Fires build operation required by build scan to determine startup duration and settings evaluated duration.
*/
private
fun fireLoadBuild(preparer: () -> Unit, gradle: GradleInternal) {
BuildOperationFiringSettingsPreparer(
{ preparer() },
gradle.serviceOf(),
gradle.serviceOf<BuildDefinition>().fromBuild
).prepareSettings(gradle)
}
/**
* Fire build operation required by build scans to determine build path (and settings execution time).
* It may be better to instead point GE at the origin build that produced the cached task graph,
* or replace this with a different event/op that carries this information and wraps some actual work.
**/
private
fun fireEvaluateSettings(gradle: GradleInternal) {
BuildOperationSettingsProcessor(
{ _, _, _, _ -> gradle.settings },
gradle.serviceOf()
).process(
gradle,
SettingsLocation(gradle.settings.settingsDir, null),
gradle.classLoaderScope,
gradle.startParameter.apply {
useEmptySettings()
}
)
}
}
internal
class StoredBuildTreeState(
val storedBuilds: StoredBuilds,
val requiredBuildServicesPerBuild: Map<BuildIdentifier, List<BuildServiceProvider<*, *>>>
)
internal
interface StoredBuilds {
/**
* Returns true if this is the first time the given [build] is seen and its state should be stored to the cache.
* Returns false if the build has already been stored to the cache.
*/
fun store(build: BuildDefinition): Boolean
}
internal
fun fillTheGapsOf(projects: Collection<Project>): List<Project> {
val projectsWithoutGaps = ArrayList<Project>(projects.size)
var index = 0
projects.forEach { project ->
var parent = project.parent
var added = 0
while (parent !== null && parent !in projectsWithoutGaps) {
projectsWithoutGaps.add(index, parent)
added += 1
parent = parent.parent
}
if (project !in projectsWithoutGaps) {
projectsWithoutGaps.add(project)
added += 1
}
index += added
}
return projectsWithoutGaps
}
| 2,095 | null | 3792 | 13,076 | c1b02a85c1d02816ba0c59fd02b656f6187a4472 | 27,140 | gradle | Apache License 2.0 |
src/main/kotlin/no/nav/amt/person/service/clients/nom/NomClientMock.kt | navikt | 618,357,446 | false | {"Kotlin": 355598, "PLpgSQL": 635, "Dockerfile": 156} | package no.nav.amt.person.service.clients.nom
class NomClientMock : NomClient {
override fun hentNavAnsatt(navIdent: String): NomNavAnsatt? {
return hentNavAnsatte(listOf(navIdent)).firstOrNull()
}
override fun hentNavAnsatte(navIdenter: List<String>): List<NomNavAnsatt> {
return navIdenter.map { navIdent ->
NomNavAnsatt(
navIdent = navIdent,
navn = "F_$navIdent E_$navIdent",
epost = "F_$navIdent.E<EMAIL>",
telefonnummer = "12345678"
)
}
}
}
| 0 | Kotlin | 0 | 0 | 907852ab4bb400de69fc37531ad9e38d18e558a9 | 480 | amt-person-service | MIT License |
src/test/kotlin/com/workos/test/TestBase.kt | workos | 419,780,611 | false | null | package com.workos.test
import com.github.tomakehurst.wiremock.client.WireMock.* // ktlint-disable no-wildcard-imports
import com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig
import com.github.tomakehurst.wiremock.junit.WireMockRule
import com.github.tomakehurst.wiremock.matching.StringValuePattern
import com.github.tomakehurst.wiremock.stubbing.StubMapping
import com.workos.WorkOS
import org.junit.ClassRule
import kotlin.test.AfterTest
open class TestBase {
val stubs = mutableListOf<StubMapping>()
companion object {
@ClassRule
@JvmField
val wireMockRule = WireMockRule(wireMockConfig().dynamicPort().dynamicHttpsPort())
}
@AfterTest
fun afterEach() {
for (stub in stubs) {
deleteStub(stub)
}
stubs.clear()
}
fun createWorkOSClient(): WorkOS {
val workos = WorkOS("apiKey")
workos.port = getWireMockPort()
workos.apiHostname = "localhost"
workos.https = false
return workos
}
fun getWireMockPort(): Int {
return wireMockRule.port()
}
fun stubResponse(
url: String,
responseBody: String,
responseStatus: Int = 200,
params: Map<String, StringValuePattern> = emptyMap(),
requestBody: String? = null,
requestHeaders: Map<String, String>? = null
): StubMapping {
val mapping = any(urlPathEqualTo(url))
.withQueryParams(params)
.willReturn(
aResponse()
.withStatus(responseStatus)
.withBody(responseBody)
.withHeader("X-Request-ID", "request_id_value")
)
if (requestBody != null) {
mapping.withRequestBody(equalToJson(requestBody))
}
if (requestHeaders != null) {
for (header in requestHeaders.entries.iterator()) {
mapping.withHeader(header.key, equalTo(header.value))
}
}
val stub = stubFor(mapping)
stubs.add(stub)
return stub
}
fun stubResponseWithScenario(
url: String,
responseBody: String,
responseStatus: Int = 200,
params: Map<String, StringValuePattern> = emptyMap(),
requestBody: String? = null,
requestHeaders: Map<String, String>? = null,
scenarioName: String,
scenarioState: String,
nextScenarioState: String
): StubMapping {
val mapping = any(urlPathEqualTo(url))
.inScenario(scenarioName)
.whenScenarioStateIs(scenarioState)
.withQueryParams(params)
.willReturn(
aResponse()
.withStatus(responseStatus)
.withBody(responseBody)
.withHeader("X-Request-ID", "request_id_value")
)
.willSetStateTo(nextScenarioState)
if (requestBody != null) {
mapping.withRequestBody(equalToJson(requestBody))
}
if (requestHeaders != null) {
for (header in requestHeaders.entries.iterator()) {
mapping.withHeader(header.key, equalTo(header.value))
}
}
val stub = stubFor(mapping)
stubs.add(stub)
return stub
}
private fun deleteStub(stub: StubMapping) {
removeStub(stub)
}
}
| 2 | Kotlin | 8 | 9 | 8be0571a48e643cea2f0c783ddb4c5fa79be1ed5 | 3,015 | workos-kotlin | MIT License |
src/main/kotlin/no/fintlabs/testrunner/config/WebClientConfig.kt | FINTLabs | 871,181,627 | false | {"Kotlin": 17639, "Dockerfile": 282} | package no.fintlabs.testrunner.config
import org.springframework.beans.factory.annotation.Value
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.web.reactive.function.client.WebClient
@Configuration
class WebClientConfig {
@Value("\${fint.metamodel-url}")
lateinit var metamodelUrl: String
@Value("\${fint.gateway-url}")
lateinit var gatewayUrl: String
@Value("\${fint.idp-url}")
lateinit var idpUrl: String
@Bean
fun idpWebClient(): WebClient = WebClient.builder().baseUrl(idpUrl).build()
@Bean
fun gatewayWebClient(): WebClient = WebClient.builder().baseUrl(gatewayUrl).build()
@Bean
fun metaModelWebClient(): WebClient = WebClient.builder().baseUrl(metamodelUrl).build()
@Bean
fun webClient(): WebClient = WebClient.create()
} | 0 | Kotlin | 0 | 0 | b97d02f1f69d1f17700a8016a769a95788981e7d | 886 | fint-test-runner-kotlin | MIT License |
kotlin/89.Gray Code(ๆ ผ้ท็ผ็ ).kt | learningtheory | 141,790,045 | false | {"Python": 4025652, "C++": 1999023, "Java": 1995266, "JavaScript": 1990554, "C": 1979022, "Ruby": 1970980, "Scala": 1925110, "Kotlin": 1917691, "Go": 1898079, "Swift": 1827809, "HTML": 124958, "Shell": 7944} | /**
<p>The gray code is a binary numeral system where two successive values differ in only one bit.</p>
<p>Given a non-negative integer <em>n</em> representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0.</p>
<p><strong>Example 1:</strong></p>
<pre>
<strong>Input:</strong> 2
<strong>Output:</strong> <code>[0,1,3,2]</code>
<strong>Explanation:</strong>
00 - 0
01 - 1
11 - 3
10 - 2
For a given <em>n</em>, a gray code sequence may not be uniquely defined.
For example, [0,2,3,1] is also a valid gray code sequence.
00 - 0
10 - 2
11 - 3
01 - 1
</pre>
<p><strong>Example 2:</strong></p>
<pre>
<strong>Input:</strong> 0
<strong>Output:</strong> <code>[0]
<strong>Explanation:</strong> We define the gray code sequence to begin with 0.
A gray code sequence of <em>n</em> has size = 2<sup>n</sup>, which for <em>n</em> = 0 the size is 2<sup>0</sup> = 1.
Therefore, for <em>n</em> = 0 the gray code sequence is [0].</code>
</pre>
<p>ๆ ผ้ท็ผ็ ๆฏไธไธชไบ่ฟๅถๆฐๅญ็ณป็ป๏ผๅจ่ฏฅ็ณป็ปไธญ๏ผไธคไธช่ฟ็ปญ็ๆฐๅผไป
ๆไธไธชไฝๆฐ็ๅทฎๅผใ</p>
<p>็ปๅฎไธไธชไปฃ่กจ็ผ็ ๆปไฝๆฐ็้่ดๆดๆฐ<em> n</em>๏ผๆๅฐๅ
ถๆ ผ้ท็ผ็ ๅบๅใๆ ผ้ท็ผ็ ๅบๅๅฟ
้กปไปฅ 0 ๅผๅคดใ</p>
<p><strong>็คบไพ 1:</strong></p>
<pre><strong>่พๅ
ฅ:</strong> 2
<strong>่พๅบ:</strong> <code>[0,1,3,2]</code>
<strong>่งฃ้:</strong>
00 - 0
01 - 1
11 - 3
10 - 2
ๅฏนไบ็ปๅฎ็ <em>n</em>๏ผๅ
ถๆ ผ้ท็ผ็ ๅบๅๅนถไธๅฏไธใ
ไพๅฆ๏ผ<code>[0,2,3,1]</code> ไนๆฏไธไธชๆๆ็ๆ ผ้ท็ผ็ ๅบๅใ
00 - 0
10 - 2
11 - 3
01 - 1</pre>
<p><strong>็คบไพ 2:</strong></p>
<pre><strong>่พๅ
ฅ:</strong> 0
<strong>่พๅบ:</strong> <code>[0]
<strong>่งฃ้:</strong> ๆไปฌๅฎไน</code>ๆ ผ้ท็ผ็ ๅบๅๅฟ
้กปไปฅ 0 ๅผๅคดใ<code>
็ปๅฎ</code>็ผ็ ๆปไฝๆฐไธบ<code> <em>n</em> ็ๆ ผ้ท็ผ็ ๅบๅ๏ผๅ
ถ้ฟๅบฆไธบ 2<sup>n</sup></code>ใ<code>ๅฝ <em>n</em> = 0 ๆถ๏ผ้ฟๅบฆไธบ 2<sup>0</sup> = 1ใ
ๅ ๆญค๏ผๅฝ <em>n</em> = 0 ๆถ๏ผๅ
ถๆ ผ้ท็ผ็ ๅบๅไธบ [0]ใ</code>
</pre>
<p>ๆ ผ้ท็ผ็ ๆฏไธไธชไบ่ฟๅถๆฐๅญ็ณป็ป๏ผๅจ่ฏฅ็ณป็ปไธญ๏ผไธคไธช่ฟ็ปญ็ๆฐๅผไป
ๆไธไธชไฝๆฐ็ๅทฎๅผใ</p>
<p>็ปๅฎไธไธชไปฃ่กจ็ผ็ ๆปไฝๆฐ็้่ดๆดๆฐ<em> n</em>๏ผๆๅฐๅ
ถๆ ผ้ท็ผ็ ๅบๅใๆ ผ้ท็ผ็ ๅบๅๅฟ
้กปไปฅ 0 ๅผๅคดใ</p>
<p><strong>็คบไพ 1:</strong></p>
<pre><strong>่พๅ
ฅ:</strong> 2
<strong>่พๅบ:</strong> <code>[0,1,3,2]</code>
<strong>่งฃ้:</strong>
00 - 0
01 - 1
11 - 3
10 - 2
ๅฏนไบ็ปๅฎ็ <em>n</em>๏ผๅ
ถๆ ผ้ท็ผ็ ๅบๅๅนถไธๅฏไธใ
ไพๅฆ๏ผ<code>[0,2,3,1]</code> ไนๆฏไธไธชๆๆ็ๆ ผ้ท็ผ็ ๅบๅใ
00 - 0
10 - 2
11 - 3
01 - 1</pre>
<p><strong>็คบไพ 2:</strong></p>
<pre><strong>่พๅ
ฅ:</strong> 0
<strong>่พๅบ:</strong> <code>[0]
<strong>่งฃ้:</strong> ๆไปฌๅฎไน</code>ๆ ผ้ท็ผ็ ๅบๅๅฟ
้กปไปฅ 0 ๅผๅคดใ<code>
็ปๅฎ</code>็ผ็ ๆปไฝๆฐไธบ<code> <em>n</em> ็ๆ ผ้ท็ผ็ ๅบๅ๏ผๅ
ถ้ฟๅบฆไธบ 2<sup>n</sup></code>ใ<code>ๅฝ <em>n</em> = 0 ๆถ๏ผ้ฟๅบฆไธบ 2<sup>0</sup> = 1ใ
ๅ ๆญค๏ผๅฝ <em>n</em> = 0 ๆถ๏ผๅ
ถๆ ผ้ท็ผ็ ๅบๅไธบ [0]ใ</code>
</pre>
**/
class Solution {
fun grayCode(n: Int): List<Int> {
}
} | 0 | Python | 1 | 3 | 6731e128be0fd3c0bdfe885c1a409ac54b929597 | 2,601 | leetcode | MIT License |
lab9/src/main/kotlin/cs/put/pmds/lab9/jaccardCoef.kt | Azbesciak | 153,350,976 | false | null | package cs.put.pmds.lab9
import com.carrotsearch.hppc.IntArrayList
import com.carrotsearch.hppc.IntHashSet
import com.carrotsearch.hppc.IntObjectHashMap
import kotlin.streams.toList
fun countAndWriteCoefficient(
total: Long, users: List<User>, output: String,
userNeighbours: (User) -> List<User>,
compute: (User, User) -> Double
) {
val progress = ProgressCounter(total)
val neighbors = users
.parallelStream()
.limit(total)
.peek { progress.increment() }
.map { user -> user.id to findClosestNeighbours(userNeighbours(user), user, compute) }
writeToFile(output, neighbors)
}
fun jaccardCoef(user: IntArray, other: IntArray): Double {
if (user.first() > other.last() || user.last() < other.first()) return 0.0
var common = 0
val userIterator = user.iterator()
val otherIterator = other.iterator()
var currentUser = userIterator.next()
var currentOther = otherIterator.next()
loop@ while (true) {
when {
currentUser == currentOther -> {
common++
if (!userIterator.hasNext() || !otherIterator.hasNext()) break@loop
currentUser = userIterator.next()
currentOther = otherIterator.next()
}
currentUser > currentOther -> {
if (!otherIterator.hasNext()) break@loop
currentOther = otherIterator.next()
}
currentUser < currentOther -> {
if (!userIterator.hasNext()) break@loop
currentUser = userIterator.next()
}
}
}
return common.toDouble() / (other.size + user.size - common)
}
fun User.getNeighbours(songs: IntObjectHashMap<IntArrayList>, users: List<User>): List<User> {
val neighbours = IntHashSet(favourites.size)
favourites.forEach { song ->
neighbours.addAll(songs[song])
}
return neighbours.map { users[it.value - 1] }
}
private fun findClosestNeighbours(userSongs: List<User>, user: User, compute: (User, User) -> Double) =
userSongs
.stream()
.map { other ->
other.id to if (user.id == other.id) 1.0 else compute(user, other)
}
.filter { it.second > 0 }
.toList()
.sortedWith(compareBy({ -it.second }, { it.first }))
.take(100) | 0 | Kotlin | 0 | 0 | f1d3cf4d51ad6588e39583f7b958c92b619799f8 | 2,438 | BigDataLabs | MIT License |
Compose/BasicswithCompose/Reply/src/androidTest/java/com/github/reply/ReplyAppStateRestorationTest.kt | pherasymchuk | 723,622,473 | false | {"Kotlin": 987660} | package com.github.reply
import androidx.activity.ComponentActivity
import androidx.compose.material3.windowsizeclass.WindowWidthSizeClass
import androidx.compose.ui.test.assertAny
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.hasAnyDescendant
import androidx.compose.ui.test.hasText
import androidx.compose.ui.test.junit4.StateRestorationTester
import androidx.compose.ui.test.junit4.createAndroidComposeRule
import androidx.compose.ui.test.onChildren
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import com.github.reply.data.local.LocalEmailsDataProvider
import com.github.reply.ui.ReplyApp
import org.junit.Rule
import org.junit.Test
class ReplyAppStateRestorationTest {
@get: Rule
val composeTestRule = createAndroidComposeRule<ComponentActivity>()
@Test
@TestCompactWidth
fun compactDevice_PerformConfigChange_SelectedEmailRetained() {
val stateRestorationTester = StateRestorationTester(composeTestRule)
stateRestorationTester.setContent { ReplyApp(windowSize = WindowWidthSizeClass.Compact) }
// Given third email is displayed
composeTestRule.onNodeWithText(composeTestRule.activity.getString(LocalEmailsDataProvider.allEmails[2].body))
.assertIsDisplayed()
// Open detailed page
composeTestRule.onNodeWithText(composeTestRule.activity.getString(LocalEmailsDataProvider.allEmails[2].subject))
.performClick()
// Verify that it shows the detailed screen for the correct email
composeTestRule.onNodeWithContentDescriptionForStringId(R.string.navigation_back)
.assertExists()
composeTestRule.onNodeWithText(composeTestRule.activity.getString(LocalEmailsDataProvider.allEmails[2].body))
.assertExists()
stateRestorationTester.emulateSavedInstanceStateRestore()
// Verify that it still shows the detailed screen for the same email
composeTestRule.onNodeWithContentDescriptionForStringId(R.string.navigation_back)
.assertExists()
composeTestRule.onNodeWithText(composeTestRule.activity.getString(LocalEmailsDataProvider.allEmails[2].body))
.assertExists()
}
@Test
@TestExpandedWidth
fun expandedDevice_PerformConfigChange_SelectedEmailRetained() {
val stateRestorationTester = StateRestorationTester(composeTestRule)
stateRestorationTester.setContent { ReplyApp(windowSize = WindowWidthSizeClass.Expanded) }
// Given second
composeTestRule.onNodeWithText(
composeTestRule.activity.getString(LocalEmailsDataProvider.allEmails[1].body)
).assertIsDisplayed()
// Select second email
composeTestRule.onNodeWithText(
composeTestRule.activity.getString(LocalEmailsDataProvider.allEmails[1].subject)
).performClick()
// Verify that the second email is displayed on the details screen
// Here I checking on children of the details screen, because home screen also contains
// that item
composeTestRule.onNodeWithTagForStringId(R.string.details_screen).onChildren()
.assertAny(
hasAnyDescendant(
hasText(
composeTestRule.activity.getString(LocalEmailsDataProvider.allEmails[1].body)
)
)
)
stateRestorationTester.emulateSavedInstanceStateRestore()
composeTestRule.onNodeWithTagForStringId(R.string.details_screen).onChildren()
.assertAny(
hasAnyDescendant(
hasText(
composeTestRule.activity.getString(LocalEmailsDataProvider.allEmails[1].body)
)
)
)
}
}
| 0 | Kotlin | 0 | 1 | 96dcaf55b7b5c5ecb2bb79bb767022dcdefcba32 | 3,833 | GoogleCodelabsApps | MIT License |
shared/src/commonMain/kotlin/com/prof18/moneyflow/domain/repository/MoneyRepository.kt | snijsure | 349,243,320 | true | {"Kotlin": 203386, "Swift": 57221, "Ruby": 2496} | package com.prof18.moneyflow.domain.repository
import com.prof18.moneyflow.domain.entities.BalanceRecap
import com.prof18.moneyflow.domain.entities.Category
import com.prof18.moneyflow.domain.entities.MoneyTransaction
import kotlinx.coroutines.flow.Flow
import com.prof18.moneyflow.presentation.addtransaction.TransactionToSave
interface MoneyRepository {
@Throws(Exception::class)
suspend fun getBalanceRecap(): Flow<BalanceRecap>
@Throws(Exception::class)
suspend fun getLatestTransactions(): Flow<List<MoneyTransaction>>
@Throws(Exception::class)
suspend fun insertTransaction(transactionToSave: TransactionToSave)
@Throws(Exception::class)
suspend fun getCategories(): Flow<List<Category>>
@Throws(Exception::class)
suspend fun deleteTransaction(transactionId: Long)
} | 0 | null | 0 | 1 | 65666f4ffa8758feebd37fd72386eba0c2cfb9fb | 820 | MoneyFlow | Apache License 2.0 |
library/kotlin/io/envoyproxy/envoymobile/LogLevel.kt | envoyproxy | 173,839,917 | false | null | package io.envoyproxy.envoymobile
/**
* Available logging levels for an Envoy instance. Note some levels may be compiled out.
*/
enum class LogLevel(internal val level: String, val levelInt: Int) {
TRACE("trace", 0),
DEBUG("debug", 1),
INFO("info", 2),
WARN("warn", 3),
ERROR("error", 4),
CRITICAL("critical", 5),
OFF("off", -1);
}
| 215 | Java | 71 | 467 | 96911b46d0ef47857f74de252de65d8cbf3d106f | 349 | envoy-mobile | Apache License 2.0 |
atomicfu/src/commonMain/kotlin/kotlinx/atomicfu/Trace.common.kt | Kotlin | 99,576,820 | false | {"Kotlin": 310810, "Shell": 762, "Java": 487} | /*
* Copyright 2016-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
@file:Suppress("INVISIBLE_REFERENCE", "INVISIBLE_MEMBER")
package kotlinx.atomicfu
import kotlin.internal.InlineOnly
/**
* Creates `Trace` object for tracing atomic operations.
*
* To use a trace create a separate field for `Trace`:
*
* ```
* val trace = Trace(size)
* ```
*
* Using it to add trace messages:
*
* ```
* trace { "Doing something" }
* ```
* or you can do multi-append in a garbage-free manner
* ```
* // Before queue.send(element) invocation
* trace.append("Adding element to the queue", element, Thread.currentThread())
* ```
*
* Pass it to `atomic` constructor to automatically trace all modifications of the corresponding field:
*
* ```
* val state = atomic(initialValue, trace)
* ```
* An optional [named][TraceBase.named] call can be used to name all the messages related to this specific instance:
*
* ```
* val state = atomic(initialValue, trace.named("state"))
* ```
*
* An optional [format] parameter can be specified to add context-specific information to each trace.
* The default format is [traceFormatDefault].
*/
@Suppress("FunctionName")
public expect fun Trace(size: Int = 32, format: TraceFormat = traceFormatDefault): TraceBase
/**
* Adds a name to the trace. For example:
*
* ```
* val state = atomic(initialValue, trace.named("state"))
* ```
*/
public expect fun TraceBase.named(name: String): TraceBase
/**
* The default trace string formatter.
*
* On JVM when `kotlinx.atomicfu.trace.thread` system property is set, then the default format
* also includes thread name for each operation.
*/
public expect val traceFormatDefault: TraceFormat
/**
* Base class for implementations of `Trace`.
*/
@OptionalJsName(TRACE_BASE_CONSTRUCTOR)
public open class TraceBase internal constructor() {
/**
* Accepts the logging [event] and appends it to the trace.
*/
@OptionalJsName(TRACE_APPEND_1)
public open fun append(event: Any) {}
/**
* Accepts the logging events [event1], [event2] and appends them to the trace.
*/
@OptionalJsName(TRACE_APPEND_2)
public open fun append(event1: Any, event2: Any) {}
/**
* Accepts the logging events [event1], [event2], [event3] and appends them to the trace.
*/
@OptionalJsName(TRACE_APPEND_3)
public open fun append(event1: Any, event2: Any, event3: Any) {}
/**
* Accepts the logging events [event1], [event2], [event3], [event4] and appends them to the trace.
*/
@OptionalJsName(TRACE_APPEND_4)
public open fun append(event1: Any, event2: Any, event3: Any, event4: Any) {}
/**
* Accepts the logging [event] and appends it to the trace.
*/
@InlineOnly
public inline operator fun invoke(event: () -> Any) {
append(event())
}
/**
* NOP tracing.
*/
public object None : TraceBase()
} | 57 | Kotlin | 58 | 917 | b94c6bd887ec48a5b172cacc0a1dac3f76c4fdbb | 2,952 | kotlinx-atomicfu | Apache License 2.0 |
prova01/Ex04_Jogador.kt | KaioPortella | 765,941,497 | false | {"Kotlin": 10171} | //Nome: <NAME> <NAME> e <NAME>
class Jogador {
//Esta funรงรฃo receberCartas recebe uma lista de cartas como entrada e imprime as cartas recebidas.
fun receberCartas(cartas: List<Carta>) {
println("Recebidas as cartas: ${cartas.joinToString(", ")}")
// Anรกlise das combinaรงรตes
if (isFlush(cartas)) {
println("Flush: Todas as cartas tรชm o mesmo naipe!")
} else if (isFullHouse(cartas)) {
println("Full House: Uma trinca e um par!")
} else if (isTrinca(cartas)) {
println("Trinca: Trรชs cartas com o mesmo valor!")
} else if (isPar(cartas)) {
println("Par: Duas cartas com o mesmo valor!")
} else {
println("Nenhuma combinaรงรฃo encontrada.")
}
}
//funcรตes para cada tipo de combinaรงรฃo
private fun isFlush(cartas: List<Carta>): Boolean = cartas.map { it.naipe }.toSet().size == 1
private fun isFullHouse(cartas: List<Carta>): Boolean {
val valores = cartas.groupingBy { it.valor }.eachCount()
return valores.containsValue(3) && valores.containsValue(2)
}
private fun isTrinca(cartas: List<Carta>): Boolean = cartas.groupingBy { it.valor }.eachCount().any { it.value == 3 }
private fun isPar(cartas: List<Carta>): Boolean = cartas.groupingBy { it.valor }.eachCount().any { it.value == 2 }
}
| 0 | Kotlin | 0 | 0 | c8f5972b5125c2f4d4b61d44e81a93f8eff7f993 | 1,365 | programacao-mobile | MIT License |
src/main/kotlin/icu/windea/pls/model/expression/complex/errors/ParadoxExpressionError.kt | DragonKnightOfBreeze | 328,104,626 | false | {"Kotlin": 3329764, "Java": 165296, "Lex": 43309, "HTML": 24521, "Shell": 2741} | package icu.windea.pls.model.expression.complex.errors
import com.intellij.codeInspection.*
import com.intellij.openapi.util.*
import com.intellij.psi.*
interface ParadoxExpressionError {
val rangeInExpression: TextRange
val description: String
val highlightType: ProblemHighlightType
}
fun ProblemsHolder.registerScriptExpressionError(element: PsiElement, error: ParadoxExpressionError) {
registerProblem(element, error.description, error.highlightType, error.rangeInExpression)
}
| 17 | Kotlin | 4 | 33 | 597996b8102f840abb13c2fed692f2b1ca08bc6b | 501 | Paradox-Language-Support | MIT License |
app/src/main/java/com/kcteam/features/logout/presentation/api/LogoutRepositoryProvider.kt | DebashisINT | 558,234,039 | false | null | package com.rajgarhiafsm.features.logout.presentation.api
/**
* Created by Pratishruti on 23-11-2017.
*/
object LogoutRepositoryProvider {
fun provideLogoutRepository(): LogoutRepository {
return LogoutRepository(LogoutApi.create())
}
} | 0 | null | 1 | 1 | e6114824d91cba2e70623631db7cbd9b4d9690ed | 255 | NationalPlastic | Apache License 2.0 |
Chapter01/Activity01.01/app/src/main/java/com/example/jetpackcompose/myapplication/MainActivity.kt | PacktPublishing | 810,886,298 | false | {"Kotlin": 915804} | package com.example.jetpackcompose.myapplication
import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.jetpackcompose.myapplication.ui.theme.MyApplicationTheme
import androidx.compose.ui.graphics.Color as ComposeColor
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
ColorCreatorScreen()
}
}
}
@Composable
fun ColorCreatorScreen() {
var redChannel by remember { mutableStateOf("") }
var greenChannel by remember { mutableStateOf("") }
var blueChannel by remember { mutableStateOf("") }
var colorToDisplay by remember { mutableStateOf(ComposeColor.White) }
val context = LocalContext.current
// Function to filter input to only allow hexadecimal characters
fun filterHexInput(input: String): String {
return input.filter { it in '0'..'9' || it in 'A'..'F' || it in 'a'..'f' }.take(2)
}
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(16.dp),
modifier = Modifier
.fillMaxSize()
.padding(16.dp)
) {
Text("Add two hexadecimal characters between 0-9, A-F or a-f without the '#' for each channel")
OutlinedTextField(
modifier = Modifier.fillMaxWidth(),
value = redChannel,
onValueChange = { redChannel = filterHexInput(it) },
label = { Text("Red Channel") }
)
OutlinedTextField(
modifier = Modifier.fillMaxWidth(),
value = greenChannel,
onValueChange = { greenChannel = filterHexInput(it) },
label = { Text("Green Channel") }
)
OutlinedTextField(
modifier = Modifier.fillMaxWidth(),
value = blueChannel,
onValueChange = { blueChannel = filterHexInput(it) },
label = { Text("Blue Channel") }
)
Button(
modifier = Modifier.fillMaxWidth(),
onClick = {
val redText = redChannel
val greenText = greenChannel
val blueText = blueChannel
// Check that all fields are filled in and show error message if not.
if (redText.isEmpty() || greenText.isEmpty() || blueText.isEmpty()) {
Toast.makeText(context, "All Values are required", Toast.LENGTH_LONG).show()
} else {
// check that 2 hexadecimal characters have been entered and if not add the same hexadecimal character again.
val red = if (redText.length == 1) redText + redText else redText
val green = if (greenText.length == 1) greenText + greenText else greenText
val blue = if (blueText.length == 1) blueText + blueText else blueText
val colorString = "#$red$green$blue"
colorToDisplay = try {
ComposeColor(android.graphics.Color.parseColor(colorString))
} catch (e: IllegalArgumentException) {
ComposeColor.White
}
}
}) {
Text(stringResource(id = R.string.create_rgb_color))
}
Text(
modifier = Modifier.background(colorToDisplay).padding(24.dp),
text = "Created color display panel"
)
}
}
@Preview(showBackground = true)
@Composable
fun MainScreenPreview() {
MyApplicationTheme {
ColorCreatorScreen()
}
}
| 0 | Kotlin | 1 | 0 | c5c51b7a25c10347a673a93384ad717870221285 | 4,717 | How-to-Build-Android-Apps-with-Kotlin-Third-Edition | MIT License |
kotlin/src/main/kotlin/com/spoonacular/MenuItemsApi.kt | ddsky | 189,444,765 | false | null | /**
* spoonacular API
* The spoonacular Nutrition, Recipe, and Food API allows you to access over 380,000 recipes, thousands of ingredients, 800,000 food products, and 100,000 menu items. Our food ontology and semantic recipe search engine makes it possible to search for recipes using natural language queries, such as \"gluten free brownies without sugar\" or \"low fat vegan cupcakes.\" You can automatically calculate the nutritional information for any recipe, analyze recipe costs, visualize ingredient lists, find recipes for what's in your fridge, find recipes based on special diets, nutritional requirements, or favorite ingredients, classify recipes into types and cuisines, convert ingredient amounts, or even compute an entire meal plan. With our powerful API, you can create many kinds of food and especially nutrition apps. Special diets/dietary requirements currently available include: vegan, vegetarian, pescetarian, gluten free, grain free, dairy free, high protein, whole 30, low sodium, low carb, Paleo, ketogenic, FODMAP, and Primal.
*
* The version of the OpenAPI document: 1.0
* Contact: <EMAIL>
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package com.spoonacular
import com.spoonacular.client.model.InlineResponse20032
import com.spoonacular.client.model.InlineResponse20035
import com.spoonacular.client.model.InlineResponse20036
import spoonacular.infrastructure.ApiClient
import spoonacular.infrastructure.ClientException
import spoonacular.infrastructure.ClientError
import spoonacular.infrastructure.ServerException
import spoonacular.infrastructure.ServerError
import spoonacular.infrastructure.MultiValueMap
import spoonacular.infrastructure.RequestConfig
import spoonacular.infrastructure.RequestMethod
import spoonacular.infrastructure.ResponseType
import spoonacular.infrastructure.Success
import spoonacular.infrastructure.toMultiValue
class MenuItemsApi(basePath: kotlin.String = "https://api.spoonacular.com") : ApiClient(basePath) {
/**
* Autocomplete Menu Item Search
* Generate suggestions for menu items based on a (partial) query. The matches will be found by looking in the title only.
* @param query The (partial) search query.
* @param number The number of results to return (between 1 and 25). (optional)
* @return InlineResponse20032
*/
@Suppress("UNCHECKED_CAST")
fun autocompleteMenuItemSearch(query: kotlin.String, number: java.math.BigDecimal?) : InlineResponse20032 {
val localVariableBody: kotlin.Any? = null
val localVariableQuery: MultiValueMap = mapOf("query" to listOf("$query"), "number" to listOf("$number"))
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.GET,
"/food/menuItems/suggest",
query = localVariableQuery,
headers = localVariableHeaders
)
val response = request<InlineResponse20032>(
localVariableConfig,
localVariableBody
)
return when (response.responseType) {
ResponseType.Success -> (response as Success<*>).data as InlineResponse20032
ResponseType.Informational -> TODO()
ResponseType.Redirection -> TODO()
ResponseType.ClientError -> throw ClientException((response as ClientError<*>).body as? String ?: "Client error")
ResponseType.ServerError -> throw ServerException((response as ServerError<*>).message ?: "Server error")
}
}
/**
* Get Menu Item Information
* Use a menu item id to get all available information about a menu item, such as nutrition.
* @param id The item's id.
* @return InlineResponse20036
*/
@Suppress("UNCHECKED_CAST")
fun getMenuItemInformation(id: kotlin.Int) : InlineResponse20036 {
val localVariableBody: kotlin.Any? = null
val localVariableQuery: MultiValueMap = mapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.GET,
"/food/menuItems/{id}".replace("{"+"id"+"}", "$id"),
query = localVariableQuery,
headers = localVariableHeaders
)
val response = request<InlineResponse20036>(
localVariableConfig,
localVariableBody
)
return when (response.responseType) {
ResponseType.Success -> (response as Success<*>).data as InlineResponse20036
ResponseType.Informational -> TODO()
ResponseType.Redirection -> TODO()
ResponseType.ClientError -> throw ClientException((response as ClientError<*>).body as? String ?: "Client error")
ResponseType.ServerError -> throw ServerException((response as ServerError<*>).message ?: "Server error")
}
}
/**
* Menu Item Nutrition by ID Image
* Visualize a menu item's nutritional information as HTML including CSS.
* @param id The menu item id.
* @return kotlin.Any
*/
@Suppress("UNCHECKED_CAST")
fun menuItemNutritionByIDImage(id: java.math.BigDecimal) : kotlin.Any {
val localVariableBody: kotlin.Any? = null
val localVariableQuery: MultiValueMap = mapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.GET,
"/food/menuItems/{id}/nutritionWidget.png".replace("{"+"id"+"}", "$id"),
query = localVariableQuery,
headers = localVariableHeaders
)
val response = request<kotlin.Any>(
localVariableConfig,
localVariableBody
)
return when (response.responseType) {
ResponseType.Success -> (response as Success<*>).data as kotlin.Any
ResponseType.Informational -> TODO()
ResponseType.Redirection -> TODO()
ResponseType.ClientError -> throw ClientException((response as ClientError<*>).body as? String ?: "Client error")
ResponseType.ServerError -> throw ServerException((response as ServerError<*>).message ?: "Server error")
}
}
/**
* Menu Item Nutrition Label Image
* Visualize a menu item's nutritional label information as an image.
* @param id The menu item id.
* @param showOptionalNutrients Whether to show optional nutrients. (optional)
* @param showZeroValues Whether to show zero values. (optional)
* @param showIngredients Whether to show a list of ingredients. (optional)
* @return kotlin.Any
*/
@Suppress("UNCHECKED_CAST")
fun menuItemNutritionLabelImage(id: java.math.BigDecimal, showOptionalNutrients: kotlin.Boolean?, showZeroValues: kotlin.Boolean?, showIngredients: kotlin.Boolean?) : kotlin.Any {
val localVariableBody: kotlin.Any? = null
val localVariableQuery: MultiValueMap = mapOf("showOptionalNutrients" to listOf("$showOptionalNutrients"), "showZeroValues" to listOf("$showZeroValues"), "showIngredients" to listOf("$showIngredients"))
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.GET,
"/food/menuItems/{id}/nutritionLabel.png".replace("{"+"id"+"}", "$id"),
query = localVariableQuery,
headers = localVariableHeaders
)
val response = request<kotlin.Any>(
localVariableConfig,
localVariableBody
)
return when (response.responseType) {
ResponseType.Success -> (response as Success<*>).data as kotlin.Any
ResponseType.Informational -> TODO()
ResponseType.Redirection -> TODO()
ResponseType.ClientError -> throw ClientException((response as ClientError<*>).body as? String ?: "Client error")
ResponseType.ServerError -> throw ServerException((response as ServerError<*>).message ?: "Server error")
}
}
/**
* Menu Item Nutrition Label Widget
* Visualize a menu item's nutritional label information as HTML including CSS.
* @param id The menu item id.
* @param defaultCss Whether the default CSS should be added to the response. (optional, default to true)
* @param showOptionalNutrients Whether to show optional nutrients. (optional)
* @param showZeroValues Whether to show zero values. (optional)
* @param showIngredients Whether to show a list of ingredients. (optional)
* @return kotlin.String
*/
@Suppress("UNCHECKED_CAST")
fun menuItemNutritionLabelWidget(id: java.math.BigDecimal, defaultCss: kotlin.Boolean?, showOptionalNutrients: kotlin.Boolean?, showZeroValues: kotlin.Boolean?, showIngredients: kotlin.Boolean?) : kotlin.String {
val localVariableBody: kotlin.Any? = null
val localVariableQuery: MultiValueMap = mapOf("defaultCss" to listOf("$defaultCss"), "showOptionalNutrients" to listOf("$showOptionalNutrients"), "showZeroValues" to listOf("$showZeroValues"), "showIngredients" to listOf("$showIngredients"))
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.GET,
"/food/menuItems/{id}/nutritionLabel".replace("{"+"id"+"}", "$id"),
query = localVariableQuery,
headers = localVariableHeaders
)
val response = request<kotlin.String>(
localVariableConfig,
localVariableBody
)
return when (response.responseType) {
ResponseType.Success -> (response as Success<*>).data as kotlin.String
ResponseType.Informational -> TODO()
ResponseType.Redirection -> TODO()
ResponseType.ClientError -> throw ClientException((response as ClientError<*>).body as? String ?: "Client error")
ResponseType.ServerError -> throw ServerException((response as ServerError<*>).message ?: "Server error")
}
}
/**
* Search Menu Items
* Search over 115,000 menu items from over 800 fast food and chain restaurants. For example, McDonald's Big Mac or Starbucks Mocha.
* @param query The (natural language) search query. (optional)
* @param minCalories The minimum amount of calories the menu item must have. (optional)
* @param maxCalories The maximum amount of calories the menu item can have. (optional)
* @param minCarbs The minimum amount of carbohydrates in grams the menu item must have. (optional)
* @param maxCarbs The maximum amount of carbohydrates in grams the menu item can have. (optional)
* @param minProtein The minimum amount of protein in grams the menu item must have. (optional)
* @param maxProtein The maximum amount of protein in grams the menu item can have. (optional)
* @param minFat The minimum amount of fat in grams the menu item must have. (optional)
* @param maxFat The maximum amount of fat in grams the menu item can have. (optional)
* @param addMenuItemInformation If set to true, you get more information about the menu items returned. (optional)
* @param offset The number of results to skip (between 0 and 900). (optional)
* @param number The maximum number of items to return (between 1 and 100). Defaults to 10. (optional, default to 10)
* @return InlineResponse20035
*/
@Suppress("UNCHECKED_CAST")
fun searchMenuItems(query: kotlin.String?, minCalories: java.math.BigDecimal?, maxCalories: java.math.BigDecimal?, minCarbs: java.math.BigDecimal?, maxCarbs: java.math.BigDecimal?, minProtein: java.math.BigDecimal?, maxProtein: java.math.BigDecimal?, minFat: java.math.BigDecimal?, maxFat: java.math.BigDecimal?, addMenuItemInformation: kotlin.Boolean?, offset: kotlin.Int?, number: kotlin.Int?) : InlineResponse20035 {
val localVariableBody: kotlin.Any? = null
val localVariableQuery: MultiValueMap = mapOf("query" to listOf("$query"), "minCalories" to listOf("$minCalories"), "maxCalories" to listOf("$maxCalories"), "minCarbs" to listOf("$minCarbs"), "maxCarbs" to listOf("$maxCarbs"), "minProtein" to listOf("$minProtein"), "maxProtein" to listOf("$maxProtein"), "minFat" to listOf("$minFat"), "maxFat" to listOf("$maxFat"), "addMenuItemInformation" to listOf("$addMenuItemInformation"), "offset" to listOf("$offset"), "number" to listOf("$number"))
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
val localVariableConfig = RequestConfig(
RequestMethod.GET,
"/food/menuItems/search",
query = localVariableQuery,
headers = localVariableHeaders
)
val response = request<InlineResponse20035>(
localVariableConfig,
localVariableBody
)
return when (response.responseType) {
ResponseType.Success -> (response as Success<*>).data as InlineResponse20035
ResponseType.Informational -> TODO()
ResponseType.Redirection -> TODO()
ResponseType.ClientError -> throw ClientException((response as ClientError<*>).body as? String ?: "Client error")
ResponseType.ServerError -> throw ServerException((response as ServerError<*>).message ?: "Server error")
}
}
/**
* Menu Item Nutrition by ID Widget
* Visualize a menu item's nutritional information as HTML including CSS.
* @param id The item's id.
* @param defaultCss Whether the default CSS should be added to the response. (optional, default to true)
* @param accept Accept header. (optional)
* @return kotlin.String
*/
@Suppress("UNCHECKED_CAST")
fun visualizeMenuItemNutritionByID(id: kotlin.Int, defaultCss: kotlin.Boolean?, accept: kotlin.String?) : kotlin.String {
val localVariableBody: kotlin.Any? = null
val localVariableQuery: MultiValueMap = mapOf("defaultCss" to listOf("$defaultCss"))
val localVariableHeaders: MutableMap<String, String> = mutableMapOf("Accept" to accept.toString())
val localVariableConfig = RequestConfig(
RequestMethod.GET,
"/food/menuItems/{id}/nutritionWidget".replace("{"+"id"+"}", "$id"),
query = localVariableQuery,
headers = localVariableHeaders
)
val response = request<kotlin.String>(
localVariableConfig,
localVariableBody
)
return when (response.responseType) {
ResponseType.Success -> (response as Success<*>).data as kotlin.String
ResponseType.Informational -> TODO()
ResponseType.Redirection -> TODO()
ResponseType.ClientError -> throw ClientException((response as ClientError<*>).body as? String ?: "Client error")
ResponseType.ServerError -> throw ServerException((response as ServerError<*>).message ?: "Server error")
}
}
}
| 6 | PHP | 34 | 18 | 63f955ceb2c356fefdd48ec634deb3c3e16a6ae7 | 15,126 | spoonacular-api-clients | MIT License |
org.librarysimplified.audiobook.tests/src/test/java/org/librarysimplified/audiobook/tests/PlayerManifestTest.kt | ThePalaceProject | 379,956,255 | false | {"Kotlin": 716069, "Java": 2392, "Shell": 968} | package org.librarysimplified.audiobook.tests
import org.joda.time.Duration
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.Assertions.assertNotNull
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import org.librarysimplified.audiobook.feedbooks.FeedbooksRights
import org.librarysimplified.audiobook.feedbooks.FeedbooksSignature
import org.librarysimplified.audiobook.manifest.api.PlayerManifest
import org.librarysimplified.audiobook.manifest.api.PlayerManifestScalar
import org.librarysimplified.audiobook.manifest.api.PlayerManifestTOC
import org.librarysimplified.audiobook.manifest.api.PlayerManifestTOCs
import org.librarysimplified.audiobook.manifest.api.PlayerMillisecondsReadingOrderItem
import org.librarysimplified.audiobook.manifest.api.PlayerPalaceID
import org.librarysimplified.audiobook.manifest_parser.api.ManifestParsers
import org.librarysimplified.audiobook.manifest_parser.api.ManifestUnparsed
import org.librarysimplified.audiobook.manifest_parser.extension_spi.ManifestParserExtensionType
import org.librarysimplified.audiobook.media3.ExoLCP
import org.librarysimplified.audiobook.parser.api.ParseResult
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.net.URI
import java.util.ServiceLoader
/**
* Tests for the {@link org.librarysimplified.audiobook.api.PlayerRawManifest} type.
*/
class PlayerManifestTest {
fun log(): Logger = LoggerFactory.getLogger(PlayerManifestTest::class.java)
@Test
fun testEmptyManifest() {
val result =
ManifestParsers.parse(
uri = URI.create("urn:empty"),
input = ManifestUnparsed(PlayerPalaceID("x"), ByteArray(0)),
extensions = listOf()
)
this.log().debug("result: {}", result)
assertTrue(result is ParseResult.Failure, "Result is failure")
}
@Test
fun testErrorMinimal0() {
val result =
ManifestParsers.parse(
uri = URI.create("urn:minimal"),
input = this.resource("error_minimal_0.json"),
extensions = listOf()
)
this.log().debug("result: {}", result)
assertTrue(result is ParseResult.Failure, "Result is failure")
}
@Test
fun testOkMinimal0() {
val result =
ManifestParsers.parse(
uri = URI.create("urn:minimal"),
input = this.resource("ok_minimal_0.json"),
extensions = listOf()
)
this.log().debug("result: {}", result)
assertTrue(result is ParseResult.Success, "Result is success")
val success: ParseResult.Success<PlayerManifest> =
result as ParseResult.Success<PlayerManifest>
val manifest = success.result
this.checkMinimalValues(manifest)
val tocItems = PlayerManifestTOCs.createTOC(manifest) { index -> "Track $index" }
this.checkTOCInvariants(tocItems, manifest)
}
@Test
fun testOkMinimal0WithExtensions() {
val result =
ManifestParsers.parse(
uri = URI.create("urn:minimal"),
input = this.resource("ok_minimal_0.json"),
extensions = ServiceLoader.load(ManifestParserExtensionType::class.java).toList()
)
this.log().debug("result: {}", result)
assertTrue(result is ParseResult.Success, "Result is success")
val success: ParseResult.Success<PlayerManifest> =
result as ParseResult.Success<PlayerManifest>
val manifest = success.result
this.checkMinimalValues(manifest)
}
private fun checkMinimalValues(manifest: PlayerManifest) {
assertEquals(3, manifest.readingOrder.size)
assertEquals("Track 0", manifest.readingOrder[0].link.title.toString())
assertEquals("100.0", manifest.readingOrder[0].link.duration.toString())
assertEquals("audio/mpeg", manifest.readingOrder[0].link.type.toString())
assertEquals(
"http://www.example.com/0.mp3",
manifest.readingOrder[0].link.hrefURI.toString()
)
assertEquals("Track 1", manifest.readingOrder[1].link.title.toString())
assertEquals("200.0", manifest.readingOrder[1].link.duration.toString())
assertEquals("audio/mpeg", manifest.readingOrder[1].link.type.toString())
assertEquals(
"http://www.example.com/1.mp3",
manifest.readingOrder[1].link.hrefURI.toString()
)
assertEquals("Track 2", manifest.readingOrder[2].link.title.toString())
assertEquals("300.0", manifest.readingOrder[2].link.duration.toString())
assertEquals("audio/mpeg", manifest.readingOrder[2].link.type.toString())
assertEquals(
"http://www.example.com/2.mp3",
manifest.readingOrder[2].link.hrefURI.toString()
)
assertEquals("title", manifest.metadata.title)
assertEquals("urn:id", manifest.metadata.identifier)
val tocItems = PlayerManifestTOCs.createTOC(manifest) { index -> "Track $index" }
this.checkTOCInvariants(tocItems, manifest)
}
@Test
fun testOkNullTitles() {
val result =
ManifestParsers.parse(
uri = URI.create("nulltitles"),
input = this.resource("null_titles.json"),
extensions = listOf()
)
this.log().debug("result: {}", result)
assertTrue(result is ParseResult.Success, "Result is success")
val success: ParseResult.Success<PlayerManifest> =
result as ParseResult.Success<PlayerManifest>
val manifest = success.result
this.checkNullTitleValues(manifest)
val tocItems = PlayerManifestTOCs.createTOC(manifest) { index -> "Track $index" }
this.checkTOCInvariants(tocItems, manifest)
}
private fun checkNullTitleValues(manifest: PlayerManifest) {
assertEquals(2, manifest.readingOrder.size)
// null title should be null
Assertions.assertNull(manifest.readingOrder[0].link.title)
// no title should be null
Assertions.assertNull(manifest.readingOrder[1].link.title)
}
@Test
fun testOkNullLinkType() {
val result =
ManifestParsers.parse(
uri = URI.create("null_link_type"),
input = this.resource("null_link_type.json"),
extensions = listOf()
)
this.log().debug("result: {}", result)
assertTrue(result is ParseResult.Success, "Result is success")
val success: ParseResult.Success<PlayerManifest> =
result as ParseResult.Success<PlayerManifest>
val manifest = success.result
this.checkNullLinkTypeValues(manifest)
val tocItems = PlayerManifestTOCs.createTOC(manifest) { index -> "Track $index" }
this.checkTOCInvariants(tocItems, manifest)
}
private fun checkNullLinkTypeValues(manifest: PlayerManifest) {
assertEquals(2, manifest.links.size)
// null type should be null
Assertions.assertNull(manifest.links[0].type)
// no type should be null
Assertions.assertNull(manifest.links[1].type)
}
@Test
fun testOkFlatlandGardeur() {
val result =
ManifestParsers.parse(
uri = URI.create("flatland"),
input = this.resource("flatland.audiobook-manifest.json"),
extensions = listOf()
)
this.log().debug("result: {}", result)
assertTrue(result is ParseResult.Success, "Result is success")
val success: ParseResult.Success<PlayerManifest> =
result as ParseResult.Success<PlayerManifest>
val manifest = success.result
this.checkFlatlandValues(manifest)
val tocItems = PlayerManifestTOCs.createTOC(manifest) { index -> "Track $index" }
this.checkTOCInvariants(tocItems, manifest)
}
@Test
fun testOkFlatlandGardeurWithExtensions() {
val result =
ManifestParsers.parse(
uri = URI.create("flatland"),
input = this.resource("flatland.audiobook-manifest.json"),
extensions = ServiceLoader.load(ManifestParserExtensionType::class.java).toList()
)
this.log().debug("result: {}", result)
assertTrue(result is ParseResult.Success, "Result is success")
val success: ParseResult.Success<PlayerManifest> =
result as ParseResult.Success<PlayerManifest>
val manifest = success.result
this.checkFlatlandValues(manifest)
}
private fun checkFlatlandValues(manifest: PlayerManifest) {
assertEquals(
"Flatland: A Romance of Many Dimensions",
manifest.metadata.title
)
assertEquals(
"https://librivox.org/flatland-a-romance-of-many-dimensions-by-edwin-abbott-abbott/",
manifest.metadata.identifier
)
assertEquals(
9,
manifest.readingOrder.size
)
assertEquals(
"Part 1, Sections 1 - 3",
manifest.readingOrder[0].link.title.toString()
)
assertEquals(
"Part 1, Sections 4 - 5",
manifest.readingOrder[1].link.title.toString()
)
assertEquals(
"Part 1, Sections 6 - 7",
manifest.readingOrder[2].link.title.toString()
)
assertEquals(
"Part 1, Sections 8 - 10",
manifest.readingOrder[3].link.title.toString()
)
assertEquals(
"Part 1, Sections 11 - 12",
manifest.readingOrder[4].link.title.toString()
)
assertEquals(
"Part 2, Sections 13 - 14",
manifest.readingOrder[5].link.title.toString()
)
assertEquals(
"Part 2, Sections 15 - 17",
manifest.readingOrder[6].link.title.toString()
)
assertEquals(
"Part 2, Sections 18 - 20",
manifest.readingOrder[7].link.title.toString()
)
assertEquals(
"Part 2, Sections 21 - 22",
manifest.readingOrder[8].link.title.toString()
)
assertEquals(
"audio/mpeg",
manifest.readingOrder[0].link.type.toString()
)
assertEquals(
"audio/mpeg",
manifest.readingOrder[1].link.type.toString()
)
assertEquals(
"audio/mpeg",
manifest.readingOrder[2].link.type.toString()
)
assertEquals(
"audio/mpeg",
manifest.readingOrder[3].link.type.toString()
)
assertEquals(
"audio/mpeg",
manifest.readingOrder[4].link.type.toString()
)
assertEquals(
"audio/mpeg",
manifest.readingOrder[5].link.type.toString()
)
assertEquals(
"audio/mpeg",
manifest.readingOrder[6].link.type.toString()
)
assertEquals(
"audio/mpeg",
manifest.readingOrder[7].link.type.toString()
)
assertEquals(
"audio/mpeg",
manifest.readingOrder[8].link.type.toString()
)
assertEquals(
"1371.0",
manifest.readingOrder[0].link.duration.toString()
)
assertEquals(
"1669.0",
manifest.readingOrder[1].link.duration.toString()
)
assertEquals(
"1506.0",
manifest.readingOrder[2].link.duration.toString()
)
assertEquals(
"1798.0",
manifest.readingOrder[3].link.duration.toString()
)
assertEquals(
"1225.0",
manifest.readingOrder[4].link.duration.toString()
)
assertEquals(
"1659.0",
manifest.readingOrder[5].link.duration.toString()
)
assertEquals(
"2086.0",
manifest.readingOrder[6].link.duration.toString()
)
assertEquals(
"2662.0",
manifest.readingOrder[7].link.duration.toString()
)
assertEquals(
"1177.0",
manifest.readingOrder[8].link.duration.toString()
)
assertEquals(
"http://www.archive.org/download/flatland_rg_librivox/flatland_1_abbott.mp3",
manifest.readingOrder[0].link.hrefURI.toString()
)
assertEquals(
"http://www.archive.org/download/flatland_rg_librivox/flatland_2_abbott.mp3",
manifest.readingOrder[1].link.hrefURI.toString()
)
assertEquals(
"http://www.archive.org/download/flatland_rg_librivox/flatland_3_abbott.mp3",
manifest.readingOrder[2].link.hrefURI.toString()
)
assertEquals(
"http://www.archive.org/download/flatland_rg_librivox/flatland_4_abbott.mp3",
manifest.readingOrder[3].link.hrefURI.toString()
)
assertEquals(
"http://www.archive.org/download/flatland_rg_librivox/flatland_5_abbott.mp3",
manifest.readingOrder[4].link.hrefURI.toString()
)
assertEquals(
"http://www.archive.org/download/flatland_rg_librivox/flatland_6_abbott.mp3",
manifest.readingOrder[5].link.hrefURI.toString()
)
assertEquals(
"http://www.archive.org/download/flatland_rg_librivox/flatland_7_abbott.mp3",
manifest.readingOrder[6].link.hrefURI.toString()
)
assertEquals(
"http://www.archive.org/download/flatland_rg_librivox/flatland_8_abbott.mp3",
manifest.readingOrder[7].link.hrefURI.toString()
)
assertEquals(
"http://www.archive.org/download/flatland_rg_librivox/flatland_9_abbott.mp3",
manifest.readingOrder[8].link.hrefURI.toString()
)
val tocItems = PlayerManifestTOCs.createTOC(manifest) { index -> "Track $index" }
this.checkTOCInvariants(tocItems, manifest)
}
@Test
fun testOkFeedbooks0() {
val result =
ManifestParsers.parse(
uri = URI.create("feedbooks"),
input = this.resource("feedbooks_0.json"),
extensions = listOf()
)
this.log().debug("result: {}", result)
assertTrue(result is ParseResult.Success, "Result is success")
val success: ParseResult.Success<PlayerManifest> =
result as ParseResult.Success<PlayerManifest>
val manifest = success.result
this.checkFeedbooks0Values(manifest)
val tocItems = PlayerManifestTOCs.createTOC(manifest) { index -> "Track $index" }
this.checkTOCInvariants(tocItems, manifest)
}
@Test
fun testOkFeedbooks0WithExtensions() {
val result =
ManifestParsers.parse(
uri = URI.create("feedbooks"),
input = this.resource("feedbooks_0.json"),
extensions = ServiceLoader.load(ManifestParserExtensionType::class.java).toList()
)
this.log().debug("result: {}", result)
assertTrue(result is ParseResult.Success, "Result is success")
val success: ParseResult.Success<PlayerManifest> =
result as ParseResult.Success<PlayerManifest>
val manifest = success.result
this.checkFeedbooks0Values(manifest)
val extensions = manifest.extensions
this.run {
val sig = extensions[0] as FeedbooksSignature
assertEquals("http://www.w3.org/2001/04/xmldsig-more#rsa-sha256", sig.algorithm)
assertEquals("https://www.cantookaudio.com", sig.issuer)
assertEquals(
"eKLux/4TtJc6VH6RTOi5lBMh9mT1j2y1z50OruWZgy8QjyPMjDV+aVZWUt7OUTinUHQfWNPBB6DxixgTZ07TQsix<KEY>
sig.value
)
}
this.run {
val rights = extensions[1] as FeedbooksRights
assertEquals("2020-02-01T17:15:52.000", rights.validStart.toString())
assertEquals("2020-03-29T17:15:52.000", rights.validEnd.toString())
}
val tocItems = PlayerManifestTOCs.createTOC(manifest) { index -> "Track $index" }
this.checkTOCInvariants(tocItems, manifest)
}
private fun checkFeedbooks0Values(manifest: PlayerManifest) {
assertEquals(
"http://archive.org/details/gleams_of_sunshine_1607_librivox",
manifest.metadata.identifier
)
assertEquals(
"Gleams of Sunshine",
manifest.metadata.title
)
assertEquals(1, manifest.readingOrder.size)
this.run {
assertEquals(
128.0,
manifest.readingOrder[0].link.duration
)
assertEquals(
"01 - Invocation",
manifest.readingOrder[0].link.title
)
assertEquals(
120.0,
manifest.readingOrder[0].link.bitrate
)
assertEquals(
"audio/mpeg",
manifest.readingOrder[0].link.type?.fullType
)
assertEquals(
"http://archive.org/download/gleams_of_sunshine_1607_librivox/gleamsofsunshine_01_chant.mp3",
manifest.readingOrder[0].link.hrefURI.toString()
)
val encrypted0 = manifest.readingOrder[0].link.properties.encrypted!!
assertEquals(
"http://www.feedbooks.com/audiobooks/access-restriction",
encrypted0.scheme
)
assertEquals(
"https://www.cantookaudio.com",
(encrypted0.values["profile"] as PlayerManifestScalar.PlayerManifestScalarString).text
)
}
assertEquals(3, manifest.links.size)
assertEquals(
"cover",
manifest.links[0].relation[0]
)
assertEquals(
180,
manifest.links[0].width
)
assertEquals(
180,
manifest.links[0].height
)
assertEquals(
"image/jpeg",
manifest.links[0].type?.fullType
)
assertEquals(
"http://archive.org/services/img/gleams_of_sunshine_1607_librivox",
manifest.links[0].hrefURI.toString()
)
assertEquals(
"self",
manifest.links[1].relation[0]
)
assertEquals(
"application/audiobook+json",
manifest.links[1].type?.fullType
)
assertEquals(
"https://api.archivelab.org/books/gleams_of_sunshine_1607_librivox/opds_audio_manifest",
manifest.links[1].hrefURI.toString()
)
assertEquals(
"license",
manifest.links[2].relation[0]
)
assertEquals(
"application/vnd.readium.license.status.v1.0+json",
manifest.links[2].type?.fullType
)
assertEquals(
"http://example.com/license/status",
manifest.links[2].hrefURI.toString()
)
val tocItems = PlayerManifestTOCs.createTOC(manifest) { index -> "Track $index" }
this.checkTOCInvariants(tocItems, manifest)
}
@Test
fun testOkFindaway0() {
val result =
ManifestParsers.parse(
uri = URI.create("findaway"),
input = this.resource("findaway.json"),
extensions = listOf()
)
this.log().debug("result: {}", result)
assertTrue(result is ParseResult.Success, "Result is success")
val success: ParseResult.Success<PlayerManifest> =
result as ParseResult.Success<PlayerManifest>
val manifest = success.result
assertEquals(
"Most Dangerous",
manifest.metadata.title
)
assertEquals(
"urn:librarysimplified.org/terms/id/Bibliotheca%20ID/hxaee89",
manifest.metadata.identifier
)
val encrypted = manifest.metadata.encrypted!!
assertEquals(
"http://librarysimplified.org/terms/drm/scheme/FAE",
encrypted.scheme
)
assertEquals(
"REDACTED0",
encrypted.values["findaway:accountId"].toString()
)
assertEquals(
"REDACTED1",
encrypted.values["findaway:checkoutId"].toString()
)
assertEquals(
"REDACTED2",
encrypted.values["findaway:sessionKey"].toString()
)
assertEquals(
"REDACTED3",
encrypted.values["findaway:fulfillmentId"].toString()
)
assertEquals(
"REDACTED4",
encrypted.values["findaway:licenseId"].toString()
)
assertEquals(
"1",
manifest.readingOrder[0].link.properties.extras["findaway:sequence"].toString()
)
assertEquals(
"0",
manifest.readingOrder[0].link.properties.extras["findaway:part"].toString()
)
val tocItems = PlayerManifestTOCs.createTOC(manifest) { index -> "Track $index" }
this.checkTOCInvariants(tocItems, manifest)
}
@Test
fun testOkFindaway20201015() {
val result =
ManifestParsers.parse(
uri = URI.create("findaway"),
input = this.resource("findaway-20201015.json"),
extensions = listOf()
)
this.log().debug("result: {}", result)
assertTrue(result is ParseResult.Success, "Result is success")
val success: ParseResult.Success<PlayerManifest> =
result as ParseResult.Success<PlayerManifest>
val manifest = success.result
assertEquals(
"Man Riding West",
manifest.metadata.title
)
assertEquals(
"urn:librarysimplified.org/terms/id/Bibliotheca%20ID/ebwowg9",
manifest.metadata.identifier
)
val encrypted = manifest.metadata.encrypted!!
assertEquals(
"http://librarysimplified.org/terms/drm/scheme/FAE",
encrypted.scheme
)
assertEquals(
"REDACTED0",
encrypted.values["findaway:accountId"].toString()
)
assertEquals(
"REDACTED1",
encrypted.values["findaway:checkoutId"].toString()
)
assertEquals(
"REDACTED2",
encrypted.values["findaway:sessionKey"].toString()
)
assertEquals(
"REDACTED3",
encrypted.values["findaway:fulfillmentId"].toString()
)
assertEquals(
"REDACTED4",
encrypted.values["findaway:licenseId"].toString()
)
assertEquals(
"1",
manifest.readingOrder[0].link.properties.extras["findaway:sequence"].toString()
)
assertEquals(
"0",
manifest.readingOrder[0].link.properties.extras["findaway:part"].toString()
)
val tocItems = PlayerManifestTOCs.createTOC(manifest) { index -> "Track $index" }
this.checkTOCInvariants(tocItems, manifest)
}
@Test
fun testOkFindawayLeading0() {
val result =
ManifestParsers.parse(
uri = URI.create("findaway"),
input = this.resource("findaway_leading_0.json"),
extensions = listOf()
)
this.log().debug("result: {}", result)
assertTrue(result is ParseResult.Success, "Result is success")
val success: ParseResult.Success<PlayerManifest> =
result as ParseResult.Success<PlayerManifest>
val manifest = success.result
val encrypted = manifest.metadata.encrypted!!
assertEquals(
"012345",
encrypted.values["findaway:fulfillmentId"].toString()
)
val tocItems = PlayerManifestTOCs.createTOC(manifest) { index -> "Track $index" }
this.checkTOCInvariants(tocItems, manifest)
}
@Test
fun testOkFeedbooks1() {
val result =
ManifestParsers.parse(
uri = URI.create("feedbooks"),
input = this.resource("feedbooks_1.json"),
extensions = listOf()
)
this.log().debug("result: {}", result)
assertTrue(result is ParseResult.Success, "Result is success")
val success: ParseResult.Success<PlayerManifest> =
result as ParseResult.Success<PlayerManifest>
val manifest = success.result
this.checkFeedbooks1Values(manifest)
val tocItems = PlayerManifestTOCs.createTOC(manifest) { index -> "Track $index" }
this.checkTOCInvariants(tocItems, manifest)
}
@Test
fun testOkFeedbooks1WithExtensions() {
val result =
ManifestParsers.parse(
uri = URI.create("feedbooks"),
input = this.resource("feedbooks_1.json"),
extensions = ServiceLoader.load(ManifestParserExtensionType::class.java).toList()
)
this.log().debug("result: {}", result)
assertTrue(result is ParseResult.Success, "Result is success")
val success: ParseResult.Success<PlayerManifest> =
result as ParseResult.Success<PlayerManifest>
val manifest = success.result
this.checkFeedbooks1Values(manifest)
val tocItems = PlayerManifestTOCs.createTOC(manifest) { index -> "Track $index" }
this.checkTOCInvariants(tocItems, manifest)
}
@Test
fun testOkIGen() {
val result =
ManifestParsers.parse(
uri = URI.create("igen"),
input = this.resource("igen.json"),
extensions = ServiceLoader.load(ManifestParserExtensionType::class.java).toList()
)
this.log().debug("result: {}", result)
assertTrue(result is ParseResult.Success, "Result is success")
val success: ParseResult.Success<PlayerManifest> =
result as ParseResult.Success<PlayerManifest>
val manifest = success.result
assertEquals("urn:isbn:9781508245063", manifest.metadata.identifier)
for (item in manifest.readingOrder) {
assertFalse(item.link.hrefURI.toString().startsWith("/"))
}
val tocItems = PlayerManifestTOCs.createTOC(manifest) { index -> "Track $index" }
this.checkTOCInvariants(tocItems, manifest)
}
private fun checkFeedbooks1Values(manifest: PlayerManifest) {
assertEquals(
"urn:uuid:35c5e499-9cb9-46e0-9e47-c517973f9e7f",
manifest.metadata.identifier
)
assertEquals(
"Rise of the Dragons, Book 1",
manifest.metadata.title
)
/*
* I don't think we really need to check the contents of all 41 spine items.
* The rest of the test suite should hopefully cover this sufficiently.
*/
assertEquals(41, manifest.readingOrder.size)
assertEquals(3, manifest.links.size)
}
private fun resource(name: String): ManifestUnparsed {
val path = "/org/librarysimplified/audiobook/tests/" + name
return ManifestUnparsed(
palaceId = PlayerPalaceID(path),
data = ResourceMarker::class.java.getResourceAsStream(path)?.readBytes()
?: throw AssertionError("Missing resource file: " + path)
)
}
/**
* "This one is an example of a manifest with an implicit โintroductionโ or โforwardโ chapter.
* The โ9781442304611_00_TheDemonsCovenant_Title.mp3โ file from the ReadingOrder is never
* referenced in the TOC."
*/
@Test
fun testDifficultManifest0() {
val result =
ManifestParsers.parse(
uri = URI.create("demon"),
input = this.resource("audible/demon.json"),
extensions = ServiceLoader.load(ManifestParserExtensionType::class.java).toList()
)
this.log().debug("result: {}", result)
assertTrue(result is ParseResult.Success, "Result is success")
val success: ParseResult.Success<PlayerManifest> =
result as ParseResult.Success<PlayerManifest>
val manifest =
success.result
val tocItems =
PlayerManifestTOCs.createTOC(manifest) { index -> "Track $index" }
this.checkTOCInvariants(tocItems, manifest)
}
private fun checkTOCInvariants(
tocItems: PlayerManifestTOC,
manifest: PlayerManifest
) {
println("# Reading Order Items")
manifest.readingOrder.forEachIndexed { index, link ->
println("[$index] ${tocItems.readingOrderIntervals[link.id]}")
}
println("# TOC Items")
var tocTotal = 0L
tocItems.tocItemsInOrder.forEachIndexed { index, toc ->
val size = toc.intervalAbsoluteMilliseconds.size()
tocTotal += size.value
println("[$index] Size $size | Total $tocTotal | Item $toc")
}
val durationSum =
manifest.readingOrder.sumOf { item ->
Duration.standardSeconds((item.link.duration ?: 0L).toLong()).millis
}
val readingOrderIntervalsSum =
tocItems.readingOrderIntervals.values.sumOf {
i -> (i.upper - i.lower).value + 1
}
val tocItemIntervalsSum =
tocItems.tocItemsInOrder.sumOf {
i -> (i.intervalAbsoluteMilliseconds.upper - i.intervalAbsoluteMilliseconds.lower).value + 1
}
assertEquals(
durationSum,
readingOrderIntervalsSum,
"Sum of reading order intervals must equal reading order duration sum"
)
assertEquals(
durationSum,
tocItemIntervalsSum,
"Sum of TOC item intervals must equal reading order duration sum"
)
for (item in manifest.readingOrder) {
val duration = (item.link.duration ?: 1).toLong() + 10
for (time in 0..duration) {
val tocItem = tocItems.lookupTOCItem(item.id, PlayerMillisecondsReadingOrderItem(time))
assertNotNull(tocItem, "TOC item for ${item.id} time $time must not be null")
}
}
}
/**
* "This one is a good example of a tricky manifest where some chapters span multiple tracks.
* For example the chapter โLondon Bridgeโ spans 3 different tracks. And โThe City of Londonโ
* chapter has two almost complete tracks as part of it.
*
* It also has an example of a very small chapter โBook One - Quicksilverโ
*
* This is an example of a manifest where figuring out the length of the final chapter is
* slightly more difficult because there is no following chapter, so you have to use the duration
* of the tracks to the end of the book to calculate it."
*/
@Test
fun testDifficultManifest1() {
val result =
ManifestParsers.parse(
uri = URI.create("quicksilver"),
input = this.resource("audible/quicksilver.json"),
extensions = ServiceLoader.load(ManifestParserExtensionType::class.java).toList()
)
this.log().debug("result: {}", result)
assertTrue(result is ParseResult.Success, "Result is success")
val success: ParseResult.Success<PlayerManifest> =
result as ParseResult.Success<PlayerManifest>
val manifest =
success.result
val tocItems =
PlayerManifestTOCs.createTOC(manifest) { index -> "Track $index" }
this.checkTOCInvariants(tocItems, manifest)
}
/**
* "This one has an example of a 0 length chapter โJourneymanโ, which is another weird edge case.
* In a ticket we asked DeMarque about fixing these, but it might be good to be able to handle
* this case."
*/
@Test
fun testDifficultManifest2() {
val result =
ManifestParsers.parse(
uri = URI.create("weapon"),
input = this.resource("audible/weapon.json"),
extensions = ServiceLoader.load(ManifestParserExtensionType::class.java).toList()
)
this.log().debug("result: {}", result)
assertTrue(result is ParseResult.Success, "Result is success")
val success: ParseResult.Success<PlayerManifest> =
result as ParseResult.Success<PlayerManifest>
val manifest =
success.result
val tocItems =
PlayerManifestTOCs.createTOC(manifest) { index -> "Track $index" }
this.checkTOCInvariants(tocItems, manifest)
}
/**
* "Another example of 0 length chapters:"
*/
@Test
fun testDifficultManifest3() {
val result =
ManifestParsers.parse(
uri = URI.create("yellow_eyes"),
input = this.resource("audible/yellow_eyes.json"),
extensions = ServiceLoader.load(ManifestParserExtensionType::class.java).toList()
)
this.log().debug("result: {}", result)
assertTrue(result is ParseResult.Success, "Result is success")
val success: ParseResult.Success<PlayerManifest> =
result as ParseResult.Success<PlayerManifest>
val manifest =
success.result
val tocItems =
PlayerManifestTOCs.createTOC(manifest) { index -> "Track $index" }
this.checkTOCInvariants(tocItems, manifest)
}
/**
* Random game audio.
*/
@Test
fun testRandomGameAudio() {
val result =
ManifestParsers.parse(
uri = URI.create("random-game-audio.json"),
input = this.resource("random-game-audio.json"),
extensions = ServiceLoader.load(ManifestParserExtensionType::class.java).toList()
)
this.log().debug("result: {}", result)
assertTrue(result is ParseResult.Success, "Result is success")
val success: ParseResult.Success<PlayerManifest> =
result as ParseResult.Success<PlayerManifest>
val manifest =
success.result
val tocItems =
PlayerManifestTOCs.createTOC(manifest) { index -> "Track $index" }
assertEquals(4, tocItems.tocItemsInOrder.size)
assertEquals(0, tocItems.tocItemsInOrder[0].intervalAbsoluteMilliseconds.lower.value)
assertEquals(10000, tocItems.tocItemsInOrder[1].intervalAbsoluteMilliseconds.lower.value)
assertEquals(20000, tocItems.tocItemsInOrder[2].intervalAbsoluteMilliseconds.lower.value)
assertEquals(30000, tocItems.tocItemsInOrder[3].intervalAbsoluteMilliseconds.lower.value)
this.checkTOCInvariants(tocItems, manifest)
}
/**
* I-Strahd
*/
@Test
fun testIStrahd() {
val result =
ManifestParsers.parse(
uri = URI.create("i_strahd.json"),
input = this.resource("audible/i_strahd.json"),
extensions = ServiceLoader.load(ManifestParserExtensionType::class.java).toList()
)
this.log().debug("result: {}", result)
assertTrue(result is ParseResult.Success, "Result is success")
val success: ParseResult.Success<PlayerManifest> =
result as ParseResult.Success<PlayerManifest>
val manifest = success.result
assertTrue(ExoLCP.isLCP(manifest), "Manifest is inferred as LCP")
}
}
| 1 | Kotlin | 1 | 1 | e876ad5481897b14c37c0969997dcce0807fac33 | 31,833 | android-audiobook | Apache License 2.0 |
lib/src/main/kotlin/be/zvz/klover/format/OpusAudioDataFormat.kt | organization | 673,130,266 | false | null | package be.zvz.klover.format
import be.zvz.klover.format.transcoder.AudioChunkDecoder
import be.zvz.klover.format.transcoder.AudioChunkEncoder
import be.zvz.klover.format.transcoder.OpusChunkDecoder
import be.zvz.klover.format.transcoder.OpusChunkEncoder
import be.zvz.klover.player.AudioConfiguration
/**
* An [AudioDataFormat] for OPUS.
*
* @param channelCount Number of channels.
* @param sampleRate Sample rate (frequency).
* @param chunkSampleCount Number of samples in one chunk.
*/
class OpusAudioDataFormat(channelCount: Int, sampleRate: Int, chunkSampleCount: Int) :
AudioDataFormat(channelCount, sampleRate, chunkSampleCount) {
private val maximumChunkSize: Int
private val expectedChunkSize: Int
init {
maximumChunkSize = 32 + 1536 * chunkSampleCount / 960
expectedChunkSize = 32 + 512 * chunkSampleCount / 960
}
override fun codecName(): String {
return CODEC_NAME
}
override fun silenceBytes(): ByteArray {
return SILENT_OPUS_FRAME
}
override fun expectedChunkSize(): Int {
return expectedChunkSize
}
override fun maximumChunkSize(): Int {
return maximumChunkSize
}
override fun createDecoder(): AudioChunkDecoder {
return OpusChunkDecoder(this)
}
override fun createEncoder(configuration: AudioConfiguration): AudioChunkEncoder {
return OpusChunkEncoder(configuration, this)
}
override fun equals(o: Any?): Boolean {
return this === o || o != null && javaClass == o.javaClass && super.equals(o)
}
override fun hashCode(): Int {
var result = super.hashCode()
result = 31 * result + maximumChunkSize
result = 31 * result + expectedChunkSize
return result
}
companion object {
const val CODEC_NAME = "OPUS"
private val SILENT_OPUS_FRAME = byteArrayOf(0xFC.toByte(), 0xFF.toByte(), 0xFE.toByte())
}
}
| 1 | Kotlin | 0 | 2 | 06e801808933ff8c627543d579c4be00061eb305 | 1,951 | Klover | Apache License 2.0 |
multiplatform/src/iosSimulatorArm64Main/kotlin/com/vsevolodganin/clicktrack/Main.kt | vganin | 293,315,190 | false | {"Kotlin": 611912, "C++": 4113, "Ruby": 2402, "Swift": 526, "CMake": 281} | package com.vsevolodganin.clicktrack
import androidx.compose.runtime.remember
import androidx.compose.ui.window.ComposeUIViewController
import com.arkivanov.decompose.DefaultComponentContext
import com.arkivanov.essenty.lifecycle.LifecycleRegistry
import com.vsevolodganin.clicktrack.di.component.ApplicationComponent
import com.vsevolodganin.clicktrack.di.component.MainViewControllerComponent
import com.vsevolodganin.clicktrack.di.component.create
import com.vsevolodganin.clicktrack.ui.RootView
// TODO: ๐ง Under heavy construction ๐ง
fun MainViewController() = ComposeUIViewController {
val rootViewModel = remember {
MainViewControllerComponent::class.create(
applicationComponent = ApplicationComponent::class.create(),
componentContext = DefaultComponentContext(LifecycleRegistry())
)
.also {
it.migrationManager.tryMigrate()
}
.rootViewModel
}
RootView(rootViewModel)
}
| 7 | Kotlin | 1 | 22 | e0de3d92ee1921eda2053064fd4ae082b831caa9 | 984 | click-track | Apache License 2.0 |
idea/testData/findUsages/libraryUsages/kotlinLibrary/LibraryNestedClassMemberFunctionUsages.0.kt | JakeWharton | 99,388,807 | false | null | // PSI_ELEMENT: org.jetbrains.kotlin.psi.KtNamedFunction
// OPTIONS: usages
// FIND_BY_REF
// WITH_FILE_NAME
package usages
import library.*
fun test() {
val f = A.T::bar
A.T().<caret>bar(1)
}
// FIR_COMPARISON | 1 | null | 30 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 222 | kotlin | Apache License 2.0 |
src/test/kotlin/com/leetcode/P14Test.kt | antop-dev | 229,558,170 | false | {"Maven POM": 1, "Text": 4, "Ignore List": 1, "Markdown": 1, "Java": 233, "Kotlin": 832, "Python": 10} | package com.leetcode
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
class P14Test {
val p = P14()
@Test
fun `example 1`() {
assertEquals("fl", p.longestCommonPrefix(arrayOf("flower", "flow", "flight")))
}
@Test
fun `example 2`() {
assertEquals("", p.longestCommonPrefix(arrayOf("dog", "racecar", "car")))
}
@Test
fun `example 3`() {
assertEquals("", p.longestCommonPrefix(arrayOf("")))
}
@Test
fun `example 4`() {
assertEquals("", p.longestCommonPrefix(arrayOf("", "b")))
}
@Test
fun `example 5`() {
assertEquals("c", p.longestCommonPrefix(arrayOf("c", "c")))
}
@Test
fun `example 6`() {
assertEquals("a", p.longestCommonPrefix(arrayOf("aa", "a")))
}
}
| 6 | Kotlin | 0 | 0 | c445a4d34cdd4b400d4171121cef11f1c6dc9aad | 825 | algorithm | MIT License |
core/src/main/kotlin/com/malinskiy/marathon/execution/strategy/impl/flakiness/ProbabilityBasedFlakinessStrategy.kt | lukaville | 251,365,845 | true | {"Kotlin": 530071, "JavaScript": 41573, "SCSS": 27631, "HTML": 2925, "Shell": 2350, "CSS": 1662} | package com.malinskiy.marathon.execution.strategy.impl.flakiness
import com.malinskiy.marathon.analytics.external.MetricsProvider
import com.malinskiy.marathon.execution.TestShard
import com.malinskiy.marathon.execution.strategy.FlakinessStrategy
import com.malinskiy.marathon.test.Test
import java.time.Instant
/**
* The idea is that flakiness anticipates the flakiness of the test based on the probability of test passing
* and tries to maximize the probability of passing when executed multiple times.
* For example the probability of test A passing is 0.5 and configuration has probability of 0.8 requested,
* then the flakiness strategy multiplies the test A to be executed 3 times
* (0.5 x 0.5 x 0.5 = 0.125 is the probability of all tests failing, so with probability 0.875 > 0.8 at least one of tests will pass).
*/
class ProbabilityBasedFlakinessStrategy(
val minSuccessRate: Double,
val maxCount: Int,
val timeLimit: Instant
) : FlakinessStrategy {
override fun process(
testShard: TestShard,
metricsProvider: MetricsProvider
): TestShard {
val tests = testShard.tests
val output = mutableListOf<Test>()
tests.forEach {
val successRate = metricsProvider.successRate(it, timeLimit)
if (successRate < minSuccessRate) {
val maxFailRate = 1.0 - minSuccessRate
var currentFailRate = 1.0 - successRate
var counter = 0
while (currentFailRate > maxFailRate && counter < maxCount) {
output.add(it)
currentFailRate *= currentFailRate
counter++
}
}
}
return testShard.copy(flakyTests = output)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as ProbabilityBasedFlakinessStrategy
if (minSuccessRate != other.minSuccessRate) return false
if (maxCount != other.maxCount) return false
if (timeLimit != other.timeLimit) return false
return true
}
override fun hashCode(): Int {
var result = minSuccessRate.hashCode()
result = 31 * result + maxCount
result = 31 * result + timeLimit.hashCode()
return result
}
override fun toString(): String {
return "ProbabilityBasedFlakinessStrategy(minSuccessRate=$minSuccessRate, maxCount=$maxCount, timeLimit=$timeLimit)"
}
}
| 1 | Kotlin | 6 | 1 | e07de46f42f42e7b0a335bc1f81682deaa769288 | 2,538 | marathon | Apache License 2.0 |
client/standalone/src/main/kotlin/ai/flowstorm/client/standalone/io/NoSpeechDevice.kt | flowstorm | 327,536,541 | false | null | package ai.flowstorm.client.standalone.io
import ai.flowstorm.client.audio.SpeechDevice
object NoSpeechDevice : SpeechDevice {
override val isSpeechDetected = true
override val speechAngle = 0
override fun close() {}
override fun toString(): String = this::class.simpleName!!
} | 1 | null | 5 | 9 | 53dae04fa113963d632ea4d44e184885271b0322 | 297 | core | Apache License 2.0 |
core/uwb/uwb/src/main/java/androidx/core/uwb/UwbClientSessionScope.kt | androidx | 256,589,781 | false | null | /*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.core.uwb
import kotlinx.coroutines.flow.Flow
/** Interface for client session that is established between nearby UWB devices. */
interface UwbClientSessionScope {
/**
* Returns a flow of [RangingResult]. Consuming the flow will initiate the UWB ranging and only
* one flow can be initiated. To consume the flow from multiple consumers, convert the flow to a
* SharedFlow.
*
* @throws [IllegalStateException] if a new flow was consumed again after the UWB ranging is
* already initiated.
* @throws [androidx.core.uwb.exceptions.UwbSystemCallbackException] if the backend UWB system
* has resulted in an error.
* @throws [SecurityException] if ranging does not have the android.permission.UWB_RANGING
* permission. Apps must have requested and been granted this permission before calling this
* method.
* @throws [IllegalArgumentException] if the client starts a ranging session without setting
* complex channel and peer address.
* @throws [IllegalArgumentException] if the client starts a ranging session with invalid config
* id or ranging update type.
*/
fun prepareSession(parameters: RangingParameters): Flow<RangingResult>
/** Returns the [RangingCapabilities] which the device supports. */
val rangingCapabilities: RangingCapabilities
/**
* A local address can only be used for a single ranging session. After a ranging session is
* ended, a new address will be allocated.
*
* Ranging session duration may also be limited to prevent addresses from being used for too
* long. In this case, your ranging session would be suspended and clients would need to
* exchange the new address with their peer before starting again.
*/
val localAddress: UwbAddress
/**
* Dynamically reconfigures range data notification config to an active ranging session.
*
* @throws [IllegalStateException] if the ranging is inactive.
*
* Otherwise, this method will return successfully, then clients are expected to handle
* [RangingResult.RangingResultPeerDisconnected] with the controlee as parameter of the
* callback.
*/
suspend fun reconfigureRangeDataNtf(configType: Int, proximityNear: Int, proximityFar: Int)
}
| 30 | null | 974 | 5,321 | 98b929d303f34d569e9fd8a529f022d398d1024b | 2,942 | androidx | Apache License 2.0 |
amethyst.core/common/src/main/kotlin/org/hexworks/amethyst/api/base/BaseFacet.kt | MaTriXy | 196,859,874 | true | {"Kotlin": 43839} | package org.hexworks.amethyst.api.base
import org.hexworks.amethyst.api.Attribute
import org.hexworks.amethyst.api.Context
import org.hexworks.amethyst.api.system.Facet
import org.hexworks.cobalt.datatypes.factory.IdentifierFactory
import kotlin.reflect.KClass
abstract class BaseFacet<C : Context>(vararg mandatoryAttribute: KClass<out Attribute>) : Facet<C> {
override val id = IdentifierFactory.randomIdentifier()
override val mandatoryAttributes: Set<KClass<out Attribute>> = mandatoryAttribute.toSet()
}
| 0 | Kotlin | 0 | 0 | 64b28c8f3ae8d92da49ad2c65416aacfc43c1568 | 521 | amethyst | Apache License 2.0 |
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/quicksight/CfnTemplateWaterfallChartOptionsPropertyDsl.kt | cloudshiftinc | 667,063,030 | false | null | @file:Suppress(
"RedundantVisibilityModifier",
"RedundantUnitReturnType",
"RemoveRedundantQualifierName",
"unused",
"UnusedImport",
"ClassName",
"REDUNDANT_PROJECTION",
"DEPRECATION"
)
package cloudshift.awscdk.dsl.services.quicksight
import cloudshift.awscdk.common.CdkDslMarker
import kotlin.String
import software.amazon.awscdk.services.quicksight.CfnDashboard
/**
* The options that determine the presentation of trend arrows in a KPI visual.
*
* Example:
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import software.amazon.awscdk.services.quicksight.*;
* TrendArrowOptionsProperty trendArrowOptionsProperty = TrendArrowOptionsProperty.builder()
* .visibility("visibility")
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-quicksight-dashboard-trendarrowoptions.html)
*/
@CdkDslMarker
public class CfnDashboardTrendArrowOptionsPropertyDsl {
private val cdkBuilder: CfnDashboard.TrendArrowOptionsProperty.Builder =
CfnDashboard.TrendArrowOptionsProperty.builder()
/** @param visibility The visibility of the trend arrows. */
public fun visibility(visibility: String) {
cdkBuilder.visibility(visibility)
}
public fun build(): CfnDashboard.TrendArrowOptionsProperty = cdkBuilder.build()
}
| 4 | null | 0 | 3 | c59c6292cf08f0fc3280d61e7f8cff813a608a62 | 1,428 | awscdk-dsl-kotlin | Apache License 2.0 |
app/src/main/java/com/eatssu/android/ui/review/delete/DeleteViewModel.kt | EAT-SSU | 601,871,281 | false | null | package com.eatssu.android.ui.review.etc
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.eatssu.android.base.BaseResponse
import com.eatssu.android.data.dto.request.ModifyReviewRequest
import com.eatssu.android.data.service.ReviewService
import com.eatssu.android.util.RetrofitImpl
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class FixViewModel : ViewModel() {
private val _isDone = MutableLiveData<Boolean>()
val isDone: LiveData<Boolean> get() = _isDone
private val _toastMessage = MutableLiveData<String>()
val toastMessage: LiveData<String> get() = _toastMessage
fun postData(reviewId: Long, comment: String, mainGrade: Int, amountGrade: Int, tasteGrade: Int) {
val service = RetrofitImpl.retrofit.create(ReviewService::class.java)
val reviewData = ModifyReviewRequest(mainGrade, amountGrade, tasteGrade, comment)
viewModelScope.launch(Dispatchers.IO) {
service.modifyReview(reviewId, reviewData).enqueue(object : Callback<BaseResponse<Void>> {
override fun onResponse(call: Call<BaseResponse<Void>>, response: Response<BaseResponse<Void>>) {
if (response.isSuccessful) {
if (response.code() == 200) {
handleSuccessResponse("์์ ์ด ์๋ฃ๋์์ต๋๋ค.")
} else {
handleErrorResponse("์์ ์ด ์คํจํ์์ต๋๋ค.")
}
}
}
override fun onFailure(call: Call<BaseResponse<Void>>, t: Throwable) {
handleErrorResponse("์์ ์ด ์คํจํ์์ต๋๋ค.")
}
})
}
}
fun handleSuccessResponse(message: String) {
viewModelScope.launch(Dispatchers.Main) {
_toastMessage.value = message
_isDone.value = true
}
}
fun handleErrorResponse(message: String) {
viewModelScope.launch(Dispatchers.Main) {
_toastMessage.value = message
_isDone.value = false
}
}
} | 25 | null | 0 | 9 | ebd47bfe9e971a017f27a2436f56978cf7d9ec28 | 2,252 | Android | MIT License |
shared/src/iosTest/kotlin/siarhei/luskanau/kmm/shared/GreetingTest.kt | siarhei-luskanau | 346,266,438 | false | null | package siarhei.luskanau.kmm.shared
import kotlin.test.Test
import kotlin.test.assertEquals
import platform.Foundation.NSBundle
class GreetingTest {
@Test
fun testExample() {
val bundle = NSBundle.mainBundle()
assertEquals(
expected = "{\n" +
" \"name\": \"kotlinx.serialization\",\n" +
" \"language\": \"${bundle}\"\n" +
"}\n",
actual = ResourceReader(bundle = bundle).readResource("data.json")
)
}
}
| 0 | null | 0 | 1 | fdb82c5d39266154bc6b36da799165b3fcf69807 | 515 | kmm-sample | MIT License |
app/src/main/kotlin/dev/sanmer/pi/ui/screens/sessions/SessionsScreen.kt | SanmerApps | 720,492,308 | false | {"Kotlin": 258662, "Java": 15047, "AIDL": 3726} | package dev.sanmer.pi.ui.screens.sessions
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.material3.TopAppBarScrollBehavior
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.NavController
import dev.sanmer.pi.R
import dev.sanmer.pi.ui.component.Loading
import dev.sanmer.pi.ui.component.NavigateUpTopBar
import dev.sanmer.pi.ui.component.PageIndicator
import dev.sanmer.pi.viewmodel.SessionsViewModel
@Composable
fun SessionsScreen(
navController: NavController,
viewModel: SessionsViewModel = hiltViewModel()
) {
DisposableEffect(viewModel) {
viewModel.registerCallback()
onDispose { viewModel.unregisterCallback() }
}
val list by viewModel.sessions.collectAsStateWithLifecycle()
val scrollBehavior = TopAppBarDefaults.pinnedScrollBehavior()
val state = rememberLazyListState()
Scaffold(
modifier = Modifier.nestedScroll(scrollBehavior.nestedScrollConnection),
topBar = {
TopBar(
onAbandonAll = viewModel::abandonAll,
navController = navController,
scrollBehavior = scrollBehavior
)
}
) { innerPadding ->
Box(modifier = Modifier
.padding(innerPadding)
) {
if (viewModel.isLoading) {
Loading()
}
if (list.isEmpty() && !viewModel.isLoading) {
PageIndicator(
icon = R.drawable.list_details,
text = R.string.apps_empty,
)
}
LazyColumn(
state = state
) {
items(
items = list,
key = { it.sessionId }
) {
SessionItem(session = it)
}
}
}
}
}
@Composable
private fun TopBar(
onAbandonAll: () -> Unit,
navController: NavController,
scrollBehavior: TopAppBarScrollBehavior
) = NavigateUpTopBar(
title = stringResource(id = R.string.sessions_title),
actions = {
IconButton(onClick = onAbandonAll) {
Icon(
painter = painterResource(id = R.drawable.cookie_off),
contentDescription = null
)
}
},
navController = navController,
scrollBehavior = scrollBehavior
) | 0 | Kotlin | 3 | 168 | 889c42f761aa41efc171a6b9cf87a7d019bae7ff | 3,166 | PI | MIT License |
app/src/main/java/pl/vemu/zsme/ui/components/SimpleSmallAppBar.kt | xVemu | 231,614,467 | false | null | package pl.vemu.zsme.ui.components
import androidx.annotation.StringRes
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.ArrowBack
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.SmallTopAppBar
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.res.stringResource
import androidx.navigation.NavController
import pl.vemu.zsme.R
@Composable
fun simpleSmallAppBar(@StringRes title: Int, navController: NavController): @Composable () -> Unit =
simpleSmallAppBar(stringResource(title), navController)
@Composable
fun simpleSmallAppBar(title: String, navController: NavController): @Composable () -> Unit =
{
SmallTopAppBar(
title = { Text(title) },
navigationIcon = {
IconButton(onClick = {
navController.popBackStack()
}) {
Icon(
imageVector = Icons.Rounded.ArrowBack,
contentDescription = stringResource(R.string.back_button),
)
}
}
)
} | 0 | Kotlin | 0 | 3 | 42b8d5e8bfcd071939b7eb9caeacc1bc6030356b | 1,227 | zsme | MIT License |
compose-kit/src/main/java/com/nikoarap/compose_kit/composables/Expandables.kt | nikoarap | 700,991,912 | false | {"Kotlin": 342382} | package com.nikoarap.compose_kit.composables
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
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.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.material3.Card
import androidx.compose.material3.Divider
import androidx.compose.material3.Icon
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import com.nikoarap.compose_kit.R
import com.nikoarap.compose_kit.styles.DP_16
import com.nikoarap.compose_kit.styles.DP_8
import com.nikoarap.compose_kit.utils.Constants.Companion.EIGHTY_PERCENT
import com.nikoarap.compose_kit.utils.Constants.Companion.EMPTY
import com.nikoarap.compose_kit.utils.Constants.Companion.ICON
import com.nikoarap.compose_kit.utils.Constants.Companion.ONE
import com.nikoarap.compose_kit.utils.Constants.Companion.ONE_EIGHTY_FLOAT
import com.nikoarap.compose_kit.utils.Constants.Companion.THREE
import com.nikoarap.compose_kit.utils.Constants.Companion.ZERO_FLOAT
/**
* Composable function to display an expandable section with a title, subtitle, and optional content.
*
* @param title The title text of the expandable section.
* @param subtitle The subtitle text of the expandable section.
* @param titleTypography The style of the title in material design scale
* @param subtitleTypography The style of the subtitle in material design scale
* @param titleColor The color of the title text.
* @param subtitleColor The color of the subtitle text.
* @param textStartPaddingsDp The start paddings for the title and subtitle texts.
* @param iconSizeDp The size for the expand/collapse icon.
* @param iconSidePaddingsDp The paddings for the expand/collapse icon.
* @param iconTintColor The color of the expand/collapse icon.
* @param dividerColor The color of the divider line.
* @param isExpanded A boolean representing whether the section is expanded or collapsed. You can also use the value of a mutable state that is declared in your viewModel for the state to be remembered in your lifecycle
* @param expandableContent The content to be displayed when the section is expanded.
*
* This Composable function creates an expandable section with a title, subtitle, and an optional content area.
* The section can be expanded or collapsed by tapping on it.
*
* Example usage:
* ```
* ExpandableSection(
* title = "Section Title",
* subtitle = "Section Subtitle",
* titleTypography = MaterialTheme.typography.bodyLarge,
* subtitleTypography = MaterialTheme.typography.bodyLarge,
* titleColor = Color.Black,
* subtitleColor = Color.Gray,
* textStartPaddingsDp = 16.dp,
* iconSizeDp = 24.dp,
* iconSidePaddingsDp = 16.dp,
* iconTintColor = Color.Gray,
* dividerColor = Color.Gray,
* isExpanded = isExpanded,
* expandableContent = {
* // Content to display when the section is expanded
* Text("This is the expandable content.")
* }
* )
* ```
*/
@Composable
fun ExpandableSection(
title: String,
subtitle: String,
titleTypography: TextStyle,
subtitleTypography: TextStyle,
titleColor: Color,
subtitleColor: Color,
textStartPaddingsDp: Dp,
iconSizeDp: Dp,
iconSidePaddingsDp: Dp,
iconTintColor: Color,
dividerColor: Color,
isExpanded: Boolean,
expandableContent: @Composable () -> Unit
) {
var expandedState by remember { mutableStateOf(isExpanded) }
val rotationState by animateFloatAsState(targetValue = if (expandedState) ONE_EIGHTY_FLOAT else ZERO_FLOAT, label = EMPTY)
Card(
modifier = Modifier
.fillMaxWidth()
.wrapContentHeight()
) {
Row(
modifier = Modifier.clickable {
expandedState = !expandedState
},
verticalAlignment = Alignment.CenterVertically,
) {
Column(
Modifier
.padding(top = DP_16, bottom = DP_8)
.height(intrinsicSize = IntrinsicSize.Max)
) {
CustomizedText(
modifier = Modifier.padding(start = textStartPaddingsDp),
textValue = title,
typography = titleTypography,
maxLines = ONE,
textColor = titleColor,
softWrap = true
)
CustomizedText(
modifier = Modifier.padding(start = textStartPaddingsDp),
textValue = subtitle,
typography = subtitleTypography,
maxLines = ONE,
textColor = subtitleColor,
softWrap = true
)
}
Column(
Modifier
.wrapContentHeight()
.weight(EIGHTY_PERCENT, true),
horizontalAlignment = Alignment.End
) {
Row(
verticalAlignment = Alignment.CenterVertically,
) {
Spacer(Modifier.width(iconSidePaddingsDp))
Icon(
modifier = Modifier
.size(iconSizeDp)
.rotate(rotationState),
painter = painterResource(R.drawable.ic_caret_down),
contentDescription = ICON,
tint = iconTintColor
)
Spacer(Modifier.width(iconSidePaddingsDp))
}
}
}
}
when {
expandedState -> {
expandableContent()
}
else -> {
Divider(
modifier = Modifier.fillMaxWidth(),
color = dividerColor,
thickness = THREE.dp
)
}
}
} | 0 | Kotlin | 0 | 2 | eb4e487f4c6681aa4b8f3e477754bc1d1921af05 | 6,925 | compose-kit | Apache License 2.0 |
shared/src/commonMain/kotlin/com/codewithfk/eventhub/scorecard/presentation/new_match_screen/NewMatchScreenState.kt | furqanullah717 | 729,414,725 | false | {"Kotlin": 68839, "Swift": 802} | package com.codewithfk.eventhub.scorecard.presentation.new_match_screen
sealed class NewMatchScreenState {
object Idle : NewMatchScreenState()
object Loading : NewMatchScreenState()
object Success : NewMatchScreenState()
data class Error(val message: String) : NewMatchScreenState()
} | 0 | Kotlin | 0 | 0 | 1d56215457510b809c3d652cba80f20e897e4e1e | 301 | kmm-offline-cricket-scorecard | MIT License |
app/src/main/java/com/example/linkedup/HomeActivity.kt | HaqqiLucky | 871,143,159 | false | {"Kotlin": 87171} | package com.example.linkedup
import android.os.Bundle
import android.util.Log
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.linkedup.item.LokerAdapter
import com.example.linkedup.item.LokerViewModel
import com.example.linkedup.utils.Loker
import com.example.linkedup.utils.LokerDatabase
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
class HomeActivity : AppCompatActivity() {
private lateinit var lokerViewModel: LokerViewModel
private lateinit var recyclerView: RecyclerView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_home)
if (savedInstanceState == null) {
val userId = intent.getIntExtra("EXTRA_USER_ID", -1) // Atur default value jika tidak ada
val userName = intent.getStringExtra("EXTRA_USER_NAME")
val userDescription = intent.getStringExtra("EXTRA_USER_DESCRIPTION")
val homeFragment = HomeFragment().apply {
arguments = Bundle().apply {
putInt("EXTRA_USER_ID", userId) // Pastikan ini sesuai dengan tipe data yang benar
putString("EXTRA_USER_NAME", userName)
putString("EXTRA_USER_DESCRIPTION", userDescription) // Pastikan ada properti description di model User
}
}
supportFragmentManager.beginTransaction()
.replace(R.id.fragment_container, homeFragment)
.commit()
}
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
insets
}
// lokerViewModel = ViewModelProvider(this).get(LokerViewModel::class.java)
//
// recyclerView = findViewById(R.id.itemloker) // Pastikan ID ini benar
// recyclerView.layoutManager = LinearLayoutManager(this)
//
// lokerViewModel.allLoker.observe(this) { lokerList ->
// lokerList?.let {
// recyclerView.adapter = LokerAdapter(it)
// }
// }
// insertDummyData()
}
// private fun insertDummyData() {
// val currentDate = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(Date())
//
// val dummyData = listOf(
// Loker(title = "Developer", gaji = 8000000, deskripsi = "Bertanggung jawab untuk pengembangan aplikasi.", instansi = "PT. A", dibuat = currentDate, status = true),
// Loker(title = "Designer", gaji = 7000000, deskripsi = "Mendesain UI/UX aplikasi.", instansi = "PT. B", dibuat = currentDate, status = true),
// Loker(title = "Product Manager", gaji = 9000000, deskripsi = "Mengelola produk dari awal hingga akhir.", instansi = "PT. C", dibuat = currentDate, status = true)
// )
//
// lifecycleScope.launch {
// try {
// dummyData.forEach { lokerViewModel.insert(it) }
// } catch (e: Exception) {
// Log.e("LokerActivity", "Error inserting dummy data", e)
// }
// }
// }
} | 0 | Kotlin | 0 | 0 | fad4a9dd41ee4978fed0529a6466b77b897f8a48 | 3,672 | LinkedUp | MIT License |
java/kotlin/src/main/kotlin/cosmos/authz/v1beta1/MsgExecKt.kt | dimitar-petrov | 575,395,653 | false | null | //Generated by the protocol buffer compiler. DO NOT EDIT!
// source: cosmos/authz/v1beta1/tx.proto
package cosmos.authz.v1beta1;
@kotlin.jvm.JvmSynthetic
inline fun msgExec(block: cosmos.authz.v1beta1.MsgExecKt.Dsl.() -> Unit): cosmos.authz.v1beta1.Tx.MsgExec =
cosmos.authz.v1beta1.MsgExecKt.Dsl._create(cosmos.authz.v1beta1.Tx.MsgExec.newBuilder()).apply { block() }._build()
object MsgExecKt {
@kotlin.OptIn(com.google.protobuf.kotlin.OnlyForUseByGeneratedProtoCode::class)
@com.google.protobuf.kotlin.ProtoDslMarker
class Dsl private constructor(
@kotlin.jvm.JvmField private val _builder: cosmos.authz.v1beta1.Tx.MsgExec.Builder
) {
companion object {
@kotlin.jvm.JvmSynthetic
@kotlin.PublishedApi
internal fun _create(builder: cosmos.authz.v1beta1.Tx.MsgExec.Builder): Dsl = Dsl(builder)
}
@kotlin.jvm.JvmSynthetic
@kotlin.PublishedApi
internal fun _build(): cosmos.authz.v1beta1.Tx.MsgExec = _builder.build()
/**
* <code>string grantee = 1;</code>
*/
var grantee: kotlin.String
@JvmName("getGrantee")
get() = _builder.getGrantee()
@JvmName("setGrantee")
set(value) {
_builder.setGrantee(value)
}
/**
* <code>string grantee = 1;</code>
*/
fun clearGrantee() {
_builder.clearGrantee()
}
/**
* An uninstantiable, behaviorless type to represent the field in
* generics.
*/
@kotlin.OptIn(com.google.protobuf.kotlin.OnlyForUseByGeneratedProtoCode::class)
class MsgsProxy private constructor() : com.google.protobuf.kotlin.DslProxy()
/**
* <pre>
* Authorization Msg requests to execute. Each msg must implement Authorization interface
* The x/authz will try to find a grant matching (msg.signers[0], grantee, MsgTypeURL(msg))
* triple and validate it.
* </pre>
*
* <code>repeated .google.protobuf.Any msgs = 2 [(.cosmos_proto.accepts_interface) = "sdk.Msg, authz.Authorization"];</code>
*/
val msgs: com.google.protobuf.kotlin.DslList<com.google.protobuf.Any, MsgsProxy>
@kotlin.jvm.JvmSynthetic
get() = com.google.protobuf.kotlin.DslList(
_builder.getMsgsList()
)
/**
* <pre>
* Authorization Msg requests to execute. Each msg must implement Authorization interface
* The x/authz will try to find a grant matching (msg.signers[0], grantee, MsgTypeURL(msg))
* triple and validate it.
* </pre>
*
* <code>repeated .google.protobuf.Any msgs = 2 [(.cosmos_proto.accepts_interface) = "sdk.Msg, authz.Authorization"];</code>
* @param value The msgs to add.
*/
@kotlin.jvm.JvmSynthetic
@kotlin.jvm.JvmName("addMsgs")
fun com.google.protobuf.kotlin.DslList<com.google.protobuf.Any, MsgsProxy>.add(value: com.google.protobuf.Any) {
_builder.addMsgs(value)
}/**
* <pre>
* Authorization Msg requests to execute. Each msg must implement Authorization interface
* The x/authz will try to find a grant matching (msg.signers[0], grantee, MsgTypeURL(msg))
* triple and validate it.
* </pre>
*
* <code>repeated .google.protobuf.Any msgs = 2 [(.cosmos_proto.accepts_interface) = "sdk.Msg, authz.Authorization"];</code>
* @param value The msgs to add.
*/
@kotlin.jvm.JvmSynthetic
@kotlin.jvm.JvmName("plusAssignMsgs")
inline operator fun com.google.protobuf.kotlin.DslList<com.google.protobuf.Any, MsgsProxy>.plusAssign(value: com.google.protobuf.Any) {
add(value)
}/**
* <pre>
* Authorization Msg requests to execute. Each msg must implement Authorization interface
* The x/authz will try to find a grant matching (msg.signers[0], grantee, MsgTypeURL(msg))
* triple and validate it.
* </pre>
*
* <code>repeated .google.protobuf.Any msgs = 2 [(.cosmos_proto.accepts_interface) = "sdk.Msg, authz.Authorization"];</code>
* @param values The msgs to add.
*/
@kotlin.jvm.JvmSynthetic
@kotlin.jvm.JvmName("addAllMsgs")
fun com.google.protobuf.kotlin.DslList<com.google.protobuf.Any, MsgsProxy>.addAll(values: kotlin.collections.Iterable<com.google.protobuf.Any>) {
_builder.addAllMsgs(values)
}/**
* <pre>
* Authorization Msg requests to execute. Each msg must implement Authorization interface
* The x/authz will try to find a grant matching (msg.signers[0], grantee, MsgTypeURL(msg))
* triple and validate it.
* </pre>
*
* <code>repeated .google.protobuf.Any msgs = 2 [(.cosmos_proto.accepts_interface) = "sdk.Msg, authz.Authorization"];</code>
* @param values The msgs to add.
*/
@kotlin.jvm.JvmSynthetic
@kotlin.jvm.JvmName("plusAssignAllMsgs")
inline operator fun com.google.protobuf.kotlin.DslList<com.google.protobuf.Any, MsgsProxy>.plusAssign(values: kotlin.collections.Iterable<com.google.protobuf.Any>) {
addAll(values)
}/**
* <pre>
* Authorization Msg requests to execute. Each msg must implement Authorization interface
* The x/authz will try to find a grant matching (msg.signers[0], grantee, MsgTypeURL(msg))
* triple and validate it.
* </pre>
*
* <code>repeated .google.protobuf.Any msgs = 2 [(.cosmos_proto.accepts_interface) = "sdk.Msg, authz.Authorization"];</code>
* @param index The index to set the value at.
* @param value The msgs to set.
*/
@kotlin.jvm.JvmSynthetic
@kotlin.jvm.JvmName("setMsgs")
operator fun com.google.protobuf.kotlin.DslList<com.google.protobuf.Any, MsgsProxy>.set(index: kotlin.Int, value: com.google.protobuf.Any) {
_builder.setMsgs(index, value)
}/**
* <pre>
* Authorization Msg requests to execute. Each msg must implement Authorization interface
* The x/authz will try to find a grant matching (msg.signers[0], grantee, MsgTypeURL(msg))
* triple and validate it.
* </pre>
*
* <code>repeated .google.protobuf.Any msgs = 2 [(.cosmos_proto.accepts_interface) = "sdk.Msg, authz.Authorization"];</code>
*/
@kotlin.jvm.JvmSynthetic
@kotlin.jvm.JvmName("clearMsgs")
fun com.google.protobuf.kotlin.DslList<com.google.protobuf.Any, MsgsProxy>.clear() {
_builder.clearMsgs()
}}
}
@kotlin.jvm.JvmSynthetic
inline fun cosmos.authz.v1beta1.Tx.MsgExec.copy(block: cosmos.authz.v1beta1.MsgExecKt.Dsl.() -> Unit): cosmos.authz.v1beta1.Tx.MsgExec =
cosmos.authz.v1beta1.MsgExecKt.Dsl._create(this.toBuilder()).apply { block() }._build()
| 0 | Kotlin | 0 | 0 | ddd9cd1abce2d51cf273be478c2b614960ace761 | 6,495 | terra.proto | Apache License 2.0 |
app/src/main/java/com/bossed/waej/ui/OrderSettleActivity.kt | Ltow | 710,230,789 | false | {"Kotlin": 2304560, "Java": 395495, "HTML": 71364} | package com.bossed.waej.ui
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.bossed.waej.R
import com.bossed.waej.adapter.AddAccountAdapter
import com.bossed.waej.base.BaseActivity
import com.bossed.waej.base.BaseResponse
import com.bossed.waej.http.UrlConstants.OrderSettleUrl
import com.bossed.waej.javebean.AccountBean
import com.bossed.waej.util.*
import com.gyf.immersionbar.ImmersionBar
import com.hjq.bar.OnTitleBarListener
import kotlinx.android.synthetic.main.activity_order_settle.*
import java.math.BigDecimal
class OrderSettleActivity : BaseActivity(), View.OnClickListener {
private lateinit var adapter: AddAccountAdapter
private val list = ArrayList<AccountBean>()
override fun getLayoutId(): Int {
return R.layout.activity_order_settle
}
override fun initView(savedInstanceState: Bundle?) {
ImmersionBar.with(this).statusBarDarkFont(true).init()
setMarginTop(tb_order_settle)
rv_order_settle.layoutManager = LinearLayoutManager(this)
list.add(AccountBean())
adapter = AddAccountAdapter(list, 1)
adapter.bindToRecyclerView(rv_order_settle)
val footView = LayoutInflater.from(this).inflate(R.layout.layout_footer_view_item, null)
footView.findViewById<TextView>(R.id.tv_add_item).setOnClickListener(this)
footView.findViewById<TextView>(R.id.tv_add_item).text = "ๆถๆฌพๆนๅผ"
adapter.setFooterView(footView)
tv_total_money.text = "๏ฟฅ${intent.getStringExtra("total")}"
tv_residue.text = "๏ฟฅ${intent.getStringExtra("moneyOwe")}"
tv_balancePay.text = "ไฝ้ขๆตๆฃ๏ผ๏ฟฅ${intent.getStringExtra("balancePay")}"
tv_moneyOwe.text = "ๅฉไฝๅบๆถ๏ผ๏ฟฅ${intent.getStringExtra("moneyOwe")}"
}
override fun initListener() {
tb_order_settle.setOnTitleBarListener(object : OnTitleBarListener {
override fun onLeftClick(view: View?) {
onBackPressed()
}
override fun onTitleClick(view: View?) {
}
override fun onRightClick(view: View?) {
}
})
et_reduction.addTextChangedListener(object : TextChangedListener {
override fun afterTextChange(s: String) {
if (s == "-")
return
tv_reduction.text =
"๏ฟฅ${
BigDecimal(if (TextUtils.isEmpty(s)) "0" else s).setScale(
2,
BigDecimal.ROUND_HALF_DOWN
)
}"
countTotal()
}
})
adapter.setOnItemChildClickListener { adapter, view, position ->
when (view.id) {
R.id.tv_name -> {
PopupWindowUtils.get().showSelAccountPop(this) {
list[position].accountType = it.methodName
list[position].accountId = it.id
list[position].accountName = it.name
adapter.setNewData(list)
}
}
R.id.iv_delete -> {
list.removeAt(position)
adapter.setNewData(list)
countTotal()
}
}
}
adapter.setOnTextChangeListener {
countTotal()
}
}
private fun countTotal() {
var priceTotal = BigDecimal(0.0)
for (bean: AccountBean in list) {
priceTotal += BigDecimal(if (TextUtils.isEmpty(bean.money)) "0" else bean.money)
}
val total = BigDecimal(intent.getStringExtra("moneyOwe")).subtract(priceTotal)
.subtract(BigDecimal(if (TextUtils.isEmpty(et_reduction.text.toString())) "0" else et_reduction.text.toString()))
.setScale(2, BigDecimal.ROUND_HALF_DOWN)
tv_collection_total.text = "๏ฟฅ${priceTotal.setScale(2, BigDecimal.ROUND_HALF_DOWN)}"
tv_residue.text = "๏ฟฅ$total"
}
override fun onClick(v: View?) {
when (v?.id) {
R.id.tv_add_item -> {
if (DoubleClicksUtils.get().isFastDoubleClick)
return
list.add(AccountBean())
adapter.setNewData(list)
}
R.id.tv_cancel -> {
if (DoubleClicksUtils.get().isFastDoubleClick)
return
finish()
}
R.id.tv_confirm -> {
if (DoubleClicksUtils.get().isFastDoubleClick)
return
if (list.isEmpty()) {
ToastUtils.showShort("่ฏทๅกซๅๆถๆฌพไฟกๆฏๅ็กฎ่ฎค็ป็ฎ")
return
}
val reduction =
if (TextUtils.isEmpty(et_reduction.text.toString())) 0.0 else et_reduction.text.toString()
.toDouble()
if (reduction > intent.getStringExtra("moneyOwe").toDouble()) {
ToastUtils.showShort("ๅๅ
้้ขไธ่ฝๅคงไบๅบๆถ้้ข")
return
}
PopupWindowUtils.get().showConfirmPop(
this, "ๆฌๅๆป้้ข${
intent.getStringExtra("moneyOwe")
}๏ผๅฎๆถ${
tv_collection_total.text.toString().substring(1)
}ๅๅ
${
tv_reduction.text.toString().substring(1)
}ๅ
๏ผๆฌๅๅฉไฝๅบๆถ${tv_residue.text.toString().substring(1)}"
) {
val params = HashMap<String, Any>()
val accountList = ArrayList<HashMap<String, Any>>()
for (acc: AccountBean in list) {
if (TextUtils.isEmpty(acc.accountName)) {
ToastUtils.showShort("่ฏท้ๆฉๆๅ ้คไธบ็ฉบ็ๆถๆฌพๆนๅผ")
return@showConfirmPop
}
if (TextUtils.isEmpty(acc.money)) {
ToastUtils.showShort("่ฏท่พๅ
ฅ ${acc.accountName} ็ๆถๆฌพ้้ข")
return@showConfirmPop
}
val map = HashMap<String, Any>()
map["accountId"] = acc.accountId!!
map["money"] = acc.money
accountList.add(map)
}
params["orderId"] = intent.getIntExtra("orderId", -1)
params["summary"] = et_remark.text.toString()
params["discount"] =
if (TextUtils.isEmpty(et_reduction.text.toString())) "0" else et_reduction.text.toString()
params["accountList"] = accountList
LoadingUtils.showLoading(this, "ๅ ่ฝฝไธญ...")
RetrofitUtils.get().postJson(
OrderSettleUrl, params, this,
object : RetrofitUtils.OnCallBackListener {
override fun onSuccess(s: String) {
LogUtils.d("tag", s)
val t = GsonUtils.fromJson(s, BaseResponse::class.java)
if (t.code == 200)
finish()
ToastUtils.showShort(t.msg)
}
override fun onFailed(e: String) {
ToastUtils.showShort(e)
}
})
}
}
}
}
} | 0 | Kotlin | 0 | 0 | 8c2e9928f6c47484bec7a5beca32ed4b10200f9c | 7,799 | wananexiu | Mulan Permissive Software License, Version 2 |
libraries/tools/kotlin-gradle-plugin/src/common/kotlin/org/jetbrains/kotlin/gradle/targets/native/internal/GetCommonizerTargetOfSourceSet.kt | JetBrains | 3,432,266 | false | null | /*
* Copyright 2010-2020 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.gradle.targets.native.internal
import org.gradle.api.Project
import org.jetbrains.kotlin.commonizer.CommonizerTarget
import org.jetbrains.kotlin.commonizer.SharedCommonizerTarget
import org.jetbrains.kotlin.commonizer.allLeaves
import org.jetbrains.kotlin.gradle.plugin.KotlinSourceSet
import org.jetbrains.kotlin.gradle.plugin.mpp.CompilationSourceSetUtil.compilationsBySourceSets
import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinMetadataCompilation
internal fun Project.getCommonizerTarget(sourceSet: KotlinSourceSet): CommonizerTarget? {
val allCompilationLeafTargets = compilationsBySourceSets(this)[sourceSet].orEmpty()
.filter { compilation -> compilation !is KotlinMetadataCompilation }
.map { compilation -> getCommonizerTarget(compilation) ?: return null }
.allLeaves()
return when {
allCompilationLeafTargets.isEmpty() -> null
allCompilationLeafTargets.size == 1 -> allCompilationLeafTargets.single()
else -> SharedCommonizerTarget(allCompilationLeafTargets)
}
}
internal fun Project.getSharedCommonizerTarget(sourceSet: KotlinSourceSet): SharedCommonizerTarget? {
return getCommonizerTarget(sourceSet) as? SharedCommonizerTarget
}
| 157 | null | 5209 | 42,102 | 65f712ab2d54e34c5b02ffa3ca8c659740277133 | 1,452 | kotlin | Apache License 2.0 |
app/src/main/java/io/aethibo/fireshare/usecases/DeletePost.kt | primepixel | 321,027,979 | false | null | /*
* Created by <NAME> on 2.2.2021
* Copyright (c) 2021 . All rights reserved.
*/
package io.aethibo.fireshare.usecases
import io.aethibo.fireshare.data.remote.main.MainRepository
import io.aethibo.fireshare.domain.Post
import io.aethibo.fireshare.framework.utils.Resource
interface DeletePostUseCase {
suspend operator fun invoke(body: Post): Resource<Post>
}
class DeletePostUseCaseImpl(private val repository: MainRepository) : DeletePostUseCase {
override suspend fun invoke(body: Post): Resource<Post> =
repository.deletePost(body)
} | 0 | Kotlin | 1 | 3 | 75d672d86095d23dfd90283800116e73a336927c | 566 | Fireshare | Apache License 2.0 |
compiler/fir/analysis-tests/testData/resolve/companionObjectCall.kt | JetBrains | 3,432,266 | false | null | // UNEXPECTED BEHAVIOUR
// Issue: KT-37056
class A()
// TESTCASE NUMBER: 1
fun case1(a: A?) {
val test = a?.let {
Case1.invoke(it) //resolved to private constructor
<!INAPPLICABLE_CANDIDATE!>Case1<!>(it) //resolved to private constructor
<!INAPPLICABLE_CANDIDATE!>Case1<!>(A()) //resolved to private constructor
}
<!INAPPLICABLE_CANDIDATE!>Case1<!>(A()) //resolved to private constructor
<!INAPPLICABLE_CANDIDATE!>Case1<!>(a = A()) //resolved to private constructor
}
class Case1 private constructor(val a: String) {
companion object {
operator fun invoke(a: A) = ""
}
}
// TESTCASE NUMBER: 2
fun case2(a: A){
<!INAPPLICABLE_CANDIDATE!>Case2<!>(a)
<!INAPPLICABLE_CANDIDATE!>Case2<!>(a = a)
}
class Case2 {
companion object {
operator fun invoke(a: A) = ""
}
}
// TESTCASE NUMBER: 3
fun case3(a: A){
Case3.Companion(a) //ok resolved to (2)
Case3.Companion(parameterA = a) //ok resolved to (2)
}
class Case3 {
companion object {
operator fun invoke(parameterA: A) = "" //(2)
}
} | 181 | null | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 1,091 | kotlin | Apache License 2.0 |
save-cosv/src/main/kotlin/com/saveourtool/save/backend/service/IBackendService.kt | saveourtool | 300,279,336 | false | {"Kotlin": 3303010, "SCSS": 43215, "JavaScript": 5532, "HTML": 5481, "Shell": 2770, "Smarty": 2608, "Dockerfile": 1366} | @file:Suppress("FILE_NAME_INCORRECT")
package com.saveourtool.save.backend.service
import com.saveourtool.save.entities.Organization
import com.saveourtool.save.entities.User
import com.saveourtool.save.entities.cosv.LnkVulnerabilityMetadataTag
import com.saveourtool.save.info.UserPermissions
import com.saveourtool.save.permission.Permission
import org.jetbrains.annotations.Blocking
import org.springframework.security.core.Authentication
import java.nio.file.Path
/**
* Interface for service to get required info for COSV from backend
*/
@Suppress("CLASS_NAME_INCORRECT")
interface IBackendService {
/**
* Working directory for backend
*/
val workingDir: Path
/**
* @param user user for update
* @return updated user
*/
fun saveUser(user: User): User
/**
* @param organization organization for update
* @return updated organization
*/
fun saveOrganization(organization: Organization): Organization
/**
* @param name name of organization
* @return found [Organization] by name
*/
fun getOrganizationByName(name: String): Organization
/**
* @param name name of organization
* @return found [User] by name
*/
fun getUserByName(name: String): User
/**
* @param authentication
* @param organizationName name of organization
* @return found [UserPermissions] by organizationName
*/
fun getUserPermissionsByOrganizationName(authentication: Authentication, organizationName: String): UserPermissions
/**
* @param authentication
* @param organizationName name of organization
* @param permission
* @return true if [authentication] has [permission] in [organizationName], otherwise -- false
*/
@Blocking
fun hasPermissionInOrganization(
authentication: Authentication,
organizationName: String,
permission: Permission,
): Boolean
/**
* @param identifier [com.saveourtool.save.entities.cosv.VulnerabilityMetadata.identifier]
* @param tagName tag to add
* @return new [LnkVulnerabilityMetadataTag]
*/
fun addVulnerabilityTags(
identifier: String,
tagName: Set<String>
): List<LnkVulnerabilityMetadataTag>?
}
| 195 | Kotlin | 2 | 36 | b516684f26005464e2da1f664e747228ca85d0d3 | 2,263 | save-cloud | MIT License |
crabzilla-core/src/test/kotlin/io/github/crabzilla/core/command/CommandSessionTest.kt | crabzilla | 91,769,036 | false | null | package io.github.crabzilla.core.command
import io.github.crabzilla.core.command.CommandException.UnknownCommandException
import io.github.crabzilla.core.test.TestSpecification
import io.github.crabzilla.example1.customer.Customer
import io.github.crabzilla.example1.customer.CustomerCommand.UnknownCommand
import io.github.crabzilla.example1.customer.CustomerEvent
import io.github.crabzilla.example1.customer.customerConfig
import io.github.crabzilla.example1.customer.customerEventHandler
import org.assertj.core.api.Assertions
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
import java.util.Arrays.asList
import java.util.UUID
@DisplayName("A CommandSession")
internal class CommandSessionTest {
lateinit var commandSession: CommandSession<Customer, CustomerEvent>
val customer = Customer(id = UUID.randomUUID(), name = "c1")
@Test
fun can_be_instantiated() {
CommandSession(customer, customerEventHandler)
}
// TODO test
// val events = tracker
// .execute { c -> c.create(cmd.targetId, cmd.name) }
// .execute { c -> c.activate(cmd.reason) }
// .collectEvents()
//
@Nested
@DisplayName("when new")
internal inner class WhenIsNew {
@BeforeEach
fun instantiate() {
commandSession = CommandSession(customer, customerEventHandler)
}
@Test
fun is_empty() {
assertThat(commandSession.appliedEvents().size).isEqualTo(0)
}
@Test
fun has_empty_state() {
assertThat(commandSession.currentState).isEqualTo(customer)
}
@Test
fun statusData_matches() {
val sessionData = commandSession.toSessionData()
assertThat(sessionData.newState).isEqualTo(customer)
assertThat(sessionData.originalState).isEqualTo(customer)
assertThat(sessionData.events).isEmpty()
}
@Nested
@DisplayName("when adding a create customer event")
internal inner class WhenAddingNewEvent {
val id = UUID.randomUUID()
private val customerCreated = CustomerEvent.CustomerRegistered(id, "customer-1")
private val expectedCustomer = Customer(id, "customer-1", false, null)
@BeforeEach
fun apply_create_event() {
commandSession.execute { customer -> listOf(customerCreated) }
}
@Test
fun has_new_state() {
assertThat(commandSession.currentState).isEqualTo(expectedCustomer)
}
@Test
fun has_only_create_event() {
assertThat(commandSession.appliedEvents()).contains(customerCreated)
assertThat(commandSession.appliedEvents().size).isEqualTo(1)
}
@Test
fun statusData_matches() {
val sessionData = commandSession.toSessionData()
assertThat(sessionData.newState).isEqualTo(expectedCustomer)
assertThat(sessionData.originalState).isEqualTo(customer)
assertThat(sessionData.events).containsOnly(customerCreated)
}
@Nested
@DisplayName("when adding an activate customer event")
internal inner class WhenAddingActivateEvent {
private val customerActivated = CustomerEvent.CustomerActivated("is ok")
private val expectedCustomer = Customer(
id, "customer-1", true,
customerActivated.reason
)
@BeforeEach
fun apply_activate_event() {
commandSession.execute { customer -> listOf(customerActivated) }
}
@Test
fun has_new_state() {
assertThat(commandSession.currentState).isEqualTo(expectedCustomer)
}
@Test
fun has_both_create_and_activated_evenst() {
assertThat(commandSession.appliedEvents()[0]).isEqualTo(customerCreated)
assertThat(commandSession.appliedEvents()[1]).isEqualTo(customerActivated)
assertThat(commandSession.appliedEvents().size).isEqualTo(2)
}
}
}
}
@Nested
@DisplayName("when adding both create and activate events")
internal inner class WhenAddingCreateActivateEvent {
val isOk = "is ok"
val id = UUID.randomUUID()
private val customerCreated = CustomerEvent.CustomerRegistered(id, "customer-1")
private val customerActivated = CustomerEvent.CustomerActivated(isOk)
private val expectedCustomer = Customer(id, "customer-1", true, isOk)
@BeforeEach
fun instantiate() {
// given
commandSession = CommandSession(customer, customerEventHandler)
// when
commandSession.execute { customer -> asList(customerCreated, customerActivated) }
}
// then
@Test
fun has_new_state() {
assertThat(commandSession.currentState).isEqualTo(expectedCustomer)
}
@Test
fun has_both_event() {
assertThat(commandSession.appliedEvents()).contains(customerCreated)
assertThat(commandSession.appliedEvents()).contains(customerActivated)
assertThat(commandSession.appliedEvents().size).isEqualTo(2)
}
}
@Test
fun `a UnknownCommand will fail`() {
Assertions.assertThatExceptionOfType(UnknownCommandException::class.java)
.isThrownBy {
TestSpecification(customerConfig)
.whenCommand(UnknownCommand("?"))
}.withMessage(UnknownCommand::class.java.canonicalName)
}
}
| 1 | Kotlin | 8 | 62 | 09cb11ffb7cc9ecb328cf47f15d79587137b1895 | 5,332 | crabzilla | Apache License 2.0 |
app/src/main/java/dev/patrickgold/florisboard/settings/SettingsMainActivity.kt | gokmendeniz | 273,973,202 | true | {"Kotlin": 194978, "HTML": 25896} | package dev.patrickgold.florisboard.settings
import android.content.Intent
import android.content.SharedPreferences
import android.net.Uri
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.ScrollView
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDelegate
import androidx.appcompat.widget.Toolbar
import androidx.fragment.app.Fragment
import androidx.preference.PreferenceFragmentCompat
import androidx.preference.PreferenceManager
import com.google.android.material.bottomnavigation.BottomNavigationView
import dev.patrickgold.florisboard.R
import dev.patrickgold.florisboard.ime.core.PrefHelper
import dev.patrickgold.florisboard.util.hideAppIcon
import dev.patrickgold.florisboard.util.showAppIcon
private const val FRAGMENT_TAG = "FRAGMENT_TAG"
private const val PREF_RES_ID = "PREF_RES_ID"
private const val SELECTED_ITEM_ID = "SELECTED_ITEM_ID"
class SettingsMainActivity : AppCompatActivity(),
BottomNavigationView.OnNavigationItemSelectedListener,
SharedPreferences.OnSharedPreferenceChangeListener {
private lateinit var navigationView: BottomNavigationView
lateinit var prefs: PrefHelper
private lateinit var scrollView: ScrollView
override fun onCreate(savedInstanceState: Bundle?) {
prefs = PrefHelper(this, PreferenceManager.getDefaultSharedPreferences(this))
prefs.initDefaultPreferences()
val mode = when (prefs.advanced.settingsTheme) {
"light" -> AppCompatDelegate.MODE_NIGHT_NO
"dark" -> AppCompatDelegate.MODE_NIGHT_YES
"auto" -> AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM
else -> AppCompatDelegate.MODE_NIGHT_UNSPECIFIED
}
AppCompatDelegate.setDefaultNightMode(mode)
super.onCreate(savedInstanceState)
setContentView(R.layout.settings_activity)
val toolbar = findViewById<Toolbar>(R.id.toolbar)
setSupportActionBar(toolbar)
navigationView = findViewById(R.id.settings__navigation)
navigationView.setOnNavigationItemSelectedListener(this)
scrollView = findViewById(R.id.settings__scroll_view)
navigationView.selectedItemId =
savedInstanceState?.getInt(SELECTED_ITEM_ID) ?: R.id.settings__navigation__home
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putInt(SELECTED_ITEM_ID, navigationView.selectedItemId)
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.settings__navigation__home -> {
supportActionBar?.title = String.format(
resources.getString(R.string.settings__home__title),
resources.getString(R.string.app_name)
)
loadFragment(HomeFragment())
true
}
R.id.settings__navigation__keyboard -> {
supportActionBar?.setTitle(R.string.settings__keyboard__title)
loadFragment(KeyboardFragment())
true
}
R.id.settings__navigation__looknfeel -> {
supportActionBar?.setTitle(R.string.settings__looknfeel__title)
loadFragment(LooknfeelFragment())
true
}
R.id.settings__navigation__gestures -> {
supportActionBar?.setTitle(R.string.settings__gestures__title)
loadFragment(GesturesFragment())
true
}
R.id.settings__navigation__advanced -> {
supportActionBar?.setTitle(R.string.settings__advanced__title)
loadFragment(AdvancedFragment())
true
}
else -> false
}
}
private fun loadFragment(fragment: Fragment) {
val transaction = supportFragmentManager.beginTransaction()
transaction.replace(R.id.settings__frame_container, fragment, FRAGMENT_TAG)
//transaction.addToBackStack(null)
transaction.commit()
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.settings_main_menu, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
android.R.id.home -> {
onBackPressed()
true
}
R.id.settings__menu_help -> {
val browserIntent = Intent(
Intent.ACTION_VIEW,
Uri.parse(resources.getString(R.string.florisboard__repo_url))
)
startActivity(browserIntent)
true
}
R.id.settings__menu_about -> {
startActivity(Intent(this, AboutActivity::class.java))
true
}
else -> super.onOptionsItemSelected(item)
}
}
override fun onSharedPreferenceChanged(sp: SharedPreferences?, key: String?) {
if (key == PrefHelper.Advanced.SETTINGS_THEME) {
recreate()
}
val fragment = supportFragmentManager.findFragmentByTag(FRAGMENT_TAG)
if (fragment != null && fragment.isVisible) {
if (fragment is LooknfeelFragment) {
if (key == PrefHelper.Theme.NAME) {
// TODO: recreate() is only a lazy solution, better would be to only recreate
// the keyboard view
recreate()
}
}
}
}
private fun updateLauncherIconStatus() {
// Set LauncherAlias enabled/disabled state just before destroying/pausing this activity
if (prefs.advanced.showAppIcon) {
showAppIcon(this)
} else {
hideAppIcon(this)
}
}
override fun onResume() {
prefs.shared.registerOnSharedPreferenceChangeListener(this)
super.onResume()
}
override fun onPause() {
prefs.shared.unregisterOnSharedPreferenceChangeListener(this)
updateLauncherIconStatus()
super.onPause()
}
override fun onDestroy() {
prefs.shared.unregisterOnSharedPreferenceChangeListener(this)
updateLauncherIconStatus()
super.onDestroy()
}
class PrefFragment : PreferenceFragmentCompat() {
companion object {
fun createFromResource(prefResId: Int): PrefFragment {
val args = Bundle()
args.putInt(PREF_RES_ID, prefResId)
val fragment = PrefFragment()
fragment.arguments = args
return fragment
}
}
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
setPreferencesFromResource(arguments?.getInt(PREF_RES_ID) ?: 0, rootKey)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
listView.isFocusable = false
listView.isNestedScrollingEnabled = false
super.onViewCreated(view, savedInstanceState)
}
}
}
| 0 | null | 0 | 0 | 4e697932983c44bb0c183328852a2cfa2af03461 | 7,225 | florisboard | Apache License 2.0 |
app/src/main/java/com/babylon/wallet/android/presentation/ui/composables/assets/PoolUnitsTab.kt | radixdlt | 513,047,280 | false | null | package com.babylon.wallet.android.presentation.ui.composables.assets
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
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.foundation.lazy.LazyListScope
import androidx.compose.foundation.lazy.items
import androidx.compose.material.Text
import androidx.compose.material3.HorizontalDivider
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.babylon.wallet.android.R
import com.babylon.wallet.android.designsystem.theme.RadixTheme
import com.babylon.wallet.android.domain.model.assets.Assets
import com.babylon.wallet.android.domain.model.assets.PoolUnit
import com.babylon.wallet.android.domain.model.resources.Resource
import com.babylon.wallet.android.presentation.account.composable.EmptyResourcesContent
import com.babylon.wallet.android.presentation.transfer.assets.AssetsTab
import com.babylon.wallet.android.presentation.ui.composables.Thumbnail
import com.babylon.wallet.android.presentation.ui.modifier.throttleClickable
import kotlinx.collections.immutable.ImmutableMap
import kotlinx.collections.immutable.toImmutableMap
import rdx.works.core.displayableQuantity
import java.math.BigDecimal
fun LazyListScope.poolUnitsTab(
assets: Assets,
action: AssetsViewAction
) {
if (assets.ownedPoolUnits.isEmpty()) {
item {
EmptyResourcesContent(
modifier = Modifier.fillMaxWidth(),
tab = AssetsTab.PoolUnits
)
}
}
if (assets.ownedPoolUnits.isNotEmpty()) {
items(
items = assets.ownedPoolUnits,
key = { item -> item.resourceAddress }
) { item ->
PoolUnitItem(
modifier = Modifier
.padding(horizontal = RadixTheme.dimensions.paddingDefault)
.padding(top = RadixTheme.dimensions.paddingSemiLarge),
poolUnit = item,
action = action
)
}
}
}
@Composable
private fun PoolUnitItem(
modifier: Modifier = Modifier,
poolUnit: PoolUnit,
action: AssetsViewAction
) {
AssetCard(
modifier = modifier
.throttleClickable {
when (action) {
is AssetsViewAction.Click -> {
action.onPoolUnitClick(poolUnit)
}
is AssetsViewAction.Selection -> {
action.onFungibleCheckChanged(poolUnit.stake, !action.isSelected(poolUnit.resourceAddress))
}
}
}
) {
Row(
modifier = Modifier.padding(RadixTheme.dimensions.paddingLarge),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(RadixTheme.dimensions.paddingMedium)
) {
Thumbnail.PoolUnit(
modifier = Modifier.size(44.dp),
poolUnit = poolUnit
)
Column(modifier = Modifier.weight(1f)) {
Text(
text = poolUnit.name(),
style = RadixTheme.typography.secondaryHeader,
color = RadixTheme.colors.gray1,
maxLines = 2
)
val associatedDAppName = remember(poolUnit) {
poolUnit.pool?.associatedDApp?.name
}
if (!associatedDAppName.isNullOrEmpty()) {
Text(
text = associatedDAppName,
style = RadixTheme.typography.body2HighImportance,
color = RadixTheme.colors.gray2,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
}
}
if (action is AssetsViewAction.Selection) {
val isSelected = remember(poolUnit.stake, action) {
action.isSelected(poolUnit.resourceAddress)
}
AssetsViewCheckBox(
isSelected = isSelected,
onCheckChanged = { isChecked ->
action.onFungibleCheckChanged(poolUnit.stake, isChecked)
}
)
}
}
Text(
modifier = Modifier.padding(horizontal = RadixTheme.dimensions.paddingLarge),
text = stringResource(id = R.string.account_staking_worth),
style = RadixTheme.typography.body2HighImportance,
color = RadixTheme.colors.gray2
)
Spacer(modifier = Modifier.height(RadixTheme.dimensions.paddingSmall))
val resourcesWithAmounts = remember(poolUnit) {
poolUnit.pool?.resources?.associateWith {
poolUnit.resourceRedemptionValue(it)
}.orEmpty().toImmutableMap()
}
PoolResourcesValues(
modifier = Modifier
.padding(horizontal = RadixTheme.dimensions.paddingLarge)
.padding(bottom = RadixTheme.dimensions.paddingLarge),
resources = resourcesWithAmounts
)
}
}
@Composable
fun PoolResourcesValues(
modifier: Modifier = Modifier,
resources: ImmutableMap<Resource.FungibleResource, BigDecimal?>,
isCompact: Boolean = true
) {
Column(modifier = modifier.assetOutlineBorder()) {
val itemsSize = resources.size
resources.entries.forEachIndexed { index, resourceWithAmount ->
Row(
modifier = Modifier.padding(
horizontal = RadixTheme.dimensions.paddingDefault,
vertical = if (isCompact) RadixTheme.dimensions.paddingMedium else RadixTheme.dimensions.paddingLarge
),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(RadixTheme.dimensions.paddingMedium)
) {
Thumbnail.Fungible(
modifier = Modifier.size(if (isCompact) 24.dp else 44.dp),
token = resourceWithAmount.key
)
Text(
modifier = Modifier.weight(1f),
text = resourceWithAmount.key.displayTitle,
style = RadixTheme.typography.body2HighImportance,
color = RadixTheme.colors.gray1,
maxLines = 2
)
Text(
text = resourceWithAmount.value?.displayableQuantity().orEmpty(),
style = if (isCompact) RadixTheme.typography.body1HighImportance else RadixTheme.typography.secondaryHeader,
color = RadixTheme.colors.gray1,
maxLines = 1
)
}
if (index != itemsSize - 1) {
HorizontalDivider(color = RadixTheme.colors.gray4)
}
}
}
}
// Pool units just display the name and have no fallback
@Composable
fun PoolUnit.name() = displayTitle
| 9 | null | 6 | 9 | 36c670dd32d181e462e9962d476cb8a370fbe4fe | 7,585 | babylon-wallet-android | Apache License 2.0 |
src/main/kotlin/com/sourcegraph/cody/config/CodyPersistentAccountsHost.kt | sourcegraph | 702,947,607 | false | null | package com.sourcegraph.cody.config
import com.intellij.openapi.project.Project
import com.sourcegraph.cody.telemetry.TelemetryV2
class CodyPersistentAccountsHost(private val project: Project) : CodyAccountsHost {
override fun addAccount(
server: SourcegraphServerPath,
login: String,
displayName: String?,
token: String,
id: String
) {
TelemetryV2.sendTelemetryEvent(project, "auth.signin.token", "clicked")
val codyAccount = CodyAccount(login, displayName, server, id)
val authManager = CodyAuthenticationManager.getInstance()
authManager.updateAccountToken(codyAccount, token)
authManager.setActiveAccount(codyAccount)
}
}
| 291 | null | 19 | 62 | 6219e45cd89922ca0abf431f9a0dd1505dbc7058 | 685 | jetbrains | Apache License 2.0 |
src/main/kotlin/com/sourcegraph/cody/config/CodyPersistentAccountsHost.kt | sourcegraph | 702,947,607 | false | null | package com.sourcegraph.cody.config
import com.intellij.openapi.project.Project
import com.sourcegraph.cody.telemetry.TelemetryV2
class CodyPersistentAccountsHost(private val project: Project) : CodyAccountsHost {
override fun addAccount(
server: SourcegraphServerPath,
login: String,
displayName: String?,
token: String,
id: String
) {
TelemetryV2.sendTelemetryEvent(project, "auth.signin.token", "clicked")
val codyAccount = CodyAccount(login, displayName, server, id)
val authManager = CodyAuthenticationManager.getInstance()
authManager.updateAccountToken(codyAccount, token)
authManager.setActiveAccount(codyAccount)
}
}
| 291 | null | 19 | 62 | 6219e45cd89922ca0abf431f9a0dd1505dbc7058 | 685 | jetbrains | Apache License 2.0 |
app/src/main/java/de/dertyp7214/rboardthememanager/preferences/Repos.kt | Ruslan-Yapparov-86RUS | 430,297,331 | true | {"Kotlin": 288153} | package de.dertyp7214.rboardthememanager.preferences
import android.app.Activity.RESULT_OK
import android.content.Intent
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.edit
import androidx.preference.PreferenceManager
import androidx.recyclerview.widget.RecyclerView
import de.Maxr1998.modernpreferences.PreferenceScreen
import de.Maxr1998.modernpreferences.PreferencesAdapter
import de.Maxr1998.modernpreferences.helpers.checkBox
import de.Maxr1998.modernpreferences.helpers.onClick
import de.dertyp7214.rboardthememanager.Config
import de.dertyp7214.rboardthememanager.R
import de.dertyp7214.rboardthememanager.core.*
import de.dertyp7214.rboardthememanager.screens.ManageRepo
import de.dertyp7214.rboardthememanager.utils.doAsync
import org.json.JSONArray
import java.net.URL
class Repos(
private val activity: AppCompatActivity,
private val args: SafeJSON,
private val onRequestReload: () -> Unit
) :
AbstractMenuPreference() {
private val sharedPreferences by lazy { PreferenceManager.getDefaultSharedPreferences(activity) }
private val repositories = hashMapOf<String, Boolean>()
private val resultLauncher: ActivityResultLauncher<Intent>
private var modified = false
init {
val repos = sharedPreferences.getStringSet("repos", Config.REPOS.toSet())
repos?.let { repositories.putAll(it.toList().toMap()) }
resultLauncher =
activity.registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
if (it.resultCode == RESULT_OK) {
it.data?.getStringExtra("key")?.also { key ->
when (it.data?.getStringExtra("action")) {
"delete" -> {
modified = true
repositories.remove(key)
onRequestReload()
}
"disable" -> {
modified = true
repositories[key] = false
onRequestReload()
}
"enable" -> {
modified = true
repositories[key] = true
onRequestReload()
}
"share" -> {
TODO("Add share logic for repo")
}
}
}
}
}
}
override fun preferences(builder: PreferenceScreen.Builder) {
val prefs = PreferenceManager.getDefaultSharedPreferences(activity)
repositories.forEach { (key, value) ->
prefs.edit { remove(key) }
builder.checkBox(key) {
val pref = this
title = key.replace("https://raw.githubusercontent.com/", "...")
defaultValue = value
onClick {
pref.checked = value
ManageRepo::class.java.start(activity, resultLauncher) {
putExtra("key", key)
putExtra("enabled", value)
}
false
}
}
}
}
override fun loadMenu(menuInflater: MenuInflater, menu: Menu?) {
if (menu != null) menuInflater.inflate(R.menu.repos, menu)
}
override fun onMenuClick(menuItem: MenuItem): Boolean {
return when (menuItem.itemId) {
R.id.add -> {
activity.openInputDialog(R.string.repository) { dialog, text ->
doAsync({
try {
JSONArray(URL(text).getTextFromUrl())
true
} catch (e: Exception) {
false
}
}) {
dialog.dismiss()
if (it) {
repositories[text] = true
onRequestReload()
modified = true
} else activity.openDialog(
R.string.invalid_repo_long,
R.string.invalid_repo,
false,
::dismiss,
::dismiss
)
}
}
true
}
R.id.apply -> {
apply()
modified = false
true
}
else -> false
}
}
override fun getExtraView(): View? = null
override fun onStart(recyclerView: RecyclerView, adapter: PreferencesAdapter) {
adapter.currentScreen.indexOf(args.getString("highlight"))
.let { if (it >= 0) recyclerView.scrollToPosition(it) }
}
private fun apply() {
sharedPreferences.edit {
putStringSet("repos", repositories.toSet())
}
Config.REPOS.apply {
clear()
addAll(repositories.toSet())
}
}
override fun onBackPressed(callback: () -> Unit) {
if (modified) {
activity.openDialog(R.string.save_repos, R.string.apply, false, {
callback()
}) {
apply()
callback()
}
} else callback()
}
} | 0 | null | 0 | 0 | beda76c0e052831a54959d0d6db553824baa2eed | 5,796 | RboardThemeManagerV3 | MIT License |
src/main/kotlin/com/refinedmods/refinedstorage/util/WorldUtils.kt | thinkslynk | 290,596,653 | true | {"Kotlin": 695976, "Shell": 456} | package com.refinedmods.refinedstorage.util
import com.mojang.authlib.GameProfile
import com.refinedmods.refinedstorage.render.Styles
import net.minecraft.entity.player.PlayerEntity
import net.minecraft.server.network.ServerPlayerEntity
import net.minecraft.server.network.ServerPlayerInteractionManager
import net.minecraft.server.world.ServerWorld
import net.minecraft.text.TranslatableText
import net.minecraft.util.hit.BlockHitResult
import net.minecraft.util.math.BlockPos
import net.minecraft.world.World
import java.util.*
object WorldUtils {
fun updateBlock(world: World, pos: BlockPos) {
if (world.canSetBlock(pos)) {
val state = world.getBlockState(pos)
world.updateListeners(pos, state, state, 0b11)
}
}
// TODO Item capability
// fun getItemHandler(tile: BlockEntity, side: Direction): IItemHandler {
//
// var handler: IItemHandler? = tile.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, side).orElse(null)
// if (handler == null) {
// if (side != null && tile is ISidedInventory) {
// handler = SidedInvWrapper(tile as ISidedInventory?, side)
// } else if (tile is IInventory) {
// handler = InvWrapper(tile as IInventory?)
// }
// }
// return handler
// }
// TODO Fluid
// fun getFluidHandler(tile: BlockEntity?, side: Direction?): IFluidHandler? {
// return if (tile != null) {
// tile.getCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, side).orElse(null)
// } else null
// }
fun getFakePlayer(world: ServerWorld, owner: UUID?): ServerPlayerEntity {
if (owner != null) {
return world.server.playerManager.getPlayer(owner)!!
}
val fakeProfile = GameProfile(null, "cured_storage")
return ServerPlayerEntity(world.server, world, fakeProfile, ServerPlayerInteractionManager(world))
}
fun sendNoPermissionMessage(player: PlayerEntity) {
player.sendMessage(
TranslatableText("misc.refinedstorage.security.no_permission")
.setStyle(Styles.RED), true
)
}
fun rayTracePlayer(world: World, player: PlayerEntity): BlockHitResult? {
return null // TODO Rethink this a bit
// val reachDistance: Double = player.getAttribute(ForgeMod.REACH_DISTANCE.get()).getValue()
// val base: Vector3d = player.getEyePosition(1.0f)
// val look: Vector3d = player.getLookVec()
// val target: Vector3d = base.add(look.x * reachDistance, look.y * reachDistance, look.z * reachDistance)
// return world.rayTraceBlocks(RayTraceContext(base, target, RayTraceContext.BlockMode.OUTLINE, RayTraceContext.FluidMode.NONE, player))
}
} | 1 | Kotlin | 0 | 2 | c92afa51af0e5e08caded00882f91171652a89e3 | 2,787 | refinedstorage | MIT License |
src/main/kotlin/dev/syoritohatsuki/yacg/integration/jade/GeneratorComponentProvider.kt | syorito-hatsuki | 589,090,428 | false | {"Kotlin": 38722} | package dev.syoritohatsuki.yacg.integration.jade
import dev.syoritohatsuki.yacg.YetAnotherCobblestoneGenerator.MOD_ID
import dev.syoritohatsuki.yacg.common.block.entity.GeneratorBlockEntity
import dev.syoritohatsuki.yacg.common.item.UpgradeItem
import dev.syoritohatsuki.yacg.registry.ItemsRegistry
import net.minecraft.item.ItemStack
import net.minecraft.nbt.NbtCompound
import net.minecraft.util.Identifier
import snownee.jade.api.BlockAccessor
import snownee.jade.api.IBlockComponentProvider
import snownee.jade.api.IServerDataProvider
import snownee.jade.api.ITooltip
import snownee.jade.api.config.IPluginConfig
object GeneratorComponentProvider : IBlockComponentProvider, IServerDataProvider<BlockAccessor> {
override fun getUid(): Identifier = Identifier(MOD_ID, "generators")
override fun appendServerData(data: NbtCompound, accessor: BlockAccessor) {
data.putBoolean("coefficient", false)
data.putBoolean("count", false)
data.putBoolean("speed", false)
(accessor.blockEntity as GeneratorBlockEntity).listUpgrades.forEach {
when (it) {
UpgradeItem.UpgradesTypes.COEFFICIENT -> data.putBoolean("coefficient", true)
UpgradeItem.UpgradesTypes.COUNT -> data.putBoolean("count", true)
UpgradeItem.UpgradesTypes.SPEED -> data.putBoolean("speed", true)
}
}
}
override fun appendTooltip(tooltip: ITooltip, accessor: BlockAccessor, config: IPluginConfig) {
val elements = tooltip.elementHelper
if (accessor.serverData.getBoolean("coefficient")) tooltip.append(
elements.item(
ItemStack(ItemsRegistry.COEFFICIENT_UPGRADE),
0.5f
)
)
if (accessor.serverData.getBoolean("count")) tooltip.append(
elements.item(
ItemStack(ItemsRegistry.COUNT_UPGRADE),
0.5f
)
)
if (accessor.serverData.getBoolean("speed")) tooltip.append(
elements.item(
ItemStack(ItemsRegistry.SPEED_UPGRADE),
0.5f
)
)
}
} | 2 | Kotlin | 4 | 2 | 4b86f78a01e6b12237ef7b818575468c4297dfe9 | 2,145 | yet-another-cobble-gen | MIT License |
subprojects/samples-tests/src/test/kotlin/org/gradle/kotlin/dsl/samples/samples.kt | jnizet | 146,316,824 | true | {"Kotlin": 1080014, "Java": 5870, "Shell": 549} | package org.gradle.kotlin.dsl.samples
import org.gradle.kotlin.dsl.fixtures.loadPropertiesFrom
import org.gradle.kotlin.dsl.fixtures.mergePropertiesInto
import org.gradle.kotlin.dsl.fixtures.rootProjectDir
import org.junit.Assume
import java.io.File
internal
val samplesRootDir = File(rootProjectDir, "samples")
internal
fun copySampleProject(from: File, to: File) {
withMergedGradleProperties(to.resolve("gradle.properties")) {
from.copyRecursively(to)
listOf(".gradle", "build").map { File(to, it) }.filter { it.exists() }.forEach {
it.deleteRecursively()
}
}
}
private
fun withMergedGradleProperties(gradlePropertiesFile: File, action: () -> Unit) {
loadThenDeletePropertiesFrom(gradlePropertiesFile).let { baseProperties ->
action()
mergePropertiesInto(gradlePropertiesFile, baseProperties.map { it.toPair() })
}
}
private
fun loadThenDeletePropertiesFrom(file: File) =
loadPropertiesFrom(file).also { file.delete() }
internal
fun assumeAndroidHomeIsSet() =
Assume.assumeTrue(System.getenv().containsKey("ANDROID_HOME"))
| 0 | Kotlin | 0 | 1 | 75ad0e760f9c6fe2d3f0728f60837a0b22184566 | 1,114 | kotlin-dsl | Apache License 2.0 |
compose/foundation/foundation/integration-tests/foundation-demos/src/main/java/androidx/compose/foundation/demos/text2/ReceiveContentDemos.kt | androidx | 256,589,781 | false | null | /*
* Copyright 2023 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.foundation.demos.text2
import android.content.ClipDescription
import android.content.Context
import android.graphics.ImageDecoder
import android.net.Uri
import android.os.Build
import android.provider.MediaStore
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.content.MediaType
import androidx.compose.foundation.content.ReceiveContentListener
import androidx.compose.foundation.content.TransferableContent
import androidx.compose.foundation.content.consume
import androidx.compose.foundation.content.contentReceiver
import androidx.compose.foundation.content.hasMediaType
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
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.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.input.TextFieldState
import androidx.compose.foundation.text.input.rememberTextFieldState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Card
import androidx.compose.material.Divider
import androidx.compose.material.Icon
import androidx.compose.material.LocalTextStyle
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Clear
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun TextFieldReceiveContentDemo() {
var dragging by remember { mutableStateOf(false) }
var hovering by remember { mutableStateOf(false) }
val context = LocalContext.current
val scope = rememberCoroutineScope()
var images: List<ImageBitmap> by remember { mutableStateOf(emptyList()) }
val receiveContentListener = remember {
object : ReceiveContentListener {
override fun onDragStart() {
dragging = true
}
override fun onDragEnd() {
dragging = false
hovering = false
}
override fun onDragEnter() {
hovering = true
}
override fun onDragExit() {
hovering = false
}
override fun onReceive(
transferableContent: TransferableContent
): TransferableContent? {
val newImageUris = mutableListOf<Uri>()
return transferableContent
.consume { item ->
// this happens in the ui thread, try not to load images here.
val isImageBitmap = item.uri?.isImageBitmap(context) ?: false
if (isImageBitmap) {
newImageUris += item.uri
}
isImageBitmap
}
.also {
// delegate image loading to IO dispatcher.
scope.launch(Dispatchers.IO) {
images = newImageUris.mapNotNull { it.readImageBitmap(context) }
}
}
}
}
}
Column(
modifier = Modifier
.fillMaxSize()
.contentReceiver(
hintMediaTypes = setOf(MediaType.Image),
receiveContentListener = receiveContentListener
)
.padding(16.dp)
.background(
color = when {
hovering -> MaterialTheme.colors.primary
dragging -> MaterialTheme.colors.primary.copy(alpha = 0.7f)
else -> MaterialTheme.colors.background
},
shape = RoundedCornerShape(8.dp)
),
verticalArrangement = Arrangement.Bottom
) {
Column(Modifier.weight(1f), verticalArrangement = Arrangement.Center) {
Text(
if (dragging) "Drop it anywhere" else "Chat messages should appear here...",
modifier = Modifier.fillMaxWidth(),
textAlign = TextAlign.Center
)
}
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
images.forEach { imageBitmap ->
Box(Modifier.size(80.dp)) {
Image(
bitmap = imageBitmap,
contentDescription = "",
contentScale = ContentScale.Crop,
modifier = Modifier
.fillMaxSize()
.padding(4.dp)
.clip(RoundedCornerShape(4.dp))
)
Icon(
Icons.Default.Clear,
"remove image",
modifier = Modifier
.size(16.dp)
.align(Alignment.TopEnd)
.background(MaterialTheme.colors.background, CircleShape)
.clip(CircleShape)
.clickable {
images = images.filterNot { it == imageBitmap }
}
)
}
}
}
BasicTextField(
state = rememberTextFieldState(),
modifier = demoTextFieldModifiers,
textStyle = LocalTextStyle.current
)
}
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun NestedReceiveContentDemo() {
val state = remember { TextFieldState() }
val context = LocalContext.current
Column {
var descriptionToggle by remember { mutableStateOf(false) }
Text(
if (descriptionToggle) Description else "Click to see the description...",
Modifier
.padding(8.dp)
.clickable { descriptionToggle = !descriptionToggle }
)
Spacer(Modifier.height(8.dp))
ReceiveContentShowcase(
"Everything Consumer",
MediaType.All, {
// consume everything here
null
},
modifier = Modifier.verticalScroll(rememberScrollState())
) {
val coroutineScope = rememberCoroutineScope()
var images by remember { mutableStateOf<List<ImageBitmap>>(emptyList()) }
ReceiveContentShowcase(
title = "Image Consumer",
hintMediaType = MediaType.Image,
onReceive = { transferableContent ->
if (!transferableContent.hasMediaType(MediaType.Image)) {
transferableContent
} else {
var uri: Uri? = null
transferableContent.consume { item ->
// only consume this item if we can read
if (item.uri != null && uri == null) {
uri = item.uri
true
} else {
false
}
}.also {
coroutineScope.launch(Dispatchers.IO) {
uri?.readImageBitmap(context)?.let { images = listOf(it) }
}
}
}
},
onClear = { images = emptyList() }
) {
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
images.forEach {
Image(it, contentDescription = null, Modifier.size(100.dp))
}
}
ReceiveContentShowcase(
"Text Consumer",
MediaType.Text, {
it.consume { item ->
val text = item.coerceToText(context)
// only consume if it has text in it.
!text.isNullOrBlank() && item.uri == null
}
}
) {
BasicTextField(
state = state,
modifier = demoTextFieldModifiers,
textStyle = LocalTextStyle.current
)
}
}
}
}
}
/**
* Wraps the given [content] composable with a content receiver that shows all the received content.
*/
@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun ReceiveContentShowcase(
title: String,
hintMediaType: MediaType,
onReceive: (TransferableContent) -> TransferableContent?,
modifier: Modifier = Modifier,
onClear: () -> Unit = {},
content: @Composable () -> Unit
) {
val transferableContentState = remember { mutableStateOf<TransferableContent?>(null) }
val receiveContentState = remember {
ReceiveContentState(setOf(hintMediaType)) {
transferableContentState.value = it
onReceive(it)
}
}
Column(
modifier
.dropReceiveContent(receiveContentState)
.padding(8.dp)
) {
Card(
Modifier
.fillMaxWidth()
.clickable {
transferableContentState.value = null
onClear()
},
elevation = 4.dp,
backgroundColor = if (receiveContentState.hovering) {
MaterialTheme.colors.secondary
} else {
MaterialTheme.colors.surface
}
) {
Column(
modifier = Modifier.padding(8.dp),
verticalArrangement = Arrangement.spacedBy(4.dp)
) {
val transferableContent = transferableContentState.value
if (transferableContent == null) {
Text(
"$title - Hasn't received anything yet!",
style = MaterialTheme.typography.h6
)
} else {
Text("$title - Summary", style = MaterialTheme.typography.h6)
KeyValueEntry(
"Item count",
"${transferableContent.clipEntry.clipData.itemCount}"
)
KeyValueEntry("Source", "${transferableContent.source}")
KeyValueEntry(
"linkUri",
"${transferableContent.platformTransferableContent?.linkUri}"
)
Text("Items", style = MaterialTheme.typography.h6)
for (i in 0 until transferableContent.clipEntry.clipData.itemCount) {
val item = transferableContent.clipEntry.clipData.getItemAt(i)
if (item.uri != null) KeyValueEntry("Uri", "${item.uri}")
if (item.text != null) KeyValueEntry("Text", "${item.text}")
if (item.intent != null) KeyValueEntry("Intent", "${item.intent}")
Divider(Modifier.fillMaxWidth())
}
}
}
}
Spacer(Modifier.height(8.dp))
content()
}
}
@Composable
private fun KeyValueEntry(
key: String,
value: String
) {
Row {
Text(key, fontWeight = FontWeight.Bold)
Spacer(modifier = Modifier.width(8.dp))
Text(value)
}
}
@Suppress("ClassVerificationFailure", "DEPRECATION")
private fun Uri.readImageBitmap(context: Context): ImageBitmap? {
return try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
ImageDecoder.decodeBitmap(ImageDecoder.createSource(context.contentResolver, this))
} else {
MediaStore.Images.Media.getBitmap(context.contentResolver, this)
}.asImageBitmap()
} catch (e: Exception) {
null
}
}
private fun Uri.isImageBitmap(context: Context): Boolean {
val type = context.contentResolver.getType(this)
if (ClipDescription.compareMimeTypes(type, "image/*")) return true
return !context.contentResolver.getStreamTypes(this, "image/*").isNullOrEmpty()
}
@OptIn(ExperimentalFoundationApi::class)
class ReceiveContentState(
var hintMediaTypes: Set<MediaType>,
private val onReceive: (TransferableContent) -> TransferableContent?
) {
internal var hovering by mutableStateOf(false)
internal var dragging by mutableStateOf(false)
internal val listener = object : ReceiveContentListener {
override fun onDragEnter() {
hovering = true
}
override fun onDragEnd() {
hovering = false
dragging = false
}
override fun onDragStart() {
dragging = true
}
override fun onDragExit() {
hovering = false
}
override fun onReceive(transferableContent: TransferableContent): TransferableContent? {
dragging = false
hovering = false
return [email protected](transferableContent)
}
}
}
@OptIn(ExperimentalFoundationApi::class)
fun Modifier.dropReceiveContent(
state: ReceiveContentState
) = composed {
contentReceiver(state.hintMediaTypes, state.listener)
.background(
color = if (state.hovering) {
MaterialTheme.colors.secondary
} else if (state.dragging) {
MaterialTheme.colors.primary
} else {
MaterialTheme.colors.surface
},
shape = RoundedCornerShape(8.dp)
)
}
private const val Description = "Below setup works as follows;\n" +
" - There are 3 nested receiveContent nodes.\n" +
" - The outermost one consumes everything that's passed to it.\n" +
" - The middle one only consumes image content.\n" +
" - The innermost one only consumes text content.\n" +
" - BasicTextField that's nested the deepest would delegate whatever it receives " +
"to all 3 parents in order of proximity.\n" +
" - Each node shows all the items it receives, not just what it consumes.\n\n" +
"ReceiveContent works with keyboard, paste, and drag/drop.\n" +
"Click on any card to clear its internal state.\n" +
"Click on this description to hide it."
| 29 | null | 937 | 5,321 | 98b929d303f34d569e9fd8a529f022d398d1024b | 16,574 | androidx | Apache License 2.0 |
app/src/main/java/com/guoyi/listeninglove/ui/download/ui/TaskItemAdapter.kt | GuoyiZhang | 242,757,044 | false | null | package com.cat.music.ui.download.ui
import android.content.Context
import androidx.recyclerview.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ProgressBar
import android.widget.TextView
import com.cat.music.MusicApp
import com.cat.music.MusicApp.mContext
import com.cat.music.R
import com.cat.music.ui.download.TasksManager
import com.cat.music.ui.download.TasksManagerModel
import com.cat.music.utils.LogUtil
import com.liulishuo.filedownloader.BaseDownloadTask
import com.liulishuo.filedownloader.FileDownloader
import com.liulishuo.filedownloader.model.FileDownloadStatus
import com.liulishuo.filedownloader.util.FileDownloadUtils
import java.io.File
/**
* Created by yonglong on 2018/1/23.
*/
class TaskItemAdapter(private val mContext: Context, var models: List<TasksManagerModel>?) : RecyclerView.Adapter<TaskItemAdapter.TaskItemViewHolder>() {
private val taskActionOnClickListener = View.OnClickListener { v ->
if (v.tag == null) {
return@OnClickListener
}
val holder = v.tag as TaskItemViewHolder
when ((v as TextView).text) {
v.getResources().getString(R.string.pause) -> // to pause
FileDownloader.getImpl().pause(holder.id)
v.getResources().getString(R.string.start) -> {
// to start
val model = TasksManager[holder.adapterPosition]
val task = FileDownloader.getImpl().create(model.url)
.setPath(model.path)
.setCallbackProgressTimes(100)
.setListener(taskDownloadListener)
TasksManager.addTaskForViewHolder(task)
holder.id = task.id
TasksManager.updateViewHolder(holder.id, holder)
task.start()
}
v.getResources().getString(R.string.delete) -> {
// to delete
File(TasksManager[holder.adapterPosition].path).delete()
holder.taskActionBtn.isEnabled = true
holder.updateNotDownloaded(FileDownloadStatus.INVALID_STATUS.toInt(), 0, 0)
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TaskItemViewHolder {
val view = LayoutInflater.from(mContext).inflate(R.layout.item_download_music, parent, false)
return TaskItemViewHolder(view)
}
override fun onBindViewHolder(holder: TaskItemViewHolder, position: Int) {
val model = models!![position]
holder.taskActionBtn.setOnClickListener(taskActionOnClickListener)
holder.update(model.tid, holder.adapterPosition)
holder.taskActionBtn.tag = holder
holder.taskNameTv.text = model.name
TasksManager.updateViewHolder(holder.id, holder)
holder.taskActionBtn.isEnabled = true
if (FileDownloader.getImpl().isServiceConnected) {
val status = TasksManager.getStatus(model.tid, model.path!!)
if (status == FileDownloadStatus.pending.toInt() || status == FileDownloadStatus.started.toInt() ||
status == FileDownloadStatus.connected.toInt()) {
// start task, but file not created yet
holder.updateDownloading(status, TasksManager.getSoFar(model.tid), TasksManager.getTotal(model.tid))
} else if (!File(model.path).exists() && !File(FileDownloadUtils.getTempPath(model.path)).exists()) {
// not exist file
holder.updateNotDownloaded(status, 0, 0)
} else if (TasksManager.isDownloaded(status)) {
// already downloaded and exist
LogUtil.e(TAG, "already downloaded and exist")
holder.updateDownloaded()
} else if (status == FileDownloadStatus.progress.toInt()) {
// downloading
holder.updateDownloading(status, TasksManager.getSoFar(model.tid), TasksManager.getTotal(model.tid))
} else {
// not start
holder.updateNotDownloaded(status, TasksManager.getSoFar(model.tid), TasksManager.getTotal(model.tid))
}
} else {
holder.taskStatusTv.setText(R.string.tasks_manager_demo_status_loading)
holder.taskActionBtn.isEnabled = false
}
}
override fun getItemCount(): Int {
return models!!.size
}
inner class TaskItemViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var taskNameTv = itemView.findViewById<TextView>(R.id.task_name_tv)
var taskStatusTv = itemView.findViewById<TextView>(R.id.task_status_tv)
var taskPb = itemView.findViewById<ProgressBar>(R.id.task_pb)
var taskActionBtn = itemView.findViewById<Button>(R.id.task_action_btn)
/**
* viewHolder position
*/
var position1 = 0
/**
* download id
*/
var id: Int = 0
// internal var taskNameTv: TextView
// internal var taskStatusTv: TextView
// internal var taskPb: ProgressBar
// internal var taskActionBtn: Button
fun update(id: Int, position: Int) {
this.id = id
this.position1 = position
}
fun updateDownloaded() {
taskPb.max = 1
taskPb.progress = 1
taskStatusTv.setText(R.string.tasks_manager_demo_status_completed)
taskActionBtn.setText(R.string.delete)
taskActionBtn.visibility = View.GONE
taskPb.visibility = View.GONE
TasksManager.finishTask(id)
}
fun updateNotDownloaded(status: Int, sofar: Long, total: Long) {
if (sofar > 0 && total > 0) {
val percent = sofar / total.toFloat()
taskPb.max = 100
taskPb.progress = (percent * 100).toInt()
} else {
taskPb.max = 1
taskPb.progress = 0
}
when (status.toByte()) {
FileDownloadStatus.error -> taskStatusTv.setText(R.string.tasks_manager_demo_status_error)
FileDownloadStatus.paused -> taskStatusTv.setText(R.string.tasks_manager_demo_status_paused)
else -> taskStatusTv.setText(R.string.tasks_manager_demo_status_not_downloaded)
}
taskActionBtn.setText(R.string.start)
}
fun updateDownloading(status: Int, sofar: Long, total: Long) {
val percent = sofar / total.toFloat()
taskPb.max = 100
taskPb.progress = (percent * 100).toInt()
when (status.toByte()) {
FileDownloadStatus.pending -> taskStatusTv.setText(R.string.tasks_manager_demo_status_pending)
FileDownloadStatus.started -> taskStatusTv.setText(R.string.tasks_manager_demo_status_started)
FileDownloadStatus.connected -> taskStatusTv.setText(R.string.tasks_manager_demo_status_connected)
// FileDownloadStatus.progress -> taskStatusTv.setText(R.string.tasks_manager_demo_status_progress)
else -> taskStatusTv.text = MusicApp.mContext.getString(
R.string.tasks_manager_demo_status_downloading, (percent * 100).toInt())
}
taskActionBtn.setText(R.string.pause)
}
}
companion object {
private val TAG = "TaskItemAdapter"
val taskDownloadListener = FileDownloadListener()
}
}
| 4 | null | 503 | 5 | 6d9442bad15910fe6d813bdf556fe1562d950947 | 7,571 | 077-Android-ListeningLove | Apache License 2.0 |
src/main/java/com/anyascii/build/Emojis.kt | zhilangtaosha | 322,543,717 | true | {"JSON": 4, "Shell": 6, "Maven POM": 2, "YAML": 3, "Text": 11, "Ignore List": 1, "Git Attributes": 1, "Batchfile": 2, "Markdown": 3, "Go": 4, "Go Module": 1, "INI": 2, "Java": 4, "Perl": 99, "X PixMap": 159, "Raku": 19, "Microsoft Visual Studio Solution": 1, "XML": 2, "C#": 3, "Kotlin": 22, "PHP": 547, "JavaScript": 548, "Ruby": 548, "Python": 549, "TOML": 1, "Rust": 3} | package com.anyascii.build
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import java.io.File
private val EMOJI_BLACKLIST = "ยฉยฎโผโโขโใใ๐๐๐๐ฏ๐ฒ๐ณ๐ด๐ต๐ถ๐ท๐ธ๐น๐บ๐๐".codePointsArray().asList()
fun emojis() = jacksonObjectMapper()
.readTree(File("input/discord-emojis.json"))
.flatten()
.filter { it["surrogates"].asText().codePointsArray().dropLastWhile { it == 0xfe0f }.size == 1 }
.associateTo(Table()) { it["surrogates"].asText().codePointAt(0) to it["names"].first().asText().let { ":$it:" } }
.minus(EMOJI_BLACKLIST) | 0 | null | 0 | 0 | d5ea332081cefe3868602959982a427e74e487b9 | 564 | anyascii | ISC License |
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/quicksight/DashboardVersionDefinitionPropertyDsl.kt | F43nd1r | 643,016,506 | false | null | package com.faendir.awscdkkt.generated.services.quicksight
import com.faendir.awscdkkt.AwsCdkDsl
import javax.`annotation`.Generated
import kotlin.Unit
import software.amazon.awscdk.services.quicksight.CfnDashboard
@Generated
public fun buildDashboardVersionDefinitionProperty(initializer: @AwsCdkDsl
CfnDashboard.DashboardVersionDefinitionProperty.Builder.() -> Unit):
CfnDashboard.DashboardVersionDefinitionProperty =
CfnDashboard.DashboardVersionDefinitionProperty.Builder().apply(initializer).build()
| 1 | Kotlin | 0 | 0 | e08d201715c6bd4914fdc443682badc2ccc74bea | 519 | aws-cdk-kt | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.