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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
identity-starter/src/main/kotlin/com/labijie/application/identity/service/IUserService.kt | hongque-pro | 309,874,586 | false | null | package com.labijie.application.identity.service
import com.labijie.application.identity.data.RoleRecord as Role
import com.labijie.application.identity.data.UserRecord as User
import com.labijie.application.identity.model.RegisterInfo
import com.labijie.application.identity.model.UserAndRoles
import com.labijie.application.model.OrderBy
/**
* Created with IntelliJ IDEA.
* @author <NAME>
* @date 2019-09-06
*/
interface IUserService {
fun getUserById(userId: Long): User?
fun getUser(usr: String): User?
fun getUserRoles(userId: Long): List<Role>
fun resetPassword(userId: Long, password: String): Boolean
fun addRoleToUser(roleId: Long, userId: Long): Boolean
fun removeRoleFromUser(roleId: Long, userId: Long): Boolean
fun changePassword(userId: Long, oldPassword: String, newPassword: String): Boolean
fun changePhone(userId: Long, phoneNumber: String, confirmed: Boolean = true): Boolean
fun setUserEnabled(userId: Long, enabled: Boolean): Boolean
fun getUsers(pageSize: Int, lastUserId: Long? = null, order: OrderBy = OrderBy.Descending): List<User>
fun getOrCreateRole(roleName: String): Role
fun createUser(user: User, vararg roles: String): UserAndRoles
fun registerUser(register: RegisterInfo): UserAndRoles
fun updateUser(userId: Long, user: User): Boolean
fun getDefaultUserType(): Byte {
return 0
}
fun getDefaultUserRoles(): Array<String>
} | 0 | Kotlin | 0 | 5 | c8be28b6fb0813c673de5e82c6d9bd0f3e6bb953 | 1,440 | application-framework | Apache License 2.0 |
ui/src/main/java/org/redaksi/ui/cari/CariViewModel.kt | 100nandoo | 475,824,222 | false | {"Kotlin": 108530, "Java": 34584} | package org.redaksi.ui.cari
import androidx.compose.ui.text.input.TextFieldValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import androidx.paging.cachedIn
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import org.redaksi.data.remote.PillarApi
import org.redaksi.ui.ScreenState
import org.redaksi.ui.cari.paging.CariSource
import org.redaksi.ui.utama.ArticleUi
import javax.inject.Inject
@HiltViewModel
class CariViewModel @Inject constructor(private val pillarApi: PillarApi) : ViewModel() {
private val viewModelState = MutableStateFlow(CariViewModelState())
val uiState = viewModelState
fun onEvent(cariEvent: CariEvent) {
when (cariEvent) {
is CariEvent.LoadSearchArticle -> loadSearchArticle(cariEvent.keyword)
is CariEvent.UpdateTextFieldValue -> updateTextFieldValue(cariEvent.textFieldValue)
}
}
private fun loadSearchArticle(keyword: String) {
viewModelScope.launch {
val cariPager = Pager(PagingConfig(pageSize = 10)) {
CariSource(pillarApi, keyword)
}.flow.cachedIn(viewModelScope)
viewModelState.update { it.copy(articlesUi = cariPager, screenState = ScreenState.CONTENT) }
}
}
private fun updateTextFieldValue(textFieldValue: TextFieldValue) {
viewModelState.update { it.copy(textFieldValue = textFieldValue) }
}
}
data class CariViewModelState(
val articlesUi: Flow<PagingData<ArticleUi>> = flowOf(),
val textFieldValue: TextFieldValue = TextFieldValue(),
val screenState: ScreenState = ScreenState.BLANK
)
sealed class CariEvent {
data class LoadSearchArticle(val keyword: String) : CariEvent()
data class UpdateTextFieldValue(val textFieldValue: TextFieldValue) : CariEvent()
}
| 0 | Kotlin | 0 | 2 | f13a8147622264c50ab86274ab5a227e05bd7308 | 2,099 | Pillar | MIT License |
src/main/kotlin/wzq/codelf/plugin/action/SearchAction.kt | Zhiqiang-Wu | 721,409,431 | false | {"Kotlin": 31403} | package wzq.codelf.plugin.action
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.wm.ToolWindowManager
/**
* @author 吴志强
* @date 2023/11/25
*/
class SearchAction : AnAction() {
override fun actionPerformed(e: AnActionEvent) {
val project = e.project ?: return
val toolWindow = ToolWindowManager.getInstance(project).getToolWindow("Codelf")
toolWindow?.show()
// TODO 打开 toolWindow 后直接根据选中值搜索
}
} | 0 | Kotlin | 0 | 1 | 2d81cdbbc5ff4e14b18e7e1d72d64f8439cb665a | 525 | idea-codelf-plugin | MIT License |
app/src/main/java/com/example/sunnyweather/ui/place/PlaceViewModel.kt | AkiraKanade | 384,362,014 | false | null | package com.example.sunnyweather.ui.place
class PlaceViewModel {
} | 0 | Kotlin | 0 | 0 | 87cc08ae733b6d9fe3f3f184f226cd0a43de11ed | 67 | SunnyWeather | Apache License 2.0 |
src/main/kotlin/br/com/zup/orangetalents/compartilhado/ErrorHandler.kt | rsousaj | 383,873,611 | true | {"Kotlin": 56336} | package br.com.zup.orangetalents.compartilhado
import io.micronaut.aop.Around
import io.micronaut.aop.InterceptorBean
import kotlin.annotation.AnnotationRetention.*
import kotlin.annotation.AnnotationTarget.*
@Around
@MustBeDocumented
@Target(FUNCTION)
@Retention(RUNTIME)
annotation class ErrorHandler()
| 0 | Kotlin | 0 | 0 | c35d3cb1565c432048b44d10da7bf66bcc712617 | 307 | orange-talents-05-template-pix-keymanager-grpc | Apache License 2.0 |
services/unit-service/src/main/kotlin/org/katan/service/unit/repository/UnitEntity.kt | KatanPanel | 182,468,654 | false | null | package org.katan.service.unit.repository
import kotlinx.datetime.Instant
public interface UnitEntity {
public var nodeId: Int
public var externalId: String?
public var name: String
public var createdAt: Instant
public var updatedAt: Instant
public var deletedAt: Instant?
public var instanceId: Long?
public var status: String
public fun getId(): Long
}
| 5 | Kotlin | 5 | 55 | 2c4d99e277e372e78a14486748de3c3624a45cdb | 402 | Katan | Apache License 2.0 |
src/main/kotlin/sqlbuilder/pool/Drivers.kt | laurentvdl | 27,872,125 | false | null | package sqlbuilder.pool
interface Drivers {
companion object {
const val MYSQL = "com.mysql.jdbc.Driver"
const val H2 = "org.h2.Driver"
const val DB2 = "com.ibm.db2.jcc.DB2Driver"
const val ORACLE = "oracle.jdbc.OracleDriver"
}
}
| 1 | null | 2 | 6 | 4efe1dd61f6da45192a1b2741d654269616535d0 | 271 | sqlbuilder | Apache License 2.0 |
app/src/main/java/ch/abertschi/adfree/view/mod/ActiveDetectorActivity.kt | abertschi | 88,356,929 | false | null | package ch.abertschi.adfree.view.mod
import android.opengl.Visibility
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.text.Html
import android.widget.TextView
import android.view.LayoutInflater
import ch.abertschi.adfree.R
import org.jetbrains.anko.*
import android.support.v7.widget.RecyclerView
import android.view.ViewGroup
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.SwitchCompat
import android.view.View
import android.widget.ScrollView
import ch.abertschi.adfree.detector.AdDetectable
import java.lang.IllegalStateException
class ActiveDetectorActivity : AppCompatActivity(), AnkoLogger {
private lateinit var detectorRecyclerView: RecyclerView
private lateinit var detectorViewAdapter: RecyclerView.Adapter<*>
private lateinit var detectorViewManager: RecyclerView.LayoutManager
private lateinit var presenter: ActiveDetectorPresenter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.mod_active_detectors)
val textView = findViewById<TextView>(R.id.detectors_activity_title)
presenter = ActiveDetectorPresenter(this)
val category: String = intent.extras.getString(CategoriesPresenter.BUNDLE_CATEGORY_KEY)
?: throw IllegalStateException("must set category")
val text =
"fine-tune detectors for <font color=#FFFFFF>$category</font>."
textView.text = Html.fromHtml(text)
findViewById<ScrollView>(R.id.mod_active_scroll).scrollTo(0, 0)
detectorViewManager = LinearLayoutManager(this)
detectorViewAdapter = DetectorAdapter(presenter.getDetectors(category), presenter)
detectorRecyclerView = findViewById<RecyclerView>(R.id.detector_recycle_view).apply {
layoutManager = detectorViewManager
adapter = detectorViewAdapter
}
}
fun showInfo(info: String) {
longToast(info)
}
}
class DetectorAdapter(
private val detectors: List<AdDetectable>,
private val presenter: ActiveDetectorPresenter
) :
RecyclerView.Adapter<DetectorAdapter.MyViewHolder>(), AnkoLogger {
class MyViewHolder(
val view: View,
val title: TextView,
val subtitle: TextView,
val switch: SwitchCompat,
val sepView: View
) : RecyclerView.ViewHolder(view)
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): MyViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.mod_active_detectors_view_element, parent, false)
val title = view.findViewById(R.id.det_title) as TextView
val subtitle = view.findViewById(R.id.det_subtitle) as TextView
val switch = view.findViewById<TextView>(R.id.det_switch) as SwitchCompat
val sep = view.findViewById<View>(R.id.mod_det_seperation)
return MyViewHolder(view, title, subtitle, switch, sep)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
holder.title.text = "> " + detectors[position].getMeta().title
holder.subtitle.text = detectors[position].getMeta().description
holder.switch.isChecked = presenter.isEnabled(detectors[position])
holder.title.onClick {
holder.switch.toggle()
}
holder.subtitle.onClick {
holder.switch.toggle()
}
holder.view.onClick {
holder.switch.toggle()
}
holder.switch.setOnCheckedChangeListener { _, isChecked ->
presenter.onDetectorToggled(isChecked, detectors[position])
info(detectors[position].javaClass.canonicalName)
}
holder.sepView.visibility =
if (position == detectors.size - 1) View.INVISIBLE else View.VISIBLE
}
override fun getItemCount() = detectors.size
}
| 22 | null | 23 | 243 | b916a9ab8a09bb5ac9bfb9e7d1cc10d7bd8dc411 | 3,943 | ad-free | Apache License 2.0 |
buildSrc/src/main/kotlin/generator/DomainGenerator.kt | iseki0 | 366,910,553 | true | {"Kotlin": 97960} | package org.hildan.chrome.devtools.build.generator
import com.squareup.kotlinpoet.*
import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy
import org.hildan.chrome.devtools.build.model.ChromeDPCommand
import org.hildan.chrome.devtools.build.model.ChromeDPDomain
import org.hildan.chrome.devtools.build.model.ChromeDPEvent
import org.hildan.chrome.devtools.build.model.asClassName
import kotlinx.serialization.DeserializationStrategy
private const val INPUT_ARG = "input"
private const val SESSION_ARG = "session"
private const val DESERIALIZERS_PROP = "deserializersByEventName"
private val deserializerClassName = DeserializationStrategy::class.asClassName()
private val serializerFun = MemberName("kotlinx.serialization", "serializer")
private val coroutineFlowClass = ClassName("kotlinx.coroutines.flow", "Flow")
private fun mapOfDeserializers(eventsSealedClassName: ClassName): ParameterizedTypeName {
val deserializerClass = deserializerClassName.parameterizedBy(WildcardTypeName.producerOf(eventsSealedClassName))
return MAP.parameterizedBy(String::class.asTypeName(), deserializerClass)
}
fun ChromeDPCommand.createInputTypeSpec(): TypeSpec =
TypeSpec.classBuilder(inputTypeName ?: error("trying to build input type for no-arg command")).apply {
addKdoc("Request object containing input parameters for the [%T.%N] command.", domainName.asClassName(), name)
addAnnotation(Annotations.serializable)
if (deprecated) {
addAnnotation(Annotations.deprecatedChromeApi)
}
if (experimental) {
addAnnotation(Annotations.experimentalChromeApi)
}
addModifiers(KModifier.DATA)
addPrimaryConstructorProps(parameters)
}.build()
fun ChromeDPCommand.createOutputTypeSpec(): TypeSpec =
TypeSpec.classBuilder(outputTypeName).apply {
addKdoc("Response type for the [%T.%N] command.", domainName.asClassName(), name)
addAnnotation(Annotations.serializable)
if (deprecated) {
addAnnotation(Annotations.deprecatedChromeApi)
}
if (experimental) {
addAnnotation(Annotations.experimentalChromeApi)
}
addModifiers(KModifier.DATA)
addPrimaryConstructorProps(returns)
}.build()
fun ChromeDPDomain.createDomainClass(): TypeSpec = TypeSpec.classBuilder(name.asClassName()).apply {
description?.let { addKdoc(it.escapeKDoc()) }
addKdoc(linkToDocSentence(docUrl))
if (deprecated) {
addAnnotation(Annotations.deprecatedChromeApi)
}
if (experimental) {
addAnnotation(Annotations.experimentalChromeApi)
}
primaryConstructor(FunSpec.constructorBuilder()
.addModifiers(KModifier.INTERNAL)
.addParameter(SESSION_ARG, ExtClasses.chromeDPSession)
.build())
addProperty(PropertySpec.builder(SESSION_ARG, ExtClasses.chromeDPSession)
.addModifiers(KModifier.PRIVATE)
.initializer(SESSION_ARG)
.build())
if (events.isNotEmpty()) {
addAllEventsFunction(this@createDomainClass)
events.forEach { event ->
addFunction(event.toSubscribeFunctionSpec())
}
}
commands.forEach { cmd ->
addFunction(cmd.toFunctionSpec())
}
}.build()
private fun ChromeDPCommand.toFunctionSpec(): FunSpec = FunSpec.builder(name).apply {
description?.let { addKdoc(it.escapeKDoc()) }
addKdoc(linkToDocSentence(docUrl))
if (deprecated) {
addAnnotation(Annotations.deprecatedChromeApi)
}
if (experimental) {
addAnnotation(Annotations.experimentalChromeApi)
}
addModifiers(KModifier.SUSPEND)
val inputArg = if (inputTypeName != null) {
addParameter(INPUT_ARG, inputTypeName)
INPUT_ARG
} else {
"Unit"
}
returns(outputTypeName)
addStatement("return %N.request(%S, %L)", SESSION_ARG, "$domainName.$name", inputArg)
}.build()
private fun ChromeDPEvent.toSubscribeFunctionSpec(): FunSpec =
FunSpec.builder(name).apply {
description?.let { addKdoc(it.escapeKDoc()) }
addKdoc(linkToDocSentence(docUrl))
if (deprecated) {
addAnnotation(Annotations.deprecatedChromeApi)
}
if (experimental) {
addAnnotation(Annotations.experimentalChromeApi)
}
returns(coroutineFlowClass.parameterizedBy(eventTypeName))
addStatement("return %N.events(%S)", SESSION_ARG, "$domainName.$name")
}.build()
private fun TypeSpec.Builder.addAllEventsFunction(domain: ChromeDPDomain) {
addProperty(PropertySpec.builder(DESERIALIZERS_PROP, mapOfDeserializers(domain.eventsParentClassName))
.addKdoc("Mapping between events and their deserializer.")
.addModifiers(KModifier.PRIVATE)
.initializer(domain.deserializersMapCodeBlock())
.build())
addFunction(FunSpec.builder("events")
.addKdoc("Subscribes to all events related to this domain.")
.returns(coroutineFlowClass.parameterizedBy(domain.eventsParentClassName))
.addCode("return %N.events(%N)", SESSION_ARG, DESERIALIZERS_PROP)
.build())
}
private fun ChromeDPDomain.deserializersMapCodeBlock(): CodeBlock = CodeBlock.builder().apply {
add("mapOf(\n")
events.forEach { e ->
add("%S to %M<%T>(),\n", "${e.domainName}.${e.name}", serializerFun, e.eventTypeName)
}
add(")")
}.build()
| 0 | null | 0 | 0 | 4b553ad4d92b08d879fc146f8d43569a04c037a6 | 5,399 | chrome-devtools-kotlin | MIT License |
compiler/tests-spec/testData/diagnostics/notLinked/dfa/pos/14.kt | JetBrains | 3,432,266 | false | null | // DIAGNOSTICS: -UNUSED_EXPRESSION
// SKIP_TXT
/*
* KOTLIN DIAGNOSTICS NOT LINKED SPEC TEST (POSITIVE)
*
* SECTIONS: dfa
* NUMBER: 14
* DESCRIPTION: Raw data flow analysis test
*/
// TESTCASE NUMBER: 1
fun case_1(vararg x: Int?) {
if (<!SENSELESS_COMPARISON!>x != null<!>) {
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Array<out kotlin.Int?>")!>x<!>
x[0]
}
}
// TESTCASE NUMBER: 2
fun case_2(vararg x: Int?) {
x[0].apply {
if (this != null) {
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int? & kotlin.Int")!>this<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int? & kotlin.Int")!>this<!>.inv()
}
}
x[0].also {
if (it != null) {
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int? & kotlin.Int")!>it<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int? & kotlin.Int")!>it<!>.inv()
}
}
}
// TESTCASE NUMBER: 3
fun <T> case_3(vararg x: T?) {
if (<!SENSELESS_COMPARISON!>x != null<!>) {
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Array<out T?>")!>x<!>
x[0]
}
}
// TESTCASE NUMBER: 4
fun <T : Number?> case_4(vararg x: T?) {
x[0].apply {
if (this != null) {
<!DEBUG_INFO_EXPRESSION_TYPE("T? & T?!!")!>this<!>
<!DEBUG_INFO_EXPRESSION_TYPE("T? & T?!!")!>this<!>.toByte()
}
}
x[0].also {
if (it != null) {
<!DEBUG_INFO_EXPRESSION_TYPE("T? & T?!!")!>it<!>
<!DEBUG_INFO_EXPRESSION_TYPE("T? & T?!!")!>it<!>.toByte()
}
}
}
| 181 | null | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 1,520 | kotlin | Apache License 2.0 |
src/test/kotlin/com/theapache64/stackzy/data/repo/AdbRepoTest.kt | theapache64 | 336,369,141 | false | null | package com.theapache64.stackzy.data.repo
import com.malinskiy.adam.request.pkg.Package
import com.theapache64.expekt.should
import com.theapache64.stackzy.data.local.AndroidApp
import com.theapache64.stackzy.test.FLUTTER_PACKAGE_NAME
import com.theapache64.stackzy.test.MyDaggerMockRule
import com.theapache64.stackzy.test.NATIVE_KOTLIN_PACKAGE_NAME
import com.theapache64.stackzy.test.runBlockingUnitTest
import it.cosenonjaviste.daggermock.InjectFromComponent
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.first
import org.junit.Rule
import org.junit.Test
import org.junit.jupiter.api.BeforeAll
class AdbRepoTest {
@get:Rule
val daggerMockRule = MyDaggerMockRule()
@InjectFromComponent
private lateinit var adbRepo: AdbRepo
@BeforeAll
@Test
fun beforeAll() = runBlockingUnitTest {
val devices = adbRepo.watchConnectedDevice().first()
assert(devices.isNotEmpty()) {
"No device found. Please connect a device to run this test"
}
}
@Test
fun `Device list works`() = runBlockingUnitTest {
val connectedDevices = adbRepo.watchConnectedDevice().first()
if (connectedDevices.isEmpty()) {
assert(false) {
"Are you sure you've at least one device connected"
}
} else {
// not empty. one or more devices are connected
assert(true)
}
}
@Test
fun `App list works`() = runBlockingUnitTest {
val connectedDevices = adbRepo.watchConnectedDevice().first()
val installedApps = adbRepo.getInstalledApps(connectedDevices.first().device)
if (installedApps.isEmpty()) {
assert(false) {
"Are you sure you've at least one device connected"
}
} else {
//verify both system apps and 3rd apps are available
val (systemApps, thirdPartyApps) = installedApps.partition { it.isSystemApp }
systemApps.size.should.above(0)
thirdPartyApps.size.should.above(0)
// not empty. one or more devices are connected
assert(true)
}
}
@Test
fun `Fetch path works - native android`() = runBlockingUnitTest {
val device = adbRepo.watchConnectedDevice().first().first()
val apkPath = adbRepo.getApkPath(
device,
AndroidApp(
Package(NATIVE_KOTLIN_PACKAGE_NAME),
isSystemApp = false,
)
)
apkPath.should.startWith("/data/app/")
}
@Test
fun `Fetch path works - flutter`() = runBlockingUnitTest {
val device = adbRepo.watchConnectedDevice().first().first()
val apkPath = adbRepo.getApkPath(
device,
AndroidApp(
Package(FLUTTER_PACKAGE_NAME),
isSystemApp = false,
)
)
apkPath.should.startWith("/data/app/")
}
@Test
fun `Fetch path fails for invalid package`() = runBlockingUnitTest {
val device = adbRepo.watchConnectedDevice().first().first()
val app = "dffgfgdf"
val apkPath = adbRepo.getApkPath(
device,
AndroidApp(
Package(app),
isSystemApp = false,
)
)
apkPath.should.`null`
}
@Test
fun `Download ADB works`() = runBlockingUnitTest {
var lastProgress = 0
adbRepo.downloadAdb()
.distinctUntilChanged()
.collect {
lastProgress = it
}
lastProgress.should.equal(100)
}
} | 24 | null | 54 | 962 | 4c7919f1c8f4b72e0dda3d41ffe6d3eda18e6896 | 3,683 | stackzy | Apache License 2.0 |
domain/src/main/kotlin/com/yossisegev/domain/entities/VideoEntity.kt | mrsegev | 122,669,273 | false | null | package com.yossisegev.domain.entities
/**
* Created by <NAME> on 11/01/2018.
*/
data class VideoEntity(
var id: String,
var name: String,
var youtubeKey: String? = null) {
companion object {
const val SOURCE_YOUTUBE = "YouTube"
const val TYPE_TRAILER = "Trailer"
}
} | 7 | Kotlin | 147 | 772 | 7df52e6c93d6932b4b58de9f4f906f86df93dce1 | 319 | MovieNight | Apache License 2.0 |
feature-staking-impl/src/main/java/jp/co/soramitsu/staking/impl/presentation/validators/ValidatorsAdapter.kt | soramitsu | 278,060,397 | false | {"Kotlin": 5738291, "Java": 18796} | package jp.co.soramitsu.staking.impl.presentation.validators
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import jp.co.soramitsu.common.list.PayloadGenerator
import jp.co.soramitsu.common.list.resolvePayload
import jp.co.soramitsu.common.utils.inflateChild
import jp.co.soramitsu.common.utils.makeGone
import jp.co.soramitsu.common.utils.makeVisible
import jp.co.soramitsu.common.utils.setVisible
import jp.co.soramitsu.feature_staking_impl.R
import jp.co.soramitsu.staking.impl.presentation.validators.change.ValidatorModel
class ValidatorsAdapter(
private val itemHandler: ItemHandler,
initialMode: Mode = Mode.VIEW
) : ListAdapter<ValidatorModel, ValidatorViewHolder>(ValidatorDiffCallback) {
private var mode = initialMode
interface ItemHandler {
fun validatorInfoClicked(validatorModel: ValidatorModel)
fun validatorClicked(validatorModel: ValidatorModel) {
// default empty
}
fun removeClicked(validatorModel: ValidatorModel) {
// default empty
}
}
enum class Mode {
VIEW, EDIT
}
fun modeChanged(newMode: Mode) {
mode = newMode
notifyItemRangeChanged(0, itemCount, mode)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ValidatorViewHolder {
val view = parent.inflateChild(R.layout.item_validator)
return ValidatorViewHolder(view)
}
override fun onBindViewHolder(holder: ValidatorViewHolder, position: Int) {
val item = getItem(position)
holder.bind(item, itemHandler, mode)
}
override fun onBindViewHolder(holder: ValidatorViewHolder, position: Int, payloads: MutableList<Any>) {
val item = getItem(position)
resolvePayload(
holder,
position,
payloads,
onUnknownPayload = { holder.bindIcon(mode, item, itemHandler) },
onDiffCheck = {
when (it) {
ValidatorModel::isChecked -> holder.bindIcon(mode, item, itemHandler)
ValidatorModel::scoring -> holder.bindScoring(item)
}
}
)
}
}
class ValidatorViewHolder(private val containerView: View) : RecyclerView.ViewHolder(containerView) {
fun bind(
validator: ValidatorModel,
itemHandler: ValidatorsAdapter.ItemHandler,
mode: ValidatorsAdapter.Mode
) = with(containerView) {
findViewById<TextView>(R.id.itemValidatorName).text = validator.title
findViewById<ImageView>(R.id.itemValidatorIcon).setImageDrawable(validator.image)
findViewById<ImageView>(R.id.itemValidatorInfo).setOnClickListener {
itemHandler.validatorInfoClicked(validator)
}
setOnClickListener {
itemHandler.validatorClicked(validator)
}
bindIcon(mode, validator, itemHandler)
bindScoring(validator)
}
fun bindIcon(
mode: ValidatorsAdapter.Mode,
validatorModel: ValidatorModel,
handler: ValidatorsAdapter.ItemHandler
) = with(containerView) {
val icon = findViewById<ImageView>(R.id.itemValidatorActionIcon)
when {
mode == ValidatorsAdapter.Mode.EDIT -> {
icon.setImageResource(R.drawable.ic_delete_symbol)
icon.makeVisible()
icon.setOnClickListener { handler.removeClicked(validatorModel) }
}
validatorModel.isChecked == null -> {
icon.makeGone()
}
else -> {
icon.setOnClickListener(null)
icon.setImageResource(R.drawable.ic_checkmark_white_24)
icon.setVisible(validatorModel.isChecked, falseState = View.INVISIBLE)
}
}
}
fun bindScoring(validatorModel: ValidatorModel) = with(containerView) {
val scoringPrimary = findViewById<TextView>(R.id.itemValidatorScoringPrimary)
val scoringSecondary = findViewById<TextView>(R.id.itemValidatorScoringSecondary)
when (val scoring = validatorModel.scoring) {
null -> {
scoringPrimary.makeGone()
scoringSecondary.makeGone()
}
is ValidatorModel.Scoring.OneField -> {
scoringPrimary.makeVisible()
scoringSecondary.makeGone()
scoringPrimary.text = scoring.field
}
is ValidatorModel.Scoring.TwoFields -> {
scoringPrimary.makeVisible()
scoringSecondary.makeVisible()
scoringPrimary.text = scoring.primary
scoringSecondary.text = scoring.secondary
}
}
}
}
object ValidatorDiffCallback : DiffUtil.ItemCallback<ValidatorModel>() {
override fun areItemsTheSame(oldItem: ValidatorModel, newItem: ValidatorModel): Boolean {
return oldItem.address == newItem.address
}
override fun areContentsTheSame(oldItem: ValidatorModel, newItem: ValidatorModel): Boolean {
return oldItem.scoring == newItem.scoring && oldItem.title == newItem.title && oldItem.isChecked == newItem.isChecked
}
override fun getChangePayload(oldItem: ValidatorModel, newItem: ValidatorModel): Any? {
return ValidatorPayloadGenerator.diff(oldItem, newItem)
}
}
private object ValidatorPayloadGenerator : PayloadGenerator<ValidatorModel>(
ValidatorModel::isChecked,
ValidatorModel::scoring
)
| 15 | Kotlin | 30 | 89 | 812c6ed5465d19a0616865cbba3e946d046720a1 | 5,702 | fearless-Android | Apache License 2.0 |
solarsystem/src/main/kotlin/fail/stderr/usb/data/system/KeplerianOrbitalParametersData.kt | stderr-fail | 824,200,675 | false | {"Kotlin": 106132, "GDScript": 21392, "Java": 8583, "Shell": 446} | package fail.stderr.usb.data.system
@JvmRecord
data class KeplerianOrbitalParametersData(
/** semi-major axis in **meters** */
@JvmField
val semiMajorAxis: Double,
/** eccentricity in **dimensionless** */
@JvmField
val eccentricity: Double,
/** inclination in **radians** */
@JvmField
val inclination: Double,
/**
* * ω
* * perigee argument
* * argument of periapsis
*
* in **radians**
*/
@JvmField
val perigreeArgument: Double,
/**
* * Ω
* * right ascension of ascending node
* * raan
* * longitude of the ascending node
* * lan
*
* in **radians**
*/
@JvmField
val raan: Double,
/**
* * mean
* * mean anomaly at epoch
* * eccentric or true anomaly
*
* in **radians**
*/
@JvmField
val anomaly: Double
)
| 0 | Kotlin | 0 | 1 | 85b76f09c86bcd3c95730ea37a51e84a8c7a7ffd | 817 | untitled-space-bureau | MIT License |
app/src/main/java/com/example/startertemplet/domain/service/ApiService.kt | atharva-pardeshi | 720,217,566 | false | {"Kotlin": 24965, "Java": 181} | package com.example.startertemplet.domain.service
import com.example.startertemplet.viewModel.response.DataResponse
import retrofit2.http.GET
import retrofit2.http.Query
interface ApiService {
@GET("services/custom-software-development.html")
suspend fun getTermsOfUse(): DataResponse
}
| 0 | Kotlin | 2 | 0 | b2c4380d9855118c7079ea4390648283df97ddd4 | 298 | StarterTemplate | MIT License |
app/src/main/java/android/example/com/udacityfirstproject/ui/shoeDetails/ShoeDetailsFragment.kt | MinaWadeeBibawey | 577,851,084 | false | null | package android.example.com.udacityfirstproject.ui.shoeDetails
import android.example.com.udacityfirstproject.databinding.ShoeDetailsFragmentBinding
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
class ShoeDetailsFragment : Fragment() {
lateinit var binding: ShoeDetailsFragmentBinding
private val viewModel: SharedViewModel by activityViewModels()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = ShoeDetailsFragmentBinding.inflate(layoutInflater)
binding.sharedViewModel = viewModel
binding.lifecycleOwner = this
binding.showDetailsModel = viewModel.detailsModel
viewModel.savedButtonClicked.observe(viewLifecycleOwner) { savedButtonClicked ->
if (savedButtonClicked) {
viewModel.resetSavedButtons()
findNavController().popBackStack()
}
}
viewModel.cancelButtonClicked.observe(viewLifecycleOwner) { cancelButtonClicked ->
if (cancelButtonClicked) {
viewModel.resetSavedButtons()
findNavController().popBackStack()
}
}
return binding.root
}
} | 0 | Kotlin | 0 | 0 | 7750d4cacf8aa04b655dd1f91827ee255c35713b | 1,494 | UdacityFirstProject | MIT License |
src/main/kotlin/org/jetbrains/plugins/bsp/flow/open/BspProjectOpenProcessor.kt | JetBrains | 521,228,542 | false | null | package org.jetbrains.plugins.bsp.flow.open
import com.intellij.ide.impl.OpenProjectTask
import com.intellij.ide.impl.ProjectUtilCore
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ex.ProjectManagerEx
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.projectImport.ProjectOpenProcessor
import com.intellij.projectImport.ProjectOpenedCallback
import org.jetbrains.magicmetamodel.ProjectDetails
import org.jetbrains.plugins.bsp.config.BspPluginBundle
import org.jetbrains.plugins.bsp.config.BspPluginIcons
import org.jetbrains.plugins.bsp.config.isBspProject
import org.jetbrains.plugins.bsp.config.rootDir
import org.jetbrains.plugins.bsp.extension.points.BspConnectionDetailsGeneratorExtension
import org.jetbrains.plugins.bsp.protocol.connection.BspConnectionDetailsGeneratorProvider
import org.jetbrains.plugins.bsp.protocol.connection.BspConnectionFilesProvider
import org.jetbrains.plugins.bsp.services.BspCoroutineService
import org.jetbrains.plugins.bsp.services.MagicMetaModelService
import java.nio.file.Path
import javax.swing.Icon
public class BspProjectOpenProcessor : ProjectOpenProcessor() {
override val name: String = BspPluginBundle.message("plugin.name")
override val icon: Icon = BspPluginIcons.bsp
override fun canOpenProject(file: VirtualFile): Boolean {
val bspConnectionFilesProvider = BspConnectionFilesProvider(file)
val bspConnectionDetailsGeneratorProvider =
BspConnectionDetailsGeneratorProvider(file, BspConnectionDetailsGeneratorExtension.extensions())
return bspConnectionFilesProvider.isAnyBspConnectionFileDefined() or
bspConnectionDetailsGeneratorProvider.canGenerateAnyBspConnectionDetailsFile()
}
override fun doOpenProject(
virtualFile: VirtualFile,
projectToClose: Project?,
forceOpenInNewFrame: Boolean
): Project? {
val projectPath = virtualFile.toNioPath()
val openProjectTask = calculateOpenProjectTask(projectPath, forceOpenInNewFrame, projectToClose, virtualFile)
return ProjectManagerEx.getInstanceEx().openProject(projectPath, openProjectTask)
}
public fun calculateOpenProjectTask(
projectPath: Path,
forceOpenInNewFrame: Boolean,
projectToClose: Project?,
virtualFile: VirtualFile
): OpenProjectTask = OpenProjectTask {
runConfigurators = true
isNewProject = !ProjectUtilCore.isValidProjectPath(projectPath)
isRefreshVfsNeeded = !ApplicationManager.getApplication().isUnitTestMode
this.forceOpenInNewFrame = forceOpenInNewFrame
this.projectToClose = projectToClose
beforeOpen = { it.initProperties(virtualFile); true }
callback = ProjectOpenedCallback { project, _ -> project.initializeEmptyMagicMetaModel() }
}
}
public fun Project.initializeEmptyMagicMetaModel() {
val magicMetaModelService = MagicMetaModelService.getInstance(this)
magicMetaModelService.initializeMagicModel(
ProjectDetails(
targetsId = emptyList(),
targets = emptySet(),
sources = emptyList(),
resources = emptyList(),
dependenciesSources = emptyList(),
javacOptions = emptyList(),
pythonOptions = emptyList(),
outputPathUris = emptyList(),
libraries = emptyList(),
)
)
BspCoroutineService.getInstance(this).start {
magicMetaModelService.value.loadDefaultTargets().applyOnWorkspaceModel()
}
}
public fun Project.initProperties(projectRootDir: VirtualFile) {
this.isBspProject = true
this.rootDir = projectRootDir
}
| 0 | Kotlin | 2 | 8 | df2456dedf66c11578b491460abf95bce87c051c | 3,545 | intellij-bsp | Apache License 2.0 |
app/src/test/java/com/guzzardi/profileslist/view/views/profileslist/ProfileViewHolderTest.kt | gonzaloguzzardi | 448,302,624 | false | {"Kotlin": 35401} | package com.guzzardi.profileslist.view.views.profileslist
import android.view.View
import android.widget.FrameLayout
import com.guzzardi.profileslist.RobolectricTest
import com.guzzardi.profileslist.model.UserProfile
import org.junit.Assert
import org.junit.Test
class ProfileViewHolderTest : RobolectricTest() {
@Test
fun `bind correctly displays definition text value`() {
val viewHolder = createViewHolder()
viewHolder.bind(UserProfile(GIVEN_NAME, FAMILY_NAME, "", null))
Assert.assertEquals(View.VISIBLE, viewHolder.fullName.visibility)
Assert.assertEquals("$GIVEN_NAME $FAMILY_NAME", viewHolder.fullName.text)
}
private fun createViewHolder() =
ProfileViewHolder.create(FrameLayout(context)) as ProfileViewHolder
private companion object {
const val GIVEN_NAME = "Test"
const val FAMILY_NAME = "McTesting"
}
} | 0 | Kotlin | 0 | 0 | b7ff24f441248c2c316774bf6c0e51c83d02266c | 902 | profiles-list | MIT License |
app/src/main/java/openfoodfacts/github/scrachx/openfood/features/productlist/ProductListActivity.kt | openfoodfacts | 35,174,991 | false | null | package openfoodfacts.github.scrachx.openfood.features.productlist
import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.viewModels
import androidx.annotation.RequiresApi
import androidx.core.app.ActivityCompat.shouldShowRequestPermissionRationale
import androidx.core.content.ContextCompat.checkSelfPermission
import androidx.core.net.toUri
import androidx.lifecycle.flowWithLifecycle
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.squareup.picasso.Picasso
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import logcat.LogPriority
import logcat.logcat
import openfoodfacts.github.scrachx.openfood.AppFlavor
import openfoodfacts.github.scrachx.openfood.AppFlavor.Companion.isFlavors
import openfoodfacts.github.scrachx.openfood.BuildConfig
import openfoodfacts.github.scrachx.openfood.R
import openfoodfacts.github.scrachx.openfood.analytics.AnalyticsEvent
import openfoodfacts.github.scrachx.openfood.analytics.MatomoAnalytics
import openfoodfacts.github.scrachx.openfood.databinding.ActivityYourListedProductsBinding
import openfoodfacts.github.scrachx.openfood.features.product.view.ProductViewActivityStarter
import openfoodfacts.github.scrachx.openfood.features.shared.BaseActivity
import openfoodfacts.github.scrachx.openfood.listeners.CommonBottomListenerInstaller.installBottomNavigation
import openfoodfacts.github.scrachx.openfood.listeners.CommonBottomListenerInstaller.selectNavigationItem
import openfoodfacts.github.scrachx.openfood.models.Barcode
import openfoodfacts.github.scrachx.openfood.models.entities.ProductLists
import openfoodfacts.github.scrachx.openfood.utils.Intent
import openfoodfacts.github.scrachx.openfood.utils.SortType.BARCODE
import openfoodfacts.github.scrachx.openfood.utils.SortType.BRAND
import openfoodfacts.github.scrachx.openfood.utils.SortType.GRADE
import openfoodfacts.github.scrachx.openfood.utils.SortType.TIME
import openfoodfacts.github.scrachx.openfood.utils.SortType.TITLE
import openfoodfacts.github.scrachx.openfood.utils.SwipeController
import openfoodfacts.github.scrachx.openfood.utils.getCsvFolderName
import openfoodfacts.github.scrachx.openfood.utils.isHardwareCameraInstalled
import openfoodfacts.github.scrachx.openfood.utils.writeListToFile
import java.io.File
import java.text.SimpleDateFormat
import java.util.*
import javax.inject.Inject
@AndroidEntryPoint
class ProductListActivity : BaseActivity() {
private var _binding: ActivityYourListedProductsBinding? = null
private val binding get() = _binding!!
private val viewModel: ProductListViewModel by viewModels()
@Inject
lateinit var matomoAnalytics: MatomoAnalytics
@Inject
lateinit var picasso: Picasso
@Inject
lateinit var productViewActivityStarter: ProductViewActivityStarter
private lateinit var adapter: ProductListAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
_binding = ActivityYourListedProductsBinding.inflate(layoutInflater)
setContentView(binding.root)
setSupportActionBar(binding.toolbar)
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
supportActionBar!!.setDisplayShowHomeEnabled(true)
title = viewModel.listName
// OnClick
binding.scanFirstYourListedProduct.setOnClickListener { checkPermsStartScan() }
adapter = ProductListAdapter(this, picasso).apply {
onItemClickListener = {
// TODO: Find a better way to do this
lifecycleScope.launch {
productViewActivityStarter.openProduct(
Barcode(it.barcode),
this@ProductListActivity
)
}
}
}
binding.rvYourListedProducts.adapter = adapter
binding.rvYourListedProducts.layoutManager = LinearLayoutManager(this)
binding.rvYourListedProducts.setHasFixedSize(false)
lifecycleScope.launch {
viewModel.productList.flowWithLifecycle(lifecycle).collect {
if (it.products.isEmpty()) {
binding.tvInfoYourListedProducts.visibility = View.VISIBLE
binding.scanFirstYourListedProduct.visibility = View.VISIBLE
setInfo(it, binding.tvInfoYourListedProducts)
}
adapter.products = it.products
adapter.notifyDataSetChanged()
}
}
ItemTouchHelper(SwipeController(this) { onRightSwiped(it) })
.attachToRecyclerView(binding.rvYourListedProducts)
binding.bottomNavigation.bottomNavigation.selectNavigationItem(0)
binding.bottomNavigation.bottomNavigation.installBottomNavigation(this)
}
override fun onDestroy() {
_binding = null
super.onDestroy()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_your_listed_products, menu)
return true
}
override fun onPrepareOptionsMenu(menu: Menu?): Boolean {
if (menu == null) return false
listOf(
R.id.action_export_all_listed_products,
R.id.action_sort_listed_products,
R.id.action_share_list
).forEach {
menu.findItem(it).isVisible = adapter.products.isNotEmpty()
}
return true
}
private val requestWriteLauncher = registerForActivityResult(ActivityResultContracts.RequestPermission())
{ if (it) exportAsCSV() }
override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) {
android.R.id.home -> {
setResult(RESULT_OK, Intent().apply {
putExtra("update", true)
})
finish()
true
}
R.id.action_export_all_listed_products -> {
val perm = Manifest.permission.WRITE_EXTERNAL_STORAGE
when {
checkSelfPermission(this, perm) == PackageManager.PERMISSION_GRANTED -> {
exportAsCSV()
matomoAnalytics.trackEvent(AnalyticsEvent.ShoppingListExported)
}
shouldShowRequestPermissionRationale(this, perm) -> {
MaterialAlertDialogBuilder(this)
.setTitle(R.string.action_about)
.setMessage(R.string.permision_write_external_storage)
.setNeutralButton(android.R.string.ok) { _, _ ->
requestWriteLauncher.launch(perm)
}
.show()
}
else -> {
requestWriteLauncher.launch(perm)
}
}
true
}
R.id.action_sort_listed_products -> {
val sortTypes = if (isFlavors(AppFlavor.OFF)) {
arrayOf(
getString(R.string.by_title),
getString(R.string.by_brand),
getString(R.string.by_nutrition_grade),
getString(R.string.by_barcode),
getString(R.string.by_time)
)
} else {
arrayOf(
getString(R.string.by_title),
getString(R.string.by_brand),
getString(R.string.by_time),
getString(R.string.by_barcode)
)
}
MaterialAlertDialogBuilder(this)
.setTitle(R.string.sort_by)
.setItems(sortTypes) { _, position ->
val sortType = when (position) {
0 -> TITLE
1 -> BRAND
2 -> if (isFlavors(AppFlavor.OFF)) GRADE else TIME
3 -> BARCODE
else -> TIME
}
viewModel.sortBy(sortType)
}
.show()
true
}
R.id.action_share_list -> {
shareList()
true
}
else -> super.onOptionsItemSelected(item)
}
private fun setInfo(productList: ProductLists, view: TextView) = if (productList.id == 1L) {
view.setText(R.string.txt_info_eaten_products)
} else {
view.setText(R.string.txt_info_your_listed_products)
}
private fun checkPermsStartScan() {
if (!isHardwareCameraInstalled(this)) {
logcat(LogPriority.WARN) { "Device has no camera installed." }
return
}
when {
checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED -> {
startScanActivity()
}
shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA) -> {
MaterialAlertDialogBuilder(this)
.setTitle(R.string.action_about)
.setMessage(R.string.permission_camera)
.setNeutralButton(android.R.string.ok) { _, _ ->
requestCameraThenOpenScan.launch(Manifest.permission.CAMERA)
}
.show()
}
else -> {
requestCameraThenOpenScan.launch(Manifest.permission.CAMERA)
}
}
}
@RequiresApi(Build.VERSION_CODES.KITKAT)
val fileWriterLauncher = registerForActivityResult(CreateCSVContract())
{ uri -> uri?.let { writeListToFile(this, viewModel.productList.value, it) } }
private fun exportAsCSV() {
Toast.makeText(this, R.string.txt_exporting_your_listed_products, Toast.LENGTH_LONG).show()
val productList = viewModel.productList.value
val listName = productList.listName
val flavor = BuildConfig.FLAVOR.uppercase(Locale.ROOT)
val date = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(Date())
val fileName = "$flavor-${listName}_$date.csv"
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
fileWriterLauncher.launch(fileName)
} else {
@Suppress("DEPRECATION")
val baseDir = File(Environment.getExternalStorageDirectory(), getCsvFolderName())
if (!baseDir.exists()) baseDir.mkdirs()
val file = File(baseDir, fileName)
writeListToFile(this, productList, file.toUri())
}
}
private fun shareList() {
val productList = viewModel.productList.value
val shareUrl = "${BuildConfig.OFWEBSITE}search?code=${productList.products.joinToString(",") { it.barcode }}"
startActivity(Intent.createChooser(Intent().apply {
action = Intent.ACTION_SEND
type = "text/plain"
putExtra(Intent.EXTRA_TEXT, shareUrl)
}, null))
matomoAnalytics.trackEvent(AnalyticsEvent.ShoppingListShared)
}
private fun onRightSwiped(position: Int) {
val productToRemove = adapter.products.getOrNull(position) ?: return
adapter.remove(productToRemove)
viewModel.removeProduct(productToRemove)
matomoAnalytics.trackEvent(AnalyticsEvent.ShoppingListProductRemoved(productToRemove.barcode))
}
override fun onBackPressed() {
setResult(RESULT_OK, Intent().apply { putExtra("update", true) })
super.onBackPressed()
}
companion object {
fun start(context: Context, listID: Long, listName: String) {
context.startActivity(Intent<ProductListActivity>(context).apply {
putExtra(KEY_LIST_ID, listID)
putExtra(KEY_LIST_NAME, listName)
})
}
const val KEY_LIST_ID = "listId"
const val KEY_LIST_NAME = "listName"
const val KEY_PRODUCT_TO_ADD = "product"
}
}
| 390 | null | 447 | 772 | 836bab540ec9e2792b692a3b25ff61e444fae045 | 12,380 | openfoodfacts-androidapp | Apache License 2.0 |
app/src/androidTest/java/com/example/sandbox/main/image/ImageFragmentViewTest.kt | rafikFares | 523,404,801 | false | {"Kotlin": 200088} | package com.example.sandbox.main.image
import androidx.fragment.app.testing.FragmentScenario
import androidx.fragment.app.testing.launchFragmentInContainer
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.isDisplayed
import androidx.test.espresso.matcher.ViewMatchers.withId
import com.example.sandbox.R
import com.example.sandbox.fragment.BaseAndroidUiFragmentTest
import com.example.sandbox.rule.DisableAnimationsRule
import org.hamcrest.Matchers.not
import org.junit.Rule
import org.junit.Test
class ImageFragmentViewTest : BaseAndroidUiFragmentTest<ImageFragment>() {
@get:Rule
val disableAnimationsRule = DisableAnimationsRule()
override val fragmentScenario: FragmentScenario<ImageFragment>
get() = launchFragmentInContainer(themeResId = R.style.Theme_Sandbox)
@Test
fun initialViewState() {
onView(
withId(R.id.imageProgress)
).check(
matches(not(isDisplayed()))
)
onView(
withId(R.id.fullImage)
).check(
matches(not(isDisplayed()))
)
}
}
| 2 | Kotlin | 0 | 0 | f84378d4253e45a42469b6bb4b42ea614efdcd1a | 1,191 | Sandbox_v2 | Apache License 2.0 |
history/src/main/java/com/chrisjanusa/history/HistoryListUIManager.kt | chrisjanusa | 209,855,968 | false | {"Kotlin": 223559} | package com.chrisjanusa.blocks
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.recyclerview.widget.LinearLayoutManager
import com.chrisjanusa.base.CommunicationHelper
import com.chrisjanusa.base.interfaces.FeatureUIManager
import com.chrisjanusa.base.interfaces.BaseFragmentDetails
import com.chrisjanusa.base.models.RandomizerState
import com.chrisjanusa.base.models.RandomizerViewModel
import com.chrisjanusa.baselist.BlockClickAndRefreshAction
import com.chrisjanusa.baselist.FavoriteClickAndRefreshAction
import com.chrisjanusa.baselist.RestaurantAdapter
import com.chrisjanusa.yelp.models.Restaurant
import java.util.*
object BlocksListUIManager : FeatureUIManager {
override fun init(randomizerViewModel: RandomizerViewModel, baseFragmentDetails: BaseFragmentDetails) {
if (baseFragmentDetails is BlocksFragmentDetails) {
baseFragmentDetails.fragment.run {
baseFragmentDetails.binding.recyclerView.apply {
// set a LinearLayoutManager to handle Android
// RecyclerView behavior
layoutManager = LinearLayoutManager(activity)
// set the custom adapter to the RecyclerView
adapter = RestaurantAdapter(
randomizerViewModel.state.value?.blockList ?: LinkedList(),
randomizerViewModel
) { inflater: LayoutInflater, parent: ViewGroup -> RestaurantViewHolder(inflater, parent) }
}
}
}
}
override fun render(state: RandomizerState, baseFragmentDetails: BaseFragmentDetails) {
}
fun renderFavBlock(
restaurant: Restaurant,
view: View,
randomizerViewModel: RandomizerViewModel,
position: Int
) {
val state = randomizerViewModel.state.value?.copy() ?: return
view.run {
val favIcon =
if (state.favList.contains(restaurant))
R.drawable.star_selected
else
R.drawable.star_default
findViewById<ImageView>(R.id.favButton).setImageResource(favIcon)
findViewById<ImageView>(R.id.favButton).setOnClickListener {
CommunicationHelper.sendAction(
FavoriteClickAndRefreshAction(
restaurant,
position,
R.id.recyclerView
),
randomizerViewModel
)
}
val blockIcon =
if (state.blockList.contains(restaurant))
R.drawable.block_selected
else
R.drawable.block_default
findViewById<ImageView>(R.id.blockButton).setImageResource(blockIcon)
findViewById<ImageView>(R.id.blockButton).setOnClickListener {
CommunicationHelper.sendAction(
BlockClickAndRefreshAction(
restaurant,
position,
R.id.recyclerView
),
randomizerViewModel
)
}
}
}
} | 1 | Kotlin | 0 | 0 | cd1bfe507e320d2774869d926fd35bc721d2c218 | 3,298 | RandomRestaurantKotlin | MIT License |
src/main/kotlin/io/zeko/db/sql/connections/DBLogger.kt | darkredz | 253,306,508 | false | null | package io.zeko.db.sql.connections
interface DBLogger {
fun getSqlLogLevel(): DBLogLevel
fun setSqlLogLevel(level: DBLogLevel): DBLogger
fun getParamsLogLevel(): DBLogLevel
fun setParamsLogLevel(level: DBLogLevel): DBLogger
fun setLogLevels(sqlLevel: DBLogLevel, paramsLevel: DBLogLevel): DBLogger
fun logQuery(sql: String, params: List<Any?>? = null)
fun logError(err: Exception)
fun logUnsupportedSql(err: Exception)
fun logRetry(numRetriesLeft: Int, err: Exception)
}
| 2 | Kotlin | 6 | 89 | a70f6d207d77048f690d0d728e22091fe152dda8 | 508 | Zeko-SQL-Builder | Apache License 2.0 |
richtext/src/main/java/cn/memox/ext/tip/internal/TipNodeRenderer.kt | BingyanStudio | 709,754,810 | false | {"Kotlin": 439255} | package com.bingyan.bbhust.ext.tip.internal
import com.bingyan.bbhust.ext.tip.Tip
import org.commonmark.node.Node
import org.commonmark.renderer.NodeRenderer
abstract class TipNodeRenderer : NodeRenderer {
override fun getNodeTypes(): Set<Class<out Node>> {
return setOf<Class<out Node>>(Tip::class.java)
}
} | 1 | Kotlin | 0 | 1 | c7203e6b6fd69585cb752e14fb42b4463b46308b | 326 | BBHustAndroid | Apache License 2.0 |
src/test/kotlin/org/jetbrains/kotlinx/jupyter/test/testUtil.kt | Kotlin | 63,066,291 | false | null | package org.jetbrains.kotlinx.jupyter.test
import io.kotest.assertions.fail
import io.kotest.matchers.types.shouldBeInstanceOf
import io.kotest.matchers.types.shouldBeTypeOf
import jupyter.kotlin.JavaRuntime
import org.jetbrains.kotlinx.jupyter.api.AfterCellExecutionCallback
import org.jetbrains.kotlinx.jupyter.api.Code
import org.jetbrains.kotlinx.jupyter.api.CodeCell
import org.jetbrains.kotlinx.jupyter.api.CodePreprocessor
import org.jetbrains.kotlinx.jupyter.api.DisplayContainer
import org.jetbrains.kotlinx.jupyter.api.DisplayResult
import org.jetbrains.kotlinx.jupyter.api.DisplayResultWithCell
import org.jetbrains.kotlinx.jupyter.api.ExecutionCallback
import org.jetbrains.kotlinx.jupyter.api.ExtensionsProcessor
import org.jetbrains.kotlinx.jupyter.api.FieldsProcessor
import org.jetbrains.kotlinx.jupyter.api.HtmlData
import org.jetbrains.kotlinx.jupyter.api.InterruptionCallback
import org.jetbrains.kotlinx.jupyter.api.JREInfoProvider
import org.jetbrains.kotlinx.jupyter.api.JupyterClientType
import org.jetbrains.kotlinx.jupyter.api.KotlinKernelVersion
import org.jetbrains.kotlinx.jupyter.api.LibraryLoader
import org.jetbrains.kotlinx.jupyter.api.MimeTypedResult
import org.jetbrains.kotlinx.jupyter.api.Notebook
import org.jetbrains.kotlinx.jupyter.api.RenderersProcessor
import org.jetbrains.kotlinx.jupyter.api.ResultsAccessor
import org.jetbrains.kotlinx.jupyter.api.TextRenderersProcessor
import org.jetbrains.kotlinx.jupyter.api.VariableState
import org.jetbrains.kotlinx.jupyter.api.VariableStateImpl
import org.jetbrains.kotlinx.jupyter.api.libraries.ColorScheme
import org.jetbrains.kotlinx.jupyter.api.libraries.ColorSchemeChangedCallback
import org.jetbrains.kotlinx.jupyter.api.libraries.CommManager
import org.jetbrains.kotlinx.jupyter.api.libraries.ExecutionHost
import org.jetbrains.kotlinx.jupyter.api.libraries.JupyterIntegration
import org.jetbrains.kotlinx.jupyter.api.libraries.LibraryDefinition
import org.jetbrains.kotlinx.jupyter.api.libraries.LibraryReference
import org.jetbrains.kotlinx.jupyter.api.libraries.LibraryResolutionRequest
import org.jetbrains.kotlinx.jupyter.api.libraries.Variable
import org.jetbrains.kotlinx.jupyter.api.libraries.createLibrary
import org.jetbrains.kotlinx.jupyter.api.withId
import org.jetbrains.kotlinx.jupyter.config.defaultRepositoriesCoordinates
import org.jetbrains.kotlinx.jupyter.config.defaultRuntimeProperties
import org.jetbrains.kotlinx.jupyter.libraries.AbstractLibraryResolutionInfo
import org.jetbrains.kotlinx.jupyter.libraries.ChainedLibraryResolver
import org.jetbrains.kotlinx.jupyter.libraries.KERNEL_LIBRARIES
import org.jetbrains.kotlinx.jupyter.libraries.LibraryDescriptor
import org.jetbrains.kotlinx.jupyter.libraries.LibraryResolver
import org.jetbrains.kotlinx.jupyter.libraries.parseLibraryDescriptors
import org.jetbrains.kotlinx.jupyter.log
import org.jetbrains.kotlinx.jupyter.messaging.CommunicationFacilityMock
import org.jetbrains.kotlinx.jupyter.messaging.DisplayHandler
import org.jetbrains.kotlinx.jupyter.messaging.comms.CommManagerImpl
import org.jetbrains.kotlinx.jupyter.repl.CompletionResult
import org.jetbrains.kotlinx.jupyter.repl.EvalRequestData
import org.jetbrains.kotlinx.jupyter.repl.ReplForJupyter
import org.jetbrains.kotlinx.jupyter.repl.ReplRuntimeProperties
import org.jetbrains.kotlinx.jupyter.repl.creating.ReplComponentsProviderBase
import org.jetbrains.kotlinx.jupyter.repl.notebook.MutableCodeCell
import org.jetbrains.kotlinx.jupyter.repl.notebook.MutableNotebook
import org.jetbrains.kotlinx.jupyter.repl.renderValue
import org.jetbrains.kotlinx.jupyter.repl.result.EvalResultEx
import java.io.File
import kotlin.reflect.KClass
import kotlin.reflect.typeOf
import kotlin.script.experimental.jvm.util.scriptCompilationClasspathFromContext
import kotlin.test.assertEquals
val testDataDir = File("src/test/testData")
const val standardResolverBranch = "master"
val testRepositories = defaultRepositoriesCoordinates
val standardResolverRuntimeProperties = object : ReplRuntimeProperties by defaultRuntimeProperties {
override val currentBranch: String
get() = standardResolverBranch
}
val classpath = scriptCompilationClasspathFromContext(
"lib",
"api",
"shared-compiler",
"kotlin-stdlib",
"kotlin-reflect",
"kotlin-script-runtime",
"kotlinx-serialization-json-jvm",
"kotlinx-serialization-core-jvm",
classLoader = TestDisplayHandler::class.java.classLoader,
)
val KClass<*>.classPathEntry: File get() {
return File(this.java.protectionDomain.codeSource.location.toURI().path)
}
inline fun <reified T> classPathEntry(): File {
return (typeOf<T>().classifier as KClass<*>).classPathEntry
}
val testLibraryResolver: LibraryResolver
get() = getResolverFromNamesMap(parseLibraryDescriptors(readLibraries()))
fun assertUnit(value: Any?) = assertEquals(Unit, value)
fun assertStartsWith(expectedPrefix: String, actual: String) {
if (actual.startsWith(expectedPrefix)) return
val actualStart = actual.substring(0, minOf(expectedPrefix.length, actual.length))
throw AssertionError("Expected a string to start with '$expectedPrefix', but it starts with '$actualStart")
}
fun Collection<Pair<String, String>>.toLibraries(): LibraryResolver {
val libJsons = associate { it.first to it.second }
return getResolverFromNamesMap(parseLibraryDescriptors(libJsons))
}
@JvmName("toLibrariesStringLibraryDefinition")
fun Collection<Pair<String, LibraryDefinition>>.toLibraries() = getResolverFromNamesMap(definitions = toMap())
fun getResolverFromNamesMap(
descriptors: Map<String, LibraryDescriptor>? = null,
definitions: Map<String, LibraryDefinition>? = null,
): LibraryResolver {
return InMemoryLibraryResolver(
null,
descriptors?.mapKeys { entry -> LibraryReference(AbstractLibraryResolutionInfo.Default(), entry.key) },
definitions?.mapKeys { entry -> LibraryReference(AbstractLibraryResolutionInfo.Default(), entry.key) },
)
}
fun readLibraries(basePath: String? = null): Map<String, String> {
return KERNEL_LIBRARIES.homeLibrariesDir(basePath?.let(::File))
.listFiles()?.filter(KERNEL_LIBRARIES::isLibraryDescriptor)
?.map {
log.info("Loading '${it.nameWithoutExtension}' descriptor from '${it.canonicalPath}'")
it.nameWithoutExtension to it.readText()
}
.orEmpty()
.toMap()
}
fun CompletionResult.getOrFail(): CompletionResult.Success = when (this) {
is CompletionResult.Success -> this
else -> fail("Result should be success")
}
fun Map<String, VariableState>.mapToStringValues(): Map<String, String?> {
return mapValues { it.value.stringValue }
}
fun Map<String, VariableState>.getStringValue(variableName: String): String? {
return get(variableName)?.stringValue
}
fun Map<String, VariableState>.getValue(variableName: String): Any? {
return get(variableName)?.value?.getOrNull()
}
class InMemoryLibraryResolver(
parent: LibraryResolver?,
initialDescriptorsCache: Map<LibraryReference, LibraryDescriptor>? = null,
initialDefinitionsCache: Map<LibraryReference, LibraryDefinition>? = null,
) : ChainedLibraryResolver(parent) {
private val definitionsCache = hashMapOf<LibraryReference, LibraryDefinition>()
private val descriptorsCache = hashMapOf<LibraryReference, LibraryDescriptor>()
init {
initialDescriptorsCache?.forEach { (key, value) ->
descriptorsCache[key] = value
}
initialDefinitionsCache?.forEach { (key, value) ->
definitionsCache[key] = value
}
}
override fun shouldResolve(reference: LibraryReference): Boolean {
return reference.shouldBeCachedInMemory
}
override fun tryResolve(reference: LibraryReference, arguments: List<Variable>): LibraryDefinition? {
return definitionsCache[reference] ?: descriptorsCache[reference]?.convertToDefinition(arguments)
}
override fun save(reference: LibraryReference, definition: LibraryDefinition) {
definitionsCache[reference] = definition
}
}
open class TestDisplayHandler(val list: MutableList<Any> = mutableListOf()) : DisplayHandler {
override fun handleDisplay(value: Any, host: ExecutionHost, id: String?) {
list.add(value)
}
override fun handleUpdate(value: Any, host: ExecutionHost, id: String?) {
TODO("Not yet implemented")
}
}
class TestDisplayHandlerWithRendering(
private val notebook: MutableNotebook,
list: MutableList<Any> = mutableListOf(),
) : TestDisplayHandler(list) {
override fun handleDisplay(value: Any, host: ExecutionHost, id: String?) {
super.handleDisplay(value, host, id)
val display = renderValue(notebook, host, value)?.let { if (id != null) it.withId(id) else it } ?: return
notebook.currentCell?.addDisplay(display)
}
override fun handleUpdate(value: Any, host: ExecutionHost, id: String?) {
super.handleUpdate(value, host, id)
val display = renderValue(notebook, host, value) ?: return
val container = notebook.displays
container.update(id, display)
container.getById(id).distinctBy { it.cell.id }.forEach {
it.cell.displays.update(id, display)
}
}
}
object NotebookMock : Notebook {
private val cells = hashMapOf<Int, MutableCodeCell>()
override val cellsList: Collection<CodeCell>
get() = emptyList()
override val variablesState = mutableMapOf<String, VariableStateImpl>()
override val cellVariables = mapOf<Int, Set<String>>()
override val resultsAccessor = ResultsAccessor { getResult(it) }
override fun getCell(id: Int): MutableCodeCell {
return cells[id] ?: throw ArrayIndexOutOfBoundsException(
"There is no cell with number '$id'",
)
}
override fun getResult(id: Int): Any? {
return getCell(id).result
}
override val displays: DisplayContainer
get() = notImplemented()
override fun getAllDisplays(): List<DisplayResultWithCell> {
return displays.getAll()
}
override fun getDisplaysById(id: String?): List<DisplayResultWithCell> {
return displays.getById(id)
}
override fun history(before: Int): CodeCell? {
notImplemented()
}
override val currentColorScheme: ColorScheme?
get() = null
override fun changeColorScheme(newScheme: ColorScheme) {
notImplemented()
}
override fun renderHtmlAsIFrame(data: HtmlData): MimeTypedResult {
notImplemented()
}
override val kernelVersion: KotlinKernelVersion
get() = defaultRuntimeProperties.version!!
override val jreInfo: JREInfoProvider
get() = JavaRuntime
override val renderersProcessor: RenderersProcessor
get() = notImplemented()
override val textRenderersProcessor: TextRenderersProcessor
get() = notImplemented()
override val fieldsHandlersProcessor: FieldsProcessor
get() = notImplemented()
override val beforeCellExecutionsProcessor: ExtensionsProcessor<ExecutionCallback<*>>
get() = notImplemented()
override val afterCellExecutionsProcessor: ExtensionsProcessor<AfterCellExecutionCallback>
get() = notImplemented()
override val shutdownExecutionsProcessor: ExtensionsProcessor<ExecutionCallback<*>>
get() = notImplemented()
override val codePreprocessorsProcessor: ExtensionsProcessor<CodePreprocessor>
get() = notImplemented()
override val interruptionCallbacksProcessor: ExtensionsProcessor<InterruptionCallback>
get() = notImplemented()
override val colorSchemeChangeCallbacksProcessor: ExtensionsProcessor<ColorSchemeChangedCallback>
get() = notImplemented()
override val libraryRequests: Collection<LibraryResolutionRequest>
get() = notImplemented()
override val libraryLoader: LibraryLoader
get() = notImplemented()
override fun getLibraryFromDescriptor(descriptorText: String, options: Map<String, String>): LibraryDefinition {
notImplemented()
}
private fun notImplemented(): Nothing {
error("Not supposed to be called")
}
override val jupyterClientType: JupyterClientType
get() = JupyterClientType.UNKNOWN
override val commManager: CommManager
get() = CommManagerImpl(CommunicationFacilityMock)
}
object ReplComponentsProviderMock : ReplComponentsProviderBase()
fun library(builder: JupyterIntegration.Builder.() -> Unit) = createLibrary(NotebookMock, builder)
fun ReplForJupyter.evalEx(code: Code) = evalEx(EvalRequestData(code))
inline fun <reified T : Throwable> ReplForJupyter.evalError(code: Code): T {
val result = evalEx(code)
result.shouldBeInstanceOf<EvalResultEx.Error>()
return result.error.shouldBeTypeOf()
}
inline fun <reified T : Throwable> ReplForJupyter.evalRenderedError(code: Code): DisplayResult? {
val result = evalEx(code)
result.shouldBeInstanceOf<EvalResultEx.RenderedError>()
result.error.shouldBeTypeOf<T>()
return result.displayError
}
fun ReplForJupyter.evalInterrupted(code: Code) {
val result = evalEx(code)
result.shouldBeInstanceOf<EvalResultEx.Interrupted>()
}
fun ReplForJupyter.evalExSuccess(code: Code): EvalResultEx.Success {
val result = evalEx(code)
result.shouldBeInstanceOf<EvalResultEx.Success>()
return result
}
fun ReplForJupyter.evalRaw(code: Code): Any? {
return evalExSuccess(code).internalResult.result.value
}
fun ReplForJupyter.evalRendered(code: Code): Any? {
return evalExSuccess(code).renderedValue
}
val EvalResultEx.rawValue get(): Any? {
this.shouldBeTypeOf<EvalResultEx.Success>()
return this.internalResult.result.value
}
val EvalResultEx.renderedValue get(): Any? {
this.shouldBeTypeOf<EvalResultEx.Success>()
return this.renderedValue
}
val EvalResultEx.displayValue get(): Any? {
this.shouldBeTypeOf<EvalResultEx.Success>()
return this.displayValue
}
fun EvalResultEx.assertSuccess() {
when (this) {
is EvalResultEx.AbstractError -> throw error
is EvalResultEx.Interrupted -> throw InterruptedException()
is EvalResultEx.Success -> {}
}
}
| 79 | null | 97 | 984 | 94794065fd0a616b757a8cabf4574bb63344facb | 14,238 | kotlin-jupyter | Apache License 2.0 |
src/test/kotlin/org/jetbrains/kotlinx/jupyter/test/testUtil.kt | Kotlin | 63,066,291 | false | null | package org.jetbrains.kotlinx.jupyter.test
import io.kotest.assertions.fail
import io.kotest.matchers.types.shouldBeInstanceOf
import io.kotest.matchers.types.shouldBeTypeOf
import jupyter.kotlin.JavaRuntime
import org.jetbrains.kotlinx.jupyter.api.AfterCellExecutionCallback
import org.jetbrains.kotlinx.jupyter.api.Code
import org.jetbrains.kotlinx.jupyter.api.CodeCell
import org.jetbrains.kotlinx.jupyter.api.CodePreprocessor
import org.jetbrains.kotlinx.jupyter.api.DisplayContainer
import org.jetbrains.kotlinx.jupyter.api.DisplayResult
import org.jetbrains.kotlinx.jupyter.api.DisplayResultWithCell
import org.jetbrains.kotlinx.jupyter.api.ExecutionCallback
import org.jetbrains.kotlinx.jupyter.api.ExtensionsProcessor
import org.jetbrains.kotlinx.jupyter.api.FieldsProcessor
import org.jetbrains.kotlinx.jupyter.api.HtmlData
import org.jetbrains.kotlinx.jupyter.api.InterruptionCallback
import org.jetbrains.kotlinx.jupyter.api.JREInfoProvider
import org.jetbrains.kotlinx.jupyter.api.JupyterClientType
import org.jetbrains.kotlinx.jupyter.api.KotlinKernelVersion
import org.jetbrains.kotlinx.jupyter.api.LibraryLoader
import org.jetbrains.kotlinx.jupyter.api.MimeTypedResult
import org.jetbrains.kotlinx.jupyter.api.Notebook
import org.jetbrains.kotlinx.jupyter.api.RenderersProcessor
import org.jetbrains.kotlinx.jupyter.api.ResultsAccessor
import org.jetbrains.kotlinx.jupyter.api.TextRenderersProcessor
import org.jetbrains.kotlinx.jupyter.api.VariableState
import org.jetbrains.kotlinx.jupyter.api.VariableStateImpl
import org.jetbrains.kotlinx.jupyter.api.libraries.ColorScheme
import org.jetbrains.kotlinx.jupyter.api.libraries.ColorSchemeChangedCallback
import org.jetbrains.kotlinx.jupyter.api.libraries.CommManager
import org.jetbrains.kotlinx.jupyter.api.libraries.ExecutionHost
import org.jetbrains.kotlinx.jupyter.api.libraries.JupyterIntegration
import org.jetbrains.kotlinx.jupyter.api.libraries.LibraryDefinition
import org.jetbrains.kotlinx.jupyter.api.libraries.LibraryReference
import org.jetbrains.kotlinx.jupyter.api.libraries.LibraryResolutionRequest
import org.jetbrains.kotlinx.jupyter.api.libraries.Variable
import org.jetbrains.kotlinx.jupyter.api.libraries.createLibrary
import org.jetbrains.kotlinx.jupyter.api.withId
import org.jetbrains.kotlinx.jupyter.config.defaultRepositoriesCoordinates
import org.jetbrains.kotlinx.jupyter.config.defaultRuntimeProperties
import org.jetbrains.kotlinx.jupyter.libraries.AbstractLibraryResolutionInfo
import org.jetbrains.kotlinx.jupyter.libraries.ChainedLibraryResolver
import org.jetbrains.kotlinx.jupyter.libraries.KERNEL_LIBRARIES
import org.jetbrains.kotlinx.jupyter.libraries.LibraryDescriptor
import org.jetbrains.kotlinx.jupyter.libraries.LibraryResolver
import org.jetbrains.kotlinx.jupyter.libraries.parseLibraryDescriptors
import org.jetbrains.kotlinx.jupyter.log
import org.jetbrains.kotlinx.jupyter.messaging.CommunicationFacilityMock
import org.jetbrains.kotlinx.jupyter.messaging.DisplayHandler
import org.jetbrains.kotlinx.jupyter.messaging.comms.CommManagerImpl
import org.jetbrains.kotlinx.jupyter.repl.CompletionResult
import org.jetbrains.kotlinx.jupyter.repl.EvalRequestData
import org.jetbrains.kotlinx.jupyter.repl.ReplForJupyter
import org.jetbrains.kotlinx.jupyter.repl.ReplRuntimeProperties
import org.jetbrains.kotlinx.jupyter.repl.creating.ReplComponentsProviderBase
import org.jetbrains.kotlinx.jupyter.repl.notebook.MutableCodeCell
import org.jetbrains.kotlinx.jupyter.repl.notebook.MutableNotebook
import org.jetbrains.kotlinx.jupyter.repl.renderValue
import org.jetbrains.kotlinx.jupyter.repl.result.EvalResultEx
import java.io.File
import kotlin.reflect.KClass
import kotlin.reflect.typeOf
import kotlin.script.experimental.jvm.util.scriptCompilationClasspathFromContext
import kotlin.test.assertEquals
val testDataDir = File("src/test/testData")
const val standardResolverBranch = "master"
val testRepositories = defaultRepositoriesCoordinates
val standardResolverRuntimeProperties = object : ReplRuntimeProperties by defaultRuntimeProperties {
override val currentBranch: String
get() = standardResolverBranch
}
val classpath = scriptCompilationClasspathFromContext(
"lib",
"api",
"shared-compiler",
"kotlin-stdlib",
"kotlin-reflect",
"kotlin-script-runtime",
"kotlinx-serialization-json-jvm",
"kotlinx-serialization-core-jvm",
classLoader = TestDisplayHandler::class.java.classLoader,
)
val KClass<*>.classPathEntry: File get() {
return File(this.java.protectionDomain.codeSource.location.toURI().path)
}
inline fun <reified T> classPathEntry(): File {
return (typeOf<T>().classifier as KClass<*>).classPathEntry
}
val testLibraryResolver: LibraryResolver
get() = getResolverFromNamesMap(parseLibraryDescriptors(readLibraries()))
fun assertUnit(value: Any?) = assertEquals(Unit, value)
fun assertStartsWith(expectedPrefix: String, actual: String) {
if (actual.startsWith(expectedPrefix)) return
val actualStart = actual.substring(0, minOf(expectedPrefix.length, actual.length))
throw AssertionError("Expected a string to start with '$expectedPrefix', but it starts with '$actualStart")
}
fun Collection<Pair<String, String>>.toLibraries(): LibraryResolver {
val libJsons = associate { it.first to it.second }
return getResolverFromNamesMap(parseLibraryDescriptors(libJsons))
}
@JvmName("toLibrariesStringLibraryDefinition")
fun Collection<Pair<String, LibraryDefinition>>.toLibraries() = getResolverFromNamesMap(definitions = toMap())
fun getResolverFromNamesMap(
descriptors: Map<String, LibraryDescriptor>? = null,
definitions: Map<String, LibraryDefinition>? = null,
): LibraryResolver {
return InMemoryLibraryResolver(
null,
descriptors?.mapKeys { entry -> LibraryReference(AbstractLibraryResolutionInfo.Default(), entry.key) },
definitions?.mapKeys { entry -> LibraryReference(AbstractLibraryResolutionInfo.Default(), entry.key) },
)
}
fun readLibraries(basePath: String? = null): Map<String, String> {
return KERNEL_LIBRARIES.homeLibrariesDir(basePath?.let(::File))
.listFiles()?.filter(KERNEL_LIBRARIES::isLibraryDescriptor)
?.map {
log.info("Loading '${it.nameWithoutExtension}' descriptor from '${it.canonicalPath}'")
it.nameWithoutExtension to it.readText()
}
.orEmpty()
.toMap()
}
fun CompletionResult.getOrFail(): CompletionResult.Success = when (this) {
is CompletionResult.Success -> this
else -> fail("Result should be success")
}
fun Map<String, VariableState>.mapToStringValues(): Map<String, String?> {
return mapValues { it.value.stringValue }
}
fun Map<String, VariableState>.getStringValue(variableName: String): String? {
return get(variableName)?.stringValue
}
fun Map<String, VariableState>.getValue(variableName: String): Any? {
return get(variableName)?.value?.getOrNull()
}
class InMemoryLibraryResolver(
parent: LibraryResolver?,
initialDescriptorsCache: Map<LibraryReference, LibraryDescriptor>? = null,
initialDefinitionsCache: Map<LibraryReference, LibraryDefinition>? = null,
) : ChainedLibraryResolver(parent) {
private val definitionsCache = hashMapOf<LibraryReference, LibraryDefinition>()
private val descriptorsCache = hashMapOf<LibraryReference, LibraryDescriptor>()
init {
initialDescriptorsCache?.forEach { (key, value) ->
descriptorsCache[key] = value
}
initialDefinitionsCache?.forEach { (key, value) ->
definitionsCache[key] = value
}
}
override fun shouldResolve(reference: LibraryReference): Boolean {
return reference.shouldBeCachedInMemory
}
override fun tryResolve(reference: LibraryReference, arguments: List<Variable>): LibraryDefinition? {
return definitionsCache[reference] ?: descriptorsCache[reference]?.convertToDefinition(arguments)
}
override fun save(reference: LibraryReference, definition: LibraryDefinition) {
definitionsCache[reference] = definition
}
}
open class TestDisplayHandler(val list: MutableList<Any> = mutableListOf()) : DisplayHandler {
override fun handleDisplay(value: Any, host: ExecutionHost, id: String?) {
list.add(value)
}
override fun handleUpdate(value: Any, host: ExecutionHost, id: String?) {
TODO("Not yet implemented")
}
}
class TestDisplayHandlerWithRendering(
private val notebook: MutableNotebook,
list: MutableList<Any> = mutableListOf(),
) : TestDisplayHandler(list) {
override fun handleDisplay(value: Any, host: ExecutionHost, id: String?) {
super.handleDisplay(value, host, id)
val display = renderValue(notebook, host, value)?.let { if (id != null) it.withId(id) else it } ?: return
notebook.currentCell?.addDisplay(display)
}
override fun handleUpdate(value: Any, host: ExecutionHost, id: String?) {
super.handleUpdate(value, host, id)
val display = renderValue(notebook, host, value) ?: return
val container = notebook.displays
container.update(id, display)
container.getById(id).distinctBy { it.cell.id }.forEach {
it.cell.displays.update(id, display)
}
}
}
object NotebookMock : Notebook {
private val cells = hashMapOf<Int, MutableCodeCell>()
override val cellsList: Collection<CodeCell>
get() = emptyList()
override val variablesState = mutableMapOf<String, VariableStateImpl>()
override val cellVariables = mapOf<Int, Set<String>>()
override val resultsAccessor = ResultsAccessor { getResult(it) }
override fun getCell(id: Int): MutableCodeCell {
return cells[id] ?: throw ArrayIndexOutOfBoundsException(
"There is no cell with number '$id'",
)
}
override fun getResult(id: Int): Any? {
return getCell(id).result
}
override val displays: DisplayContainer
get() = notImplemented()
override fun getAllDisplays(): List<DisplayResultWithCell> {
return displays.getAll()
}
override fun getDisplaysById(id: String?): List<DisplayResultWithCell> {
return displays.getById(id)
}
override fun history(before: Int): CodeCell? {
notImplemented()
}
override val currentColorScheme: ColorScheme?
get() = null
override fun changeColorScheme(newScheme: ColorScheme) {
notImplemented()
}
override fun renderHtmlAsIFrame(data: HtmlData): MimeTypedResult {
notImplemented()
}
override val kernelVersion: KotlinKernelVersion
get() = defaultRuntimeProperties.version!!
override val jreInfo: JREInfoProvider
get() = JavaRuntime
override val renderersProcessor: RenderersProcessor
get() = notImplemented()
override val textRenderersProcessor: TextRenderersProcessor
get() = notImplemented()
override val fieldsHandlersProcessor: FieldsProcessor
get() = notImplemented()
override val beforeCellExecutionsProcessor: ExtensionsProcessor<ExecutionCallback<*>>
get() = notImplemented()
override val afterCellExecutionsProcessor: ExtensionsProcessor<AfterCellExecutionCallback>
get() = notImplemented()
override val shutdownExecutionsProcessor: ExtensionsProcessor<ExecutionCallback<*>>
get() = notImplemented()
override val codePreprocessorsProcessor: ExtensionsProcessor<CodePreprocessor>
get() = notImplemented()
override val interruptionCallbacksProcessor: ExtensionsProcessor<InterruptionCallback>
get() = notImplemented()
override val colorSchemeChangeCallbacksProcessor: ExtensionsProcessor<ColorSchemeChangedCallback>
get() = notImplemented()
override val libraryRequests: Collection<LibraryResolutionRequest>
get() = notImplemented()
override val libraryLoader: LibraryLoader
get() = notImplemented()
override fun getLibraryFromDescriptor(descriptorText: String, options: Map<String, String>): LibraryDefinition {
notImplemented()
}
private fun notImplemented(): Nothing {
error("Not supposed to be called")
}
override val jupyterClientType: JupyterClientType
get() = JupyterClientType.UNKNOWN
override val commManager: CommManager
get() = CommManagerImpl(CommunicationFacilityMock)
}
object ReplComponentsProviderMock : ReplComponentsProviderBase()
fun library(builder: JupyterIntegration.Builder.() -> Unit) = createLibrary(NotebookMock, builder)
fun ReplForJupyter.evalEx(code: Code) = evalEx(EvalRequestData(code))
inline fun <reified T : Throwable> ReplForJupyter.evalError(code: Code): T {
val result = evalEx(code)
result.shouldBeInstanceOf<EvalResultEx.Error>()
return result.error.shouldBeTypeOf()
}
inline fun <reified T : Throwable> ReplForJupyter.evalRenderedError(code: Code): DisplayResult? {
val result = evalEx(code)
result.shouldBeInstanceOf<EvalResultEx.RenderedError>()
result.error.shouldBeTypeOf<T>()
return result.displayError
}
fun ReplForJupyter.evalInterrupted(code: Code) {
val result = evalEx(code)
result.shouldBeInstanceOf<EvalResultEx.Interrupted>()
}
fun ReplForJupyter.evalExSuccess(code: Code): EvalResultEx.Success {
val result = evalEx(code)
result.shouldBeInstanceOf<EvalResultEx.Success>()
return result
}
fun ReplForJupyter.evalRaw(code: Code): Any? {
return evalExSuccess(code).internalResult.result.value
}
fun ReplForJupyter.evalRendered(code: Code): Any? {
return evalExSuccess(code).renderedValue
}
val EvalResultEx.rawValue get(): Any? {
this.shouldBeTypeOf<EvalResultEx.Success>()
return this.internalResult.result.value
}
val EvalResultEx.renderedValue get(): Any? {
this.shouldBeTypeOf<EvalResultEx.Success>()
return this.renderedValue
}
val EvalResultEx.displayValue get(): Any? {
this.shouldBeTypeOf<EvalResultEx.Success>()
return this.displayValue
}
fun EvalResultEx.assertSuccess() {
when (this) {
is EvalResultEx.AbstractError -> throw error
is EvalResultEx.Interrupted -> throw InterruptedException()
is EvalResultEx.Success -> {}
}
}
| 79 | null | 97 | 984 | 94794065fd0a616b757a8cabf4574bb63344facb | 14,238 | kotlin-jupyter | Apache License 2.0 |
src/cypress/lexer/Lexer.kt | Shom770 | 537,689,516 | false | null | package cypress.lexer
import cypress.CypressError
class Lexer(private val text: String) {
private val tokens = mutableListOf<Token>()
private val textIterator = text.toList().listIterator()
private val validOperators = "+-*/<>"
private val miscCharacters = "(){},="
private val validDigits = "0123456789."
private val validIdentifiers = ('A'..'z').joinToString("").replace("[\\]^_`", "_")
private val keywords = hashMapOf(
"not" to TokenType.NOT,
"and" to TokenType.AND,
"or" to TokenType.OR,
"if" to TokenType.IF,
"else" to TokenType.ELSE,
"for" to TokenType.FOR,
"proc" to TokenType.PROC
)
private fun advance(n: Int = 1): IndexedValue<Char> {
// Deal with the case where when advancing through the text, the amount of times to advance is 0.
if (n <= 0) {
return IndexedValue(textIterator.nextIndex() - 1, text[textIterator.nextIndex() - 1])
}
repeat(n - 1) { textIterator.next() }
return IndexedValue(textIterator.nextIndex(), textIterator.next())
}
private fun peekAhead(): Char? {
return text.getOrNull(textIterator.nextIndex())
}
private fun lexOperator(index: Int, currentChar: Char): Token {
return when (currentChar) {
'+' -> Token(TokenType.PLUS, span = index..index)
'/' -> Token(TokenType.FORWARD_SLASH, span = index..index)
// Defining behavior for the operators -, ->, *, **, <, <=, >, >=
'-' -> {
if (peekAhead() == '>') {
Token(TokenType.ARROW, span = index..advance().index)
}
else {
Token(TokenType.MINUS, span = index..index)
}
}
'*' -> {
if (peekAhead() == '*') {
Token(TokenType.DOUBLE_ASTERISK, span = index..advance().index)
} else {
Token(TokenType.ASTERISK, span = index..index)
}
}
'<' -> {
if (peekAhead() == '=') {
Token(TokenType.LESS_THAN_OR_EQUAL, span = index..advance().index)
} else {
Token(TokenType.LESS_THAN, span = index..index)
}
}
'>' -> {
if (peekAhead() == '=') {
Token(TokenType.GREATER_THAN_OR_EQUAL, span = index..advance().index)
} else {
Token(TokenType.GREATER_THAN, span = index..index)
}
}
else -> throw CypressError.CypressSyntaxError("Invalid character: $currentChar")
}
}
private fun lexIdentifier(index: Int): Token {
val endOfIdentifier = text.substring(
index until text.length
).indexOfFirst {
it !in validIdentifiers
}.takeIf {
it >= 0
} ?: (text.length - index)
val spanOfIdentifier = index until endOfIdentifier + index
return Token(
keywords.getOrDefault(text.substring(spanOfIdentifier).lowercase(), TokenType.IDENTIFIER),
span = spanOfIdentifier
).also {
advance(spanOfIdentifier.last - spanOfIdentifier.first)
}
}
private fun lexNumber(index: Int): Token {
val endOfNumber = text.substring(
index until text.length
).indexOfFirst {
it !in validDigits
}.takeIf {
it >= 0
} ?: (text.length - index)
val spanOfNumber = index until endOfNumber + index
val decimalPointCount = text.substring(spanOfNumber).count { it == '.' }
if (decimalPointCount > 1) {
throw CypressError.CypressSyntaxError(
"Found $decimalPointCount decimal points within this number: ${text.substring(spanOfNumber)}."
)
}
return Token(if (decimalPointCount == 0) TokenType.INT else TokenType.FLOAT, span = spanOfNumber).also {
advance(spanOfNumber.last - spanOfNumber.first)
}
}
private fun lexMiscCharacters(index: Int, currentChar: Char): Token {
return when (currentChar) {
'(' -> Token(TokenType.OPEN_PAREN, span = index..index)
')' -> Token(TokenType.CLOSE_PAREN, span = index..index)
'{' -> Token(TokenType.OPEN_BRACE, span = index..index)
'}' -> Token(TokenType.CLOSE_BRACE, span = index..index)
',' -> Token(TokenType.COMMA, span = index..index)
'=' -> {
if (peekAhead() == '=') {
Token(TokenType.EQUALS, span = index..advance().index)
}
else {
Token(TokenType.ASSIGN, span = index..index)
}
}
else -> throw CypressError.CypressSyntaxError("Invalid character: $currentChar at index $index")
}
}
fun tokenize(): MutableList<Token> {
while (textIterator.hasNext()) {
val (index, currentChar) = advance()
// Deal with when we're lexing whitespace
if (!currentChar.toString().matches(Regex("."))) {
tokens.add(Token(TokenType.NEWLINE, span = index..index))
continue
}
else if (currentChar.isWhitespace()) {
continue
}
tokens.add(
when (currentChar) {
in validOperators -> lexOperator(index, currentChar)
in miscCharacters -> lexMiscCharacters(index, currentChar)
in validDigits -> lexNumber(index)
in validIdentifiers -> lexIdentifier(index)
else -> throw CypressError.CypressSyntaxError("Invalid character: $currentChar at index: $index")
}
)
}
return tokens
}
}
| 0 | Kotlin | 0 | 0 | f9f8a68fe5f79da09d02f7acff6e8e91415f149f | 5,968 | cypress | MIT License |
app/src/main/java/com/wireguard/android/model/ApplicationData.kt | msfjarvis | 143,062,973 | false | null | /*
* Copyright © 2017-2018 WireGuard LLC.
* Copyright © 2018-2019 <NAME> <<EMAIL>>. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
package com.wireguard.android.model
import android.graphics.drawable.Drawable
import androidx.databinding.BaseObservable
import androidx.databinding.Bindable
import com.wireguard.android.BR
import com.wireguard.util.Keyed
class ApplicationData(
val icon: Drawable,
val name: String,
val packageName: String,
private var excludedFromTunnel: Boolean,
@Bindable
val isGloballyExcluded: Boolean = false
) : BaseObservable(), Keyed<String> {
override val key: String
get() = name
var isExcludedFromTunnel: Boolean
@Bindable
get() = if (isGloballyExcluded) true else excludedFromTunnel
set(excludedFromTunnel) {
if (!isGloballyExcluded) {
this.excludedFromTunnel = excludedFromTunnel
notifyPropertyChanged(BR.excludedFromTunnel)
}
}
}
| 3 | null | 27 | 159 | 18d78ad28cfafac9838bd6b5d36762c3987ff0e8 | 1,010 | viscerion | Apache License 2.0 |
app/src/test/kotlin/dev/fobo66/factcheckerassistant/data/FakeFactCheckApi.kt | fobo66 | 257,629,867 | false | {"Kotlin": 69919} | package dev.fobo66.factcheckerassistant.data
import dev.fobo66.factcheckerassistant.api.FactCheckApi
import dev.fobo66.factcheckerassistant.api.models.FactCheckResponse
class FakeFactCheckApi(
val response: FactCheckResponse,
val error: Exception? = null
) : FactCheckApi {
override suspend fun search(
query: String,
languageCode: String,
pageSize: Int,
pageToken: String?,
key: String
): FactCheckResponse = if (error == null) {
response
} else {
throw error
}
}
| 6 | Kotlin | 1 | 6 | 8b68807ee345b8fe84f301439dcd062a69d677f3 | 547 | FactCheckerAssistant | The Unlicense |
security/src/main/java/dev/funkymuse/security/AtbashCipher.kt | FunkyMuse | 168,687,007 | false | null | package com.crazylegend.kotlinextensions.dataStructuresAndAlgorithms.cryptography
/**
* Created by hristijan on 3/29/19 to long live and prosper !
*/
/**
* Atbash cipher is one of the oldest ciphers known. It is a substitution cipher which works by reversing the alphabet.
* For instance, "AZ" would become "ZA" and so on.
*
* The encryption method creates a reversed list from the original latin alphabet. The letters are then substituted
* by finding out their index in the original list and replacing the letter with the one with the same index from
* the reversed list.
*
* Decrypting works the same way, just with the lists in a different order.
*/
fun atbashEncrypt(text: String): String {
// Create a list of all the letters in the English alphabet.
val alphabet = listOf(
'a', 'b', 'c', 'd', 'e',
'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o',
'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y',
'z')
// Reverse it and put it in a new, reversed list.
val reversedAlphabet = alphabet.reversed()
// The string for output
var resultString = ""
/*
For every character of the original text:
If the character is not in the English alphabet, add it to the result.
Otherwise (if the character is in the English alphabet), substitute it with a character on the same position
in the reversed list, and then append it to the result.
*/
text.forEach { character ->
if (!alphabet.contains(character.toLowerCase())) resultString += character
else {
var newChar = reversedAlphabet[alphabet.indexOf(character.toLowerCase())]
// If the original character is in upper case, the substitute should be upper case, too.
if (character.isUpperCase()) newChar = newChar.toUpperCase()
resultString += newChar
}
}
return resultString
}
/**
* For documentation refer above, as it works following exactly the same principle.
*/
fun atbashDecrypt(text: String): String {
val alphabet = listOf(
'a', 'b', 'c', 'd', 'e',
'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o',
'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y',
'z')
val reversedAlphabet = alphabet.reversed()
var resultString = ""
text.forEach { character ->
if (!alphabet.contains(character.toLowerCase())) resultString += character
else {
var newChar = alphabet[reversedAlphabet.indexOf(character.toLowerCase())]
if (character.isUpperCase()) newChar = newChar.toUpperCase()
resultString += newChar
}
}
return resultString
} | 6 | null | 92 | 818 | fe984e6bdeb95fb5819f27dcb12001dcfd911819 | 2,775 | KAHelpers | MIT License |
src/main/kotlin/com/lunivore/montecarluni/engine/CycleTimesCalculator.kt | lunivore | 87,801,722 | false | null | package com.lunivore.montecarluni.engine
import com.lunivore.montecarluni.model.CycleTime
import com.lunivore.montecarluni.model.Record
import java.time.Duration
class CycleTimesCalculator() {
fun calculateCycleTimes(records: List<Record>): List<CycleTime> {
val sortedRecords = records.sortedBy { it.resolvedOrLastUpdatedDate }
return sortedRecords.mapIndexed { i, r ->
if (i == 0) {
CycleTime("", r.resolvedOrLastUpdatedDate, null)
} else {
CycleTime("", r.resolvedOrLastUpdatedDate,
Duration.between(sortedRecords[i-1].resolvedOrLastUpdatedDate, r.resolvedOrLastUpdatedDate))
}}
}
} | 7 | Kotlin | 1 | 5 | 9dd5a604c07455f4d330c70a207a65ea978438fd | 705 | montecarluni | Apache License 2.0 |
typescript-kotlin/src/main/kotlin/typescript/createLogicalNot.kt | turansky | 393,199,102 | false | null | // Automatically generated - do not modify!
@file:JsModule("typescript")
@file:JsNonModule
package typescript
/** @deprecated Use `factory.createLogicalNot` or the factory supplied by your transformation context instead. */
/*
external val createLogicalNot: (operand: Expression) => PrefixUnaryExpression
*/
| 0 | Kotlin | 1 | 10 | bcf03704c0e7670fd14ec4ab01dff8d7cca46bf0 | 311 | react-types-kotlin | Apache License 2.0 |
shared/src/commonMain/kotlin/com/example/moveeapp_compose_kmm/map/Map.kt | adessoTurkey | 673,248,729 | false | {"Kotlin": 334470, "Swift": 3538, "Ruby": 101} | package com.example.moveeapp_compose_kmm.map
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import com.example.moveeapp_compose_kmm.domain.location.DeviceLocation
import com.example.moveeapp_compose_kmm.ui.scene.map.Cinema
import com.example.moveeapp_compose_kmm.ui.scene.map.MapUiState
@Composable
expect fun Map(modifier: Modifier, uiState: MapUiState, onMarkerClick : (Cinema?) -> Unit, onPositionChange: (DeviceLocation) -> Unit)
| 6 | Kotlin | 3 | 78 | 2dbbd48654ee482258c37f0e51e52eb6af15ec3c | 468 | compose-multiplatform-sampleapp | Apache License 2.0 |
src/main/kotlin/xyz/olympusblog/dto/password/PasswordsEqualConstraint.kt | sentrionic | 376,094,493 | false | {"Kotlin": 68969, "HTML": 197} | package xyz.olympusblog.dto.password
import javax.validation.Constraint
import javax.validation.ConstraintValidator
import javax.validation.ConstraintValidatorContext
import kotlin.reflect.KClass
@Target(AnnotationTarget.ANNOTATION_CLASS, AnnotationTarget.CLASS)
@kotlin.annotation.Retention(AnnotationRetention.RUNTIME)
@MustBeDocumented
@Constraint(validatedBy = [PasswordsEqualConstraintValidator::class])
annotation class PasswordsEqualConstraint(
val message: String,
val groups: Array<KClass<*>> = [],
val payload: Array<KClass<out Any>> = []
)
class PasswordsEqualConstraintValidator :
ConstraintValidator<PasswordsEqualConstraint?, Any> {
override fun initialize(arg0: PasswordsEqualConstraint?) {}
override fun isValid(candidate: Any, arg1: ConstraintValidatorContext): Boolean {
val user: ChangePasswordDTO = candidate as ChangePasswordDTO
return user.newPassword == user.confirmNewPassword
}
} | 0 | Kotlin | 0 | 0 | eb7171aa6a58f565ddd489c3d5adde88c0f6626c | 951 | OlympusSpring | MIT License |
app/src/main/kotlin/org/wentura/locoway/data/model/Connection.kt | AdrianMiozga | 796,770,944 | false | {"Kotlin": 221313} | package org.wentura.locoway.data.model
import java.time.LocalDateTime
data class Connection(
val trainId: Long,
val trainNumber: Long,
val trainBrand: TrainBrand,
val ticketPrice: String,
val departureStation: String,
val arrivalStation: String,
val departureDateTime: LocalDateTime,
val arrivalDateTime: LocalDateTime,
val dogPrice: String = "0",
val bikePrice: String? = "0",
val luggagePrice: String = "0",
)
| 0 | Kotlin | 0 | 0 | a4f74769b2a18bf15d06366a4d116a4747131939 | 458 | Locoway-Android | MIT License |
platform/platform-impl/src/com/intellij/openapi/project/DumbServiceImpl.kt | JetBrains | 2,489,216 | false | null | // Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.project
import com.intellij.concurrency.currentThreadContext
import com.intellij.icons.AllIcons
import com.intellij.ide.IdeBundle
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.application.*
import com.intellij.openapi.application.impl.ApplicationImpl
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.blockingContext
import com.intellij.openapi.progress.util.PingProgress
import com.intellij.openapi.project.MergingQueueGuiExecutor.ExecutorStateListener
import com.intellij.openapi.project.MergingTaskQueue.SubmissionReceipt
import com.intellij.openapi.project.SingleTaskExecutor.AutoclosableProgressive
import com.intellij.openapi.startup.StartupActivity.RequiredForSmartMode
import com.intellij.openapi.ui.MessageType
import com.intellij.openapi.util.Computable
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.ModificationTracker
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.wm.WindowManager
import com.intellij.openapi.wm.ex.StatusBarEx
import com.intellij.platform.util.coroutines.childScope
import com.intellij.serviceContainer.NonInjectable
import com.intellij.util.ConcurrencyUtil
import com.intellij.util.SystemProperties
import com.intellij.util.application
import com.intellij.util.concurrency.ThreadingAssertions
import com.intellij.util.indexing.IndexingBundle
import com.intellij.util.ui.DeprecationStripePanel
import com.intellij.util.ui.UIUtil
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
import org.jetbrains.annotations.*
import org.jetbrains.annotations.ApiStatus.Internal
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.locks.LockSupport
import javax.swing.JComponent
@ApiStatus.Internal
open class DumbServiceImpl @NonInjectable @VisibleForTesting constructor(private val myProject: Project,
private val myPublisher: DumbModeListener,
private val scope: CoroutineScope) : DumbService(), Disposable, ModificationTracker, DumbServiceBalloon.Service {
private val myState: MutableStateFlow<DumbState> = MutableStateFlow(DumbState(!myProject.isDefault, 0L, 0))
// should only be accessed from EDT. This is to order synchronous and asynchronous publishing
private var lastPublishedState: DumbState = myState.value
override val project: Project = myProject
override var isAlternativeResolveEnabled: Boolean
get() = myAlternativeResolveTracker.isAlternativeResolveEnabled
set(enabled) {
myAlternativeResolveTracker.isAlternativeResolveEnabled = enabled
}
override val modificationTracker: ModificationTracker get() = this
@Volatile
var dumbModeStartTrace: Throwable? = null
private set
private var scheduledTasksScope: CoroutineScope = scope.childScope()
private val myTaskQueue: DumbServiceMergingTaskQueue = DumbServiceMergingTaskQueue()
private val myGuiDumbTaskRunner: DumbServiceGuiExecutor
private val mySyncDumbTaskRunner: DumbServiceSyncTaskQueue
private val myAlternativeResolveTracker: DumbServiceAlternativeResolveTracker
//used from EDT
private val myBalloon: DumbServiceBalloon
@Volatile
private var myWaitIntolerantThread: Thread? = null
// should only be accessed from EDT to avoid races between `queueTaskOnEDT` and `enterSmartModeIfDumb` (invoked from `afterLastTask`)
private var myLatestReceipt: SubmissionReceipt? = null
private inner class DumbTaskListener : ExecutorStateListener {
/*
* beforeFirstTask and afterLastTask always follow one after another. Receiving several beforeFirstTask or afterLastTask in row is
* always a failure of DumbServiceGuiTaskQueue.
* return true to start queue processing, false otherwise
*/
override fun beforeFirstTask(): Boolean {
// if a queue has already been emptied by modal dumb progress, DumbServiceGuiExecutor will not invoke processing on empty queue
LOG.assertTrue(myState.value.isDumb,
"State should be DUMB, but was " + myState.value)
return true
}
override fun afterLastTask(latestReceipt: SubmissionReceipt?) {
}
}
constructor(project: Project, scope: CoroutineScope) : this(project, project.messageBus.syncPublisher<DumbModeListener>(DUMB_MODE), scope)
init {
myGuiDumbTaskRunner = DumbServiceGuiExecutor(myProject, myTaskQueue, DumbTaskListener())
mySyncDumbTaskRunner = DumbServiceSyncTaskQueue(myProject, myTaskQueue)
if (Registry.`is`("scanning.should.pause.dumb.queue", false)) {
myProject.service<DumbServiceScanningListener>().subscribe()
}
if (Registry.`is`("vfs.refresh.should.pause.dumb.queue", true)) {
DumbServiceVfsBatchListener(myProject, myGuiDumbTaskRunner.guiSuspender())
}
myBalloon = DumbServiceBalloon(myProject, this)
myAlternativeResolveTracker = DumbServiceAlternativeResolveTracker()
// any project starts in dumb mode (except default project which is always smart)
// we assume that queueStartupActivitiesRequiredForSmartMode will be invoked to advance DUMB > SMART
}
fun queueStartupActivitiesRequiredForSmartMode() {
queueTask(InitialDumbTaskRequiredForSmartMode(project))
if (isSynchronousTaskExecution) {
// This is the same side effects as produced by enterSmartModeIfDumb (except updating icons). We apply them synchronously, because
// invokeLaterWithDumbStartModality(this::enterSmartModeIfDumb) does not work well in synchronous environments (e.g. in unit tests):
// code continues to execute without waiting for smart mode to start because of invoke*Later*. See, for example, DbSrcFileDialectTest
application.invokeAndWait {
myState.update { it.incrementDumbCounter().decrementDumbCounter() }
publishDumbModeChangedEvent()
}
}
}
override fun cancelTask(task: DumbModeTask) {
LOG.info("cancel $task [${project.name}]")
myTaskQueue.cancelTask(task)
}
override fun dispose() {
ApplicationManager.getApplication().assertWriteIntentLockAcquired()
myBalloon.dispose()
scheduledTasksScope.cancel("On dispose of DumbService", ProcessCanceledException())
myTaskQueue.disposePendingTasks()
}
override fun suspendIndexingAndRun(activityName: @NlsContexts.ProgressText String, activity: Runnable) {
myGuiDumbTaskRunner.suspendAndRun(activityName, activity)
}
override suspend fun suspendIndexingAndRun(activityName: @NlsContexts.ProgressText String, activity: suspend () -> Unit) {
myGuiDumbTaskRunner.guiSuspender().suspendAndRun(activityName, activity)
}
override val isDumb: Boolean
get() {
if (ALWAYS_SMART) return false
if (!ApplicationManager.getApplication().isReadAccessAllowed && Registry.`is`("ide.check.is.dumb.contract")) {
LOG.error("To avoid race conditions isDumb method should be used only under read action or in EDT thread.",
IllegalStateException())
}
return myState.value.isDumb
}
/**
* This method starts dumb mode (if not started), then runs suspend lambda, then ends dumb mode (if no other dumb tasks are running).
*
* This method can be invoked from any thread. It will switch to EDT to start/stop dumb mode. Runnable itself will be invoked from
* method's invocation context (thread).
*/
@TestOnly
suspend fun <T> runInDumbMode(block: suspend () -> T): T = runInDumbMode("test", block)
/**
* This method starts dumb mode (if not started), then runs suspend lambda, then ends dumb mode (if no other dumb tasks are running).
*
* This method can be invoked from any thread. It will switch to EDT to start/stop dumb mode. Runnable itself will be invoked from
* method's invocation context (thread).
*
* @param debugReason will only be printed to logs
*/
@Internal
suspend fun <T> runInDumbMode(debugReason: @NonNls String, block: suspend () -> T): T {
LOG.info("[$project]: running dumb task without visible indicator: $debugReason")
blockingContext { // because we need correct modality
application.invokeAndWait {
incrementDumbCounter(trace = Throwable())
}
}
try {
return block()
}
finally {
decrementDumbCounter()
LOG.info("[$project]: finished dumb task without visible indicator: $debugReason")
}
}
// We cannot make this function `suspend`, because we have a contract that if dumb task is queued from EDT, dumb service becomes dumb
// immediately. DumbService.queue is blocking method at the moment.
private fun incrementDumbCounter(trace: Throwable) {
ThreadingAssertions.assertEventDispatchThread()
if (myState.getAndUpdate { it.tryIncrementDumbCounter() }.incrementWillChangeDumbState) {
// If already dumb - just increment the counter. We don't need a write action (to not interrupt NBRA), neither we need EDT.
// Otherwise, increment the counter under write action because this will change dumb state
val enteredDumb = application.runWriteAction(Computable {
val old = myState.getAndUpdate { it.incrementDumbCounter() }
return@Computable old.isSmart
})
if (enteredDumb) {
LOG.info("enter dumb mode [${project.name}]")
dumbModeStartTrace = trace
publishDumbModeChangedEvent()
}
}
}
private suspend fun decrementDumbCounter() {
// If there are other dumb tasks - just decrement the counter. We don't need a write action (to not interrupt NBRA), neither we need EDT.
// Otherwise, decrement the counter under write action because this will change dumb state
if (myState.getAndUpdate { it.tryDecrementDumbCounter() }.decrementWillChangeDumbState) {
withContext(Dispatchers.EDT) {
val exitDumb = writeAction {
val new = myState.updateAndGet { it.decrementDumbCounter() }
return@writeAction new.isSmart
}
if (exitDumb) {
LOG.info("exit dumb mode [${project.name}]")
dumbModeStartTrace = null
publishDumbModeChangedEvent()
}
}
}
}
private fun publishDumbModeChangedEvent() {
ThreadingAssertions.assertEventDispatchThread()
val currentState = myState.value
if (lastPublishedState.modificationCounter >= currentState.modificationCounter) {
return // already published
}
// First change lastPublishedState, then publish. This is to address the situation that new event
// should be published while publishing current event
val wasDumb = lastPublishedState.isDumb
lastPublishedState = myState.value
if (wasDumb != currentState.isDumb) {
if (currentState.isDumb) {
runCatchingIgnorePCE { myPublisher.enteredDumbMode() }
}
else {
runCatchingIgnorePCE { myPublisher.exitDumbMode() }
}
}
}
override fun runWhenSmart(@Async.Schedule runnable: Runnable) {
myProject.getService(SmartModeScheduler::class.java).runWhenSmart(runnable)
}
override fun unsafeRunWhenSmart(@Async.Schedule runnable: Runnable) {
// we probably don't need unsafeRunWhenSmart anymore
runWhenSmart(runnable)
}
@OptIn(ExperimentalCoroutinesApi::class)
override fun queueTask(task: DumbModeTask) {
if (LOG.isDebugEnabled) {
LOG.debug("Scheduling task $task")
}
if (myProject.isDefault) {
LOG.error("No indexing tasks should be created for default project: $task")
}
if (isSynchronousTaskExecution) {
mySyncDumbTaskRunner.runTaskSynchronously(task)
return
}
val trace = Throwable()
val modality = ModalityState.defaultModalityState()
if (ApplicationManager.getApplication().isDispatchThread) {
queueTaskOnEdt(task, modality, trace)
}
else {
invokeLaterOnEdtInScheduledTasksScope(start = CoroutineStart.ATOMIC) {
try {
ensureActive()
queueTaskOnEdt(task, modality, trace)
}
catch (t: CancellationException) {
Disposer.dispose(task)
}
}
}
}
private fun invokeLaterOnEdtInScheduledTasksScope(start: CoroutineStart = CoroutineStart.DEFAULT,
block: suspend CoroutineScope.() -> Unit): Job {
val modality = ModalityState.defaultModalityState()
return scheduledTasksScope.launch(modality.asContextElement() + Dispatchers.EDT + currentThreadContext().minusKey(Job), start, block)
}
private fun queueTaskOnEdt(task: DumbModeTask, modality: ModalityState, trace: Throwable) {
ThreadingAssertions.assertEventDispatchThread()
myLatestReceipt = myTaskQueue.addTask(task)
incrementDumbCounter(trace)
// we want to invoke LATER. I.e. right now one can invoke completeJustSubmittedTasks and
// drain the queue synchronously under modal progress
var dumbModeCounterWillBeDecrementedFromOnFinish = false
invokeLaterOnEdtInScheduledTasksScope {
dumbModeCounterWillBeDecrementedFromOnFinish = true
myGuiDumbTaskRunner.startBackgroundProcess(onFinish = {
scope.launch(modality.asContextElement()) {
decrementDumbCounter()
}
})
}.invokeOnCompletion {
if (!dumbModeCounterWillBeDecrementedFromOnFinish) {
scope.launch(modality.asContextElement()) {
decrementDumbCounter()
}
}
}
}
override fun showDumbModeNotification(message: @NlsContexts.PopupContent String) {
showDumbModeNotificationForFunctionality(message, DumbModeBlockedFunctionality.Other)
}
override fun showDumbModeNotificationForFunctionality(message: @NlsContexts.PopupContent String,
functionality: DumbModeBlockedFunctionality) {
DumbModeBlockedFunctionalityCollector.logFunctionalityBlocked(project, functionality)
doShowDumbModeNotification(message)
}
/**
* Doesn't log new event if the equality object is equal to the previous one
*/
fun showDumbModeNotificationForFunctionalityWithCoalescing(message: @NlsContexts.PopupContent String,
functionality: DumbModeBlockedFunctionality,
equality: Any) {
DumbModeBlockedFunctionalityCollector.logFunctionalityBlockedWithCoalescing(project, functionality, equality)
doShowDumbModeNotification(message)
}
private fun doShowDumbModeNotification(message: @NlsContexts.PopupContent String) {
UIUtil.invokeLaterIfNeeded {
val ideFrame = WindowManager.getInstance().getIdeFrame(myProject)
if (ideFrame != null) {
val statusBar = ideFrame.statusBar as StatusBarEx?
statusBar?.notifyProgressByBalloon(MessageType.WARNING, message)
}
}
}
override fun showDumbModeNotificationForAction(message: @NlsContexts.PopupContent String, actionId: String?) {
if (actionId == null) {
DumbModeBlockedFunctionalityCollector.logFunctionalityBlocked(project, DumbModeBlockedFunctionality.ActionWithoutId)
}
else {
DumbModeBlockedFunctionalityCollector.logActionBlocked(project, actionId)
}
doShowDumbModeNotification(message)
}
override fun showDumbModeActionBalloon(balloonText: @NlsContexts.PopupContent String,
runWhenSmartAndBalloonStillShowing: Runnable,
actionIds: List<String>) {
myBalloon.showDumbModeActionBalloon(balloonText, {
DumbModeBlockedFunctionalityCollector.logActionsBlocked(project, actionIds, true)
runWhenSmartAndBalloonStillShowing.run()
}, { DumbModeBlockedFunctionalityCollector.logActionsBlocked(project, actionIds, false) })
}
override fun cancelAllTasksAndWait() {
val application = ApplicationManager.getApplication()
if (!application.isWriteIntentLockAcquired || application.isWriteAccessAllowed) {
throw AssertionError("Must be called on write thread without write action")
}
LOG.info("Purge dumb task queue")
val currentThread = Thread.currentThread()
val initialThreadName = currentThread.name
ConcurrencyUtil.runUnderThreadName(initialThreadName + " [DumbService.cancelAllTasksAndWait(state = " + myState.value + ")]") {
// isRunning will be false eventually, because we are on EDT, and no new task can be queued outside the EDT
// (we only wait for currently running task to terminate).
myGuiDumbTaskRunner.cancelAllTasks()
while (myGuiDumbTaskRunner.isRunning.value && !myProject.isDisposed) {
PingProgress.interactWithEdtProgress()
LockSupport.parkNanos(50000000)
}
// Invoked after myGuiDumbTaskRunner has stopped to make sure that all the tasks submitted from the executor callbacks are canceled
// This also cancels all the tasks that are waiting for the EDT to queue new dumb tasks
val oldTaskScope = scheduledTasksScope
scheduledTasksScope = scope.childScope()
oldTaskScope.cancel("DumbService.cancelAllTasksAndWait", ProcessCanceledException())
}
}
override fun waitForSmartMode() {
waitForSmartMode(Long.MAX_VALUE)
}
fun waitForSmartMode(milliseconds: Long): Boolean {
if (ALWAYS_SMART) return true
val application = ApplicationManager.getApplication()
if (application.isReadAccessAllowed) {
throw AssertionError("Don't invoke waitForSmartMode from inside read action in dumb mode")
}
if (myWaitIntolerantThread === Thread.currentThread()) {
throw AssertionError("Don't invoke waitForSmartMode from a background startup activity")
}
val switched = CountDownLatch(1)
val smartModeScheduler = myProject.getService(SmartModeScheduler::class.java)
smartModeScheduler.runWhenSmart { switched.countDown() }
// we check getCurrentMode here because of tests which may hang because runWhenSmart needs EDT for scheduling
val startTime = System.currentTimeMillis()
while (!myProject.isDisposed && smartModeScheduler.getCurrentMode() != 0) {
// it is fine to unblock the caller when myProject.isDisposed, even if didn't reach smart mode: we are on background thread
// without read action. Dumb mode may start immediately after the caller is unblocked, so caller is prepared for this situation.
try {
if (switched.await(50, TimeUnit.MILLISECONDS)) break
}
catch (ignored: InterruptedException) {
}
ProgressManager.checkCanceled()
if (startTime + milliseconds < System.currentTimeMillis()) return false
}
return true
}
override fun wrapGently(dumbUnawareContent: JComponent, parentDisposable: Disposable): JComponent {
val wrapper = DumbUnawareHider(dumbUnawareContent)
wrapper.setContentVisible(!isDumb)
project.messageBus.connect(parentDisposable).subscribe(DUMB_MODE, object : DumbModeListener {
override fun enteredDumbMode() {
wrapper.setContentVisible(false)
}
override fun exitDumbMode() {
wrapper.setContentVisible(true)
}
})
return wrapper
}
override fun wrapWithSpoiler(dumbAwareContent: JComponent, updateRunnable: Runnable, parentDisposable: Disposable): JComponent {
//TODO replace with a proper mockup implementation
val stripePanel = DeprecationStripePanel(IdeBundle.message("dumb.mode.results.might.be.incomplete"), AllIcons.General.Warning)
.withAlternativeAction(IdeBundle.message("dumb.mode.spoiler.wrapper.reload.text"), object : DumbAwareAction() {
override fun actionPerformed(e: AnActionEvent) {
updateRunnable.run()
}
})
stripePanel.isVisible = isDumb
project.messageBus.connect(parentDisposable).subscribe(DUMB_MODE, object : DumbModeListener {
override fun enteredDumbMode() {
stripePanel.isVisible = true
updateRunnable.run()
}
override fun exitDumbMode() {
stripePanel.isVisible = false
updateRunnable.run()
}
})
return stripePanel.wrap(dumbAwareContent)
}
override fun smartInvokeLater(runnable: Runnable) {
smartInvokeLater(runnable, ModalityState.defaultModalityState())
}
override fun smartInvokeLater(runnable: Runnable, modalityState: ModalityState) {
ApplicationManager.getApplication().invokeLater({
if (isDumb) {
runWhenSmart { smartInvokeLater(runnable, modalityState) }
}
else {
runnable.run()
}
}, modalityState, myProject.disposed)
}
override fun completeJustSubmittedTasks() {
ApplicationManager.getApplication().assertWriteIntentLockAcquired()
LOG.assertTrue(myProject.isInitialized, "Project should have been initialized")
while (myState.value.isDumb && !myTaskQueue.isEmpty) {
val queueProcessedUnderModalProgress = processQueueUnderModalProgress()
if (!queueProcessedUnderModalProgress) {
// processQueueUnderModalProgress did nothing (i.e. processing is being done under non-modal indicator)
break
}
}
if (myState.value.isSmart) { // we can reach this statement in dumb mode if queue is processed in background
// DumbServiceSyncTaskQueue does not respect threading policies: it can add tasks outside of EDT
// and process them without switching to dumb mode. This behavior has to be fixed, but for now just ignore
// it, because it has been working like this for years already.
// Reproducing in test: com.jetbrains.cidr.lang.refactoring.OCRenameMoveFileTest
LOG.assertTrue(isSynchronousTaskExecution || myTaskQueue.isEmpty, "Task queue is not empty. Current state is " + myState.value)
}
}
private fun processQueueUnderModalProgress(): Boolean {
val startTrace = Throwable()
NoAccessDuringPsiEvents.checkCallContext("modal indexing")
return myGuiDumbTaskRunner.tryStartProcessInThisThread { processTask: AutoclosableProgressive ->
try {
LOG.infoWithDebug("Processing dumb queue under modal progress (start)", startTrace)
(ApplicationManager.getApplication() as ApplicationImpl).executeSuspendingWriteAction(myProject, IndexingBundle.message(
"progress.indexing.title")) {
processTask.use {
processTask.run(
ProgressManager.getInstance().progressIndicator)
}
}
}
finally {
LOG.infoWithDebug("Processing dumb queue under modal progress (end)", startTrace)
}
}
}
override fun runWithWaitForSmartModeDisabled(): AccessToken {
myWaitIntolerantThread = Thread.currentThread()
return object : AccessToken() {
override fun finish() {
myWaitIntolerantThread = null
}
}
}
override fun getModificationCount(): Long {
return myState.value.modificationCounter
}
internal val dumbStateAsFlow: StateFlow<DumbState> = myState
internal data class DumbState(
val isDumb: Boolean, val modificationCounter: Long, val dumbCounter: Int
) {
private fun nextCounterState(nextVal: Int): DumbState {
if (nextVal > 0) {
return DumbState(true, modificationCounter + 1, nextVal)
}
else {
LOG.assertTrue(nextVal == 0) { "Invalid nextVal=$nextVal" }
return DumbState(false, modificationCounter + 1, 0)
}
}
val incrementWillChangeDumbState: Boolean = isSmart
val decrementWillChangeDumbState: Boolean = dumbCounter == 1
fun incrementDumbCounter(): DumbState = nextCounterState(dumbCounter + 1)
fun decrementDumbCounter(): DumbState = nextCounterState(dumbCounter - 1)
fun tryIncrementDumbCounter(): DumbState = if (incrementWillChangeDumbState) this else incrementDumbCounter()
fun tryDecrementDumbCounter(): DumbState = if (decrementWillChangeDumbState) this else decrementDumbCounter()
val isSmart: Boolean get() = !isDumb
}
companion object {
@JvmField
val REQUIRED_FOR_SMART_MODE_STARTUP_ACTIVITY: ExtensionPointName<RequiredForSmartMode> = ExtensionPointName(
"com.intellij.requiredForSmartModeStartupActivity")
@JvmField
val ALWAYS_SMART: Boolean = SystemProperties.getBooleanProperty("idea.no.dumb.mode", false)
private val LOG = Logger.getInstance(DumbServiceImpl::class.java)
@JvmStatic
fun getInstance(project: Project): DumbServiceImpl {
return DumbService.getInstance(project) as DumbServiceImpl
}
private fun runCatchingIgnorePCE(runnable: Runnable) {
try {
runnable.run()
}
catch (ignored: ProcessCanceledException) {
}
catch (e: Exception) {
LOG.error(e)
}
}
@JvmStatic
val isSynchronousTaskExecution: Boolean
get() {
val application = ApplicationManager.getApplication()
return (application.isUnitTestMode || isSynchronousHeadlessApplication) &&
!java.lang.Boolean.parseBoolean(System.getProperty(IDEA_FORCE_DUMB_QUEUE_TASKS, "false"))
}
/**
* Flag to force dumb tasks to work on background thread in tests or synchronous headless mode.
*/
const val IDEA_FORCE_DUMB_QUEUE_TASKS: String = "idea.force.dumb.queue.tasks"
private val isSynchronousHeadlessApplication: Boolean
get() = application.isHeadlessEnvironment && !java.lang.Boolean.getBoolean("ide.async.headless.mode")
}
}
| 251 | null | 5079 | 16,158 | 831d1a4524048aebf64173c1f0b26e04b61c6880 | 26,212 | intellij-community | Apache License 2.0 |
tests/MyGame/Example/StructOfStructsOfStructs.kt | google | 19,953,044 | false | {"C++": 3978587, "Rust": 1062705, "Python": 718341, "Swift": 654668, "Java": 622914, "C#": 595507, "JavaScript": 563679, "Kotlin": 450038, "Dart": 413224, "TypeScript": 363551, "PHP": 189050, "Go": 148114, "Nim": 98057, "Lua": 97503, "CMake": 64821, "Starlark": 53887, "Shell": 27868, "Batchfile": 2105, "C": 1364, "Ruby": 912, "Roff": 648, "Makefile": 481} | // automatically generated by the FlatBuffers compiler, do not modify
package MyGame.Example
import com.google.flatbuffers.BaseVector
import com.google.flatbuffers.BooleanVector
import com.google.flatbuffers.ByteVector
import com.google.flatbuffers.Constants
import com.google.flatbuffers.DoubleVector
import com.google.flatbuffers.FlatBufferBuilder
import com.google.flatbuffers.FloatVector
import com.google.flatbuffers.LongVector
import com.google.flatbuffers.StringVector
import com.google.flatbuffers.Struct
import com.google.flatbuffers.Table
import com.google.flatbuffers.UnionVector
import java.nio.ByteBuffer
import java.nio.ByteOrder
import kotlin.math.sign
@Suppress("unused")
class StructOfStructsOfStructs : Struct() {
fun __init(_i: Int, _bb: ByteBuffer) {
__reset(_i, _bb)
}
fun __assign(_i: Int, _bb: ByteBuffer) : StructOfStructsOfStructs {
__init(_i, _bb)
return this
}
val a : MyGame.Example.StructOfStructs? get() = a(MyGame.Example.StructOfStructs())
fun a(obj: MyGame.Example.StructOfStructs) : MyGame.Example.StructOfStructs? = obj.__assign(bb_pos + 0, bb)
companion object {
fun createStructOfStructsOfStructs(builder: FlatBufferBuilder, a_a_id: UInt, a_a_distance: UInt, a_b_a: Short, a_b_b: Byte, a_c_id: UInt, a_c_distance: UInt) : Int {
builder.prep(4, 20)
builder.prep(4, 20)
builder.prep(4, 8)
builder.putInt(a_c_distance.toInt())
builder.putInt(a_c_id.toInt())
builder.prep(2, 4)
builder.pad(1)
builder.putByte(a_b_b)
builder.putShort(a_b_a)
builder.prep(4, 8)
builder.putInt(a_a_distance.toInt())
builder.putInt(a_a_id.toInt())
return builder.offset()
}
}
}
| 171 | C++ | 3230 | 23,149 | 69a53e495d708db31c91568a781f0f1ef163fbb0 | 1,823 | flatbuffers | Apache License 2.0 |
compiler/testData/diagnostics/tests/enum/compareTwoDifferentEnums.kt | JakeWharton | 99,388,807 | false | null | // !LANGUAGE: -ProhibitComparisonOfIncompatibleEnums
// FILE: JavaEnumA.java
public enum JavaEnumA {}
// FILE: JavaEnumB.java
public enum JavaEnumB {}
// FILE: test.kt
enum class KotlinEnumA
enum class KotlinEnumB
fun jj(a: JavaEnumA, b: JavaEnumB) = <!INCOMPATIBLE_ENUM_COMPARISON!>a == b<!>
fun jk(a: JavaEnumA, b: KotlinEnumB) = <!INCOMPATIBLE_ENUM_COMPARISON!>a == b<!>
fun kk(a: KotlinEnumA, b: KotlinEnumB) = <!INCOMPATIBLE_ENUM_COMPARISON!>a == b<!>
| 181 | null | 5771 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 463 | kotlin | Apache License 2.0 |
konf-core/src/test/kotlin/com/uchuhimo/konf/source/env/EnvProviderSpec.kt | uchuhimo | 96,800,312 | false | null | /*
* Copyright 2017-2019 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 com.uchuhimo.konf.source.env
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import com.uchuhimo.konf.Config
import com.uchuhimo.konf.ConfigSpec
import kotlin.test.assertTrue
import org.jetbrains.spek.api.dsl.given
import org.jetbrains.spek.api.dsl.it
import org.jetbrains.spek.api.dsl.on
import org.jetbrains.spek.subject.SubjectSpek
import org.jetbrains.spek.subject.itBehavesLike
object EnvProviderSpec : SubjectSpek<EnvProvider>({
subject { EnvProvider }
given("a source provider") {
on("create source from system environment") {
val source = subject.env()
it("should have correct type") {
assertThat(source.info["type"], equalTo("system-environment"))
}
it("should return a source which contains value from system environment") {
val config = Config { addSpec(SourceSpec) }.withSource(source)
assertThat(config[SourceSpec.Test.type], equalTo("env"))
assertTrue { config[SourceSpec.camelCase] }
}
it("should return a case-insensitive source") {
val config = Config().withSource(source).apply { addSpec(SourceSpec) }
assertThat(config[SourceSpec.Test.type], equalTo("env"))
assertTrue { config[SourceSpec.camelCase] }
}
}
on("create flatten source from system environment") {
val source = subject.env(nested = false)
it("should return a source which contains value from system environment") {
val config = Config { addSpec(FlattenSourceSpec) }.withSource(source)
assertThat(config[FlattenSourceSpec.SOURCE_TEST_TYPE], equalTo("env"))
assertTrue { config[FlattenSourceSpec.SOURCE_CAMELCASE] }
}
}
on("create source from system environment (deprecated)") {
val source = subject.fromEnv()
it("should have correct type") {
assertThat(source.info["type"], equalTo("system-environment"))
}
it("should return a source which contains value from system environment") {
val config = Config { addSpec(SourceSpec) }.withSource(source)
assertThat(config[SourceSpec.Test.type], equalTo("env"))
assertTrue { config[SourceSpec.camelCase] }
}
it("should return a case-insensitive source") {
val config = Config().withSource(source).apply { addSpec(SourceSpec) }
assertThat(config[SourceSpec.Test.type], equalTo("env"))
assertTrue { config[SourceSpec.camelCase] }
}
}
}
})
object EnvProviderInJavaSpec : SubjectSpek<EnvProvider>({
subject { EnvProvider.get() }
itBehavesLike(EnvProviderSpec)
})
object SourceSpec : ConfigSpec() {
object Test : ConfigSpec() {
val type by required<String>()
}
val camelCase by required<Boolean>()
}
object FlattenSourceSpec : ConfigSpec("") {
val SOURCE_CAMELCASE by required<Boolean>()
val SOURCE_TEST_TYPE by required<String>()
}
| 13 | null | 23 | 294 | 8aa88358b89f7ef2b124ee608b852a18a43aac7f | 3,797 | konf | Apache License 2.0 |
components/resources/library/src/commonTest/kotlin/org/jetbrains/compose/resources/TestComposeEnvironment.kt | JetBrains | 293,498,508 | false | null | package org.jetbrains.compose.resources
import androidx.compose.runtime.Composable
@OptIn(InternalResourceApi::class)
internal fun getTestEnvironment() = ResourceEnvironment(
language = LanguageQualifier("en"),
region = RegionQualifier("US"),
theme = ThemeQualifier.LIGHT,
density = DensityQualifier.XHDPI
)
internal val TestComposeEnvironment = object : ComposeEnvironment {
@Composable
override fun rememberEnvironment() = getTestEnvironment()
} | 64 | null | 1174 | 16,150 | 7e9832f6494edf3e7967082c11417e78cfd1d9d0 | 474 | compose-multiplatform | Apache License 2.0 |
android/feature/home/src/androidTest/kotlin/com/bael/dads/feature/home/worker/factory/FakeFetchDadJokeFeedWorkerFactory.kt | ErickSumargo | 325,042,307 | false | null | package com.bael.dads.feature.home.worker.factory
import android.content.Context
import androidx.work.ListenableWorker
import androidx.work.WorkerFactory
import androidx.work.WorkerParameters
import com.bael.dads.domain.home.usecase.LoadDadJokeFeedUseCase
import com.bael.dads.domain.home.usecase.LoadDadJokeUseCase
import com.bael.dads.feature.home.notification.factory.NewFeedReminderNotificationFactory
import com.bael.dads.feature.home.worker.FetchDadJokeFeedWorker
import com.bael.dads.library.preference.Preference
import com.bael.dads.library.presentation.notification.NotificationPublisher
import javax.inject.Inject
import javax.inject.Singleton
/**
* Created by ErickSumargo on 15/05/21.
*/
@Singleton
internal class FakeFetchDadJokeFeedWorkerFactory @Inject constructor(
private val loadDadJokeUseCase: LoadDadJokeUseCase,
private val loadDadJokeFeedUseCase: LoadDadJokeFeedUseCase,
private val preference: Preference,
private val notificationPublisher: NotificationPublisher,
private val newFeedReminderNotificationFactory: NewFeedReminderNotificationFactory
) : WorkerFactory() {
override fun createWorker(
appContext: Context,
workerClassName: String,
workerParameters: WorkerParameters
): ListenableWorker {
return FetchDadJokeFeedWorker(
appContext,
workerParameters,
loadDadJokeUseCase,
loadDadJokeFeedUseCase,
preference,
notificationPublisher,
newFeedReminderNotificationFactory
)
}
}
| 1 | Kotlin | 21 | 242 | 8eb44894518e23f535a69cbe0207ad034f6a282f | 1,566 | Dads | MIT License |
Lab7/src/main/kotlin/LagrangePolynomial.kt | knu-3-velychko | 276,469,956 | false | null | class LagrangePolynomial(private val points: Array<Point>) : Method {
override val result: DoubleArray by lazy {
val size = points.size
var res = DoubleArray(size) { 0.0 }
for (i in points.indices) {
res += getCoefs(i)
}
res
}
private fun getCoefs(index: Int): DoubleArray {
var array = DoubleArray(1) { 1.0 }
var product = 1.0
for (i in points.indices) {
if (i == index) continue
val currentTerm = doubleArrayOf(1.0, -points[i].x)
product *= points[index].x - points[i].x
array *= currentTerm
}
return array * (points[index].y / product)
}
operator fun DoubleArray.plus(array: DoubleArray): DoubleArray {
val size = if (this.size > array.size) this.size else array.size
val result = DoubleArray(size) { 0.0 }
val size1 = this.size
val size2 = array.size
for (i in 1..size1) {
result[size - i] += this[size1 - i]
}
for (i in 1..size2) {
result[size - i] += array[size2 - i]
}
return result
}
}
| 0 | Kotlin | 0 | 0 | 79eaf1bfc471495bd2155b3ec5d4f4aa539d8704 | 1,160 | NumericalMethods | MIT License |
src/main/kotlin/org/jetbrains/bio/pubtrends/pm/PubmedArticle.kt | JetBrains-Research | 151,591,143 | false | {"Jupyter Notebook": 4174293, "Python": 401387, "HTML": 234375, "Kotlin": 122006, "JavaScript": 9805, "Dockerfile": 5181, "CSS": 3252, "Shell": 2620} | package org.jetbrains.bio.pubtrends.pm
data class Author(
val name: String = "",
val affiliation: List<String> = listOf()
)
data class Journal(val name: String = "")
data class DatabankEntry(
val name: String = "",
val accessionNumber: List<String> = listOf()
)
data class AuxInfo(
val authors: List<Author> = listOf(),
val databanks: List<DatabankEntry> = listOf(),
val journal: Journal = Journal(),
val language: String = ""
)
enum class PublicationType {
ClinicalTrial,
Dataset,
TechnicalReport,
Review,
Article
}
data class PubmedArticle(
val pmid: Int = 0,
val title: String = "",
val abstract: String = "",
val year: Int = 1970,
val type: PublicationType = PublicationType.Article,
val keywords: List<String> = listOf(),
val mesh: List<String> = listOf(),
val doi: String = "",
val aux: AuxInfo = AuxInfo(),
val citations: List<Int> = listOf()
) | 44 | Jupyter Notebook | 2 | 29 | c400fb031e35c6c95a3a4b3bf98c108303e199d8 | 949 | pubtrends | Apache License 2.0 |
jvm-debugger/coroutines/src/org/jetbrains/kotlin/idea/debugger/coroutine/proxy/mirror/evaluator.kt | JetBrains | 278,369,660 | false | null | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.debugger.coroutine.proxy.mirror
import com.sun.jdi.*
import org.jetbrains.kotlin.idea.debugger.evaluate.DefaultExecutionContext
import java.lang.IllegalArgumentException
sealed class MethodEvaluator<T>(val method: Method?) {
fun value(value: ObjectReference?, context: DefaultExecutionContext, vararg values: Value): T? {
return method?.let {
return when {
method.isStatic -> {
// pass extension methods like the usual ones.
val args = if (value != null) {
listOf(value) + values.toList()
} else
values.toList()
@Suppress("UNCHECKED_CAST")
context.invokeMethod(method.declaringType() as ClassType, method, args) as T?
}
value != null ->
@Suppress("UNCHECKED_CAST")
context.invokeMethod(value, method, values.toList()) as T?
else -> throw IllegalArgumentException("Exception while calling method " + method.signature() + " with an empty value.")
}
}
}
class DefaultMethodEvaluator<T>(method: Method?) : MethodEvaluator<T>(method)
class MirrorMethodEvaluator<T, F>(method: Method?, private val mirrorProvider: MirrorProvider<T, F>): MethodEvaluator<T>(method) {
fun mirror(ref: ObjectReference, context: DefaultExecutionContext, vararg values: Value): F? {
return mirrorProvider.mirror(value(ref, context, *values), context)
}
fun isCompatible(value: T) = mirrorProvider.isCompatible(value)
}
}
sealed class FieldEvaluator<T>(val field: Field?, val thisRef: ReferenceTypeProvider) {
@Suppress("UNCHECKED_CAST")
fun value(value: ObjectReference): T? =
field?.let { value.getValue(it) as T? }
@Suppress("UNCHECKED_CAST")
fun staticValue(): T? = thisRef.getCls().let { it.getValue(field) as? T }
class DefaultFieldEvaluator<T>(field: Field?, thisRef: ReferenceTypeProvider) : FieldEvaluator<T>(field, thisRef)
class MirrorFieldEvaluator<T, F>(field: Field?, thisRef: ReferenceTypeProvider, private val mirrorProvider: MirrorProvider<T, F>) : FieldEvaluator<T>(field, thisRef) {
fun mirror(ref: ObjectReference, context: DefaultExecutionContext): F? =
mirrorProvider.mirror(value(ref), context)
fun mirrorOnly(value: T, context: DefaultExecutionContext) = mirrorProvider.mirror(value, context)
fun isCompatible(value: T) = mirrorProvider.isCompatible(value)
}
}
| 284 | null | 5162 | 82 | cc81d7505bc3e9ad503d706998ae8026c067e838 | 2,762 | intellij-kotlin | Apache License 2.0 |
domain/src/main/kotlin/studio/lunabee/onesafe/domain/usecase/authentication/ChangePasswordUseCase.kt | LunabeeStudio | 624,544,471 | false | {"Kotlin": 2733174, "Java": 11977, "Python": 3979} | /*
* Copyright (c) 2023 Lunabee Studio
*
* 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.
*
* Created by Lunabee Studio / Date - 4/7/2023 - for the oneSafe6 SDK.
* Last modified 4/7/23, 12:24 AM
*/
package studio.lunabee.onesafe.domain.usecase.authentication
import com.lunabee.lbcore.model.LBResult
import com.lunabee.lblogger.LBLogger
import studio.lunabee.onesafe.domain.model.safe.SafeCrypto
import studio.lunabee.onesafe.domain.repository.EditCryptoRepository
import studio.lunabee.onesafe.domain.repository.SafeItemKeyRepository
import studio.lunabee.onesafe.domain.repository.SafeRepository
import studio.lunabee.onesafe.domain.repository.StorageManager
import studio.lunabee.onesafe.domain.usecase.settings.SetSecuritySettingUseCase
import studio.lunabee.onesafe.error.OSError
import studio.lunabee.onesafe.use
import javax.inject.Inject
private val log = LBLogger.get<ChangePasswordUseCase>()
class ChangePasswordUseCase @Inject constructor(
private val safeItemKeyRepository: SafeItemKeyRepository,
private val editCryptoRepository: EditCryptoRepository,
private val transactionManager: StorageManager,
private val setSecuritySettingUseCase: SetSecuritySettingUseCase,
private val safeRepository: SafeRepository,
) {
suspend operator fun invoke(newPassword: CharArray): LBResult<Unit> = OSError.runCatching(logger = log) {
newPassword.use {
editCryptoRepository.generateCryptographicData(newPassword)
}
val safeId = safeRepository.currentSafeId()
transactionManager.withTransaction {
val keys = safeItemKeyRepository.getAllSafeItemKeys(safeId)
editCryptoRepository.reEncryptItemKeys(keys)
safeItemKeyRepository.update(keys)
val cryptoSafe = editCryptoRepository.overrideMainCryptographicData(safeId)
val safeCrypto = SafeCrypto(
id = safeId,
salt = cryptoSafe.salt,
encTest = cryptoSafe.encTest,
encIndexKey = cryptoSafe.encIndexKey,
encBubblesKey = cryptoSafe.encBubblesKey,
encItemEditionKey = cryptoSafe.encItemEditionKey,
biometricCryptoMaterial = null,
)
safeRepository.updateSafeCrypto(safeCrypto = safeCrypto)
setSecuritySettingUseCase.setLastPasswordVerification(currentSafeId = safeId)
}
}
}
| 0 | Kotlin | 1 | 2 | a34f0ddaf9dc649c2f2082dc2526921bb1a491df | 2,913 | oneSafe6_SDK_Android | Apache License 2.0 |
GeneralLedger/app/src/main/java/com/ideahamster/generalledger/data/network/NetworkModule.kt | sridharnalam | 613,153,998 | false | null | package com.ideahamster.generalledger.data.network
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import javax.inject.Named
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object NetworkModule {
private const val BASE_URL = "https://take-home-test-api.herokuapp.com"
@Singleton
@Provides
fun provideOkHttp(@Named("loggingInterceptor") httpLoggingInterceptor: HttpLoggingInterceptor): OkHttpClient {
return OkHttpClient.Builder()
.addInterceptor(httpLoggingInterceptor)
.build()
}
@Singleton
@Provides
@Named("loggingInterceptor")
fun provideLoggingInterceptor(): HttpLoggingInterceptor {
return HttpLoggingInterceptor().apply {
this.level = HttpLoggingInterceptor.Level.BODY
}
}
@Provides
fun provideRetrofit(okHttpClient: OkHttpClient): Retrofit {
return Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient)
.build()
}
@Provides
fun provideLedgerApiService(retrofit: Retrofit): LedgerApiService {
return retrofit.create(LedgerApiService::class.java)
}
} | 0 | Kotlin | 0 | 0 | f0977938f94975252ee71289309570efb54ab86b | 1,464 | GeneralLedger | Apache License 2.0 |
platform/diff-impl/tests/com/intellij/diff/comparison/ComparisonUtilAutoTest.kt | androidports | 115,100,208 | false | null | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.diff.comparison
import com.intellij.diff.DiffTestCase
import com.intellij.diff.HeavyDiffTestCase
import com.intellij.diff.fragments.DiffFragment
import com.intellij.diff.fragments.LineFragment
import com.intellij.diff.fragments.MergeLineFragment
import com.intellij.diff.fragments.MergeWordFragment
import com.intellij.diff.tools.util.base.HighlightPolicy
import com.intellij.diff.tools.util.base.IgnorePolicy
import com.intellij.diff.util.DiffUtil
import com.intellij.diff.util.Range
import com.intellij.diff.util.ThreeSide
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.impl.DocumentImpl
import com.intellij.openapi.util.Couple
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vcs.ex.createRanges
class ComparisonUtilAutoTest : HeavyDiffTestCase() {
val RUNS = 30
val MAX_LENGTH = 300
fun testChar() {
doTestChar(System.currentTimeMillis(), RUNS, MAX_LENGTH)
}
fun testWord() {
doTestWord(System.currentTimeMillis(), RUNS, MAX_LENGTH)
}
fun testLine() {
doTestLine(System.currentTimeMillis(), RUNS, MAX_LENGTH)
}
fun testLineSquashed() {
doTestLineSquashed(System.currentTimeMillis(), RUNS, MAX_LENGTH)
}
fun testLineTrimSquashed() {
doTestLineTrimSquashed(System.currentTimeMillis(), RUNS, MAX_LENGTH)
}
fun testExplicitBlocks() {
doTestExplicitBlocks(System.currentTimeMillis(), RUNS, MAX_LENGTH)
}
fun testMerge() {
doTestMerge(System.currentTimeMillis(), RUNS, MAX_LENGTH)
}
private fun doTestLine(seed: Long, runs: Int, maxLength: Int) {
val policies = listOf(ComparisonPolicy.DEFAULT, ComparisonPolicy.TRIM_WHITESPACES, ComparisonPolicy.IGNORE_WHITESPACES)
doTest(seed, runs, maxLength, policies) { text1, text2, policy, debugData ->
val sequence1 = text1.charsSequence
val sequence2 = text2.charsSequence
val fragments = MANAGER.compareLinesInner(sequence1, sequence2, policy, INDICATOR)
debugData.put("Fragments", fragments)
checkResultLine(text1, text2, fragments, policy, true)
}
}
private fun doTestLineSquashed(seed: Long, runs: Int, maxLength: Int) {
val policies = listOf(ComparisonPolicy.DEFAULT, ComparisonPolicy.TRIM_WHITESPACES, ComparisonPolicy.IGNORE_WHITESPACES)
doTest(seed, runs, maxLength, policies) { text1, text2, policy, debugData ->
val sequence1 = text1.charsSequence
val sequence2 = text2.charsSequence
val fragments = MANAGER.compareLinesInner(sequence1, sequence2, policy, INDICATOR)
debugData.put("Fragments", fragments)
val squashedFragments = MANAGER.squash(fragments)
debugData.put("Squashed Fragments", squashedFragments)
checkResultLine(text1, text2, squashedFragments, policy, false)
}
}
private fun doTestLineTrimSquashed(seed: Long, runs: Int, maxLength: Int) {
val policies = listOf(ComparisonPolicy.DEFAULT, ComparisonPolicy.TRIM_WHITESPACES, ComparisonPolicy.IGNORE_WHITESPACES)
doTest(seed, runs, maxLength, policies) { text1, text2, policy, debugData ->
val sequence1 = text1.charsSequence
val sequence2 = text2.charsSequence
val fragments = MANAGER.compareLinesInner(sequence1, sequence2, policy, INDICATOR)
debugData.put("Fragments", fragments)
val processed = MANAGER.processBlocks(fragments, sequence1, sequence2, policy, true, true)
debugData.put("Processed Fragments", processed)
checkResultLine(text1, text2, processed, policy, false)
}
}
private fun doTestChar(seed: Long, runs: Int, maxLength: Int) {
val policies = listOf(ComparisonPolicy.DEFAULT, ComparisonPolicy.IGNORE_WHITESPACES)
doTest(seed, runs, maxLength, policies) { text1, text2, policy, debugData ->
val sequence1 = text1.charsSequence
val sequence2 = text2.charsSequence
val fragments = MANAGER.compareChars(sequence1, sequence2, policy, INDICATOR)
debugData.put("Fragments", fragments)
checkResultChar(sequence1, sequence2, fragments, policy)
}
}
private fun doTestWord(seed: Long, runs: Int, maxLength: Int) {
val policies = listOf(ComparisonPolicy.DEFAULT, ComparisonPolicy.TRIM_WHITESPACES, ComparisonPolicy.IGNORE_WHITESPACES)
doTest(seed, runs, maxLength, policies) { text1, text2, policy, debugData ->
val sequence1 = text1.charsSequence
val sequence2 = text2.charsSequence
val fragments = MANAGER.compareWords(sequence1, sequence2, policy, INDICATOR)
debugData.put("Fragments", fragments)
checkResultWord(sequence1, sequence2, fragments, policy)
}
}
private fun doTestExplicitBlocks(seed: Long, runs: Int, maxLength: Int) {
val ignorePolicies = listOf(IgnorePolicy.DEFAULT, IgnorePolicy.TRIM_WHITESPACES, IgnorePolicy.IGNORE_WHITESPACES, IgnorePolicy.IGNORE_WHITESPACES_CHUNKS)
val highlightPolicies = listOf(HighlightPolicy.BY_LINE, HighlightPolicy.BY_WORD, HighlightPolicy.BY_WORD_SPLIT)
doTest(seed, runs, maxLength) { text1, text2, debugData ->
for (highlightPolicy in highlightPolicies) {
for (ignorePolicy in ignorePolicies) {
debugData.put("HighlightPolicy", highlightPolicy)
debugData.put("IgnorePolicy", ignorePolicy)
val sequence1 = text1.charsSequence
val sequence2 = text2.charsSequence
val ranges = createRanges(sequence2, sequence1).map { Range(it.vcsLine1, it.vcsLine2, it.line1, it.line2) }
debugData.put("Ranges", ranges)
val fragments = compareExplicitBlocks(sequence1, sequence2, ranges, highlightPolicy, ignorePolicy)
debugData.put("Fragments", fragments)
checkResultLine(text1, text2, fragments, ignorePolicy.comparisonPolicy, !highlightPolicy.isShouldSquash)
}
}
}
}
private fun doTestMerge(seed: Long, runs: Int, maxLength: Int) {
val policies = listOf(ComparisonPolicy.DEFAULT, ComparisonPolicy.TRIM_WHITESPACES, ComparisonPolicy.IGNORE_WHITESPACES)
doTest3(seed, runs, maxLength, policies) { text1, text2, text3, policy, debugData ->
val sequence1 = text1.charsSequence
val sequence2 = text2.charsSequence
val sequence3 = text3.charsSequence
val fragments = MANAGER.compareLines(sequence1, sequence2, sequence3, policy, INDICATOR)
val fineFragments = fragments.map { f ->
val chunk1 = DiffUtil.getLinesContent(text1, f.startLine1, f.endLine1)
val chunk2 = DiffUtil.getLinesContent(text2, f.startLine2, f.endLine2)
val chunk3 = DiffUtil.getLinesContent(text3, f.startLine3, f.endLine3)
val wordFragments = ByWord.compare(chunk1, chunk2, chunk3, policy, INDICATOR)
Pair(f, wordFragments)
}
debugData.put("Fragments", fineFragments)
checkResultMerge(text1, text2, text3, fineFragments, policy)
}
}
private fun doTest(seed: Long, runs: Int, maxLength: Int, policies: List<ComparisonPolicy>,
test: (Document, Document, ComparisonPolicy, DiffTestCase.DebugData) -> Unit) {
doTest(seed, runs, maxLength) { text1, text2, debugData ->
for (comparisonPolicy in policies) {
debugData.put("Policy", comparisonPolicy)
test(text1, text2, comparisonPolicy, debugData)
}
}
}
private fun doTest(seed: Long, runs: Int, maxLength: Int,
test: (Document, Document, DiffTestCase.DebugData) -> Unit) {
doAutoTest(seed, runs) { debugData ->
debugData.put("MaxLength", maxLength)
val text1 = DocumentImpl(generateText(maxLength))
val text2 = DocumentImpl(generateText(maxLength))
debugData.put("Text1", textToReadableFormat(text1.charsSequence))
debugData.put("Text2", textToReadableFormat(text2.charsSequence))
test(text1, text2, debugData)
}
}
private fun doTest3(seed: Long, runs: Int, maxLength: Int, policies: List<ComparisonPolicy>,
test: (Document, Document, Document, ComparisonPolicy, DiffTestCase.DebugData) -> Unit) {
doAutoTest(seed, runs) { debugData ->
debugData.put("MaxLength", maxLength)
val text1 = DocumentImpl(generateText(maxLength))
val text2 = DocumentImpl(generateText(maxLength))
val text3 = DocumentImpl(generateText(maxLength))
debugData.put("Text1", textToReadableFormat(text1.charsSequence))
debugData.put("Text2", textToReadableFormat(text2.charsSequence))
debugData.put("Text3", textToReadableFormat(text3.charsSequence))
for (comparisonPolicy in policies) {
debugData.put("Policy", comparisonPolicy)
test(text1, text2, text2, comparisonPolicy, debugData)
}
}
}
private fun checkResultLine(text1: Document, text2: Document, fragments: List<LineFragment>, policy: ComparisonPolicy, allowNonSquashed: Boolean) {
checkLineConsistency(text1, text2, fragments, allowNonSquashed)
for (fragment in fragments) {
if (fragment.innerFragments != null) {
val sequence1 = text1.subSequence(fragment.startOffset1, fragment.endOffset1)
val sequence2 = text2.subSequence(fragment.startOffset2, fragment.endOffset2)
checkResultWord(sequence1, sequence2, fragment.innerFragments!!, policy)
}
}
checkValidRanges(text1.charsSequence, text2.charsSequence, fragments, policy, true)
checkCantTrimLines(text1, text2, fragments, policy, allowNonSquashed)
}
private fun checkResultWord(text1: CharSequence, text2: CharSequence, fragments: List<DiffFragment>, policy: ComparisonPolicy) {
checkDiffConsistency(fragments)
checkValidRanges(text1, text2, fragments, policy, false)
}
private fun checkResultChar(text1: CharSequence, text2: CharSequence, fragments: List<DiffFragment>, policy: ComparisonPolicy) {
checkDiffConsistency(fragments)
checkValidRanges(text1, text2, fragments, policy, false)
}
private fun checkResultMerge(text1: Document,
text2: Document,
text3: Document,
fragments: List<Pair<MergeLineFragment, List<MergeWordFragment>>>,
policy: ComparisonPolicy) {
val lineFragments = fragments.map { it.first }
checkLineConsistency3(text1, text2, text3, lineFragments)
checkValidRanges3(text1, text2, text3, lineFragments, policy)
checkCantTrimLines3(text1, text2, text3, lineFragments, policy)
for (pair in fragments) {
val f = pair.first
val innerFragments = pair.second
val chunk1 = DiffUtil.getLinesContent(text1, f.startLine1, f.endLine1)
val chunk2 = DiffUtil.getLinesContent(text2, f.startLine2, f.endLine2)
val chunk3 = DiffUtil.getLinesContent(text3, f.startLine3, f.endLine3)
checkDiffConsistency3(innerFragments)
checkValidRanges3(chunk1, chunk2, chunk3, innerFragments, policy)
}
}
private fun checkLineConsistency(text1: Document, text2: Document, fragments: List<LineFragment>, allowNonSquashed: Boolean) {
var last1 = -1
var last2 = -1
for (fragment in fragments) {
val startOffset1 = fragment.startOffset1
val startOffset2 = fragment.startOffset2
val endOffset1 = fragment.endOffset1
val endOffset2 = fragment.endOffset2
val start1 = fragment.startLine1
val start2 = fragment.startLine2
val end1 = fragment.endLine1
val end2 = fragment.endLine2
assertTrue(startOffset1 >= 0)
assertTrue(startOffset2 >= 0)
assertTrue(endOffset1 <= text1.textLength)
assertTrue(endOffset2 <= text2.textLength)
assertTrue(start1 >= 0)
assertTrue(start2 >= 0)
assertTrue(end1 <= getLineCount(text1))
assertTrue(end2 <= getLineCount(text2))
assertTrue(startOffset1 <= endOffset1)
assertTrue(startOffset2 <= endOffset2)
assertTrue(start1 <= end1)
assertTrue(start2 <= end2)
assertTrue(start1 != end1 || start2 != end2)
assertTrue(allowNonSquashed || start1 != last1 || start2 != last2)
checkLineOffsets(fragment, text1, text2)
last1 = end1
last2 = end2
}
}
private fun checkLineConsistency3(text1: Document, text2: Document, text3: Document, fragments: List<MergeLineFragment>) {
var last1 = -1
var last2 = -1
var last3 = -1
for (fragment in fragments) {
val start1 = fragment.startLine1
val start2 = fragment.startLine2
val start3 = fragment.startLine3
val end1 = fragment.endLine1
val end2 = fragment.endLine2
val end3 = fragment.endLine3
assertTrue(start1 >= 0)
assertTrue(start2 >= 0)
assertTrue(start3 >= 0)
assertTrue(end1 <= getLineCount(text1))
assertTrue(end2 <= getLineCount(text2))
assertTrue(end3 <= getLineCount(text3))
assertTrue(start1 <= end1)
assertTrue(start2 <= end2)
assertTrue(start3 <= end3)
assertTrue(start1 != end1 || start2 != end2 || start3 != end3)
assertTrue(start1 != last1 || start2 != last2 || start3 != last3)
last1 = end1
last2 = end2
last3 = end3
}
}
private fun checkDiffConsistency(fragments: List<DiffFragment>) {
var last1 = -1
var last2 = -1
for (diffFragment in fragments) {
val start1 = diffFragment.startOffset1
val start2 = diffFragment.startOffset2
val end1 = diffFragment.endOffset1
val end2 = diffFragment.endOffset2
assertTrue(start1 <= end1)
assertTrue(start2 <= end2)
assertTrue(start1 != end1 || start2 != end2)
assertTrue(start1 != last1 || start2 != last2)
last1 = end1
last2 = end2
}
}
private fun checkDiffConsistency3(fragments: List<MergeWordFragment>) {
var last1 = -1
var last2 = -1
var last3 = -1
for (diffFragment in fragments) {
val start1 = diffFragment.startOffset1
val start2 = diffFragment.startOffset2
val start3 = diffFragment.startOffset3
val end1 = diffFragment.endOffset1
val end2 = diffFragment.endOffset2
val end3 = diffFragment.endOffset3
assertTrue(start1 <= end1)
assertTrue(start2 <= end2)
assertTrue(start3 <= end3)
assertTrue(start1 != end1 || start2 != end2 || start3 != end3)
assertTrue(start1 != last1 || start2 != last2 || start3 != last3)
last1 = end1
last2 = end2
last3 = end3
}
}
private fun checkLineOffsets(fragment: LineFragment, before: Document, after: Document) {
checkLineOffsets(before, fragment.startLine1, fragment.endLine1, fragment.startOffset1, fragment.endOffset1)
checkLineOffsets(after, fragment.startLine2, fragment.endLine2, fragment.startOffset2, fragment.endOffset2)
}
private fun checkLineOffsets(document: Document, startLine: Int, endLine: Int, startOffset: Int, endOffset: Int) {
if (startLine != endLine) {
assertEquals(document.getLineStartOffset(startLine), startOffset)
var offset = document.getLineEndOffset(endLine - 1)
if (offset < document.textLength) offset++
assertEquals(offset, endOffset)
}
else {
val offset = if (startLine == getLineCount(document))
document.textLength
else
document.getLineStartOffset(startLine)
assertEquals(offset, startOffset)
assertEquals(offset, endOffset)
}
}
private fun checkValidRanges(text1: CharSequence, text2: CharSequence, fragments: List<DiffFragment>, policy: ComparisonPolicy, skipNewline: Boolean) {
// TODO: better check for Trim spaces case ?
val ignoreSpacesUnchanged = policy != ComparisonPolicy.DEFAULT
val ignoreSpacesChanged = policy == ComparisonPolicy.IGNORE_WHITESPACES
var last1 = 0
var last2 = 0
for (fragment in fragments) {
val start1 = fragment.startOffset1
val start2 = fragment.startOffset2
val end1 = fragment.endOffset1
val end2 = fragment.endOffset2
val chunk1 = text1.subSequence(last1, start1)
val chunk2 = text2.subSequence(last2, start2)
assertEqualsCharSequences(chunk1, chunk2, ignoreSpacesUnchanged, skipNewline)
val chunkContent1 = text1.subSequence(start1, end1)
val chunkContent2 = text2.subSequence(start2, end2)
if (!skipNewline) {
assertNotEqualsCharSequences(chunkContent1, chunkContent2, ignoreSpacesChanged, skipNewline)
}
last1 = fragment.endOffset1
last2 = fragment.endOffset2
}
val chunk1 = text1.subSequence(last1, text1.length)
val chunk2 = text2.subSequence(last2, text2.length)
assertEqualsCharSequences(chunk1, chunk2, ignoreSpacesUnchanged, skipNewline)
}
private fun checkValidRanges3(text1: Document, text2: Document, text3: Document, fragments: List<MergeLineFragment>, policy: ComparisonPolicy) {
val ignoreSpaces = policy != ComparisonPolicy.DEFAULT
var last1 = 0
var last2 = 0
var last3 = 0
for (fragment in fragments) {
val start1 = fragment.startLine1
val start2 = fragment.startLine2
val start3 = fragment.startLine3
val content1 = DiffUtil.getLinesContent(text1, last1, start1)
val content2 = DiffUtil.getLinesContent(text2, last2, start2)
val content3 = DiffUtil.getLinesContent(text3, last3, start3)
assertEqualsCharSequences(content2, content1, ignoreSpaces, false)
assertEqualsCharSequences(content2, content3, ignoreSpaces, false)
last1 = fragment.endLine1
last2 = fragment.endLine2
last3 = fragment.endLine3
}
val content1 = DiffUtil.getLinesContent(text1, last1, getLineCount(text1))
val content2 = DiffUtil.getLinesContent(text2, last2, getLineCount(text2))
val content3 = DiffUtil.getLinesContent(text3, last3, getLineCount(text3))
assertEqualsCharSequences(content2, content1, ignoreSpaces, false)
assertEqualsCharSequences(content2, content3, ignoreSpaces, false)
}
private fun checkValidRanges3(text1: CharSequence, text2: CharSequence, text3: CharSequence, fragments: List<MergeWordFragment>, policy: ComparisonPolicy) {
val ignoreSpacesUnchanged = policy != ComparisonPolicy.DEFAULT
val ignoreSpacesChanged = policy == ComparisonPolicy.IGNORE_WHITESPACES
var last1 = 0
var last2 = 0
var last3 = 0
for (fragment in fragments) {
val start1 = fragment.startOffset1
val start2 = fragment.startOffset2
val start3 = fragment.startOffset3
val end1 = fragment.endOffset1
val end2 = fragment.endOffset2
val end3 = fragment.endOffset3
val content1 = text1.subSequence(last1, start1)
val content2 = text2.subSequence(last2, start2)
val content3 = text3.subSequence(last3, start3)
assertEqualsCharSequences(content2, content1, ignoreSpacesUnchanged, false)
assertEqualsCharSequences(content2, content3, ignoreSpacesUnchanged, false)
val chunkContent1 = text1.subSequence(start1, end1)
val chunkContent2 = text2.subSequence(start2, end2)
val chunkContent3 = text3.subSequence(start3, end3)
assertFalse(isEqualsCharSequences(chunkContent2, chunkContent1, ignoreSpacesChanged) &&
isEqualsCharSequences(chunkContent2, chunkContent3, ignoreSpacesChanged))
last1 = fragment.endOffset1
last2 = fragment.endOffset2
last3 = fragment.endOffset3
}
val content1 = text1.subSequence(last1, text1.length)
val content2 = text2.subSequence(last2, text2.length)
val content3 = text3.subSequence(last3, text3.length)
assertEqualsCharSequences(content2, content1, ignoreSpacesUnchanged, false)
assertEqualsCharSequences(content2, content3, ignoreSpacesUnchanged, false)
}
private fun checkCantTrimLines(text1: Document, text2: Document, fragments: List<LineFragment>, policy: ComparisonPolicy, allowNonSquashed: Boolean) {
for (fragment in fragments) {
val sequence1 = getFirstLastLines(text1, fragment.startLine1, fragment.endLine1)
val sequence2 = getFirstLastLines(text2, fragment.startLine2, fragment.endLine2)
if (sequence1 == null || sequence2 == null) continue
checkNonEqualsIfLongEnough(sequence1.first, sequence2.first, policy, allowNonSquashed)
checkNonEqualsIfLongEnough(sequence1.second, sequence2.second, policy, allowNonSquashed)
}
}
private fun checkCantTrimLines3(text1: Document, text2: Document, text3: Document, fragments: List<MergeLineFragment>, policy: ComparisonPolicy) {
for (fragment in fragments) {
val sequence1 = getFirstLastLines(text1, fragment.startLine1, fragment.endLine1)
val sequence2 = getFirstLastLines(text2, fragment.startLine2, fragment.endLine2)
val sequence3 = getFirstLastLines(text3, fragment.startLine3, fragment.endLine3)
if (sequence1 == null || sequence2 == null || sequence3 == null) continue
assertFalse(MANAGER.isEquals(sequence2.first, sequence1.first, policy) && MANAGER.isEquals(sequence2.first, sequence3.first, policy))
assertFalse(MANAGER.isEquals(sequence2.second, sequence1.second, policy) && MANAGER.isEquals(sequence2.second, sequence3.second, policy))
}
}
private fun checkNonEqualsIfLongEnough(line1: CharSequence, line2: CharSequence, policy: ComparisonPolicy, allowNonSquashed: Boolean) {
// in non-squashed blocks non-trimmed elements are possible
if (allowNonSquashed) {
if (policy != ComparisonPolicy.IGNORE_WHITESPACES) return
if (countNonWhitespaceCharacters(line1) <= ComparisonUtil.getUnimportantLineCharCount()) return
if (countNonWhitespaceCharacters(line2) <= ComparisonUtil.getUnimportantLineCharCount()) return
}
assertFalse(MANAGER.isEquals(line1, line2, policy))
}
private fun countNonWhitespaceCharacters(line: CharSequence): Int {
return (0 until line.length).count { !StringUtil.isWhiteSpace(line[it]) }
}
private fun getFirstLastLines(text: Document, start: Int, end: Int): Couple<CharSequence>? {
if (start == end) return null
val firstLineRange = DiffUtil.getLinesRange(text, start, start + 1)
val lastLineRange = DiffUtil.getLinesRange(text, end - 1, end)
val firstLine = firstLineRange.subSequence(text.charsSequence)
val lastLine = lastLineRange.subSequence(text.charsSequence)
return Couple.of(firstLine, lastLine)
}
private fun Document.subSequence(start: Int, end: Int): CharSequence {
return this.charsSequence.subSequence(start, end)
}
private val MergeLineFragment.startLine1: Int get() = this.getStartLine(ThreeSide.LEFT)
private val MergeLineFragment.startLine2: Int get() = this.getStartLine(ThreeSide.BASE)
private val MergeLineFragment.startLine3: Int get() = this.getStartLine(ThreeSide.RIGHT)
private val MergeLineFragment.endLine1: Int get() = this.getEndLine(ThreeSide.LEFT)
private val MergeLineFragment.endLine2: Int get() = this.getEndLine(ThreeSide.BASE)
private val MergeLineFragment.endLine3: Int get() = this.getEndLine(ThreeSide.RIGHT)
private val MergeWordFragment.startOffset1: Int get() = this.getStartOffset(ThreeSide.LEFT)
private val MergeWordFragment.startOffset2: Int get() = this.getStartOffset(ThreeSide.BASE)
private val MergeWordFragment.startOffset3: Int get() = this.getStartOffset(ThreeSide.RIGHT)
private val MergeWordFragment.endOffset1: Int get() = this.getEndOffset(ThreeSide.LEFT)
private val MergeWordFragment.endOffset2: Int get() = this.getEndOffset(ThreeSide.BASE)
private val MergeWordFragment.endOffset3: Int get() = this.getEndOffset(ThreeSide.RIGHT)
}
| 6 | null | 4829 | 4 | 6e4f7135c5843ed93c15a9782f29e4400df8b068 | 24,015 | intellij-community | Apache License 2.0 |
oauth/src/main/java/com/lightspark/sdk/auth/oauth/OAuthHelper.kt | lightsparkdev | 590,703,408 | false | {"Kotlin": 1705939, "Java": 34937, "Dockerfile": 1719, "Shell": 490} | package com.lightspark.sdk.auth.oauth
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.net.Uri
import com.lightspark.sdk.core.requester.ServerEnvironment
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlinx.coroutines.suspendCancellableCoroutine
import net.openid.appauth.AuthState
import net.openid.appauth.AuthorizationException
import net.openid.appauth.AuthorizationRequest
import net.openid.appauth.AuthorizationResponse
import net.openid.appauth.AuthorizationService
import net.openid.appauth.AuthorizationServiceConfiguration
import net.openid.appauth.EndSessionRequest
import net.openid.appauth.EndSessionResponse
import net.openid.appauth.ResponseTypeValues
class OAuthHelper(
context: Context,
private val OAuthStateStorage: OAuthStateStorage = SharedPrefsOAuthStateStorage(context),
private var serverEnvironment: ServerEnvironment = ServerEnvironment.DEV,
) {
private val authService = AuthorizationService(context.applicationContext)
private val authState: AuthState
get() = OAuthStateStorage.getCurrent()
init {
val savedAuthState = OAuthStateStorage.getCurrent()
if (savedAuthState.authorizationServiceConfiguration == null) {
OAuthStateStorage.replace(defaultAuthState())
}
}
private fun defaultAuthState(): AuthState {
val serviceConfig = when (serverEnvironment) {
ServerEnvironment.DEV -> AuthorizationServiceConfiguration(
Uri.parse("https://dev.dev.sparkinfra.net/oauth/authorize"),
Uri.parse("https://api.dev.dev.sparkinfra.net/oauth/token"),
)
ServerEnvironment.PROD -> AuthorizationServiceConfiguration(
Uri.parse("https://app.lightspark.com/oauth/authorize"),
Uri.parse("https://api.lightspark.com/oauth/token"),
)
}
return AuthState(serviceConfig)
}
fun setServerEnvironment(environment: ServerEnvironment): Boolean {
if (serverEnvironment == environment) return false
serverEnvironment = environment
if (OAuthStateStorage.getCurrent().authorizationServiceConfiguration?.authorizationEndpoint !=
defaultAuthState().authorizationServiceConfiguration?.authorizationEndpoint
) {
OAuthStateStorage.replace(defaultAuthState())
return true
}
return false
}
fun isAuthorized() = authState.isAuthorized
fun launchAuthFlow(
clientId: String,
redirectUri: String,
completedIntent: PendingIntent,
canceledIntent: PendingIntent? = null,
) {
val authRequest = AuthorizationRequest.Builder(
requireNotNull(authState.authorizationServiceConfiguration) {
"Authorization service configuration is null"
},
clientId,
ResponseTypeValues.CODE,
Uri.parse(redirectUri),
)
.setScope("all") // TODO: Replace with actual scopes as needed
.build()
authService.performAuthorizationRequest(
authRequest,
completedIntent,
canceledIntent ?: completedIntent,
)
}
fun handleAuthResponseAndRequestToken(
response: Intent,
clientSecret: String,
callback: (String?, Exception?) -> Unit,
) {
try {
handleAuthResponse(response)
} catch (e: Exception) {
callback(null, e)
return
}
fetchAndPersistRefreshToken(clientSecret, callback)
}
fun handleAuthResponse(intent: Intent) {
val response = AuthorizationResponse.fromIntent(intent)
val ex = AuthorizationException.fromIntent(intent)
OAuthStateStorage.updateAfterAuthorization(response, ex)
if (response == null) {
throw ex ?: IllegalStateException("Authorization response is null")
}
}
fun fetchAndPersistRefreshToken(
clientSecret: String,
callback: (String?, Exception?) -> Unit,
) {
val authorizationResponse = requireNotNull(authState.lastAuthorizationResponse) {
"Authorization response is null. Call handleAuthResponse() first."
}
authService.performTokenRequest(
authorizationResponse.createTokenExchangeRequest(),
OAuthCustomClientAuthentication(clientSecret),
) { response, exception ->
OAuthStateStorage.updateAfterTokenResponse(response, exception)
callback(response?.refreshToken, exception)
}
}
fun withAuthToken(block: (String, String) -> Unit) {
authState.performActionWithFreshTokens(authService) { accessToken, idToken, ex ->
OAuthStateStorage.replace(authState)
if (accessToken != null) {
block(
accessToken,
requireNotNull(idToken) { "ID token is null when access token is not" },
)
} else {
throw ex ?: IllegalStateException("Authorization response is null")
}
}
}
suspend fun getFreshAuthToken(): String {
return suspendCancellableCoroutine { continuation ->
authState.performActionWithFreshTokens(authService) { accessToken, _, ex ->
OAuthStateStorage.replace(authState)
if (accessToken != null) {
continuation.resume(accessToken)
} else {
continuation.resumeWithException(
ex ?: IllegalStateException("Authorization response is null"),
)
}
}
}
}
fun endSession(
completedIntent: PendingIntent,
redirectUri: String? = null,
canceledIntent: PendingIntent? = null,
) {
val serviceConfig = authState.authorizationServiceConfiguration ?: return
val endSessionRequest = EndSessionRequest.Builder(serviceConfig)
.setIdTokenHint(authState.idToken)
.setPostLogoutRedirectUri(redirectUri.let { Uri.parse(it) })
.build()
authService.performEndSessionRequest(
endSessionRequest,
completedIntent,
canceledIntent ?: completedIntent,
)
}
fun parseEndSessionResponse(intent: Intent): String {
val response = EndSessionResponse.fromIntent(intent)
val ex = AuthorizationException.fromIntent(intent)
if (response != null) {
return response.state ?: ""
} else {
throw ex ?: IllegalStateException("End session response is null")
}
}
}
| 0 | Kotlin | 1 | 4 | 1fffb0495467231f021da31534a32c657b2c0462 | 6,774 | kotlin-sdk | Apache License 2.0 |
app/src/main/java/pl/srw/billcalculator/common/list/DataBindingAdapter.kt | sewerk | 20,012,125 | false | {"Java": 427319, "Kotlin": 313019} | package pl.srw.billcalculator.common.list
import android.databinding.ViewDataBinding
import android.support.v7.util.DiffUtil
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup
import kotlinx.coroutines.experimental.android.UI
import kotlinx.coroutines.experimental.async
import org.jetbrains.anko.coroutines.experimental.bg
import timber.log.Timber
abstract class DataBindingAdapter <T, V : ViewDataBinding> : RecyclerView.Adapter<DataBindingVH<V>>() {
var items: List<T> = emptyList()
private set
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DataBindingVH<V> {
val inflater = LayoutInflater.from(parent.context)
val binding = createBinding(inflater, parent)
return DataBindingVH(binding)
}
override fun onBindViewHolder(holder: DataBindingVH<V>, position: Int) {
bind(holder.binding, items[position])
holder.binding.executePendingBindings()
}
fun replaceData(update: List<T>) {
Timber.d("Replacing data")
if (update.isEmpty()) throw IllegalArgumentException("New list cannot be empty")
else if (items.isEmpty() && update.isNotEmpty()) {
items = update.copy()
notifyDataSetChanged()
}
else calculateDiffAsnc(update)
}
override fun getItemCount() = items.size
protected abstract fun createBinding(inflater: LayoutInflater, parent: ViewGroup): V
protected abstract fun bind(binding: V, item: T)
protected abstract fun areItemsTheSame(oldItem: T, newItem: T): Boolean
protected abstract fun areContentsTheSame(oldItem: T, newItem: T): Boolean
private fun calculateDiffAsnc(update: List<T>) {
async(UI) {
val diffResult = bg { calculateDiff(items, update) }
diffResult.await().run {
items = update.copy()
dispatchUpdatesTo(this@DataBindingAdapter)
}
}
}
@SuppressWarnings("ReturnCount")
private fun calculateDiff(oldItems: List<T>, update: List<T>): DiffUtil.DiffResult {
return DiffUtil.calculateDiff(object : DiffUtil.Callback() {
override fun getOldListSize(): Int {
return oldItems.size
}
override fun getNewListSize(): Int {
return update.size
}
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
val oldItem = oldItems[oldItemPosition]
val newItem = update[newItemPosition]
return areItemsTheSame(oldItem, newItem)
}
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
val oldItem = oldItems[oldItemPosition]
val newItem = update[newItemPosition]
return areContentsTheSame(oldItem, newItem)
}
})
}
}
private fun <E> List<E>.copy(): List<E> = this.toList()
| 0 | Java | 3 | 7 | cb30459d77370bfb44b8c45fadf4d515345f919a | 3,029 | Bill-Calculator | MIT License |
src/test/kotlin/structures/Stack2Test.kt | DmitryTsyvtsyn | 418,166,620 | false | {"Kotlin": 228861} | package structures
import org.junit.Test
import org.junit.Assert.assertEquals
class Stack2Test {
@Test
fun test() {
val stack = Stack2<Int>()
stack.push(1)
stack.push(2)
stack.push(3)
assertEquals(false, stack.isEmpty)
assertEquals(3, stack.size)
assertEquals(3, stack.pop())
assertEquals(2, stack.pop())
assertEquals(1, stack.pop())
assertEquals(true, stack.isEmpty)
assertEquals(0, stack.size)
stack.push(10)
stack.push(20)
stack.push(30)
assertEquals(3, stack.size)
assertEquals(30, stack.peek())
assertEquals(3, stack.size)
stack.clear()
assertEquals(true, stack.isEmpty)
assertEquals(0, stack.size)
}
} | 0 | Kotlin | 135 | 788 | 1f89f062a056e24cc289ffdd0c6e23cadf8df887 | 791 | Kotlin-Algorithms-and-Design-Patterns | MIT License |
recorder-st/src/main/java/me/shetj/ndk/soundtouch/ISoundTouch.kt | SheTieJun | 207,213,419 | false | {"Kotlin": 301463} |
package me.shetj.ndk.soundtouch
// /*** SoundTouch
// *
// * * ST处理的对象是PCM(Pulse Code Modulation,脉冲编码调制),.wav文件中主要是这种格式
// * mp3等格式经过了压缩,需转换为PCM后再用ST处理。
// * * Tempo节拍 :通过拉伸时间,改变声音的播放速率而不影响音调。
// * * Playback Rate回放率 : 以不同的转率播放唱片(DJ打碟?),通过采样率转换实现。
// * * Pitch音调 :在保持节拍不变的前提下改变声音的音调,结合采样率转换+时间拉伸实现。如:增高音调的处理过程是:将原音频拉伸时长,再通过采样率转换,同时减少时长与增高音调变为原时长。
// * @author stj
// * @Date 2021/11/5-15:11
// * @Email <EMAIL>
// */
//
// interface ISoundTouch {
//
// fun init(
// channels: Int, //设置声道(1单,2双)
// sampleRate: Int,//设置采样率
// tempo: Float, //指定节拍,设置新的节拍tempo,源tempo=1.0,小于1则变慢;大于1变快,通过拉伸时间,改变声音的播放速率而不影响音调。
// @FloatRange(from = -12.0, to = 12.0) pitch: Float,//音调, 重点, 大于0 是变女生,小于0是变男声
// rate: Float//指定播放速率,源rate=1.0,小于1变慢;大于1
// )
//
// //指定播放速率
// fun setRate(speed: Float)
//
// //一般用来设置倍速,我们变音,默认 1.0就好
// fun setTempo(tempo: Float)
//
// //在原速1.0基础上,按百分比做增量,取值(-50 .. +100 %)
// fun setRateChange(@FloatRange(from = -50.0, to = 100.0) rateChange: Float)
//
// //在原速1.0基础上 源tempo=1.0,小于1则变慢;大于1变快 tempo (-50 .. +100 %)
// fun setTempoChange(@FloatRange(from = -50.0, to = 100.0) tempoChange: Float)
//
//
// //在源pitch的基础上,使用半音(Semitones)设置新的pitch [-12.0,12.0]
// //男声:-10
// //女声:+10
// fun setPitchSemiTones(@FloatRange(from = -12.0, to = 12.0) pitch: Float)
//
//
// //处理文件
// fun processFile(inputFile: String, outputFile: String): Boolean
//
// //实时处理PCM 流
// fun putSamples(samples: ShortArray, len: Int)
//
// fun receiveSamples(outputBuf: ShortArray): Int
//
// //获取最后一段数据
// fun flush(mp3buf: ShortArray): Int
//
// fun close()
//
// }
| 0 | Kotlin | 2 | 30 | 75da57f9e5f98779950e736fa40018a141e8c0f9 | 1,659 | Mp3Recorder | MIT License |
kommons-core/src/test/kotlin/io/kommons/TypeReferenceTest.kt | debop | 235,066,649 | false | null | package io.kommons
import org.amshove.kluent.shouldBeFalse
import org.amshove.kluent.shouldBeTrue
import org.junit.jupiter.api.Test
import java.math.BigDecimal
class TypeReferenceTest {
@Test
fun `assignable from`() {
Any::class.isAssignableFrom(Any::class).shouldBeTrue()
Number::class.java.isAssignableFrom(Long::class.java).shouldBeFalse()
Number::class.isAssignableFrom(Long::class).shouldBeFalse()
Long::class.isAssignableFrom(Number::class).shouldBeFalse()
Long::class.isAssignableFrom(BigDecimal::class).shouldBeFalse()
BigDecimal::class.isAssignableFrom(Long::class).shouldBeFalse()
}
} | 0 | Kotlin | 11 | 53 | c00bcc0542985bbcfc4652d0045f31e5c1304a70 | 660 | kotlin-design-patterns | Apache License 2.0 |
core/test/src/main/kotlin/me/jerryokafor/ihenkiri/core/test/util/ScreenshotHelper.kt | jerryOkafor | 677,650,066 | false | null | /*
* The MIT License (MIT)
*
* Copyright (c) 2023 IheNkiri Project
*
* 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 me.jerryokafor.ihenkiri.core.test.util
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.platform.LocalInspectionMode
import androidx.compose.ui.test.junit4.AndroidComposeTestRule
import androidx.compose.ui.test.onRoot
import androidx.test.ext.junit.rules.ActivityScenarioRule
import com.github.takahirom.roborazzi.RoborazziOptions
import com.github.takahirom.roborazzi.captureRoboImage
import com.google.accompanist.testharness.TestHarness
import me.jerryokafor.core.ds.theme.IheNkiriTheme
import org.robolectric.RuntimeEnvironment
val DefaultRoborazziOptions = RoborazziOptions(
compareOptions = RoborazziOptions.CompareOptions(changeThreshold = 0f),
recordOptions = RoborazziOptions.RecordOptions(resizeScale = 0.5),
)
enum class DefaultTestDevices(val description: String, val spec: String) {
PHONE(
description = "phone",
spec = "spec:shape=Normal,width=640,height=360,unit=dp,dpi=480",
),
FOLDABLE(
description = "foldable",
spec = "spec:shape=Normal,width=673,height=841,unit=dp,dpi=480",
),
TABLET(
description = "tablet",
spec = "spec:shape=Normal,width=1280,height=800,unit=dp,dpi=480",
),
}
fun <A : ComponentActivity> AndroidComposeTestRule<ActivityScenarioRule<A>, A>.captureMultiDevice(
screenshotName: String,
body: @Composable () -> Unit,
) {
DefaultTestDevices.values().forEach {
this.captureForDevice(it.description, it.spec, screenshotName, body = body)
}
}
@Suppress("LongParameterList")
fun <A : ComponentActivity> AndroidComposeTestRule<ActivityScenarioRule<A>, A>.captureForDevice(
deviceName: String,
deviceSpec: String,
screenshotName: String,
roborazziOptions: RoborazziOptions = DefaultRoborazziOptions,
darkMode: Boolean = false,
body: @Composable () -> Unit,
) {
val (width, height, dpi) = extractSpecs(deviceSpec)
// Set qualifiers from specs
RuntimeEnvironment.setQualifiers("w${width}dp-h${height}dp-${dpi}dpi")
this.activity.setContent {
CompositionLocalProvider(LocalInspectionMode provides true) {
TestHarness(darkMode = darkMode) { body() }
}
}
this.onRoot().captureRoboImage(
"src/test/screenshots/${screenshotName}_$deviceName.png",
roborazziOptions = roborazziOptions,
)
}
/**
* Takes six screenshots combining light/dark and default/Android themes and whether dynamic color
* is enabled.
*/
fun <A : ComponentActivity> AndroidComposeTestRule<ActivityScenarioRule<A>, A>.captureMultiTheme(
name: String,
overrideFileName: String? = null,
shouldCompareDarkMode: Boolean = true,
shouldCompareDynamicColor: Boolean = true,
content: @Composable (desc: String) -> Unit,
) {
val darkModeValues = if (shouldCompareDarkMode) listOf(true, false) else listOf(false)
val dynamicThemingValues = if (shouldCompareDynamicColor) listOf(true, false) else listOf(false)
var darkMode by mutableStateOf(true)
var dynamicTheming by mutableStateOf(false)
this.setContent {
CompositionLocalProvider(
LocalInspectionMode provides true,
) {
IheNkiriTheme(
isDarkTheme = darkMode,
isDynamicColor = dynamicTheming,
) {
// Keying is necessary in some cases (e.g. animations)
key(darkMode, dynamicTheming) {
val description =
generateDescription(
shouldCompareDarkMode,
darkMode,
shouldCompareDynamicColor,
dynamicTheming,
)
content(description)
}
}
}
}
// Create permutations
darkModeValues.forEach { isDarkMode ->
darkMode = isDarkMode
val darkModeDesc = if (isDarkMode) "dark" else "light"
dynamicThemingValues.forEach dynamicTheme@{ isDynamicTheming ->
dynamicTheming = isDynamicTheming
val dynamicThemingDesc = if (isDynamicTheming) "dynamic" else "notDynamic"
val filename = overrideFileName ?: name
this.onRoot().captureRoboImage(
"src/test/screenshots/" +
"$name/$filename" + "_$darkModeDesc" +
"_$dynamicThemingDesc" +
".png",
roborazziOptions = DefaultRoborazziOptions,
)
}
}
}
@Composable
private fun generateDescription(
shouldCompareDarkMode: Boolean,
darkMode: Boolean,
shouldCompareDynamicColor: Boolean,
dynamicTheming: Boolean,
): String {
val description =
"" +
if (shouldCompareDarkMode) {
if (darkMode) "Dark" else "Light"
} else {
""
} +
if (shouldCompareDynamicColor) {
if (dynamicTheming) " Dynamic" else ""
} else {
""
}
return description.trim()
}
/**
* Extracts some properties from the spec string. Note that this function is not exhaustive.
*/
private fun extractSpecs(deviceSpec: String): TestDeviceSpecs {
val specs =
deviceSpec.substringAfter("spec:")
.split(",")
.map { it.split("=") }
.associate { it[0] to it[1] }
val width = specs["width"]?.toInt() ?: 640
val height = specs["height"]?.toInt() ?: 480
val dpi = specs["dpi"]?.toInt() ?: 480
return TestDeviceSpecs(width, height, dpi)
}
data class TestDeviceSpecs(val width: Int, val height: Int, val dpi: Int)
| 17 | null | 2 | 9 | 1041e823e566b6a8549676e2dc36be66b8b1b76a | 7,139 | IheNkiri | MIT License |
src/main/kotlin/ui/poplist/PopListImpl.kt | i-am-arunkumar | 393,908,591 | true | {"Kotlin": 100873} | package ui.poplist
import com.intellij.ui.OnePixelSplitter
import javax.swing.event.ListSelectionEvent
import javax.swing.event.ListSelectionListener
/**
* Implementation Details like selection changes abstracted from [PopList]
*/
class PopListImpl<T>(
private val adapter: PopList<T>,
private val popModel: PopListModel<T>,
vertical: Boolean,
proportion: Float
) : OnePixelSplitter(vertical, proportion) {
private var itemViewCorrespondingIndex = -1
private val selectionListener = ListSelectionListener {
val index = popModel.selectionModel.minSelectionIndex
when (index) {
itemViewCorrespondingIndex -> return@ListSelectionListener
-1 -> detachItemView()
else -> {
if (itemViewCorrespondingIndex == -1)
attachItemView()
adapter.itemView.updateView(popModel.listModel.getElementAt(index))
}
}
itemViewCorrespondingIndex = index
}
private fun attachItemView() {
adapter.itemContainer.add(adapter.itemView.component)
adapter.itemContainer.updateUI()
}
private fun detachItemView() {
adapter.itemContainer.remove(adapter.itemView.component)
adapter.itemContainer.updateUI()
}
init {
firstComponent = adapter.listContainer
secondComponent = adapter.itemContainer
adapter.listComponent.apply {
selectionModel = popModel.selectionModel
model = popModel.listModel
}
selectionListener.valueChanged(null)
popModel.selectionModel.addListSelectionListener(selectionListener)
}
} | 0 | null | 0 | 0 | 4f72acfdb83c7917faa397818bd198b67fd3d6d8 | 1,668 | AutoCp | MIT License |
src/main/kotlin/ui/poplist/PopListImpl.kt | i-am-arunkumar | 393,908,591 | true | {"Kotlin": 100873} | package ui.poplist
import com.intellij.ui.OnePixelSplitter
import javax.swing.event.ListSelectionEvent
import javax.swing.event.ListSelectionListener
/**
* Implementation Details like selection changes abstracted from [PopList]
*/
class PopListImpl<T>(
private val adapter: PopList<T>,
private val popModel: PopListModel<T>,
vertical: Boolean,
proportion: Float
) : OnePixelSplitter(vertical, proportion) {
private var itemViewCorrespondingIndex = -1
private val selectionListener = ListSelectionListener {
val index = popModel.selectionModel.minSelectionIndex
when (index) {
itemViewCorrespondingIndex -> return@ListSelectionListener
-1 -> detachItemView()
else -> {
if (itemViewCorrespondingIndex == -1)
attachItemView()
adapter.itemView.updateView(popModel.listModel.getElementAt(index))
}
}
itemViewCorrespondingIndex = index
}
private fun attachItemView() {
adapter.itemContainer.add(adapter.itemView.component)
adapter.itemContainer.updateUI()
}
private fun detachItemView() {
adapter.itemContainer.remove(adapter.itemView.component)
adapter.itemContainer.updateUI()
}
init {
firstComponent = adapter.listContainer
secondComponent = adapter.itemContainer
adapter.listComponent.apply {
selectionModel = popModel.selectionModel
model = popModel.listModel
}
selectionListener.valueChanged(null)
popModel.selectionModel.addListSelectionListener(selectionListener)
}
} | 0 | null | 0 | 0 | 4f72acfdb83c7917faa397818bd198b67fd3d6d8 | 1,668 | AutoCp | MIT License |
core/designsystem/src/main/kotlin/com/merxury/blocker/core/designsystem/component/scrollbar/AppScrollbars.kt | lihenggui | 115,417,337 | 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.merxury.blocker.core.designsystem.component.scrollbar
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.SpringSpec
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.gestures.Orientation.Horizontal
import androidx.compose.foundation.gestures.Orientation.Vertical
import androidx.compose.foundation.interaction.InteractionSource
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsDraggedAsState
import androidx.compose.foundation.interaction.collectIsHoveredAsState
import androidx.compose.foundation.interaction.collectIsPressedAsState
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import com.merxury.blocker.core.designsystem.component.scrollbar.ThumbState.Active
import com.merxury.blocker.core.designsystem.component.scrollbar.ThumbState.Dormant
import com.merxury.blocker.core.designsystem.component.scrollbar.ThumbState.Inactive
import kotlinx.coroutines.delay
/**
* A [Scrollbar] that allows for fast scrolling of content.
* Its thumb disappears when the scrolling container is dormant.
* @param modifier a [Modifier] for the [Scrollbar]
* @param state the driving state for the [Scrollbar]
* @param scrollInProgress a flag indicating if the scrolling container for the scrollbar is
* currently scrolling
* @param orientation the orientation of the scrollbar
* @param onThumbMoved the fast scroll implementation
*/
@Composable
fun FastScrollbar(
modifier: Modifier = Modifier,
state: ScrollbarState,
scrollInProgress: Boolean,
orientation: Orientation,
onThumbMoved: (Float) -> Unit,
) {
val interactionSource = remember { MutableInteractionSource() }
Scrollbar(
modifier = modifier,
orientation = orientation,
interactionSource = interactionSource,
state = state,
thumb = {
FastScrollbarThumb(
scrollInProgress = scrollInProgress,
interactionSource = interactionSource,
orientation = orientation,
)
},
onThumbMoved = onThumbMoved,
)
}
/**
* A simple [Scrollbar].
* Its thumb disappears when the scrolling container is dormant.
* @param modifier a [Modifier] for the [Scrollbar]
* @param state the driving state for the [Scrollbar]
* @param scrollInProgress a flag indicating if the scrolling container for the scrollbar is
* currently scrolling
* @param orientation the orientation of the scrollbar
*/
@Composable
fun DecorativeScrollbar(
modifier: Modifier = Modifier,
state: ScrollbarState,
scrollInProgress: Boolean,
orientation: Orientation,
) {
val interactionSource = remember { MutableInteractionSource() }
Scrollbar(
modifier = modifier,
orientation = orientation,
interactionSource = interactionSource,
state = state,
thumb = {
DecorativeScrollbarThumb(
interactionSource = interactionSource,
scrollInProgress = scrollInProgress,
orientation = orientation,
)
},
)
}
/**
* A scrollbar thumb that is intended to also be a touch target for fast scrolling.
*/
@Composable
private fun FastScrollbarThumb(
scrollInProgress: Boolean,
interactionSource: InteractionSource,
orientation: Orientation,
) {
Box(
modifier = Modifier
.run {
when (orientation) {
Vertical -> width(12.dp).fillMaxHeight()
Horizontal -> height(12.dp).fillMaxWidth()
}
}
.background(
color = scrollbarThumbColor(
scrollInProgress = scrollInProgress,
interactionSource = interactionSource,
),
shape = RoundedCornerShape(16.dp),
),
)
}
/**
* A decorative scrollbar thumb for communicating a user's position in a list solely.
*/
@Composable
private fun DecorativeScrollbarThumb(
scrollInProgress: Boolean,
interactionSource: InteractionSource,
orientation: Orientation,
) {
Box(
modifier = Modifier
.run {
when (orientation) {
Vertical -> width(2.dp).fillMaxHeight()
Horizontal -> height(2.dp).fillMaxWidth()
}
}
.background(
color = scrollbarThumbColor(
scrollInProgress = scrollInProgress,
interactionSource = interactionSource,
),
shape = RoundedCornerShape(16.dp),
),
)
}
/**
* The color of the scrollbar thumb as a function of its interaction state.
* @param scrollInProgress if the scrolling container is currently scrolling
* @param interactionSource source of interactions in the scrolling container
*/
@Composable
private fun scrollbarThumbColor(
scrollInProgress: Boolean,
interactionSource: InteractionSource,
): Color {
var state by remember { mutableStateOf(Dormant) }
val pressed by interactionSource.collectIsPressedAsState()
val hovered by interactionSource.collectIsHoveredAsState()
val dragged by interactionSource.collectIsDraggedAsState()
val active = pressed || hovered || dragged || scrollInProgress
val color by animateColorAsState(
targetValue = when (state) {
Active -> MaterialTheme.colorScheme.onSurface.copy(0.5f)
Inactive -> MaterialTheme.colorScheme.onSurface.copy(alpha = 0.2f)
Dormant -> Color.Transparent
},
animationSpec = SpringSpec(
stiffness = Spring.StiffnessLow,
),
label = "Scrollbar thumb color",
)
LaunchedEffect(active) {
when (active) {
true -> state = Active
false -> {
state = Inactive
delay(2_000)
state = Dormant
}
}
}
return color
}
private enum class ThumbState {
Active, Inactive, Dormant
}
| 27 | null | 50 | 724 | 502a1eb13841517d0bf5a380104c8261e318bb2b | 7,544 | blocker | Apache License 2.0 |
magick-kt-native-q8/src/commonMain/kotlin/imagemagick/bridge/ChannelStatistics.kt | Gounlaf | 692,782,810 | false | {"Kotlin": 954080, "C": 942148, "C++": 3285} | @file:Suppress("KDocMissingDocumentation")
package imagemagick.bridge
import imagemagick.core.enums.PixelChannel
import imagemagick.core.toNative
import kotlinx.cinterop.CPointer
import kotlinx.cinterop.ExperimentalForeignApi
import libMagickNative.ChannelStatistics
import libMagickNative.ChannelStatistics_Depth_Get
import libMagickNative.ChannelStatistics_Entropy_Get
import libMagickNative.ChannelStatistics_Kurtosis_Get
import libMagickNative.ChannelStatistics_Maximum_Get
import libMagickNative.ChannelStatistics_Mean_Get
import libMagickNative.ChannelStatistics_Minimum_Get
import libMagickNative.ChannelStatistics_Skewness_Get
import libMagickNative.ChannelStatistics_StandardDeviation_Get
import libMagickNative.Statistics_DisposeList
import libMagickNative.Statistics_GetInstance
import platform.posix.size_t
@ExperimentalForeignApi
public inline fun CPointer<ChannelStatistics>.dispose(): Unit = Statistics_DisposeList(this)
@ExperimentalForeignApi
public inline fun CPointer<ChannelStatistics>.getInstance(channel: PixelChannel): CPointer<ChannelStatistics>? =
Statistics_GetInstance(this, channel.toNative())
@ExperimentalForeignApi
public inline val CPointer<ChannelStatistics>.depth: size_t get() = ChannelStatistics_Depth_Get(this)
@ExperimentalForeignApi
public inline val CPointer<ChannelStatistics>.entropy: Double get() = ChannelStatistics_Entropy_Get(this)
@ExperimentalForeignApi
public inline val CPointer<ChannelStatistics>.kurtosis: Double get() = ChannelStatistics_Kurtosis_Get(this)
@ExperimentalForeignApi
public inline val CPointer<ChannelStatistics>.maximum: Double get() = ChannelStatistics_Maximum_Get(this)
@ExperimentalForeignApi
public inline val CPointer<ChannelStatistics>.mean: Double get() = ChannelStatistics_Mean_Get(this)
@ExperimentalForeignApi
public inline val CPointer<ChannelStatistics>.minimum: Double get() = ChannelStatistics_Minimum_Get(this)
@ExperimentalForeignApi
public inline val CPointer<ChannelStatistics>.skewness: Double get() = ChannelStatistics_Skewness_Get(this)
@ExperimentalForeignApi
public inline val CPointer<ChannelStatistics>.standardDeviation: Double get() = ChannelStatistics_StandardDeviation_Get(this)
| 0 | Kotlin | 0 | 0 | a075a88d293b5c77668d8079c73b463c2d601fc8 | 2,192 | Magick.KT | MIT License |
src/main/kotlin/com/piashcse/entities/user/UserHasType.kt | piashcse | 410,331,425 | false | null | package com.piashcse.entities.user
import com.piashcse.entities.base.BaseIntEntity
import com.piashcse.entities.base.BaseIntEntityClass
import com.piashcse.entities.base.BaseIntIdTable
import org.jetbrains.exposed.dao.id.EntityID
object UserHasTypeTable : BaseIntIdTable("user_has_type") {
val userId = reference("user_id", UserTable.id)
val userTypeId = varchar("user_type_id", 50)
}
class UserHasTypeEntity(id: EntityID<String>) : BaseIntEntity(id, UserHasTypeTable) {
companion object : BaseIntEntityClass<UserHasTypeEntity>(UserHasTypeTable)
var userId by UserHasTypeTable.userId
var userTypeId by UserHasTypeTable.userTypeId
//var users by UsersEntity referencedOn UserHasTypeTable.user_id
fun userHasTypeResponse() = UserHasType(id.toString(), userTypeId)
}
data class UserHasType(
val id: String, val userType: String
) | 0 | Kotlin | 5 | 26 | 74b152e2dc10238197a0fb99595730edd55621fd | 864 | ktor-E-Commerce | PostgreSQL License |
src/main/kotlin/no/nav/personbruker/dittnav/eventtestproducer/ytelsestesting/TestDataService.kt | navikt | 219,521,847 | false | null | package no.nav.personbruker.dittnav.eventtestproducer.ytelsestesting
import kotlinx.coroutines.delay
import no.nav.personbruker.dittnav.eventtestproducer.beskjed.BeskjedProducer
import no.nav.personbruker.dittnav.eventtestproducer.beskjed.ProduceBeskjedDto
import no.nav.personbruker.dittnav.eventtestproducer.common.InnloggetBruker
import no.nav.personbruker.dittnav.eventtestproducer.common.createKeyForEvent
import no.nav.personbruker.dittnav.eventtestproducer.done.DoneProducer
import no.nav.personbruker.dittnav.eventtestproducer.innboks.InnboksProducer
import no.nav.personbruker.dittnav.eventtestproducer.innboks.ProduceInnboksDto
import no.nav.personbruker.dittnav.eventtestproducer.oppgave.OppgaveProducer
import no.nav.personbruker.dittnav.eventtestproducer.oppgave.ProduceOppgaveDto
import no.nav.personbruker.dittnav.eventtestproducer.statusoppdatering.ProduceStatusoppdateringDto
import no.nav.personbruker.dittnav.eventtestproducer.statusoppdatering.StatusoppdateringProducer
import org.slf4j.LoggerFactory
import java.time.Instant
import java.util.*
class TestDataService(
private val doneProducer: DoneProducer,
private val beskjedProducer: BeskjedProducer,
private val oppgaveProducer: OppgaveProducer,
private val innboksProducer: InnboksProducer,
private val statusoppdateringProducer: StatusoppdateringProducer
) {
private val log = LoggerFactory.getLogger(TestDataService::class.java)
val dummySystembruker = "dittnav-event-test-producer"
suspend fun produserBeskjeder(produceDone: Boolean, yTestDto: YTestDto) {
log.info("Produserer ${yTestDto.antallEventer} beskjeder")
val start = Instant.now()
val innloggetBruker = InnloggetBruker(yTestDto.ident, 4, "dummyToken")
for (i in 1..yTestDto.antallEventer) {
val key = createKeyForEvent(eventId = UUID.randomUUID().toString(), systembruker = dummySystembruker)
val dto = ProduceBeskjedDto(tekst = "Beskjedtekst $i", link = "https://beskjed-$i", grupperingsid = "grupperingsid-$i", eksternVarsling = yTestDto.eksternVarsling)
val beskjedEvent = beskjedProducer.createBeskjedForIdent(innloggetBruker, dto)
beskjedProducer.sendEventToKafka(key, beskjedEvent)
if(produceDone) {
val doneEvent = doneProducer.createDoneEvent(innloggetBruker)
doneProducer.sendEventToKafka(key, doneEvent)
}
if (isShouldTakeASmallBreakAndLogProgress(i, yTestDto.antallEventer)) {
log.info("Har produsert beskjed nummer $i tar en liten pause")
delay(1000)
}
}
beregnBruktTid(start)
}
suspend fun produserOppgaver(produceDone: Boolean, yTestDto: YTestDto) {
log.info("Produserer ${yTestDto.antallEventer} oppgaver")
val start = Instant.now()
val innloggetBruker = InnloggetBruker(yTestDto.ident, 4, "dummyToken")
for (i in 1..yTestDto.antallEventer) {
val key = createKeyForEvent(eventId = UUID.randomUUID().toString(), systembruker = dummySystembruker)
val dto = ProduceOppgaveDto(tekst = "Oppgavetekst $i", link = "https://oppgave-$i", grupperingsid = "grupperingsid-$i", eksternVarsling = yTestDto.eksternVarsling)
val oppgaveEvent = oppgaveProducer.createOppgaveForIdent(innloggetBruker, dto)
oppgaveProducer.sendEventToKafka(key, oppgaveEvent)
if(produceDone) {
val doneEvent = doneProducer.createDoneEvent(innloggetBruker)
doneProducer.sendEventToKafka(key, doneEvent)
}
if (isShouldTakeASmallBreakAndLogProgress(i, yTestDto.antallEventer)) {
log.info("Har produsert oppgave nummer $i tar en liten pause")
delay(1000)
}
}
beregnBruktTid(start)
}
suspend fun produserInnboks(produceDone: Boolean, yTestDto: YTestDto) {
log.info("Produserer ${yTestDto.antallEventer} innboks-eventer")
val start = Instant.now()
val innloggetBruker = InnloggetBruker(yTestDto.ident, 4, "dummyToken")
for (i in 1..yTestDto.antallEventer) {
val key = createKeyForEvent("i-$i", dummySystembruker)
val dto = ProduceInnboksDto("Innbokstekst $i", "https://innboks-$i", "grupperingsid-$i")
val innboksEvent = innboksProducer.createInnboksForIdent(innloggetBruker, dto)
innboksProducer.sendEventToKafka(key, innboksEvent)
if(produceDone) {
val doneEvent = doneProducer.createDoneEvent(innloggetBruker)
doneProducer.sendEventToKafka(key, doneEvent)
}
if (isShouldTakeASmallBreakAndLogProgress(i, yTestDto.antallEventer)) {
log.info("Har produsert innboks-event nummer $i tar en liten pause")
delay(1000)
}
}
beregnBruktTid(start)
}
suspend fun produserStatusoppdateringer(yTestDto: YTestDto) {
log.info("Produserer ${yTestDto.antallEventer} Statusoppdatering-eventer")
val start = Instant.now()
val innloggetBruker = InnloggetBruker(yTestDto.ident, 4, "dummyToken")
for (i in 1..yTestDto.antallEventer) {
val key = createKeyForEvent("s-$i", dummySystembruker)
val dto = ProduceStatusoppdateringDto("https://dummyLink_$i", "SENDT", "dummyStatusIntern_$i", "dummySakstema_$i", "grupperingsid-$i")
val statusoppdateringEvent = statusoppdateringProducer.createStatusoppdateringForIdent(innloggetBruker, dto)
statusoppdateringProducer.sendEventToKafka(key, statusoppdateringEvent)
if (isShouldTakeASmallBreakAndLogProgress(i, yTestDto.antallEventer)) {
log.info("Har produsert Statusoppdatering-event nummer $i tar en liten pause")
delay(1000)
}
}
beregnBruktTid(start)
}
private fun beregnBruktTid(start: Instant) {
val stop = Instant.now()
val tidbrukt = stop.minusMillis(start.toEpochMilli()).toEpochMilli()
val tidbruktISekunder = tidbrukt / 1000
log.info("Gjenbrukt kafka-produsent med venting, produseringen tok: $tidbruktISekunder sekunder.\n")
}
private fun isShouldTakeASmallBreakAndLogProgress(i: Int, antallEventer: Int) = i % (antallEventer / 10) == 0
}
| 0 | Kotlin | 1 | 1 | a50026f76b82c424fc6a0e94d5602f9ccf0f5727 | 6,392 | dittnav-event-test-producer | MIT License |
core/src/main/kotlin/org/hyrical/hcf/profile/commands/LivesCommand.kt | Hyrical | 597,847,737 | false | {"Kotlin": 323471, "Java": 30373} | package org.hyrical.hcf.profile.commands
import co.aikar.commands.BaseCommand
import co.aikar.commands.annotation.CommandAlias
import co.aikar.commands.annotation.HelpCommand
import co.aikar.commands.annotation.Name
import co.aikar.commands.annotation.Optional
import co.aikar.commands.annotation.Subcommand
import org.bukkit.entity.Player
import org.hyrical.hcf.HCFPlugin
import org.hyrical.hcf.config.impl.LangFile
import org.hyrical.hcf.profile.ProfileService
import org.hyrical.hcf.registry.annotations.Command
import org.hyrical.hcf.utils.translate
import java.text.NumberFormat
@Command
@CommandAlias("lives")
object LivesCommand : BaseCommand() {
@HelpCommand
fun help(player: Player) {
for (string in LangFile.getStringList("LIVES.LIVES-HELP")){
player.sendMessage(translate(string))
}
}
@Subcommand("check")
fun check(player: Player, @Optional @Name("target") target: Player?) {
val targetProfile = if (target == null) {
HCFPlugin.instance.profileService.getProfile(player.uniqueId)
} else {
HCFPlugin.instance.profileService.getProfile(target.uniqueId)
} ?: return
if (target == null) {
player.sendMessage(translate(LangFile.getString("LIVES.LIVES-CHECK.LIVES-SELF")!!.replace("%lives%", targetProfile.lives.toString())))
} else {
player.sendMessage(translate(LangFile.getString("LIVES.LIVES-CHECK.LIVES-TARGET")!!.replace("%target%", target.displayName).replace("%lives%", targetProfile.lives.toString())))
}
}
@Subcommand("send")
fun send(player: Player, @Name("target") target: Player, @Name("amount") amount: Int) {
if (amount <= 0) {
player.sendMessage(translate(LangFile.getString("LIVES.LIVES-SEND.NEGATIVE-AMOUNT")!!))
return
}
val profile = HCFPlugin.instance.profileService.getProfile(player.uniqueId) ?: return
val targetProfile = HCFPlugin.instance.profileService.getProfile(target.uniqueId) ?: return
if (profile.friendLives < amount) {
player.sendMessage(translate(LangFile.getString("LIVES.LIVES-SEND.NOT-ENOUGH")!!))
return
}
profile.friendLives -= amount
targetProfile.friendLives += amount
player.sendMessage(translate(LangFile.getString("LIVES.LIVES-SEND.SEND-SELF")!!
.replace("%target%", player.displayName).replace("%amount%", NumberFormat.getInstance().format(amount))))
target.sendMessage(translate(LangFile.getString("LIVES.LIVES-SEND.SEND-TARGET")!!
.replace("%player%", player.displayName).replace("%amount%", NumberFormat.getInstance().format(amount))))
HCFPlugin.instance.profileService.save(profile)
HCFPlugin.instance.profileService.save(targetProfile)
}
// TODO: rewvive
} | 13 | Kotlin | 0 | 3 | 74a1512f3af2db591bcd233d2012e4dbded10e8a | 2,859 | HCF | MIT License |
presentation/src/main/java/com/nisrulz/example/spacexapi/presentation/navigation/AppNavigation.kt | nisrulz | 708,230,156 | false | {"Kotlin": 95643} | package com.nisrulz.example.spacexapi.presentation.navigation
import androidx.compose.runtime.Composable
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import com.nisrulz.example.spacexapi.presentation.features.launch_detail.LaunchDetailScreen
import com.nisrulz.example.spacexapi.presentation.features.list_of_launches.ListOfLaunchesScreen
import com.nisrulz.example.spacexapi.presentation.navigation.NavigationRoute.LaunchDetail
import com.nisrulz.example.spacexapi.presentation.navigation.NavigationRoute.ListOfLaunches
@Composable
fun AppNavigation() {
val navController = rememberNavController()
NavHost(
navController = navController,
startDestination = ListOfLaunches.route
) {
composable(ListOfLaunches.route) {
ListOfLaunchesScreen(navigateToDetails = { launchId ->
navController.navigate(
LaunchDetail.build(launchId)
)
})
}
composable(LaunchDetail.route) { backStackEntry ->
backStackEntry.arguments?.apply {
val launchId = getString("launchId")
if (launchId != null) {
LaunchDetailScreen(launchId = launchId)
}
}
}
}
} | 1 | Kotlin | 0 | 5 | f43012cd4a1f226434c2f43f27a693ec9e23b954 | 1,365 | android-spacex-app | Apache License 2.0 |
ui-components/src/main/java/com/mapbox/navigation/ui/components/maps/internal/ui/CameraModeButtonComponent.kt | mapbox | 87,455,763 | false | {"Kotlin": 9692008, "Python": 65081, "Java": 36829, "HTML": 17811, "Makefile": 9840, "Shell": 7129} | package com.mapbox.navigation.ui.maps.internal.ui
import android.view.View
import com.mapbox.navigation.core.MapboxNavigation
import com.mapbox.navigation.ui.base.lifecycle.UIComponent
import com.mapbox.navigation.ui.maps.camera.NavigationCamera
import com.mapbox.navigation.ui.maps.camera.state.NavigationCameraState
import com.mapbox.navigation.ui.maps.internal.extensions.flowNavigationCameraState
import com.mapbox.navigation.ui.maps.view.MapboxCameraModeButton
import com.mapbox.navigation.ui.utils.internal.Provider
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
interface CameraModeButtonComponentContract {
val buttonState: StateFlow<NavigationCameraState>
fun onClick(view: View)
}
class CameraModeButtonComponent(
private val cameraModeButton: MapboxCameraModeButton,
private val contractProvider: Provider<CameraModeButtonComponentContract>,
) : UIComponent() {
override fun onAttached(mapboxNavigation: MapboxNavigation) {
super.onAttached(mapboxNavigation)
val contract = contractProvider.get()
contract.buttonState.observe { cameraModeButton.setState(it) }
cameraModeButton.setOnClickListener(contract::onClick)
}
override fun onDetached(mapboxNavigation: MapboxNavigation) {
super.onDetached(mapboxNavigation)
cameraModeButton.setOnClickListener(null)
}
}
internal class MapboxCameraModeButtonComponentContract(
private val navigationCameraProvider: Provider<NavigationCamera?>
) : UIComponent(),
CameraModeButtonComponentContract {
private val _buttonState = MutableStateFlow(NavigationCameraState.OVERVIEW)
override val buttonState: StateFlow<NavigationCameraState> = _buttonState.asStateFlow()
private var navigationCamera: NavigationCamera? = null
override fun onClick(view: View) {
when (buttonState.value) {
NavigationCameraState.OVERVIEW ->
navigationCamera?.requestNavigationCameraToFollowing()
NavigationCameraState.FOLLOWING ->
navigationCamera?.requestNavigationCameraToOverview()
else -> {
/* do nothing */
}
}
}
override fun onAttached(mapboxNavigation: MapboxNavigation) {
super.onAttached(mapboxNavigation)
navigationCamera = navigationCameraProvider.get()
navigationCamera?.flowNavigationCameraState()?.observe {
if (it != NavigationCameraState.IDLE) {
_buttonState.value = it
}
}
}
override fun onDetached(mapboxNavigation: MapboxNavigation) {
super.onDetached(mapboxNavigation)
navigationCamera = null
}
}
| 508 | Kotlin | 319 | 621 | ad73c6011348cb9b24b92a369024ca06f48845ab | 2,762 | mapbox-navigation-android | Apache License 2.0 |
viewmodels/src/main/java/com/example/viewmodels/CountryListViewModel.kt | perrystreetsoftware | 538,729,133 | false | null | package com.example.viewmodels
import com.example.domainmodels.Continent
import com.example.domainmodels.Country
import com.example.domainmodels.ServerStatus
import com.example.errors.CountryListError
import com.example.logic.CountryListLogic
import com.example.logic.ServerStatusLogic
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.subjects.BehaviorSubject
class CountryListViewModel(
private val logic: CountryListLogic,
private val serverStatusLogic: ServerStatusLogic
) : DisposableViewModel() {
data class UiState(
val continents: List<Continent> = emptyList(),
val isLoading: Boolean = false,
val isLoaded: Boolean = false,
val error: CountryListError? = null,
val serverStatus: ServerStatus? = null,
val navigationTarget: Country? = null,
)
private val _state: BehaviorSubject<UiState> = BehaviorSubject.createDefault(UiState())
val state: Observable<UiState> = _state
init {
// https://stackoverflow.com/questions/73305899/why-launchedeffect-call-second-time-when-i-navigate-back
onPageLoaded()
}
private fun onPageLoaded() {
disposables.add(logic.continents.doOnNext {
_state.onNext(_state.value!!.copy(continents = it))
}.subscribe())
disposables.add(serverStatusLogic.status.doOnNext {
_state.onNext(_state.value!!.copy(serverStatus = it))
}.subscribe())
disposables.add(
logic.reload()
.doOnSubscribe {
_state.onNext(_state.value!!.copy(isLoading = true))
}
.subscribe({
_state.onNext(_state.value!!.copy(isLoading = false, isLoaded = true))
}, { error ->
_state.onNext(
_state.value!!.copy(
isLoading = false,
isLoaded = true,
error = (error as CountryListError)
)
)
})
)
disposables.add(
serverStatusLogic.reload().subscribe()
)
}
fun onRefreshTapped() {
disposables.add(
logic.getForbiddenApi().subscribe({}, { emitError(it) })
)
}
fun onFailOtherTapped() {
emitError(CountryListError.Other)
}
fun dismissError() {
_state.onNext(_state.value!!.copy(error = null))
}
fun onCountrySelected(country: Country) {
disposables.add(
logic.canAccessCountry(country).subscribe(
{
_state.onNext(_state.value!!.copy(navigationTarget = country))
},
{
emitError(it)
}
)
)
}
fun resetNavigationTarget() {
_state.onNext(_state.value!!.copy(navigationTarget = null))
}
fun navigateToRandomCountry() {
disposables.add(
logic.getRandomCountry().subscribe(
{ onCountrySelected(it) },
{ emitError(it) }
)
)
}
private fun emitError(error: Throwable) {
when (val countryListError = error as CountryListError) {
is CountryListError.NotEnoughPermissionsError -> {
_state.onNext(_state.value!!.copy(error = countryListError))
}
else -> {
_state.onNext(_state.value!!.copy(error = countryListError))
}
}
}
override fun onCleared() {
super.onCleared()
disposables.dispose()
}
}
| 0 | null | 2 | 4 | 9092407e7163368715b94f89770dc01de957f3be | 3,660 | DemoAppAndroid | MIT License |
didsdk/android/src/main/kotlin/com/appgate/didsdk/DidsdkPlugin.kt | appgate | 668,476,346 | false | null | package com.appgate.didsdk
import android.content.Context
import android.content.Intent
import android.util.Log
import com.appgate.appgate_sdk.data.utils.GsonUtil
import com.appgate.appgate_sdk.encryptor.exceptions.SDKException
import com.appgate.didm_auth.DetectID
import com.appgate.didm_auth.common.handler.EnrollmentResultHandler
import com.appgate.didsdk.constants.ArgumentsConstants
import com.appgate.didsdk.constants.DIDMethodChannelNames.ACCOUNTS_MODULE
import com.appgate.didsdk.constants.DIDMethodChannelNames.DID_SDK
import com.appgate.didsdk.constants.DIDMethodChannelNames.OTP_MODULE
import com.appgate.didsdk.constants.DIDMethodChannelNames.PUSH_MODULE
import com.appgate.didsdk.constants.DIDMethodChannelNames.QR_MODULE
import com.appgate.didsdk.constants.DIDModulesNames.APPROVED_PUSH_ALERT_ACTION
import com.appgate.didsdk.constants.DIDModulesNames.CONFIRM_PUSH_TRANSACTION_ACTION
import com.appgate.didsdk.constants.DIDModulesNames.CONFIRM_QRCODE_TRANSACTION_ACTION
import com.appgate.didsdk.constants.DIDModulesNames.DECLINE_PUSH_TRANSACTION_ACTION
import com.appgate.didsdk.constants.DIDModulesNames.DECLINE_QRCODE_TRANSACTION_ACTION
import com.appgate.didsdk.constants.DIDModulesNames.DID_REGISTRATION_BY_QRCODE
import com.appgate.didsdk.constants.DIDModulesNames.DID_REGISTRATION_WITH_URL
import com.appgate.didsdk.constants.DIDModulesNames.EXIST_ACCOUNTS
import com.appgate.didsdk.constants.DIDModulesNames.GET_ACCOUNTS
import com.appgate.didsdk.constants.DIDModulesNames.GET_CHALLENGE_QUESTION_OTP
import com.appgate.didsdk.constants.DIDModulesNames.GET_DEVICE_ID
import com.appgate.didsdk.constants.DIDModulesNames.GET_MASKED_APP_INSTANCE_ID
import com.appgate.didsdk.constants.DIDModulesNames.GET_MOBILE_ID
import com.appgate.didsdk.constants.DIDModulesNames.GET_TOKEN_TIME_STEP_VALUE
import com.appgate.didsdk.constants.DIDModulesNames.GET_TOKEN_VALUE
import com.appgate.didsdk.constants.DIDModulesNames.PUSH_ALERT_OPEN_LISTENER
import com.appgate.didsdk.constants.DIDModulesNames.PUSH_TRANSACTION_OPEN_LISTENER
import com.appgate.didsdk.constants.DIDModulesNames.QR_AUTHENTICATION_PROCESS
import com.appgate.didsdk.constants.DIDModulesNames.REMOVE_ACCOUNT
import com.appgate.didsdk.constants.DIDModulesNames.SET_ACCOUNT_USERNAME
import com.appgate.didsdk.constants.DIDModulesNames.SET_APPLICATION_NAME
import com.appgate.didsdk.constants.DIDModulesNames.UPDATE_GLOBAL_CONFIG
import com.appgate.didsdk.constants.SDKErrors.ERROR_CHANNEL_METHOD
import com.appgate.didsdk.constants.SDKErrors.ERROR_NOT_ARGUMENTS
import com.appgate.didsdk.constants.model.TransactionInfoDomain
import com.appgate.didsdk.modules.AccountsModule
import com.appgate.didsdk.modules.OTPModule
import com.appgate.didsdk.modules.PushModule
import com.appgate.didsdk.modules.PushModule.Companion.FT_TRANSACTION_INFO
import com.appgate.didsdk.modules.PushModule.Companion.FT_TYPE_PUSH
import com.appgate.didsdk.modules.QRModule
import com.appgate.didsdk.util.DIDPushUtil
import com.appgate.didsdk.util.DIDTypePush
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import io.flutter.plugin.common.PluginRegistry.NewIntentListener
/** DidsdkPlugin */
class DidsdkPlugin : MethodCallHandler, NewIntentListener, FlutterPlugin, ActivityAware {
/// The MethodChannel that will the communication between Flutter and native Android
///
/// This local reference serves to register the plugin with the Flutter Engine and unregister it
/// when the Flutter Engine is detached from the Activity
private lateinit var registerChannel: MethodChannel
private lateinit var accountsChannel: MethodChannel
private lateinit var qrChannel: MethodChannel
private lateinit var otpChannel: MethodChannel
private lateinit var pushChannel: MethodChannel
private lateinit var sdk: DetectID
private var context: Context? = null
override fun onAttachedToEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
registerChannel = MethodChannel(flutterPluginBinding.binaryMessenger, DID_SDK.value)
registerChannel.setMethodCallHandler(this)
accountsChannel = MethodChannel(flutterPluginBinding.binaryMessenger, ACCOUNTS_MODULE.value)
accountsChannel.setMethodCallHandler(this)
qrChannel = MethodChannel(flutterPluginBinding.binaryMessenger, QR_MODULE.value)
qrChannel.setMethodCallHandler(this)
otpChannel = MethodChannel(flutterPluginBinding.binaryMessenger, OTP_MODULE.value)
otpChannel.setMethodCallHandler(this)
pushChannel = MethodChannel(flutterPluginBinding.binaryMessenger, PUSH_MODULE.value)
pushChannel.setMethodCallHandler(this)
}
override fun onMethodCall(call: MethodCall, result: Result) {
val accountsModule = AccountsModule(context)
val qrModule = QRModule(context)
val otpModule = OTPModule(context)
val pushModule = PushModule(context, pushChannel)
when (call.method) {
"getPlatformVersion" -> {
result.success("Android ${android.os.Build.VERSION.RELEASE}")
}
DID_REGISTRATION_WITH_URL.value -> {
didRegistrationWithUrl(call, result)
}
DID_REGISTRATION_BY_QRCODE.value -> {
didRegistrationByQRCode(call, result)
}
EXIST_ACCOUNTS.value -> {
accountsModule.existAccounts(result)
}
GET_ACCOUNTS.value -> {
accountsModule.getAccounts(result)
}
PUSH_TRANSACTION_OPEN_LISTENER.value -> {
pushModule.setPushTransactionOpenListener(result)
}
PUSH_ALERT_OPEN_LISTENER.value -> {
pushModule.setPushAlertOpenListener(result)
}
CONFIRM_PUSH_TRANSACTION_ACTION.value -> {
pushModule.confirmOrDecline(true, call, result)
}
DECLINE_PUSH_TRANSACTION_ACTION.value -> {
pushModule.confirmOrDecline(false, call, result)
}
APPROVED_PUSH_ALERT_ACTION.value -> {
pushModule.approvePush(call, result)
}
QR_AUTHENTICATION_PROCESS.value -> {
qrModule.qrAuthenticationProcess(call, result)
}
CONFIRM_QRCODE_TRANSACTION_ACTION.value -> {
qrModule.confirmOrDecline(true, call, result)
}
DECLINE_QRCODE_TRANSACTION_ACTION.value -> {
qrModule.confirmOrDecline(false, call, result)
}
SET_ACCOUNT_USERNAME.value -> {
accountsModule.setAccountUsername(call, result)
}
SET_APPLICATION_NAME.value -> {
setApplicationName(call, result)
}
REMOVE_ACCOUNT.value -> {
accountsModule.removeAccount(call, result)
}
UPDATE_GLOBAL_CONFIG.value -> {
accountsModule.updateGlobalConfig(call, result)
}
GET_DEVICE_ID.value -> {
getDeviceID(result)
}
GET_MASKED_APP_INSTANCE_ID.value -> {
getMaskedAppInstanceID(result)
}
GET_MOBILE_ID.value -> {
getMobileID(result)
}
GET_TOKEN_VALUE.value -> {
otpModule.getTokenValue(call, result)
}
GET_TOKEN_TIME_STEP_VALUE.value -> {
otpModule.getTokenTimeStepValue(call, result)
}
GET_CHALLENGE_QUESTION_OTP.value -> {
otpModule.getChallengeQuestionOtp(call, result)
}
else -> {
result.error(
ERROR_CHANNEL_METHOD.code,
ERROR_CHANNEL_METHOD.message,
ERROR_CHANNEL_METHOD.details
)
}
}
}
private fun didRegistrationByQRCode(call: MethodCall, result: Result) {
val url = call.argument<String>(ArgumentsConstants.URL.value)
val code = call.argument<String>(ArgumentsConstants.CODE.value)
if (code.isNullOrEmpty())
result.error(
ERROR_NOT_ARGUMENTS.code, ERROR_NOT_ARGUMENTS.message, ERROR_NOT_ARGUMENTS.details
)
DetectID.sdk(context)
.didRegistrationByQRCode(code!!, url!!, object : EnrollmentResultHandler {
override fun onSuccess() {
Log.d(TAG, "onSuccess()")
val value: MutableList<String> = ArrayList(1)
value.add("")
result.success(value)
}
override fun onFailure(exception: SDKException) {
Log.e(TAG, "onFailure: ", exception)
result.error("${exception.code}", exception.message, exception.localizedMessage)
}
})
}
private fun didRegistrationWithUrl(call: MethodCall, result: Result) {
val url = call.argument<String>(ArgumentsConstants.URL.value)
if (url.isNullOrEmpty())
result.error(
ERROR_NOT_ARGUMENTS.code,
ERROR_NOT_ARGUMENTS.message,
ERROR_NOT_ARGUMENTS.details
)
DetectID.sdk(context).didRegistration(url!!, object : EnrollmentResultHandler {
override fun onSuccess() {
Log.d(TAG, "onSuccess()")
val value: MutableList<String> = ArrayList(1)
value.add("")
result.success(value)
}
override fun onFailure(exception: SDKException) {
Log.e(TAG, "onFailure: ", exception)
result.error("${exception.code}", exception.message, exception.localizedMessage)
}
})
}
private fun setApplicationName(call: MethodCall, result: Result) {
val name = call.argument<String>(ArgumentsConstants.NAME.value)
if (name.isNullOrEmpty())
result.error(
ERROR_NOT_ARGUMENTS.code, ERROR_NOT_ARGUMENTS.message, ERROR_NOT_ARGUMENTS.details
)
DetectID.sdk(context).setApplicationName(name)
val value: MutableList<String> = ArrayList(1)
value.add("")
result.success(value)
}
private fun getDeviceID(result: Result) {
val value: MutableList<String> = ArrayList(1)
value.add(DetectID.sdk(context).deviceID)
result.success(value)
}
private fun getMaskedAppInstanceID(result: Result) {
val value: MutableList<String> = ArrayList(1)
value.add(DetectID.sdk(context).maskedAppInstanceID)
result.success(value)
}
private fun getMobileID(result: Result) {
val value: MutableList<String> = ArrayList(1)
value.add(DetectID.sdk(context).mobileID)
result.success(value)
}
private fun initDID() {
this.sdk = DetectID.sdk(context)
}
override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
registerChannel.setMethodCallHandler(null)
accountsChannel.setMethodCallHandler(null)
qrChannel.setMethodCallHandler(null)
otpChannel.setMethodCallHandler(null)
pushChannel.setMethodCallHandler(null)
}
override fun onAttachedToActivity(binding: ActivityPluginBinding) {
binding.addOnNewIntentListener(this)
this.context = binding.activity
this.initDID()
}
override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
binding.addOnNewIntentListener(this)
this.context = binding.activity
this.initDID()
}
override fun onDetachedFromActivityForConfigChanges() {}
override fun onDetachedFromActivity() {}
override fun onNewIntent(intent: Intent): Boolean {
DIDPushUtil().getExtrasSendData(pushChannel,intent)
return true
}
companion object {
private var TAG = DidsdkPlugin::class.java.simpleName
}
}
| 0 | Kotlin | 0 | 0 | 1fa974c6ba221214898897d3750a1671028fbfc4 | 12,433 | fp-rba-didsdk-example-flutter-native-wrapper | MIT License |
geary-papermc-tracking/src/main/kotlin/com/mineinabyss/geary/papermc/tracking/entities/systems/AttemptSpawnListener.kt | MineInAbyss | 592,086,123 | false | null | package com.mineinabyss.geary.papermc.tracking.entities.systems
import com.mineinabyss.geary.annotations.Handler
import com.mineinabyss.geary.datatypes.family.family
import com.mineinabyss.geary.papermc.tracking.entities.components.AttemptSpawn
import com.mineinabyss.geary.papermc.tracking.entities.components.SetEntityType
import com.mineinabyss.geary.systems.GearyListener
import com.mineinabyss.geary.systems.accessors.EventScope
import com.mineinabyss.geary.systems.accessors.TargetScope
import com.mineinabyss.idofront.nms.aliases.toBukkit
import com.mineinabyss.idofront.nms.aliases.toNMS
import com.mineinabyss.idofront.typealiases.BukkitEntity
import net.minecraft.core.BlockPos
import net.minecraft.world.entity.MobSpawnType
import org.bukkit.event.entity.CreatureSpawnEvent
class AttemptSpawnListener : GearyListener() {
private val TargetScope.mobType by get<SetEntityType>()
private val EventScope.attemptSpawn by get<AttemptSpawn>()
val TargetScope.family by family {
not { has<BukkitEntity>() }
}
@Handler
fun TargetScope.handle(event: EventScope) {
val loc = event.attemptSpawn.location
val world = loc.world.toNMS()
mobType.entityTypeFromRegistry.spawn(
world,
null,
// We set the entity here so that we don't create a separate Geary entity in EntityWorldEventTracker
// This is called before adding to the world.
{ mob -> entity.set(mob.toBukkit()) },
BlockPos(loc.x.toInt(), loc.y.toInt(), loc.z.toInt()),
MobSpawnType.COMMAND,
false,
false,
CreatureSpawnEvent.SpawnReason.COMMAND
)
}
}
| 0 | Kotlin | 0 | 1 | afb0722015f1d6206b89cc09e210814361decd47 | 1,699 | geary-papermc | MIT License |
app/src/main/java/com/wechantloup/gamelistoptimization/webdownloader/WebDownloader.kt | Pilou44 | 414,594,767 | false | null | package com.wechantloup.gamelistoptimization.webdownloader
import com.wechantloup.gamelistoptimization.utils.FlipperUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.Call
import okhttp3.Callback
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okhttp3.ResponseBody
import java.io.File
import java.io.IOException
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine
class WebDownloader {
private val httpClient: OkHttpClient =
OkHttpClient.Builder()
.addNetworkInterceptor(FlipperUtils.createInterceptor())
.build()
suspend fun download(url: String, dest: File) = withContext(Dispatchers.IO) {
val assetResponse = httpClient.sendGetRequest(url)
dest.writeResponse(assetResponse)
}
private suspend fun OkHttpClient.sendGetRequest(url: String): Response {
val request = Request.Builder()
.url(url)
.get()
.build()
return sendRequest(request)
}
private class UnsuccessfulException(response: Response, serializedBody: String) :
Exception("${response.requestUrl()} - ${response.code} - body: $serializedBody")
private class NoBodyException(response: Response) : Exception("${response.requestUrl()} - ${response.code}")
companion object {
private suspend fun OkHttpClient.sendRequest(request: Request): Response = suspendCoroutine { continuation ->
try {
newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
continuation.resumeWithException(e)
}
override fun onResponse(call: Call, response: Response) {
continuation.resume(response)
}
})
} catch (e: Exception) {
continuation.resumeWithException(e)
}
}
private fun File.writeResponse(response: Response) {
response.useSuccessfulBodyOrThrow {
writeBytes(it.bytes())
}
}
private fun Response.useSuccessfulBodyOrThrow(action: (ResponseBody) -> Unit) {
use { response ->
val responseBody = response.body ?: throw NoBodyException(response)
responseBody.use { body ->
if (response.isSuccessful) {
action(body)
} else {
throw UnsuccessfulException(response, body.string())
}
}
}
}
private fun Response.requestUrl(): String = request.url.toString()
}
}
| 0 | Kotlin | 0 | 0 | b49d5228d2ef796b4aff0f7afb87b2bbc5ca168d | 2,825 | GameListOptimization | Apache License 2.0 |
src/main/kotlin/io/prometheus/common/ScrapeResults.kt | pambrose | 87,608,617 | false | null | /*
* Copyright © 2020 <NAME> (<EMAIL>)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("UndocumentedPublicClass", "UndocumentedPublicFunction")
package io.prometheus.common
import com.github.pambrose.common.util.EMPTY_BYTE_ARRAY
import io.ktor.http.HttpStatusCode
internal class ScrapeResults(val agentId: String,
val scrapeId: Long,
var validResponse: Boolean = false,
var statusCode: Int = HttpStatusCode.NotFound.value,
var contentType: String = "",
var zipped: Boolean = false,
var contentAsText: String = "",
var contentAsZipped: ByteArray = EMPTY_BYTE_ARRAY,
var failureReason: String = "",
var url: String = "") {
fun setDebugInfo(url: String, failureReason: String = "") {
this.url = url
this.failureReason = failureReason
}
} | 4 | Kotlin | 16 | 94 | 92ff24c8d2a6955ab11b4f79fcb79c6aea8ff786 | 1,548 | prometheus-proxy | Apache License 2.0 |
video-sdk/src/main/java/com/kaleyra/video_sdk/utils/WindowSizeClassUtil.kt | KaleyraVideo | 686,975,102 | false | {"Kotlin": 5207104, "Shell": 7470, "Python": 6799, "Java": 2583} | package com.kaleyra.video_sdk.utils
import android.content.res.Configuration
import androidx.compose.material3.windowsizeclass.ExperimentalMaterial3WindowSizeClassApi
import androidx.compose.material3.windowsizeclass.WindowSizeClass
import androidx.compose.material3.windowsizeclass.WindowWidthSizeClass
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.unit.DpSize
import androidx.compose.ui.unit.dp
internal object WindowSizeClassUtil {
@OptIn(ExperimentalMaterial3WindowSizeClassApi::class)
@Composable
fun currentWindowAdaptiveInfo(configuration: Configuration = LocalConfiguration.current): WindowSizeClass {
val size = DpSize(configuration.screenWidthDp.dp, configuration.screenHeightDp.dp)
return WindowSizeClass.calculateFromSize(size)
}
fun WindowSizeClass.isAtLeastMediumWidth(): Boolean {
return widthSizeClass in setOf(WindowWidthSizeClass.Medium, WindowWidthSizeClass.Expanded)
}
}
| 0 | Kotlin | 0 | 1 | 9faa41e5903616889f2d0cd79ba21e18afe800ed | 1,022 | VideoAndroidSDK | Apache License 2.0 |
app/src/main/java/com/example/compose/rally/data/util/csv/CSVParser.kt | lloppy | 718,107,694 | false | {"Kotlin": 191709} | package com.example.compose.rally.data.util.csv
import android.content.Context
import android.net.Uri
import android.os.Build
import android.util.Log
import android.widget.Toast
import androidx.annotation.RequiresApi
import com.example.compose.rally.R
import com.example.compose.rally.data.account.Account
import com.example.compose.rally.data.account.AccountRepository
import com.example.compose.rally.data.bill.Bill
import com.example.compose.rally.data.bill.BillRepository
import com.example.compose.rally.data.category.defaultAccountCategories
import com.example.compose.rally.data.category.defaultBillCategories
import java.io.BufferedReader
import java.io.InputStreamReader
import java.nio.charset.Charset.*
import java.time.LocalDateTime
//* 1. "Дата операции";
// 2. "Дата платежа";
// 3. "Номер карты";
// 4. "Статус";
// 5. "Сумма операции";
// 6. "Валюта операции";
// 7. "Сумма платежа";
// 8. "Валюта платежа";
// 9. "Кэшбэк";
// 10. "Категория";
// 11. "MCC";
// 12. "Описание";
// 13. "Бонусы (включая кэшбэк)";
// 14. "Округление на инвесткопилку";
// 15. "Сумма операции с округлением"/
@RequiresApi(Build.VERSION_CODES.O)
fun handleCSVFile(context: Context, uri: Uri) {
try {
val inputStream = context.contentResolver.openInputStream(uri)
val reader = BufferedReader(InputStreamReader(inputStream, forName("Windows-1251")))
var line: String?
while (reader.readLine().also { line = it } != null) {
var cleanLine = line!!.replace("\"", "")
var groups = cleanLine.split(";")
Log.e("csv", "${groups[4].first()} date is ${groups[0]} ")
if (groups[4].first() == '-') {
takeExpenseSplit(groups, context)
} else if (groups[4].first().isDigit()) {
takeIncomeSplit(groups)
}
}
reader.close()
inputStream?.close()
Toast.makeText(context, context.getString(R.string.read_sucsess), Toast.LENGTH_SHORT).show()
} catch (e: Exception) {
e.printStackTrace()
Toast.makeText(context, context.getString(R.string.error_occured), Toast.LENGTH_SHORT)
.show()
}
}
@RequiresApi(Build.VERSION_CODES.O)
fun takeIncomeSplit(group: List<String>) {
val regex = "^(\\d{2}).(\\d{2}).(\\d{4}) (\\d{2}):(\\d{2}):\\d{2}".toRegex()
val matchResult = regex.find(group[0])
val (day, month, year, hour, minute) = matchResult!!.destructured
val balance = group[14].split(",")
if (!defaultAccountCategories.contains(group[9])) {
defaultAccountCategories += group[9]
}
var name = group[11]
var counter = 0
while (AccountRepository.accounts.any { account -> account.name == name }) {
name = "${group[11]} ${++counter}"
}
AccountRepository.addAccount(
Account(
name = name,
date = LocalDateTime.of(
year.toInt(),
month.toInt(),
day.toInt(),
hour.toInt(),
minute.toInt()
),
timesRepeat = 0,
cardNumber = if (group[2].isNullOrEmpty()) 0 else group[2].replace("*", "").toInt(),
balance = balance[0].toFloat() + (balance[1].toFloat() / 100),
category = group[9]
)
)
}
@RequiresApi(Build.VERSION_CODES.O)
fun takeExpenseSplit(group: List<String>, context: Context) {
val regex = "^(\\d{2}).(\\d{2}).(\\d{4}) (\\d{2}):(\\d{2}):\\d{2}".toRegex()
val matchResult = regex.find(group[0])
val (day, month, year, hour, minute) = matchResult!!.destructured
val amount = group[14].split(",")
if (!defaultBillCategories.contains(group[9])) {
defaultBillCategories += group[9]
}
var name = group[11]
var counter = 0
while (BillRepository.bills.any { bill -> bill.name == name }) {
name = "${group[11]} ${++counter}"
}
BillRepository.addBill(
Bill(
name = name,
date = LocalDateTime.of(
year.toInt(),
month.toInt(),
day.toInt(),
hour.toInt(),
minute.toInt()
),
timesRepeat = 0,
billPhoto = null,
category = group[9],
mcc = if (group[10].isNullOrEmpty()) null else group[10].toInt(),
amount = amount[0].toFloat() + (amount[1].toFloat() / 100),
),
context = context
)
}
| 5 | Kotlin | 1 | 0 | bec0bd2d1822f41ed0f050f97f7110b06e59f4ff | 4,472 | Finance-Assistant | MIT License |
core/builtins/src/kotlin/internal/progressionUtil.kt | gigliovale | 89,726,097 | false | null | /*
* Copyright 2010-2015 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 kotlin.internal
// a mod b (in arithmetical sense)
private fun mod(a: Int, b: Int): Int {
val mod = a % b
return if (mod >= 0) mod else mod + b
}
private fun mod(a: Long, b: Long): Long {
val mod = a % b
return if (mod >= 0) mod else mod + b
}
// (a - b) mod c
private fun differenceModulo(a: Int, b: Int, c: Int): Int {
return mod(mod(a, c) - mod(b, c), c)
}
private fun differenceModulo(a: Long, b: Long, c: Long): Long {
return mod(mod(a, c) - mod(b, c), c)
}
/**
* Calculates the final element of a bounded arithmetic progression, i.e. the last element of the progression which is in the range
* from [start] to [end] in case of a positive [increment], or from [end] to [start] in case of a negative
* increment.
*
* No validation on passed parameters is performed. The given parameters should satisfy the condition: either
* `increment > 0` and `start >= end`, or `increment < 0` and`start >= end`.
* @param start first element of the progression
* @param end ending bound for the progression
* @param increment increment, or difference of successive elements in the progression
* @return the final element of the progression
* @suppress
*/
public fun getProgressionFinalElement(start: Int, end: Int, increment: Int): Int {
if (increment > 0) {
return end - differenceModulo(end, start, increment)
}
else {
return end + differenceModulo(start, end, -increment)
}
}
/**
* Calculates the final element of a bounded arithmetic progression, i.e. the last element of the progression which is in the range
* from [start] to [end] in case of a positive [increment], or from [end] to [start] in case of a negative
* increment.
*
* No validation on passed parameters is performed. The given parameters should satisfy the condition: either
* `increment > 0` and `start >= end`, or `increment < 0` and`start >= end`.
* @param start first element of the progression
* @param end ending bound for the progression
* @param increment increment, or difference of successive elements in the progression
* @return the final element of the progression
* @suppress
*/
public fun getProgressionFinalElement(start: Long, end: Long, increment: Long): Long {
if (increment > 0) {
return end - differenceModulo(end, start, increment)
}
else {
return end + differenceModulo(start, end, -increment)
}
}
| 5 | null | 4 | 6 | ce145c015d6461c840050934f2200dbc11cb3d92 | 3,010 | kotlin | Apache License 2.0 |
compiler/testData/codegen/box/inlineClasses/UIntArraySortExample.kt | JakeWharton | 99,388,807 | false | null | // KJS_WITH_FULL_RUNTIME
// !LANGUAGE: +InlineClasses
// IGNORE_BACKEND: JVM_IR
inline class UInt(private val value: Int) : Comparable<UInt> {
companion object {
private const val INT_MASK = 0xffffffffL
}
fun asInt(): Int = value
fun toLong(): Long = value.toLong() and INT_MASK
override fun compareTo(other: UInt): Int =
flip().compareTo(other.flip())
override fun toString(): String {
return toLong().toString()
}
private fun flip(): Int =
value xor Int.MIN_VALUE
}
inline class UIntArray(private val intArray: IntArray) {
val size: Int get() = intArray.size
operator fun get(index: Int): UInt = UInt(intArray[index])
operator fun set(index: Int, value: UInt) {
intArray[index] = value.asInt()
}
operator fun iterator(): UIntIterator = UIntIterator(intArray.iterator())
}
inline class UIntIterator(private val intIterator: IntIterator) : Iterator<UInt> {
override fun next(): UInt {
return UInt(intIterator.next())
}
override fun hasNext(): Boolean {
return intIterator.hasNext()
}
}
fun uIntArrayOf(vararg u: Int): UIntArray = UIntArray(u)
fun UIntArray.swap(i: Int, j: Int) {
this[j] = this[i].also { this[i] = this[j] }
}
fun UIntArray.quickSort() {
quickSort(0, size - 1)
}
private fun UIntArray.quickSort(l: Int, r: Int) {
if (l < r) {
val q = partition(l, r)
quickSort(l, q - 1)
quickSort(q + 1, r)
}
}
private fun UIntArray.partition(l: Int, r: Int): Int {
val m = this[(l + r) / 2]
var i = l
var j = r
while (i <= j) {
while (this[i] < m) i++
while (this[j] > m) j--
if (i <= j)
swap(i++, j--)
}
return i
}
fun check(array: UIntArray, resultAsInt: String, resultAsInner: String) {
val actualAsInt = StringBuilder()
val actualAsInner = StringBuilder()
for (n in array) {
actualAsInt.append("${n.asInt()} ")
actualAsInner.append(n.toString() + " ")
}
if (actualAsInt.toString() != resultAsInt) {
throw IllegalStateException("wrong result as int (actual): $actualAsInt ; expected: $resultAsInt")
}
if (actualAsInner.toString() != resultAsInner) {
throw IllegalStateException("wrong result as inner (actual): $actualAsInner ; expected: $resultAsInner")
}
}
fun box(): String {
val a1 = uIntArrayOf(1, 2, 3)
a1.quickSort()
check(a1, "1 2 3 ", "1 2 3 ")
val a2 = uIntArrayOf(-1)
a2.quickSort()
check(a2, "-1 ", "4294967295 ")
val a3 = uIntArrayOf(-1, 1, 0)
a3.quickSort()
check(a3, "0 1 -1 ", "0 1 4294967295 ")
val a4 = uIntArrayOf(-1, Int.MAX_VALUE)
a4.quickSort()
check(a4, "${Int.MAX_VALUE} -1 ", "2147483647 4294967295 ")
return "OK"
} | 181 | null | 5748 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 2,814 | kotlin | Apache License 2.0 |
src/main/kotlin/io/xhub/confIOMessenger/domain/Message.kt | x-hub | 109,389,736 | false | {"Kotlin": 15330} | package io.xhub.confIOMessenger.domain
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.databind.node.BooleanNode
import io.vertx.core.json.JsonObject
import io.xhub.confIOMessenger.annotation.IgnoreNotNullUnknown
@IgnoreNotNullUnknown
sealed class Message(
@JsonProperty()
open val text:String?=null,
@JsonProperty("is_echo")
val is_echo:Boolean?= null
){
@IgnoreNotNullUnknown
data class ReceivedMessage(
@JsonProperty("text")
override var text:String?=null,
@JsonProperty("attachments")
val attachments:List<Attachement>?=null,
@JsonProperty("quick_reply")
val quick_reply:QuickReply?=null
) :Message(text)
@IgnoreNotNullUnknown
data class SentMessage(
@JsonProperty("text")
override var text:String?=null,
@JsonProperty("attachment")
val attachment:Attachement?=null,
@JsonProperty("quick_replies")
val quick_replies:List<QuickReply>?= null
):Message(text)
}
| 0 | Kotlin | 2 | 0 | a13323ca0103fabca5dea64e6cd70ff450e8d23e | 1,213 | confIO.messenger | MIT License |
src/main/kotlin/io/xhub/confIOMessenger/domain/Message.kt | x-hub | 109,389,736 | false | {"Kotlin": 15330} | package io.xhub.confIOMessenger.domain
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.databind.node.BooleanNode
import io.vertx.core.json.JsonObject
import io.xhub.confIOMessenger.annotation.IgnoreNotNullUnknown
@IgnoreNotNullUnknown
sealed class Message(
@JsonProperty()
open val text:String?=null,
@JsonProperty("is_echo")
val is_echo:Boolean?= null
){
@IgnoreNotNullUnknown
data class ReceivedMessage(
@JsonProperty("text")
override var text:String?=null,
@JsonProperty("attachments")
val attachments:List<Attachement>?=null,
@JsonProperty("quick_reply")
val quick_reply:QuickReply?=null
) :Message(text)
@IgnoreNotNullUnknown
data class SentMessage(
@JsonProperty("text")
override var text:String?=null,
@JsonProperty("attachment")
val attachment:Attachement?=null,
@JsonProperty("quick_replies")
val quick_replies:List<QuickReply>?= null
):Message(text)
}
| 0 | Kotlin | 2 | 0 | a13323ca0103fabca5dea64e6cd70ff450e8d23e | 1,213 | confIO.messenger | MIT License |
client/jfx/src/main/kotlin/net/corda/client/jfx/model/TransactionDataModel.kt | corda | 70,137,417 | false | null | package net.corda.client.jfx.model
import javafx.beans.value.ObservableValue
import net.corda.client.jfx.utils.distinctBy
import net.corda.client.jfx.utils.lift
import net.corda.client.jfx.utils.map
import net.corda.client.jfx.utils.recordInSequence
import net.corda.core.contracts.*
import net.corda.core.crypto.entropyToKeyPair
import net.corda.core.identity.AbstractParty
import net.corda.core.identity.CordaX500Name
import net.corda.core.identity.Party
import net.corda.core.internal.eagerDeserialise
import net.corda.core.transactions.LedgerTransaction
import net.corda.core.transactions.SignedTransaction
import net.corda.core.transactions.WireTransaction
import java.math.BigInteger.ZERO
private class Unknown : Contract {
override fun verify(tx: LedgerTransaction) = throw UnsupportedOperationException()
object State : ContractState {
override val participants: List<AbstractParty> = emptyList()
}
}
/**
* [PartiallyResolvedTransaction] holds a [SignedTransaction] that has zero or more inputs resolved. The intent is
* to prepare clients for cases where an input can only be resolved in the future/cannot be resolved at all (for example
* because of permissioning)
*/
data class PartiallyResolvedTransaction(
val transaction: SignedTransaction,
val inputs: List<ObservableValue<InputResolution>>,
val outputs: List<ObservableValue<out OutputResolution>>) {
val id = transaction.id
sealed class InputResolution {
abstract val stateRef: StateRef
data class Unresolved(override val stateRef: StateRef) : InputResolution()
data class Resolved(val stateAndRef: StateAndRef<ContractState>) : InputResolution() {
override val stateRef: StateRef get() = stateAndRef.ref
}
}
sealed class OutputResolution {
abstract val stateRef: StateRef
data class Unresolved(override val stateRef: StateRef) : OutputResolution()
data class Resolved(val stateAndRef: StateAndRef<ContractState>) : OutputResolution() {
override val stateRef: StateRef get() = stateAndRef.ref
}
}
companion object {
private val DUMMY_NOTARY = Party(CordaX500Name("Dummy Notary", "Nowhere", "ZZ"), entropyToKeyPair(ZERO).public)
fun fromSignedTransaction(
transaction: SignedTransaction,
inputTransactions: Map<StateRef, SignedTransaction?>
): PartiallyResolvedTransaction {
/**
* Forcibly deserialize our transaction outputs up-front.
* Replace any [TransactionState] objects that fail to
* deserialize with a dummy transaction state that uses
* the transaction's notary.
*/
val unknownTransactionState = TransactionState(
data = Unknown.State,
contract = Unknown::class.java.name,
notary = transaction.notary ?: DUMMY_NOTARY
)
transaction.coreTransaction.outputs.eagerDeserialise { _, _ -> unknownTransactionState }
return PartiallyResolvedTransaction(
transaction = transaction,
inputs = transaction.inputs.map { stateRef ->
val tx = inputTransactions[stateRef]
if (tx == null) {
InputResolution.Unresolved(stateRef)
} else {
InputResolution.Resolved(tx.coreTransaction.outRef(stateRef.index))
}.lift()
},
outputs = if (transaction.coreTransaction is WireTransaction) {
transaction.tx.outRefsOfType<ContractState>().map {
OutputResolution.Resolved(it).lift()
}
} else {
// Transaction will have the same number of outputs as inputs
val outputCount = transaction.coreTransaction.inputs.size
val stateRefs = (0 until outputCount).map { StateRef(transaction.id, it) }
stateRefs.map { stateRef ->
val tx = inputTransactions[stateRef]
if (tx == null) {
OutputResolution.Unresolved(stateRef)
} else {
OutputResolution.Resolved(tx.coreTransaction.outRef(stateRef.index))
}.lift()
}
})
}
}
}
/**
* This model provides an observable list of transactions and what state machines/flows recorded them
*/
class TransactionDataModel {
private val transactions by observable(NodeMonitorModel::transactions)
private val collectedTransactions = transactions.recordInSequence().distinctBy { it.id }
private val rpcProxy by observableValue(NodeMonitorModel::proxyObservable)
@Suppress("DEPRECATION")
val partiallyResolvedTransactions = collectedTransactions.map {
PartiallyResolvedTransaction.fromSignedTransaction(it,
it.inputs.map { stateRef ->
stateRef to rpcProxy.value!!.cordaRPCOps.internalFindVerifiedTransaction(stateRef.txhash)
}.toMap())
}
}
| 62 | null | 1077 | 3,989 | d27aa0e6850d3804d0982024054376d452e7073a | 5,345 | corda | Apache License 2.0 |
src/test/java/io/javalin/TestStaticFiles.kt | xxDark | 268,796,863 | false | null | /*
* Javalin - https://javalin.io
* Copyright 2017 <NAME>
* Licensed under Apache 2.0: https://github.com/tipsy/javalin/blob/master/LICENSE
*
*/
package io.javalin
import io.javalin.core.util.Header
import io.javalin.core.util.OptionalDependency
import io.javalin.http.UnauthorizedResponse
import io.javalin.http.staticfiles.Location
import org.assertj.core.api.Assertions.assertThat
import org.eclipse.jetty.server.ServletResponseHttpWrapper
import org.eclipse.jetty.servlet.FilterHolder
import org.junit.Test
import java.util.*
import javax.servlet.*
class TestStaticFiles {
private val defaultStaticResourceApp = Javalin.create { it.addStaticFiles("/public") } // classpath
private val externalStaticResourceApp = Javalin.create { it.addStaticFiles("src/test/external/", Location.EXTERNAL) }
private val multiLocationStaticResourceApp = Javalin.create { servlet ->
servlet.addStaticFiles("src/test/external/", Location.EXTERNAL)
servlet.addStaticFiles("/public/immutable")
servlet.addStaticFiles("/public/protected")
servlet.addStaticFiles("/public/subdir")
}
private val devLoggingApp = Javalin.create {
it.addStaticFiles("/public")
it.enableDevLogging()
}
private val customFilterStaticResourceApp = Javalin.create {
val filter = object : Filter {
override fun init(config: FilterConfig?) {
}
override fun doFilter(request: ServletRequest?, response: ServletResponse?, chain: FilterChain?) {
chain?.doFilter(request, ServletResponseHttpWrapper(response))
}
override fun destroy() {
}
}
it.addStaticFiles("/public")
it.configureServletContextHandler { handler ->
handler.addFilter(FilterHolder(filter), "/*", EnumSet.allOf(DispatcherType::class.java))
}
}
@Test
fun `serving HTML from classpath works`() = TestUtil.test(defaultStaticResourceApp) { _, http ->
assertThat(http.get("/html.html").status).isEqualTo(200)
assertThat(http.get("/html.html").headers.getFirst(Header.CONTENT_TYPE)).contains("text/html")
assertThat(http.getBody("/html.html")).contains("HTML works")
}
@Test
fun `serving JS from classpath works`() = TestUtil.test(defaultStaticResourceApp) { _, http ->
assertThat(http.get("/script.js").status).isEqualTo(200)
assertThat(http.get("/script.js").headers.getFirst(Header.CONTENT_TYPE)).contains("application/javascript")
assertThat(http.getBody("/script.js")).contains("JavaScript works")
}
@Test
fun `serving CSS from classpath works`() = TestUtil.test(defaultStaticResourceApp) { _, http ->
assertThat(http.get("/styles.css").status).isEqualTo(200)
assertThat(http.get("/styles.css").headers.getFirst(Header.CONTENT_TYPE)).contains("text/css")
assertThat(http.getBody("/styles.css")).contains("CSS works")
}
@Test
fun `before-handler runs before static resources`() = TestUtil.test(defaultStaticResourceApp) { app, http ->
app.before("/protected/*") { throw UnauthorizedResponse("Protected") }
assertThat(http.get("/protected/secret.html").status).isEqualTo(401)
assertThat(http.getBody("/protected/secret.html")).isEqualTo("Protected")
}
@Test
fun `directory root returns simple 404 if there is no welcome file`() = TestUtil.test(defaultStaticResourceApp) { _, http ->
assertThat(http.get("/").status).isEqualTo(404)
assertThat(http.getBody("/")).isEqualTo("Not found")
}
@Test
fun `directory root return welcome file if there is a welcome file`() = TestUtil.test(defaultStaticResourceApp) { _, http ->
assertThat(http.get("/subdir/").status).isEqualTo(200)
assertThat(http.getBody("/subdir/")).isEqualTo("<h1>Welcome file</h1>")
}
@Test
fun `expires is set to max-age=0 by default`() = TestUtil.test(defaultStaticResourceApp) { _, http ->
assertThat(http.get("/script.js").headers.getFirst(Header.CACHE_CONTROL)).isEqualTo("max-age=0")
}
@Test
fun `expires is set to 1 year for files in immutable directory`() = TestUtil.test(defaultStaticResourceApp) { _, http ->
assertThat(http.get("/immutable/library-1.0.0.min.js").headers.getFirst(Header.CACHE_CONTROL)).isEqualTo("max-age=31622400")
}
@Test
fun `files in external locations are found`() = TestUtil.test(externalStaticResourceApp) { _, http ->
assertThat(http.get("/html.html").status).isEqualTo(200)
assertThat(http.getBody("/html.html")).contains("HTML works")
}
@Test
fun `one app can handle multiple static file locations`() = TestUtil.test(multiLocationStaticResourceApp) { _, http ->
assertThat(http.get("/html.html").status).isEqualTo(200) // src/test/external/html.html
assertThat(http.getBody("/html.html")).contains("HTML works")
assertThat(http.get("/").status).isEqualTo(200)
assertThat(http.getBody("/")).isEqualTo("<h1>Welcome file</h1>")
assertThat(http.get("/secret.html").status).isEqualTo(200)
assertThat(http.getBody("/secret.html")).isEqualTo("<h1>Secret file</h1>")
assertThat(http.get("/styles.css").status).isEqualTo(404)
}
@Test
fun `content type works in debugmmode`() = TestUtil.test(devLoggingApp) { _, http ->
assertThat(http.get("/html.html").status).isEqualTo(200)
assertThat(http.get("/html.html").headers.getFirst(Header.CONTENT_TYPE)).contains("text/html")
assertThat(http.getBody("/html.html")).contains("HTML works")
assertThat(http.get("/script.js").headers.getFirst(Header.CONTENT_TYPE)).contains("application/javascript")
assertThat(http.get("/styles.css").headers.getFirst(Header.CONTENT_TYPE)).contains("text/css")
}
@Test
fun `WebJars available if enabled`() = TestUtil.test(Javalin.create { it.enableWebjars() }) { _, http ->
assertThat(http.get("/webjars/swagger-ui/${OptionalDependency.SWAGGERUI.version}/swagger-ui.css").status).isEqualTo(200)
assertThat(http.get("/webjars/swagger-ui/${OptionalDependency.SWAGGERUI.version}/swagger-ui.css").headers.getFirst(Header.CONTENT_TYPE)).contains("text/css")
assertThat(http.get("/webjars/swagger-ui/${OptionalDependency.SWAGGERUI.version}/swagger-ui.css").headers.getFirst(Header.CACHE_CONTROL)).isEqualTo("max-age=31622400")
}
@Test
fun `WebJars not available if not enabled`() = TestUtil.test { _, http ->
assertThat(http.get("/webjars/swagger-ui/${OptionalDependency.SWAGGERUI.version}/swagger-ui.css").status).isEqualTo(404)
}
@Test
fun `Correct content type is returned when a custom filter with a response wrapper is added`() = TestUtil.test(customFilterStaticResourceApp) { _, http ->
assertThat(http.get("/html.html").status).isEqualTo(200)
assertThat(http.get("/html.html").headers.getFirst(Header.CONTENT_TYPE)).contains("text/html")
}
}
| 1 | null | 1 | 1 | ac4eadd2113272801e7103167f6cf2646e1e6958 | 7,038 | javalin | Apache License 2.0 |
basick/src/main/java/com/mozhimen/basick/utilk/android/view/UtilKInputMethodManagerWrapper.kt | mozhimen | 353,952,154 | false | null | package com.mozhimen.basick.utilk.android.view
import android.app.Activity
import android.content.Context
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import androidx.annotation.RequiresApi
import com.mozhimen.basick.elemk.android.os.cons.CVersCode
import com.mozhimen.basick.elemk.android.view.cons.CKeyEvent
import com.mozhimen.basick.lintk.optin.OptInApiDeprecated_Official_AfterV_31_11_S
import com.mozhimen.basick.utilk.bases.BaseUtilK
import com.mozhimen.basick.utilk.android.content.UtilKContext
import com.mozhimen.basick.utilk.android.app.UtilKActivity
import com.mozhimen.basick.utilk.android.os.UtilKBuildVersion
import com.mozhimen.basick.utilk.android.util.dt
import com.mozhimen.basick.utilk.android.util.et
import com.mozhimen.basick.utilk.java.lang.UtilKReflect
import java.lang.reflect.Field
/**
* @ClassName UtilKKeyBoard
* @Description 如果你希望他在7.0生效,你还需设置manifest->android:windowSoftInputMode="stateAlwaysHidden"
* @Author mozhimen / <NAME>
* @Date 2022/1/15 20:01
* @Version 1.0
*/
object UtilKInputManager : BaseUtilK() {
/**
* 是否显示
*/
@JvmStatic
fun isShow(activity: Activity): Boolean =
UtilKDecorView.getInvisibleHeight(activity) > 0
/**
* 是否需要隐藏软键盘
* Return whether touch the view.
* for Example:
*
* inActivity:
*
override fun dispatchTouchEvent(event: MotionEvent?): Boolean {
if (event?.action == MotionEvent.ACTION_DOWN) {
val focusView: View? = currentFocus
if (focusView != null && UtilKKeyBoard.isShouldHide(focusView, event)) {
UtilKKeyBoard.hide(this)
}
}
return super.dispatchTouchEvent(event)
}
*
* inFragment:
*
@SuppressLint("ClickableViewAccessibility")
override fun inflateView(viewGroup: ViewGroup?) {
viewGroup?.setOnTouchListener { _, event ->
if (event?.action == MotionEvent.ACTION_DOWN) {
val focusView: View? = requireActivity().currentFocus
if (focusView != null && UtilKKeyBoard.isShouldHide(focusView, event)) {
UtilKKeyBoard.hide(requireActivity())
}
}
false
}
super.inflateView(viewGroup)
}
* @param view View 如果焦点不是EditText则忽略,这个发生在视图刚绘制完,第一个焦点不在EditView上,和用户用轨迹球选择其他的焦点
* @param event MotionEvent
* @return Boolean
*/
fun isShouldHide(view: View, event: MotionEvent): Boolean {
if (view is EditText) {
val ints = intArrayOf(0, 0)
view.getLocationOnScreen(ints)
val left = ints[0]
val top = ints[1]
val bottom = top + view.getHeight()
val right = left + view.getWidth()
return !(event.rawX > left && event.rawX < right && event.rawY > top && event.rawY < bottom)
}
return false
}
////////////////////////////////////////////////////////////////////////////
/**
* 显示软键盘
*/
@JvmStatic
fun show(activity: Activity) {
if (UtilKInputMethodManager.isActive(activity) && UtilKActivity.getCurrentFocus(activity) != null)
show(UtilKActivity.getCurrentFocus(activity)!!)
}
/**
* 显示软键盘
*/
@JvmStatic
fun show(view: View) {
var focusView = view
if (!view.hasFocus()) {
UtilKView.applyRequestFocus(view)
view.findFocus()?.let { focusView = it }
}
UtilKInputMethodManager.showSoftInput(focusView)
}
/**
* 显示系统键盘
* @param editText 需要操作的输入框
*/
fun show(editText: EditText) {
if (!editText.isEnabled || !editText.hasFocus()) return
show(editText as View)
}
/**
* 延迟显示软键盘
*/
@JvmStatic
fun showByDelay(view: View, delayMillis: Long) {
view.postDelayed({ show(view) }, delayMillis)
}
/**
* 关闭软键盘
*/
@JvmStatic
fun hide(activity: Activity) {
if (((UtilKWindow.getPeekDecorView(activity) != null || UtilKInputMethodManager.isActive(activity)) && UtilKActivity.getCurrentFocus(activity) != null) && isShow(activity))
hide(UtilKActivity.getCurrentFocus(activity)!!)
}
/**
* 隐藏软键盘
*/
@JvmStatic
fun hide(view: View) {
if (UtilKInputMethodManager.isActive(view))
UtilKInputMethodManager.hideSoftInputFromWindow(view)
}
/**
* 点击空白地方隐藏软键盘
* Click blank area to hide soft input.
* Copy the following code in ur activity.
*/
@JvmStatic
fun hideByClickOther() {
Log.d(TAG, "hideByClickOther: Please refer to the following code.")
//kotlin
/*override fun dispatchTouchEvent(event: MotionEvent?): Boolean {
if (event?.action == MotionEvent.ACTION_DOWN) {
val focusView: View? = currentFocus
if (focusView != null && UtilKKeyBoard.isShouldHide(focusView, event)) {
UtilKKeyBoard.hide(this)
}
}
return super.dispatchTouchEvent(event)
}*/
//java
/*
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
View view = getCurrentFocus();
if (UtilKKeyBoard.isShouldHideKeyboard(view, ev)) {
UtilKKeyBoard.hide(this);
}
}
return super.dispatchTouchEvent(ev);
}
*/
}
/**
* Click blank area to hide soft input.
* Copy the following code in ur activity.
*/
@JvmStatic
fun clickBlankAreaToHide() {
}
@JvmStatic
fun handleKeyEventHide(view: View, keyCode: Int) {
if (keyCode == CKeyEvent.KEYCODE_ENTER)
hide(view)
}
////////////////////////////////////////////////////////////////////////////
/**
* 修复在RecyclerView中持有内存泄漏的问题
*/
@JvmStatic
fun fixInputLeak(context: Context, tag: String) {
if (UtilKBuildVersion.isAfterV_29_10_Q())
fixInputLeakAfter29(context, tag)
else
fixInputLeakBefore29(context, tag)
}
/**
* 修复在RecyclerView中持有内存泄漏的问题
*/
@JvmStatic
@RequiresApi(CVersCode.V_29_10_Q)
fun fixInputLeakAfter29(context: Context, tag: String) {
val inputMethodManager = UtilKInputMethodManager.get(context)
try {
val fieldMCurRootView = UtilKReflect.getField(inputMethodManager, "mCurRootView")
if (!fieldMCurRootView.isAccessible)
fieldMCurRootView.isAccessible = true
val mCurRootView = fieldMCurRootView.get(inputMethodManager)
if (mCurRootView != null) {
val fieldMImeFocusController = UtilKReflect.getField(mCurRootView, "mImeFocusController")
if (!fieldMImeFocusController.isAccessible)
fieldMImeFocusController.isAccessible = true
val mImeFocusController = fieldMImeFocusController.get(mCurRootView)
if (mImeFocusController != null) {
val fieldMNextServedView = UtilKReflect.getField(mImeFocusController, "mNextServedView")
if (!fieldMNextServedView.isAccessible)
fieldMNextServedView.isAccessible = true
val mNextServedView = fieldMNextServedView.get(mImeFocusController)
if (mNextServedView != null) {
val fieldMParent = UtilKReflect.getField(mNextServedView, "mParent")
if (!fieldMParent.isAccessible)
fieldMParent.isAccessible = true
val mParent = fieldMParent.get(mNextServedView)
if (mParent != null) {
fieldMParent.set(mParent, null)
Log.d(TAG, "fixInputMethodLeak: $tag set view mNextServedView: mParent null in inputMethodManager")
}
// val mParent1Field = UtilKReflect.getField(mParentObj, "mParent")
// if (!mParent1Field.isAccessible) mParent1Field.isAccessible = true
// val mParent1Obj = mParent1Field.get(mParentObj)
// if (mParent1Obj != null) {
// mParent1Field.set(mParent1Obj, null)
// Log.d(TAG, "fixInputMethodLeak: $tag set view mNextServedView: mParent null in inputMethodManager")
// }
}
}
}
} catch (e: Exception) {
e.printStackTrace()
e.message?.et(TAG)
}
}
/**
* 修复在RecyclerView中持有内存泄漏的问题
*/
@JvmStatic
fun fixInputLeakBefore29(context: Context, tag: String) {
if (UtilKBuildVersion.isAfterV_29_10_Q()) return
val inputMethodManager = UtilKContext.getInputMethodManager(context)
val leakViews = arrayOf("mCurRootView", "mServedView", "mNextServedView")
var fieldLeakView: Field
var view: Any?
for (leakView in leakViews) {
try {
fieldLeakView = UtilKReflect.getField(inputMethodManager, leakView)
if (!fieldLeakView.isAccessible)
fieldLeakView.isAccessible = true
view = fieldLeakView.get(inputMethodManager)
if (view != null && view is View) {
if (view.context == context) { //注意需要判断View关联的Context是不是当前Activity,否则有可能造成正常的输入框输入失效
fieldLeakView.set(inputMethodManager, null)
"fixInputMethodLeakBefore29: $tag set view $leakView null in inputMethodManager".dt(TAG)
} else
break
}
} catch (e: Exception) {
e.printStackTrace()
e.message?.et(TAG)
}
}
}
}
/////////////////////////////////////////////////////////////////////////
//object UtilKKeyBoard {
// private val _context = UtilKApplication.instance.applicationContext
//
// /**
// * 显示软键盘
// * @param context Context
// */
// @JvmStatic
// fun toggle(context: Context) {
// (context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager).toggleSoftInput(0, 0)
// }
//
// /**
// * Toggle the soft input display or not.
// */
// fun toggle() {
// (_context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager).toggleSoftInput(0, 0)
// }
//
// /**
// * 显示软键盘
// */
// @JvmStatic
// fun show() {
// (_context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager).toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY)
// }
//
// /**
// * 显示软键盘
// * @param activity Activity
// */
// @JvmStatic
// fun show(activity: Activity) {
// if (!isKeyBoardVisible(activity)) toggle()
// }
//
// /**
// * Show the soft input.
// * @param view The view.
// */
// @JvmStatic
// fun show(view: View) {
// show(view, 0)
// }
//
// /**
// * Show the soft input.
// * @param view The view.
// * @param flags Provides additional operating flags. Currently may be
// * 0 or have the [InputMethodManager.SHOW_IMPLICIT] bit set.
// */
// @JvmStatic
// fun show(view: View, flags: Int) {
// val inputMethodManager = _context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
// view.isFocusable = true
// view.isFocusableInTouchMode = true
// view.requestFocus()
// inputMethodManager.showSoftInput(view, flags, object : ResultReceiver(Handler()) {
// override fun onReceiveResult(resultCode: Int, resultData: Bundle?) {
// if (resultCode == InputMethodManager.RESULT_UNCHANGED_HIDDEN || resultCode == InputMethodManager.RESULT_HIDDEN) toggle()
// }
// })
// inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY)
// }
//
// /**
// * 延迟显示软键盘
// * @param view View
// * @param delayMillis Long
// */
// @JvmStatic
// fun showPostDelay(view: View, delayMillis: Long) {
// view.postDelayed({ show(view) }, delayMillis)
// }
//
// /**
// * 显示软键盘
// * @param view View
// */
// /*@JvmStatic
// fun show(view: View) {
// var focusView = view
// if (!view.hasFocus()) {
// UtilKView.requestFocus(view)
// view.findFocus()?.let { focusView = it }
// }
// (focusView.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager).showSoftInput(focusView, 0)
// }*/
//
// /**
// * Hide the soft input.
// * @param activity The activity.
// */
// @JvmStatic
// fun hide(activity: Activity) {
// hide(activity.window)
// }
//
// /**
// * 关闭软键盘
// * @param activity Activity
// */
// /*@JvmStatic
// fun hide(activity: Activity) {
// if (activity.window.peekDecorView() != null && isActive(activity)) {
// (activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager).hideSoftInputFromWindow(activity.currentFocus?.windowToken, 0)
// }
// }*/
//
// /**
// * Hide the soft input.
// * @param window The window.
// */
// @JvmStatic
// fun hide(window: Window) {
// var view = window.currentFocus
// if (view == null) {
// val decorView = window.decorView
// val focusView = decorView.findViewWithTag<View>("keyboardTagView")
// if (focusView == null) {
// view = EditText(window.context).apply { tag = "keyboardTagView" }
// (decorView as ViewGroup).addView(view, 0, 0)
// } else {
// view = focusView
// }
// view.requestFocus()
// }
// hide(view)
// }
//
// /**
// * Hide the soft input.
// * @param view The view.
// */
// /*@JvmStatic
// fun hide(view: View) {
// (_context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager).hideSoftInputFromWindow(view.windowToken, 0)
// }*/
//
// /**
// * 隐藏软键盘
// * @param view View
// */
// @JvmStatic
// fun hide(view: View) {
// (view.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager).hideSoftInputFromWindow(view.windowToken, 0)
// }
//
// private var _millis: Long = 0
//
// /**
// * Hide the soft input.
// * @param activity The activity.
// */
// @JvmStatic
// fun hideByToggle(activity: Activity) {
// val nowMillis = SystemClock.elapsedRealtime()
// val delta = nowMillis - _millis
// if (abs(delta) > 500 && isKeyBoardVisible(activity)) {
// toggle()
// }
// _millis = nowMillis
// }
//
// /**
// * Return whether soft input is visible.
// * @param activity The activity.
// * @return `true`: yes<br></br>`false`: no
// */
// @JvmStatic
// fun isKeyBoardVisible(activity: Activity): Boolean {
// return UtilKWindow.getDecorViewInvisibleHeight(activity.window) > 0
// }
//
//
// /**
// * 是否需要隐藏软键盘
// * @param view View 如果焦点不是EditText则忽略,这个发生在视图刚绘制完,第一个焦点不在EditView上,和用户用轨迹球选择其他的焦点
// * @param event MotionEvent
// * @return Boolean
// */
// @JvmStatic
// fun isNeedHide(view: View, event: MotionEvent): Boolean {
// if (view is EditText) {
// val ints = intArrayOf(0, 0)//left,top
// view.getLocationInWindow(ints)
// val right = ints[0] + view.getWidth()
// val bottom = ints[1] + view.getHeight()
// return !(event.x > ints[0] && event.x < right && event.y > ints[1] && event.y < bottom)
// }
// return false
// }
//
// /**
// * 是否打开
// * @return Boolean
// */
// @JvmStatic
// fun isActive(activity: Activity): Boolean =
// (activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager).isActive
//
// /**
// * 是否打开
// * @return Boolean
// */
// @JvmStatic
// fun isActive(): Boolean =
// (_context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager).isActive
//
// /**
// * 是否打开
// * @param view View
// * @return Boolean
// */
// @JvmStatic
// fun isActive(view: View): Boolean =
// (_context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager).isActive(view)
//
// /**
// * 修复在RecyclerView中持有内存泄漏的问题
// * @param context Context
// */
// @JvmStatic
// fun fixInputMethodLeak(context: Context, tag: String = TAG) {
// if (Build.VERSION.SDK_INT >= CVersionCode.V_29_10_Q) {
// fixInputMethodLeakAfterQ(context, tag)
// } else {
// fixInputMethodLeakBeforeQ(context, tag)
// }
// }
//
// /**
// * 修复在RecyclerView中持有内存泄漏的问题
// * @param context Context
// * @param tag String
// */
// @JvmStatic
// fun fixInputMethodLeakAfterQ(context: Context, tag: String) {
// val inputMethodManager = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
// val field: Field
// val fieldObj: Any?
// try {
// field = UtilKReflect.getField(inputMethodManager, "mCurRootView")
// if (!field.isAccessible) field.isAccessible = true
// fieldObj = field.get(inputMethodManager)
// if (fieldObj != null && fieldObj is ViewParent) {
// field.set(inputMethodManager, null)
// Log.d(TAG, "fixInputMethodLeak: $tag set view mCurRootView null in inputMethodManager")
// }
// } catch (e: Exception) {
// e.printStackTrace()
// e.message?.et(TAG)
// }
// }
//
// /**
// * Fix the leaks of soft input.
// * @param activity The activity.
// */
// @JvmStatic
// fun fixInputMethodLeakBeforeQ(activity: Activity) {
// fixInputMethodLeakBeforeQ(activity.window)
// }
//
// /**
// * Fix the leaks of soft input.
// * @param window The window.
// */
// @JvmStatic
// fun fixInputMethodLeakBeforeQ(window: Window) {
// val inputMethodManager = _context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
// val leakViews = arrayOf("mLastSrvView", "mCurRootView", "mServedView", "mNextServedView")
// for (leakView in leakViews) {
// try {
// val leakField = InputMethodManager::class.java.getDeclaredField(leakView)
// if (!leakField.isAccessible) leakField.isAccessible = true
// val fieldObj = leakField.get(inputMethodManager) as? View ?: continue
// if (fieldObj.rootView == window.decorView.rootView) {
// leakField.set(inputMethodManager, null)
// }
// } catch (e: Exception) {
// e.printStackTrace()
// e.message?.et(TAG)
// }
// }
// }
//
// /**
// * 修复在RecyclerView中持有内存泄漏的问题
// * @param context Context
// * @param tag String
// */
// @JvmStatic
// fun fixInputMethodLeakBeforeQ(context: Context, tag: String) {
// val inputMethodManager = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
// val leakViews = arrayOf("mLastSrvView", "mCurRootView", "mServedView", "mNextServedView")
// var leakField: Field
// var fieldObj: Any?
// for (leakView in leakViews) {
// try {
// leakField = UtilKReflect.getField(inputMethodManager, leakView)
// if (!leakField.isAccessible) leakField.isAccessible = true
// fieldObj = leakField.get(inputMethodManager) as? View ?: continue
// if (fieldObj is View) {
// if (fieldObj.context == context) { //注意需要判断View关联的Context是不是当前Activity,否则有可能造成正常的输入框输入失效
// leakField.set(inputMethodManager, null)
// Log.d(TAG, "fixInputMethodLeak: $tag set view $leakView null in inputMethodManager")
// } else {
// break
// }
// }
// } catch (e: Exception) {
// e.printStackTrace()
// e.message?.et(TAG)
// }
// }
// }
//
// /**
// * Fix the bug of 5497 in Android.
// * Don't set adjustResize
// * @param activity The activity.
// */
// @JvmStatic
// fun fixAndroidBug5497(activity: Activity) {
// fixAndroidBug5497(activity.window)
// }
//
// /**
// * Fix the bug of 5497 in Android.
// * It will clean the adjustResize
// * @param window The window.
// */
// @JvmStatic
// fun fixAndroidBug5497(window: Window) {
// val softInputMode = window.attributes.softInputMode
// window.setSoftInputMode(softInputMode and CWinMgrLP.SOFT_INPUT_ADJUST_RESIZE.inv())
// val contentView = window.findViewById<FrameLayout>(R.id.content)
// val contentViewChild = contentView.getChildAt(0)
// val paddingBottom = contentViewChild.paddingBottom
// val contentViewInvisibleHeightPre5497 = intArrayOf(UtilKWindow.getContentViewInvisibleHeight(window))
// contentView.viewTreeObserver.addOnGlobalLayoutListener {
// val height = UtilKWindow.getContentViewInvisibleHeight(window)
// if (contentViewInvisibleHeightPre5497[0] != height) {
// contentViewChild.setPadding(
// contentViewChild.paddingLeft,
// contentViewChild.paddingTop,
// contentViewChild.paddingRight,
// paddingBottom + UtilKWindow.getDecorViewInvisibleHeight(window)
// )
// contentViewInvisibleHeightPre5497[0] = height
// }
// }
// }
//} | 1 | null | 8 | 118 | e46732e4fc58f1ad66e3974a393e3af411de7b17 | 22,270 | SwiftKit | Apache License 2.0 |
mobile/src/main/java/rs/readahead/washington/mobile/views/fragment/uwazi/entry/SharedUwaziSubmissionViewModel.kt | Horizontal-org | 193,379,924 | false | {"Text": 2, "Gradle": 9, "Java Properties": 2, "Shell": 1, "Ignore List": 8, "Batchfile": 1, "Markdown": 6, "INI": 6, "Proguard": 7, "Kotlin": 255, "XML": 692, "Java": 425, "JSON": 1, "YAML": 2} | package rs.readahead.washington.mobile.views.fragment.uwazi.entry
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.google.firebase.crashlytics.FirebaseCrashlytics
import com.google.gson.Gson
import com.hzontal.tella_vault.VaultFile
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import rs.readahead.washington.mobile.MyApplication
import rs.readahead.washington.mobile.bus.SingleLiveEvent
import rs.readahead.washington.mobile.data.database.KeyDataSource
import rs.readahead.washington.mobile.data.database.UwaziDataSource
import rs.readahead.washington.mobile.data.repository.MediaFileRequestBody
import rs.readahead.washington.mobile.data.repository.ProgressListener
import rs.readahead.washington.mobile.data.repository.UwaziRepository
import rs.readahead.washington.mobile.domain.entity.UWaziUploadServer
import rs.readahead.washington.mobile.domain.entity.collect.FormMediaFile
import rs.readahead.washington.mobile.domain.entity.collect.FormMediaFileStatus
import rs.readahead.washington.mobile.domain.entity.uwazi.CollectTemplate
import rs.readahead.washington.mobile.domain.entity.uwazi.UwaziEntityInstance
import rs.readahead.washington.mobile.domain.entity.uwazi.UwaziEntityStatus
import rs.readahead.washington.mobile.presentation.uwazi.SendEntityRequest
import timber.log.Timber
import java.net.URLEncoder
private const val MULTIPART_FORM_DATA = "text/plain"
class SharedUwaziSubmissionViewModel : ViewModel(){
private val keyDataSource: KeyDataSource = MyApplication.getKeyDataSource()
private val disposables = CompositeDisposable()
private val _instance = SingleLiveEvent<UwaziEntityInstance>()
val instance: LiveData<UwaziEntityInstance> get() = _instance
private val _template = MutableLiveData<CollectTemplate>()
val template: LiveData<CollectTemplate> get() = _template
private val repository = UwaziRepository()
val progress = MutableLiveData<UwaziEntityStatus>()
private val _server = MutableLiveData<UWaziUploadServer>()
val server: LiveData<UWaziUploadServer> get() = _server
var error = MutableLiveData<Throwable>()
private val _attachments = MutableLiveData<List<FormMediaFile>>()
val attachments: LiveData<List<FormMediaFile>> get() = _attachments
//TODO THIS IS UGLY WILL REPLACE IT FLOWABLE RX LATER
private val _progressCallBack = SingleLiveEvent<Pair<String, Float>>()
val progressCallBack: LiveData<Pair<String, Float>> get() = _progressCallBack
fun saveEntityInstance(instance : UwaziEntityInstance) {
disposables.add(keyDataSource.uwaziDataSource
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.flatMap { dataSource: UwaziDataSource -> dataSource.saveEntityInstance(instance).toObservable() }
.doFinally { progress.postValue(instance.status) }
.subscribe ({
progress.postValue(instance.status)
// _instance.postValue(savedInstance)
}
) { throwable: Throwable? ->
FirebaseCrashlytics.getInstance().recordException(
throwable
?: throw NullPointerException("Expression 'throwable' must not be null")
)
error.postValue(throwable)
})
}
fun getUwaziServerAndSaveEntity(serverID: Long, entity: UwaziEntityInstance) {
keyDataSource.uwaziDataSource
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.flatMap { dataSource: UwaziDataSource ->
dataSource.getUwaziServerById(serverID).toObservable()
}
?.subscribe(
{ server: UWaziUploadServer? ->
if (server != null) {
if (server.password.isNullOrEmpty() or server.username.isNullOrEmpty()){
submitWhiteListedEntity(server, entity)
}else{
submitEntity(server, entity)
}
}
},
{ throwable: Throwable? ->
FirebaseCrashlytics.getInstance().recordException(throwable!!)
error.postValue(throwable)
}
)?.let {
disposables.add(
it
)
}
}
fun submitEntity(server: UWaziUploadServer, entity: UwaziEntityInstance) {
disposables.add(
repository.submitEntity(
server = server,
entity = createRequestBody(Gson().toJson(entity.createEntityRequest())),
attachments = createListOfAttachments(entity.widgetMediaFiles, _progressCallBack)
)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnError { progress.postValue(UwaziEntityStatus.SUBMISSION_ERROR) }
.flatMap {
entity.status = UwaziEntityStatus.SUBMITTED
entity.formPartStatus = FormMediaFileStatus.SUBMITTED
keyDataSource.uwaziDataSource.blockingFirst().saveEntityInstance(entity)
}
.subscribe({
progress.postValue(UwaziEntityStatus.SUBMITTED)
}
) { throwable: Throwable? ->
FirebaseCrashlytics.getInstance().recordException(
throwable
?: throw NullPointerException("Expression 'throwable' must not be null")
)
error.postValue(throwable)
progress.postValue(UwaziEntityStatus.SUBMISSION_ERROR)
})
}
private fun submitWhiteListedEntity(server: UWaziUploadServer, entity: UwaziEntityInstance) {
disposables.add(
repository.submitWhiteListedEntity(
server = server,
entity = createRequestBody(Gson().toJson(entity.createEntityRequest())),
attachments = createListOfAttachments(entity.widgetMediaFiles, _progressCallBack)
)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnError { progress.postValue(UwaziEntityStatus.SUBMISSION_ERROR) }
.flatMap {
entity.status = UwaziEntityStatus.SUBMITTED
entity.formPartStatus = FormMediaFileStatus.SUBMITTED
keyDataSource.uwaziDataSource.blockingFirst().saveEntityInstance(entity)
}
.subscribe({
progress.postValue(UwaziEntityStatus.SUBMITTED)
}
) { throwable: Throwable? ->
FirebaseCrashlytics.getInstance().recordException(
throwable
?: throw NullPointerException("Expression 'throwable' must not be null")
)
error.postValue(throwable)
progress.postValue(UwaziEntityStatus.SUBMISSION_ERROR)
})
}
private fun UwaziEntityInstance.createEntityRequest() = SendEntityRequest(
metadata = removeAttachments(metadata.toMutableMap()),
template = collectTemplate?.entityRow?._id ?: "",
title = title,
type = type
)
private fun removeAttachments(metadata : MutableMap<String,List<Any>>) : Map<String,List<Any>>{
metadata.remove("supporting_files")
metadata.remove("primary_documents")
return metadata
}
private fun createRequestBody(s: String): RequestBody {
return RequestBody.create(
MediaType.parse(MULTIPART_FORM_DATA), s
)
}
private fun createListOfAttachments(
attachments: List<VaultFile?>?,
progressCallBack: SingleLiveEvent<Pair<String, Float>>,
): List<MultipartBody.Part?> {
val listAttachments: MutableList<MultipartBody.Part?> = mutableListOf()
var fileToUpload: MultipartBody.Part?
try {
if (attachments != null) {
for (i in attachments.indices) {
attachments[i]?.let { vaultFile->
val requestBody = MediaFileRequestBody(
vaultFile,
ProgressListener(vaultFile.id, progressCallBack)
)
fileToUpload =
requestBody.let { file ->
MultipartBody.Part.createFormData(
"attachments",
URLEncoder.encode(vaultFile.name, "utf-8"),
file
)
}
listAttachments.add(fileToUpload)
}
}
}
} catch (e: Exception) {
Timber.d(e.message ?: "Error attaching files")
}
return listAttachments.toList()
}
override fun onCleared() {
disposables.dispose()
super.onCleared()
}
} | 15 | Java | 15 | 49 | b941e38f9d62032e1471b6dfd5e467b44acca23d | 9,502 | Tella-Android | Apache License 2.0 |
Kotlin Basico/1. Linguagem Kotlin/src/IIIMaisConceitos/nullSafe.kt | DevMasterTeam | 180,258,237 | false | null | package IIIMaisConceitos
fun main() {
val str1: String
// println(str1.length)
val str2: String? = null
// println(str2.length)
val str3: String? = null
println(str3?.length)
val str4: String? = null
println(str4!!.length)
} | 0 | Kotlin | 18 | 14 | 0523a4ac9dfeb136fb0a690053c854c1ed772b6c | 262 | UdemyKotlinIniciante | MIT License |
common/src/main/java/jp/co/soramitsu/common/compose/component/AssetListItem.kt | soramitsu | 278,060,397 | false | null | package jp.co.soramitsu.common.compose.component
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.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.material.Card
import androidx.compose.material.Divider
import androidx.compose.material.Icon
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Alignment.Companion.CenterStart
import androidx.compose.ui.Alignment.Companion.CenterVertically
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import com.valentinilk.shimmer.shimmer
import jp.co.soramitsu.common.R
import jp.co.soramitsu.common.compose.theme.FearlessAppTheme
import jp.co.soramitsu.common.compose.theme.bold
import jp.co.soramitsu.common.compose.theme.customColors
import jp.co.soramitsu.common.compose.theme.customTypography
import jp.co.soramitsu.common.compose.theme.white16
import jp.co.soramitsu.common.compose.theme.white64
import jp.co.soramitsu.common.compose.viewstate.AssetListItemShimmerViewState
import jp.co.soramitsu.common.compose.viewstate.AssetListItemViewState
@Composable
fun AssetListItem(
state: AssetListItemViewState,
modifier: Modifier = Modifier,
onClick: (AssetListItemViewState) -> Unit
) {
BackgroundCornered(
modifier = modifier
.testTag("AssetListItem_${state.assetSymbol}_${state.assetName}")
.clickable(onClick = { onClick(state) })
) {
val assetRateColor = if (state.assetTokenRate.orEmpty().startsWith("+")) {
MaterialTheme.customColors.greenText
} else {
MaterialTheme.customColors.red
}
Row(
Modifier
.height(IntrinsicSize.Min)
.padding(horizontal = 8.dp)
.fillMaxWidth()
) {
AsyncImage(
model = getImageRequest(LocalContext.current, state.assetIconUrl),
contentDescription = null,
modifier = Modifier
.testTag("AssetListItem_${state.assetSymbol}_image")
.size(42.dp)
.padding(start = 4.dp)
.align(CenterVertically)
)
MarginHorizontal(margin = 8.dp)
Divider(
color = white16,
modifier = Modifier
.height(64.dp)
.width(1.dp)
.align(CenterVertically)
)
MarginHorizontal(margin = 8.dp)
Box(
Modifier.fillMaxWidth()
) {
Column(
Modifier
.padding(vertical = 8.dp)
.align(CenterStart)
) {
Row {
Text(
text = state.assetName.uppercase(),
style = MaterialTheme.customTypography.capsTitle2,
modifier = Modifier
.alpha(0.64f)
.testTag("AssetListItem_${state.assetSymbol}_chain_name")
)
if (state.isTestnet) {
MarginHorizontal(margin = 4.dp)
TestnetBadge()
}
Spacer(
modifier = Modifier
.height(1.dp)
.weight(1.0f)
)
AssetChainsBadge(
urls = state.assetChainUrls.values.toList(),
modifier = Modifier
.testTag("AssetListItem_${state.assetSymbol}_chains")
)
}
Row {
Text(
text = state.assetSymbol.uppercase(),
style = MaterialTheme.customTypography.header3,
modifier = Modifier
.padding(vertical = 4.dp)
.align(CenterVertically)
.testTag("AssetListItem_${state.assetSymbol}_symbol")
)
Spacer(
modifier = Modifier
.height(1.dp)
.weight(1.0f)
)
if (state.assetTransferableBalance == null) {
Shimmer(
Modifier
.padding(top = 8.dp, bottom = 4.dp)
.size(height = 16.dp, width = 54.dp)
)
} else {
Text(
text = state.assetTransferableBalance,
style = MaterialTheme.customTypography.header3.copy(textAlign = TextAlign.End),
modifier = Modifier
.padding(vertical = 4.dp)
.padding(start = 4.dp)
.testTag("AssetListItem_${state.assetSymbol}_transferable")
)
}
}
Row {
Text(
text = state.assetTokenFiat.orEmpty(),
style = MaterialTheme.customTypography.body1,
modifier = Modifier
.alpha(0.64f)
.testTag("AssetListItem_${state.assetSymbol}_change_fiat")
)
Text(
text = state.assetTokenRate.orEmpty(),
style = MaterialTheme.customTypography.body1.copy(
color = assetRateColor
),
modifier = Modifier
.padding(start = 4.dp)
.testTag("AssetListItem_${state.assetSymbol}_change_percent")
)
Spacer(
modifier = Modifier
.height(1.dp)
.weight(1.0f)
)
Text(
text = state.assetTransferableBalanceFiat.orEmpty(),
style = MaterialTheme.customTypography.body1,
modifier = Modifier
.alpha(0.64f)
.padding(start = 4.dp)
.testTag("AssetListItem_${state.assetSymbol}_transferable_fiat")
)
}
}
}
}
}
}
@Composable
fun TestnetBadge() {
Card(backgroundColor = white16) {
Row(
modifier = Modifier
.padding(bottom = 2.dp, start = 2.dp, end = 4.dp),
verticalAlignment = CenterVertically
) {
Icon(
modifier = Modifier
.width(16.dp)
.padding(top = 1.dp),
painter = painterResource(R.drawable.ic_token_testnet),
tint = white64,
contentDescription = null
)
MarginHorizontal(margin = 4.dp)
Text(
text = stringResource(id = R.string.label_testnet).uppercase(),
style = MaterialTheme.customTypography.body3.bold().copy(color = white64)
)
}
}
}
@Composable
fun AssetListItemShimmer(
state: AssetListItemShimmerViewState,
modifier: Modifier = Modifier
) {
BackgroundCornered(
modifier = modifier
.testTag("AssetListItem_shimmer")
) {
Row(
Modifier
.height(IntrinsicSize.Min)
.padding(horizontal = 8.dp)
.fillMaxWidth()
) {
AsyncImage(
model = getImageRequest(LocalContext.current, state.assetIconUrl),
contentDescription = null,
modifier = Modifier
.testTag("AssetListItem_shimmer_image")
.size(42.dp)
.padding(start = 4.dp)
.align(CenterVertically)
.shimmer()
)
MarginHorizontal(margin = 8.dp)
Divider(
color = white16,
modifier = Modifier
.height(64.dp)
.width(1.dp)
.align(CenterVertically)
)
MarginHorizontal(margin = 8.dp)
Column(
Modifier
.padding(vertical = 8.dp)
.align(CenterVertically)
) {
Shimmer(
Modifier
.height(11.dp)
.width(95.dp)
)
MarginVertical(margin = 8.dp)
Shimmer(
Modifier
.height(16.dp)
.width(43.dp)
)
MarginVertical(margin = 11.dp)
Row {
Shimmer(
Modifier
.height(12.dp)
.width(51.dp)
)
Shimmer(
Modifier
.height(12.dp)
.width(53.dp)
.padding(start = 4.dp)
)
}
}
Spacer(
modifier = Modifier
.height(1.dp)
.weight(1.0f)
)
Column(
Modifier
.padding(vertical = 8.dp)
.align(CenterVertically)
) {
AssetChainsBadge(
urls = state.assetChainUrls,
modifier = Modifier
.align(Alignment.End)
.shimmer()
.testTag("AssetListItem_shimmer_chains")
)
MarginVertical(margin = 8.dp)
Shimmer(
Modifier
.size(height = 16.dp, width = 54.dp)
.align(Alignment.End)
)
MarginVertical(margin = 11.dp)
Shimmer(
Modifier
.size(height = 12.dp, width = 69.dp)
.align(Alignment.End)
)
}
}
}
}
@Preview
@Composable
private fun PreviewAssetListItem() {
val assetIconUrl =
"https://raw.githubusercontent.com/soramitsu/fearless-utils/master/icons/chains/white/Polkadot.svg"
val assetChainUrlsMap = mapOf(
"" to "https://raw.githubusercontent.com/soramitsu/fearless-utils/master/icons/chains/white/Karura.svg",
"" to "https://raw.githubusercontent.com/soramitsu/fearless-utils/master/icons/chains/white/kilt.svg",
"" to "https://raw.githubusercontent.com/soramitsu/fearless-utils/master/icons/chains/white/Moonriver.svg",
"" to "https://raw.githubusercontent.com/soramitsu/fearless-utils/master/icons/chains/white/Polkadot.svg",
"" to "https://raw.githubusercontent.com/soramitsu/fearless-utils/master/icons/chains/white/Moonbeam.svg",
"" to "https://raw.githubusercontent.com/soramitsu/fearless-utils/master/icons/chains/white/Statemine.svg",
"" to "https://raw.githubusercontent.com/soramitsu/fearless-utils/master/icons/chains/white/Rococo.svg"
)
val state = AssetListItemViewState(
assetIconUrl = assetIconUrl,
assetName = "Karura asset",
assetChainName = "Karura",
assetSymbol = "KSM",
assetTokenFiat = "$<PASSWORD>",
assetTokenRate = "+5.67%",
assetTransferableBalance = "444.3",
assetTransferableBalanceFiat = "$2345.32",
assetChainUrls = assetChainUrlsMap,
chainId = "",
chainAssetId = "",
isSupported = true,
isHidden = false,
priceId = null,
isTestnet = false
)
FearlessAppTheme {
Box(modifier = Modifier.background(Color.Black)) {
Column {
AssetListItem(state) {}
MarginVertical(margin = 8.dp)
AssetListItem(
state.copy(
isTestnet = true,
assetTransferableBalance = "123,456,123,456,123,456,789,456,789.01234"
)
) {}
MarginVertical(margin = 8.dp)
AssetListItemShimmer(
state = AssetListItemShimmerViewState(
assetIconUrl,
assetChainUrlsMap.values.toList()
)
)
}
}
}
}
| 9 | null | 30 | 89 | 1de6dfa7c77d4960eca2d215df2bdcf71a2ef5f2 | 14,279 | fearless-Android | Apache License 2.0 |
src/main/kotlin/me/bytebeats/charts/desktop/app/theme/Colors.kt | bytebeats | 468,312,472 | false | {"Kotlin": 84437} | package me.bytebeats.charts.desktop.app.theme
import androidx.compose.ui.graphics.Color
/**
* @Author bytebeats
* @Email <<EMAIL>>
* @Github https://github.com/bytebeats
* @Created at 2022/3/10 21:08
* @Version 1.0
* @Description TO-DO
*/
val Purple200 = Color(0xFFBB86FC)
val Purple500 = Color(0xFF6200EE)
val Purple700 = Color(0xFF3700B3)
val Teal200 = Color(0xFF03DAC5) | 1 | Kotlin | 2 | 28 | 840a040acc2470d14917af6566a141f75e9b2c99 | 382 | compose-charts-desktop | The Unlicense |
platform/lang-impl/src/com/intellij/ide/navbar/ui/StaticNavBarPanel.kt | JetBrains | 2,489,216 | false | null | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.navbar.ui
import com.intellij.ide.navbar.ide.*
import com.intellij.ide.navbar.vm.NavBarVm
import com.intellij.openapi.application.EDT
import com.intellij.openapi.project.Project
import com.intellij.ui.components.JBPanel
import com.intellij.util.attachAsChildTo
import com.intellij.util.ui.UIUtil
import com.intellij.util.ui.update.Activatable
import com.intellij.util.ui.update.UiNotifyConnector
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.transformLatest
import java.awt.BorderLayout
import java.awt.Window
internal open class StaticNavBarPanel(
private val project: Project,
private val cs: CoroutineScope,
private val updateRequests: Flow<Any>,
private val requestNavigation: (NavBarVmItem) -> Unit,
) : JBPanel<StaticNavBarPanel>(BorderLayout()), Activatable {
private val _window: MutableStateFlow<Window?> = MutableStateFlow(null)
private val _vm: MutableStateFlow<NavBarVm?> = MutableStateFlow(null)
val model: NavBarVm? get() = _vm.value
override fun hideNotify() {
_window.value = null
}
override fun showNotify() {
_window.value = UIUtil.getWindow(this)
}
init {
UiNotifyConnector.installOn(this, this, false)
// This coroutine will GC-ed together with the `StaticNavBarPanel` instance as long as it isn't referenced by anything else,
// `attachAsChildTo` makes sure the coroutine refs are cleaned.
@OptIn(DelicateCoroutinesApi::class)
GlobalScope.launch {
_window.collectLatest { window ->
if (window != null) {
coroutineScope {
val windowScope = this@coroutineScope
cs.launch {
attachAsChildTo(windowScope)
handleWindow(window)
}
}
}
}
}
@OptIn(DelicateCoroutinesApi::class)
GlobalScope.launch(Dispatchers.EDT) {
_vm.collectLatest { vm ->
if (vm != null) {
handleVm(vm)
}
}
}
}
private suspend fun handleWindow(window: Window): Nothing = supervisorScope {
val vm = NavBarVmImpl(
this@supervisorScope,
initialItems = getDefaultModel(project),
contextItems = contextItems(window),
requestNavigation,
)
_vm.value = vm
try {
awaitCancellation()
}
finally {
_vm.value = null
}
}
protected open suspend fun getDefaultModel(project: Project): List<NavBarVmItem> = defaultModel(project)
protected open fun contextItems(window: Window): Flow<List<NavBarVmItem>> {
@OptIn(ExperimentalCoroutinesApi::class)
return updateRequests.transformLatest {
dataContext(window, panel = this@StaticNavBarPanel)?.let {
emit(contextModel(it, project))
}
}
}
private suspend fun handleVm(vm: NavBarVm): Nothing = supervisorScope {
val panel = NewNavBarPanel(this@supervisorScope, vm, project, isFloating = false)
add(panel)
try {
awaitCancellation()
}
finally {
remove(panel)
}
}
}
| 233 | null | 4931 | 15,571 | 92c8aad1c748d6741e2c8e326e76e68f3832f649 | 3,236 | intellij-community | Apache License 2.0 |
telek/src/commonMain/kotlin/by/dev/madhead/telek/telek/Telek.kt | madhead | 249,262,852 | false | null | package by.dev.madhead.telek.telek
import by.dev.madhead.telek.model.Message
import by.dev.madhead.telek.model.Update
import by.dev.madhead.telek.model.User
import by.dev.madhead.telek.model.WebhookInfo
import by.dev.madhead.telek.model.communication.AnswerCallbackQueryRequest
import by.dev.madhead.telek.model.communication.GetUpdatesRequest
import by.dev.madhead.telek.model.communication.SendMessageRequest
import by.dev.madhead.telek.model.communication.SendPhotoRequest
import by.dev.madhead.telek.model.communication.SetWebhookRequest
/**
* [Telegram Bot API][https://core.telegram.org/bots/api] client.
*/
@Suppress("TooManyFunctions")
interface Telek {
/**
* Use this method to receive incoming updates using long polling ([wiki][https://en.wikipedia.org/wiki/Push_technology#Long_polling]).
* An Array of [Update] objects is returned.
*/
suspend fun getUpdates(request: GetUpdatesRequest): List<Update>
/**
* Use this method to specify a url and receive incoming updates via an outgoing webhook. Whenever there is an update for the bot,
* we will send an HTTPS POST request to the specified url, containing a JSON-serialized [Update]. In case of an unsuccessful request,
* we will give up after a reasonable amount of attempts. Returns *True* on success.
*
* If you'd like to make sure that the Webhook request comes from Telegram, we recommend using a secret path in the URL, e.g.
* `https://www.example.com/<token>`. Since nobody else knows your bot‘s token, you can be pretty sure it’s us.
*/
suspend fun setWebhook(request: SetWebhookRequest)
/**
* Use this method to remove webhook integration if you decide to switch back to [getUpdates].
* Returns *True* on success.
* Requires no parameters.
*/
suspend fun deleteWebhook()
/**
* Use this method to get current webhook status.
* Requires no parameters.
* On success, returns a [WebhookInfo] object.
* If the bot is using [getUpdates], will return an object with the url field empty.
*/
suspend fun getWebhookInfo(): WebhookInfo
/**
* A simple method for testing your bot's auth token.
* Requires no parameters.
* Returns basic information about the bot in form of a [User] object.
*/
suspend fun getMe(): User
/**
* Use this method to send text messages.
* On success, the sent [Message] is returned.
*/
suspend fun sendMessage(request: SendMessageRequest): Message
/**
* Use this method to forward messages of any kind.
* On success, the sent [Message] is returned.
*/
suspend fun forwardMessage()
/**
* Use this method to send photos.
* On success, the sent [Message] is returned.
*/
suspend fun sendPhoto(request: SendPhotoRequest): Message
/**
* Use this method to send audio files, if you want Telegram clients to display them in the music player.
* Your audio must be in the .MP3 or .M4A format.
* On success, the sent [Message] is returned.
* Bots can currently send audio files of up to 50 MB in size, this limit may be changed in the future.
*
* For sending voice messages, use the [sendVoice] method instead.
*/
suspend fun sendAudio()
/**
* Use this method to send general files.
* On success, the sent [Message] is returned.
* Bots can currently send files of any type of up to 50 MB in size, this limit may be changed in the future.
*/
suspend fun sendDocument()
/**
* Use this method to send video files, Telegram clients support mp4 videos (other formats may be sent as
* [Document][by.dev.madhead.telek.model.Document]). On success, the sent [Message] is returned. Bots can currently send video files
* of up to 50 MB in size, this limit may be changed in the future.
*/
suspend fun sendVideo()
/**
* Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound).
* On success, the sent [Message] is returned.
* Bots can currently send animation files of up to 50 MB in size, this limit may be changed in the future.
*/
suspend fun sendAnimation()
/**
* Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message.
* For this to work, your audio must be in an .OGG file encoded with OPUS (other formats may be sent as
* [Audio][by.dev.madhead.telek.model.Audio] or [Document][by.dev.madhead.telek.model.Document]).
* On success, the sent [Message] is returned. Bots can currently send voice messages of up to 50 MB in size, this limit may be
* changed in the future.
*/
suspend fun sendVoice()
/**
* As of [v.4.0][https://telegram.org/blog/video-messages-and-telescope], Telegram clients support rounded square mp4 videos of up to
* 1 minute long. Use this method to send video messages. On success, the sent [Message] is returned.
*/
suspend fun sendVideoNote()
/**
* Use this method to send a group of photos or videos as an album.
* On success, an array of the sent [Messages][Message] is returned.
*/
suspend fun sendMediaGroup()
/**
* Use this method to send point on the map.
* On success, the sent [Message] is returned.
*/
suspend fun sendLocation()
/**
* Use this method to edit live location messages.
* A location can be edited until its `live_period` expires or editing is explicitly disabled by a call to [stopMessageLiveLocation].
* On success, if the edited message was sent by the bot, the edited [Message] is returned, otherwise *True* is returned.
*/
suspend fun editMessageLiveLocation()
/**
* Use this method to stop updating a live location message before `live_period` expires.
* On success, if the message was sent by the bot, the sent [Message] is returned, otherwise *True* is returned.
*/
suspend fun stopMessageLiveLocation()
/**
* Use this method to send information about a venue.
* On success, the sent [Message] is returned.
*/
suspend fun sendVenue()
/**
* Use this method to send phone contacts.
* On success, the sent [Message] is returned.
*/
suspend fun sendContact()
/**
* Use this method to send a native poll.
* On success, the sent [Message] is returned.
*/
suspend fun sendPoll()
/**
* Use this method to send a dice, which will have a random value from 1 to 6. On success, the sent [Message] is returned.
* (Yes, we're aware of the *“proper”* singular of *die*. But it's awkward, and we decided to help it change. One dice at a time!)
*/
suspend fun sendDice()
/**
* Use this method when you need to tell the user that something is happening on the bot's side.
* The status is set for 5 seconds or less (when a message arrives from your bot, Telegram clients clear its typing status).
* Returns *True* on success.
*
* > Example: The [ImageBot][https://t.me/imagebot] needs some time to process a request and upload the image. Instead of sending a
* text message along the lines of “Retrieving image, please wait…”, the bot may use [sendChatAction] with `action = upload_photo`.
* The user will see a “sending photo” status for the bot.
*
* We only recommend using this method when a response from the bot will take a **noticeable** amount of time to arrive.
*/
suspend fun sendChatAction()
/**
* Use this method to get a list of profile pictures for a user.
* Returns a [UserProfilePhotos][by.dev.madhead.telek.model.UserProfilePhotos] object.
*/
suspend fun getUserProfilePhotos()
/**
* Use this method to get basic info about a file and prepare it for downloading. For the moment, bots can download files of up to 20MB
* in size. On success, a [File][by.dev.madhead.telek.model.File] object is returned. The file can then be downloaded via the link
* `https://api.telegram.org/file/bot<token>/<file_path>`, where `<file_path>` is taken from the response. It is guaranteed that the
* link will be valid for at least 1 hour. When the link expires, a new one can be requested by calling [getFile] again.
*
* **Note:** This function may not preserve the original file name and MIME type. You should save the file's MIME type and name
* (if available) when the File object is received.
*/
suspend fun getFile()
/**
* Use this method to kick a user from a group, a supergroup or a channel. In the case of supergroups and channels, the user will not
* be able to return to the group on their own using invite links, etc., unless
* [unbanned][https://core.telegram.org/bots/api#unbanchatmember] first. The bot must be an administrator in the chat for this to work
* and must have the appropriate admin rights. Returns *True* on success.
*/
suspend fun kickChatMember()
/**
* Use this method to unban a previously kicked user in a supergroup or channel.
* The user will **not** return to the group or channel automatically, but will be able to join via link, etc.
* The bot must be an administrator for this to work.
* Returns *True* on success.
*/
suspend fun unbanChatMember()
/**
* Use this method to restrict a user in a supergroup.
* The bot must be an administrator in the supergroup for this to work and must have the appropriate admin rights.
* Pass *True* for all permissions to lift restrictions from a user.
* Returns *True* on success.
*/
suspend fun restrictChatMember()
/**
* Use this method to promote or demote a user in a supergroup or a channel.
* The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.
* Pass *False* for all boolean parameters to demote a user.
* Returns *True* on success.
*/
suspend fun promoteChatMember()
/**
* Use this method to set a custom title for an administrator in a supergroup promoted by the bot.
* Returns *True* on success.
*/
suspend fun setChatAdministratorCustomTitle()
/**
* Use this method to set default chat permissions for all members.
* The bot must be an administrator in the group or a supergroup for this to work and must have the *can_restrict_members* admin rights.
* Returns *True* on success.
*/
suspend fun setChatPermissions()
/**
* Use this method to generate a new invite link for a chat; any previously generated link is revoked.
* The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.
* Returns the new invite link as *String* on success.
*/
suspend fun exportChatInviteLink()
/**
* Use this method to set a new profile photo for the chat.
* Photos can't be changed for private chats.
* The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.
* Returns *True* on success.
*/
suspend fun setChatPhoto()
/**
* Use this method to delete a chat photo.
* Photos can't be changed for private chats.
* The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.
* Returns *True* on success.
*/
suspend fun deleteChatPhoto()
/**
* Use this method to change the title of a chat.
* Titles can't be changed for private chats.
* The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.
* Returns *True* on success.
*/
suspend fun setChatTitle()
/**
* Use this method to change the description of a group, a supergroup or a channel.
* The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.
* Returns *True* on success.
*/
suspend fun setChatDescription()
/**
* Use this method to pin a message in a group, a supergroup, or a channel. The bot must be an administrator in the chat for this
* to work and must have the ‘can_pin_messages’ admin right in the supergroup or ‘can_edit_messages’ admin right in the channel.
* Returns *True* on success.
*/
suspend fun pinChatMessage()
/**
* Use this method to unpin a message in a group, a supergroup, or a channel. The bot must be an administrator in the chat for this
* to work and must have the ‘can_pin_messages’ admin right in the supergroup or ‘can_edit_messages’ admin right in the channel.
* Returns *True* on success.
*/
suspend fun unpinChatMessage()
/**
* Use this method for your bot to leave a group, supergroup or channel.
* Returns *True* on success.
*/
suspend fun leaveChat()
/**
* Use this method to get up to date information about the chat (current name of the user for one-on-one conversations, current
* username of a user, group or channel, etc.). Returns a [Chat][by.dev.madhead.telek.model.Chat] object on success.
*/
suspend fun getChat()
/**
* Use this method to get a list of administrators in a chat. On success, returns an Array of
* [ChatMember][by.dev.madhead.telek.model.ChatMember] objects that contains information about all chat administrators except other
* bots. If the chat is a group or a supergroup and no administrators were appointed, only the creator will be returned.
*/
suspend fun getChatAdministrators()
/**
* Use this method to get the number of members in a chat.
* Returns *Int* on success.
*/
suspend fun getChatMembersCount()
/**
* Use this method to get information about a member of a chat.
* Returns a [ChatMember][by.dev.madhead.telek.model.ChatMember] object on success.
*/
suspend fun getChatMember()
/**
* Use this method to set a new group sticker set for a supergroup.
* The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.
* Use the field *can_set_sticker_set* optionally returned in [getChat] requests to check if the bot can use this method.
* Returns *True* on success.
*/
suspend fun setChatStickerSet()
/**
* Use this method to delete a group sticker set from a supergroup.
* The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.
* Use the field *can_set_sticker_set* optionally returned in [getChat] requests to check if the bot can use this method.
* Returns *True* on success.
*/
suspend fun deleteChatStickerSet()
/**
* Use this method to send answers to callback queries sent from
* [inline keyboards][https://core.telegram.org/bots#inline-keyboards-and-on-the-fly-updating]. The answer will be displayed to the
* user as a notification at the top of the chat screen or as an alert. On success, *True* is returned.
*
* >Alternatively, the user can be redirected to the specified Game URL.
* For this option to work, you must first create a game for your bot via [@Botfather][https://t.me/botfather] and accept the terms.
* Otherwise, you may use links like `t.me/your_bot?start=XXXX` that open your bot with a parameter.
*/
suspend fun answerCallbackQuery(request: AnswerCallbackQueryRequest): Boolean
/**
* Use this method to change the list of the bot's commands.
* Returns *True* on success.
*/
suspend fun setMyCommands()
/**
* Use this method to get the current list of the bot's commands.
* Requires no parameters.
* Returns Array of [BotCommand] on success.
*/
suspend fun getMyCommands()
/**
* Use this method to edit text and [game][https://core.telegram.org/bots/api#games] messages.
* On success, if edited message is sent by the bot, the edited [Message] is returned, otherwise *True* is returned.
*/
suspend fun editMessageText()
/**
* Use this method to edit captions of messages.
* On success, if edited message is sent by the bot, the edited [Message] is returned, otherwise *True* is returned.
*/
suspend fun editMessageCaption()
/**
* Use this method to edit animation, audio, document, photo, or video messages.
* If a message is a part of a message album, then it can be edited only to a photo or a video.
* Otherwise, message type can be changed arbitrarily.
* When inline message is edited, new file can't be uploaded.
* Use previously uploaded file via its file_id or specify a URL.
* On success, if the edited message was sent by the bot, the edited [Message] is returned, otherwise *True* is returned.
*/
suspend fun editMessageMedia()
/**
* Use this method to edit only the reply markup of messages.
* On success, if edited message is sent by the bot, the edited [Message] is returned, otherwise *True* is returned.
*/
suspend fun editMessageReplyMarkup()
/**
* Use this method to stop a poll which was sent by the bot.
* On success, the stopped [Poll][by.dev.madhead.telek.model.Poll] with the final results is returned.
*/
suspend fun stopPoll()
/**
* Use this method to delete a message, including service messages, with the following limitations:
* - A message can only be deleted if it was sent less than 48 hours ago.
* - Bots can delete outgoing messages in private chats, groups, and supergroups.
* - Bots can delete incoming messages in private chats.
* - Bots granted can_post_messages permissions can delete outgoing messages in channels.
* - If the bot is an administrator of a group, it can delete any message there.
* - If the bot has can_delete_messages permission in a supergroup or a channel, it can delete any message there.
*
* Returns *True* on success.
*/
suspend fun deleteMessage()
/**
* Use this method to send static .WEBP or [animated][https://telegram.org/blog/animated-stickers] .TGS stickers.
* On success, the sent [Message] is returned.
*/
suspend fun sendSticker()
/**
* Use this method to get a sticker set.
* On success, a [StickerSet][by.dev.madhead.telek.model.StickerSet] object is returned.
*/
suspend fun getStickerSet()
/**
* Use this method to upload a .PNG file with a sticker for later use in [createNewStickerSet] and [addStickerToSet] methods
* (can be used multiple times). Returns the uploaded [File][by.dev.madhead.telek.model.File] on success.
*/
suspend fun uploadStickerFile()
/**
* Use this method to create new sticker set owned by a user.
* The bot will be able to edit the created sticker set.
* Returns *True* on success.
*/
suspend fun createNewStickerSet()
/**
* Use this method to add a new sticker to a set created by the bot.
* Returns *True* on success.
*/
suspend fun addStickerToSet()
/**
* Use this method to move a sticker in a set created by the bot to a specific position.
* Returns *True* on success.
*/
suspend fun setStickerPositionInSet()
/**
* Use this method to delete a sticker from a set created by the bot.
* Returns *True* on success.
*/
suspend fun deleteStickerFromSet()
/**
* Use this method to set the thumbnail of a sticker set.
* Animated thumbnails can be set for animated sticker sets only.
* Returns *True* on success.
*/
suspend fun setStickerSetThumb()
/**
* Use this method to send answers to an inline query.
* On success, *True* is returned.
* No more than **50** results per query are allowed.
*/
suspend fun answerInlineQuery()
/**
* Use this method to send invoices.
* On success, the sent [Message] is returned.
*/
suspend fun sendInvoice()
/**
* If you sent an invoice requesting a shipping address and the parameter *is_flexible* was specified, the Bot API will send an
* [Update] with a *shipping_query* field to the bot. Use this method to reply to shipping queries. On success, *True* is returned.
*/
suspend fun answerShippingQuery()
/**
* Once the user has confirmed their payment and shipping details, the Bot API sends the final confirmation in the form of an [Update]
* with the field *pre_checkout_query*. Use this method to respond to such pre-checkout queries. On success, *True* is returned.
* **Note:** The Bot API must receive an answer within 10 seconds after the pre-checkout query was sent.
*/
suspend fun answerPreCheckoutQuery()
/**
* Informs a user that some of the Telegram Passport elements they provided contains errors. The user will not be able to re-submit
* their Passport to you until the errors are fixed (the contents of the field for which you returned the error must change).
* Returns *True* on success.
*
* Use this if the data submitted by the user doesn't satisfy the standards your service requires for any reason.
* For example, if a birthday date seems invalid, a submitted document is blurry, a scan shows evidence of tampering, etc.
* Supply some details in the error message to make sure the user knows how to correct the issues.
*/
suspend fun setPassportDataErrors()
/**
* Use this method to send a game.
* On success, the sent [Message] is returned.
*/
suspend fun sendGame()
/**
* Use this method to set the score of the specified user in a game.
* On success, if the message was sent by the bot, returns the edited [Message], otherwise returns *True*.
* Returns an error, if the new score is not greater than the user's current score in the chat and *force* is *False*.
*/
suspend fun setGameScore()
/**
* Use this method to get data for high score tables.
* Will return the score of the specified user and several of his neighbors in a game.
* On success, returns an *Array* of [GameHighScore][by.dev.madhead.telek.model.GameHighScore] objects.
*
* >This method will currently return scores for the target user, plus two of his closest neighbors on each side.
* Will also return the top three users if the user and his neighbors are not among them.
* Please note that this behavior is subject to change.
*/
suspend fun getGameHighScores()
}
| 0 | Kotlin | 0 | 0 | 8f1dff19cce8394d76ef9ed6df4577a2d67e84f7 | 22,707 | telek | MIT License |
mapbox/src/main/java/nz/co/trademe/mapme/mapbox/MapboxMarkerAnnotation.kt | TradeMe | 98,249,217 | false | null | package nz.co.trademe.mapme.mapbox
import android.content.Context
import android.graphics.Bitmap
import android.util.Log
import com.mapbox.mapboxsdk.annotations.IconFactory
import com.mapbox.mapboxsdk.annotations.Marker
import com.mapbox.mapboxsdk.annotations.MarkerOptions
import com.mapbox.mapboxsdk.maps.MapboxMap
import nz.co.trademe.mapme.LatLng
import nz.co.trademe.mapme.annotations.MarkerAnnotation
class MapboxMarkerAnnotation(latLng: LatLng,
title: String?,
icon: Bitmap? = null) : MarkerAnnotation(latLng, title, icon) {
override fun onUpdateIcon(icon: Bitmap?) {
nativeMarker?.let {
if (icon != null) {
nativeMarker?.icon = (IconFactory.recreate(nativeMarker!!.icon.id, icon))
} else {
nativeMarker?.icon = null
}
}
}
override fun onUpdateTitle(title: String?) {
nativeMarker?.title = title
}
override fun onUpdatePosition(position: LatLng) {
nativeMarker?.position = position.toMapBoxLatLng()
}
override fun onUpdateZIndex(index: Float) {
Log.w(MapboxMarkerAnnotation::class.simpleName, "zIndex not supported on MapboxMarkerAnnotations")
}
override fun onUpdateAlpha(alpha: Float) {
Log.w(MapboxMarkerAnnotation::class.simpleName, "alpha not supported on MapboxMarkerAnnotations")
}
override fun onUpdateAnchor(anchorUV: Pair<Float, Float>) {
Log.w(MapboxMarkerAnnotation::class.simpleName, "anchor not supported on MapboxMarkerAnnotations")
}
private var nativeMarker: Marker? = null
override fun annotatesObject(objec: Any): Boolean {
return nativeMarker?.equals(objec) ?: false
}
override fun removeFromMap(map: Any, context: Context) {
nativeMarker?.remove()
nativeMarker = null
}
override fun addToMap(map: Any, context: Context) {
val mapboxMap = map as MapboxMap
val markerOptions = MarkerOptions()
.icon(icon?.toMapboxIcon(context))
.title(title)
.position(latLng.toMapBoxLatLng())
nativeMarker = mapboxMap.addMarker(markerOptions)
}
}
| 12 | null | 80 | 847 | df0e928452c9d9fa001fb51f6af103b509830047 | 2,224 | MapMe | MIT License |
android/navigation_module_compose/src/main/java/com/example/sdk/sample/ui/common/DemoTheme.kt | citymapper | 346,046,671 | false | {"Swift": 89819, "Kotlin": 64091, "Ruby": 652} | package com.example.sdk.sample.ui.common
import androidx.compose.material.MaterialTheme
import androidx.compose.material.lightColors
import androidx.compose.runtime.Composable
val demoColors = lightColors()
@Composable
fun DemoTheme(children: @Composable () -> Unit) {
MaterialTheme(colors = demoColors) {
children()
}
}
| 1 | Swift | 2 | 4 | 87d37d87de5ef26c21779f4c5d2856a3413c71cb | 332 | sdk-samples | MIT License |
plants/plant-list/src/main/kotlin/xyz/qwexter/plant_list/PlantsScreen.kt | qwexter | 345,752,908 | false | null | package xyz.qwexter.plant_list
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.*
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewmodel.compose.viewModel
import xyz.qwexter.compose_ui.components.Header
import xyz.qwexter.navigation.NavCommandProcessor
import xyz.qwexter.navigation.NavFabAddTag
import xyz.qwexter.plant_list.components.AddTagButton
import xyz.qwexter.plant_list.components.TagButton
import xyz.qwexter.selectable_plant.component.PlantCard
import xyz.qwexter.selectable_plant.data.UiPlant
@ExperimentalMaterialApi
@Composable
fun PlantsScreen(
navCommandProcessor: NavCommandProcessor,
factory: ViewModelProvider.Factory? = null,
viewModel: PlantsViewModel = viewModel(factory = factory)
) {
val plants: List<UiPlant> by viewModel.plants.collectAsState(emptyList())
val tags: List<UiTag> by viewModel.tags.collectAsState(emptyList())
val lazyListState = rememberLazyListState()
PlantsScreenContent(
plants,
tags,
lazyListState,
viewModel::onTagClicked
) { navCommandProcessor.reduce(NavFabAddTag) }
}
@ExperimentalMaterialApi
@Composable
internal fun PlantsScreenContent(
plants: List<UiPlant>,
tags: List<UiTag>,
lazyListState: LazyListState,
onTagClicked: (Long) -> Unit,
onAddTagClicked: () -> Unit
) {
LazyColumn(
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight(),
state = lazyListState,
) {
item {
Header(
"Тэги",
Modifier
.fillMaxWidth()
.wrapContentHeight()
.padding(horizontal = 16.dp)
)
}
item {
TagsRow(
tags,
onTagClicked::invoke,
onAddTagClicked::invoke
)
}
item {
Header(
"Мои Растения",
Modifier
.fillMaxWidth()
.wrapContentHeight()
.padding(horizontal = 16.dp)
)
}
items(plants) { item ->
PlantCard(
item,
Modifier
.fillMaxWidth()
.wrapContentHeight()
.padding(start = 16.dp, end = 16.dp, bottom = 12.dp),
onPlantClicked = {}
)
}
}
}
@Composable
fun TagsRow(
tags: List<UiTag>,
onTagClicked: (Long) -> Unit,
onAddTagClicked: () -> Unit
) {
LazyRow(
horizontalArrangement = Arrangement.spacedBy(12.dp),
contentPadding = PaddingValues(horizontal = 16.dp),
modifier = Modifier
.fillMaxWidth()
.wrapContentHeight()
) {
items(tags) {
when (it) {
is UiTag.Tag -> TagButton(it, onClick = onTagClicked::invoke)
is UiTag.AddTag -> AddTagButton(it, onClick = onAddTagClicked::invoke)
}
}
}
}
| 2 | Kotlin | 0 | 0 | c6c5ec88436948c6046ea95d269d8727b0d0798c | 3,322 | plantscare | MIT License |
apps/etterlatte-brev-api/src/main/kotlin/no/nav/etterlatte/brev/oversendelsebrev/OversendelseBrevService.kt | navikt | 417,041,535 | false | {"Kotlin": 7159442, "TypeScript": 1725433, "Handlebars": 26265, "Shell": 12687, "HTML": 1734, "CSS": 598, "PLpgSQL": 556, "Dockerfile": 547} | package no.nav.etterlatte.brev.oversendelsebrev
import kotlinx.coroutines.runBlocking
import no.nav.etterlatte.brev.Brevkoder
import no.nav.etterlatte.brev.Brevtype
import no.nav.etterlatte.brev.EtterlatteBrevKode
import no.nav.etterlatte.brev.PDFGenerator
import no.nav.etterlatte.brev.VedtaksbrevKanIkkeSlettes
import no.nav.etterlatte.brev.adresse.AdresseService
import no.nav.etterlatte.brev.adresse.AvsenderRequest
import no.nav.etterlatte.brev.behandling.PersonerISak
import no.nav.etterlatte.brev.behandlingklient.BehandlingKlient
import no.nav.etterlatte.brev.db.BrevRepository
import no.nav.etterlatte.brev.hentinformasjon.BrevdataFacade
import no.nav.etterlatte.brev.model.Brev
import no.nav.etterlatte.brev.model.BrevDataFerdigstilling
import no.nav.etterlatte.brev.model.BrevDataFerdigstillingRequest
import no.nav.etterlatte.brev.model.BrevID
import no.nav.etterlatte.brev.model.BrevInnhold
import no.nav.etterlatte.brev.model.BrevProsessType
import no.nav.etterlatte.brev.model.Mottaker
import no.nav.etterlatte.brev.model.OpprettNyttBrev
import no.nav.etterlatte.brev.model.Pdf
import no.nav.etterlatte.brev.model.Slate
import no.nav.etterlatte.libs.common.behandling.Klage
import no.nav.etterlatte.libs.common.behandling.KlageUtfallMedData
import no.nav.etterlatte.libs.common.behandling.SakType
import no.nav.etterlatte.libs.common.feilhaandtering.GenerellIkkeFunnetException
import no.nav.etterlatte.libs.common.feilhaandtering.InternfeilException
import no.nav.etterlatte.libs.common.feilhaandtering.UgyldigForespoerselException
import no.nav.etterlatte.libs.common.person.Folkeregisteridentifikator
import no.nav.etterlatte.libs.common.person.Vergemaal
import no.nav.etterlatte.libs.common.tidspunkt.Tidspunkt
import no.nav.etterlatte.libs.ktor.token.BrukerTokenInfo
import java.time.LocalDate
import java.util.UUID
interface OversendelseBrevService {
fun hentOversendelseBrev(behandlingId: UUID): Brev?
suspend fun opprettOversendelseBrev(
behandlingId: UUID,
brukerTokenInfo: BrukerTokenInfo,
): Brev
suspend fun pdf(
brevId: Long,
behandlingId: UUID,
brukerTokenInfo: BrukerTokenInfo,
): Pdf
fun ferdigstillOversendelseBrev(
brevId: Long,
sakId: Long,
brukerTokenInfo: BrukerTokenInfo,
): Pdf
suspend fun slettOversendelseBrev(
behandlingId: UUID,
brukerTokenInfo: BrukerTokenInfo,
)
}
class OversendelseBrevServiceImpl(
private val brevRepository: BrevRepository,
private val pdfGenerator: PDFGenerator,
private val adresseService: AdresseService,
private val brevdataFacade: BrevdataFacade,
private val behandlingKlient: BehandlingKlient,
) : OversendelseBrevService {
override fun hentOversendelseBrev(behandlingId: UUID): Brev? =
brevRepository.hentBrevForBehandling(behandlingId, Brevtype.OVERSENDELSE_KLAGE).singleOrNull()
override suspend fun opprettOversendelseBrev(
behandlingId: UUID,
brukerTokenInfo: BrukerTokenInfo,
): Brev {
val eksisterendeBrev =
brevRepository
.hentBrevForBehandling(behandlingId, Brevtype.OVERSENDELSE_KLAGE)
.singleOrNull()
if (eksisterendeBrev != null) {
return eksisterendeBrev
}
val klage = brevdataFacade.hentKlage(behandlingId, brukerTokenInfo)
val generellBrevData =
brevdataFacade.hentGenerellBrevData(
sakId = klage.sak.id,
// Setter behandlingId som null for å unngå å hente en behandling med klageId'en
behandlingId = null,
brukerTokenInfo = brukerTokenInfo,
)
val brev =
brevRepository.opprettBrev(
OpprettNyttBrev(
sakId = klage.sak.id,
behandlingId = behandlingId,
soekerFnr = klage.sak.ident,
prosessType = BrevProsessType.AUTOMATISK,
mottaker = finnMottaker(klage.sak.sakType, generellBrevData.personerISak),
opprettet = Tidspunkt.now(),
innhold =
BrevInnhold(
tittel = EtterlatteBrevKode.KLAGE_OVERSENDELSE_BRUKER.tittel ?: "Klage oversendelse",
spraak = generellBrevData.spraak,
),
innholdVedlegg = listOf(),
brevtype = Brevtype.OVERSENDELSE_KLAGE,
),
)
return brev
}
override suspend fun pdf(
brevId: Long,
behandlingId: UUID,
brukerTokenInfo: BrukerTokenInfo,
): Pdf {
val brev = brevRepository.hentBrev(brevId)
if (!brev.kanEndres()) {
return brevRepository.hentPdf(
brevId,
) ?: throw InternfeilException("Har et brev som ikke kan endres men ikke har en pdf, brevId=$brevId")
}
if (brev.brevtype != Brevtype.OVERSENDELSE_KLAGE) {
throw UgyldigForespoerselException(
"FEIL_BREVTYPE",
"Brevet med id=$brevId er ikke av typen oversendelse klage, og kan ikke hentes som et oversendelse klage-brev",
)
}
if (brev.behandlingId != behandlingId) {
throw UgyldigForespoerselException(
"FEIL_BREV_ID",
"Brevet med id=$brevId er ikke koblet på behandlingen med id=$behandlingId",
)
}
val klage = brevdataFacade.hentKlage(requireNotNull(brev.behandlingId), brukerTokenInfo)
return pdfGenerator.genererPdf(
id = brev.id,
bruker = brukerTokenInfo,
avsenderRequest = { bruker, generellData -> AvsenderRequest(bruker.ident(), generellData.sak.enhet) },
brevKode = { Brevkoder.OVERSENDELSE_KLAGE },
brevData = { req -> OversendelseBrevFerdigstillingData.fra(req, klage) },
)
}
private suspend fun finnMottaker(
sakType: SakType,
personerISak: PersonerISak,
): Mottaker =
with(personerISak) {
val mottakerFnr: String =
when (verge) {
is Vergemaal -> verge.foedselsnummer.value
else ->
innsender?.fnr?.value?.takeIf { Folkeregisteridentifikator.isValid(it) }
?: soeker.fnr.value
}
adresseService.hentMottakerAdresse(sakType, mottakerFnr)
}
override fun ferdigstillOversendelseBrev(
brevId: Long,
sakId: Long,
brukerTokenInfo: BrukerTokenInfo,
): Pdf {
val brev = brevRepository.hentBrev(brevId)
if (brev.sakId != sakId) {
throw MismatchSakOgBrevException(brevId, sakId)
}
if (!brev.kanEndres()) {
return brevRepository.hentPdf(brevId) ?: throw GenerellIkkeFunnetException()
}
if (brev.brevtype != Brevtype.OVERSENDELSE_KLAGE) {
throw UgyldigForespoerselException(
"FEIL_BREVTYPE",
"Kan ikke ferdigstille brevet med id=$brevId som oversendelsesbrev, " +
"siden det har feil brevtype",
)
}
val behandlingId = checkNotNull(brev.behandlingId)
val klage =
runBlocking {
brevdataFacade.hentKlage(klageId = behandlingId, brukerTokenInfo)
}
val pdf =
runBlocking {
pdfGenerator.ferdigstillOgGenererPDF(
id = brev.id,
bruker = brukerTokenInfo,
avsenderRequest = { bruker, generellData ->
AvsenderRequest(
bruker.ident(),
generellData.sak.enhet,
)
},
brevKode = { Brevkoder.OVERSENDELSE_KLAGE },
brevData = { req -> OversendelseBrevFerdigstillingData.fra(req, klage) },
)
}
return pdf
}
override suspend fun slettOversendelseBrev(
behandlingId: UUID,
brukerTokenInfo: BrukerTokenInfo,
) {
val brev =
brevRepository
.hentBrevForBehandling(behandlingId, Brevtype.OVERSENDELSE_KLAGE)
.singleOrNull() ?: return
if (!brev.kanEndres()) {
throw VedtaksbrevKanIkkeSlettes(brev.id, "Brevet har status (${brev.status})")
}
val behandlingKanEndres = behandlingKlient.hentVedtaksbehandlingKanRedigeres(behandlingId, brukerTokenInfo)
if (!behandlingKanEndres) {
throw VedtaksbrevKanIkkeSlettes(brev.id, "Behandlingen til vedtaksbrevet kan ikke endres")
}
brevRepository.settBrevSlettet(brev.id, brukerTokenInfo)
}
}
data class OversendelseBrevFerdigstillingData(
val sakType: SakType,
val klageDato: LocalDate,
val vedtakDato: LocalDate,
val innstillingTekst: String,
val under18Aar: Boolean,
val harVerge: Boolean,
val bosattIUtlandet: Boolean,
) : BrevDataFerdigstilling {
override val innhold: List<Slate.Element> = emptyList()
companion object {
fun fra(
request: BrevDataFerdigstillingRequest,
klage: Klage,
): BrevDataFerdigstilling {
val innstilling =
when (val utfall = klage.utfall) {
is KlageUtfallMedData.DelvisOmgjoering -> {
utfall.innstilling
}
is KlageUtfallMedData.StadfesteVedtak -> {
utfall.innstilling
}
else -> throw UgyldigForespoerselException(
"FEIL_DATA_KLAGE",
"Klagen med id=${klage.id} har ikke en innstilling, så kan ikke lage et oversendelsesbrev",
)
}
return OversendelseBrevFerdigstillingData(
sakType = request.generellBrevData.sak.sakType,
klageDato = klage.innkommendeDokument?.mottattDato ?: klage.opprettet.toLocalDate(),
vedtakDato =
checkNotNull(
klage.formkrav
?.formkrav
?.vedtaketKlagenGjelder
?.datoAttestert
?.toLocalDate(),
) {
"Klagen har en ugyldig referanse til når originalt vedtak ble attestert, klageId=${klage.id}"
},
innstillingTekst = innstilling.innstillingTekst,
under18Aar = request.generellBrevData.personerISak.soeker.under18 ?: false,
harVerge = request.generellBrevData.personerISak.verge != null,
// TODO: støtte bosatt utland klage
bosattIUtlandet = false,
)
}
}
}
class MismatchSakOgBrevException(
brevId: BrevID,
sakId: Long,
) : UgyldigForespoerselException(
code = "SAKID_MATCHER_IKKE",
detail = "Brevet med id=$brevId har ikke angitt sakId=$sakId",
)
| 9 | Kotlin | 0 | 6 | fe4ed6670fcc0d3fcd117c51b5a7acc224fa6bd2 | 11,254 | pensjon-etterlatte-saksbehandling | MIT License |
app1/src/main/java/cn/cxy/news/network/BaseRepository.kt | hspbc666 | 312,502,040 | false | null | package cn.cxy.news.network
import com.google.gson.GsonBuilder
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
open class BaseRepository {
val apiService: NetworkService by lazy {
val okHttpClient = OkHttpClient.Builder().build()
Retrofit.Builder()
.client(okHttpClient)
.baseUrl("https://wanandroid.com/")
.addConverterFactory(GsonConverterFactory.create(GsonBuilder().create()))
.build().create(NetworkService::class.java)
}
} | 0 | Kotlin | 0 | 1 | cb76cc950adb29345f235b0b0d9a833b0daa1b2c | 562 | orange-news | Apache License 2.0 |
src/main/kotlin/com/ovnny/notifications/config/security/SecurityConfig.kt | ovnny2 | 561,561,429 | false | null | package com.ovnny.notifications.config.security
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
import org.springframework.security.config.annotation.web.configurers.oauth2.server.resource.OAuth2ResourceServerConfigurer
import org.springframework.security.oauth2.jwt.JwtDecoder
import org.springframework.security.oauth2.jwt.JwtDecoders
import org.springframework.security.web.SecurityFilterChain
@Configuration
@EnableWebSecurity
class SecurityConfig(
private val jwtProperties: JwtIssuerUriProperties
) {
@Bean
@Throws(Exception::class)
fun filterChain(http: HttpSecurity): SecurityFilterChain {
http.authorizeRequests()
.antMatchers("/v1/notifications**")
.hasRole("USER")
.anyRequest()
.authenticated()
http.oauth2ResourceServer {
obj: OAuth2ResourceServerConfigurer<HttpSecurity?> -> obj.jwt()
}
return http.build()
}
@Bean
protected fun jwtDecoder(): JwtDecoder {
return JwtDecoders.fromIssuerLocation(jwtProperties.issuerUri)
}
} | 0 | Kotlin | 0 | 0 | 0b053c9e8508689ce5a108bba13e86280a60a296 | 1,307 | notifications | Apache License 2.0 |
example/android/app/src/main/kotlin/com/yuxiaor/flutter/g_faraday_example/basic/Native2FlutterActivity.kt | gfaraday | 299,574,522 | false | null | package com.yuxiaor.flutter.g_faraday_example.basic
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.yuxiaor.flutter.g_faraday.FaradayActivity
import com.yuxiaor.flutter.g_faraday_example.R
import com.yuxiaor.flutter.g_faraday_example.faraday.KEY_ARGS
import java.util.*
class Native2FlutterActivity: AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_native2flutter)
findViewById<Button>(R.id.button).setOnClickListener {
val intent = FaradayActivity.builder(routeName = "native2flutter", Date().toString()).build(this)
startActivityForResult(intent, 1)
}
findViewById<Button>(R.id.transparentButton).setOnClickListener {
val intent = TransparentBackgroundFlutterActivity.build(this)
startActivity(intent)
// 阻止动画
overridePendingTransition(0, 0)
}
actionBar?.title = "Native2Flutter"
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
data?.extras.let {
val textView = findViewById<TextView>(R.id.result)
if (it != null) {
textView.text = it.get(KEY_ARGS)?.toString()
textView.setTextColor(Color.RED)
} else {
textView.text = null
}
}
}
} | 9 | null | 21 | 142 | f6f73d59812bb73fbdb5af1ad6d60c4bd2017d0b | 1,644 | g_faraday | MIT License |
platform/platform-api/src/com/intellij/openapi/wm/BannerStartPagePromoter.kt | ingokegel | 72,937,917 | false | null | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.wm
import com.intellij.icons.AllIcons
import com.intellij.openapi.ui.popup.IconButton
import com.intellij.openapi.util.SystemInfo
import com.intellij.ui.InplaceButton
import com.intellij.ui.JBColor
import com.intellij.ui.components.panels.BackgroundRoundedPanel
import com.intellij.ui.components.panels.NonOpaquePanel
import com.intellij.ui.scale.JBUIScale
import com.intellij.util.ui.*
import org.jetbrains.annotations.Nls
import java.awt.Component
import java.awt.Dimension
import java.awt.Font
import java.awt.Rectangle
import java.awt.event.ActionEvent
import javax.swing.*
abstract class BannerStartPagePromoter : StartPagePromoter {
override fun getPromotion(isEmptyState: Boolean): JComponent {
val vPanel: JPanel = NonOpaquePanel()
vPanel.layout = BoxLayout(vPanel, BoxLayout.PAGE_AXIS)
vPanel.alignmentY = Component.TOP_ALIGNMENT
val headerPanel: JPanel = NonOpaquePanel()
headerPanel.layout = BoxLayout(headerPanel, BoxLayout.X_AXIS)
headerPanel.alignmentX = Component.LEFT_ALIGNMENT
headerPanel.add(createHeader())
headerPanel.add(Box.createHorizontalGlue())
val hPanel: JPanel = BackgroundRoundedPanel(JBUI.scale(16))
closeAction?.let { closeAction ->
val closeIcons = IconButton(null, AllIcons.Actions.Close, AllIcons.Actions.CloseDarkGrey)
val closeButton = InplaceButton(closeIcons) {
closeAction(hPanel)
}
closeButton.maximumSize = Dimension(16, 16)
headerPanel.add(closeButton)
}
vPanel.add(headerPanel)
vPanel.add(rigid(0, 4))
val description = JLabel("<html>${description}</html>").also {
it.alignmentX = Component.LEFT_ALIGNMENT
it.font = JBUI.Fonts.label().deriveFont(JBUI.Fonts.label().size2D + (when {
SystemInfo.isLinux -> JBUIScale.scale(-2)
SystemInfo.isMac -> JBUIScale.scale(-1)
else -> 0
}))
it.foreground = UIUtil.getContextHelpForeground()
}
vPanel.add(description)
val jButton = JButton()
jButton.isOpaque = false
jButton.alignmentX = Component.LEFT_ALIGNMENT
jButton.action = object : AbstractAction(actionLabel) {
override fun actionPerformed(e: ActionEvent?) {
runAction()
}
}
val minSize = JBDimension(0, 8)
vPanel.add(Box.Filler(minSize, minSize, Dimension(0, Short.MAX_VALUE.toInt())))
vPanel.add(buttonPixelHunting(jButton))
hPanel.background = JBColor.namedColor("WelcomeScreen.SidePanel.background", JBColor(0xF2F2F2, 0x3C3F41))
hPanel.layout = BoxLayout(hPanel, BoxLayout.X_AXIS)
hPanel.border = JBUI.Borders.empty(12, 16, 16, 16)
val picture = JLabel(promoImage)
picture.alignmentY = Component.TOP_ALIGNMENT
hPanel.add(picture)
hPanel.add(rigid(20, 0))
hPanel.add(vPanel)
return hPanel
}
private fun buttonPixelHunting(button: JButton): JPanel {
val buttonPlace = object: JPanel() {
override fun updateUI() {
super.updateUI()
val buttonSizeWithoutInsets = Dimension(button.preferredSize.width - button.insets.left - button.insets.right,
button.preferredSize.height - button.insets.top - button.insets.bottom)
apply {
layout = null
maximumSize = buttonSizeWithoutInsets
preferredSize = buttonSizeWithoutInsets
minimumSize = buttonSizeWithoutInsets
isOpaque = false
alignmentX = LEFT_ALIGNMENT
}
button.bounds = Rectangle(-button.insets.left, -button.insets.top, button.preferredSize.width, button.preferredSize.height)
}
}
buttonPlace.add(button)
buttonPlace.updateUI()
return buttonPlace
}
private fun rigid(width: Int, height: Int): Component {
return scaledRigid(JBUI.scale(width), JBUI.scale(height))
}
private fun scaledRigid(width: Int, height: Int): Component {
return (Box.createRigidArea(Dimension(width, height)) as JComponent).apply {
alignmentX = Component.LEFT_ALIGNMENT
alignmentY = Component.TOP_ALIGNMENT
}
}
protected abstract val headerLabel: @Nls String
protected abstract val actionLabel: @Nls String
protected abstract val description: @Nls String
protected abstract val promoImage: Icon
protected open val closeAction: ((promoPanel: JPanel) -> Unit)? = null
protected abstract fun runAction()
protected open fun createHeader(): JLabel {
val result = JLabel(headerLabel)
val labelFont = StartupUiUtil.labelFont
result.font = JBFont.create(labelFont).deriveFont(Font.BOLD).deriveFont(labelFont.size2D + JBUI.scale(2))
return result
}
} | 251 | null | 5079 | 2 | b07eabd319ad5b591373d63c8f502761c2b2dfe8 | 4,761 | intellij-community | Apache License 2.0 |
app/src/main/java/com/kcteam/features/billing/presentation/BillingListFragment.kt | DebashisINT | 558,234,039 | false | null | package com.breezesalesoriplast.features.billing.presentation
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import com.google.android.material.floatingactionbutton.FloatingActionButton
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.FileProvider
import com.breezesalesoriplast.NumberToWords
import com.pnikosis.materialishprogress.ProgressWheel
import com.breezesalesoriplast.R
import com.breezesalesoriplast.app.AppDatabase
import com.breezesalesoriplast.app.NetworkConstant
import com.breezesalesoriplast.app.Pref
import com.breezesalesoriplast.app.domain.*
import com.breezesalesoriplast.app.types.FragType
import com.breezesalesoriplast.app.utils.AppUtils
import com.breezesalesoriplast.app.utils.FTStorageUtils
import com.breezesalesoriplast.base.BaseResponse
import com.breezesalesoriplast.base.presentation.BaseActivity
import com.breezesalesoriplast.base.presentation.BaseFragment
import com.breezesalesoriplast.features.addshop.api.AddShopRepositoryProvider
import com.breezesalesoriplast.features.addshop.api.assignToPPList.AssignToPPListRepoProvider
import com.breezesalesoriplast.features.addshop.api.assignedToDDList.AssignToDDListRepoProvider
import com.breezesalesoriplast.features.addshop.api.typeList.TypeListRepoProvider
import com.breezesalesoriplast.features.addshop.model.AddShopRequestData
import com.breezesalesoriplast.features.addshop.model.AddShopResponse
import com.breezesalesoriplast.features.addshop.model.AssignedToShopListResponseModel
import com.breezesalesoriplast.features.addshop.model.assigntoddlist.AssignToDDListResponseModel
import com.breezesalesoriplast.features.addshop.model.assigntopplist.AssignToPPListResponseModel
import com.breezesalesoriplast.features.billing.api.AddBillingRepoProvider
import com.breezesalesoriplast.features.billing.model.AddBillingInputParamsModel
import com.breezesalesoriplast.features.dashboard.presentation.DashboardActivity
import com.breezesalesoriplast.features.location.LocationWizard
import com.breezesalesoriplast.features.location.model.ShopDurationRequest
import com.breezesalesoriplast.features.location.model.ShopDurationRequestData
import com.breezesalesoriplast.features.location.shopdurationapi.ShopDurationRepositoryProvider
import com.breezesalesoriplast.features.nearbyshops.presentation.QrCodeDialog
import com.breezesalesoriplast.features.viewAllOrder.api.addorder.AddOrderRepoProvider
import com.breezesalesoriplast.features.viewAllOrder.model.AddOrderInputParamsModel
import com.breezesalesoriplast.features.viewAllOrder.model.AddOrderInputProductList
import com.breezesalesoriplast.widgets.AppCustomTextView
import com.itextpdf.text.*
import com.itextpdf.text.pdf.PdfPCell
import com.itextpdf.text.pdf.PdfPTable
import com.itextpdf.text.pdf.PdfWriter
import com.itextpdf.text.pdf.draw.VerticalPositionMark
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.uiThread
import timber.log.Timber
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import kotlin.collections.ArrayList
/**
* Created by Saikat on 19-02-2019.
*/
// 1.0 AddBillingFragment AppV 4.0.6 saheli 12-01-2023 multiple contact Data added on Api called
class BillingListFragment : BaseFragment(), View.OnClickListener {
private lateinit var mContext: Context
private lateinit var rv_billing_list: RecyclerView
private lateinit var fab: FloatingActionButton
private lateinit var progress_wheel: ProgressWheel
private lateinit var tv_no_data_available: AppCustomTextView
companion object {
private var order: OrderDetailsListEntity? = null
fun newInstance(objects: Any): BillingListFragment {
val fragment = BillingListFragment()
if (objects is OrderDetailsListEntity)
order = objects
return fragment
}
}
override fun onAttach(context: Context) {
super.onAttach(context)
mContext = context
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
super.onCreateView(inflater, container, savedInstanceState)
val view = inflater.inflate(R.layout.fragment_billing_list, container, false)
initView(view)
val list = AppDatabase.getDBInstance()!!.billingDao().getDataOrderIdWise(order?.order_id!!) as ArrayList
if (list != null && list.isNotEmpty())
initAdapter(list)
else {
tv_no_data_available.visibility = View.VISIBLE
}
return view
}
@SuppressLint("RestrictedApi")
private fun initView(view: View) {
fab = view.findViewById(R.id.fab)
progress_wheel = view.findViewById(R.id.progress_wheel)
progress_wheel.stopSpinning()
rv_billing_list = view.findViewById(R.id.rv_billing_list)
rv_billing_list.layoutManager = LinearLayoutManager(mContext)
tv_no_data_available = view.findViewById(R.id.tv_no_data_available)
if (Pref.canAddBillingFromBillingList)
fab.visibility = View.VISIBLE
else
fab.visibility = View.GONE
fab.setOnClickListener(this)
}
private fun initAdapter(list: ArrayList<BillingEntity>) {
tv_no_data_available.visibility = View.GONE
rv_billing_list.adapter = BillingListAdapter(mContext, list, object : BillingListAdapter.OnClickListener {
override fun onSyncClick(adapterPosition: Int) {
if (AppUtils.isOnline(mContext)) {
if (!(mContext as DashboardActivity).shop?.isUploaded!!)
syncShop(list[adapterPosition], (mContext as DashboardActivity).shop!!)
else
checkToCallOrderApi(list[adapterPosition])
} else
(mContext as DashboardActivity).showSnackMessage(getString(R.string.no_internet))
}
override fun onDownloadClick(bill: BillingEntity) {
/*val heading = "SALES INVOICE"
var pdfBody = "\n\n\n\nInvoice No.: " + bill.invoice_no + "\n\nInvoice Date: " +
AppUtils.convertToCommonFormat(bill.invoice_date) + "\n\nInvoice Amount: " + getString(R.string.rupee_symbol_with_space) + bill.invoice_amount +
"\n\nOrder No.: " + bill.order_id + "\n\nOrder Date: "
val order = AppDatabase.getDBInstance()!!.orderDetailsListDao().getSingleOrder(bill.order_id)
val shop = AppDatabase.getDBInstance()?.addShopEntryDao()?.getShopByIdN(order?.shop_id)
pdfBody = pdfBody + order?.only_date!! + "\n\nParty Name: " + shop?.shopName + "\n\nAddress: " + shop?.address +
"\n\nContact No.: " + shop?.ownerContactNumber + "\n\nSales Person: " + Pref.user_name + "\n\n\n"
val productList = AppDatabase.getDBInstance()!!.orderProductListDao().getDataAccordingToOrderId(order.order_id!!)
productList?.forEach { it1 ->
pdfBody = pdfBody + "Item: " + it1.product_name + "\nQty: " + it1.qty + " Rate: " +
getString(R.string.rupee_symbol_with_space) + it1.rate + " Amount: " + getString(R.string.rupee_symbol_with_space) +
it1.total_price + "\n\n"
}
pdfBody = pdfBody + "Total Amount: " + getString(R.string.rupee_symbol_with_space) + order.amount
val image = BitmapFactory.decodeResource(mContext.resources, R.mipmap.ic_launcher)
val path = FTStorageUtils.stringToPdf(pdfBody, mContext, "FTS_" + bill.bill_id + ".pdf", image,
heading, 2.7f)
if (!TextUtils.isEmpty(path)) {
try {
val shareIntent = Intent(Intent.ACTION_SEND)
val fileUrl = Uri.parse(path)
val file = File(fileUrl.path)
//val uri = Uri.fromFile(file)
//27-09-2021
val uri: Uri = FileProvider.getUriForFile(mContext, context!!.applicationContext.packageName.toString() + ".provider", file)
shareIntent.type = "image/png"
shareIntent.putExtra(Intent.EXTRA_STREAM, uri)
startActivity(Intent.createChooser(shareIntent, "Share pdf using"));
} catch (e: Exception) {
e.printStackTrace()
}
} else
(mContext as DashboardActivity).showSnackMessage("Pdf can not be sent.")*/
/*27-04-2022*/
saveDataAsPdf(bill)
}
override fun onCreateQrClick(bill: BillingEntity) {
var pdfBody = "Invoice No.: " + bill.invoice_no + "\n\nInvoice Date: " +
AppUtils.convertToCommonFormat(bill.invoice_date) + "\n\nInvoice Amount: INR." + bill.invoice_amount +
"\n\nOrder No.: " + bill.order_id + "\n\nOrder Date: "
val order = AppDatabase.getDBInstance()!!.orderDetailsListDao().getSingleOrder(bill.order_id)
val shop = AppDatabase.getDBInstance()?.addShopEntryDao()?.getShopByIdN(order?.shop_id)
pdfBody = pdfBody + order?.only_date!! + "\n\nParty Name: " + shop?.shopName + "\n\nAddress: " + shop?.address +
"\n\nContact No.: " + shop?.ownerContactNumber + "\n\nSales Person: " + Pref.user_name + "\n\n\n"
val productList = AppDatabase.getDBInstance()!!.orderProductListDao().getDataAccordingToOrderId(order.order_id!!)
productList?.forEach { it1 ->
pdfBody = pdfBody + "Item: " + it1.product_name + "\nQty: " + it1.qty + " Rate: INR." + it1.rate + " Amount: INR." +
it1.total_price + "\n\n"
}
pdfBody = pdfBody + "Total Amount: INR." + order.amount
val bitmap = AppUtils.createQrCode(pdfBody)
if (bitmap != null)
QrCodeDialog.newInstance(bitmap, shop?.shop_id!!, shop.shopName!!, bill.bill_id!!, "Create QR of Invoice").show((mContext as DashboardActivity).supportFragmentManager, "")
}
})
}
private fun saveDataAsPdf(obj: BillingEntity) {
/*27-04-2022 new pdf format*/
var document: Document = Document()
var fileName = "FTS" + "_" + obj.bill_id
fileName = fileName.replace("/", "_")
val path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString() + "/breezesalesoriplastApp/INVOICEDETALIS/"
var pathNew = ""
val dir = File(path)
if (!dir.exists()) {
dir.mkdirs()
}
try {
try {
PdfWriter.getInstance(document, FileOutputStream(path + fileName + ".pdf"))
}catch (ex:Exception){
ex.printStackTrace()
pathNew = mContext.filesDir.toString() + "/" + fileName+".pdf"
//val file = File(mContext.filesDir.toString() + "/" + fileName)
PdfWriter.getInstance(document, FileOutputStream(pathNew))
}
document.open()
var font: Font = Font(Font.FontFamily.HELVETICA, 10f, Font.BOLD)
var fontBoldU: Font = Font(Font.FontFamily.HELVETICA, 12f, Font.UNDERLINE or Font.BOLD)
var font1: Font = Font(Font.FontFamily.HELVETICA, 8f, Font.NORMAL)
val grayFront = Font(Font.FontFamily.HELVETICA, 8f, Font.NORMAL, BaseColor.GRAY)
//image add
val bm: Bitmap = BitmapFactory.decodeResource(resources, R.drawable.breezelogo)
val bitmap = Bitmap.createScaledBitmap(bm, 80, 80, true);
val stream = ByteArrayOutputStream()
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream)
var img: Image? = null
val byteArray: ByteArray = stream.toByteArray()
try {
img = Image.getInstance(byteArray)
img.scaleToFit(110f, 110f)
img.scalePercent(70f)
img.alignment = Image.ALIGN_LEFT
} catch (e: BadElementException) {
e.printStackTrace()
} catch (e: IOException) {
e.printStackTrace()
}
/////////////////////////////
val sp = Paragraph("", font)
sp.spacingAfter = 50f
document.add(sp)
val h = Paragraph("SALES INVOICE ", fontBoldU)
h.alignment = Element.ALIGN_CENTER
val pHead = Paragraph()
pHead.add(Chunk(img, 0f, -30f))
pHead.add(h)
document.add(pHead)
val x = Paragraph("", font)
x.spacingAfter = 20f
document.add(x)
val order = AppDatabase.getDBInstance()!!.orderDetailsListDao().getSingleOrder(obj.order_id)
val widthsOrder = floatArrayOf(0.50f, 0.50f)
var tableHeaderOrder: PdfPTable = PdfPTable(widthsOrder)
tableHeaderOrder.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER)
tableHeaderOrder.setWidthPercentage(100f)
val cell11 = PdfPCell(Phrase("Invoice No : " + obj.invoice_no + "\n\n" + "Invoice Date : " + AppUtils.convertToCommonFormat(obj.invoice_date), font))
cell11.setHorizontalAlignment(Element.ALIGN_LEFT)
cell11.borderColor = BaseColor.GRAY
tableHeaderOrder.addCell(cell11)
val cell222 = PdfPCell(Phrase("Order No : " + obj.order_id + "\n\n" + "Order Date : " + order.only_date, font))
cell222.setHorizontalAlignment(Element.ALIGN_LEFT);
cell222.borderColor = BaseColor.GRAY
cell222.paddingBottom = 10f
tableHeaderOrder.addCell(cell222)
document.add(tableHeaderOrder)
// var orderNoDate: String = ""
// var InvoicDate: String = ""
// val tableRows = PdfPTable(widthsOrder)
// tableRows.defaultCell.horizontalAlignment = Element.ALIGN_LEFT
// tableRows.setWidthPercentage(100f);
//
// var cellBodySl1 = PdfPCell(Phrase(orderNoDate + "Order Date: " + AppUtils.convertDateTimeToCommonFormat(obj.date!!), font))
// cellBodySl1.setHorizontalAlignment(Element.ALIGN_LEFT)
// cellBodySl1.borderColor = BaseColor.GRAY
//// tableRows.addCell(cellBodySl1)
//
//
// var cellBody22 = PdfPCell(Phrase(InvoicDate + invoiceNo + "Invoice Date: " + invoiceDate, font))
// cellBody22.setHorizontalAlignment(Element.ALIGN_LEFT)
// cellBody22.borderColor = BaseColor.GRAY
//// tableRows.addCell(cellBody22)
//
// document.add(tableRows)
document.add(Paragraph())
val xz = Paragraph("", font)
xz.spacingAfter = 10f
document.add(xz)
val HeadingPartyDetls = Paragraph("Details of Party ", fontBoldU)
HeadingPartyDetls.indentationLeft = 82f
// HeadingPartyDetls.alignment = Element.ALIGN_LEFT
HeadingPartyDetls.spacingAfter = 2f
document.add(HeadingPartyDetls)
val shop = AppDatabase.getDBInstance()?.addShopEntryDao()?.getShopByIdN(order.shop_id)
val Parties = Paragraph("Name : " + shop?.shopName, font1)
Parties.alignment = Element.ALIGN_LEFT
Parties.spacingAfter = 2f
document.add(Parties)
val address = Paragraph("Address : " + shop?.address, font1)
address.alignment = Element.ALIGN_LEFT
address.spacingAfter = 2f
document.add(address)
val Contact = Paragraph("Contact No. : " + shop?.ownerContactNumber, font1)
Contact.alignment = Element.ALIGN_LEFT
Contact.spacingAfter = 2f
document.add(Contact)
val xze = Paragraph("", font)
xze.spacingAfter = 10f
document.add(xze)
// table header
//val widths = floatArrayOf(0.55f, 0.05f, 0.2f, 0.2f)
val widths = floatArrayOf(0.06f, 0.58f, 0.07f, 0.07f, 0.07f, 0.15f)
var tableHeader: PdfPTable = PdfPTable(widths)
tableHeader.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT)
tableHeader.setWidthPercentage(100f)
val cell111 = PdfPCell(Phrase("SL. ", font))
cell111.setHorizontalAlignment(Element.ALIGN_LEFT)
cell111.borderColor = BaseColor.GRAY
tableHeader.addCell(cell111);
val cell1 = PdfPCell(Phrase("Item Description ", font))
cell1.setHorizontalAlignment(Element.ALIGN_LEFT)
cell1.borderColor = BaseColor.GRAY
tableHeader.addCell(cell1);
val cell2 = PdfPCell(Phrase("Qty ", font))
cell2.setHorizontalAlignment(Element.ALIGN_LEFT);
cell2.borderColor = BaseColor.GRAY
tableHeader.addCell(cell2);
val cell21 = PdfPCell(Phrase("Unit ", font))
cell21.setHorizontalAlignment(Element.ALIGN_LEFT);
cell21.borderColor = BaseColor.GRAY
tableHeader.addCell(cell21);
val cell3 = PdfPCell(Phrase("Rate ", font))
cell3.setHorizontalAlignment(Element.ALIGN_LEFT);
cell3.borderColor = BaseColor.GRAY
tableHeader.addCell(cell3);
val cell4 = PdfPCell(Phrase("Amount ", font))
cell4.setHorizontalAlignment(Element.ALIGN_LEFT);
cell4.borderColor = BaseColor.GRAY
tableHeader.addCell(cell4);
document.add(tableHeader)
//table body
var srNo: String = ""
var item: String = ""
var qty: String = ""
var unit: String = ""
var rate: String = ""
var amount: String = ""
val productList = AppDatabase.getDBInstance()!!.orderProductListDao().getDataAccordingToOrderId(order.order_id!!)
for (i in 0..productList.size - 1) {
srNo = (i + 1).toString() + " "
item = productList!!.get(i).product_name + " "
qty = productList!!.get(i).qty + " "
//unit = "KG" + " "
unit = productList!!.get(i).watt.toString()+" "
rate = getString(R.string.rupee_symbol_with_space) + " " + productList!!.get(i).rate + " "
amount = getString(R.string.rupee_symbol_with_space) + " " + productList!!.get(i).total_price + " "
val tableRows = PdfPTable(widths)
tableRows.defaultCell.horizontalAlignment = Element.ALIGN_CENTER
tableRows.setWidthPercentage(100f);
var cellBodySr = PdfPCell(Phrase(srNo, font1))
cellBodySr.setHorizontalAlignment(Element.ALIGN_LEFT);
cellBodySr.borderColor = BaseColor.GRAY
tableRows.addCell(cellBodySr)
var cellBodySl = PdfPCell(Phrase(item, font1))
cellBodySl.setHorizontalAlignment(Element.ALIGN_LEFT);
cellBodySl.borderColor = BaseColor.GRAY
tableRows.addCell(cellBodySl)
var cellBody2 = PdfPCell(Phrase(qty, font1))
cellBody2.setHorizontalAlignment(Element.ALIGN_LEFT)
cellBody2.borderColor = BaseColor.GRAY
tableRows.addCell(cellBody2)
var cellBody21 = PdfPCell(Phrase(unit, font1))
cellBody21.setHorizontalAlignment(Element.ALIGN_LEFT)
cellBody21.borderColor = BaseColor.GRAY
tableRows.addCell(cellBody21)
var cellBody3 = PdfPCell(Phrase(rate, font1))
cellBody3.setHorizontalAlignment(Element.ALIGN_LEFT)
cellBody3.borderColor = BaseColor.GRAY
tableRows.addCell(cellBody3)
var cellBody4 = PdfPCell(Phrase(amount, font1))
cellBody4.setHorizontalAlignment(Element.ALIGN_LEFT)
cellBody4.borderColor = BaseColor.GRAY
tableRows.addCell(cellBody4)
document.add(tableRows)
document.add(Paragraph())
}
val xffx = Paragraph("", font)
xffx.spacingAfter = 12f
document.add(xffx)
// val para = Paragraph()
// val glue = Chunk(VerticalPositionMark())
// val ph1 = Phrase()
// val main = Paragraph()
// ph1.add(Chunk("Rupees " + NumberToWords.numberToWord(order.amount!!.toDouble().toInt()!!)!!.toUpperCase() + " Only ", font))
// ph1.add(glue) // Here I add special chunk to the same phrase.
//
// ph1.add(Chunk("Total Amount: " + "\u20B9" + order.amount, font))
// para.add(ph1)
// document.add(para)
//
// val xfffx = Paragraph("", font)
// xfffx.spacingAfter = 8f
// document.add(xfffx)
val para1 = Paragraph ()
val glue1 = Chunk(VerticalPositionMark())
val ph11 = Phrase()
val main1 = Paragraph()
ph11.add(Chunk("Rupees " + NumberToWords.numberToWord(obj.invoice_amount!!.toDouble().toInt()!!)!!.toUpperCase() + " Only ", font))
ph11.add(glue1) // Here I add special chunk to the same phrase.
ph11.add(Chunk("Total Invoice Amount: " + "\u20B9" + obj.invoice_amount, font))
para1.add(ph11)
document.add(para1)
val xfx = Paragraph("", font)
xfx.spacingAfter = 12f
document.add(xfx)
val widthsSalesPerson = floatArrayOf(1f)
var tablewidthsSalesPersonHeader: PdfPTable = PdfPTable(widthsSalesPerson)
tablewidthsSalesPersonHeader.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT)
tablewidthsSalesPersonHeader.setWidthPercentage(100f)
val cellsales = PdfPCell(Phrase("Entered by: " + Pref.user_name, font1))
cellsales.setHorizontalAlignment(Element.ALIGN_LEFT)
cellsales.borderColor = BaseColor.GRAY
tablewidthsSalesPersonHeader.addCell(cellsales)
document.add(tablewidthsSalesPersonHeader)
// val salesPerson = Paragraph("Entered by: " + Pref.user_name, font)
// salesPerson.alignment = Element.ALIGN_LEFT
// salesPerson.spacingAfter = 10f
// document.add(salesPerson)
document.close()
var sendingPath = path + fileName + ".pdf"
if(!pathNew.equals("")){
sendingPath = pathNew
}
if (!TextUtils.isEmpty(sendingPath)) {
try {
val shareIntent = Intent(Intent.ACTION_SEND)
val fileUrl = Uri.parse(sendingPath)
val file = File(fileUrl.path)
val uri: Uri = FileProvider.getUriForFile(mContext, mContext.applicationContext.packageName.toString() + ".provider", file)
shareIntent.type = "image/png"
shareIntent.putExtra(Intent.EXTRA_STREAM, uri)
startActivity(Intent.createChooser(shareIntent, "Share pdf using"))
} catch (e: Exception) {
e.printStackTrace()
(mContext as DashboardActivity).showSnackMessage(getString(R.string.something_went_wrong1))
}
}
} catch (ex: Exception) {
ex.printStackTrace()
(mContext as DashboardActivity).showSnackMessage(getString(R.string.something_went_wrong))
}
}
private fun syncShop(billing: BillingEntity, shop: AddShopDBModelEntity) {
val addShopData = AddShopRequestData()
//if (!shop.isUploaded) {
addShopData.session_token = Pref.session_token
addShopData.address = shop.address
addShopData.owner_contact_no = shop.ownerContactNumber
addShopData.owner_email = shop.ownerEmailId
addShopData.owner_name = shop.ownerName
addShopData.pin_code = shop.pinCode
addShopData.shop_lat = shop.shopLat.toString()
addShopData.shop_long = shop.shopLong.toString()
addShopData.shop_name = shop.shopName.toString()
addShopData.type = shop.type.toString()
addShopData.shop_id = shop.shop_id
addShopData.user_id = Pref.user_id
if (!TextUtils.isEmpty(shop.dateOfBirth))
addShopData.dob = AppUtils.changeAttendanceDateFormatToCurrent(shop.dateOfBirth)
if (!TextUtils.isEmpty(shop.dateOfAniversary))
addShopData.date_aniversary = AppUtils.changeAttendanceDateFormatToCurrent(shop.dateOfAniversary)
addShopData.assigned_to_dd_id = shop.assigned_to_dd_id
addShopData.assigned_to_pp_id = shop.assigned_to_pp_id
addShopData.added_date = shop.added_date
addShopData.amount = shop.amount
addShopData.area_id = shop.area_id
addShopData.model_id = shop.model_id
addShopData.primary_app_id = shop.primary_app_id
addShopData.secondary_app_id = shop.secondary_app_id
addShopData.lead_id = shop.lead_id
addShopData.stage_id = shop.stage_id
addShopData.funnel_stage_id = shop.funnel_stage_id
addShopData.booking_amount = shop.booking_amount
addShopData.type_id = shop.type_id
addShopData.director_name = shop.director_name
addShopData.key_person_name = shop.person_name
addShopData.phone_no = shop.person_no
if (!TextUtils.isEmpty(shop.family_member_dob))
addShopData.family_member_dob = AppUtils.changeAttendanceDateFormatToCurrent(shop.family_member_dob)
if (!TextUtils.isEmpty(shop.add_dob))
addShopData.addtional_dob = AppUtils.changeAttendanceDateFormatToCurrent(shop.add_dob)
if (!TextUtils.isEmpty(shop.add_doa))
addShopData.addtional_doa = AppUtils.changeAttendanceDateFormatToCurrent(shop.add_doa)
addShopData.specialization = shop.specialization
addShopData.category = shop.category
addShopData.doc_address = shop.doc_address
addShopData.doc_pincode = shop.doc_pincode
addShopData.is_chamber_same_headquarter = shop.chamber_status.toString()
addShopData.is_chamber_same_headquarter_remarks = shop.remarks
addShopData.chemist_name = shop.chemist_name
addShopData.chemist_address = shop.chemist_address
addShopData.chemist_pincode = shop.chemist_pincode
addShopData.assistant_contact_no = shop.assistant_no
addShopData.average_patient_per_day = shop.patient_count
addShopData.assistant_name = shop.assistant_name
if (!TextUtils.isEmpty(shop.doc_family_dob))
addShopData.doc_family_member_dob = AppUtils.changeAttendanceDateFormatToCurrent(shop.doc_family_dob)
if (!TextUtils.isEmpty(shop.assistant_dob))
addShopData.assistant_dob = AppUtils.changeAttendanceDateFormatToCurrent(shop.assistant_dob)
if (!TextUtils.isEmpty(shop.assistant_doa))
addShopData.assistant_doa = AppUtils.changeAttendanceDateFormatToCurrent(shop.assistant_doa)
if (!TextUtils.isEmpty(shop.assistant_family_dob))
addShopData.assistant_family_dob = AppUtils.changeAttendanceDateFormatToCurrent(shop.assistant_family_dob)
addShopData.entity_id = shop.entity_id
addShopData.party_status_id = shop.party_status_id
addShopData.retailer_id = shop.retailer_id
addShopData.dealer_id = shop.dealer_id
addShopData.beat_id = shop.beat_id
addShopData.assigned_to_shop_id = shop.assigned_to_shop_id
addShopData.actual_address = shop.actual_address
var uniqKeyObj = AppDatabase.getDBInstance()!!.shopActivityDao().getNewShopActivityKey(shop.shop_id, false)
addShopData.shop_revisit_uniqKey = uniqKeyObj?.shop_revisit_uniqKey!!
// duplicate shop api call
addShopData.isShopDuplicate=shop.isShopDuplicate
callAddShopApi(addShopData, shop.shopImageLocalPath, shop.doc_degree, billing)
//}
}
private fun callAddShopApi(addShop: AddShopRequestData, shop_imgPath: String?, degree_imgPath: String?, billing: BillingEntity) {
if (BaseActivity.isApiInitiated)
return
BaseActivity.isApiInitiated = true
progress_wheel.spin()
Timber.d("=======SyncShop Input Params (Add Billing)=============")
Timber.d("shop id=======> " + addShop.shop_id)
val index = addShop.shop_id!!.indexOf("_")
Timber.d("decoded shop id=======> " + addShop.user_id + "_" + AppUtils.getDate(addShop.shop_id!!.substring(index + 1, addShop.shop_id!!.length).toLong()))
Timber.d("shop added date=======> " + addShop.added_date)
Timber.d("shop address=======> " + addShop.address)
Timber.d("assigned to dd id=======> " + addShop.assigned_to_dd_id)
Timber.d("assigned to pp id=======> " + addShop.assigned_to_pp_id)
Timber.d("date aniversery=======> " + addShop.date_aniversary)
Timber.d("dob=======> " + addShop.dob)
Timber.d("shop owner phn no=======> " + addShop.owner_contact_no)
Timber.d("shop owner email=======> " + addShop.owner_email)
Timber.d("shop owner name=======> " + addShop.owner_name)
Timber.d("shop pincode=======> " + addShop.pin_code)
Timber.d("session token=======> " + addShop.session_token)
Timber.d("shop lat=======> " + addShop.shop_lat)
Timber.d("shop long=======> " + addShop.shop_long)
Timber.d("shop name=======> " + addShop.shop_name)
Timber.d("shop type=======> " + addShop.type)
Timber.d("user id=======> " + addShop.user_id)
Timber.d("amount=======> " + addShop.amount)
Timber.d("area id=======> " + addShop.area_id)
Timber.d("model id=======> " + addShop.model_id)
Timber.d("primary app id=======> " + addShop.primary_app_id)
Timber.d("secondary app id=======> " + addShop.secondary_app_id)
Timber.d("lead id=======> " + addShop.lead_id)
Timber.d("stage id=======> " + addShop.stage_id)
Timber.d("funnel stage id=======> " + addShop.funnel_stage_id)
Timber.d("booking amount=======> " + addShop.booking_amount)
Timber.d("type id=======> " + addShop.type_id)
if (shop_imgPath != null)
Timber.d("shop image path=======> $shop_imgPath")
Timber.d("director name=======> " + addShop.director_name)
Timber.d("family member dob=======> " + addShop.family_member_dob)
Timber.d("key person's name=======> " + addShop.key_person_name)
Timber.d("phone no=======> " + addShop.phone_no)
Timber.d("additional dob=======> " + addShop.addtional_dob)
Timber.d("additional doa=======> " + addShop.addtional_doa)
Timber.d("doctor family member dob=======> " + addShop.doc_family_member_dob)
Timber.d("specialization=======> " + addShop.specialization)
Timber.d("average patient count per day=======> " + addShop.average_patient_per_day)
Timber.d("category=======> " + addShop.category)
Timber.d("doctor address=======> " + addShop.doc_address)
Timber.d("doctor pincode=======> " + addShop.doc_pincode)
Timber.d("chambers or hospital under same headquarter=======> " + addShop.is_chamber_same_headquarter)
Timber.d("chamber related remarks=======> " + addShop.is_chamber_same_headquarter_remarks)
Timber.d("chemist name=======> " + addShop.chemist_name)
Timber.d("chemist name=======> " + addShop.chemist_address)
Timber.d("chemist pincode=======> " + addShop.chemist_pincode)
Timber.d("assistant name=======> " + addShop.assistant_name)
Timber.d("assistant contact no=======> " + addShop.assistant_contact_no)
Timber.d("assistant dob=======> " + addShop.assistant_dob)
Timber.d("assistant date of anniversary=======> " + addShop.assistant_doa)
Timber.d("assistant family dob=======> " + addShop.assistant_family_dob)
Timber.d("entity id=======> " + addShop.entity_id)
Timber.d("party status id=======> " + addShop.party_status_id)
Timber.d("retailer id=======> " + addShop.retailer_id)
Timber.d("dealer id=======> " + addShop.dealer_id)
Timber.d("beat id=======> " + addShop.beat_id)
Timber.d("assigned to shop id=======> " + addShop.assigned_to_shop_id)
Timber.d("actual address=======> " + addShop.actual_address)
if (degree_imgPath != null)
Timber.d("doctor degree image path=======> $degree_imgPath")
Timber.d("======================================================")
if (TextUtils.isEmpty(shop_imgPath) && TextUtils.isEmpty(degree_imgPath)) {
val repository = AddShopRepositoryProvider.provideAddShopWithoutImageRepository()
BaseActivity.compositeDisposable.add(
repository.addShop(addShop)
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe({ result ->
val addShopResult = result as AddShopResponse
Timber.d("syncShopFromShopList : " + ", SHOP: " + addShop.shop_name + ", RESPONSE:" + result.message)
if (addShopResult.status == NetworkConstant.SUCCESS) {
AppDatabase.getDBInstance()!!.addShopEntryDao().updateIsUploaded(true, addShop.shop_id)
doAsync {
val resultAs = runLongTask(addShop.shop_id)
uiThread {
if (resultAs == true) {
BaseActivity.isApiInitiated = false
getAssignedPPListApi(addShop.shop_id, billing)
}
}
}
progress_wheel.stopSpinning()
} else if (addShopResult.status == NetworkConstant.DUPLICATE_SHOP_ID) {
Timber.d("DuplicateShop : " + ", SHOP: " + addShop.shop_name)
AppDatabase.getDBInstance()!!.addShopEntryDao().updateIsUploaded(true, addShop.shop_id)
progress_wheel.stopSpinning()
//(mContext as DashboardActivity).showSnackMessage(addShopResult.message!!)
if (AppDatabase.getDBInstance()!!.addShopEntryDao().getDuplicateShopData(addShop.owner_contact_no).size > 0) {
AppDatabase.getDBInstance()!!.addShopEntryDao().deleteShopById(addShop.shop_id)
AppDatabase.getDBInstance()!!.shopActivityDao().deleteShopByIdAndDate(addShop.shop_id!!, AppUtils.getCurrentDateForShopActi())
}
doAsync {
val resultAs = runLongTask(addShop.shop_id)
uiThread {
if (resultAs == true) {
BaseActivity.isApiInitiated = false
getAssignedPPListApi(addShop.shop_id, billing)
}
}
}
} else {
BaseActivity.isApiInitiated = false
progress_wheel.stopSpinning()
(mContext as DashboardActivity).showSnackMessage(getString(R.string.unable_to_sync))
}
}, { error ->
error.printStackTrace()
BaseActivity.isApiInitiated = false
progress_wheel.stopSpinning()
if (error != null)
Timber.d("syncShopFromShopList : " + ", SHOP: " + addShop.shop_name + error.localizedMessage)
(mContext as DashboardActivity).showSnackMessage(getString(R.string.unable_to_sync))
})
)
} else {
val repository = AddShopRepositoryProvider.provideAddShopRepository()
BaseActivity.compositeDisposable.add(
repository.addShopWithImage(addShop, shop_imgPath, degree_imgPath, mContext)
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe({ result ->
val addShopResult = result as AddShopResponse
Timber.d("syncShopFromShopList : " + ", SHOP: " + addShop.shop_name + ", RESPONSE:" + result.message)
if (addShopResult.status == NetworkConstant.SUCCESS) {
AppDatabase.getDBInstance()!!.addShopEntryDao().updateIsUploaded(true, addShop.shop_id)
doAsync {
val resultAs = runLongTask(addShop.shop_id)
uiThread {
if (resultAs == true) {
BaseActivity.isApiInitiated = false
getAssignedPPListApi(addShop.shop_id, billing)
}
}
}
progress_wheel.stopSpinning()
} else if (addShopResult.status == NetworkConstant.DUPLICATE_SHOP_ID) {
Timber.d("DuplicateShop : " + ", SHOP: " + addShop.shop_name)
AppDatabase.getDBInstance()!!.addShopEntryDao().updateIsUploaded(true, addShop.shop_id)
progress_wheel.stopSpinning()
//(mContext as DashboardActivity).showSnackMessage(addShopResult.message!!)
if (AppDatabase.getDBInstance()!!.addShopEntryDao().getDuplicateShopData(addShop.owner_contact_no).size > 0) {
AppDatabase.getDBInstance()!!.addShopEntryDao().deleteShopById(addShop.shop_id)
AppDatabase.getDBInstance()!!.shopActivityDao().deleteShopByIdAndDate(addShop.shop_id!!, AppUtils.getCurrentDateForShopActi())
}
doAsync {
val resultAs = runLongTask(addShop.shop_id)
uiThread {
if (resultAs == true) {
BaseActivity.isApiInitiated = false
getAssignedPPListApi(addShop.shop_id, billing)
}
}
}
} else {
BaseActivity.isApiInitiated = false
progress_wheel.stopSpinning()
(mContext as DashboardActivity).showSnackMessage(getString(R.string.unable_to_sync))
}
}, { error ->
error.printStackTrace()
BaseActivity.isApiInitiated = false
progress_wheel.stopSpinning()
if (error != null)
Timber.d("syncShopFromShopList : " + ", SHOP: " + addShop.shop_name + error.localizedMessage)
(mContext as DashboardActivity).showSnackMessage(getString(R.string.unable_to_sync))
})
)
}
}
private fun runLongTask(shop_id: String?): Any {
val shopActivity = AppDatabase.getDBInstance()!!.shopActivityDao().durationAvailableForShop(shop_id!!, true, false)
if (shopActivity != null)
callShopActivitySubmit(shop_id)
return true
}
private var shop_duration = ""
private var startTimeStamp = ""
private fun callShopActivitySubmit(shopId: String) {
var list = AppDatabase.getDBInstance()!!.shopActivityDao().getShopForDay(shopId, AppUtils.getCurrentDateForShopActi())
if (list.isEmpty())
return
var shopDataList: MutableList<ShopDurationRequestData> = java.util.ArrayList()
var shopDurationApiReq = ShopDurationRequest()
shopDurationApiReq.user_id = Pref.user_id
shopDurationApiReq.session_token = Pref.session_token
if (!Pref.isMultipleVisitEnable) {
var shopActivity = list[0]
var shopDurationData = ShopDurationRequestData()
shopDurationData.shop_id = shopActivity.shopid
if (shopActivity.startTimeStamp != "0" && !shopActivity.isDurationCalculated) {
val totalMinute = AppUtils.getMinuteFromTimeStamp(shopActivity.startTimeStamp, System.currentTimeMillis().toString())
val duration = AppUtils.getTimeFromTimeSpan(shopActivity.startTimeStamp, System.currentTimeMillis().toString())
AppDatabase.getDBInstance()!!.shopActivityDao().updateTotalMinuteForDayOfShop(shopActivity.shopid!!, totalMinute, AppUtils.getCurrentDateForShopActi())
AppDatabase.getDBInstance()!!.shopActivityDao().updateTimeDurationForDayOfShop(shopActivity.shopid!!, duration, AppUtils.getCurrentDateForShopActi())
shopDurationData.spent_duration = duration
} else {
shopDurationData.spent_duration = shopActivity.duration_spent
}
shopDurationData.visited_date = shopActivity.visited_date
shopDurationData.visited_time = shopActivity.visited_date
if (TextUtils.isEmpty(shopActivity.distance_travelled))
shopActivity.distance_travelled = "0.0"
shopDurationData.distance_travelled = shopActivity.distance_travelled
var sList = AppDatabase.getDBInstance()!!.addShopEntryDao().getShopByIdList(shopDurationData.shop_id)
if (sList != null && sList.isNotEmpty())
shopDurationData.total_visit_count = sList[0].totalVisitCount
if (!TextUtils.isEmpty(shopActivity.feedback))
shopDurationData.feedback = shopActivity.feedback
else
shopDurationData.feedback = ""
shopDurationData.isFirstShopVisited = shopActivity.isFirstShopVisited
shopDurationData.distanceFromHomeLoc = shopActivity.distance_from_home_loc
shopDurationData.next_visit_date = shopActivity.next_visit_date
if (!TextUtils.isEmpty(shopActivity.early_revisit_reason))
shopDurationData.early_revisit_reason = shopActivity.early_revisit_reason
else
shopDurationData.early_revisit_reason = ""
shopDurationData.device_model = shopActivity.device_model
shopDurationData.android_version = shopActivity.android_version
shopDurationData.battery = shopActivity.battery
shopDurationData.net_status = shopActivity.net_status
shopDurationData.net_type = shopActivity.net_type
shopDurationData.in_time = shopActivity.in_time
shopDurationData.out_time = shopActivity.out_time
shopDurationData.start_timestamp = shopActivity.startTimeStamp
shopDurationData.in_location = shopActivity.in_loc
shopDurationData.out_location = shopActivity.out_loc
shopDurationData.shop_revisit_uniqKey = shopActivity.shop_revisit_uniqKey!!
/*10-12-2021*/
shopDurationData.updated_by = Pref.user_id
try {
shopDurationData.updated_on = shopActivity.updated_on!!
} catch (ex: Exception) {
shopDurationData.updated_on = ""
}
if (!TextUtils.isEmpty(shopActivity.pros_id!!))
shopDurationData.pros_id = shopActivity.pros_id!!
else
shopDurationData.pros_id = ""
if (!TextUtils.isEmpty(shopActivity.agency_name!!))
shopDurationData.agency_name = shopActivity.agency_name!!
else
shopDurationData.agency_name = ""
if (!TextUtils.isEmpty(shopActivity.approximate_1st_billing_value))
shopDurationData.approximate_1st_billing_value = shopActivity.approximate_1st_billing_value!!
else
shopDurationData.approximate_1st_billing_value = ""
//duration garbage fix
try{
if(shopDurationData.spent_duration!!.contains("-") || shopDurationData.spent_duration!!.length != 8)
{
shopDurationData.spent_duration="00:00:10"
}
}catch (ex:Exception){
shopDurationData.spent_duration="00:00:10"
}
// Suman 06-05-2024 Suman SyncActivity update mantis 27335 begin
try {
var shopOb = AppDatabase.getDBInstance()!!.addShopEntryDao().getShopByIdN(shopDurationData.shop_id)
shopDurationData.shop_lat=shopOb.shopLat.toString()
shopDurationData.shop_long=shopOb.shopLong.toString()
shopDurationData.shop_addr=shopOb.address.toString()
}catch (ex:Exception){
ex.printStackTrace()
}
// Suman 06-05-2024 Suman SyncActivity update mantis 27335 end
shopDataList.add(shopDurationData)
} else {
for (i in list.indices) {
var shopActivity = list[i]
var shopDurationData = ShopDurationRequestData()
shopDurationData.shop_id = shopActivity.shopid
if (shopActivity.startTimeStamp != "0" && !shopActivity.isDurationCalculated) {
val totalMinute = AppUtils.getMinuteFromTimeStamp(shopActivity.startTimeStamp, System.currentTimeMillis().toString())
val duration = AppUtils.getTimeFromTimeSpan(shopActivity.startTimeStamp, System.currentTimeMillis().toString())
AppDatabase.getDBInstance()!!.shopActivityDao().updateTotalMinuteForDayOfShop(shopActivity.shopid!!, totalMinute, AppUtils.getCurrentDateForShopActi(), shopActivity.startTimeStamp)
AppDatabase.getDBInstance()!!.shopActivityDao().updateTimeDurationForDayOfShop(shopActivity.shopid!!, duration, AppUtils.getCurrentDateForShopActi(), shopActivity.startTimeStamp)
shopDurationData.spent_duration = duration
} else {
shopDurationData.spent_duration = shopActivity.duration_spent
}
shopDurationData.visited_date = shopActivity.visited_date
shopDurationData.visited_time = shopActivity.visited_date
if (TextUtils.isEmpty(shopActivity.distance_travelled))
shopActivity.distance_travelled = "0.0"
shopDurationData.distance_travelled = shopActivity.distance_travelled
var sList = AppDatabase.getDBInstance()!!.addShopEntryDao().getShopByIdList(shopDurationData.shop_id)
if (sList != null && sList.isNotEmpty())
shopDurationData.total_visit_count = sList[0].totalVisitCount
if (!TextUtils.isEmpty(shopActivity.feedback))
shopDurationData.feedback = shopActivity.feedback
else
shopDurationData.feedback = ""
shopDurationData.isFirstShopVisited = shopActivity.isFirstShopVisited
shopDurationData.distanceFromHomeLoc = shopActivity.distance_from_home_loc
shopDurationData.next_visit_date = shopActivity.next_visit_date
if (!TextUtils.isEmpty(shopActivity.early_revisit_reason))
shopDurationData.early_revisit_reason = shopActivity.early_revisit_reason
else
shopDurationData.early_revisit_reason = ""
shopDurationData.device_model = shopActivity.device_model
shopDurationData.android_version = shopActivity.android_version
shopDurationData.battery = shopActivity.battery
shopDurationData.net_status = shopActivity.net_status
shopDurationData.net_type = shopActivity.net_type
shopDurationData.in_time = shopActivity.in_time
shopDurationData.out_time = shopActivity.out_time
shopDurationData.start_timestamp = shopActivity.startTimeStamp
shopDurationData.in_location = shopActivity.in_loc
shopDurationData.out_location = shopActivity.out_loc
shopDurationData.shop_revisit_uniqKey = shopActivity.shop_revisit_uniqKey!!
/*10-12-2021*/
shopDurationData.updated_by = Pref.user_id
try {
shopDurationData.updated_on = shopActivity.updated_on!!
} catch (Ex: Exception) {
shopDurationData.updated_on = ""
}
if (!TextUtils.isEmpty(shopActivity.pros_id!!))
shopDurationData.pros_id = shopActivity.pros_id!!
else
shopDurationData.pros_id = ""
if (!TextUtils.isEmpty(shopActivity.agency_name!!))
shopDurationData.agency_name = shopActivity.agency_name!!
else
shopDurationData.agency_name = ""
if (!TextUtils.isEmpty(shopActivity.approximate_1st_billing_value))
shopDurationData.approximate_1st_billing_value = shopActivity.approximate_1st_billing_value!!
else
shopDurationData.approximate_1st_billing_value = ""
//duration garbage fix
try{
if(shopDurationData.spent_duration!!.contains("-") || shopDurationData.spent_duration!!.length != 8)
{
shopDurationData.spent_duration="00:00:10"
}
}catch (ex:Exception){
shopDurationData.spent_duration="00:00:10"
}
//New shop Create issue
shopDurationData.isnewShop = shopActivity.isnewShop!!
// 1.0 BillingFragment AppV 4.0.6 multiple contact Data added on Api called
shopDurationData.multi_contact_name = shopActivity.multi_contact_name
shopDurationData.multi_contact_number = shopActivity.multi_contact_number
// Suman 06-05-2024 Suman SyncActivity update mantis 27335 begin
try {
var shopOb = AppDatabase.getDBInstance()!!.addShopEntryDao().getShopByIdN(shopDurationData.shop_id)
shopDurationData.shop_lat=shopOb.shopLat.toString()
shopDurationData.shop_long=shopOb.shopLong.toString()
shopDurationData.shop_addr=shopOb.address.toString()
}catch (ex:Exception){
ex.printStackTrace()
}
// Suman 06-05-2024 Suman SyncActivity update mantis 27335 end
shopDataList.add(shopDurationData)
}
}
if (shopDataList.isEmpty()) {
return
}
shopDurationApiReq.shop_list = shopDataList
val repository = ShopDurationRepositoryProvider.provideShopDurationRepository()
BaseActivity.compositeDisposable.add(
repository.shopDuration(shopDurationApiReq)
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe({ result ->
Timber.d("syncShopActivityFromShopList : " + ", SHOP: " + list[0].shop_name + ", RESPONSE:" + result.message)
if (result.status == NetworkConstant.SUCCESS) {
}
}, { error ->
error.printStackTrace()
if (error != null)
Timber.d("syncShopActivityFromShopList : " + ", SHOP: " + list[0].shop_name + error.localizedMessage)
// (mContext as DashboardActivity).showSnackMessage("ERROR")
})
)
}
private fun getAssignedPPListApi(shop_id: String?, billing: BillingEntity) {
val shopActivityList = AppDatabase.getDBInstance()!!.shopActivityDao().getShopForDay(shop_id!!, AppUtils.getCurrentDateForShopActi())
/*if (shopActivityList[0].isVisited && shopActivityList[0].isDurationCalculated) {
if (!Pref.isMultipleVisitEnable)
AppDatabase.getDBInstance()!!.shopActivityDao().updateisUploaded(true, shop_id, AppUtils.getCurrentDateForShopActi())
else
AppDatabase.getDBInstance()!!.shopActivityDao().updateisUploaded(true, shop_id, AppUtils.getCurrentDateForShopActi(), startTimeStamp)
Timber.d("============sync locally shop visited (Add Billing)==========")
}*/
shopActivityList?.forEach {
if (it.isVisited && it.isDurationCalculated) {
if (!Pref.isMultipleVisitEnable)
AppDatabase.getDBInstance()!!.shopActivityDao().updateisUploaded(true, shop_id, AppUtils.getCurrentDateForShopActi())
else
AppDatabase.getDBInstance()!!.shopActivityDao().updateisUploaded(true, shop_id, AppUtils.getCurrentDateForShopActi(), startTimeStamp)
Timber.d("============sync locally shop visited (Billing List)==========")
}
}
if (BaseActivity.isApiInitiated)
return
BaseActivity.isApiInitiated = true
val repository = AssignToPPListRepoProvider.provideAssignPPListRepository()
progress_wheel.spin()
BaseActivity.compositeDisposable.add(
repository.assignToPPList(Pref.profile_state)
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe({ result ->
val response = result as AssignToPPListResponseModel
if (response.status == NetworkConstant.SUCCESS) {
val list = response.assigned_to_pp_list
if (list != null && list.isNotEmpty()) {
doAsync {
val assignPPList = AppDatabase.getDBInstance()?.ppListDao()?.getAll()
if (assignPPList != null)
AppDatabase.getDBInstance()?.ppListDao()?.delete()
for (i in list.indices) {
val assignToPP = AssignToPPEntity()
assignToPP.pp_id = list[i].assigned_to_pp_id
assignToPP.pp_name = list[i].assigned_to_pp_authorizer_name
assignToPP.pp_phn_no = list[i].phn_no
AppDatabase.getDBInstance()?.ppListDao()?.insert(assignToPP)
}
uiThread {
BaseActivity.isApiInitiated = false
progress_wheel.stopSpinning()
getAssignedDDListApi(shop_id, billing)
}
}
} else {
BaseActivity.isApiInitiated = false
progress_wheel.stopSpinning()
getAssignedDDListApi(shop_id, billing)
}
} else {
BaseActivity.isApiInitiated = false
progress_wheel.stopSpinning()
getAssignedDDListApi(shop_id, billing)
}
}, { error ->
error.printStackTrace()
BaseActivity.isApiInitiated = false
progress_wheel.stopSpinning()
getAssignedDDListApi(shop_id, billing)
})
)
}
private fun getAssignedDDListApi(shop_id: String?, billing: BillingEntity) {
if (BaseActivity.isApiInitiated)
return
BaseActivity.isApiInitiated = true
val repository = AssignToDDListRepoProvider.provideAssignDDListRepository()
progress_wheel.spin()
BaseActivity.compositeDisposable.add(
repository.assignToDDList(Pref.profile_state)
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe({ result ->
val response = result as AssignToDDListResponseModel
if (response.status == NetworkConstant.SUCCESS) {
val list = response.assigned_to_dd_list
if (list != null && list.isNotEmpty()) {
doAsync {
val assignDDList = AppDatabase.getDBInstance()?.ddListDao()?.getAll()
if (assignDDList != null)
AppDatabase.getDBInstance()?.ddListDao()?.delete()
for (i in list.indices) {
val assignToDD = AssignToDDEntity()
assignToDD.dd_id = list[i].assigned_to_dd_id
assignToDD.dd_name = list[i].assigned_to_dd_authorizer_name
assignToDD.dd_phn_no = list[i].phn_no
assignToDD.pp_id = list[i].assigned_to_pp_id
assignToDD.type_id = list[i].type_id
assignToDD.dd_latitude = list[i].dd_latitude
assignToDD.dd_longitude = list[i].dd_longitude
AppDatabase.getDBInstance()?.ddListDao()?.insert(assignToDD)
}
uiThread {
BaseActivity.isApiInitiated = false
progress_wheel.stopSpinning()
getAssignedToShopApi(shop_id, billing)
}
}
} else {
BaseActivity.isApiInitiated = false
progress_wheel.stopSpinning()
getAssignedToShopApi(shop_id, billing)
}
} else {
BaseActivity.isApiInitiated = false
progress_wheel.stopSpinning()
getAssignedToShopApi(shop_id, billing)
}
}, { error ->
error.printStackTrace()
BaseActivity.isApiInitiated = false
progress_wheel.stopSpinning()
getAssignedToShopApi(shop_id, billing)
})
)
}
private fun getAssignedToShopApi(shop_id: String?, billing: BillingEntity) {
if (BaseActivity.isApiInitiated)
return
BaseActivity.isApiInitiated = true
val repository = TypeListRepoProvider.provideTypeListRepository()
progress_wheel.spin()
BaseActivity.compositeDisposable.add(
repository.assignToShopList(Pref.profile_state)
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe({ result ->
val response = result as AssignedToShopListResponseModel
if (response.status == NetworkConstant.SUCCESS) {
val list = response.shop_list
AppDatabase.getDBInstance()?.assignToShopDao()?.delete()
doAsync {
list?.forEach {
val shop = AssignToShopEntity()
AppDatabase.getDBInstance()?.assignToShopDao()?.insert(shop.apply {
assigned_to_shop_id = it.assigned_to_shop_id
name = it.name
phn_no = it.phn_no
type_id = it.type_id
})
}
uiThread {
progress_wheel.stopSpinning()
BaseActivity.isApiInitiated = false
checkToCallOrderApi(billing)
}
}
} else {
progress_wheel.stopSpinning()
BaseActivity.isApiInitiated = false
checkToCallOrderApi(billing)
}
}, { error ->
progress_wheel.stopSpinning()
error.printStackTrace()
BaseActivity.isApiInitiated = false
checkToCallOrderApi(billing)
})
)
}
private fun checkToCallOrderApi(billing: BillingEntity) {
if (!order?.isUploaded!!) {
syncAddOrderApi(order?.shop_id, order?.order_id, order?.amount!!, order?.date!!, order?.remarks, order?.signature, order?.order_lat,
order?.order_long, billing, order)
} else {
callAddBillApi(billing)
}
}
private fun syncAddOrderApi(shop_id: String?, order_id: String?, amount: String, date: String, remarks: String?, signature: String?,
orderLat: String?, orderLong: String?, billing: BillingEntity, orderListDetails: OrderDetailsListEntity?) {
if (BaseActivity.isApiInitiated)
return
BaseActivity.isApiInitiated = true
val addOrder = AddOrderInputParamsModel()
addOrder.collection = ""
addOrder.description = ""
addOrder.order_amount = amount
addOrder.order_date = date //AppUtils.getCurrentDateFormatInTa(date)
addOrder.order_id = order_id
addOrder.shop_id = shop_id
addOrder.session_token = Pref.session_token
addOrder.user_id = Pref.user_id
addOrder.latitude = orderLat
addOrder.longitude = orderLong
if (orderListDetails!!.scheme_amount != null)
addOrder.scheme_amount = orderListDetails!!.scheme_amount
else
addOrder.scheme_amount = ""
if (remarks != null)
addOrder.remarks = remarks
else
addOrder.remarks = ""
if (orderListDetails?.patient_name != null)
addOrder.patient_name = orderListDetails.patient_name
else
addOrder.patient_name = ""
if (orderListDetails?.patient_address != null)
addOrder.patient_address = orderListDetails.patient_address
else
addOrder.patient_address = ""
if (orderListDetails?.patient_no != null)
addOrder.patient_no = orderListDetails.patient_no
else
addOrder.patient_no = ""
val shopActivity = AppDatabase.getDBInstance()!!.shopActivityDao().getShopActivityForId(shop_id!!)
if (shopActivity != null) {
if (shopActivity.isVisited && !shopActivity.isDurationCalculated && shopActivity.date == AppUtils.getCurrentDateForShopActi()) {
val shopDetail = AppDatabase.getDBInstance()!!.addShopEntryDao().getShopByIdN(shop_id)
if (!TextUtils.isEmpty(shopDetail.address))
addOrder.address = shopDetail.address
else
addOrder.address = ""
} else {
if (!TextUtils.isEmpty(orderLat) && !TextUtils.isEmpty(orderLong))
addOrder.address = LocationWizard.getLocationName(mContext, orderLat!!.toDouble(), orderLong!!.toDouble())
else
addOrder.address = ""
}
} else {
if (!TextUtils.isEmpty(orderLat) && !TextUtils.isEmpty(orderLong))
addOrder.address = LocationWizard.getLocationName(mContext, orderLat!!.toDouble(), orderLong!!.toDouble())
else
addOrder.address = ""
}
/*06-01-2022*/
if (orderListDetails?.Hospital != null)
addOrder.Hospital = orderListDetails?.Hospital
else
addOrder.Hospital = ""
if (orderListDetails?.Email_Address != null)
addOrder.Email_Address = orderListDetails?.Email_Address
else
addOrder.Email_Address = ""
val list = AppDatabase.getDBInstance()!!.orderProductListDao().getDataAccordingToShopAndOrderId(order_id!!, shop_id!!)
val productList = java.util.ArrayList<AddOrderInputProductList>()
for (i in list.indices) {
val product = AddOrderInputProductList()
product.id = list[i].product_id
product.qty = list[i].qty
product.rate = list[i].rate
product.total_price = list[i].total_price
product.product_name = list[i].product_name
product.scheme_qty = list[i].scheme_qty
product.scheme_rate = list[i].scheme_rate
product.total_scheme_price = list[i].total_scheme_price
product.MRP = list[i].MRP
//mantis 25601
product.order_mrp = list[i].order_mrp
product.order_discount = list[i].order_discount
productList.add(product)
}
addOrder.product_list = productList
progress_wheel.spin()
if (TextUtils.isEmpty(signature)) {
val repository = AddOrderRepoProvider.provideAddOrderRepository()
BaseActivity.compositeDisposable.add(
repository.addNewOrder(addOrder)
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe({ result ->
val orderList = result as BaseResponse
progress_wheel.stopSpinning()
BaseActivity.isApiInitiated = false
if (orderList.status == NetworkConstant.SUCCESS) {
AppDatabase.getDBInstance()!!.orderDetailsListDao().updateIsUploaded(true, order_id)
callAddBillApi(billing)
} else
(mContext as DashboardActivity).showSnackMessage(getString(R.string.unable_to_sync))
}, { error ->
error.printStackTrace()
BaseActivity.isApiInitiated = false
progress_wheel.stopSpinning()
(mContext as DashboardActivity).showSnackMessage(getString(R.string.unable_to_sync))
})
)
} else {
val repository = AddOrderRepoProvider.provideAddOrderImageRepository()
BaseActivity.compositeDisposable.add(
repository.addNewOrder(addOrder, signature!!, mContext)
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe({ result ->
val orderList = result as BaseResponse
progress_wheel.stopSpinning()
BaseActivity.isApiInitiated = false
if (orderList.status == NetworkConstant.SUCCESS) {
AppDatabase.getDBInstance()!!.orderDetailsListDao().updateIsUploaded(true, order_id)
callAddBillApi(billing)
} else
(mContext as DashboardActivity).showSnackMessage(getString(R.string.unable_to_sync))
}, { error ->
error.printStackTrace()
BaseActivity.isApiInitiated = false
progress_wheel.stopSpinning()
(mContext as DashboardActivity).showSnackMessage(getString(R.string.unable_to_sync))
})
)
}
}
private fun callAddBillApi(billing: BillingEntity) {
if (BaseActivity.isApiInitiated)
return
BaseActivity.isApiInitiated = true
val addBill = AddBillingInputParamsModel()
addBill.bill_id = billing.bill_id
addBill.invoice_amount = billing.invoice_amount
addBill.invoice_date = billing.invoice_date
addBill.invoice_no = billing.invoice_no
addBill.remarks = billing.remarks
addBill.order_id = billing.order_id
addBill.session_token = Pref.session_token!!
addBill.user_id = Pref.user_id!!
addBill.patient_no = billing.patient_no
addBill.patient_name = billing.patient_name
addBill.patient_address = billing.patient_address
val list = AppDatabase.getDBInstance()!!.billProductDao().getDataAccordingToBillId(addBill.bill_id)
val productList = ArrayList<AddOrderInputProductList>()
for (i in list.indices) {
val product = AddOrderInputProductList()
product.id = list[i].product_id
product.qty = list[i].qty
product.rate = list[i].rate
product.total_price = list[i].total_price
product.product_name = list[i].product_name
productList.add(product)
}
addBill.product_list = productList
Timber.d("======SYNC BILLING DETAILS INPUT PARAMS (BILLING LIST)======")
Timber.d("USER ID===> " + addBill.user_id)
Timber.d("SESSION ID====> " + addBill.session_token)
Timber.d("BILL ID====> " + addBill.bill_id)
Timber.d("INVOICE NO.====> " + addBill.invoice_no)
Timber.d("INVOICE DATE====> " + addBill.invoice_date)
Timber.d("INVOICE AMOUNT====> " + addBill.invoice_amount)
Timber.d("REMARKS====> " + addBill.remarks)
Timber.d("ORDER ID====> " + addBill.order_id)
try {
Timber.d("PATIENT NO====> " + addBill.patient_no)
Timber.d("PATIENT NAME====> " + addBill.patient_name)
Timber.d("PATIENT ADDRESS====> " + addBill.patient_address)
} catch (e: Exception) {
e.printStackTrace()
}
if (!TextUtils.isEmpty(billing.attachment))
Timber.d("ATTACHMENT=======> " + billing.attachment)
Timber.d("PRODUCT LIST SIZE====> " + addBill.product_list?.size)
Timber.d("==============================================================")
if (!TextUtils.isEmpty(billing.attachment)) {
val repository = AddBillingRepoProvider.addBillImageRepository()
progress_wheel.spin()
BaseActivity.compositeDisposable.add(
repository.addBillingDetailsMultipart(addBill, billing.attachment, mContext)
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe({ result ->
val baseResponse = result as BaseResponse
Timber.d("SYNC BILLING DETAILS : " + "RESPONSE : " + baseResponse.status + "\n" + "Time : " + AppUtils.getCurrentDateTime() + ", USER :" + Pref.user_name + ", MESSAGE : " + baseResponse.message)
BaseActivity.isApiInitiated = false
if (baseResponse.status == NetworkConstant.SUCCESS) {
AppDatabase.getDBInstance()!!.billingDao().updateIsUploadedBillingIdWise(true, addBill.bill_id)
updateItem()
(mContext as DashboardActivity).showSnackMessage(baseResponse.message!!)
} else
(mContext as DashboardActivity).showSnackMessage("Unable to sync billing")
progress_wheel.stopSpinning()
}, { error ->
Timber.d("SYNC BILLING DETAILS : " + "ERROR : " + "\n" + "Time : " + AppUtils.getCurrentDateTime() + ", USER :" + Pref.user_name + ", MESSAGE : " + error.localizedMessage)
error.printStackTrace()
BaseActivity.isApiInitiated = false
progress_wheel.stopSpinning()
(mContext as DashboardActivity).showSnackMessage("Unable to sync billing")
})
)
} else {
val repository = AddBillingRepoProvider.addBillRepository()
progress_wheel.spin()
BaseActivity.compositeDisposable.add(
repository.addBillingDetails(addBill)
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe({ result ->
val baseResponse = result as BaseResponse
Timber.d("SYNC BILLING DETAILS : " + "RESPONSE : " + baseResponse.status + "\n" + "Time : " + AppUtils.getCurrentDateTime() + ", USER :" + Pref.user_name + ", MESSAGE : " + baseResponse.message)
BaseActivity.isApiInitiated = false
if (baseResponse.status == NetworkConstant.SUCCESS) {
AppDatabase.getDBInstance()!!.billingDao().updateIsUploadedBillingIdWise(true, addBill.bill_id)
updateItem()
(mContext as DashboardActivity).showSnackMessage(baseResponse.message!!)
} else
(mContext as DashboardActivity).showSnackMessage("Unable to sync billing")
progress_wheel.stopSpinning()
}, { error ->
Timber.d("SYNC BILLING DETAILS : " + "ERROR : " + "\n" + "Time : " + AppUtils.getCurrentDateTime() + ", USER :" + Pref.user_name + ", MESSAGE : " + error.localizedMessage)
error.printStackTrace()
BaseActivity.isApiInitiated = false
progress_wheel.stopSpinning()
(mContext as DashboardActivity).showSnackMessage("Unable to sync billing")
})
)
}
}
override fun onClick(p0: View?) {
when (p0?.id) {
R.id.fab -> {
if (!Pref.isAddAttendence)
(context as DashboardActivity).checkToShowAddAttendanceAlert()
else
(mContext as DashboardActivity).loadFragment(FragType.AddBillingFragment, true, order!!)
}
}
}
fun updateItem() {
val list = AppDatabase.getDBInstance()!!.billingDao().getDataOrderIdWise(order?.order_id!!) as ArrayList
if (list != null && list.isNotEmpty())
initAdapter(list)
else {
tv_no_data_available.visibility = View.VISIBLE
}
}
} | 0 | null | 1 | 1 | a9aabcf48662c76db18bcece75cae9ac961da1ed | 78,857 | NationalPlastic | Apache License 2.0 |
app/src/main/java/com/kcteam/features/TA/ViewAllTAListFragment.kt | DebashisINT | 558,234,039 | false | null | package com.breezebppoddarhospital.features.TA
import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import com.google.android.material.floatingactionbutton.FloatingActionButton
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import com.breezebppoddarhospital.R
import com.breezebppoddarhospital.app.AppDatabase
import com.breezebppoddarhospital.app.domain.AddShopDBModelEntity
import com.breezebppoddarhospital.app.domain.ShopActivityEntity
import com.breezebppoddarhospital.app.domain.TaListDBModelEntity
import com.breezebppoddarhospital.app.domain.ViewAllOrderListEntity
import com.breezebppoddarhospital.app.utils.AppUtils
import com.breezebppoddarhospital.app.utils.ImagePickerManager
import com.breezebppoddarhospital.base.presentation.BaseFragment
import com.breezebppoddarhospital.features.TA.model.TaList
import com.breezebppoddarhospital.features.dashboard.presentation.DashboardActivity
import com.breezebppoddarhospital.features.nearbyshops.presentation.ShopAddressUpdateListener
import com.breezebppoddarhospital.widgets.AppCustomTextView
import com.github.jhonnyx2012.horizontalpicker.HorizontalPicker
import com.pnikosis.materialishprogress.ProgressWheel
import java.io.File
import java.util.*
/**
* Created by Pratishruti on 15-11-2017.
*/
class ViewAllTAListFragment : BaseFragment(), View.OnClickListener {
private var ViewAllTAListRecyclerViewAdapter: ViewAllTAListRecyclerViewAdapter? = null
private lateinit var order_list_rv: RecyclerView
private lateinit var layoutManager: RecyclerView.LayoutManager
private lateinit var myshop_name_TV: AppCustomTextView
private lateinit var myshop_address_TV: AppCustomTextView
private lateinit var order_amount_tv: AppCustomTextView
private lateinit var no_data_available_tv: AppCustomTextView
private lateinit var picker: HorizontalPicker
private lateinit var ViewAllOrderListEntityList: ArrayList<ViewAllOrderListEntity>
private lateinit var progress_wheel: ProgressWheel
private lateinit var add_ta_fb: FloatingActionButton
private lateinit var mTaDialog: Dialog
private lateinit var mAddTADialog: AddTADialog
private var dialogFragment: AddTADialog = AddTADialog(true)
var i: Int = 0
private var mTalist: ArrayList<TaList> = ArrayList()
private lateinit var mContext: Context
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
super.onCreateView(inflater, container, savedInstanceState)
val view = inflater.inflate(R.layout.fragment_view_all_ta_list, container, false)
initView(view)
return view
}
override fun onAttach(context: Context) {
super.onAttach(context)
mContext = context
}
companion object {
var mShopActivityEntity: ShopActivityEntity? = null
fun getInstance(objects: Any): ViewAllTAListFragment {
val mViewAllOrderListFragment = ViewAllTAListFragment()
if (objects is ShopActivityEntity) {
mShopActivityEntity = objects
}
return mViewAllOrderListFragment
}
}
private fun initView(view: View) {
add_ta_fb = view.findViewById(R.id.add_ta_fb)
order_list_rv = view.findViewById(R.id.order_list_rv)
ViewAllOrderListEntityList = ArrayList()
myshop_name_TV = view.findViewById(R.id.myshop_name_TV)
myshop_address_TV = view.findViewById(R.id.myshop_address_TV)
order_amount_tv = view.findViewById(R.id.order_amount_tv)
no_data_available_tv = view.findViewById(R.id.no_data_available_tv)
progress_wheel = view.findViewById(R.id.progress_wheel)
progress_wheel.stopSpinning()
val mTaList: TaList = TaList("2018-08-09", "2018-08-29", "10000", "na", "Approved")
mTalist?.add(mTaList)
val mTaList1: TaList = TaList("2018-08-09", "2018-08-29", "12000", "na", "Pending")
mTalist?.add(mTaList1)
val mTaList2: TaList = TaList("2018-08-09", "2018-08-29", "13000", "na", "Rejected")
mTalist?.add(mTaList2)
insertDataToDatabase(mTalist)
if (mShopActivityEntity != null) {
myshop_name_TV.setText(mShopActivityEntity?.shop_name)
myshop_address_TV.setText(mShopActivityEntity?.shop_address)
order_amount_tv.text = "Order Amount: ₹10,000"
}
//generateOrderListDate()
//initAdapter(ta_list)
add_ta_fb.setOnClickListener(this)
}
private fun generateOrderListDate() {
for (i in 0..9) {
var mViewAllOrderListEntity: ViewAllOrderListEntity = ViewAllOrderListEntity()
mViewAllOrderListEntity.amount = "1000"
mViewAllOrderListEntity.itemId = i
mViewAllOrderListEntity.date = "03-Sep-18"
ViewAllOrderListEntityList.add(mViewAllOrderListEntity)
}
}
private fun insertDataToDatabase(ta_list: ArrayList<TaList>) {
AppDatabase.getDBInstance()!!.taListDao().deleteAll()
var list: MutableList<TaListDBModelEntity> = ArrayList()
var shopObj = TaListDBModelEntity()
for (i in 0 until ta_list.size) {
shopObj.from_date = ta_list[i].fromDate
shopObj.to_date = ta_list[i].toDate
shopObj.amount = ta_list[i].amount
shopObj.description = ta_list[i].description
shopObj.status = ta_list[i].status
list.add(shopObj)
AppDatabase.getDBInstance()!!.taListDao().insert(shopObj)
}
initAdapter()
}
override fun onClick(p0: View?) {
i = 0
when (p0?.id) {
R.id.add_ta_fb -> {
AddTADialog(true)
}
}
}
private fun initAdapter() {
var mTaList: ArrayList<TaListDBModelEntity> = AppDatabase.getDBInstance()!!.taListDao().getAll() as ArrayList<TaListDBModelEntity>
Collections.sort(mTaList, byDate);
if (ViewAllTAListRecyclerViewAdapter == null) {
if (mTaList.size > 0)
ViewAllTAListRecyclerViewAdapter = ViewAllTAListRecyclerViewAdapter(mContext, mTaList, object : ViewAllTAListRecyclerViewAdapter.onScrollEndListener {
override fun onScrollEnd() {
}
}, object : ViewAllTAListRecyclerViewAdapter.onItemClickListener {
override fun onActionItemClick() {
AddTADialog(false)
}
})
else
no_data_available_tv.visibility = View.GONE
} else {
if (mTaList.size > 0)
ViewAllTAListRecyclerViewAdapter?.notifyAdapter(mTaList)
else
no_data_available_tv.visibility = View.GONE
}
layoutManager = LinearLayoutManager(mContext, LinearLayout.VERTICAL, false)
order_list_rv.layoutManager = layoutManager
order_list_rv.adapter = ViewAllTAListRecyclerViewAdapter
}
val byDate: Comparator<TaListDBModelEntity> = object : Comparator<TaListDBModelEntity> {
// internal var sdf = TaListDBModelEntity("yyyy,MM,dd")
override fun compare(p0: TaListDBModelEntity?, p1: TaListDBModelEntity?): Int {
return if (AppUtils.getDateFormat(p0?.from_date!!).getTime() > AppUtils.getDateFormat(p1?.from_date!!).getTime()) 1 else -1
}
}
private fun AddTADialog(action: Boolean): AddTADialog {
try {
dialogFragment = AddTADialog.getInstance(action, object : ShopAddressUpdateListener {
override fun onAddedDataSuccess() {
initAdapter()
}
override fun getDialogInstance(mdialog: Dialog?) {
mTaDialog = mdialog!!
}
override fun onUpdateClick(address: AddShopDBModelEntity?) {
(mContext as DashboardActivity).showSnackMessage("Order added successfully")
}
})
dialogFragment.show((mContext as DashboardActivity).supportFragmentManager, "AddOrderDialog")
} catch (e: Exception) {
}
return dialogFragment
}
fun showPickedFileFromGalleryFetch(data: Intent?) {
val filePath = ImagePickerManager.getImagePathFromData(data, mContext)
val file = File(filePath)
val strFileName: String = file.name
if (mTaDialog != null && mTaDialog.isShowing)
dialogFragment.showPickedFile(strFileName, filePath)
}
fun getCaptureImage(imG_URI: Uri) {
val file = File(imG_URI.path)
val strFileName: String = file.name
if (mTaDialog != null && mTaDialog.isShowing)
dialogFragment.showPickedFile(strFileName, imG_URI.path!!)
}
} | 0 | null | 1 | 1 | a9aabcf48662c76db18bcece75cae9ac961da1ed | 9,072 | NationalPlastic | Apache License 2.0 |
src/main/kotlin/demo/suspension/DemoSuspension2.kt | gdg-minsk | 793,403,177 | false | {"Kotlin": 29583} | package demo.suspension
import kotlin.coroutines.suspendCoroutine
suspend fun main() {
println("Before")
suspendCoroutine<Unit> {
println("Before too")
}
println("After")
} | 0 | Kotlin | 0 | 0 | 895d8c032205acfa3f23383a06afb9c140209db1 | 200 | coffe-code-kotlin-coroutines | Apache License 2.0 |
kotlin-native/backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/serialization/ProtoUtils.kt | JetBrains | 3,432,266 | false | {"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80} | /*
* Copyright 2010-2023 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.backend.konan.serialization
import org.jetbrains.kotlin.backend.common.serialization.IrLibraryFile
import org.jetbrains.kotlin.backend.common.serialization.IrSymbolDeserializer
import org.jetbrains.kotlin.backend.common.serialization.encodings.BinaryNameAndType
import org.jetbrains.kotlin.backend.common.serialization.encodings.BinarySymbolData
import org.jetbrains.kotlin.backend.common.serialization.encodings.FunctionFlags
import org.jetbrains.kotlin.ir.declarations.IrClass
import org.jetbrains.kotlin.ir.declarations.IrFunction
import org.jetbrains.kotlin.ir.declarations.IrProperty
import org.jetbrains.kotlin.ir.declarations.IrSimpleFunction
import org.jetbrains.kotlin.ir.util.render
import org.jetbrains.kotlin.backend.common.serialization.proto.IrClass as ProtoClass
import org.jetbrains.kotlin.backend.common.serialization.proto.IrDeclaration as ProtoDeclaration
import org.jetbrains.kotlin.backend.common.serialization.proto.IrFunction as ProtoFunction
import org.jetbrains.kotlin.backend.common.serialization.proto.IrProperty as ProtoProperty
internal fun ProtoClass.findClass(irClass: IrClass, fileReader: IrLibraryFile, symbolDeserializer: IrSymbolDeserializer): ProtoClass {
val signature = irClass.symbol.signature ?: error("No signature for ${irClass.render()}")
var result: ProtoClass? = null
for (i in 0 until this.declarationCount) {
val child = this.getDeclaration(i)
val childClass = when {
child.declaratorCase == ProtoDeclaration.DeclaratorCase.IR_CLASS -> child.irClass
child.declaratorCase == ProtoDeclaration.DeclaratorCase.IR_ENUM_ENTRY
&& child.irEnumEntry.hasCorrespondingClass() -> child.irEnumEntry.correspondingClass
else -> continue
}
val name = fileReader.string(childClass.name)
if (name == irClass.name.asString()) {
if (result == null)
result = childClass
else {
val resultIdSignature = symbolDeserializer.deserializeIdSignature(BinarySymbolData.decode(result.base.symbol).signatureId)
if (resultIdSignature == signature)
return result
result = childClass
}
}
}
return result ?: error("Class ${irClass.render()} is not found")
}
internal fun ProtoClass.findProperty(irProperty: IrProperty, fileReader: IrLibraryFile, symbolDeserializer: IrSymbolDeserializer): ProtoProperty {
val signature = irProperty.symbol.signature ?: error("No signature for ${irProperty.render()}")
var result: ProtoProperty? = null
for (i in 0 until this.declarationCount) {
val child = this.getDeclaration(i)
if (child.declaratorCase != ProtoDeclaration.DeclaratorCase.IR_PROPERTY) continue
val childProperty = child.irProperty
val name = fileReader.string(child.irProperty.name)
if (name == irProperty.name.asString()) {
if (result == null)
result = childProperty
else {
val resultIdSignature = symbolDeserializer.deserializeIdSignature(BinarySymbolData.decode(result.base.symbol).signatureId)
if (resultIdSignature == signature)
return result
result = childProperty
}
}
}
return result ?: error("Property ${irProperty.render()} is not found")
}
internal fun ProtoProperty.findAccessor(irProperty: IrProperty, irFunction: IrSimpleFunction): ProtoFunction {
if (irFunction == irProperty.getter)
return getter
require(irFunction == irProperty.setter) { "Accessor should be either a getter or a setter. ${irFunction.render()}" }
return setter
}
internal fun ProtoClass.findInlineFunction(irFunction: IrFunction, fileReader: IrLibraryFile, symbolDeserializer: IrSymbolDeserializer): ProtoFunction {
(irFunction as? IrSimpleFunction)?.correspondingPropertySymbol?.owner?.let { irProperty ->
return findProperty(irProperty, fileReader, symbolDeserializer).findAccessor(irProperty, irFunction)
}
val signature = irFunction.symbol.signature ?: error("No signature for ${irFunction.render()}")
var result: ProtoFunction? = null
for (i in 0 until this.declarationCount) {
val child = this.getDeclaration(i)
if (child.declaratorCase != ProtoDeclaration.DeclaratorCase.IR_FUNCTION) continue
val childFunction = child.irFunction
if (childFunction.base.valueParameterCount != irFunction.valueParameters.size) continue
if (childFunction.base.hasExtensionReceiver() xor (irFunction.extensionReceiverParameter != null)) continue
if (childFunction.base.hasDispatchReceiver() xor (irFunction.dispatchReceiverParameter != null)) continue
if (!FunctionFlags.decode(childFunction.base.base.flags).isInline) continue
val nameAndType = BinaryNameAndType.decode(childFunction.base.nameType)
val name = fileReader.string(nameAndType.nameIndex)
if (name == irFunction.name.asString()) {
if (result == null)
result = childFunction
else {
val resultIdSignature = symbolDeserializer.deserializeIdSignature(BinarySymbolData.decode(result.base.base.symbol).signatureId)
if (resultIdSignature == signature)
return result
result = childFunction
}
}
}
return result ?: error("Function ${irFunction.render()} is not found")
}
| 181 | Kotlin | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 5,752 | kotlin | Apache License 2.0 |
app/src/main/java/com/inc/mowa/ui/introduction/IntroductionActivity.kt | oss-inc | 675,047,392 | false | {"Kotlin": 99409, "Java": 2957} | package com.inc.mowa.ui.introduction
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.inc.mowa.R
import com.inc.mowa.databinding.ActivityIntroductionBinding
import com.inc.mowa.ui.login.LoginActivity
import com.inc.mowa.utils.getIntroductionViewStatus
import com.inc.mowa.utils.setIntroductionViewStatus
class IntroductionActivity : AppCompatActivity() {
private lateinit var binding: ActivityIntroductionBinding
private var isShown = 1
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityIntroductionBinding.inflate(layoutInflater)
setContentView(binding.root)
initFragments()
initClickListener()
}
override fun onStart() {
super.onStart()
if (getIntroductionViewStatus() == 0) {
// already check not show
startLoginActivity()
}
if (getIntroductionViewStatus() == 2) {
binding.introductionNotShowCb.visibility = android.view.View.INVISIBLE
}
}
/**
* Initialize fragments containing application introduction contents
*
* @author seonwoo
*/
private fun initFragments() {
supportFragmentManager.beginTransaction()
.replace(R.id.introduction_fl, IntroductionFragment())
.commitAllowingStateLoss()
}
/**
* Initialize click listener
*
* @author seonwoo
*/
private fun initClickListener() {
// click close button
binding.introductionExitIv.setOnClickListener {
if (getIntroductionViewStatus() == 2) {
finish()
} else {
isShown = if (binding.introductionNotShowCb.isChecked) 0 else 1
setIntroductionViewStatus(isShown)
startLoginActivity()
}
}
}
/**
* Start activity (LoginActivity)
*
* @author seonwoo
*/
private fun startLoginActivity() {
val intent = Intent(this@IntroductionActivity, LoginActivity::class.java)
startActivity(intent)
finish()
}
}
| 2 | Kotlin | 1 | 0 | 68de1abaa2fa63d05865ee1bedc2bc14f668fd4c | 2,191 | mowa-frontend-android | Apache License 2.0 |
app/src/main/java/me/kofesst/android/shoppinglist/presentation/ShoppingListApp.kt | kofesst | 513,660,159 | false | {"Kotlin": 162181} | package me.kofesst.android.shoppinglist.presentation
import androidx.compose.foundation.layout.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.ArrowBack
import androidx.compose.material.icons.outlined.ExitToApp
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.currentBackStackEntryAsState
import me.kofesst.android.shoppinglist.presentation.screen.Screen
import me.kofesst.android.shoppinglist.presentation.screen.ScreenConstants
import me.kofesst.android.shoppinglist.presentation.screen.route
import me.kofesst.android.shoppinglist.presentation.screen.withArgs
import me.kofesst.android.shoppinglist.presentation.utils.AppText
import me.kofesst.android.shoppinglist.presentation.utils.activity
val LocalAppState = compositionLocalOf<AppState> {
error("App state didn't initialize")
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ShoppingListApp(
viewModel: MainViewModel
) {
val appState = LocalAppState.current
val navController = appState.navController
val topBarState = remember { appState.topBarState }
val bottomBarState = remember { appState.bottomBarState }
val navBackStackEntry by navController.currentBackStackEntryAsState()
val currentRoute = navBackStackEntry?.destination?.route
DatabaseNotificationsHandle(
appState = appState
)
Scaffold(
topBar = {
Column(
modifier = Modifier.fillMaxWidth()
) {
TopBar(
state = topBarState,
navController = navController,
viewModel = viewModel,
currentScreenRoute = currentRoute
)
Divider(
modifier = Modifier.padding(horizontal = 10.dp)
)
}
},
bottomBar = {
BottomBar(
state = bottomBarState,
currentScreenRoute = currentRoute,
navController = navController
)
},
snackbarHost = {
SnackbarHost(
hostState = appState.snackbarHostState,
snackbar = { data ->
AppSnackbar(
snackbarData = data
)
}
)
}
) {
ScreensNavHost(
navController = navController,
padding = it
)
}
}
@Composable
private fun DatabaseNotificationsHandle(
appState: AppState
) {
val context = LocalContext.current
val mainViewModel = hiltViewModel<MainViewModel>(
viewModelStoreOwner = context.activity!!
)
val authState by mainViewModel.authState
LaunchedEffect(authState) {
when (authState) {
AuthState.LoggedOut -> {
mainViewModel.unsubscribeFromDatabaseChanges()
}
AuthState.LoggedIn -> {
mainViewModel.subscribeToDatabaseChanges { changedListId ->
appState.showSnackbar(
message = AppText.Toast.listChangedToast(context = context),
action = AppText.Action.showChangedListAction(context = context),
onActionPerform = {
appState.navController.navigate(
route = Screen.ListDetails.withArgs(
ScreenConstants.ListDetails.LIST_ID_ARG_NAME to changedListId
)
)
}
)
}
}
}
}
}
@Composable
private fun ScreensNavHost(
navController: NavHostController,
padding: PaddingValues
) {
NavHost(
navController = navController,
startDestination = Screen.Auth.routeName,
modifier = Modifier
.fillMaxSize()
.padding(padding)
) {
Screen.values.forEach { screen ->
composable(
route = screen.route,
arguments = screen.args
) {
screen.ScreenContent(
navController = navController,
backStackEntry = it,
modifier = Modifier.fillMaxSize()
)
}
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun TopBar(
state: TopBarState,
navController: NavController,
viewModel: MainViewModel,
currentScreenRoute: String?
) {
if (state.visible) {
val appState = LocalAppState.current
val bottomBarScreens = Screen.values.filter { screen ->
screen.bottomBarSettings.visible
}
SmallTopAppBar(
title = {
Text(
text = state.title(),
style = MaterialTheme.typography.headlineSmall
)
},
actions = {
if (bottomBarScreens.any { it.routeName == currentScreenRoute }) {
IconButton(
onClick = {
viewModel.clearSession {
viewModel.onSignOut()
appState.navController.navigate(
route = Screen.Auth.routeName
) {
if (currentScreenRoute != null) {
popUpTo(currentScreenRoute) {
inclusive = true
}
}
}
}
}
) {
Icon(
imageVector = Icons.Outlined.ExitToApp,
contentDescription = AppText.Action.clearSessionAction()
)
}
}
state.actions.forEach {
val action = it.onClick()
IconButton(onClick = action) {
Icon(
imageVector = it.icon,
contentDescription = it.description()
)
}
}
},
navigationIcon = {
if (state.hasBackButton) {
IconButton(onClick = { navController.navigateUp() }) {
Icon(
imageVector = Icons.Outlined.ArrowBack,
contentDescription = null
)
}
}
},
modifier = Modifier.fillMaxWidth()
)
}
}
@Composable
private fun BottomBar(
state: BottomBarState,
currentScreenRoute: String?,
navController: NavController
) {
val bottomBarScreens = Screen.values.filter { screen ->
screen.bottomBarSettings.visible
}
if (state.visible) {
BottomAppBar(
tonalElevation = 5.dp,
modifier = Modifier.fillMaxWidth()
) {
bottomBarScreens.forEach { screen ->
val isActive = screen.route == currentScreenRoute
NavigationBarItem(
selected = isActive,
icon = {
Icon(
imageVector = screen.bottomBarSettings.icon,
contentDescription = screen.bottomBarSettings.title()
)
},
label = {
Text(
text = screen.bottomBarSettings.title(),
style = MaterialTheme.typography.bodyMedium
)
},
onClick = {
if (!isActive) {
navController.navigate(screen.route) {
if (currentScreenRoute != null) {
popUpTo(currentScreenRoute) {
inclusive = true
}
}
}
}
}
)
}
}
}
}
@Composable
private fun AppSnackbar(
snackbarData: SnackbarData,
modifier: Modifier = Modifier,
actionOnNewLine: Boolean = false,
shape: Shape = MaterialTheme.shapes.small,
containerColor: Color = MaterialTheme.colorScheme.secondaryContainer,
contentColor: Color = MaterialTheme.colorScheme.onSecondaryContainer,
actionColor: Color = MaterialTheme.colorScheme.primary
) {
Snackbar(
snackbarData = snackbarData,
modifier = modifier,
actionOnNewLine = actionOnNewLine,
shape = shape,
containerColor = containerColor,
contentColor = contentColor,
actionColor = actionColor
)
} | 0 | Kotlin | 0 | 0 | 04ef1ebc9bf5a3819a7a85dc42101e736c5c1274 | 9,633 | shopping-list-app | Apache License 2.0 |
azure-communication-ui/chat/src/test/java/com/azure/android/communication/ui/chat/redux/middleware/ChatMiddlewareUnitTest.kt | Azure | 429,521,705 | false | {"Kotlin": 2573728, "Java": 167445, "Shell": 3964, "HTML": 1856} | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.android.communication.ui.chat.redux.middleware
import com.azure.android.communication.ui.chat.redux.AppStore
import com.azure.android.communication.ui.chat.redux.action.ChatAction
import com.azure.android.communication.ui.chat.redux.middleware.sdk.ChatActionHandler
import com.azure.android.communication.ui.chat.redux.middleware.sdk.ChatMiddlewareImpl
import com.azure.android.communication.ui.chat.redux.middleware.sdk.ChatServiceListener
import com.azure.android.communication.ui.chat.redux.state.ReduxState
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mockito.verify
import org.mockito.Mockito.times
import org.mockito.junit.MockitoJUnitRunner
import org.mockito.kotlin.mock
@RunWith(MockitoJUnitRunner::class)
internal class ChatMiddlewareUnitTest {
@Test
fun chatMiddleware_invoke_when_invokedWithAnyAction_then_invokeNext() {
// arrange
val actionToDispatch = ChatAction.StartChat()
var nextReceivedAction: ChatAction? = null
val mockChatMiddlewareActionHandler = mock<ChatActionHandler> {}
val mockChatServiceListener = mock<ChatServiceListener> {}
val chatMiddlewareImplementation =
ChatMiddlewareImpl(
mockChatServiceListener,
mockChatMiddlewareActionHandler
)
val mockAppStore = mock<AppStore<ReduxState>> {}
// act
chatMiddlewareImplementation.invoke(mockAppStore)(
fun(action) {
nextReceivedAction = action as ChatAction
}
)(actionToDispatch)
// assert
Assert.assertEquals(
actionToDispatch,
nextReceivedAction
)
}
@Test
fun chatMiddleware_invoke_when_invokedWithStartChat_then_invokeStartChat() {
// arrange
val actionToDispatch = ChatAction.StartChat()
val mockChatMiddlewareActionHandler = mock<ChatActionHandler>()
val mockChatServiceListener = mock<ChatServiceListener> {}
val mockAppState = mock<ReduxState> {}
val chatMiddlewareImplementation =
ChatMiddlewareImpl(
mockChatServiceListener,
mockChatMiddlewareActionHandler
)
val mockAppStore = mock<AppStore<ReduxState>> {}
// act
chatMiddlewareImplementation.invoke(mockAppStore)(
fun(action) {
mockChatMiddlewareActionHandler.onAction(
action,
mockAppStore::dispatch,
mockAppState
)
}
)(actionToDispatch)
// assert
verify(mockChatMiddlewareActionHandler, times(1)).onAction(
actionToDispatch,
mockAppStore::dispatch,
mockAppState
)
}
}
| 6 | Kotlin | 27 | 24 | 96a897fb62cf8ce39a30f8bb7232df8aa888e084 | 2,948 | communication-ui-library-android | MIT License |
app/src/unitTest/kotlin/batect/utils/EditDistanceCalculatorSpec.kt | batect | 102,647,061 | false | {"Kotlin": 2888008, "Python": 42425, "Shell": 33457, "PowerShell": 8340, "Dockerfile": 3386, "Batchfile": 3234, "Java": 1432, "HTML": 345} | /*
Copyright 2017-2021 <NAME>.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package batect.utils
import batect.testutils.equalTo
import batect.testutils.on
import com.natpryce.hamkrest.assertion.assertThat
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
object EditDistanceCalculatorSpec : Spek({
describe("an edit distance calculator") {
on("calculating the edit distance for two empty strings") {
val editDistance = EditDistanceCalculator.calculateDistanceBetween("", "")
it("calculates the edit distance as zero") {
assertThat(editDistance, equalTo(0))
}
}
on("calculating the edit distance for an empty string and a non-empty string") {
val editDistance = EditDistanceCalculator.calculateDistanceBetween("", "abc")
it("calculates the edit distance as the length of the non-empty string") {
assertThat(editDistance, equalTo(3))
}
}
on("calculating the edit distance for a non-empty string and an empty string") {
val editDistance = EditDistanceCalculator.calculateDistanceBetween("wxyz", "")
it("calculates the edit distance as the length of the non-empty string") {
assertThat(editDistance, equalTo(4))
}
}
on("calculating the edit distance for two identical non-empty strings") {
val editDistance = EditDistanceCalculator.calculateDistanceBetween("abc", "abc")
it("calculates the edit distance as zero") {
assertThat(editDistance, equalTo(0))
}
}
on("calculating the edit distance for two strings differing only by a single character substitution") {
val editDistance = EditDistanceCalculator.calculateDistanceBetween("abc", "abd")
it("calculates the edit distance as one") {
assertThat(editDistance, equalTo(1))
}
}
on("calculating the edit distance for two strings differing only by two character substitutions") {
val editDistance = EditDistanceCalculator.calculateDistanceBetween("abc", "ade")
it("calculates the edit distance as two") {
assertThat(editDistance, equalTo(2))
}
}
on("calculating the edit distance for two strings differing only by a single character addition") {
val editDistance = EditDistanceCalculator.calculateDistanceBetween("abc", "abcd")
it("calculates the edit distance as one") {
assertThat(editDistance, equalTo(1))
}
}
on("calculating the edit distance for two strings differing only by two character additions") {
val editDistance = EditDistanceCalculator.calculateDistanceBetween("abc", "abcde")
it("calculates the edit distance as two") {
assertThat(editDistance, equalTo(2))
}
}
on("calculating the edit distance for two strings differing only by a single character deletion") {
val editDistance = EditDistanceCalculator.calculateDistanceBetween("abc", "ab")
it("calculates the edit distance as one") {
assertThat(editDistance, equalTo(1))
}
}
on("calculating the edit distance for two strings differing only by two character deletions") {
val editDistance = EditDistanceCalculator.calculateDistanceBetween("abc", "a")
it("calculates the edit distance as two") {
assertThat(editDistance, equalTo(2))
}
}
on("calculating the edit distance for two strings differing by a substitution and an addition") {
val editDistance = EditDistanceCalculator.calculateDistanceBetween("abc", "abde")
it("calculates the edit distance as two") {
assertThat(editDistance, equalTo(2))
}
}
on("calculating the edit distance for two strings differing by a substitution and a deletion") {
val editDistance = EditDistanceCalculator.calculateDistanceBetween("abc", "xabd")
it("calculates the edit distance as two") {
assertThat(editDistance, equalTo(2))
}
}
on("calculating the edit distance for two strings differing by an addition and a deletion") {
val editDistance = EditDistanceCalculator.calculateDistanceBetween("abc", "xab")
it("calculates the edit distance as two") {
assertThat(editDistance, equalTo(2))
}
}
on("calculating the edit distance for two completely different strings of the same length") {
val editDistance = EditDistanceCalculator.calculateDistanceBetween("abc", "xyz")
it("calculates the edit distance as equal to the length of those strings (ie. substituting each character for the other)") {
assertThat(editDistance, equalTo(3))
}
}
on("calculating the edit distance for two completely different strings of different lengths") {
val editDistance = EditDistanceCalculator.calculateDistanceBetween("abcdef", "xyz")
it("calculates the edit distance as equal to the length of the longer string (ie. substituting each character for the other then adding the remaining characters)") {
assertThat(editDistance, equalTo(6))
}
}
}
})
| 24 | Kotlin | 47 | 687 | 67c942241c7d52b057c5268278d6252301c48087 | 6,097 | batect | Apache License 2.0 |
app/src/main/java/com/github/jing332/tts_server_android/ui/AppActivityResultContracts.kt | jing332 | 536,800,727 | false | null | package com.github.jing332.tts_server_android.ui
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Parcelable
import androidx.activity.result.contract.ActivityResultContract
import com.github.jing332.tts_server_android.constant.KeyConst
import com.github.jing332.tts_server_android.help.ByteArrayBinder
import com.github.jing332.tts_server_android.utils.setBinder
object AppActivityResultContracts {
/**
* 用于传递Parcelable数据
*/
@Suppress("DEPRECATION")
fun <T : Parcelable> parcelableDataActivity(clz: Class<out Activity>) =
object : ActivityResultContract<T?, T?>() {
override fun createIntent(context: Context, input: T?): Intent {
return Intent(context, clz).apply {
if (input != null) putExtra(KeyConst.KEY_DATA, input)
}
}
override fun parseResult(resultCode: Int, intent: Intent?): T? {
return intent?.getParcelableExtra(KeyConst.KEY_DATA)
}
}
fun filePickerActivity() =
object :
ActivityResultContract<FilePickerActivity.IRequestData, Pair<FilePickerActivity.IRequestData?, Uri?>>() {
override fun createIntent(
context: Context,
input: FilePickerActivity.IRequestData
): Intent {
return Intent(context, FilePickerActivity::class.java).apply {
if (input is FilePickerActivity.RequestSaveFile)
setBinder(ByteArrayBinder(input.fileBytes!!))
putExtra(FilePickerActivity.KEY_REQUEST_DATA, input)
}
}
@Suppress("DEPRECATION")
override fun parseResult(
resultCode: Int,
intent: Intent?
): Pair<FilePickerActivity.IRequestData?, Uri?> {
return intent?.getParcelableExtra<FilePickerActivity.IRequestData>(
FilePickerActivity.KEY_REQUEST_DATA
) to intent?.data
}
}
} | 6 | Kotlin | 127 | 1,393 | 8e07e8842cf4cec70154041fcd6a64ad2352d8c8 | 2,134 | tts-server-android | MIT License |
jacodb-analysis/src/test/kotlin/org/jacodb/analysis/impl/BaseAnalysisTest.kt | UnitTestBot | 491,176,077 | false | {"Kotlin": 1456714, "Java": 106293, "Shell": 299, "Batchfile": 23} | /*
* Copyright 2022 UnitTestBot contributors (utbot.org)
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.jacodb.analysis.impl
import juliet.support.AbstractTestCase
import kotlinx.coroutines.runBlocking
import org.jacodb.analysis.engine.VulnerabilityInstance
import org.jacodb.api.JcClassOrInterface
import org.jacodb.api.JcMethod
import org.jacodb.api.ext.findClass
import org.jacodb.api.ext.methods
import org.jacodb.impl.features.classpaths.UnknownClasses
import org.jacodb.impl.features.hierarchyExt
import org.jacodb.testing.BaseTest
import org.jacodb.testing.WithGlobalDB
import org.jacodb.testing.allClasspath
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.params.provider.Arguments
import java.util.stream.Stream
import kotlin.streams.asStream
abstract class BaseAnalysisTest : BaseTest() {
companion object : WithGlobalDB(UnknownClasses) {
@JvmStatic
fun provideClassesForJuliet(cweNum: Int, cweSpecificBans: List<String> = emptyList()): Stream<Arguments> = runBlocking {
val cp = db.classpath(allClasspath)
val hierarchyExt = cp.hierarchyExt()
val baseClass = cp.findClass<AbstractTestCase>()
val classes = hierarchyExt.findSubClasses(baseClass, false)
classes.toArguments("CWE${cweNum}_", cweSpecificBans)
}
private fun Sequence<JcClassOrInterface>.toArguments(cwe: String, cweSpecificBans: List<String>): Stream<Arguments> = this
.map { it.name }
.filter { it.contains(cwe) }
.filterNot { className -> (commonJulietBans + cweSpecificBans).any { className.contains(it) } }
// .filter { it.contains("_68") }
.sorted()
.map { Arguments.of(it) }
.asStream()
private val commonJulietBans = listOf(
// TODO: containers not supported
"_72", "_73", "_74",
// TODO/Won't fix(?): dead parts of switches shouldn't be analyzed
"_15",
// TODO/Won't fix(?): passing through channels not supported
"_75",
// TODO/Won't fix(?): constant private/static methods not analyzed
"_11", "_08",
// TODO/Won't fix(?): unmodified non-final private variables not analyzed
"_05", "_07",
// TODO/Won't fix(?): unmodified non-final static variables not analyzed
"_10", "_14",
)
}
protected abstract fun launchAnalysis(methods: List<JcMethod>): List<VulnerabilityInstance>
protected inline fun <reified T> testOneAnalysisOnOneMethod(
vulnerabilityType: String,
methodName: String,
expectedLocations: Collection<String>,
) {
val method = cp.findClass<T>().declaredMethods.single { it.name == methodName }
val sinks = findSinks(method, vulnerabilityType)
// TODO: think about better assertions here
assertEquals(expectedLocations.size, sinks.size)
expectedLocations.forEach { expected ->
assertTrue(sinks.any { it.contains(expected) }) {
"$expected unmatched in:\n${sinks.joinToString("\n")}"
}
}
}
protected fun testSingleJulietClass(vulnerabilityType: String, className: String) {
val clazz = cp.findClass(className)
val goodMethod = clazz.methods.single { it.name == "good" }
val badMethod = clazz.methods.single { it.name == "bad" }
val goodIssues = findSinks(goodMethod, vulnerabilityType)
val badIssues = findSinks(badMethod, vulnerabilityType)
assertTrue(goodIssues.isEmpty())
assertTrue(badIssues.isNotEmpty())
}
protected fun findSinks(method: JcMethod, vulnerabilityType: String): Set<String> {
val sinks = launchAnalysis(listOf(method))
.filter { it.vulnerabilityDescription.ruleId == vulnerabilityType }
.map { it.traceGraph.sink.toString() }
return sinks.toSet()
}
} | 21 | Kotlin | 7 | 14 | a3767c890fd34a9c4e3f21e15da96d120cbdbd2e | 4,586 | jacodb | Apache License 2.0 |
project/common/src/main/kotlin/ink/ptms/adyeshach/core/entity/type/AdyArrow.kt | TabooLib | 284,936,010 | false | {"Kotlin": 1050024, "Java": 35966} | package ink.ptms.adyeshach.core.entity.type
import ink.ptms.adyeshach.core.entity.EntityThrowable
import org.bukkit.Color
/**
* @author sky
* @since 2020-08-04 19:30
*/
interface AdyArrow : AdyEntity, EntityThrowable {
fun setCritical(value: Boolean) {
setMetadata("isCritical", value)
}
fun isCritical(): Boolean {
return getMetadata("isCritical")
}
fun setNoclip(value: Boolean) {
setMetadata("noclip", value)
}
fun isNoclip(): Boolean {
return getMetadata("noclip")
}
fun setPiercingLevel(value: Byte) {
setMetadata("piercingLevel", value)
}
fun getPiercingLevel(): Byte {
return getMetadata("piercingLevel")
}
fun setColor(value: Color) {
setMetadata("color", value.asRGB())
}
fun getColor(): Color {
return Color.fromRGB(getMetadata("color"))
}
} | 13 | Kotlin | 86 | 98 | ac7098b62db19308c9f14182e33181c079b9e561 | 892 | adyeshach | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.