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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app/src/main/java/com/minhdtm/example/we_note/data/remote/FireStoreHelper.kt | hide-your-code | 501,632,307 | false | null | package com.minhdtm.example.we_note.data.remote
import com.minhdtm.example.we_note.data.model.Note
import com.minhdtm.example.we_note.data.model.User
import kotlinx.coroutines.flow.Flow
interface FireStoreHelper {
fun register(userName: String): Flow<Boolean>
fun getAllUser(): Flow<List<User>>
fun addNote(userName: String, title: String, description: String): Flow<Unit>
fun getNotes(userName: String): Flow<List<Note>>
fun getNote(userName: String, id: String): Flow<Note>
fun updateNote(userName: String, id: String, title: String, description: String): Flow<Unit>
fun deleteNote(userName: String, id: String): Flow<Unit>
}
| 0 | Kotlin | 0 | 0 | 4f0b8a963251fe12d921dfb973cfb4316f485fb5 | 664 | we_note | Apache License 2.0 |
rider/src/main/kotlin/com/jetbrains/rider/plugins/unity/ContentModelUpdater.kt | 20chan | 254,533,394 | true | {"C#": 2979478, "Kotlin": 407975, "ShaderLab": 67905, "Lex": 36697, "GLSL": 7572, "HLSL": 7370, "Java": 5463, "PowerShell": 1036, "Shell": 129} | package com.jetbrains.rider.plugins.unity
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManagerListener
import com.intellij.openapi.vfs.AsyncFileListener
import com.intellij.openapi.vfs.AsyncFileListener.ChangeApplier
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.openapi.vfs.newvfs.events.VFileCreateEvent
import com.intellij.openapi.vfs.newvfs.events.VFileDeleteEvent
import com.intellij.openapi.vfs.newvfs.events.VFileEvent
import com.intellij.util.SingleAlarm
import com.jetbrains.rd.platform.util.application
import com.jetbrains.rider.UnityProjectDiscoverer
import com.jetbrains.rider.plugins.unity.packageManager.PackageManager
import com.jetbrains.rider.plugins.unity.packageManager.PackageManagerListener
import com.jetbrains.rider.plugins.unity.packageManager.PackageSource
import com.jetbrains.rider.projectDir
import com.jetbrains.rider.projectView.ProjectModelViewHost
import com.jetbrains.rider.projectView.indexing.contentModel.ContentModelUserStore
import com.jetbrains.rider.projectView.indexing.contentModel.tryExclude
import com.jetbrains.rider.projectView.indexing.contentModel.tryInclude
import kotlinx.coroutines.Runnable
import java.io.File
// todo: This is a misuse of project listeners. ContentModelUpdater has API and stores state and even has Alarm-based events, what fits naturally here is a service with a bunch of listeners.
class ContentModelUpdater : ProjectManagerListener {
private val excludedFolders = hashSetOf<File>()
private val includedFolders = hashSetOf<File>()
private fun onRootFoldersChanged(project: Project) {
application.assertIsDispatchThread()
val newExcludedFolders = mutableSetOf<File>()
val newIncludedFolders = mutableSetOf<File>()
// It's common practice to have extra folders in the root project folder, e.g. a backup copy of Library for
// a different version of Unity, or target, which can be renamed instead of having to do a time consuming
// reimport. Also, folders containing builds for targets such as iOS.
// Exclude all folders apart from Assets, ProjectSettings and Packages
for (child in project.projectDir.children) {
if (child != null && isRootFolder(project, child) && !isInProject(project, child)) {
val file = VfsUtil.virtualToIoFile(child)
if (shouldInclude(child.name)) {
newIncludedFolders.add(file)
}
else {
newExcludedFolders.add(file)
}
}
}
for (p in PackageManager.getInstance(project).allPackages) {
if (p.packageFolder != null && p.source != PackageSource.BuiltIn
&& p.source != PackageSource.Embedded
&& p.source != PackageSource.Unknown) {
newIncludedFolders.add(VfsUtil.virtualToIoFile(p.packageFolder))
}
}
val excludesChanged = excludedFolders != newExcludedFolders
val includesChanged = includedFolders != newIncludedFolders
if (excludesChanged || includesChanged) {
// They shouldn't be attached as folders, but just make sure
val contentModel = ContentModelUserStore.getInstance(project)
contentModel.attachedFolders.removeAll(excludedFolders)
contentModel.attachedFolders.removeAll(includedFolders)
if (excludesChanged) {
contentModel.explicitExcludes.removeAll(excludedFolders)
contentModel.tryExclude(newExcludedFolders.toTypedArray(), false)
excludedFolders.clear()
excludedFolders.addAll(newExcludedFolders)
}
if (includesChanged) {
contentModel.explicitIncludes.removeAll(includedFolders)
contentModel.tryInclude(newIncludedFolders.toTypedArray(), false)
includedFolders.clear()
includedFolders.addAll(newIncludedFolders)
}
contentModel.update()
}
}
private fun isRootFolder(project: Project, file: VirtualFile): Boolean {
return file.isDirectory && file.parent == project.projectDir
}
private fun isInProject(project:Project, file: VirtualFile): Boolean {
return ProjectModelViewHost.getInstance(project).getItemsByVirtualFile(file).isNotEmpty()
}
private fun shouldInclude(name: String): Boolean {
return name.equals("Assets", true)
|| name.equals("ProjectSettings", true)
|| name.equals("Packages", true)
}
private inner class Listener(private val project: Project, private val alarm: SingleAlarm) : AsyncFileListener, PackageManagerListener {
override fun onPackagesUpdated() {
alarm.cancelAndRequest()
}
override fun prepareChange(events: MutableList<out VFileEvent>): ChangeApplier? {
var requiresUpdate = false
events.forEach {
ProgressManager.checkCanceled()
when (it) {
is VFileCreateEvent -> {
requiresUpdate = requiresUpdate || (it.isDirectory && it.parent == project.projectDir)
}
is VFileDeleteEvent -> {
requiresUpdate = requiresUpdate || isRootFolder(project, it.file)
}
}
}
if (!requiresUpdate) {
return null
}
return object: ChangeApplier {
override fun afterVfsChange() = alarm.cancelAndRequest()
}
}
}
override fun projectOpened(project: Project) {
if (UnityProjectDiscoverer.getInstance(project).isUnityProject) {
val alarm = SingleAlarm(Runnable { onRootFoldersChanged(project) }, 1000, ModalityState.any(), project)
val listener = Listener(project, alarm)
// Listen to add/remove of folders in the root of the project
VirtualFileManager.getInstance().addAsyncFileListener(listener, project)
// Listen for external packages that we should be indexing
PackageManager.getInstance(project).addListener(listener)
alarm.request()
}
}
} | 0 | null | 0 | 1 | 1e0db52a0144ac83206bf71a79eacffe4307cdba | 6,557 | resharper-unity | Apache License 2.0 |
kmath-ast/src/commonTest/kotlin/space/kscience/kmath/ast/TestCompilerOperations.kt | SciProgCentre | 129,486,382 | false | null | /*
* Copyright 2018-2022 KMath 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 space.kscience.kmath.ast
import space.kscience.kmath.expressions.MstExtendedField
import space.kscience.kmath.expressions.Symbol.Companion.x
import space.kscience.kmath.expressions.invoke
import space.kscience.kmath.operations.Float64Field
import space.kscience.kmath.operations.invoke
import kotlin.test.Test
import kotlin.test.assertEquals
internal class TestCompilerOperations {
@Test
fun testUnaryPlus() = runCompilerTest {
val expr = MstExtendedField { +x }.compileToExpression(Float64Field)
assertEquals(2.0, expr(x to 2.0))
}
@Test
fun testUnaryMinus() = runCompilerTest {
val expr = MstExtendedField { -x }.compileToExpression(Float64Field)
assertEquals(-2.0, expr(x to 2.0))
}
@Test
fun testAdd() = runCompilerTest {
val expr = MstExtendedField { x + x }.compileToExpression(Float64Field)
assertEquals(4.0, expr(x to 2.0))
}
@Test
fun testSine() = runCompilerTest {
val expr = MstExtendedField { sin(x) }.compileToExpression(Float64Field)
assertEquals(0.0, expr(x to 0.0))
}
@Test
fun testCosine() = runCompilerTest {
val expr = MstExtendedField { cos(x) }.compileToExpression(Float64Field)
assertEquals(1.0, expr(x to 0.0))
}
@Test
fun testTangent() = runCompilerTest {
val expr = MstExtendedField { tan(x) }.compileToExpression(Float64Field)
assertEquals(0.0, expr(x to 0.0))
}
@Test
fun testArcSine() = runCompilerTest {
val expr = MstExtendedField { asin(x) }.compileToExpression(Float64Field)
assertEquals(0.0, expr(x to 0.0))
}
@Test
fun testArcCosine() = runCompilerTest {
val expr = MstExtendedField { acos(x) }.compileToExpression(Float64Field)
assertEquals(0.0, expr(x to 1.0))
}
@Test
fun testAreaHyperbolicSine() = runCompilerTest {
val expr = MstExtendedField { asinh(x) }.compileToExpression(Float64Field)
assertEquals(0.0, expr(x to 0.0))
}
@Test
fun testSubtract() = runCompilerTest {
val expr = MstExtendedField { x - x }.compileToExpression(Float64Field)
assertEquals(0.0, expr(x to 2.0))
}
@Test
fun testDivide() = runCompilerTest {
val expr = MstExtendedField { x / x }.compileToExpression(Float64Field)
assertEquals(1.0, expr(x to 2.0))
}
@Test
fun testPower() = runCompilerTest {
val expr = MstExtendedField { x pow 2 }.compileToExpression(Float64Field)
assertEquals(4.0, expr(x to 2.0))
}
}
| 91 | null | 55 | 645 | 3e8f44166c4a4ed6e99e1676a7200ed044645224 | 2,747 | kmath | Apache License 2.0 |
app/src/main/java/com/example/huaweiproject/assistant/AssistantViewModel.kt | HorizonParadox | 446,429,345 | false | {"Kotlin": 70859, "Java": 26730} | package com.example.huaweiproject.assistant
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import com.example.huaweiproject.data.Assistant
import com.example.huaweiproject.data.AssistantDao
import kotlinx.coroutines.*
class AssistantViewModel(private val database: AssistantDao, application: Application):
AndroidViewModel(application) {
private var viewModeJob = Job()
override fun onCleared() {
super.onCleared()
viewModeJob.cancel()
}
private val uiScope = CoroutineScope(Dispatchers.Main + viewModeJob)
private var currentMessage = MutableLiveData<Assistant?>()
val messages = database.getAllMessages()
init {
initializeCurrentMessage()
}
private fun initializeCurrentMessage() {
uiScope.launch { currentMessage.value = getCurrentMessageFromDatabase() }
}
private suspend fun getCurrentMessageFromDatabase(): Assistant? {
return withContext(Dispatchers.IO){
var message = database.getCurrentMessage()
if (message?.assistantMessage == "DEFAULT_MESSAGE" ||
message?.humanMessage == "DEFAULT_MESSAGE"){
message = null
}
message
}
}
fun sendMessageToDataBase(assistantMessage: String, humanMessage: String){
uiScope.launch {
val newAssistant = Assistant()
newAssistant.assistantMessage = assistantMessage
newAssistant.humanMessage = humanMessage
insert(newAssistant)
currentMessage.value = getCurrentMessageFromDatabase()
}
}
private suspend fun insert(message: Assistant){
withContext(Dispatchers.IO){
database.insert(message)
}
}
private suspend fun update(message: Assistant){
withContext(Dispatchers.IO){
database.update(message)
}
}
fun onClear(){
uiScope.launch {
clear()
currentMessage.value = null
}
}
private suspend fun clear(){
withContext(Dispatchers.IO){
database.clear()
}
}
} | 0 | Kotlin | 0 | 0 | 660ab66b5b5e530d8a4641bfe5b7890956e61b27 | 2,193 | VoiceAsistantProject | MIT License |
features/dd-sdk-android-session-replay/src/test/kotlin/com/datadog/android/sessionreplay/internal/recorder/mapper/BaseRadioButtonMapperTest.kt | DataDog | 219,536,756 | false | null | /*
* Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0.
* This product includes software developed at Datadog (https://www.datadoghq.com/).
* Copyright 2016-Present Datadog, Inc.
*/
package com.datadog.android.sessionreplay.internal.recorder.mapper
import android.graphics.drawable.Drawable
import android.os.Build
import android.widget.RadioButton
import com.datadog.android.sessionreplay.forge.ForgeConfigurator
import com.datadog.android.sessionreplay.internal.recorder.GlobalBounds
import com.datadog.android.sessionreplay.internal.recorder.densityNormalized
import com.datadog.android.sessionreplay.model.MobileSegment
import com.datadog.android.sessionreplay.utils.StringUtils
import com.datadog.android.sessionreplay.utils.UniqueIdentifierGenerator
import com.datadog.android.sessionreplay.utils.ViewUtils
import com.datadog.tools.unit.annotations.TestTargetApi
import com.datadog.tools.unit.extensions.ApiLevelExtension
import fr.xgouchet.elmyr.annotation.FloatForgery
import fr.xgouchet.elmyr.annotation.Forgery
import fr.xgouchet.elmyr.annotation.IntForgery
import fr.xgouchet.elmyr.annotation.LongForgery
import fr.xgouchet.elmyr.junit5.ForgeConfiguration
import fr.xgouchet.elmyr.junit5.ForgeExtension
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.junit.jupiter.api.extension.Extensions
import org.mockito.Mock
import org.mockito.junit.jupiter.MockitoExtension
import org.mockito.junit.jupiter.MockitoSettings
import org.mockito.kotlin.any
import org.mockito.kotlin.eq
import org.mockito.kotlin.mock
import org.mockito.kotlin.whenever
import org.mockito.quality.Strictness
@Extensions(
ExtendWith(MockitoExtension::class),
ExtendWith(ForgeExtension::class),
ExtendWith(ApiLevelExtension::class)
)
@MockitoSettings(strictness = Strictness.LENIENT)
@ForgeConfiguration(ForgeConfigurator::class)
internal abstract class BaseRadioButtonMapperTest : BaseWireframeMapperTest() {
lateinit var testedRadioButtonMapper: RadioButtonMapper
@Mock
lateinit var mockuniqueIdentifierGenerator: UniqueIdentifierGenerator
@Mock
lateinit var mockTextWireframeMapper: TextViewMapper
@Forgery
lateinit var fakeTextWireframes: List<MobileSegment.Wireframe.TextWireframe>
@LongForgery
var fakeGeneratedIdentifier: Long = 0L
@Mock
lateinit var mockViewUtils: ViewUtils
@Forgery
lateinit var fakeViewGlobalBounds: GlobalBounds
lateinit var mockRadioButton: RadioButton
@IntForgery(min = 0, max = 0xffffff)
var fakeCurrentTextColor: Int = 0
@FloatForgery(min = 1f, max = 100f)
var fakeTextSize: Float = 1f
@IntForgery(min = CheckableCompoundButtonMapper.DEFAULT_CHECKABLE_HEIGHT_IN_PX.toInt(), max = 100)
var fakeIntrinsicDrawableHeight = 1
@BeforeEach
fun `set up`() {
mockRadioButton = mock {
whenever(it.textSize).thenReturn(fakeTextSize)
whenever(it.currentTextColor).thenReturn(fakeCurrentTextColor)
}
whenever(
mockuniqueIdentifierGenerator.resolveChildUniqueIdentifier(
mockRadioButton,
CheckableTextViewMapper.CHECKABLE_KEY_NAME
)
).thenReturn(fakeGeneratedIdentifier)
whenever(mockTextWireframeMapper.map(eq(mockRadioButton), eq(fakeMappingContext), any()))
.thenReturn(fakeTextWireframes)
whenever(
mockViewUtils.resolveViewGlobalBounds(
mockRadioButton,
fakeMappingContext.systemInformation.screenDensity
)
)
.thenReturn(fakeViewGlobalBounds)
testedRadioButtonMapper = setupTestedMapper()
}
internal abstract fun setupTestedMapper(): RadioButtonMapper
internal open fun expectedCheckedShapeStyle(checkBoxColor: String): MobileSegment.ShapeStyle? {
return MobileSegment.ShapeStyle(
backgroundColor = checkBoxColor,
opacity = mockRadioButton.alpha,
cornerRadius = RadioButtonMapper.CORNER_RADIUS
)
}
internal open fun expectedNotCheckedShapeStyle(checkBoxColor: String): MobileSegment.ShapeStyle? {
return MobileSegment.ShapeStyle(
opacity = mockRadioButton.alpha,
cornerRadius = RadioButtonMapper.CORNER_RADIUS
)
}
// region Unit Tests
@TestTargetApi(Build.VERSION_CODES.M)
@Test
fun `M resolve the checkbox as ShapeWireframe W map() { checked, above M }`() {
// Given
val mockDrawable = mock<Drawable> {
whenever(it.intrinsicHeight).thenReturn(fakeIntrinsicDrawableHeight)
}
whenever(mockRadioButton.buttonDrawable).thenReturn(mockDrawable)
whenever(mockRadioButton.isChecked).thenReturn(true)
val expectedRadioBoxColor = StringUtils.formatColorAndAlphaAsHexa(
fakeCurrentTextColor,
OPAQUE_ALPHA_VALUE
)
val checkBoxSize =
resolveRadioBoxSize(fakeIntrinsicDrawableHeight.toLong())
val expectedCheckBoxWireframe = MobileSegment.Wireframe.ShapeWireframe(
id = fakeGeneratedIdentifier,
x = fakeViewGlobalBounds.x + CheckableCompoundButtonMapper.MIN_PADDING_IN_PX
.densityNormalized(fakeMappingContext.systemInformation.screenDensity),
y = fakeViewGlobalBounds.y + (fakeViewGlobalBounds.height - checkBoxSize) / 2,
width = checkBoxSize,
height = checkBoxSize,
border = MobileSegment.ShapeBorder(
color = expectedRadioBoxColor,
width = CheckableTextViewMapper.CHECKABLE_BORDER_WIDTH
),
shapeStyle = expectedCheckedShapeStyle(expectedRadioBoxColor)
)
// When
val resolvedWireframes = testedRadioButtonMapper.map(
mockRadioButton,
fakeMappingContext
)
// Then
assertThat(resolvedWireframes).isEqualTo(fakeTextWireframes + expectedCheckBoxWireframe)
}
@TestTargetApi(Build.VERSION_CODES.M)
@Test
fun `M resolve the checkbox as ShapeWireframe W map() { not checked, above M }`() {
// Given
val mockDrawable = mock<Drawable> {
whenever(it.intrinsicHeight).thenReturn(fakeIntrinsicDrawableHeight)
}
whenever(mockRadioButton.buttonDrawable).thenReturn(mockDrawable)
whenever(mockRadioButton.isChecked).thenReturn(false)
val expectedRadioBoxColor = StringUtils.formatColorAndAlphaAsHexa(
fakeCurrentTextColor,
OPAQUE_ALPHA_VALUE
)
val checkBoxSize =
resolveRadioBoxSize(fakeIntrinsicDrawableHeight.toLong())
val expectedCheckBoxWireframe = MobileSegment.Wireframe.ShapeWireframe(
id = fakeGeneratedIdentifier,
x = fakeViewGlobalBounds.x + CheckableCompoundButtonMapper.MIN_PADDING_IN_PX
.densityNormalized(fakeMappingContext.systemInformation.screenDensity),
y = fakeViewGlobalBounds.y + (fakeViewGlobalBounds.height - checkBoxSize) / 2,
width = checkBoxSize,
height = checkBoxSize,
border = MobileSegment.ShapeBorder(
color = expectedRadioBoxColor,
width = CheckableTextViewMapper.CHECKABLE_BORDER_WIDTH
),
shapeStyle = expectedNotCheckedShapeStyle(expectedRadioBoxColor)
)
// When
val resolvedWireframes = testedRadioButtonMapper.map(
mockRadioButton,
fakeMappingContext
)
// Then
assertThat(resolvedWireframes).isEqualTo(fakeTextWireframes + expectedCheckBoxWireframe)
}
@Test
fun `M resolve the checkbox as ShapeWireframe W map() { checked }`() {
// Given
whenever(mockRadioButton.isChecked).thenReturn(true)
val expectedRadioBoxColor = StringUtils.formatColorAndAlphaAsHexa(
fakeCurrentTextColor,
OPAQUE_ALPHA_VALUE
)
val checkBoxSize =
resolveRadioBoxSize(CheckableCompoundButtonMapper.DEFAULT_CHECKABLE_HEIGHT_IN_PX)
val expectedCheckBoxWireframe = MobileSegment.Wireframe.ShapeWireframe(
id = fakeGeneratedIdentifier,
x = fakeViewGlobalBounds.x + CheckableCompoundButtonMapper.MIN_PADDING_IN_PX
.densityNormalized(fakeMappingContext.systemInformation.screenDensity),
y = fakeViewGlobalBounds.y + (fakeViewGlobalBounds.height - checkBoxSize) / 2,
width = checkBoxSize,
height = checkBoxSize,
border = MobileSegment.ShapeBorder(
color = expectedRadioBoxColor,
width = CheckableTextViewMapper.CHECKABLE_BORDER_WIDTH
),
shapeStyle = expectedCheckedShapeStyle(expectedRadioBoxColor)
)
// When
val resolvedWireframes = testedRadioButtonMapper.map(
mockRadioButton,
fakeMappingContext
)
// Then
assertThat(resolvedWireframes).isEqualTo(fakeTextWireframes + expectedCheckBoxWireframe)
}
@Test
fun `M resolve the checkbox as ShapeWireframe W map() { not checked }`() {
// Given
whenever(mockRadioButton.isChecked).thenReturn(false)
val expectedRadioBoxColor = StringUtils.formatColorAndAlphaAsHexa(
fakeCurrentTextColor,
OPAQUE_ALPHA_VALUE
)
val checkBoxSize =
resolveRadioBoxSize(CheckableCompoundButtonMapper.DEFAULT_CHECKABLE_HEIGHT_IN_PX)
val expectedCheckBoxWireframe = MobileSegment.Wireframe.ShapeWireframe(
id = fakeGeneratedIdentifier,
x = fakeViewGlobalBounds.x + CheckableCompoundButtonMapper.MIN_PADDING_IN_PX
.densityNormalized(fakeMappingContext.systemInformation.screenDensity),
y = fakeViewGlobalBounds.y + (fakeViewGlobalBounds.height - checkBoxSize) / 2,
width = checkBoxSize,
height = checkBoxSize,
border = MobileSegment.ShapeBorder(
color = expectedRadioBoxColor,
width = CheckableTextViewMapper.CHECKABLE_BORDER_WIDTH
),
shapeStyle = expectedNotCheckedShapeStyle(expectedRadioBoxColor)
)
// When
val resolvedWireframes = testedRadioButtonMapper.map(
mockRadioButton,
fakeMappingContext
)
// Then
assertThat(resolvedWireframes).isEqualTo(fakeTextWireframes + expectedCheckBoxWireframe)
}
@Test
fun `M ignore the checkbox W map() { unique id could not be generated }`() {
// Given
whenever(
mockuniqueIdentifierGenerator.resolveChildUniqueIdentifier(
mockRadioButton,
CheckableTextViewMapper.CHECKABLE_KEY_NAME
)
).thenReturn(null)
// When
val resolvedWireframes = testedRadioButtonMapper.map(
mockRadioButton,
fakeMappingContext
)
// Then
assertThat(resolvedWireframes).isEqualTo(fakeTextWireframes)
}
// endregion
// region Internal
private fun resolveRadioBoxSize(radioSize: Long): Long {
val density = fakeMappingContext.systemInformation.screenDensity
val size = radioSize - 2 * CheckableCompoundButtonMapper.MIN_PADDING_IN_PX
return size.densityNormalized(density)
}
// endregion
}
| 61 | null | 57 | 140 | de8989f0056124457b3296a6d6c2d91b70f181aa | 11,610 | dd-sdk-android | Apache License 2.0 |
app/src/main/kotlin/com/quittle/a11yally/view/CheckableCustomCardView.kt | quittle | 135,217,260 | false | null | package com.quittle.a11yally.view
import android.content.Context
import android.util.AttributeSet
import android.widget.Checkable
import androidx.annotation.ColorInt
import androidx.annotation.DrawableRes
import androidx.preference.PreferenceManager
import com.quittle.a11yally.R
import com.quittle.a11yally.base.isNotNull
class CheckableCustomCardView : Checkable, CustomCardView {
@FunctionalInterface
fun interface OnCheckedChangeListener {
fun onCheckedChanged(view: CheckableCustomCardView, isChecked: Boolean)
}
private val mListeners: MutableList<OnCheckedChangeListener> = mutableListOf()
@DrawableRes
private val mImageResource: Int
@ColorInt
private val mImageBackgroundColor: Int
@DrawableRes
private val mImageResourceUnchecked: Int
@ColorInt
private val mImageBackgroundColorUnchecked: Int
private var mIsChecked: Boolean = false
private val mPreferenceKey: String?
constructor(context: Context) : super(context) {
mImageResource = 0
mImageBackgroundColor = 0
mImageResourceUnchecked = 0
mImageBackgroundColorUnchecked = 0
mPreferenceKey = null
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
with(extractAttributes(context, attrs)) {
mImageResource = imageResource
mImageBackgroundColor = imageBackgroundColor
mImageResourceUnchecked = imageResourceUnchecked
mImageBackgroundColorUnchecked = imageBackgroundColorUnchecked
mIsChecked = checked
mPreferenceKey = preferenceKey
}
}
constructor(
context: Context,
attrs: AttributeSet,
defStyle: Int
) : super(context, attrs, defStyle) {
with(extractAttributes(context, attrs)) {
mImageResource = imageResource
mImageBackgroundColor = imageBackgroundColor
mImageResourceUnchecked = imageResourceUnchecked
mImageBackgroundColorUnchecked = imageBackgroundColorUnchecked
mIsChecked = checked
mPreferenceKey = preferenceKey
}
}
private companion object {
private data class Attributes(
@DrawableRes val imageResource: Int,
@ColorInt val imageBackgroundColor: Int,
@DrawableRes val imageResourceUnchecked: Int,
@ColorInt val imageBackgroundColorUnchecked: Int,
val checked: Boolean,
val preferenceKey: String?
)
@JvmField
val ON_TOGGLE = OnCheckedChangeListener { view, isChecked ->
if (isChecked) {
view.setImageResource(view.mImageResource)
view.setImageBackgroundColor(view.mImageBackgroundColor)
} else {
view.setImageResource(view.mImageResourceUnchecked)
view.setImageBackgroundColor(view.mImageBackgroundColorUnchecked)
}
view.mPreferenceKey?.let { preferenceKey ->
PreferenceManager.getDefaultSharedPreferences(view.context).edit()
.putBoolean(preferenceKey, isChecked)
?.apply()
}
}
private fun extractAttributes(context: Context, attrs: AttributeSet): Attributes {
@DrawableRes val imageResource: Int
@ColorInt val imageBackgroundColor: Int
with(context.obtainStyledAttributes(attrs, R.styleable.CustomCardView)) {
imageResource = getResourceId(R.styleable.CustomCardView_image, 0)
imageBackgroundColor = getColor(R.styleable.CustomCardView_imageBackgroundColor, 0)
}
@DrawableRes val imageResourceUnchecked: Int
@ColorInt val imageBackgroundColorUnchecked: Int
val checked: Boolean
val preferenceKey: String?
with(context.obtainStyledAttributes(attrs, R.styleable.CheckableCustomCardView)) {
imageResourceUnchecked =
getResourceId(R.styleable.CheckableCustomCardView_imageUnchecked, 0)
imageBackgroundColorUnchecked =
getColor(
R.styleable.CheckableCustomCardView_imageBackgroundColorUnchecked,
0
)
checked = getBoolean(R.styleable.CheckableCustomCardView_checked, false)
preferenceKey = getString(R.styleable.CheckableCustomCardView_preference_key)
recycle()
}
return Attributes(
imageResource,
imageBackgroundColor,
imageResourceUnchecked,
imageBackgroundColorUnchecked,
checked,
preferenceKey
)
}
}
init {
setOnCheckedChangeListener(ON_TOGGLE)
setOnClickListener {
toggle()
}
}
@DrawableRes
fun getImageResource(): Int {
return mImageResource
}
override fun onFinishInflate() {
super.onFinishInflate()
isChecked = if (mPreferenceKey.isNotNull()) {
PreferenceManager.getDefaultSharedPreferences(context)
.getBoolean(mPreferenceKey, mIsChecked)
} else {
mIsChecked
}
}
private fun setOnCheckedChangeListener(listener: OnCheckedChangeListener) {
mListeners.add(listener)
}
override fun isChecked(): Boolean {
return mIsChecked
}
override fun setChecked(isChecked: Boolean) {
mIsChecked = isChecked
mListeners.iterator().forEach {
it.onCheckedChanged(this, isChecked)
}
}
override fun toggle() {
isChecked = !isChecked
}
}
| 48 | Kotlin | 4 | 22 | b277dda83087b12774198ec8372914278088da3a | 5,782 | a11y-ally | Apache License 2.0 |
kapt-example-core/src/main/kotlin/ru/vood/dmgen/intf/IMetaEntity.kt | igorvood | 698,285,919 | false | {"Kotlin": 72032} | package ru.vood.dmgen.intf
import kotlinx.serialization.KSerializer
import ru.vood.dmgen.annotation.FlowEntityType
import kotlin.reflect.KClass
interface IMetaEntity {
val designClass: KClass<*>
val runtimeClass: KClass<*>
val entityName: EntityName
val comment: String
val serializer: KSerializer<*>
val entityType: FlowEntityType
}
@JvmInline
value class EntityName(val value: String)
| 0 | Kotlin | 0 | 0 | c989f5c1a22354363cc7ca7ac554ff80a5975bc4 | 415 | kotlin-data-model-generator | MIT License |
app/src/main/java/com/movicom/informativeapplicationcovid19/viewmodel/CountryViewModel.kt | SebastianRV26 | 289,597,953 | false | null | package com.movicom.informativeapplicationcovid19.viewmodel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.movicom.informativeapplicationcovid19.models.Country
import com.movicom.informativeapplicationcovid19.network.repositories.CountryRepository
class CountryViewModel : ViewModel() {
private val countryRepository = CountryRepository()
var countries = MutableLiveData<List<Country>>()
var message = MutableLiveData<String>()
fun refresh() {
callComics()
countries = countryRepository.getCountries()
processFinished()
}
private fun callComics() {
countryRepository.callCountry()
}
private fun processFinished() {
message = countryRepository.getMessage()
}
fun searchCountry(countryName:String): Country?{
countries.value?.forEach {
if (it.Country == countryName){
return it
}
}
return null
}
} | 0 | Kotlin | 0 | 1 | bf3bc1dfc9bdb3cb71a503f81a0cb778240283a2 | 992 | Info-COVID-App | MIT License |
core/src/main/kotlin/com/ferelin/core/adapter/base/BaseRecyclerAdapter.kt | NikitaFerelin | 339,103,168 | false | null | /*
* Copyright 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
*
* 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.ferelin.core.adapter.base
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import java.util.*
class BaseRecyclerAdapter(
vararg adapterDelegates: RecyclerAdapterDelegate
) : RecyclerView.Adapter<BaseRecyclerViewHolder>() {
private var currentList = Collections.synchronizedList(mutableListOf<ViewDataType>())
private val delegates = adapterDelegates.toList()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseRecyclerViewHolder {
val targetIndex = delegates.indexOfFirst { it.itemsViewType == viewType }
return delegates[targetIndex].onCreateViewHolder(parent)
}
override fun onBindViewHolder(holder: BaseRecyclerViewHolder, position: Int) {
holder.bind(currentList[position], position, mutableListOf())
}
override fun onBindViewHolder(
holder: BaseRecyclerViewHolder,
position: Int,
payloads: MutableList<Any>
) {
if (payloads.isNotEmpty()) {
holder.bind(currentList[position], position, payloads)
} else {
super.onBindViewHolder(holder, position, payloads)
}
}
override fun getItemCount(): Int {
return currentList.size
}
override fun getItemViewType(position: Int): Int {
return currentList[position].itemViewType
}
override fun getItemId(position: Int): Long {
return if (hasStableIds()) {
currentList[position].getUniqueId()
} else {
super.getItemId(position)
}
}
fun getByPosition(position: Int): ViewDataType {
return currentList[position]
}
fun getPositionOf(selector: (ViewDataType) -> Boolean): Int {
return currentList.indexOfFirst(selector)
}
fun update(viewDataType: ViewDataType, position: Int, payloads: Any? = null) {
currentList[position] = viewDataType
notifyItemChanged(position, payloads)
}
fun add(position: Int, viewDataType: ViewDataType) {
currentList.add(position, viewDataType)
notifyItemInserted(position)
}
fun removeAt(position: Int) {
currentList.removeAt(position)
notifyItemRemoved(position)
}
fun setData(data: List<ViewDataType>) {
if (currentList.isNotEmpty()) {
val itemCount = currentList.size
currentList = mutableListOf()
notifyItemRangeRemoved(0, itemCount)
}
currentList = data.toMutableList()
notifyItemRangeInserted(0, currentList.size)
}
} | 0 | Kotlin | 3 | 30 | 18670da6124d0328b0d323b675d0bafdb4df45f6 | 3,158 | Android_Stock_Price | Apache License 2.0 |
server/server-app/src/main/kotlin/projektor/auth/AuthConfig.kt | craigatk | 226,096,594 | false | null | package projektor.auth
import io.ktor.config.ApplicationConfig
import io.ktor.util.KtorExperimentalAPI
@KtorExperimentalAPI
data class AuthConfig(val publishToken: String?) {
companion object {
const val PublishToken = "X-PROJEKTOR-TOKEN"
fun createAuthConfig(applicationConfig: ApplicationConfig) = AuthConfig(
applicationConfig.propertyOrNull("ktor.auth.publishToken")?.getString()
)
}
}
| 18 | null | 9 | 47 | cf3f30efcf5e06dcd22424176f0956d44ce60c78 | 441 | projektor | MIT License |
integration-test-r2dbc/src/mariadb/kotlin/integration/r2dbc/mariadb/R2dbcMariaDbSetting.kt | komapper | 349,909,214 | false | null | package integration.r2dbc.mariadb
import integration.core.MariaDbSetting
import io.r2dbc.spi.ConnectionFactoryOptions
import io.r2dbc.spi.Option
import org.komapper.core.ExecutionOptions
import org.komapper.r2dbc.R2dbcDatabase
import org.testcontainers.containers.MariaDBContainer
import org.testcontainers.containers.MariaDBContainerProvider
import org.testcontainers.containers.MariaDBR2DBCDatabaseContainer
import org.testcontainers.jdbc.ConnectionUrl
@Suppress("unused")
class R2dbcMariaDbSetting(private val url: String) :
MariaDbSetting<R2dbcDatabase> {
private val options: ConnectionFactoryOptions by lazy {
val connectionUrl = ConnectionUrl.newInstance(url)
val container = MariaDBContainerProvider().newInstance(connectionUrl) as MariaDBContainer<*>
val r2dbcContainer = MariaDBR2DBCDatabaseContainer(container)
r2dbcContainer.start()
r2dbcContainer.configure(
ConnectionFactoryOptions.builder()
.option(ConnectionFactoryOptions.DRIVER, "pool")
.option(ConnectionFactoryOptions.PROTOCOL, "mariadb")
.option(Option.valueOf("initialSize"), 2)
.build(),
)
}
override val database: R2dbcDatabase
get() = R2dbcDatabase(
options = options,
executionOptions = ExecutionOptions(batchSize = 2),
)
}
| 8 | Kotlin | 4 | 97 | 851b313c66645d60f2e86934a5036efbe435396a | 1,384 | komapper | Apache License 2.0 |
app/src/main/java/com/cats_app/cats/CatsActivity.kt | AqeelMirza | 700,673,897 | false | {"Kotlin": 10221} | package com.cats_app.cats
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.ui.Modifier
import androidx.hilt.navigation.compose.hiltViewModel
import com.cats_app.ui.theme.CatsAppTheme
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class CatsActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
CatsAppTheme {
val viewModel: CatsViewModel = hiltViewModel()
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
CatPage(catsList = viewModel.state.value.catsList)
}
}
}
}
} | 0 | Kotlin | 0 | 1 | 01c60c96f766b4831ee53898f0dc2f33e3b0b2bd | 1,019 | Cats-App | MIT License |
plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/details/model/GHPRDetailsViewModel.kt | allotria | 40,114,891 | true | null | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.plugins.github.pullrequest.ui.details.model
import kotlinx.coroutines.flow.StateFlow
import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestState
import org.jetbrains.plugins.github.pullrequest.data.GHPRMergeabilityState
internal interface GHPRDetailsViewModel {
val titleState: StateFlow<String>
val descriptionState: StateFlow<String>
val reviewMergeState: StateFlow<GHPullRequestState>
val isDraftState: StateFlow<Boolean>
val number: String
val url: String
val viewerDidAuthor: Boolean
val mergeabilityState: StateFlow<GHPRMergeabilityState?>
val hasConflictsState: StateFlow<Boolean?>
val isRestrictedState: StateFlow<Boolean>
val checksState: StateFlow<GHPRMergeabilityState.ChecksState>
val requiredApprovingReviewsCountState: StateFlow<Int>
} | 0 | null | 0 | 0 | 9b9e3972a437d1a08fc73370fb09b9f45527dd2a | 936 | intellij-community | Apache License 2.0 |
me-api/src/main/kotlin/shop/hyeonme/domain/auth/usecase/LogoutUseCase.kt | TEAM-hyeonme | 776,784,109 | false | {"Kotlin": 120635, "Dockerfile": 204} | package shop.hyeonme.domain.auth.usecase
import shop.hyeonme.common.annotation.UseCase
import shop.hyeonme.domain.auth.service.AuthService
import shop.hyeonme.domain.user.service.UserService
@UseCase
class LogoutUseCase(
private val userService: UserService,
private val authService: AuthService
) {
fun execute(token: String) {
val userId = userService.findCurrentUserId()
val refreshToken = authService.queryRefreshToken(token)
authService.deleteRefreshToken(refreshToken)
}
} | 0 | Kotlin | 0 | 0 | 646621f5577418523de44ed3a229d19879ee7193 | 521 | ME-server | MIT License |
src/test/kotlin/dilivia/s2/region/S2PolylineUnitTest.kt | Enovea | 409,487,197 | false | {"Kotlin": 3249710} | /*
* Copyright © 2021 Enovea (<EMAIL>)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dilivia.s2.region
import dilivia.math.M_PI
import dilivia.math.vectors.times
import dilivia.s2.S1Angle
import dilivia.s2.S1Angle.Companion.times
import dilivia.s2.S2Debug
import dilivia.s2.S2Factory.makePolyline
import dilivia.s2.S2LatLng
import dilivia.s2.S2Point
import dilivia.s2.S2PointUtil
import dilivia.s2.S2Random
import mu.KotlinLogging
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import kotlin.math.abs
import kotlin.math.cos
import kotlin.math.pow
import kotlin.math.sin
import kotlin.math.tan
class S2PolylineUnitTest {
private val logger = KotlinLogging.logger {}
@Test
fun basic() {
val vertices = emptyList<S2Point>().toMutableList()
var empty = S2Polyline(vertices)
assertThat(empty.rectBound).isEqualTo(S2LatLngRect.empty())
empty = empty.reversed()
assertThat(empty.numVertices).isEqualTo(0)
val latlngs = listOf(
S2LatLng.fromDegrees(0, 0),
S2LatLng.fromDegrees(0, 90),
S2LatLng.fromDegrees(0, 180)
)
var semiEquator = S2Polyline.fromLatLng(latlngs)
assertThat(S2PointUtil.approxEquals(semiEquator.interpolate(0.5), S2Point(0, 1, 0))).isTrue()
semiEquator = semiEquator.reversed()
assertThat(semiEquator.vertex(2)).isEqualTo(S2Point(1, 0, 0))
}
@Test
fun getLengthAndCentroid() {
// Construct random great circles and divide them randomly into segments.
// Then make sure that the length and centroid are correct. Note that
// because of the way the centroid is computed, it does not matter how
// we split the great circle into segments.
repeat(100) {
// Choose a coordinate frame for the great circle.
val (x, y, _) = S2Random.randomFrame()
val vertices = mutableListOf<S2Point>()
var theta = 0.0
while (theta < 2 * M_PI) {
val p = cos(theta) * x + sin(theta) * y
if (vertices.isEmpty() || p != vertices.last())
vertices.add(p)
theta += S2Random.randomDouble().pow(10.0)
}
// Close the circle.
vertices.add(vertices[0])
val line = S2Polyline(vertices)
val length = line.length
assertThat(abs(length.radians - 2 * M_PI) <= 2e-14).isTrue()
val centroid = line.centroid
assertThat(centroid.norm() <= 2e-14).isTrue()
}
}
@Test
fun mayIntersect() {
val vertices = mutableListOf(
S2Point(1.0, -1.1, 0.8).normalize(),
S2Point(1.0, -0.8, 1.1).normalize()
)
val line = S2Polyline(vertices)
for (face in 0..5) {
val cell = S2Cell.fromFace(face)
assertThat(line.mayIntersect(cell)).isEqualTo((face and 1) == 0)
}
}
@Test
fun interpolate() {
var vertices = mutableListOf(
S2Point(1, 0, 0),
S2Point(0, 1, 0),
S2Point(0, 1, 1).normalize(),
S2Point(0, 0, 1)
)
val line = S2Polyline(vertices)
assertThat(line.interpolate(-0.1)).isEqualTo(vertices[0])
assertThat(S2PointUtil.approxEquals(line.interpolate(0.1), S2Point(1.0, tan(0.2 * M_PI / 2), 0.0).normalize())).isTrue()
assertThat(S2PointUtil.approxEquals(line.interpolate(0.25), S2Point(1, 1, 0).normalize())).isTrue()
assertThat(line.interpolate(0.5)).isEqualTo(vertices[1])
assertThat(S2PointUtil.approxEquals(vertices[2], line.interpolate(0.75))).isTrue()
val (vertex0, next_vertex0) = line.getSuffix(-0.1)
assertThat(vertex0).isEqualTo(vertices[0])
assertThat(next_vertex0).isEqualTo(1)
val (vertex2, next_vertex2) = line.getSuffix(0.75)
assertThat(S2PointUtil.approxEquals(vertices[2], vertex2)).isTrue()
assertThat(next_vertex2).isEqualTo(3)
val (vertex3, next_vertex3) = line.getSuffix(1.1)
assertThat(vertex3).isEqualTo(vertices[3])
assertThat(next_vertex3).isEqualTo(4)
// Check the case where the interpolation fraction is so close to 1 that
// the interpolated point is identical to the last vertex.
vertices = mutableListOf(
S2Point(1, 1, 1).normalize(),
S2Point(1.0, 1.0, 1 + 1e-15).normalize(),
S2Point(1.0, 1.0, 1 + 2e-15).normalize()
)
val shortLine = S2Polyline(vertices)
val (vertex, next_vertex) = shortLine.getSuffix(1.0 - 2e-16)
assertThat(vertex).isEqualTo(vertices[2])
assertThat(next_vertex).isEqualTo(3)
}
@Test
fun unInterpolate() {
val vertices = mutableListOf( S2Point(1, 0, 0) )
val pointLine = S2Polyline(vertices)
assertThat(pointLine.unInterpolate(S2Point(0, 1, 0), 1)).isZero()
vertices.add(S2Point(0, 1, 0))
vertices.add(S2Point(0, 1, 1).normalize())
vertices.add(S2Point(0, 0, 1))
val line = S2Polyline(vertices)
var interpolated: Pair<S2Point, Int>
interpolated = line.getSuffix(-0.1)
assertThat(line.unInterpolate(interpolated.first, interpolated.second)).isEqualTo(0.0)
interpolated = line.getSuffix(0.0)
assertThat(line.unInterpolate(interpolated.first, interpolated.second)).isEqualTo(0.0)
interpolated = line.getSuffix(0.5)
assertThat(line.unInterpolate(interpolated.first, interpolated.second)).isEqualTo(0.5)
interpolated = line.getSuffix(0.75)
assertThat(line.unInterpolate(interpolated.first, interpolated.second)).isEqualTo(0.75)
interpolated = line.getSuffix(1.1)
assertThat(line.unInterpolate(interpolated.first, interpolated.second)).isEqualTo(1.0)
// Check that the return value is clamped to 1.0.
assertThat(line.unInterpolate(S2Point(0, 1, 0), vertices.size)).isEqualTo(1.0)
}
@Test
fun project() {
val latlngs = listOf(
S2LatLng.fromDegrees(0, 0), S2LatLng.fromDegrees(0, 1),
S2LatLng.fromDegrees(0, 2), S2LatLng.fromDegrees(1, 2)
)
val line = S2Polyline.fromLatLng(latlngs)
var projected = line.project(S2LatLng.fromDegrees(0.5, -0.5).toPoint())
assertThat(S2PointUtil.approxEquals(projected.first, S2LatLng.fromDegrees(0, 0).toPoint())).isTrue()
assertThat(projected.second).isEqualTo(1)
projected = line.project(S2LatLng.fromDegrees(0.5, 0.5).toPoint())
assertThat(S2PointUtil.approxEquals(projected.first, S2LatLng.fromDegrees(0.0, 0.5).toPoint())).isTrue()
assertThat(projected.second).isEqualTo(1)
projected = line.project(S2LatLng.fromDegrees(0.5, 1.0).toPoint())
assertThat(S2PointUtil.approxEquals(projected.first, S2LatLng.fromDegrees(0, 1).toPoint())).isTrue()
assertThat(projected.second).isEqualTo(2)
projected = line.project(S2LatLng.fromDegrees(-0.5, 2.5).toPoint())
assertThat(S2PointUtil.approxEquals(projected.first, S2LatLng.fromDegrees(0, 2).toPoint())).isTrue()
assertThat(projected.second).isEqualTo(3)
projected = line.project(S2LatLng.fromDegrees(2, 2).toPoint())
assertThat(S2PointUtil.approxEquals(projected.first, S2LatLng.fromDegrees(1, 2).toPoint())).isTrue()
assertThat(projected.second).isEqualTo(4)
}
@Test
fun isOnRight() {
var latlngs = listOf(
S2LatLng.fromDegrees(0, 0), S2LatLng.fromDegrees(0, 1),
S2LatLng.fromDegrees(0, 2), S2LatLng.fromDegrees(1, 2)
)
val line = S2Polyline.fromLatLng(latlngs)
assertThat(line.isOnRight(S2LatLng.fromDegrees(-0.5, 0.5).toPoint())).isTrue()
assertThat(line.isOnRight(S2LatLng.fromDegrees(0.5, -0.5).toPoint())).isFalse()
assertThat(line.isOnRight(S2LatLng.fromDegrees(0.5, 0.5).toPoint())).isFalse()
assertThat(line.isOnRight(S2LatLng.fromDegrees(0.5, 1.0).toPoint())).isFalse()
assertThat(line.isOnRight(S2LatLng.fromDegrees(-0.5, 2.5).toPoint())).isTrue()
assertThat(line.isOnRight(S2LatLng.fromDegrees(1.5, 2.5).toPoint())).isTrue()
// Explicitly test the case where the closest point is an interior vertex.
latlngs = listOf(
S2LatLng.fromDegrees(0, 0), S2LatLng.fromDegrees(0, 1),
S2LatLng.fromDegrees(-1, 0)
)
val line2 = S2Polyline.fromLatLng(latlngs)
// The points are chosen such that they are on different sides of the two
// edges that the interior vertex is on.
assertThat(line2.isOnRight(S2LatLng.fromDegrees(-0.5, 5.0).toPoint())).isFalse()
assertThat(line2.isOnRight(S2LatLng.fromDegrees(5.5, 5.0).toPoint())).isFalse()
}
@Test
fun intersectsEmptyPolyline() {
val line1 = makePolyline("1:1, 4:4")
val emptyPolyline = S2Polyline()
assertThat(emptyPolyline.intersects(line1)).isFalse()
}
@Test
fun intersectsOnePointPolyline() {
val line1 = makePolyline("1:1, 4:4")
val line2 = makePolyline("1:1")
assertThat(line1.intersects(line2)).isFalse()
}
@Test
fun intersects() {
val line1 = makePolyline("1:1, 4:4")
val smallCrossing = makePolyline("1:2, 2:1")
val smallNoncrossing = makePolyline("1:2, 2:3")
val bigCrossing = makePolyline("1:2, 2:3, 4:3")
assertThat(line1.intersects(smallCrossing)).isTrue()
assertThat(line1.intersects(smallNoncrossing)).isFalse()
assertThat(line1.intersects(bigCrossing)).isTrue()
}
@Test
fun intersectsAtVertex() {
val line1 = makePolyline("1:1, 4:4, 4:6")
val line2 = makePolyline("1:1, 1:2")
val line3 = makePolyline("5:1, 4:4, 2:2")
assertThat(line1.intersects(line2)).isTrue()
assertThat(line1.intersects(line3)).isTrue()
}
@Test
fun intersectsVertexOnEdge() {
val horizontalLeftToRight = makePolyline("0:1, 0:3")
val verticalBottomToTop = makePolyline("-1:2, 0:2, 1:2")
val horizontalRightToLeft = makePolyline("0:3, 0:1")
val verticalTopToBottom = makePolyline("1:2, 0:2, -1:2")
assertThat(horizontalLeftToRight.intersects(verticalBottomToTop)).isTrue()
assertThat(horizontalLeftToRight.intersects(verticalTopToBottom)).isTrue()
assertThat(horizontalRightToLeft.intersects(verticalBottomToTop)).isTrue()
assertThat(horizontalRightToLeft.intersects(verticalTopToBottom)).isTrue()
}
fun checkSubsample(polyline_str: String, tolerance_degrees: Double, expected_str: String, check: S2Debug = S2Debug.ALLOW) {
logger.info { """"$polyline_str, tolerance $tolerance_degrees""" }
val polyline = makePolyline(polyline_str, check)
val indices = polyline.subsampleVertices(S1Angle.degrees(tolerance_degrees))
assertThat(indices.joinToString(",")).isEqualTo(expected_str)
}
@Test
fun subsampleVerticesTrivialInputs() {
// No vertices.
checkSubsample("", 1.0, "")
// One vertex.
checkSubsample("0:1", 1.0, "0")
// Two vertices.
checkSubsample("10:10, 11:11", 5.0, "0,1")
// Three points on a straight line.
// In theory, zero tolerance should work, but in practice there are floating
// point errors.
checkSubsample("-1:0, 0:0, 1:0", 1e-15, "0,2")
// Zero tolerance on a non-straight line.
checkSubsample("-1:0, 0:0, 1:1", 0.0, "0,1,2")
// Negative tolerance should return all vertices.
checkSubsample("-1:0, 0:0, 1:1", -1.0, "0,1,2")
// Non-zero tolerance with a straight line.
checkSubsample("0:1, 0:2, 0:3, 0:4, 0:5", 1.0, "0,4")
// And finally, verify that we still do something reasonable if the client
// passes in an invalid polyline with two or more adjacent vertices.
checkSubsample("0:1, 0:1, 0:1, 0:2", 0.0, "0,3", check = S2Debug.DISABLE)
}
@Test
fun subsampleVerticesSimpleExample() {
val polyStr = "0:0, 0:1, -1:2, 0:3, 0:4, 1:4, 2:4.5, 3:4, 3.5:4, 4:4"
checkSubsample(polyStr, 3.0, "0,9")
checkSubsample(polyStr, 2.0, "0,6,9")
checkSubsample(polyStr, 0.9, "0,2,6,9")
checkSubsample(polyStr, 0.4, "0,1,2,3,4,6,9")
checkSubsample(polyStr, 0.0, "0,1,2,3,4,5,6,7,8,9")
}
@Test
fun subsampleVerticesGuarantees() {
// Check that duplicate vertices are never generated.
checkSubsample("10:10, 12:12, 10:10", 5.0, "0")
checkSubsample("0:0, 1:1, 0:0, 0:120, 0:130", 5.0, "0,3,4")
// Check that points are not collapsed if they would create a line segment
// longer than 90 degrees, and also that the code handles original polyline
// segments longer than 90 degrees.
checkSubsample("90:0, 50:180, 20:180, -20:180, -50:180, -90:0, 30:0, 90:0", 5.0, "0,2,4,5,6,7")
// Check that the output polyline is parametrically equivalent and not just
// geometrically equivalent, i.e. that backtracking is preserved. The
// algorithm achieves this by requiring that the points must be encountered
// in increasing order of distance along each output segment, except for
// points that are within "tolerance" of the first vertex of each segment.
checkSubsample("10:10, 10:20, 10:30, 10:15, 10:40", 5.0, "0,2,3,4")
checkSubsample("10:10, 10:20, 10:30, 10:10, 10:30, 10:40", 5.0, "0,2,3,5")
checkSubsample("10:10, 12:12, 9:9, 10:20, 10:30", 5.0, "0,4")
}
fun testEquals(a_str: String, b_str: String, max_error: S1Angle): Boolean {
val a = makePolyline(a_str)
val b = makePolyline(b_str)
return a.approxEquals(b, max_error)
}
@Test
fun approxEquals() {
val degree = S1Angle.degrees(1)
// Close lines, differences within max_error.
assertThat(testEquals("0:0, 0:10, 5:5", "0:0.1, -0.1:9.9, 5:5.2", 0.5 * degree)).isTrue()
// Close lines, differences outside max_error.
assertThat(testEquals("0:0, 0:10, 5:5", "0:0.1, -0.1:9.9, 5:5.2", 0.01 * degree)).isFalse()
// Same line, but different number of vertices.
assertThat(testEquals("0:0, 0:10, 0:20", "0:0, 0:20", 0.1 * degree)).isFalse()
// Same vertices, in different order.
assertThat(testEquals("0:0, 5:5, 0:10", "5:5, 0:10, 0:0", 0.1 * degree)).isFalse()
}
@Test
fun polylineShapeBasic() {
val polyline = makePolyline("0:0, 1:0, 1:1, 2:1")
val shape = S2Polyline.Shape(polyline = polyline)
assertThat(shape.polyline).isEqualTo(polyline)
assertThat(shape.numEdges).isEqualTo(3)
assertThat(shape.numChains).isEqualTo(1)
assertThat(shape.chain(0).start).isEqualTo(0)
assertThat(shape.chain(0).length).isEqualTo(3)
val edge2 = shape . edge (2)
assertThat(edge2.v0).isEqualTo(S2LatLng.fromDegrees(1, 1).toPoint())
assertThat(edge2.v1).isEqualTo(S2LatLng.fromDegrees(2, 1).toPoint())
assertThat(shape.dimension).isEqualTo(1)
assertThat(shape.isEmpty()).isFalse()
assertThat(shape.isFull()).isFalse()
assertThat(shape.getReferencePoint().contained).isFalse()
}
@Test
fun polylineShapeEmptyPolyline() {
val polyline = S2Polyline()
val shape = S2Polyline.Shape(polyline = polyline)
assertThat(shape.numEdges).isEqualTo(0)
assertThat(shape.numChains).isEqualTo(0)
assertThat(shape.isEmpty()).isTrue()
assertThat(shape.isFull()).isFalse()
assertThat(shape.getReferencePoint().contained).isFalse()
}
fun testNearlyCovers(a_str: String, b_str: String, max_error_degrees: Double, expect_b_covers_a: Boolean, expect_a_covers_b: Boolean, check: S2Debug = S2Debug.ALLOW) {
logger.info { "a=\"$a_str\", b=\"$b_str\", max error=$max_error_degrees" }
val a = makePolyline(a_str, check)
val b = makePolyline(b_str, check)
val maxError = S1Angle.degrees(max_error_degrees)
assertThat(b.nearlyCovers(a, maxError)).isEqualTo(expect_b_covers_a)
assertThat(a.nearlyCovers(b, maxError)).isEqualTo(expect_a_covers_b)
}
@Test
fun polylineCoveringTestPolylineOverlapsSelf() {
val pline = "1:1, 2:2, -1:10"
testNearlyCovers(pline, pline, 1e-10, true, true)
}
@Test
fun polylineCoveringTestPolylineDoesNotOverlapReverse() {
testNearlyCovers("1:1, 2:2, -1:10", "-1:10, 2:2, 1:1", 1e-10, false, false)
}
@Test
fun polylineCoveringTestPolylineOverlapsEquivalent() {
// These two polylines trace the exact same polyline, but the second one uses
// three points instead of two.
testNearlyCovers("1:1, 2:1", "1:1, 1.5:1, 2:1", 1e-10, true, true)
}
@Test
fun polylineCoveringTestShortCoveredByLong() {
// The second polyline is always within 0.001 degrees of the first polyline,
// but the first polyline is too long to be covered by the second.
testNearlyCovers(
"-5:1, 10:1, 10:5, 5:10", "9:1, 9.9995:1, 10.0005:5", 1e-3, false, true)
}
@Test
fun polylineCoveringTestPartialOverlapOnly() {
// These two polylines partially overlap each other, but neither fully
// overlaps the other.
testNearlyCovers("-5:1, 10:1", "0:1, 20:1", 1.0, false, false)
}
@Test
fun polylineCoveringTestShortBacktracking() {
// Two lines that backtrack a bit (less than 1.5 degrees) on different edges.
// A simple greedy matching algorithm would fail on this example.
val t1 = "0:0, 0:2, 0:1, 0:4, 0:5"
val t2 = "0:0, 0:2, 0:4, 0:3, 0:5"
testNearlyCovers(t1, t2, 1.5, true, true)
testNearlyCovers(t1, t2, 0.5, false, false)
}
@Test
fun polylineCoveringTestLongBacktracking() {
// Two arcs with opposite direction do not overlap if the shorter arc is
// longer than max_error, but do if the shorter arc is shorter than max-error.
testNearlyCovers("5:1, -5:1", "1:1, 3:1", 1.0, false, false)
testNearlyCovers("5:1, -5:1", "1:1, 3:1", 2.5, false, true)
}
@Test
fun polylineCoveringTestIsResilientToDuplicatePoints() {
// S2Polyines are not generally supposed to contain adjacent, identical
// points, but it happens in practice. We also set S2Debug::DISABLE so
// debug binaries won't abort on such polylines.
testNearlyCovers("0:1, 0:2, 0:2, 0:3", "0:1, 0:1, 0:1, 0:3", 1e-10, true, true, S2Debug.DISABLE)
}
@Test
fun polylineCoveringTestCanChooseBetweenTwoPotentialStartingPoints() {
// Can handle two possible starting points, only one of which leads to finding
// a correct path. In the first polyline, the edge from 0:1.1 to 0:0 and the
// edge from 0:0.9 to 0:2 might be lucrative starting states for covering the
// second polyline, because both edges are with the max_error of 1.5 degrees
// from 0:10. However, only the latter is actually effective.
testNearlyCovers("0:11, 0:0, 0:9, 0:20", "0:10, 0:15", 1.5, false, true)
}
@Test
fun polylineCoveringTestStraightAndWigglyPolylinesCoverEachOther() {
testNearlyCovers("40:1, 20:1",
"39.9:0.9, 40:1.1, 30:1.15, 29:0.95, 28:1.1, 27:1.15, 26:1.05, 25:0.85, 24:1.1, 23:0.9, 20:0.99",
0.2, true, true)
}
@Test
fun polylineCoveringTestMatchStartsAtLastVertex() {
// The first polyline covers the second, but the matching segment starts at
// the last vertex of the first polyline.
testNearlyCovers(
"0:0, 0:2", "0:2, 0:3", 1.5, false, true)
}
@Test
fun polylineCoveringTestMatchStartsAtDuplicatedLastVertex() {
testNearlyCovers(
"0:0, 0:2, 0:2, 0:2", "0:2, 0:3", 1.5, false, true, S2Debug.DISABLE)
}
@Test
fun polylineCoveringTestEmptyPolylines() {
// We expect:
// anything.covers(empty) = true
// empty.covers(nonempty) = false
testNearlyCovers("0:1, 0:2", "", 0.0, false, true)
testNearlyCovers("", "", 0.0, true, true)
}
}
| 0 | Kotlin | 3 | 17 | eb5139ec5c69556e8dc19c864b052e7e45a48b49 | 20,941 | s2-geometry-kotlin | Apache License 2.0 |
app/src/main/java/com/zaneschepke/wireguardautotunnel/service/notification/NotificationService.kt | zaneschepke | 644,710,160 | false | {"Kotlin": 225248, "HTML": 1349} | package com.zaneschepke.wireguardautotunnel.service.notification
import android.app.Notification
import android.app.NotificationManager
import android.app.PendingIntent
interface NotificationService {
fun createNotification(
channelId: String,
channelName: String,
title: String = "",
action: PendingIntent? = null,
actionText: String? = null,
description: String,
showTimestamp: Boolean = false,
importance: Int = NotificationManager.IMPORTANCE_HIGH,
vibration: Boolean = false,
onGoing: Boolean = true,
lights: Boolean = true,
onlyAlertOnce: Boolean = true,
): Notification
}
| 6 | Kotlin | 8 | 96 | 79583e0e61b69312a2c317abbea09409107c8d3e | 684 | wgtunnel | MIT License |
app/src/main/java/com/mb/hunters/ui/base/BaseViewHolder.kt | mboukadir | 112,534,034 | false | null | /*
* Copyright 2017-2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mb.hunters.ui.base
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import kotlinx.android.extensions.LayoutContainer
open class BaseViewHolder(parent: ViewGroup, @LayoutRes layoutResId: Int) :
androidx.recyclerview.widget.RecyclerView.ViewHolder(
LayoutInflater.from(parent.context).inflate(layoutResId, parent, false)
),
LayoutContainer {
override val containerView: View?
get() = itemView
}
| 0 | Kotlin | 1 | 5 | abd083e1fac712ca36cbb38fe874b4664ed1b8b8 | 1,111 | hunters | Apache License 2.0 |
entity-recognition/microsoft-cognitive-services-text-analytics/MicrosoftCognitiveServicesTextAnalyticsEntityRecognition.kt | sekwiatkowski | 137,943,638 | false | null | // For English, set "language" to "en".
data class Document(val id: String, val language: String, val text: String)
data class Entity(
val name : String,
val wikipediaLanguage: String,
val wikipediaId: String,
val wikipediaUrl: String,
val bingId: String)
data class EntityRecognition(val id: String, val entities: List<Entity>)
data class EntityRecognitionResponse (val documents: List<EntityRecognition>)
val host = "https://westeurope.api.cognitive.microsoft.com"
val path = "/text/analytics/v2.0/entities"
val url = host + path
val documents = listOf(Document("1", language, text))
val gson = Gson()
val body = gson.toJson(documents)
val stringResponse = Unirest.post(url)
.header("Content-Type", "application/json")
.header("Ocp-Apim-Subscription-Key", subscriptionKey)
.body(body)
.asString()
.body
val response = gson.fromJson(stringResponse, EntityRecognitionResponse::class.java)
val entities = response.documents.single().entities
| 0 | Java | 21 | 142 | 02b1984a43ce5caefe6da4fb649dd7989e3ae131 | 990 | awesome-ai-services | Creative Commons Attribution 4.0 International |
straight/src/commonMain/kotlin/me/localx/icons/straight/outline/ScrollOld.kt | localhostov | 808,861,591 | false | {"Kotlin": 79430321, "HTML": 331, "CSS": 102} | package me.localx.icons.straight.outline
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.straight.Icons
public val Icons.Outline.ScrollOld: ImageVector
get() {
if (_scrollOld != null) {
return _scrollOld!!
}
_scrollOld = Builder(name = "ScrollOld", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveToRelative(20.0f, 17.0f)
lineTo(20.0f, 4.0f)
curveToRelative(0.0f, -2.209f, -1.791f, -4.0f, -4.0f, -4.0f)
lineTo(3.5f, 0.0f)
curveTo(1.567f, 0.0f, 0.0f, 1.567f, 0.0f, 3.5f)
verticalLineToRelative(3.5f)
horizontalLineToRelative(5.0f)
verticalLineToRelative(13.5f)
curveToRelative(0.0f, 1.933f, 1.567f, 3.5f, 3.5f, 3.5f)
horizontalLineToRelative(12.0f)
curveToRelative(1.933f, 0.0f, 3.5f, -1.567f, 3.5f, -3.5f)
verticalLineToRelative(-3.5f)
horizontalLineToRelative(-4.0f)
close()
moveTo(5.0f, 5.0f)
horizontalLineToRelative(-3.0f)
verticalLineToRelative(-1.5f)
curveToRelative(0.0f, -0.827f, 0.673f, -1.5f, 1.5f, -1.5f)
reflectiveCurveToRelative(1.5f, 0.673f, 1.5f, 1.5f)
verticalLineToRelative(1.5f)
close()
moveTo(10.0f, 20.5f)
curveToRelative(0.0f, 0.827f, -0.673f, 1.5f, -1.5f, 1.5f)
reflectiveCurveToRelative(-1.5f, -0.673f, -1.5f, -1.5f)
verticalLineToRelative(-5.5f)
horizontalLineToRelative(5.0f)
verticalLineToRelative(-2.0f)
horizontalLineToRelative(-5.0f)
verticalLineToRelative(-6.0f)
horizontalLineToRelative(4.0f)
verticalLineToRelative(-2.0f)
horizontalLineToRelative(-4.0f)
verticalLineToRelative(-1.5f)
curveToRelative(0.0f, -0.536f, -0.122f, -1.045f, -0.338f, -1.5f)
horizontalLineToRelative(9.338f)
curveToRelative(1.105f, 0.0f, 2.0f, 0.895f, 2.0f, 2.0f)
verticalLineToRelative(5.0f)
horizontalLineToRelative(-4.0f)
verticalLineToRelative(2.0f)
horizontalLineToRelative(4.0f)
verticalLineToRelative(6.0f)
horizontalLineToRelative(-8.0f)
verticalLineToRelative(3.5f)
close()
moveTo(22.0f, 20.5f)
curveToRelative(0.0f, 0.827f, -0.673f, 1.5f, -1.5f, 1.5f)
horizontalLineToRelative(-8.838f)
curveToRelative(0.216f, -0.455f, 0.338f, -0.963f, 0.338f, -1.5f)
verticalLineToRelative(-1.5f)
horizontalLineToRelative(10.0f)
verticalLineToRelative(1.5f)
close()
}
}
.build()
return _scrollOld!!
}
private var _scrollOld: ImageVector? = null
| 1 | Kotlin | 0 | 5 | cbd8b510fca0e5e40e95498834f23ec73cc8f245 | 3,822 | icons | MIT License |
src/main/kotlin/org/xpathqs/driver/navigation/base/INavigableDelegate.kt | xpathqs | 366,703,320 | false | {"Kotlin": 230690} | package org.xpathqs.driver.navigation.base
interface INavigableDelegate: INavigable {
val nav: INavigable
override fun initNavigation() {
nav.initNavigation()
}
override fun addNavigation(
to: INavigable,
order: Int,
selfState: Int,
state: Int,
globalState: Int,
action: (() -> Unit)?) {
nav.addNavigation(
to,
order,
selfState,
state,
globalState,
action
)
}
override val navOrder: Int
get() = nav.navOrder
override fun navigate(state: Int) {
nav.navigate(state)
}
} | 0 | Kotlin | 0 | 2 | 60eccb672195d82f07bb4713c1018c2816cd0c71 | 663 | driver | MIT License |
domain/src/main/java/com/jamieadkins/gwent/domain/latest/GetLatestPatchNotesUseCase.kt | jamieadkins95 | 75,647,202 | false | {"Kotlin": 340777, "Java": 15619} | package com.jamieadkins.gwent.domain.latest
import com.jamieadkins.gwent.domain.LocaleRepository
import com.jamieadkins.gwent.domain.SchedulerProvider
import io.reactivex.Observable
import javax.inject.Inject
class GetLatestPatchNotesUseCase @Inject constructor(
private val localeRepository: LocaleRepository,
private val newsRepository: NewsRepository,
private val schedulerProvider: SchedulerProvider
) {
fun getPatchNotes(): Observable<GwentNewsArticle> {
return localeRepository.getNewsLocale()
.switchMap(newsRepository::getLatestPatchNotes)
.subscribeOn(schedulerProvider.io())
.observeOn(schedulerProvider.ui())
}
} | 4 | Kotlin | 1 | 6 | e3f1e264f8b69ed2903656c95f45611f180283d4 | 690 | Roach | Apache License 2.0 |
educational-core/src/com/jetbrains/edu/learning/statistics/FeedbackSender.kt | JetBrains | 43,696,115 | false | null | package com.jetbrains.edu.learning.statistics
import com.intellij.ide.util.PropertiesComponent
import com.intellij.notification.Notification
import com.intellij.notification.NotificationListener
import com.intellij.notification.NotificationType
import com.intellij.notification.impl.NotificationFullContent
import com.intellij.openapi.project.Project
import com.intellij.util.PlatformUtils
import com.jetbrains.edu.learning.EduBrowser
import com.jetbrains.edu.learning.EduNames
import com.jetbrains.edu.learning.courseFormat.Course
import javax.swing.event.HyperlinkEvent
fun showNotification(student : Boolean, course: Course, project: Project) {
val feedbackUrl = feedbackUrlTemplate
.replace("\$PRODUCT", productMap[PlatformUtils.getPlatformPrefix()] ?:
PlatformUtils.getPlatformPrefix())
.replace("\$COURSE", course.name)
.replace("\$MODE", if (course.courseMode == EduNames.STUDY) "Learner" else "Educator")
val product = if (PlatformUtils.isPyCharmEducational()) "PyCharm Edu" else "EduTools"
val language = course.languageID
var content = if (student) studentTemplate else creatorTemplate
content = content.replace("\$PRODUCT", product)
.replace("\$URL", feedbackUrl)
.replace("\$LANGUAGE", language.toLowerCase().capitalize())
val notification = MyNotification(content, feedbackUrl)
PropertiesComponent.getInstance().setValue(feedbackAsked, true)
notification.notify(project)
}
class MyNotification(content: String, feedbackUrl : String) :
Notification("EduTools",
"Congratulations", content, NotificationType.INFORMATION,
object : NotificationListener.Adapter() {
override fun hyperlinkActivated(notification: Notification, e: HyperlinkEvent) {
EduBrowser.getInstance().browse(feedbackUrl)
}
}), NotificationFullContent
fun isFeedbackAsked() : Boolean = PropertiesComponent.getInstance().getBoolean(feedbackAsked)
const val feedbackAsked = "askFeedbackNotification"
const val feedbackUrlTemplate = "https://www.jetbrains.com/feedback/feedback.jsp?" +
"product=EduTools&ide=\$PRODUCT&course=\$COURSE&mode=\$MODE"
const val creatorTemplate = "<html>You’ve just created your first tasks with \$PRODUCT!\n" +
"Please take a moment to <a href=\"\$URL\">share</a> your experience and help us make teaching \$LANGUAGE better.</html>"
const val studentTemplate = "<html>You’ve just completed your first lesson with \$PRODUCT!\n" +
"Please take a moment to <a href=\"\$URL\">share</a> your experience and help us make learning \$LANGUAGE better.</html>"
val productMap = hashMapOf(
Pair(PlatformUtils.PYCHARM_CE_PREFIX, "PCC"),
Pair(PlatformUtils.PYCHARM_PREFIX, "PCP"),
Pair(PlatformUtils.PYCHARM_EDU_PREFIX, "PCE"),
Pair(PlatformUtils.IDEA_CE_PREFIX, "IIC"),
Pair(PlatformUtils.IDEA_PREFIX, "IIU"),
Pair("AndroidStudio", "AI"),
Pair(PlatformUtils.WEB_PREFIX, "WS"),
Pair(PlatformUtils.PHP_PREFIX, "PS"),
Pair(PlatformUtils.APPCODE_PREFIX, "AC"),
Pair(PlatformUtils.CLION_PREFIX, "CL"),
Pair(PlatformUtils.DBE_PREFIX, "DG"),
Pair(PlatformUtils.GOIDE_PREFIX, "GO"),
Pair(PlatformUtils.RIDER_PREFIX, "RD"),
Pair(PlatformUtils.RUBY_PREFIX, "RM"))
| 1 | null | 40 | 99 | cfc24fe13318de446b8adf6e05d1a7c15d9511b5 | 3,374 | educational-plugin | Apache License 2.0 |
IndeterminateRegionPainter/src/main/kotlin/example/App.kt | aterai | 158,348,575 | false | null | package example
import java.awt.*
import java.awt.event.HierarchyEvent
import java.awt.geom.Path2D
import java.awt.geom.Rectangle2D
import java.beans.PropertyChangeEvent
import java.beans.PropertyChangeListener
import javax.swing.*
import javax.swing.plaf.nimbus.AbstractRegionPainter
private var worker: SwingWorker<String, Unit?>? = null
fun makeUI(): Component {
val model = DefaultBoundedRangeModel()
val progressBar0 = JProgressBar(model)
val progressBar1 = JProgressBar(model)
val d = UIDefaults()
d["ProgressBar[Enabled+Indeterminate].foregroundPainter"] = IndeterminateRegionPainter()
progressBar1.putClientProperty("Nimbus.Overrides", d)
val p = JPanel(GridLayout(2, 1)).also {
it.add(makeTitledPanel("Default", progressBar0))
it.add(makeTitledPanel("ProgressBar[Indeterminate].foregroundPainter", progressBar1))
}
val button = JButton("Test start")
button.addActionListener {
worker?.takeUnless { it.isDone }?.cancel(true)
progressBar0.isIndeterminate = true
progressBar1.isIndeterminate = true
worker = BackgroundTask().also {
it.addPropertyChangeListener(ProgressListener(progressBar0))
it.addPropertyChangeListener(ProgressListener(progressBar1))
it.execute()
}
}
val box = Box.createHorizontalBox()
box.add(Box.createHorizontalGlue())
box.add(button)
box.add(Box.createHorizontalStrut(5))
return JPanel(BorderLayout()).also {
it.addHierarchyListener { e ->
val b = e.changeFlags and HierarchyEvent.DISPLAYABILITY_CHANGED.toLong() != 0L
if (b && !e.component.isDisplayable) {
worker?.cancel(true)
worker = null
}
}
it.add(p)
it.add(box, BorderLayout.SOUTH)
it.border = BorderFactory.createEmptyBorder(5, 5, 5, 5)
it.preferredSize = Dimension(320, 240)
}
}
private fun makeTitledPanel(
title: String,
cmp: Component,
): Component {
val p = JPanel(GridBagLayout())
p.border = BorderFactory.createTitledBorder(title)
val c = GridBagConstraints()
c.weightx = 1.0
c.fill = GridBagConstraints.HORIZONTAL
c.insets = Insets(5, 5, 5, 5)
p.add(cmp, c)
return p
}
private class BackgroundTask : SwingWorker<String, Unit?>() {
@Throws(InterruptedException::class)
override fun doInBackground(): String {
Thread.sleep(5000)
var current = 0
val lengthOfTask = 100
while (current <= lengthOfTask && !isCancelled) {
doSomething()
progress = 100 * current / lengthOfTask
current++
}
return "Done"
}
@Throws(InterruptedException::class)
fun doSomething() {
Thread.sleep(50)
}
}
private class ProgressListener(
private val progressBar: JProgressBar,
) : PropertyChangeListener {
init {
progressBar.value = 0
}
override fun propertyChange(e: PropertyChangeEvent) {
if ("progress" == e.propertyName) {
progressBar.isIndeterminate = false
val progress = e.newValue as? Int ?: 0
progressBar.value = progress
}
}
}
private class IndeterminateRegionPainter : AbstractRegionPainter() {
private val color17 = decodeColor(NIMBUS_ORANGE, .0000000000f, .00000000f, .0000000000f, -156)
private val color18 = decodeColor(NIMBUS_ORANGE, -.0157965120f, .02094239f, -.1529411700f, 0)
private val color19 = decodeColor(NIMBUS_ORANGE, -.0043216050f, .02094239f, -.0745098000f, 0)
private val color20 = decodeColor(NIMBUS_ORANGE, -.0080213990f, .02094239f, -.1019607800f, 0)
private val color21 = decodeColor(NIMBUS_ORANGE, -.0117069040f, -.17905760f, -.0235294100f, 0)
private val color22 = decodeColor(NIMBUS_ORANGE, -.0486912540f, .02094239f, -.3019608000f, 0)
private val color23 = decodeColor(NIMBUS_ORANGE, .0039403290f, -.73753220f, .1764705800f, 0)
private val color24 = decodeColor(NIMBUS_ORANGE, .0055067390f, -.46764207f, .1098039150f, 0)
private val color25 = decodeColor(NIMBUS_ORANGE, .0042127445f, -.18595415f, .0470588200f, 0)
private val color26 = decodeColor(NIMBUS_ORANGE, .0047626942f, .02094239f, .0039215684f, 0)
private val color27 = decodeColor(NIMBUS_ORANGE, .0047626942f, -.15147138f, .1607843000f, 0)
private val color28 = decodeColor(NIMBUS_ORANGE, .0106654760f, -.27317524f, .2509803800f, 0)
private val ctx = PaintContext(Insets(5, 5, 5, 5), Dimension(29, 19), false)
private var rect: Rectangle2D = Rectangle2D.Float()
private var path: Path2D = Path2D.Float()
public override fun doPaint(
g: Graphics2D,
c: JComponent,
width: Int,
height: Int,
extendedCacheKeys: Array<Any>?,
) {
path = decodePath1()
g.paint = color17
g.fill(path)
rect = decodeRect3()
g.paint = decodeGradient5(rect)
g.fill(rect)
rect = decodeRect4()
g.paint = decodeGradient6(rect)
g.fill(rect)
}
public override fun getPaintContext() = ctx
private fun decodePath1(): Path2D {
path.reset()
path.moveTo(decodeX(1f).toDouble(), decodeY(.21111111f).toDouble())
path.curveTo(
decodeAnchorX(1f, -2f).toDouble(),
decodeAnchorY(.21111111f, 0f).toDouble(),
decodeAnchorX(.21111111f, 0f).toDouble(),
decodeAnchorY(1f, -2f).toDouble(),
decodeX(.21111111f).toDouble(),
decodeY(1f).toDouble(),
)
path.curveTo(
decodeAnchorX(.21111111f, 0f).toDouble(),
decodeAnchorY(1f, 2f).toDouble(),
decodeAnchorX(.21111111f, 0f).toDouble(),
decodeAnchorY(2f, -2f).toDouble(),
decodeX(.21111111f).toDouble(),
decodeY(2f).toDouble(),
)
path.curveTo(
decodeAnchorX(.21111111f, 0f).toDouble(),
decodeAnchorY(2f, 2f).toDouble(),
decodeAnchorX(1f, -2f).toDouble(),
decodeAnchorY(2.8222225f, 0f).toDouble(),
decodeX(1f).toDouble(),
decodeY(2.8222225f).toDouble(),
)
path.curveTo(
decodeAnchorX(1f, 2f).toDouble(),
decodeAnchorY(2.8222225f, 0f).toDouble(),
decodeAnchorX(3f, 0f).toDouble(),
decodeAnchorY(2.8222225f, 0f).toDouble(),
decodeX(3f).toDouble(),
decodeY(2.8222225f).toDouble(),
)
path.lineTo(decodeX(3f).toDouble(), decodeY(2.3333333f).toDouble())
path.lineTo(decodeX(.6666667f).toDouble(), decodeY(2.3333333f).toDouble())
path.lineTo(decodeX(.6666667f).toDouble(), decodeY(.6666667f).toDouble())
path.lineTo(decodeX(3f).toDouble(), decodeY(.6666667f).toDouble())
path.lineTo(decodeX(3f).toDouble(), decodeY(.2f).toDouble())
path.curveTo(
decodeAnchorX(3f, 0f).toDouble(),
decodeAnchorY(.2f, 0f).toDouble(),
decodeAnchorX(1f, 2f).toDouble(),
decodeAnchorY(.21111111f, 0f).toDouble(),
decodeX(1f).toDouble(),
decodeY(.21111111f).toDouble(),
)
path.closePath()
return path
}
private fun decodeRect3() = rect.also {
it.setRect(
decodeX(.4f).toDouble(),
decodeY(.4f).toDouble(),
(decodeX(3f) - decodeX(.4f)).toDouble(),
(decodeY(2.6f) - decodeY(.4f)).toDouble(),
)
}
private fun decodeRect4() = rect.also {
it.setRect(
decodeX(.6f).toDouble(),
decodeY(.6f).toDouble(),
(decodeX(2.8f) - decodeX(.6f)).toDouble(),
(decodeY(2.4f) - decodeY(.6f)).toDouble(),
)
}
private fun decodeGradient5(s: Shape): Paint {
val bounds = s.bounds2D
val x = bounds.x.toFloat()
val y = bounds.y.toFloat()
val w = bounds.width.toFloat()
val h = bounds.height.toFloat()
return decodeGradient(
x + .5f * w,
y,
x + .5f * w,
y + h,
floatArrayOf(
.038709678f,
.05483871f,
.07096774f,
.28064516f,
.4903226f,
.6967742f,
.9032258f,
.9241935f,
.9451613f,
),
arrayOf(
color18,
decodeColor(color18, color19, .5f),
color19,
decodeColor(color19, color20, .5f),
color20,
decodeColor(color20, color21, .5f),
color21,
decodeColor(color21, color22, .5f),
color22,
),
)
}
private fun decodeGradient6(s: Shape): Paint {
val bounds = s.bounds2D
val x = bounds.x.toFloat()
val y = bounds.y.toFloat()
val w = bounds.width.toFloat()
val h = bounds.height.toFloat()
return decodeGradient(
x + .5f * w,
y,
x + .5f * w,
y + h,
floatArrayOf(
.038709678f,
.061290324f,
.08387097f,
.27258065f,
.46129033f,
.4903226f,
.5193548f,
.71774197f,
.91612905f,
.92419356f,
.93225807f,
),
arrayOf(
color23,
decodeColor(color23, color24, .5f),
color24,
decodeColor(color24, color25, .5f),
color25,
decodeColor(color25, color26, .5f),
color26,
decodeColor(color26, color27, .5f),
color27,
decodeColor(color27, color28, .5f),
color28,
),
)
}
companion object {
private const val NIMBUS_ORANGE = "nimbusOrange"
}
}
fun main() {
EventQueue.invokeLater {
runCatching {
// UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName())
UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel")
}.onFailure {
it.printStackTrace()
Toolkit.getDefaultToolkit().beep()
}
JFrame().apply {
defaultCloseOperation = WindowConstants.EXIT_ON_CLOSE
contentPane.add(makeUI())
pack()
setLocationRelativeTo(null)
isVisible = true
}
}
}
| 0 | null | 6 | 9 | 47a0c684f64c3db2c8b631b2c20c6c7f9205bcab | 9,389 | kotlin-swing-tips | MIT License |
plugin/src/test/kotlin/utils/utils.kt | rendner | 336,657,251 | false | {"Python": 2197537, "Kotlin": 411371, "Dockerfile": 5295} | /*
* Copyright 2021-2023 cms.rendner (<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 utils
fun <T> measureIt(message: String = "", block: () -> T): T {
val start = System.currentTimeMillis()
val r = block()
val end = System.currentTimeMillis()
println("$message: ${end - start} ms")
return r
} | 0 | Python | 1 | 12 | 1a2d095bbebade29604b8b700f2f748460357602 | 846 | py-plugin-dataframe-viewer | Apache License 2.0 |
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/b2bi/CfnTransformerDsl.kt | cloudshiftinc | 667,063,030 | false | {"Kotlin": 70198112} | @file:Suppress(
"RedundantVisibilityModifier",
"RedundantUnitReturnType",
"RemoveRedundantQualifierName",
"unused",
"UnusedImport",
"ClassName",
"REDUNDANT_PROJECTION",
"DEPRECATION"
)
package io.cloudshiftdev.awscdkdsl.services.b2bi
import io.cloudshiftdev.awscdkdsl.CfnTagDsl
import io.cloudshiftdev.awscdkdsl.common.CdkDslMarker
import kotlin.String
import kotlin.Unit
import kotlin.collections.Collection
import kotlin.collections.MutableList
import software.amazon.awscdk.CfnTag
import software.amazon.awscdk.IResolvable
import software.amazon.awscdk.services.b2bi.CfnTransformer
import software.constructs.Construct
/**
* Creates a transformer.
*
* A transformer describes how to process the incoming EDI documents and extract the necessary
* information to the output file.
*
* Example:
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import software.amazon.awscdk.services.b2bi.*;
* CfnTransformer cfnTransformer = CfnTransformer.Builder.create(this, "MyCfnTransformer")
* .ediType(EdiTypeProperty.builder()
* .x12Details(X12DetailsProperty.builder()
* .transactionSet("transactionSet")
* .version("version")
* .build())
* .build())
* .fileFormat("fileFormat")
* .mappingTemplate("mappingTemplate")
* .name("name")
* .status("status")
* // the properties below are optional
* .modifiedAt("modifiedAt")
* .sampleDocument("sampleDocument")
* .tags(List.of(CfnTag.builder()
* .key("key")
* .value("value")
* .build()))
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-b2bi-transformer.html)
*/
@CdkDslMarker
public class CfnTransformerDsl(
scope: Construct,
id: String,
) {
private val cdkBuilder: CfnTransformer.Builder = CfnTransformer.Builder.create(scope, id)
private val _tags: MutableList<CfnTag> = mutableListOf()
/**
* Returns the details for the EDI standard that is being used for the transformer.
*
* Currently, only X12 is supported. X12 is a set of standards and corresponding messages that
* define specific business documents.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-b2bi-transformer.html#cfn-b2bi-transformer-editype)
*
* @param ediType Returns the details for the EDI standard that is being used for the
* transformer.
*/
public fun ediType(ediType: IResolvable) {
cdkBuilder.ediType(ediType)
}
/**
* Returns the details for the EDI standard that is being used for the transformer.
*
* Currently, only X12 is supported. X12 is a set of standards and corresponding messages that
* define specific business documents.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-b2bi-transformer.html#cfn-b2bi-transformer-editype)
*
* @param ediType Returns the details for the EDI standard that is being used for the
* transformer.
*/
public fun ediType(ediType: CfnTransformer.EdiTypeProperty) {
cdkBuilder.ediType(ediType)
}
/**
* Returns that the currently supported file formats for EDI transformations are `JSON` and
* `XML` .
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-b2bi-transformer.html#cfn-b2bi-transformer-fileformat)
*
* @param fileFormat Returns that the currently supported file formats for EDI transformations
* are `JSON` and `XML` .
*/
public fun fileFormat(fileFormat: String) {
cdkBuilder.fileFormat(fileFormat)
}
/**
* Returns a sample EDI document that is used by a transformer as a guide for processing the EDI
* data.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-b2bi-transformer.html#cfn-b2bi-transformer-mappingtemplate)
*
* @param mappingTemplate Returns a sample EDI document that is used by a transformer as a guide
* for processing the EDI data.
*/
public fun mappingTemplate(mappingTemplate: String) {
cdkBuilder.mappingTemplate(mappingTemplate)
}
/**
* Returns a timestamp representing the date and time for the most recent change for the
* transformer object.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-b2bi-transformer.html#cfn-b2bi-transformer-modifiedat)
*
* @param modifiedAt Returns a timestamp representing the date and time for the most recent
* change for the transformer object.
*/
public fun modifiedAt(modifiedAt: String) {
cdkBuilder.modifiedAt(modifiedAt)
}
/**
* Returns the descriptive name for the transformer.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-b2bi-transformer.html#cfn-b2bi-transformer-name)
*
* @param name Returns the descriptive name for the transformer.
*/
public fun name(name: String) {
cdkBuilder.name(name)
}
/**
* Returns a sample EDI document that is used by a transformer as a guide for processing the EDI
* data.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-b2bi-transformer.html#cfn-b2bi-transformer-sampledocument)
*
* @param sampleDocument Returns a sample EDI document that is used by a transformer as a guide
* for processing the EDI data.
*/
public fun sampleDocument(sampleDocument: String) {
cdkBuilder.sampleDocument(sampleDocument)
}
/**
* Returns the state of the newly created transformer.
*
* The transformer can be either `active` or `inactive` . For the transformer to be used in a
* capability, its status must `active` .
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-b2bi-transformer.html#cfn-b2bi-transformer-status)
*
* @param status Returns the state of the newly created transformer.
*/
public fun status(status: String) {
cdkBuilder.status(status)
}
/**
* A key-value pair for a specific transformer.
*
* Tags are metadata that you can use to search for and group capabilities for various purposes.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-b2bi-transformer.html#cfn-b2bi-transformer-tags)
*
* @param tags A key-value pair for a specific transformer.
*/
public fun tags(tags: CfnTagDsl.() -> Unit) {
_tags.add(CfnTagDsl().apply(tags).build())
}
/**
* A key-value pair for a specific transformer.
*
* Tags are metadata that you can use to search for and group capabilities for various purposes.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-b2bi-transformer.html#cfn-b2bi-transformer-tags)
*
* @param tags A key-value pair for a specific transformer.
*/
public fun tags(tags: Collection<CfnTag>) {
_tags.addAll(tags)
}
public fun build(): CfnTransformer {
if (_tags.isNotEmpty()) cdkBuilder.tags(_tags)
return cdkBuilder.build()
}
}
| 0 | Kotlin | 0 | 3 | 256ad92aebe2bcf9a4160089a02c76809dbbedba | 7,436 | awscdk-dsl-kotlin | Apache License 2.0 |
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/b2bi/CfnTransformerDsl.kt | cloudshiftinc | 667,063,030 | false | {"Kotlin": 70198112} | @file:Suppress(
"RedundantVisibilityModifier",
"RedundantUnitReturnType",
"RemoveRedundantQualifierName",
"unused",
"UnusedImport",
"ClassName",
"REDUNDANT_PROJECTION",
"DEPRECATION"
)
package io.cloudshiftdev.awscdkdsl.services.b2bi
import io.cloudshiftdev.awscdkdsl.CfnTagDsl
import io.cloudshiftdev.awscdkdsl.common.CdkDslMarker
import kotlin.String
import kotlin.Unit
import kotlin.collections.Collection
import kotlin.collections.MutableList
import software.amazon.awscdk.CfnTag
import software.amazon.awscdk.IResolvable
import software.amazon.awscdk.services.b2bi.CfnTransformer
import software.constructs.Construct
/**
* Creates a transformer.
*
* A transformer describes how to process the incoming EDI documents and extract the necessary
* information to the output file.
*
* Example:
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import software.amazon.awscdk.services.b2bi.*;
* CfnTransformer cfnTransformer = CfnTransformer.Builder.create(this, "MyCfnTransformer")
* .ediType(EdiTypeProperty.builder()
* .x12Details(X12DetailsProperty.builder()
* .transactionSet("transactionSet")
* .version("version")
* .build())
* .build())
* .fileFormat("fileFormat")
* .mappingTemplate("mappingTemplate")
* .name("name")
* .status("status")
* // the properties below are optional
* .modifiedAt("modifiedAt")
* .sampleDocument("sampleDocument")
* .tags(List.of(CfnTag.builder()
* .key("key")
* .value("value")
* .build()))
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-b2bi-transformer.html)
*/
@CdkDslMarker
public class CfnTransformerDsl(
scope: Construct,
id: String,
) {
private val cdkBuilder: CfnTransformer.Builder = CfnTransformer.Builder.create(scope, id)
private val _tags: MutableList<CfnTag> = mutableListOf()
/**
* Returns the details for the EDI standard that is being used for the transformer.
*
* Currently, only X12 is supported. X12 is a set of standards and corresponding messages that
* define specific business documents.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-b2bi-transformer.html#cfn-b2bi-transformer-editype)
*
* @param ediType Returns the details for the EDI standard that is being used for the
* transformer.
*/
public fun ediType(ediType: IResolvable) {
cdkBuilder.ediType(ediType)
}
/**
* Returns the details for the EDI standard that is being used for the transformer.
*
* Currently, only X12 is supported. X12 is a set of standards and corresponding messages that
* define specific business documents.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-b2bi-transformer.html#cfn-b2bi-transformer-editype)
*
* @param ediType Returns the details for the EDI standard that is being used for the
* transformer.
*/
public fun ediType(ediType: CfnTransformer.EdiTypeProperty) {
cdkBuilder.ediType(ediType)
}
/**
* Returns that the currently supported file formats for EDI transformations are `JSON` and
* `XML` .
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-b2bi-transformer.html#cfn-b2bi-transformer-fileformat)
*
* @param fileFormat Returns that the currently supported file formats for EDI transformations
* are `JSON` and `XML` .
*/
public fun fileFormat(fileFormat: String) {
cdkBuilder.fileFormat(fileFormat)
}
/**
* Returns a sample EDI document that is used by a transformer as a guide for processing the EDI
* data.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-b2bi-transformer.html#cfn-b2bi-transformer-mappingtemplate)
*
* @param mappingTemplate Returns a sample EDI document that is used by a transformer as a guide
* for processing the EDI data.
*/
public fun mappingTemplate(mappingTemplate: String) {
cdkBuilder.mappingTemplate(mappingTemplate)
}
/**
* Returns a timestamp representing the date and time for the most recent change for the
* transformer object.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-b2bi-transformer.html#cfn-b2bi-transformer-modifiedat)
*
* @param modifiedAt Returns a timestamp representing the date and time for the most recent
* change for the transformer object.
*/
public fun modifiedAt(modifiedAt: String) {
cdkBuilder.modifiedAt(modifiedAt)
}
/**
* Returns the descriptive name for the transformer.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-b2bi-transformer.html#cfn-b2bi-transformer-name)
*
* @param name Returns the descriptive name for the transformer.
*/
public fun name(name: String) {
cdkBuilder.name(name)
}
/**
* Returns a sample EDI document that is used by a transformer as a guide for processing the EDI
* data.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-b2bi-transformer.html#cfn-b2bi-transformer-sampledocument)
*
* @param sampleDocument Returns a sample EDI document that is used by a transformer as a guide
* for processing the EDI data.
*/
public fun sampleDocument(sampleDocument: String) {
cdkBuilder.sampleDocument(sampleDocument)
}
/**
* Returns the state of the newly created transformer.
*
* The transformer can be either `active` or `inactive` . For the transformer to be used in a
* capability, its status must `active` .
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-b2bi-transformer.html#cfn-b2bi-transformer-status)
*
* @param status Returns the state of the newly created transformer.
*/
public fun status(status: String) {
cdkBuilder.status(status)
}
/**
* A key-value pair for a specific transformer.
*
* Tags are metadata that you can use to search for and group capabilities for various purposes.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-b2bi-transformer.html#cfn-b2bi-transformer-tags)
*
* @param tags A key-value pair for a specific transformer.
*/
public fun tags(tags: CfnTagDsl.() -> Unit) {
_tags.add(CfnTagDsl().apply(tags).build())
}
/**
* A key-value pair for a specific transformer.
*
* Tags are metadata that you can use to search for and group capabilities for various purposes.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-b2bi-transformer.html#cfn-b2bi-transformer-tags)
*
* @param tags A key-value pair for a specific transformer.
*/
public fun tags(tags: Collection<CfnTag>) {
_tags.addAll(tags)
}
public fun build(): CfnTransformer {
if (_tags.isNotEmpty()) cdkBuilder.tags(_tags)
return cdkBuilder.build()
}
}
| 0 | Kotlin | 0 | 3 | 256ad92aebe2bcf9a4160089a02c76809dbbedba | 7,436 | awscdk-dsl-kotlin | Apache License 2.0 |
app/src/main/kotlin/loganalyzerbot/analyzer/statemachine/SequenceStateMachine.kt | tjpal | 657,782,297 | false | null | package loganalyzerbot.analyzer.statemachine
import loganalyzerbot.analyzer.definition.SequenceDefinition
import loganalyzerbot.analyzer.report.SequenceResult
import loganalyzerbot.logreader.LogMessage
class SequenceStateMachine(private val rootSequenceDefinition: SequenceDefinition) {
var matchedSequences = mutableListOf<SequenceResult>()
private set
private var sequenceStack = mutableListOf<Pair<SequenceDefinition, SequenceResult>>()
fun process(message: LogMessage) {
if(sequenceStack.isEmpty())
matchSequenceEntry(rootSequenceDefinition, message)
else
matchMessageForCurrentSequence(message)
}
fun onFinished() {
if(sequenceStack.isNotEmpty()) {
val topEntry = sequenceStack.last()
topEntry.second.finished = false
matchedSequences.add(topEntry.second)
sequenceStack = mutableListOf()
}
}
private fun matchSequenceEntry(definition: SequenceDefinition, message: LogMessage): Boolean {
if(!definition.entryRegexMatches(message.message))
return false
sequenceStack.add(Pair(definition, SequenceResult(definition, false, message)))
return true
}
private fun matchMessageForCurrentSequence(message: LogMessage) {
val topEntry = sequenceStack.last()
// Check weather we found the exit of the current sequence
if(matchExit(topEntry, message))
return
// Check whether we found the entry of a sub-sequence
if(matchSubSequenceEntry(topEntry, message))
return
}
private fun matchSubSequenceEntry(entry: Pair<SequenceDefinition, SequenceResult>, message: LogMessage): Boolean {
val subSequence = entry.first.subSequences.find {
it.entryRegexMatches(message.message)
} ?: return false
val subSequenceEntry = Pair(subSequence, SequenceResult(subSequence, false, message))
entry.second.matchedSubSequences.add(subSequenceEntry.second)
sequenceStack.add(subSequenceEntry)
return true
}
private fun matchExit(entry: Pair<SequenceDefinition, SequenceResult>, message: LogMessage): Boolean {
if (!entry.first.exitRegexMatches(message.message))
return false
sequenceStack.removeLast()
entry.second.finished = true
entry.second.exitLogMessage = message
if (sequenceStack.isNotEmpty()) {
val parentEntry = sequenceStack.last()
parentEntry.second.matchedSubSequences.add(entry.second)
} else {
matchedSequences.add(entry.second)
}
return true
}
} | 0 | Kotlin | 0 | 0 | 625f16d91aa41cf353401b4f27b6eae03074482a | 2,688 | log-bot | MIT License |
app/src/main/kotlin/com/goodwy/keyboard/app/settings/theme/FineTuneDialog.kt | Goodwy | 811,363,624 | false | null | /*
* Copyright (C) 2022 <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 dev.patrickgold.florisboard.app.settings.theme
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.runtime.Composable
import androidx.compose.ui.unit.dp
import dev.patrickgold.florisboard.R
import dev.patrickgold.florisboard.app.enumDisplayEntriesOf
import dev.patrickgold.florisboard.app.florisPreferenceModel
import dev.patrickgold.florisboard.lib.compose.stringRes
import org.florisboard.lib.snygg.SnyggLevel
import dev.patrickgold.jetpref.datastore.ui.ListPreference
import dev.patrickgold.jetpref.datastore.ui.PreferenceLayout
import dev.patrickgold.jetpref.material.ui.JetPrefAlertDialog
private val FineTuneContentPadding = PaddingValues(horizontal = 8.dp)
@Composable
fun FineTuneDialog(onDismiss: () -> Unit) {
JetPrefAlertDialog(
title = stringRes(R.string.settings__theme_editor__fine_tune__title),
onDismiss = onDismiss,
contentPadding = FineTuneContentPadding,
) {
PreferenceLayout(florisPreferenceModel(), iconSpaceReserved = false) {
ListPreference(
listPref = prefs.theme.editorLevel,
title = stringRes(R.string.settings__theme_editor__fine_tune__level),
entries = enumDisplayEntriesOf(SnyggLevel::class),
)
ListPreference(
listPref = prefs.theme.editorDisplayColorsAs,
title = stringRes(R.string.settings__theme_editor__fine_tune__display_colors_as),
entries = enumDisplayEntriesOf(DisplayColorsAs::class),
)
ListPreference(
listPref = prefs.theme.editorDisplayKbdAfterDialogs,
title = stringRes(R.string.settings__theme_editor__fine_tune__display_kbd_after_dialogs),
entries = enumDisplayEntriesOf(DisplayKbdAfterDialogs::class),
)
}
}
}
| 509 | null | 403 | 7 | 472b7eb1a9efcf6e12e55474698f7cc3254c1341 | 2,454 | Keyboard | Apache License 2.0 |
uistate/src/main/java/com/feduss/timerwear/uistate/extension/WorkoutType+Extension.kt | feduss | 839,081,219 | false | {"Kotlin": 283136} | package com.feduss.timerwear.uistate.extension
import com.feduss.timerwear.uistate.R
import com.feduss.timerwear.entity.enums.WorkoutType
fun WorkoutType.getStringId(): Int {
return when(this) {
WorkoutType.CustomWorkout -> R.string.main_page_custom_workout_button
WorkoutType.Emom -> R.string.main_page_emom_timer_button
WorkoutType.Hiit -> R.string.main_page_hiit_timer_button
}
} | 0 | Kotlin | 0 | 3 | 664d0cfedd9818f74454a301a24ea1f854557171 | 416 | TimerWear | MIT License |
app/src/main/java/com/vultisig/wallet/ui/models/keysign/KeysignFlowViewModel.kt | vultisig | 789,965,982 | false | {"Kotlin": 1611851, "Ruby": 1713} | @file:OptIn(ExperimentalSerializationApi::class)
package com.vultisig.wallet.ui.models.keysign
import android.annotation.SuppressLint
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.vultisig.wallet.data.api.BlockChairApi
import com.vultisig.wallet.data.api.CosmosApiFactory
import com.vultisig.wallet.data.api.EvmApiFactory
import com.vultisig.wallet.data.api.FeatureFlagApi
import com.vultisig.wallet.data.api.MayaChainApi
import com.vultisig.wallet.data.api.ParticipantDiscovery
import com.vultisig.wallet.data.api.PolkadotApi
import com.vultisig.wallet.data.api.SessionApi
import com.vultisig.wallet.data.api.SolanaApi
import com.vultisig.wallet.data.api.ThorChainApi
import com.vultisig.wallet.data.api.chains.SuiApi
import com.vultisig.wallet.data.api.models.signer.JoinKeysignRequestJson
import com.vultisig.wallet.data.chains.helpers.SigningHelper
import com.vultisig.wallet.data.common.Endpoints
import com.vultisig.wallet.data.common.Utils
import com.vultisig.wallet.data.mediator.MediatorService
import com.vultisig.wallet.data.models.Coin
import com.vultisig.wallet.data.models.TssKeyType
import com.vultisig.wallet.data.models.TssKeysignType
import com.vultisig.wallet.data.models.Vault
import com.vultisig.wallet.data.models.payload.BlockChainSpecific
import com.vultisig.wallet.data.models.payload.ERC20ApprovePayload
import com.vultisig.wallet.data.models.payload.KeysignPayload
import com.vultisig.wallet.data.models.payload.SwapPayload
import com.vultisig.wallet.data.models.proto.v1.CoinProto
import com.vultisig.wallet.data.models.proto.v1.KeysignMessageProto
import com.vultisig.wallet.data.models.proto.v1.KeysignPayloadProto
import com.vultisig.wallet.data.repositories.DepositTransactionRepository
import com.vultisig.wallet.data.repositories.ExplorerLinkRepository
import com.vultisig.wallet.data.repositories.SwapTransactionRepository
import com.vultisig.wallet.data.repositories.TransactionRepository
import com.vultisig.wallet.data.repositories.VultiSignerRepository
import com.vultisig.wallet.data.usecases.CompressQrUseCase
import com.vultisig.wallet.data.usecases.Encryption
import com.vultisig.wallet.ui.models.AddressProvider
import com.vultisig.wallet.ui.models.mappers.DepositTransactionToUiModelMapper
import com.vultisig.wallet.ui.models.mappers.SwapTransactionToUiModelMapper
import com.vultisig.wallet.ui.models.mappers.TransactionToUiModelMapper
import com.vultisig.wallet.ui.navigation.Destination
import com.vultisig.wallet.ui.navigation.Navigator
import com.vultisig.wallet.ui.navigation.SendDst
import com.vultisig.wallet.ui.utils.NetworkPromptOption
import dagger.hilt.android.lifecycle.HiltViewModel
import dagger.hilt.android.qualifiers.ApplicationContext
import io.ktor.util.encodeBase64
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.encodeToByteArray
import kotlinx.serialization.protobuf.ProtoBuf
import timber.log.Timber
import vultisig.keysign.v1.CosmosSpecific
import vultisig.keysign.v1.Erc20ApprovePayload
import vultisig.keysign.v1.EthereumSpecific
import vultisig.keysign.v1.MAYAChainSpecific
import vultisig.keysign.v1.OneInchQuote
import vultisig.keysign.v1.OneInchSwapPayload
import vultisig.keysign.v1.OneInchTransaction
import vultisig.keysign.v1.PolkadotSpecific
import vultisig.keysign.v1.SolanaSpecific
import vultisig.keysign.v1.SuiSpecific
import vultisig.keysign.v1.THORChainSpecific
import vultisig.keysign.v1.THORChainSwapPayload
import vultisig.keysign.v1.UTXOSpecific
import vultisig.keysign.v1.UtxoInfo
import java.util.UUID
import javax.inject.Inject
import kotlin.random.Random
internal sealed class KeysignFlowState {
data object PeerDiscovery : KeysignFlowState()
data object Keysign : KeysignFlowState()
data class Error (val errorMessage: String) : KeysignFlowState()
}
@HiltViewModel
internal class KeysignFlowViewModel @Inject constructor(
savedStateHandle: SavedStateHandle,
private val protoBuf: ProtoBuf,
private val thorChainApi: ThorChainApi,
private val blockChairApi: BlockChairApi,
private val evmApiFactory: EvmApiFactory,
private val mayaChainApi: MayaChainApi,
private val cosmosApiFactory: CosmosApiFactory,
private val solanaApi: SolanaApi,
private val polkadotApi: PolkadotApi,
private val suiApi: SuiApi,
private val explorerLinkRepository: ExplorerLinkRepository,
private val addressProvider: AddressProvider,
@ApplicationContext private val context: Context,
private val compressQr: CompressQrUseCase,
private val navigator: Navigator<Destination>,
private val vultiSignerRepository: VultiSignerRepository,
private val sessionApi: SessionApi,
private val encryption: Encryption,
private val featureFlagApi: FeatureFlagApi,
private val transactionRepository: TransactionRepository,
private val depositTransactionRepository: DepositTransactionRepository,
private val swapTransactionRepository: SwapTransactionRepository,
private val mapTransactionToUiModel: TransactionToUiModelMapper,
private val mapDepositTransactionUiModel: DepositTransactionToUiModelMapper,
private val mapSwapTransactionToUiModel: SwapTransactionToUiModelMapper,
) : ViewModel() {
private val _sessionID: String = UUID.randomUUID().toString()
private val _serviceName: String = "vultisigApp-${Random.nextInt(1, 1000)}"
private var _serverAddress: String = "http://127.0.0.1:18080" // local mediator server
private var _participantDiscovery: ParticipantDiscovery? = null
private val _encryptionKeyHex: String = Utils.encryptionKeyHex
private var _currentVault: Vault? = null
private var _keysignPayload: KeysignPayload? = null
private val _keysignMessage: MutableState<String> = mutableStateOf("")
private var messagesToSign = emptyList<String>()
var currentState: MutableStateFlow<KeysignFlowState> =
MutableStateFlow(KeysignFlowState.PeerDiscovery)
val selection = MutableLiveData<List<String>>()
val localPartyID: String?
get() = _currentVault?.localPartyID
val keysignMessage: MutableState<String>
get() = _keysignMessage
val participants: MutableLiveData<List<String>>
get() = _participantDiscovery?.participants ?: MutableLiveData(listOf())
val networkOption: MutableState<NetworkPromptOption> =
mutableStateOf(NetworkPromptOption.INTERNET)
val password = savedStateHandle.get<String?>(SendDst.ARG_PASSWORD)
val transactionId = savedStateHandle.get<String>(SendDst.ARG_TRANSACTION_ID)
val isFastSign: Boolean
get() = password != null
private val isRelayEnabled by derivedStateOf {
networkOption.value == NetworkPromptOption.INTERNET || isFastSign
}
private var transactionTypeUiModel: TransactionTypeUiModel? = null
val keysignViewModel: KeysignViewModel
get() = KeysignViewModel(
vault = _currentVault!!,
keysignCommittee = selection.value!!,
serverAddress = _serverAddress,
sessionId = _sessionID,
encryptionKeyHex = _encryptionKeyHex,
messagesToSign = messagesToSign,
keyType = _keysignPayload?.coin?.chain?.TssKeysignType ?: TssKeyType.ECDSA,
keysignPayload = _keysignPayload!!,
thorChainApi = thorChainApi,
blockChairApi = blockChairApi,
evmApiFactory = evmApiFactory,
mayaChainApi = mayaChainApi,
cosmosApiFactory = cosmosApiFactory,
solanaApi = solanaApi,
polkadotApi = polkadotApi,
explorerLinkRepository = explorerLinkRepository,
sessionApi = sessionApi,
suiApi = suiApi,
navigator = navigator,
encryption = encryption,
featureFlagApi = featureFlagApi,
transactionTypeUiModel = transactionTypeUiModel
)
init {
viewModelScope.launch {
currentState.collect { state ->
if (state == KeysignFlowState.Keysign) {
startKeysign()
}
}
}
}
suspend fun setData(vault: Vault, context: Context, keysignPayload: KeysignPayload) {
try {
_currentVault = vault
_keysignPayload = keysignPayload
messagesToSign = SigningHelper.getKeysignMessages(
payload = _keysignPayload!!,
vault = _currentVault!!,
)
this.selection.value = listOf(vault.localPartyID)
_serverAddress = Endpoints.VULTISIG_RELAY
updateKeysignPayload(context)
updateTransactionUiModel(keysignPayload)
} catch (e: Exception) {
Timber.e(e)
moveToState(KeysignFlowState.Error(e.message.toString()))
}
}
@Suppress("ReplaceNotNullAssertionWithElvisReturn")
private suspend fun updateKeysignPayload(context: Context) {
stopParticipantDiscovery()
_currentVault ?: run {
moveToState(KeysignFlowState.Error("Vault is not set"))
return
}
val vault = _currentVault!!
_participantDiscovery = ParticipantDiscovery(
_serverAddress,
_sessionID,
vault.localPartyID,
sessionApi
)
val keysignPayload = _keysignPayload!!
val swapPayload = keysignPayload.swapPayload
val approvePayload = keysignPayload.approvePayload
val specific = keysignPayload.blockChainSpecific
val keysignProto = protoBuf.encodeToByteArray(
KeysignMessageProto(
sessionId = _sessionID,
serviceName = _serviceName,
keysignPayload = KeysignPayloadProto(
coin = keysignPayload.coin.toCoinProto(),
toAddress = keysignPayload.toAddress,
toAmount = keysignPayload.toAmount.toString(),
memo = keysignPayload.memo,
vaultLocalPartyId = keysignPayload.vaultLocalPartyID,
vaultPublicKeyEcdsa = keysignPayload.vaultPublicKeyECDSA,
utxoSpecific = if (specific is BlockChainSpecific.UTXO) {
UTXOSpecific(
byteFee = specific.byteFee.toString(),
sendMaxAmount = specific.sendMaxAmount,
)
} else null,
utxoInfo = keysignPayload.utxos.map {
UtxoInfo(
hash = it.hash,
amount = it.amount,
index = it.index,
)
},
ethereumSpecific = if (specific is BlockChainSpecific.Ethereum) {
EthereumSpecific(
maxFeePerGasWei = specific.maxFeePerGasWei.toString(),
priorityFee = specific.priorityFeeWei.toString(),
nonce = specific.nonce.toLong(),
gasLimit = specific.gasLimit.toString(),
)
} else null,
thorchainSpecific = if (specific is BlockChainSpecific.THORChain) {
THORChainSpecific(
accountNumber = specific.accountNumber.toString().toULong(),
sequence = specific.sequence.toString().toULong(),
fee = specific.fee.toString().toULong(),
isDeposit = specific.isDeposit,
)
} else null,
mayaSpecific = if (specific is BlockChainSpecific.MayaChain) {
MAYAChainSpecific(
accountNumber = specific.accountNumber.toString().toULong(),
sequence = specific.sequence.toString().toULong(),
isDeposit = specific.isDeposit,
)
} else null,
cosmosSpecific = if (specific is BlockChainSpecific.Cosmos) {
CosmosSpecific(
accountNumber = specific.accountNumber.toString().toULong(),
sequence = specific.sequence.toString().toULong(),
gas = specific.gas.toString().toULong(),
)
} else null,
solanaSpecific = if (specific is BlockChainSpecific.Solana) {
SolanaSpecific(
recentBlockHash = specific.recentBlockHash,
priorityFee = specific.priorityFee.toString(),
toTokenAssociatedAddress = specific.toAddressPubKey,
fromTokenAssociatedAddress = specific.fromAddressPubKey,
)
} else null,
polkadotSpecific = if (specific is BlockChainSpecific.Polkadot) {
PolkadotSpecific(
recentBlockHash = specific.recentBlockHash,
nonce = specific.nonce.toString().toULong(),
currentBlockNumber = specific.currentBlockNumber.toString(),
specVersion = specific.specVersion,
transactionVersion = specific.transactionVersion,
genesisHash = specific.genesisHash,
)
} else null,
suicheSpecific = if (specific is BlockChainSpecific.Sui) {
SuiSpecific(
referenceGasPrice = specific.referenceGasPrice.toString(),
coins = specific.coins,
)
} else null,
thorchainSwapPayload = if (swapPayload is SwapPayload.ThorChain) {
val from = swapPayload.data
THORChainSwapPayload(
fromAddress = from.fromAddress,
fromCoin = from.fromCoin.toCoinProto(),
toCoin = from.toCoin.toCoinProto(),
vaultAddress = from.vaultAddress,
routerAddress = from.routerAddress,
fromAmount = from.fromAmount.toString(),
toAmountDecimal = from.toAmountDecimal.toPlainString(),
toAmountLimit = from.toAmountLimit,
streamingInterval = from.streamingInterval,
streamingQuantity = from.streamingQuantity,
expirationTime = from.expirationTime,
isAffiliate = from.isAffiliate,
)
} else null,
mayachainSwapPayload = if (swapPayload is SwapPayload.MayaChain) {
val from = swapPayload.data
THORChainSwapPayload(
fromAddress = from.fromAddress,
fromCoin = from.fromCoin.toCoinProto(),
toCoin = from.toCoin.toCoinProto(),
vaultAddress = from.vaultAddress,
routerAddress = from.routerAddress,
fromAmount = from.fromAmount.toString(),
toAmountDecimal = from.toAmountDecimal.toPlainString(),
toAmountLimit = from.toAmountLimit,
streamingInterval = from.streamingInterval,
streamingQuantity = from.streamingQuantity,
expirationTime = from.expirationTime,
isAffiliate = from.isAffiliate,
)
} else null,
oneinchSwapPayload = if (swapPayload is SwapPayload.OneInch) {
val from = swapPayload.data
OneInchSwapPayload(
fromCoin = from.fromCoin.toCoinProto(),
toCoin = from.toCoin.toCoinProto(),
fromAmount = from.fromAmount.toString(),
toAmountDecimal = from.toAmountDecimal.toPlainString(),
quote = from.quote.let { it ->
OneInchQuote(
dstAmount = it.dstAmount,
tx = it.tx.let {
OneInchTransaction(
from = it.from,
to = it.to,
`data` = it.data,
`value` = it.value,
gasPrice = it.gasPrice,
gas = it.gas,
)
}
)
}
)
} else null,
erc20ApprovePayload = if (approvePayload is ERC20ApprovePayload) {
Erc20ApprovePayload(
spender = approvePayload.spender,
amount = approvePayload.amount.toString(),
)
} else null,
),
encryptionKeyHex = _encryptionKeyHex,
useVultisigRelay = isRelayEnabled
)
)
Timber.d("keysignProto: $keysignProto")
val data = compressQr(keysignProto).encodeBase64()
_keysignMessage.value =
"vultisig://vultisig.com?type=SignTransaction&resharePrefix=${vault.resharePrefix}&vault=${vault.pubKeyECDSA}&jsonData=" + data
addressProvider.update(_keysignMessage.value)
if (!isRelayEnabled) {
startMediatorService(context)
} else {
_serverAddress = Endpoints.VULTISIG_RELAY
withContext(Dispatchers.IO) {
startSession(_serverAddress, _sessionID, vault.localPartyID)
}
_participantDiscovery?.discoveryParticipants()
}
}
private fun updateTransactionUiModel(
keysignPayload: KeysignPayload,
) {
transactionId?.let {
val isSwap = keysignPayload.swapPayload != null
val isDeposit = when (val specific = keysignPayload.blockChainSpecific) {
is BlockChainSpecific.MayaChain -> specific.isDeposit
is BlockChainSpecific.THORChain -> specific.isDeposit
else -> false
}
viewModelScope.launch {
transactionTypeUiModel = when {
isSwap -> TransactionTypeUiModel.Swap(
mapSwapTransactionToUiModel(
swapTransactionRepository.getTransaction(transactionId)
)
)
isDeposit -> TransactionTypeUiModel.Deposit(
mapDepositTransactionUiModel(
depositTransactionRepository.getTransaction(transactionId)
)
)
else -> TransactionTypeUiModel.Send(
mapTransactionToUiModel(
transactionRepository.getTransaction(
transactionId
).first()
)
)
}
}
}
}
@Suppress("ReplaceNotNullAssertionWithElvisReturn")
@OptIn(DelicateCoroutinesApi::class)
private val serviceStartedReceiver: BroadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (intent.action == MediatorService.SERVICE_ACTION) {
Timber.tag("KeysignFlowViewModel").d("onReceive: Mediator service started")
if (_currentVault == null) {
moveToState(KeysignFlowState.Error("Vault is not set"))
return
}
// send a request to local mediator server to start the session
GlobalScope.launch(Dispatchers.IO) {
delay(1000) // back off a second
startSession(_serverAddress, _sessionID, _currentVault!!.localPartyID)
}
// kick off discovery
_participantDiscovery?.discoveryParticipants()
}
}
}
private fun stopService(context: Context) {
// start mediator service
val intent = Intent(context, MediatorService::class.java)
context.stopService(intent)
Timber.d("stopService: Mediator service stopped")
}
@SuppressLint("UnspecifiedRegisterReceiverFlag")
private fun startMediatorService(context: Context) {
val filter = IntentFilter()
filter.addAction(MediatorService.SERVICE_ACTION)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
context.registerReceiver(serviceStartedReceiver, filter, Context.RECEIVER_EXPORTED)
} else {
//Todo Handle older Android versions if needed
context.registerReceiver(serviceStartedReceiver, filter)
}
// start mediator service
val intent = Intent(context, MediatorService::class.java)
intent.putExtra("serverName", _serviceName)
context.startService(intent)
Timber.tag("KeysignFlowViewModel").d("startMediatorService: Mediator service started")
}
private suspend fun startSession(
serverAddr: String,
sessionID: String,
localPartyID: String,
) {
// start the session
try {
sessionApi.startSession(serverAddr, sessionID, listOf(localPartyID))
Timber.tag("KeysignFlowViewModel").d("startSession: Session started")
if (password != null) {
val vault = _currentVault!!
vultiSignerRepository.joinKeysign(
JoinKeysignRequestJson(
publicKeyEcdsa = vault.pubKeyECDSA,
messages = messagesToSign,
sessionId = sessionID,
hexEncryptionKey = _encryptionKeyHex,
derivePath = _keysignPayload!!.coin.coinType.derivationPath(),
isEcdsa = _keysignPayload?.coin?.chain?.TssKeysignType == TssKeyType.ECDSA,
password = <PASSWORD>,
)
)
}
} catch (e: Exception) {
Timber.tag("KeysignFlowViewModel").e("startSession: ${e.stackTraceToString()}")
}
}
fun addParticipant(participant: String) {
val currentList = selection.value ?: emptyList()
if (currentList.contains(participant)) return
selection.value = currentList + participant
}
fun removeParticipant(participant: String) {
selection.value = selection.value?.minus(participant)
}
@Suppress("ReplaceNotNullAssertionWithElvisReturn")
fun moveToState(nextState: KeysignFlowState) {
try {
if (nextState == KeysignFlowState.Keysign) {
cleanQrAddress()
}
currentState.update { nextState }
} catch (e: Exception) {
moveToState(KeysignFlowState.Error(e.message.toString()))
}
}
fun stopParticipantDiscovery() = viewModelScope.launch {
_participantDiscovery?.stop()
}
private fun cleanQrAddress() {
addressProvider.clean()
}
@OptIn(DelicateCoroutinesApi::class)
fun changeNetworkPromptOption(option: NetworkPromptOption, context: Context) {
if (networkOption.value == option) return
networkOption.value = option
_serverAddress = when (option) {
NetworkPromptOption.LOCAL -> {
"http://127.0.0.1:18080"
}
NetworkPromptOption.INTERNET -> {
Endpoints.VULTISIG_RELAY
}
}
GlobalScope.launch(Dispatchers.IO) {
updateKeysignPayload(context)
}
}
private suspend fun startKeysign() {
withContext(Dispatchers.IO) {
try {
val keygenCommittee = selection.value ?: emptyList()
sessionApi.startWithCommittee(_serverAddress, _sessionID, keygenCommittee)
Timber.d("Keysign started")
} catch (e: Exception) {
Timber.e("Failed to start keysign: ${e.stackTraceToString()}")
}
}
}
private fun Coin.toCoinProto() = CoinProto(
chain = chain.raw,
ticker = ticker,
address = address,
contractAddress = contractAddress,
decimals = decimal,
priceProviderId = priceProviderID,
isNativeToken = isNativeToken,
hexPublicKey = hexPublicKey,
logo = logo,
)
override fun onCleared() {
cleanQrAddress()
stopService(context)
super.onCleared()
}
fun tryAgain() {
viewModelScope.launch {
navigator.navigate(Destination.Back)
}
}
} | 58 | Kotlin | 2 | 6 | bc136dca92abbc2507d64764737fdccddd9bdf42 | 26,464 | vultisig-android | Apache License 2.0 |
adaptive-ui/src/commonMain/kotlin/fun/adaptive/ui/render/DecorationRenderApplier.kt | spxbhuhb | 788,711,010 | false | null | package `fun`.adaptive.ui.common.render
import `fun`.adaptive.ui.common.AbstractCommonFragment
import `fun`.adaptive.ui.common.fragment.layout.RawBorder
import `fun`.adaptive.ui.common.fragment.layout.RawCornerRadius
import `fun`.adaptive.ui.common.fragment.layout.RawDropShadow
import `fun`.adaptive.ui.common.instruction.BackgroundGradient
import `fun`.adaptive.ui.common.instruction.Color
abstract class DecorationRenderApplier<R> : AbstractRenderApplier() {
fun applyTo(fragment: AbstractCommonFragment<R>) {
val previousData = fragment.previousRenderData
val currentData = fragment.renderData
val previous = previousData.decoration
val current = currentData.decoration
if (previous == current) return
val receiver = fragment.receiver
// ---- border ----
val border = current?.border
val previousBorder = previous?.border
if (border != previousBorder) {
applyBorder(receiver, border)
}
// ---- corner radius ----
val cornerRadius = current?.cornerRadius
val previousCornerRadius = previous?.cornerRadius
if (cornerRadius != previousCornerRadius) {
applyCornerRadius(receiver, cornerRadius)
}
// ---- background ----
val previousColor = previous?.backgroundColor
val previousGradient = previous?.backgroundGradient
var clearBackground = (previousColor != null && previousGradient != null)
val color = current?.backgroundColor
if (color != null) {
if (color != previousColor) {
applyColor(receiver, color)
}
clearBackground = false
}
val gradient = current?.backgroundGradient
if (gradient != null) {
if (previousGradient != gradient) {
applyGradient(receiver, gradient, cornerRadius)
}
clearBackground = false
}
if (clearBackground) {
clearBackground(receiver)
}
// drop shadow
val dropShadow = current?.dropShadow
val previousDropShadow = previous?.dropShadow
if (dropShadow != previousDropShadow) {
applyDropShadow(receiver, dropShadow)
}
}
abstract fun applyBorder(receiver: R, border: RawBorder?)
abstract fun applyCornerRadius(receiver: R, cornerRadius: RawCornerRadius?)
abstract fun applyColor(receiver: R, color: Color)
abstract fun applyGradient(receiver: R, gradient: BackgroundGradient, cornerRadius: RawCornerRadius?)
abstract fun clearBackground(receiver: R)
abstract fun applyDropShadow(receiver: R, dropShadow: RawDropShadow?)
} | 34 | null | 0 | 3 | e7d8bb8682a6399675bc75d2976b862268d20fb5 | 2,729 | adaptive | Apache License 2.0 |
app/src/main/java/com/vultisig/wallet/ui/components/BoxWithSwipeRefresh.kt | vultisig | 789,965,982 | false | {"Kotlin": 1656023, "Ruby": 1713} | package com.vultisig.wallet.ui.components
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.pulltorefresh.PullToRefreshBox
import androidx.compose.material3.pulltorefresh.rememberPullToRefreshState
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
@OptIn(ExperimentalMaterial3Api::class)
@Composable
internal fun BoxWithSwipeRefresh(
onSwipe: () -> Unit,
isRefreshing: Boolean,
modifier: Modifier = Modifier,
content: @Composable BoxScope.() -> Unit,
) {
PullToRefreshBox(
modifier = modifier,
onRefresh = onSwipe,
content = content,
isRefreshing = isRefreshing,
)
} | 58 | Kotlin | 2 | 6 | 106410f378751c6ab276120fcc74c1036b46ab6e | 748 | vultisig-android | Apache License 2.0 |
design/principle/interfacesegregation/Main.kt | tony-xxw | 287,568,841 | false | {"Kotlin": 42389, "Java": 3325} | package design.principle.interfacesegregation
fun main() {
Dog().apply {
fly()
eat()
swim()
}
println()
Bird().apply {
fly()
eat()
swim()
}
println()
DogImp().apply {
eat()
swim()
}
println()
BirdImp().apply {
eat()
fly()
}
}
interface IAnimalAction {
fun fly()
fun eat()
fun swim()
}
class Dog : IAnimalAction {
override fun fly() {
}
override fun eat() {
println("吃饭")
}
override fun swim() {
println("游泳")
}
}
class Bird : IAnimalAction {
override fun fly() {
println("飞")
}
override fun eat() {
println("吃饭")
}
override fun swim() {
}
}
interface IFlyAnimalAction {
fun fly()
}
interface ISwimAnimalAction {
fun swim()
}
interface IEatAnimalAction {
fun eat()
}
class DogImp : ISwimAnimalAction, IEatAnimalAction {
override fun swim() {
println("游泳")
}
override fun eat() {
println("吃饭")
}
}
class BirdImp : IEatAnimalAction, IFlyAnimalAction {
override fun fly() {
println("飞")
}
override fun eat() {
println("吃饭")
}
} | 0 | Kotlin | 0 | 0 | 0533b3c2f7a2d65c46b6bd752e2789e850f0635b | 1,236 | LearnDesign | Apache License 2.0 |
app/src/main/java/cucerdariancatalin/sms_messenger/activities/SettingsActivity.kt | cucerdariancatalin | 586,080,344 | false | null | package cucerdariancatalin.sms_messenger.activities
import android.annotation.TargetApi
import android.content.Intent
import android.os.Build
import android.os.Bundle
import com.simplemobiletools.commons.activities.ManageBlockedNumbersActivity
import com.simplemobiletools.commons.dialogs.ChangeDateTimeFormatDialog
import com.simplemobiletools.commons.dialogs.FeatureLockedDialog
import com.simplemobiletools.commons.dialogs.RadioGroupDialog
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.*
import com.simplemobiletools.commons.models.RadioItem
import cucerdariancatalin.sms_messenger.R
import cucerdariancatalin.sms_messenger.extensions.config
import cucerdariancatalin.sms_messenger.helpers.*
import kotlinx.android.synthetic.main.activity_settings.*
import java.util.*
class SettingsActivity : SimpleActivity() {
private var blockedNumbersAtPause = -1
override fun onCreate(savedInstanceState: Bundle?) {
isMaterialActivity = true
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_settings)
updateMaterialActivityViews(settings_coordinator, settings_holder, useTransparentNavigation = true, useTopSearchMenu = false)
setupMaterialScrollListener(settings_nested_scrollview, settings_toolbar)
}
override fun onResume() {
super.onResume()
setupToolbar(settings_toolbar, NavigationIcon.Arrow)
setupPurchaseThankYou()
setupCustomizeColors()
setupCustomizeNotifications()
setupUseEnglish()
setupLanguage()
setupManageBlockedNumbers()
setupChangeDateTimeFormat()
setupFontSize()
setupShowCharacterCounter()
setupUseSimpleCharacters()
setupSendOnEnter()
setupEnableDeliveryReports()
setupSendLongMessageAsMMS()
setupGroupMessageAsMMS()
setupLockScreenVisibility()
setupMMSFileSizeLimit()
updateTextColors(settings_nested_scrollview)
if (blockedNumbersAtPause != -1 && blockedNumbersAtPause != getBlockedNumbers().hashCode()) {
refreshMessages()
}
arrayOf(
settings_color_customization_section_label,
settings_general_settings_label,
settings_outgoing_messages_label,
settings_notifications_label
).forEach {
it.setTextColor(getProperPrimaryColor())
}
}
override fun onPause() {
super.onPause()
blockedNumbersAtPause = getBlockedNumbers().hashCode()
}
private fun setupPurchaseThankYou() {
settings_purchase_thank_you_holder.beGoneIf(isOrWasThankYouInstalled())
settings_purchase_thank_you_holder.setOnClickListener {
launchPurchaseThankYouIntent()
}
}
private fun setupCustomizeColors() {
settings_color_customization_label.text = getCustomizeColorsString()
settings_color_customization_holder.setOnClickListener {
handleCustomizeColorsClick()
}
}
private fun setupCustomizeNotifications() {
settings_customize_notifications_holder.beVisibleIf(isOreoPlus())
settings_customize_notifications_holder.setOnClickListener {
launchCustomizeNotificationsIntent()
}
}
private fun setupUseEnglish() {
settings_use_english_holder.beVisibleIf((config.wasUseEnglishToggled || Locale.getDefault().language != "en") && !isTiramisuPlus())
settings_use_english.isChecked = config.useEnglish
settings_use_english_holder.setOnClickListener {
settings_use_english.toggle()
config.useEnglish = settings_use_english.isChecked
System.exit(0)
}
}
private fun setupLanguage() {
settings_language.text = Locale.getDefault().displayLanguage
settings_language_holder.beVisibleIf(isTiramisuPlus())
settings_language_holder.setOnClickListener {
launchChangeAppLanguageIntent()
}
}
// support for device-wise blocking came on Android 7, rely only on that
@TargetApi(Build.VERSION_CODES.N)
private fun setupManageBlockedNumbers() {
settings_manage_blocked_numbers.text = addLockedLabelIfNeeded(R.string.manage_blocked_numbers)
settings_manage_blocked_numbers_holder.beVisibleIf(isNougatPlus())
settings_manage_blocked_numbers_holder.setOnClickListener {
if (isOrWasThankYouInstalled()) {
Intent(this, ManageBlockedNumbersActivity::class.java).apply {
startActivity(this)
}
} else {
FeatureLockedDialog(this) { }
}
}
}
private fun setupChangeDateTimeFormat() {
settings_change_date_time_format_holder.setOnClickListener {
ChangeDateTimeFormatDialog(this) {
refreshMessages()
}
}
}
private fun setupFontSize() {
settings_font_size.text = getFontSizeText()
settings_font_size_holder.setOnClickListener {
val items = arrayListOf(
RadioItem(FONT_SIZE_SMALL, getString(R.string.small)),
RadioItem(FONT_SIZE_MEDIUM, getString(R.string.medium)),
RadioItem(FONT_SIZE_LARGE, getString(R.string.large)),
RadioItem(FONT_SIZE_EXTRA_LARGE, getString(R.string.extra_large))
)
RadioGroupDialog(this@SettingsActivity, items, config.fontSize) {
config.fontSize = it as Int
settings_font_size.text = getFontSizeText()
}
}
}
private fun setupShowCharacterCounter() {
settings_show_character_counter.isChecked = config.showCharacterCounter
settings_show_character_counter_holder.setOnClickListener {
settings_show_character_counter.toggle()
config.showCharacterCounter = settings_show_character_counter.isChecked
}
}
private fun setupUseSimpleCharacters() {
settings_use_simple_characters.isChecked = config.useSimpleCharacters
settings_use_simple_characters_holder.setOnClickListener {
settings_use_simple_characters.toggle()
config.useSimpleCharacters = settings_use_simple_characters.isChecked
}
}
private fun setupSendOnEnter() {
settings_send_on_enter.isChecked = config.sendOnEnter
settings_send_on_enter_holder.setOnClickListener {
settings_send_on_enter.toggle()
config.sendOnEnter = settings_send_on_enter.isChecked
}
}
private fun setupEnableDeliveryReports() {
settings_enable_delivery_reports.isChecked = config.enableDeliveryReports
settings_enable_delivery_reports_holder.setOnClickListener {
settings_enable_delivery_reports.toggle()
config.enableDeliveryReports = settings_enable_delivery_reports.isChecked
}
}
private fun setupSendLongMessageAsMMS() {
settings_send_long_message_mms.isChecked = config.sendLongMessageMMS
settings_send_long_message_mms_holder.setOnClickListener {
settings_send_long_message_mms.toggle()
config.sendLongMessageMMS = settings_send_long_message_mms.isChecked
}
}
private fun setupGroupMessageAsMMS() {
settings_send_group_message_mms.isChecked = config.sendGroupMessageMMS
settings_send_group_message_mms_holder.setOnClickListener {
settings_send_group_message_mms.toggle()
config.sendGroupMessageMMS = settings_send_group_message_mms.isChecked
}
}
private fun setupLockScreenVisibility() {
settings_lock_screen_visibility.text = getLockScreenVisibilityText()
settings_lock_screen_visibility_holder.setOnClickListener {
val items = arrayListOf(
RadioItem(LOCK_SCREEN_SENDER_MESSAGE, getString(R.string.sender_and_message)),
RadioItem(LOCK_SCREEN_SENDER, getString(R.string.sender_only)),
RadioItem(LOCK_SCREEN_NOTHING, getString(R.string.nothing)),
)
RadioGroupDialog(this@SettingsActivity, items, config.lockScreenVisibilitySetting) {
config.lockScreenVisibilitySetting = it as Int
settings_lock_screen_visibility.text = getLockScreenVisibilityText()
}
}
}
private fun getLockScreenVisibilityText() = getString(
when (config.lockScreenVisibilitySetting) {
LOCK_SCREEN_SENDER_MESSAGE -> R.string.sender_and_message
LOCK_SCREEN_SENDER -> R.string.sender_only
else -> R.string.nothing
}
)
private fun setupMMSFileSizeLimit() {
settings_mms_file_size_limit.text = getMMSFileLimitText()
settings_mms_file_size_limit_holder.setOnClickListener {
val items = arrayListOf(
RadioItem(7, getString(R.string.mms_file_size_limit_none), FILE_SIZE_NONE),
RadioItem(6, getString(R.string.mms_file_size_limit_2mb), FILE_SIZE_2_MB),
RadioItem(5, getString(R.string.mms_file_size_limit_1mb), FILE_SIZE_1_MB),
RadioItem(4, getString(R.string.mms_file_size_limit_600kb), FILE_SIZE_600_KB),
RadioItem(3, getString(R.string.mms_file_size_limit_300kb), FILE_SIZE_300_KB),
RadioItem(2, getString(R.string.mms_file_size_limit_200kb), FILE_SIZE_200_KB),
RadioItem(1, getString(R.string.mms_file_size_limit_100kb), FILE_SIZE_100_KB),
)
val checkedItemId = items.find { it.value == config.mmsFileSizeLimit }?.id ?: 7
RadioGroupDialog(this@SettingsActivity, items, checkedItemId) {
config.mmsFileSizeLimit = it as Long
settings_mms_file_size_limit.text = getMMSFileLimitText()
}
}
}
private fun getMMSFileLimitText() = getString(
when (config.mmsFileSizeLimit) {
FILE_SIZE_100_KB -> R.string.mms_file_size_limit_100kb
FILE_SIZE_200_KB -> R.string.mms_file_size_limit_200kb
FILE_SIZE_300_KB -> R.string.mms_file_size_limit_300kb
FILE_SIZE_600_KB -> R.string.mms_file_size_limit_600kb
FILE_SIZE_1_MB -> R.string.mms_file_size_limit_1mb
FILE_SIZE_2_MB -> R.string.mms_file_size_limit_2mb
else -> R.string.mms_file_size_limit_none
}
)
}
| 0 | Kotlin | 0 | 2 | bde8d17dfc800c3a291a96d3b4ee653f335019bb | 10,492 | SMSMessenger | MIT License |
demo/app/src/main/java/com/alessandro/claymore/demo/ClaymoreDemoApplication.kt | alecarnevale | 559,250,665 | false | {"Kotlin": 92000} | package com.alessandro.claymore.demo
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class ClaymoreDemoApplication: Application() | 1 | Kotlin | 0 | 5 | fedfc34d5d114fff7f3f5063906caf70ea419137 | 172 | claymore | Apache License 2.0 |
common-domain/src/test/java/com/paulrybitskyi/gamedge/common/domain/games/ObserveRecentlyReleasedGamesUseCaseImplTest.kt | mars885 | 289,036,871 | false | {"Kotlin": 1318694, "Shell": 593} | /*
* Copyright 2022 Paul Rybitskyi, [email protected]
*
* 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.paulrybitskyi.gamedge.common.domain.games
import app.cash.turbine.test
import com.google.common.truth.Truth.assertThat
import com.paulrybitskyi.gamedge.common.domain.games.common.ObserveGamesUseCaseParams
import com.paulrybitskyi.gamedge.common.domain.games.datastores.GamesLocalDataStore
import com.paulrybitskyi.gamedge.common.domain.games.usecases.ObservePopularGamesUseCaseImpl
import com.paulrybitskyi.gamedge.common.testing.domain.DOMAIN_GAMES
import com.paulrybitskyi.gamedge.common.testing.domain.MainCoroutineRule
import io.mockk.MockKAnnotations
import io.mockk.every
import io.mockk.impl.annotations.MockK
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.test.runTest
import org.junit.Before
import org.junit.Rule
import org.junit.Test
internal class ObservePopularGamesUseCaseImplTest {
@get:Rule
val mainCoroutineRule = MainCoroutineRule()
@MockK private lateinit var gamesLocalDataStore: GamesLocalDataStore
private lateinit var SUT: ObservePopularGamesUseCaseImpl
@Before
fun setup() {
MockKAnnotations.init(this)
SUT = ObservePopularGamesUseCaseImpl(
gamesLocalDataStore = gamesLocalDataStore,
dispatcherProvider = mainCoroutineRule.dispatcherProvider,
)
}
@Test
fun `Emits games successfully`() {
runTest {
every { gamesLocalDataStore.observePopularGames(any()) } returns flowOf(DOMAIN_GAMES)
SUT.execute(ObserveGamesUseCaseParams()).test {
assertThat(awaitItem()).isEqualTo(DOMAIN_GAMES)
awaitComplete()
}
}
}
}
| 4 | Kotlin | 63 | 659 | 69b3ada08cb877af9b775c6a4f3d9eb1c3470d9c | 2,268 | gamedge | Apache License 2.0 |
JavaFx/src/main/kotlin/io/github/slupik/schemablock/logic/executor/diagram/ExecutionEvent.kt | Slupik | 151,474,227 | false | null | package io.github.slupik.schemablock.logic.executor.diagram
import io.github.slupik.schemablock.javafx.element.block.Block
import io.github.slupik.schemablock.logic.executor.block.ExecutionResult
/**
* All rights reserved & copyright ©
*/
sealed class ExecutionEvent
object ExecutionStart: ExecutionEvent()
data class ErrorEvent(
val error: Throwable
) : ExecutionEvent()
data class PreExecutionEvent(
val executingBlock: Block
) : ExecutionEvent()
data class PostExecutionEvent(
val executedBlock: Block,
val result: ExecutionResult
) : ExecutionEvent()
object ExecutionEnd: ExecutionEvent() | 1 | null | 1 | 1 | dbcac4d6a9a3ee94710094e8312970b61f3db6f2 | 617 | SchemaBlock | Apache License 2.0 |
core-subscription/src/main/kotlin/io/vibrantnet/ryp/core/subscription/service/AccountsApiService.kt | nilscodes | 769,729,247 | false | {"Kotlin": 901616, "TypeScript": 887764, "Dockerfile": 8250, "Shell": 7536, "JavaScript": 1867} | package io.vibrantnet.ryp.core.subscription.service
import io.ryp.shared.model.LinkedExternalAccountDto
import io.ryp.shared.model.LinkedExternalAccountPartialDto
import io.vibrantnet.ryp.core.subscription.model.*
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
import java.time.Duration
interface AccountsApiService {
/**
* POST /accounts : Create New Account
* Create a new account.
*
* @param accountDto Post the necessary fields for the API to create a new user. (required)
* @return Account Created (status code 200)
* or Missing Required Information (status code 400)
* @see AccountsApi#createAccount
*/
fun createAccount(accountDto: AccountDto, referredBy: Long?): Mono<AccountDto>
/**
* GET /accounts/{accountId} : Get Account Info by numeric ID
* Retrieve the information of the account with the matching account ID.
*
* @param accountId The ID of an account (required)
* @return User Found (status code 200)
* or User Not Found (status code 404)
* @see AccountsApi#getAccountById
*/
fun getAccountById(accountId: Long): Mono<AccountDto>
/**
* GET /accounts/{providerType}/{referenceId} : Find Account by External Account Provider
* Look up an account by provider and the corresponding reference ID, to see if the account is used somewhere, without knowing the internal ID of the linked OWNER account
*
* @param providerType The provider or integration type for an external account (required)
* @param referenceId The reference ID used to identify the user in the external provider/integration (required)
* @return A matching account for the provider/reference ID combination provided. (status code 200)
* or No account under that provider type and reference ID was found. (status code 404)
* @see AccountsApi#findAccountByProviderAndReferenceId
*/
fun findAccountByProviderAndReferenceId(providerType: String, referenceId: String): Mono<AccountDto>
/**
* GET /accounts/{accountId}/externalaccounts : Show linked external accounts
*
* @param accountId (required)
* @return List of linked external accounts (status code 200)
* @see AccountsApi#getLinkedExternalAccounts
*/
fun getLinkedExternalAccounts(accountId: Long): Flux<LinkedExternalAccountDto>
/**
* PUT /accounts/{accountId}/externalaccounts/{externalAccountId} : Link existing external account
* Links an existing external account to this account (if possible)
*
* @param externalAccountId (required)
* @param accountId (required)
* @return The linked external account (status code 200)
* @see AccountsApi#linkExternalAccount
*/
fun linkExternalAccount(externalAccountId: Long, accountId: Long): Mono<LinkedExternalAccountDto>
/**
* PATCH /accounts/{accountId}/externalaccounts/{externalAccountId} : Update settings for a linked external account
* Updates an existing linked external account and changes its settings
*
* @param accountId The numeric ID of an account (required)
* @param externalAccountId The numeric ID of an external account (required)
* @param updateLinkedExternalAccountRequest (required)
* @return The updated linked external account (status code 200)
* @see AccountsApi#updateLinkedExternalAccount
*/
fun updateLinkedExternalAccount(accountId: Long, externalAccountId: Long, linkedExternalAccountPartial: LinkedExternalAccountPartialDto): Mono<LinkedExternalAccountDto>
/**
* DELETE /accounts/{accountId}/externalaccounts/{externalAccountId} : Unlink external account
* Unlink the external account from this account
*
* @param accountId (required)
* @param externalAccountId (required)
* @return Unlinking successful (status code 204)
* @see AccountsApi#unlinkExternalAccount
*/
fun unlinkExternalAccount(accountId: Long, externalAccountId: Long)
/**
* PATCH /accounts/{accountId} : Update Account Information
* Update the information of an existing user.
*
* @param accountId The numeric ID or UUID of an account (required)
* @param accountPartialDto Patch user properties to update. (required)
* @return Account Updated (status code 200)
* or User Not Found (status code 404)
* or Email Already Taken (status code 409)
* @see AccountsApi#updateAccountById
*/
fun updateAccountById(accountId: Long, accountPartialDto: AccountPartialDto): Mono<AccountDto>
/**
* PUT /accounts/{accountId}/subscriptions/projects/{projectId} : Add explicit subscription for this account and this project
*
* @param accountId The numeric ID of an account (required)
* @param projectId The numeric ID of a Project (required)
* @param newSubscription (required)
* @return OK (status code 200)
* @see AccountsApi#subscribeAccountToProject
*/
fun subscribeAccountToProject(accountId: Long, projectId: Long, newSubscription: NewSubscriptionDto): Mono<NewSubscriptionDto>
/**
* DELETE /accounts/{accountId}/subscriptions/projects/{projectId} : Remove explicit subscription for this account and project
*
* @param accountId The numeric ID of an account (required)
* @param projectId The numeric ID of a Project (required)
* @return Successful removal of explict subscriptioon status, rev (status code 204)
* @see AccountsApi#unsubscribeAccountFromProject
*/
fun unsubscribeAccountFromProject(accountId: Long, projectId: Long): Mono<Unit>
/**
* GET /accounts/{accountId}/subscriptions : Get all subscriptions for an account
*
* @param accountId The numeric ID of an account (required)
* @return All explicit subscriptions (subscribed and blocked) for this account. (status code 200)
* @see AccountsApi#getAllSubscriptionsForAccount
*/
fun getAllSubscriptionsForAccount(accountId: Long): Flux<ProjectSubscriptionDto>
/**
* GET /accounts/{accountId}/settings : Get settings for this account
* Get all settings that this account has configured.
*
* @param accountId The numeric ID of an account (required)
* @return All settings for this account (status code 200)
* @see AccountsApi#getSettingsForAccount
*/
fun getSettingsForAccount(accountId: Long): Mono<SettingsDto>
/**
* PUT /accounts/{accountId}/settings/{settingName} : Update account setting
* Create or update a single account setting with the provided value
*
* @param accountId The numeric ID of an account (required)
* @param settingName (required)
* @param setting (optional)
* @return AccountSetting (status code 200)
* @see AccountsApi#updateAccountSetting
*/
fun updateAccountSetting(accountId: Long, settingName: String, setting: SettingDto): Mono<SettingDto>
/**
* DELETE /accounts/{accountId}/settings/{settingName} : Delete account setting
* Delete a single account setting
*
* @param accountId The numeric ID of an account (required)
* @param settingName (required)
* @return Successful deletion (status code 204)
* @see AccountsApi#deleteAccountSetting
*/
fun deleteAccountSetting(accountId: Long, settingName: String): Mono<Unit>
/**
* GET /accounts/{accountId}/projects/{projectId}/notifications : Get project notification settings
* Get the current notification settings for this account on this project.
*
* @param accountId The numeric ID of an account (required)
* @param projectId The numeric ID of a Project (required)
* @return The current notification settings (status code 200)
* @see AccountsApi#getNotificationsSettingsForAccountAndProject
*/
fun getNotificationsSettingsForAccountAndProject(accountId: Long, projectId: Long): Flux<ProjectNotificationSettingDto>
/**
* PUT /accounts/{accountId}/projects/{projectId}/notifications : Update the notification settings
* Update the notification settings for this account on this project. Will remove any invalid settings, like notification settings for non-linked external accounts or external accounts that cannot receive notifications.
*
* @param accountId The numeric ID of an account (required)
* @param projectId The numeric ID of a Project (required)
* @param projectNotificationSettings (required)
* @return The confirmed notification settings (status code 200)
* @see AccountsApi#updateNotificationsSettingsForAccountAndProject
*/
fun updateNotificationsSettingsForAccountAndProject(accountId: Long, projectId: Long, projectNotificationSettings: List<ProjectNotificationSettingDto>): Flux<ProjectNotificationSettingDto>
fun extendPremium(accountId: Long, premiumDuration: Duration): Mono<AccountDto>
/**
* POST /accounts/{accountId}/externalaccounts/{externalAccountId}/subscriptionstatus : Resubscribe an explicitly unsubscribed external account
* In particular for emails and phone numbers it is possible to unsubscribe to comply with spam protection laws. This endpoint allows users to resubscribe. It verifies that the account has been verified recently (configurable) and if yes, re-enables the subscription.
*
* @param accountId The numeric ID of an account (required)
* @param externalAccountId The numeric ID of an external account (required)
* @param subscribe (required)
* @return If the account was not recently verified via this linked account, a resubscription is not possible and a 409 will be returned. (status code 409)
* or The confirmed subscription status (status code 200)
* @see AccountsApi#updateLinkedExternalAccountSubscriptionStatus
*/
fun updateLinkedExternalAccountSubscriptionStatus(accountId: Long, externalAccountId: Long, subscribe: Boolean): Mono<Boolean>
}
| 0 | Kotlin | 0 | 0 | a03ddb79eb7a71d0c440584c758cb5600c29c15e | 10,020 | reach-your-people | Apache License 2.0 |
designer/src/com/android/tools/idea/uibuilder/editor/multirepresentation/RepresentationName.kt | JetBrains | 60,701,247 | false | null | /*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.idea.uibuilder.editor.multirepresentation
/**
* A uniquely identifying display name of the corresponding [PreviewRepresentation]. It is used for
* a) Having a display string in the selection DropDownAction for a corresponding [PreviewRepresentation]
* b) Have a unique identifier for creating, storing and disposing [PreviewRepresentation]s, so that we do not create the same twice,
* know which we do not use anymore etc.
*/
typealias RepresentationName = String | 5 | null | 230 | 948 | 10110983c7e784122d94c7467e9d243aba943bf4 | 1,118 | android | Apache License 2.0 |
app/src/main/java/com/mostafahelal/AtmoDrive/auth/data/model/modelresponse/NewUser.kt | mostafa399 | 670,688,724 | false | {"Kotlin": 173866} | package com.mostafahelal.AtmoDrive.auth.data.model.modelresponse
import com.google.gson.annotations.SerializedName
data class NewUser(
@SerializedName("is_new")
val is_new: Boolean,
@SerializedName("full_name")
val full_name: String?,
)
| 0 | Kotlin | 0 | 0 | 6bab70a76af1f1bbd0ee714c390324512fc3570f | 255 | AtmoDrive | MIT License |
core/src/main/kotlin/com/malinskiy/marathon/analytics/tracker/remote/influx/InfluxDbTracker.kt | zoey-juan | 144,840,957 | true | {"Kotlin": 294489, "JavaScript": 33573, "CSS": 29044, "HTML": 2224, "Shell": 964} | package com.malinskiy.marathon.analytics.tracker.remote.influx
import com.malinskiy.marathon.analytics.tracker.NoOpTracker
import com.malinskiy.marathon.device.Device
import com.malinskiy.marathon.device.DevicePoolId
import com.malinskiy.marathon.execution.TestResult
import com.malinskiy.marathon.execution.TestStatus
import com.malinskiy.marathon.test.toSafeTestName
import org.influxdb.InfluxDB
import org.influxdb.dto.Point
import java.util.concurrent.TimeUnit
internal class InfluxDbTracker(private val influxDb: InfluxDB) : NoOpTracker() {
override fun trackTestResult(poolId: DevicePoolId, device: Device, testResult: TestResult) {
influxDb.write(Point.measurement("tests")
.time(System.currentTimeMillis(), TimeUnit.MILLISECONDS)
.tag("testname", testResult.test.toSafeTestName())
.addField("success", if (testResult.status == TestStatus.PASSED) 1.0 else 0.0)
.addField("duration", testResult.durationMillis())
.build())
}
override fun terminate() {
influxDb.close()
super.terminate()
}
}
| 0 | Kotlin | 0 | 0 | ad640271ade4aba49f28b58108068569f60e2caf | 1,120 | marathon | Apache License 2.0 |
src/test/java/org/jetbrains/plugins/ideavim/ex/implementation/commands/CmdCommandTest.kt | JetBrains | 1,459,486 | false | {"Kotlin": 5959132, "Java": 211095, "ANTLR": 84686, "HTML": 2184} | /*
* Copyright 2003-2023 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
package org.jetbrains.plugins.ideavim.ex.implementation.commands
import com.maddyhome.idea.vim.VimPlugin
import com.maddyhome.idea.vim.api.injector
import org.jetbrains.plugins.ideavim.VimTestCase
import org.junit.jupiter.api.Test
/**
* @author <NAME>
*/
class CmdCommandTest : VimTestCase() {
@Test
fun `test recursive`() {
VimPlugin.getCommand().resetAliases()
configureByText("\n")
typeText(commandToKeys("command Recur1 Recur2"))
assertPluginError(false)
typeText(commandToKeys("command Recur2 Recur1"))
assertPluginError(false)
typeText(commandToKeys("Recur1"))
assertPluginError(true) // Recursive command should error.
}
@Test
fun `test list aliases`() {
VimPlugin.getCommand().resetAliases()
configureByText("\n")
typeText(commandToKeys("command"))
assertPluginError(false)
assertExOutput("Name Args Definition\n") // There should not be any aliases.
typeText(commandToKeys("command Vs vs"))
assertPluginError(false)
typeText(commandToKeys("command Wq wq"))
assertPluginError(false)
typeText(commandToKeys("command WQ wq"))
assertPluginError(false)
typeText(commandToKeys("command-nargs=* Test1 echo"))
assertPluginError(false)
typeText(commandToKeys("command-nargs=? Test2 echo"))
assertPluginError(false)
typeText(commandToKeys("command-nargs=+ Test3 echo"))
assertPluginError(false)
typeText(commandToKeys("command-nargs=1 Test4 echo"))
assertPluginError(false)
typeText(commandToKeys("command"))
assertPluginError(false)
// The added alias should be listed
assertExOutput(
"""Name Args Definition
|Test1 * echo
|Test2 ? echo
|Test3 + echo
|Test4 1 echo
|Vs 0 vs
|Wq 0 wq
|WQ 0 wq
""".trimMargin(),
)
typeText(commandToKeys("command W"))
assertPluginError(false)
// The filtered aliases should be listed
assertExOutput(
"""Name Args Definition
|Wq 0 wq
|WQ 0 wq
""".trimMargin(),
)
}
@Test
fun `test bad alias`() {
VimPlugin.getCommand().resetAliases()
configureByText("\n")
typeText(commandToKeys("Xyz"))
assertPluginError(true)
typeText(commandToKeys("command Xyz yank"))
assertPluginError(false)
typeText(commandToKeys("Xyz"))
assertPluginError(false)
}
@Test
fun `test lowercase should fail`() {
VimPlugin.getCommand().resetAliases()
configureByText("\n")
typeText(commandToKeys("command lowercase vs"))
assertPluginError(true)
}
@Test
fun `test blacklisted alias should fail`() {
VimPlugin.getCommand().resetAliases()
configureByText("\n")
typeText(commandToKeys("command X vs"))
assertPluginError(true)
typeText(commandToKeys("command Next vs"))
assertPluginError(true)
typeText(commandToKeys("command Print vs"))
assertPluginError(true)
}
@Test
fun `test add an existing alias and overwrite`() {
VimPlugin.getCommand().resetAliases()
configureByText("\n")
typeText(commandToKeys("command Existing1 vs"))
assertPluginError(false)
typeText(commandToKeys("command Existing1 wq"))
assertPluginError(true)
typeText(commandToKeys("command! Existing1 wq"))
assertPluginError(false)
}
@Test
fun `test add command with arguments`() {
VimPlugin.getCommand().resetAliases()
configureByText("\n")
typeText(commandToKeys("command -nargs=* Error echo <args>"))
assertPluginError(false)
}
@Test
fun `test add command with range`() {
VimPlugin.getCommand().resetAliases()
configureByText("\n")
typeText(commandToKeys("command! -range Error echo <args>"))
assertPluginError(false)
kotlin.test.assertEquals("'-range' is not supported by `command`", injector.messages.getStatusBarMessage())
}
@Test
fun `test add command with complete`() {
VimPlugin.getCommand().resetAliases()
configureByText("\n")
typeText(commandToKeys("command! -complete=color Error echo <args>"))
assertPluginError(false)
kotlin.test.assertEquals("'-complete' is not supported by `command`", injector.messages.getStatusBarMessage())
}
@Test
fun `test add command with arguments short`() {
VimPlugin.getCommand().resetAliases()
configureByText("\n")
typeText(commandToKeys("command-nargs=* Error echo <args>"))
assertPluginError(false)
}
@Test
fun `test add command with arguments even shorter`() {
VimPlugin.getCommand().resetAliases()
configureByText("\n")
typeText(commandToKeys("com-nargs=* Error echo <args>"))
assertPluginError(false)
}
@Test
fun `test add command with various arguments`() {
VimPlugin.getCommand().resetAliases()
configureByText("\n")
typeText(commandToKeys("command! -nargs=0 Error echo <args>"))
assertPluginError(false)
typeText(commandToKeys("command! -nargs=1 Error echo <args>"))
assertPluginError(false)
typeText(commandToKeys("command! -nargs=* Error echo <args>"))
assertPluginError(false)
typeText(commandToKeys("command! -nargs=? Error echo <args>"))
assertPluginError(false)
typeText(commandToKeys("command! -nargs=+ Error echo <args>"))
assertPluginError(false)
}
@Test
fun `test add command with invalid arguments`() {
VimPlugin.getCommand().resetAliases()
configureByText("\n")
typeText(commandToKeys("command! -nargs= Error echo <args>"))
assertPluginError(true)
typeText(commandToKeys("command! -nargs=-1 Error echo <args>"))
assertPluginError(true)
typeText(commandToKeys("command! -nargs=# Error echo <args>"))
assertPluginError(true)
}
@Test
fun `test run command with arguments`() {
VimPlugin.getCommand().resetAliases()
configureByText("\n")
typeText(commandToKeys("let test = \"Hello!\""))
assertPluginError(false)
typeText(commandToKeys("command! -nargs=1 Error echo <args>"))
assertPluginError(false)
typeText(commandToKeys("Error test"))
assertPluginError(false)
assertExOutput("Hello!\n")
typeText(commandToKeys("command! -nargs=1 Error echo <q-args>"))
assertPluginError(false)
typeText(commandToKeys("Error test message"))
assertPluginError(false)
assertExOutput("test message\n")
}
@Test
fun `test run command that creates another command`() {
VimPlugin.getCommand().resetAliases()
configureByText("\n")
typeText(commandToKeys("command! -nargs=1 CreateCommand command -nargs=1 <args> <lt>q-args>"))
assertPluginError(false)
typeText(commandToKeys("CreateCommand Show echo"))
assertPluginError(false)
typeText(commandToKeys("Show test"))
assertPluginError(false)
assertExOutput("test\n")
}
@Test
fun `test run command missing required argument`() {
VimPlugin.getCommand().resetAliases()
configureByText("\n")
typeText(commandToKeys("command! -nargs=1 Error echo <q-args>"))
assertPluginError(false)
typeText(commandToKeys("Error"))
}
}
| 6 | Kotlin | 749 | 9,241 | 66b01b0b0d48ffec7b0148465b85e43dfbc908d3 | 7,447 | ideavim | MIT License |
ui/src/main/java/com/youhajun/ui/utils/GoogleBillingUtil.kt | YeonjunNotPed | 757,175,597 | false | {"Kotlin": 402548} | package com.youhajun.ui.utils
import android.app.Activity
import android.content.Context
import android.util.Log
import com.android.billingclient.api.AcknowledgePurchaseParams
import com.android.billingclient.api.BillingClient
import com.android.billingclient.api.BillingClient.ProductType
import com.android.billingclient.api.BillingClientStateListener
import com.android.billingclient.api.BillingFlowParams
import com.android.billingclient.api.BillingFlowParams.ProductDetailsParams
import com.android.billingclient.api.BillingFlowParams.SubscriptionUpdateParams
import com.android.billingclient.api.BillingFlowParams.SubscriptionUpdateParams.ReplacementMode
import com.android.billingclient.api.BillingResult
import com.android.billingclient.api.ConsumeParams
import com.android.billingclient.api.ProductDetails
import com.android.billingclient.api.ProductDetails.SubscriptionOfferDetails
import com.android.billingclient.api.ProductDetailsResult
import com.android.billingclient.api.Purchase
import com.android.billingclient.api.PurchasesResponseListener
import com.android.billingclient.api.PurchasesUpdatedListener
import com.android.billingclient.api.QueryProductDetailsParams
import com.android.billingclient.api.QueryPurchasesParams
import com.android.billingclient.api.acknowledgePurchase
import com.android.billingclient.api.consumePurchase
import com.android.billingclient.api.queryProductDetails
import com.youhajun.common.IoDispatcher
import com.youhajun.common.MainImmediateDispatcher
import com.youhajun.model_ui.types.store.PurchaseType
import com.youhajun.model_ui.vo.store.PurchaseItemVo
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.android.scopes.ViewModelScoped
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import javax.inject.Inject
@ViewModelScoped
class GoogleBillingUtil @Inject constructor(
@ApplicationContext private val context: Context,
@IoDispatcher private val ioDispatcher: CoroutineDispatcher,
@MainImmediateDispatcher private val mainImmediateDispatcher: CoroutineDispatcher
) {
interface Callback {
fun onConnectionError()
fun onLaunchBillingError()
fun onPurchaseError()
fun onPurchaseCancelByUser()
fun onProductDetailsEmptyOrNull()
fun onVerifyPurchase(purchase: Purchase)
fun onInAppPurchaseSuccess(purchase: Purchase)
fun onSubsPurchaseSuccess(purchase: Purchase)
}
companion object {
private const val TAG = "billing"
private const val MAX_RETRY_CONNECT_COUNT = 3
}
private var retryCount = 0
private var callback: Callback? = null
private var currentPurchaseToken: String? = null
private var productDetailsMap: HashMap<String, ProductDetails> = hashMapOf()
private lateinit var inAppProductQueryList: List<QueryProductDetailsParams.Product>
private lateinit var subsProductQueryList: List<QueryProductDetailsParams.Product>
private val purchasesUpdatedListener = PurchasesUpdatedListener(::purchaseListener)
private val purchaseResponseListener = PurchasesResponseListener(::purchaseListener)
private val scope = CoroutineScope(Job() + mainImmediateDispatcher)
private val billingClient: BillingClient by lazy {
BillingClient.newBuilder(context)
.setListener(purchasesUpdatedListener)
.enablePendingPurchases()
.build()
}
fun cleanUp() {
scope.cancel()
billingClient.endConnection()
}
fun onStartConnect(callback: Callback, purchaseItemList: List<PurchaseItemVo>) {
this.callback = callback
initProductQueryList(purchaseItemList)
startConnection()
}
fun onLaunchBillingFlow(
productIds: List<String>,
activity: Activity,
basePlanId: String? = null,
) {
Log.d(TAG, "onLaunchBillingFlow $productIds $basePlanId")
if (productIds.contains("") || productDetailsMap.isEmpty() || !billingClient.isReady) return
runCatching {
val params = if (basePlanId.isNullOrEmpty()) {
getBillingFlowParams(productIds, null, null)
} else {
getBillingFlowParams(productIds, basePlanId, currentPurchaseToken)
}
launchBillingFlow(activity, params)
}.onFailure { e ->
callback?.onLaunchBillingError()
Log.e(TAG, "onLaunchBillingFlow failed: ${e.message}")
}
}
fun onPurchaseVerifySuccess(purchase: Purchase) {
Log.d(TAG, "onPurchaseVerifySuccess : ${purchase.isAutoRenewing}")
scope.launch {
if (purchase.isAutoRenewing) approveSubPurchase(purchase)
approveInAppPurchase(purchase)
}
}
private fun initProductQueryList(purchaseItemList: List<PurchaseItemVo>) {
Log.d(TAG, "initProductQueryListInApp : ${purchaseItemList.filterNot { it.purchaseType == PurchaseType.SUBS }.distinctBy { it.productId }}")
Log.d(TAG,"initProductQueryListSubs : ${purchaseItemList.filter { it.purchaseType == PurchaseType.SUBS }.distinctBy { it.productId }}")
inAppProductQueryList = purchaseItemList.filterNot { it.purchaseType == PurchaseType.SUBS }
.distinctBy { it.productId }
.map { convertToProductQuery(it) }
subsProductQueryList = purchaseItemList.filter { it.purchaseType == PurchaseType.SUBS }
.distinctBy { it.productId }
.map { convertToProductQuery(it) }
}
private fun convertToProductQuery(item: PurchaseItemVo): QueryProductDetailsParams.Product {
val productType = when (item.purchaseType) {
PurchaseType.IN_APP_MULTIPLE,
PurchaseType.IN_APP -> ProductType.INAPP
PurchaseType.SUBS -> ProductType.SUBS
}
return QueryProductDetailsParams
.Product
.newBuilder()
.setProductId(item.productId)
.setProductType(productType)
.build()
}
private fun getBillingFlowParams(
productIds: List<String>,
basePlanId: String?,
oldPurchaseToken: String?
): BillingFlowParams {
Log.d(TAG, "getBillingFlowParams")
val productDetails = productIds.mapNotNull { productDetailsMap[it] }
val productParams = productDetails.map { buildProductDetailsParams(it, basePlanId) }
return buildBillingFlowParams(productParams, oldPurchaseToken)
}
private fun buildProductDetailsParams(
productDetails: ProductDetails,
basePlanId: String?
): ProductDetailsParams {
Log.d(TAG, "buildProductDetailsParams")
val builder = ProductDetailsParams.newBuilder().setProductDetails(productDetails)
if (!basePlanId.isNullOrEmpty()) {
val offerToken = getOfferToken(productDetails.subscriptionOfferDetails, basePlanId)
Log.d(TAG, "buildProductDetailsParams Token : $offerToken")
builder.setOfferToken(offerToken)
}
return builder.build()
}
private fun buildBillingFlowParams(
productDetailsParams: List<ProductDetailsParams>,
oldPurchaseToken: String?
): BillingFlowParams {
val builder = BillingFlowParams.newBuilder().setProductDetailsParamsList(productDetailsParams)
if (!oldPurchaseToken.isNullOrEmpty()) {
builder.setSubscriptionUpdateParams(buildSubsUpdateParams(oldPurchaseToken))
}
return builder.build()
}
private fun buildSubsUpdateParams(oldPurchaseToken: String): SubscriptionUpdateParams {
Log.d(TAG, "buildSubsUpdateParams Token : $oldPurchaseToken")
return SubscriptionUpdateParams.newBuilder()
.setOldPurchaseToken(oldPurchaseToken)
.setSubscriptionReplacementMode(ReplacementMode.CHARGE_FULL_PRICE)
.build()
}
private fun startConnection() {
Log.d(TAG, "connection start")
billingClient.startConnection(object : BillingClientStateListener {
override fun onBillingSetupFinished(billingResult: BillingResult) {
if (billingResult.responseCode == BillingClient.BillingResponseCode.OK) {
Log.d(TAG, "connection success")
onCheckPurchaseSynchronize()
scope.launch {
queryProductDetails(PurchaseType.IN_APP)
queryProductDetails(PurchaseType.SUBS)
}
} else callback?.onConnectionError()
}
override fun onBillingServiceDisconnected() {
if (retryCount < MAX_RETRY_CONNECT_COUNT) {
retryCount++
startConnection()
} else callback?.onConnectionError()
}
})
}
private fun onCheckPurchaseSynchronize() {
val params = QueryPurchasesParams.newBuilder().setProductType(ProductType.INAPP).build()
billingClient.queryPurchasesAsync(params, purchaseResponseListener)
}
private suspend fun queryProductDetails(purchaseType: PurchaseType) {
val params = buildQueryProductDetailsParams(purchaseType)
val productDetailsResult = withContext(ioDispatcher) {
billingClient.queryProductDetails(params)
}
handleProductDetailsResult(productDetailsResult)
}
private fun buildQueryProductDetailsParams(purchaseType: PurchaseType): QueryProductDetailsParams {
val list = if (purchaseType == PurchaseType.SUBS) subsProductQueryList else inAppProductQueryList
return QueryProductDetailsParams
.newBuilder()
.setProductList(list)
.build()
}
private fun handleProductDetailsResult(productDetailsResult: ProductDetailsResult) {
Log.d(TAG,"${productDetailsResult.billingResult.debugMessage}, ${productDetailsResult.productDetailsList?.size}개")
if (productDetailsResult.billingResult.responseCode == BillingClient.BillingResponseCode.OK) {
productDetailsResult.productDetailsList?.let {
productDetailsMap.putAll(it.associateBy { it.productId })
}
} else callback?.onProductDetailsEmptyOrNull()
}
private fun purchaseListener(billingResult: BillingResult, purchases: List<Purchase>?) {
Log.d(TAG,"purchaseListener")
when (billingResult.responseCode) {
BillingClient.BillingResponseCode.OK -> {
purchases?.forEach {
handlePurchase(it)
} ?: callback?.onPurchaseError()
}
BillingClient.BillingResponseCode.USER_CANCELED -> {
callback?.onPurchaseCancelByUser()
}
else -> callback?.onPurchaseError()
}
}
private fun handlePurchase(purchase: Purchase) {
Log.d(TAG,"purchaseListener")
when (purchase.purchaseState) {
Purchase.PurchaseState.PURCHASED -> {
Log.d(TAG, "processPurchasesPurchase: $purchase")
when {
!purchase.isAcknowledged -> callback?.onVerifyPurchase(purchase)
purchase.isAutoRenewing -> currentPurchaseToken = purchase.purchaseToken
}
}
Purchase.PurchaseState.PENDING -> {
Log.d(TAG, "processPurchasesPending: $purchase")
}
else -> callback?.onPurchaseError()
}
}
private suspend fun approveInAppPurchase(purchase: Purchase) {
val consumeParams = ConsumeParams.newBuilder()
.setPurchaseToken(purchase.purchaseToken)
.build()
val result = withContext(ioDispatcher) {
billingClient.consumePurchase(consumeParams)
}
handlePurchaseFinish(false, result.billingResult.responseCode, purchase)
}
private suspend fun approveSubPurchase(purchase: Purchase) {
val acknowledgePurchaseParams = AcknowledgePurchaseParams.newBuilder()
.setPurchaseToken(purchase.purchaseToken)
.build()
val result = withContext(ioDispatcher) {
billingClient.acknowledgePurchase(acknowledgePurchaseParams)
}
handlePurchaseFinish(true, result.responseCode, purchase)
}
private fun handlePurchaseFinish(isSubs: Boolean, responseCode: Int, purchase: Purchase) {
Log.d(TAG, "purchaseSuccess : $responseCode")
when (responseCode) {
BillingClient.BillingResponseCode.OK -> {
if (isSubs) callback?.onSubsPurchaseSuccess(purchase)
else callback?.onInAppPurchaseSuccess(purchase)
}
else -> callback?.onPurchaseError()
}
}
private fun launchBillingFlow(activity: Activity, params: BillingFlowParams) {
val launchResult = billingClient.launchBillingFlow(activity, params)
when (launchResult.responseCode) {
BillingClient.BillingResponseCode.OK -> {
Log.d(TAG, "onSuccessBillingLaunch : ${launchResult.debugMessage}")
}
else -> callback?.onLaunchBillingError()
}
}
private fun getOfferToken(list: List<SubscriptionOfferDetails>?, basePlanId: String): String {
return list?.let {
it.find { it.basePlanId == basePlanId }?.offerToken ?: it.first().offerToken
} ?: ""
}
} | 0 | Kotlin | 0 | 0 | d097fe886b1d8d030569765d8a10edd461e89830 | 13,575 | MyTask | Apache License 2.0 |
shared/src/commonMain/kotlin/com/example/voyager_screens_delegation_sample/App.kt | bidapphub | 811,808,219 | false | {"Kotlin": 12554, "Swift": 534} | package com.example.voyager_screens_delegation_sample
import androidx.compose.foundation.shape.AbsoluteCutCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.unit.dp
import cafe.adriel.voyager.navigator.Navigator
import cafe.adriel.voyager.transitions.SlideTransition
import com.example.voyager_screens_delegation.FirstScreen.FirstScreen
@Composable
fun App() {
MaterialTheme(
colorScheme = lightColorScheme(),
shapes = MaterialTheme.shapes.copy(
small = AbsoluteCutCornerShape(0.dp),
medium = AbsoluteCutCornerShape(0.dp),
large = AbsoluteCutCornerShape(0.dp)
)
) {
Navigator(
screen = FirstScreen(),
content = { navigator ->
SlideTransition(navigator = navigator)
}
)
}
} | 0 | Kotlin | 0 | 0 | 5b454633f8adfa5611d370ad4a80955fd84488ea | 874 | kotlin-multiplatform_voyager-screens-delegation-sample | MIT License |
lib.core/src/main/java/com/coding/zxm/lib_core/base/FragmentLazyLifecycleOwner.kt | ZhangXinmin528 | 117,549,346 | false | {"Java": 728866, "Kotlin": 166497} | package com.coding.zxm.lib_core.base
import androidx.lifecycle.*
/**
* Created by ZhangXinmin on 2021/06/10.
* Copyright (c) 2021/6/10 . All rights reserved.
*/
class FragmentLazyLifecycleOwner(private val mCallback: Callback) : LifecycleObserver,
LifecycleOwner {
private var mLifecycleRegistry: LifecycleRegistry? = null
private var mIsViewVisible = true
private var mViewState = Lifecycle.State.INITIALIZED
private fun initialize() {
if (mLifecycleRegistry == null) {
mLifecycleRegistry = LifecycleRegistry(this)
}
}
fun setViewVisible(viewVisible: Boolean) {
if (mViewState < Lifecycle.State.CREATED || !isInitialized()) {
// not trust it before onCreate
return
}
mIsViewVisible = viewVisible
if (viewVisible) {
mLifecycleRegistry?.markState(mViewState)
} else {
if (mViewState > Lifecycle.State.CREATED) {
mLifecycleRegistry?.markState(Lifecycle.State.CREATED)
} else {
mLifecycleRegistry?.markState(mViewState)
}
}
}
/**
* @return True if the Lifecycle has been initialized.
*/
fun isInitialized(): Boolean {
return mLifecycleRegistry != null
}
override fun getLifecycle(): Lifecycle {
initialize()
return mLifecycleRegistry!!
}
private fun handleLifecycleEvent(event: Lifecycle.Event) {
initialize()
mLifecycleRegistry?.handleLifecycleEvent(event)
}
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
fun onCreate(owner: LifecycleOwner?) {
mIsViewVisible = mCallback.isVisibleToUser()
mViewState = Lifecycle.State.CREATED
handleLifecycleEvent(Lifecycle.Event.ON_CREATE)
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun onStart(owner: LifecycleOwner?) {
mViewState = Lifecycle.State.STARTED
if (mIsViewVisible) {
handleLifecycleEvent(Lifecycle.Event.ON_START)
}
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
fun onResume(owner: LifecycleOwner?) {
mViewState = Lifecycle.State.RESUMED
if (mIsViewVisible && mLifecycleRegistry!!.currentState == Lifecycle.State.STARTED) {
handleLifecycleEvent(Lifecycle.Event.ON_RESUME)
}
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
fun onPause(owner: LifecycleOwner?) {
mViewState = Lifecycle.State.STARTED
if (mLifecycleRegistry!!.currentState.isAtLeast(Lifecycle.State.RESUMED)) {
handleLifecycleEvent(Lifecycle.Event.ON_PAUSE)
}
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun onStop(owner: LifecycleOwner?) {
mViewState = Lifecycle.State.CREATED
if (mLifecycleRegistry!!.currentState.isAtLeast(Lifecycle.State.STARTED)) {
handleLifecycleEvent(Lifecycle.Event.ON_STOP)
}
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
fun onDestroy(owner: LifecycleOwner?) {
mViewState = Lifecycle.State.DESTROYED
handleLifecycleEvent(Lifecycle.Event.ON_DESTROY)
}
interface Callback {
fun isVisibleToUser(): Boolean
}
}
| 0 | Java | 1 | 5 | 6b49ab3ada9691543aa85e0fecf091f93b910e47 | 3,228 | AndroidUtils | Apache License 2.0 |
app/src/main/java/developersancho/githubinginterview/di/ViewModelModule.kt | developersancho | 218,074,647 | false | {"Gradle": 3, "Java Properties": 2, "Shell": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 55, "JSON": 2, "XML": 40, "Java": 2} | package developersancho.githubinginterview.di
import developersancho.githubinginterview.ui.detail.DetailViewModel
import developersancho.githubinginterview.ui.home.HomeViewModel
import org.koin.androidx.viewmodel.dsl.viewModel
import org.koin.dsl.module
val viewModelModule = module {
viewModel { HomeViewModel(get()) }
viewModel { DetailViewModel(get()) }
} | 1 | null | 1 | 1 | 3939218adde97051b5635da61a1cc44ea6fdb7ac | 368 | GithubIngInterview | Apache License 2.0 |
sqlite-embedder-chasm/src/commonMain/kotlin/ext/BindingsExt.kt | illarionov | 769,429,996 | false | {"Kotlin": 867941} | /*
* Copyright 2024, the wasm-sqlite-open-helper project authors and contributors. Please see the AUTHORS file
* for details. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
* SPDX-License-Identifier: Apache-2.0
*/
package ru.pixnews.wasm.sqlite.open.helper.chasm.ext
import at.released.weh.wasm.core.WasmFunctionBinding
import io.github.charlietap.chasm.embedding.exports
import ru.pixnews.wasm.sqlite.open.helper.chasm.exports.ChasmFunctionBinding
import ru.pixnews.wasm.sqlite.open.helper.chasm.host.ChasmInstanceBuilder.ChasmInstance
import ru.pixnews.wasm.sqlite.open.helper.embedder.exports.SinglePropertyLazyValue
import kotlin.concurrent.Volatile
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty
internal fun ChasmInstance.functionMember(): ReadOnlyProperty<Any?, WasmFunctionBinding> {
return object : ReadOnlyProperty<Any?, WasmFunctionBinding> {
@Volatile
private var binding: SinglePropertyLazyValue<WasmFunctionBinding> = SinglePropertyLazyValue { propertyName ->
exports(instance).find { it.name == propertyName }
?: error("Property $propertyName not found")
ChasmFunctionBinding(store, instance, propertyName)
}
override fun getValue(thisRef: Any?, property: KProperty<*>): WasmFunctionBinding {
return binding.get(property)
}
}
}
| 0 | Kotlin | 1 | 3 | 90c45b7cfe512c0dfcffbc4a77bb24cc0040b16d | 1,432 | wasm-sqlite-open-helper | Apache License 2.0 |
chat/src/main/kotlin/br/edu/uea/redes/chat/service/AuthenticationService.kt | adevancomp | 753,041,990 | false | {"Kotlin": 21822} | package br.edu.uea.redes.chat.service
import br.edu.uea.redes.chat.config.properties.JwtProperties
import br.edu.uea.redes.chat.dto.AuthenticationRequest
import br.edu.uea.redes.chat.dto.AuthenticationResponse
import org.springframework.security.authentication.AuthenticationManager
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.stereotype.Service
import java.util.*
@Service
class AuthenticationService (
private val authManager: AuthenticationManager,
private val userDetailsService: CustomUserDetailsService,
private val tokenService: TokenService,
private val jwtProperties: JwtProperties
){
fun authentication(authenticationRequest: AuthenticationRequest) : AuthenticationResponse {
authManager.authenticate(
UsernamePasswordAuthenticationToken(
authenticationRequest.email,
authenticationRequest.password
)
)
val user = userDetailsService.loadUserByUsername(authenticationRequest.email)
val accessToken = createToken(user)
return AuthenticationResponse(
accessToken
)
}
private fun createToken(user:UserDetails): String = tokenService.generate(user, getAccessTokenExpiration())
private fun getAccessTokenExpiration() : Date =
Date(System.currentTimeMillis()+jwtProperties.accessTokenExpiration)
} | 0 | Kotlin | 0 | 0 | ed269b3f9ee60725760d367fe56895abe70825ba | 1,500 | redes-2 | Apache License 2.0 |
fabric/src/main/kotlin/ru/astrainteractive/astratemplate/command/HelloWorldCommand.kt | Rammahhh | 628,461,968 | false | null | package ru.astrainteractive.astratemplate.command
import com.astrainteractive.astratemplate.api.dto.UserDTO
import com.mojang.brigadier.context.CommandContext
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import net.minecraft.server.command.ServerCommandSource
import ru.astrainteractive.astralibs.async.PluginScope
import ru.astrainteractive.astralibs.di.getValue
import ru.astrainteractive.astratemplate.ServiceLocator
import java.util.UUID
fun command(literal: String, block: (CommandContext<ServerCommandSource>) -> Unit) = object : Command(literal) {
override fun onCommand(commandContext: CommandContext<ServerCommandSource>): Int {
block(commandContext)
return 1
}
}
val HelloWorldCommand = command("helloworld") {
println(ServiceLocator.helloWorldModule.value)
}
val RickMortyCommand = command("rickmorty") {
val rmApi by ServiceLocator.rmApiModule
PluginScope.launch(Dispatchers.IO) {
println(rmApi.getRandomCharacter(1))
}
}
val InsertUserCommand = command("insertuser") {
val localApi by ServiceLocator.localApi
PluginScope.launch(Dispatchers.IO) {
println(localApi.insertUser(UserDTO(-1, UUID.randomUUID().toString(), UUID.randomUUID().toString())))
}
}
val GetAllUsersCommand = command("getallusers") {
val localApi by ServiceLocator.localApi
PluginScope.launch(Dispatchers.IO) {
println(localApi.getAllUsers())
}
}
| 0 | Kotlin | 0 | 0 | e8677c117b048eb72c0badc6e70bc4342b87a065 | 1,445 | PluginTempalte | MIT License |
card/src/main/java/com/adyen/checkout/card/internal/ui/view/CardView.kt | Adyen | 91,104,663 | false | null | /*
* Copyright (c) 2022 Adyen N.V.
*
* This file is open source and available under the MIT license. See the LICENSE file for more info.
*
* Created by josephj on 16/9/2022.
*/
package com.adyen.checkout.card.internal.ui.view
import android.app.Activity
import android.content.Context
import android.content.ContextWrapper
import android.text.Editable
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.View.OnFocusChangeListener
import android.view.WindowManager
import android.widget.AdapterView
import android.widget.LinearLayout
import androidx.annotation.RestrictTo
import androidx.annotation.StringRes
import androidx.core.view.isVisible
import com.adyen.checkout.card.CardBrand
import com.adyen.checkout.card.CardComponent
import com.adyen.checkout.card.CardType
import com.adyen.checkout.card.R
import com.adyen.checkout.card.databinding.CardViewBinding
import com.adyen.checkout.card.internal.data.model.DetectedCardType
import com.adyen.checkout.card.internal.ui.CardDelegate
import com.adyen.checkout.card.internal.ui.model.CardListItem
import com.adyen.checkout.card.internal.ui.model.CardOutputData
import com.adyen.checkout.card.internal.ui.model.ExpiryDate
import com.adyen.checkout.card.internal.ui.model.InputFieldUIState
import com.adyen.checkout.card.internal.util.InstallmentUtils
import com.adyen.checkout.components.core.internal.ui.ComponentDelegate
import com.adyen.checkout.components.core.internal.ui.model.FieldState
import com.adyen.checkout.components.core.internal.ui.model.Validation
import com.adyen.checkout.core.exception.CheckoutException
import com.adyen.checkout.core.internal.util.BuildUtils
import com.adyen.checkout.ui.core.internal.ui.AddressFormUIState
import com.adyen.checkout.ui.core.internal.ui.ComponentView
import com.adyen.checkout.ui.core.internal.ui.loadLogo
import com.adyen.checkout.ui.core.internal.ui.view.AdyenTextInputEditText
import com.adyen.checkout.ui.core.internal.ui.view.RoundCornerImageView
import com.adyen.checkout.ui.core.internal.util.hideError
import com.adyen.checkout.ui.core.internal.util.isVisible
import com.adyen.checkout.ui.core.internal.util.setLocalizedHintFromStyle
import com.adyen.checkout.ui.core.internal.util.setLocalizedTextFromStyle
import com.adyen.checkout.ui.core.internal.util.showError
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
/**
* CardView for [CardComponent].
*/
@Suppress("TooManyFunctions", "LargeClass")
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
class CardView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) :
LinearLayout(
context,
attrs,
defStyleAttr
),
ComponentView {
private val binding: CardViewBinding = CardViewBinding.inflate(LayoutInflater.from(context), this)
private var installmentListAdapter: InstallmentListAdapter? = null
private var cardListAdapter: CardListAdapter? = null
private lateinit var localizedContext: Context
private lateinit var cardDelegate: CardDelegate
init {
orientation = VERTICAL
val padding = resources.getDimension(R.dimen.standard_margin).toInt()
setPadding(padding, padding, padding, 0)
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
if (!BuildUtils.isDebugBuild(context)) {
// Prevent taking screenshot and screen on recents.
getActivity(context)?.window?.addFlags(WindowManager.LayoutParams.FLAG_SECURE)
}
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
if (!BuildUtils.isDebugBuild(context)) {
getActivity(context)?.window?.clearFlags(WindowManager.LayoutParams.FLAG_SECURE)
}
}
override fun initView(delegate: ComponentDelegate, coroutineScope: CoroutineScope, localizedContext: Context) {
require(delegate is CardDelegate) { "Unsupported delegate type" }
cardDelegate = delegate
this.localizedContext = localizedContext
initLocalizedStrings(localizedContext)
observeDelegate(delegate, coroutineScope)
initCardNumberInput()
initExpiryDateInput()
initSecurityCodeInput()
initHolderNameInput()
initSocialSecurityNumberInput()
initKcpAuthenticationInput()
initPostalCodeInput()
initAddressFormInput(coroutineScope)
binding.switchStorePaymentMethod.setOnCheckedChangeListener { _, isChecked ->
delegate.updateInputData { isStorePaymentMethodSwitchChecked = isChecked }
}
}
private fun initLocalizedStrings(localizedContext: Context) {
binding.textInputLayoutCardNumber.setLocalizedHintFromStyle(
R.style.AdyenCheckout_Card_CardNumberInput,
localizedContext
)
binding.textInputLayoutExpiryDate.setLocalizedHintFromStyle(
R.style.AdyenCheckout_Card_ExpiryDateInput,
localizedContext
)
binding.textInputLayoutSecurityCode.setLocalizedHintFromStyle(
R.style.AdyenCheckout_Card_SecurityCodeInput,
localizedContext
)
binding.textInputLayoutCardHolder.setLocalizedHintFromStyle(
R.style.AdyenCheckout_Card_HolderNameInput,
localizedContext
)
binding.textInputLayoutPostalCode.setLocalizedHintFromStyle(
R.style.AdyenCheckout_PostalCodeInput,
localizedContext
)
binding.textInputLayoutSocialSecurityNumber.setLocalizedHintFromStyle(
R.style.AdyenCheckout_Card_SocialSecurityNumberInput,
localizedContext
)
binding.textInputLayoutKcpBirthDateOrTaxNumber.setLocalizedHintFromStyle(
R.style.AdyenCheckout_Card_KcpBirthDateOrTaxNumber,
localizedContext
)
binding.textInputLayoutKcpCardPassword.setLocalizedHintFromStyle(
R.style.AdyenCheckout_Card_KcpCardPassword,
localizedContext
)
binding.textInputLayoutInstallments.setLocalizedHintFromStyle(
R.style.AdyenCheckout_DropdownTextInputLayout_Installments,
localizedContext
)
binding.switchStorePaymentMethod.setLocalizedTextFromStyle(
R.style.AdyenCheckout_Card_StorePaymentSwitch,
localizedContext
)
binding.addressFormInput.initLocalizedContext(localizedContext)
}
private fun observeDelegate(delegate: CardDelegate, coroutineScope: CoroutineScope) {
delegate.outputDataFlow
.onEach { outputDataChanged(it) }
.launchIn(coroutineScope)
}
private fun outputDataChanged(cardOutputData: CardOutputData) {
onCardNumberValidated(cardOutputData)
onExpiryDateValidated(cardOutputData.expiryDateState)
setSocialSecurityNumberVisibility(cardOutputData.isSocialSecurityNumberRequired)
setKcpAuthVisibility(cardOutputData.isKCPAuthRequired)
setKcpHint(cardOutputData.kcpBirthDateOrTaxNumberHint)
setAddressInputVisibility(cardOutputData.addressUIState)
handleCvcUIState(cardOutputData.cvcUIState)
handleExpiryDateUIState(cardOutputData.expiryDateUIState)
handleHolderNameUIState(cardOutputData.holderNameUIState)
setStorePaymentSwitchVisibility(cardOutputData.showStorePaymentField)
updateInstallments(cardOutputData)
updateAddressHint(cardOutputData.addressUIState, cardOutputData.addressState.isOptional)
setCardList(cardOutputData.cardBrands, cardOutputData.isCardListVisible)
}
@Suppress("ComplexMethod", "LongMethod")
override fun highlightValidationErrors() {
cardDelegate.outputData.let {
var isErrorFocused = false
val cardNumberValidation = it.cardNumberState.validation
if (cardNumberValidation is Validation.Invalid) {
isErrorFocused = true
binding.editTextCardNumber.requestFocus()
setCardNumberError(cardNumberValidation.reason)
}
val expiryDateValidation = it.expiryDateState.validation
if (expiryDateValidation is Validation.Invalid) {
if (!isErrorFocused) {
isErrorFocused = true
binding.textInputLayoutExpiryDate.requestFocus()
}
binding.textInputLayoutExpiryDate.showError(localizedContext.getString(expiryDateValidation.reason))
}
val securityCodeValidation = it.securityCodeState.validation
if (securityCodeValidation is Validation.Invalid) {
if (!isErrorFocused) {
isErrorFocused = true
binding.textInputLayoutSecurityCode.requestFocus()
}
binding.textInputLayoutSecurityCode.showError(localizedContext.getString(securityCodeValidation.reason))
}
val holderNameValidation = it.holderNameState.validation
if (binding.textInputLayoutCardHolder.isVisible && holderNameValidation is Validation.Invalid) {
if (!isErrorFocused) {
isErrorFocused = true
binding.textInputLayoutCardHolder.requestFocus()
}
binding.textInputLayoutCardHolder.showError(localizedContext.getString(holderNameValidation.reason))
}
val postalCodeValidation = it.addressState.postalCode.validation
if (binding.textInputLayoutPostalCode.isVisible && postalCodeValidation is Validation.Invalid) {
if (!isErrorFocused) {
isErrorFocused = true
binding.textInputLayoutPostalCode.requestFocus()
}
binding.textInputLayoutPostalCode.showError(localizedContext.getString(postalCodeValidation.reason))
}
val socialSecurityNumberValidation = it.socialSecurityNumberState.validation
if (binding.textInputLayoutSocialSecurityNumber.isVisible &&
socialSecurityNumberValidation is Validation.Invalid
) {
if (!isErrorFocused) {
isErrorFocused = true
binding.textInputLayoutSocialSecurityNumber.requestFocus()
}
binding.textInputLayoutSocialSecurityNumber.showError(
localizedContext.getString(socialSecurityNumberValidation.reason)
)
}
val kcpBirthDateOrTaxNumberValidation = it.kcpBirthDateOrTaxNumberState.validation
if (binding.textInputLayoutKcpBirthDateOrTaxNumber.isVisible &&
kcpBirthDateOrTaxNumberValidation is Validation.Invalid
) {
if (!isErrorFocused) {
isErrorFocused = true
binding.textInputLayoutKcpBirthDateOrTaxNumber.requestFocus()
}
binding.textInputLayoutKcpBirthDateOrTaxNumber.showError(
localizedContext.getString(kcpBirthDateOrTaxNumberValidation.reason)
)
}
val kcpPasswordValidation = it.kcpCardPasswordState.validation
if (binding.textInputLayoutKcpCardPassword.isVisible && kcpPasswordValidation is Validation.Invalid) {
if (!isErrorFocused) {
isErrorFocused = true
binding.textInputLayoutKcpCardPassword.requestFocus()
}
binding.textInputLayoutKcpCardPassword.showError(
localizedContext.getString(kcpPasswordValidation.reason)
)
}
if (binding.addressFormInput.isVisible && !it.addressState.isValid) {
binding.addressFormInput.highlightValidationErrors(isErrorFocused)
}
}
}
private fun onCardNumberValidated(cardOutputData: CardOutputData) {
val detectedCardTypes = cardOutputData.detectedCardTypes
if (detectedCardTypes.isEmpty()) {
binding.cardBrandLogoImageViewPrimary.apply {
strokeWidth = 0f
setImageResource(R.drawable.ic_card)
alpha = 1f
}
binding.cardBrandLogoContainerSecondary.isVisible = false
binding.editTextCardNumber.setAmexCardFormat(false)
resetBrandSelectionInput()
} else {
val firtDetectedCardType = detectedCardTypes.first()
binding.cardBrandLogoImageViewPrimary.strokeWidth = RoundCornerImageView.DEFAULT_STROKE_WIDTH
binding.cardBrandLogoImageViewPrimary.loadLogo(
environment = cardDelegate.componentParams.environment,
txVariant = detectedCardTypes[0].cardBrand.txVariant,
placeholder = R.drawable.ic_card,
errorFallback = R.drawable.ic_card,
)
setDualBrandedCardImages(detectedCardTypes, cardOutputData.cardNumberState.validation)
// TODO: 29/01/2021 get this logic from OutputData
val isAmex = detectedCardTypes.any { it.cardBrand == CardBrand(cardType = CardType.AMERICAN_EXPRESS) }
binding.editTextCardNumber.setAmexCardFormat(isAmex)
if (detectedCardTypes.size == 1 &&
firtDetectedCardType.panLength == binding.editTextCardNumber.rawValue.length
) {
val cardNumberValidation = cardOutputData.cardNumberState.validation
if (cardNumberValidation is Validation.Invalid) {
setCardNumberError(cardNumberValidation.reason)
} else {
goToNextInputIfFocus(binding.editTextCardNumber)
}
}
}
}
private fun setDualBrandedCardImages(detectedCardTypes: List<DetectedCardType>, validation: Validation) {
val cardNumberHasFocus = binding.textInputLayoutCardNumber.hasFocus()
if (validation is Validation.Invalid && !cardNumberHasFocus) {
setCardNumberError(validation.reason)
} else {
detectedCardTypes.getOrNull(1)?.takeIf { it.isReliable }?.let { detectedCardType ->
binding.cardBrandLogoContainerSecondary.isVisible = true
binding.cardBrandLogoImageViewSecondary.strokeWidth = RoundCornerImageView.DEFAULT_STROKE_WIDTH
binding.cardBrandLogoImageViewSecondary.loadLogo(
environment = cardDelegate.componentParams.environment,
txVariant = detectedCardType.cardBrand.txVariant,
placeholder = R.drawable.ic_card,
errorFallback = R.drawable.ic_card,
)
initCardBrandLogoViews(detectedCardTypes.indexOfFirst { it.isSelected })
initBrandSelectionListeners()
} ?: run {
binding.cardBrandLogoImageViewPrimary.alpha = 1f
binding.cardBrandLogoContainerSecondary.isVisible = false
resetBrandSelectionInput()
}
}
}
private fun onExpiryDateValidated(expiryDateState: FieldState<ExpiryDate>) {
if (expiryDateState.validation.isValid()) {
goToNextInputIfFocus(binding.editTextExpiryDate)
}
}
private fun goToNextInputIfFocus(view: View?) {
if (rootView.findFocus() === view && view != null) {
findViewById<View>(view.nextFocusForwardId).requestFocus()
}
}
private fun initCardNumberInput() {
binding.editTextCardNumber.setOnChangeListener {
setCardErrorState(true)
cardDelegate.updateInputData { cardNumber = binding.editTextCardNumber.rawValue }
}
binding.editTextCardNumber.onFocusChangeListener = OnFocusChangeListener { _: View?, hasFocus: Boolean ->
setCardErrorState(hasFocus)
}
}
private fun setCardErrorState(hasFocus: Boolean) {
val outputData = cardDelegate.outputData
val cardNumberValidation = outputData.cardNumberState.validation
val showErrorWhileEditing = (cardNumberValidation as? Validation.Invalid)?.showErrorWhileEditing ?: false
val shouldNotShowError = hasFocus && !showErrorWhileEditing
if (shouldNotShowError) {
val shouldShowSecondaryLogo = outputData.isDualBranded
setCardNumberError(null, shouldShowSecondaryLogo)
} else if (cardNumberValidation is Validation.Invalid) {
setCardNumberError(cardNumberValidation.reason)
}
}
private fun setCardNumberError(@StringRes stringResId: Int?, shouldShowSecondaryLogo: Boolean = false) {
if (stringResId == null) {
binding.textInputLayoutCardNumber.hideError()
binding.cardBrandLogoContainerPrimary.isVisible = true
binding.cardBrandLogoContainerSecondary.isVisible = shouldShowSecondaryLogo
} else {
binding.textInputLayoutCardNumber.showError(localizedContext.getString(stringResId))
binding.cardBrandLogoContainerPrimary.isVisible = false
binding.cardBrandLogoContainerSecondary.isVisible = false
}
}
private fun initCardBrandLogoViews(selectedIndex: Int) {
when (selectedIndex) {
UNSELECTED_BRAND_INDEX -> deselectBrands()
PRIMARY_BRAND_INDEX -> selectPrimaryBrand()
SECONDARY_BRAND_INDEX -> selectSecondaryBrand()
else -> throw CheckoutException("Illegal brand index selected. Selected index must be either 0 or 1.")
}
}
private fun initBrandSelectionListeners() {
binding.cardBrandLogoContainerPrimary.setOnClickListener {
cardDelegate.updateInputData { selectedCardIndex = PRIMARY_BRAND_INDEX }
selectPrimaryBrand()
}
binding.cardBrandLogoContainerSecondary.setOnClickListener {
cardDelegate.updateInputData { selectedCardIndex = SECONDARY_BRAND_INDEX }
selectSecondaryBrand()
}
}
private fun resetBrandSelectionInput() {
binding.cardBrandLogoContainerPrimary.setOnClickListener(null)
binding.cardBrandLogoContainerSecondary.setOnClickListener(null)
}
private fun deselectBrands() {
binding.cardBrandLogoImageViewPrimary.alpha = UNSELECTED_BRAND_LOGO_ALPHA
binding.cardBrandLogoImageViewSecondary.alpha = UNSELECTED_BRAND_LOGO_ALPHA
}
private fun selectPrimaryBrand() {
binding.cardBrandLogoImageViewPrimary.alpha = SELECTED_BRAND_LOGO_ALPHA
binding.cardBrandLogoImageViewSecondary.alpha = UNSELECTED_BRAND_LOGO_ALPHA
}
private fun selectSecondaryBrand() {
binding.cardBrandLogoImageViewPrimary.alpha = UNSELECTED_BRAND_LOGO_ALPHA
binding.cardBrandLogoImageViewSecondary.alpha = SELECTED_BRAND_LOGO_ALPHA
}
private fun initExpiryDateInput() {
binding.editTextExpiryDate.setOnChangeListener {
val date = binding.editTextExpiryDate.date
cardDelegate.updateInputData { expiryDate = date }
binding.textInputLayoutExpiryDate.hideError()
}
binding.editTextExpiryDate.onFocusChangeListener = OnFocusChangeListener { _, hasFocus ->
val expiryDateValidation = cardDelegate.outputData.expiryDateState.validation
if (hasFocus) {
binding.textInputLayoutExpiryDate.hideError()
} else if (expiryDateValidation is Validation.Invalid) {
binding.textInputLayoutExpiryDate.showError(localizedContext.getString(expiryDateValidation.reason))
}
}
}
private fun initSecurityCodeInput() {
val securityCodeEditText = binding.textInputLayoutSecurityCode.editText as? SecurityCodeInput
securityCodeEditText?.setOnChangeListener { editable: Editable ->
cardDelegate.updateInputData { securityCode = editable.toString() }
binding.textInputLayoutSecurityCode.hideError()
}
securityCodeEditText?.onFocusChangeListener = OnFocusChangeListener { _, hasFocus ->
val securityCodeValidation = cardDelegate.outputData.securityCodeState.validation
if (hasFocus) {
binding.textInputLayoutSecurityCode.hideError()
} else if (securityCodeValidation is Validation.Invalid) {
binding.textInputLayoutSecurityCode.showError(localizedContext.getString(securityCodeValidation.reason))
}
}
}
private fun initHolderNameInput() {
val cardHolderEditText = binding.textInputLayoutCardHolder.editText as? AdyenTextInputEditText
cardHolderEditText?.setOnChangeListener { editable: Editable ->
cardDelegate.updateInputData { holderName = editable.toString() }
binding.textInputLayoutCardHolder.hideError()
}
cardHolderEditText?.onFocusChangeListener = OnFocusChangeListener { _, hasFocus ->
val holderNameValidation = cardDelegate.outputData.holderNameState.validation
if (hasFocus) {
binding.textInputLayoutCardHolder.hideError()
} else if (holderNameValidation is Validation.Invalid) {
binding.textInputLayoutCardHolder.showError(localizedContext.getString(holderNameValidation.reason))
}
}
}
private fun initSocialSecurityNumberInput() {
val socialSecurityNumberEditText =
binding.textInputLayoutSocialSecurityNumber.editText as? AdyenTextInputEditText
socialSecurityNumberEditText?.setOnChangeListener { editable ->
cardDelegate.updateInputData { socialSecurityNumber = editable.toString() }
binding.textInputLayoutSocialSecurityNumber.hideError()
}
socialSecurityNumberEditText?.onFocusChangeListener = OnFocusChangeListener { _, hasFocus ->
val socialSecurityNumberValidation = cardDelegate.outputData.socialSecurityNumberState.validation
if (hasFocus) {
binding.textInputLayoutSocialSecurityNumber.hideError()
} else if (socialSecurityNumberValidation is Validation.Invalid) {
binding.textInputLayoutSocialSecurityNumber.showError(
localizedContext.getString(socialSecurityNumberValidation.reason)
)
}
}
}
private fun initKcpAuthenticationInput() {
initKcpBirthDateOrTaxNumberInput()
initKcpCardPasswordInput()
}
private fun initKcpBirthDateOrTaxNumberInput() {
val kcpBirthDateOrRegistrationNumberEditText =
binding.textInputLayoutKcpBirthDateOrTaxNumber.editText as? AdyenTextInputEditText
kcpBirthDateOrRegistrationNumberEditText?.setOnChangeListener {
cardDelegate.updateInputData { kcpBirthDateOrTaxNumber = it.toString() }
binding.textInputLayoutKcpBirthDateOrTaxNumber.hideError()
}
kcpBirthDateOrRegistrationNumberEditText?.onFocusChangeListener = OnFocusChangeListener { _, hasFocus ->
val kcpBirthDateOrTaxNumberValidation = cardDelegate.outputData.kcpBirthDateOrTaxNumberState.validation
if (hasFocus) {
binding.textInputLayoutKcpBirthDateOrTaxNumber.hideError()
} else if (kcpBirthDateOrTaxNumberValidation is Validation.Invalid) {
binding.textInputLayoutKcpBirthDateOrTaxNumber.showError(
localizedContext.getString(kcpBirthDateOrTaxNumberValidation.reason)
)
}
}
}
private fun initKcpCardPasswordInput() {
val kcpPasswordEditText = binding.textInputLayoutKcpCardPassword.editText as? AdyenTextInputEditText
kcpPasswordEditText?.setOnChangeListener {
cardDelegate.updateInputData { kcpCardPassword = it.toString() }
binding.textInputLayoutKcpCardPassword.hideError()
}
kcpPasswordEditText?.onFocusChangeListener = OnFocusChangeListener { _, hasFocus ->
val kcpBirthDateOrRegistrationNumberValidation = cardDelegate.outputData.kcpCardPasswordState.validation
if (hasFocus) {
binding.textInputLayoutKcpCardPassword.hideError()
} else if (kcpBirthDateOrRegistrationNumberValidation is Validation.Invalid) {
binding.textInputLayoutKcpCardPassword.showError(
localizedContext.getString(kcpBirthDateOrRegistrationNumberValidation.reason)
)
}
}
}
private fun initPostalCodeInput() {
val postalCodeEditText = binding.textInputLayoutPostalCode.editText as? AdyenTextInputEditText
postalCodeEditText?.setOnChangeListener {
cardDelegate.updateInputData { address.postalCode = it.toString() }
binding.textInputLayoutPostalCode.hideError()
}
postalCodeEditText?.onFocusChangeListener = OnFocusChangeListener { _, hasFocus ->
val postalCodeValidation = cardDelegate.outputData.addressState.postalCode.validation
if (hasFocus) {
binding.textInputLayoutPostalCode.hideError()
} else if (postalCodeValidation is Validation.Invalid) {
binding.textInputLayoutPostalCode.showError(localizedContext.getString(postalCodeValidation.reason))
}
}
}
private fun initAddressFormInput(coroutineScope: CoroutineScope) {
binding.addressFormInput.attachDelegate(cardDelegate, coroutineScope)
}
private fun updateInstallments(cardOutputData: CardOutputData) {
val installmentTextInputLayout = binding.textInputLayoutInstallments
val installmentAutoCompleteTextView = binding.autoCompleteTextViewInstallments
if (cardOutputData.installmentOptions.isNotEmpty()) {
if (installmentListAdapter == null) {
initInstallments()
}
if (cardOutputData.installmentState.value == null) {
updateInstallmentSelection(cardOutputData.installmentOptions.first())
val installmentOptionText = InstallmentUtils.getTextForInstallmentOption(
localizedContext,
cardOutputData.installmentOptions.first()
)
installmentAutoCompleteTextView.setText(installmentOptionText)
}
installmentListAdapter?.setItems(cardOutputData.installmentOptions)
installmentTextInputLayout.isVisible = true
} else {
installmentTextInputLayout.isVisible = false
}
}
private fun initInstallments() {
installmentListAdapter = InstallmentListAdapter(context, localizedContext)
installmentListAdapter?.let {
binding.autoCompleteTextViewInstallments.apply {
inputType = 0
setAdapter(it)
onItemClickListener = AdapterView.OnItemClickListener { _, _, position, _ ->
updateInstallmentSelection(installmentListAdapter?.getItem(position))
}
}
}
}
private fun handleCvcUIState(cvcUIState: InputFieldUIState) {
when (cvcUIState) {
InputFieldUIState.REQUIRED -> {
binding.textInputLayoutSecurityCode.isVisible = true
binding.textInputLayoutSecurityCode.setLocalizedHintFromStyle(
R.style.AdyenCheckout_Card_SecurityCodeInput,
localizedContext
)
}
InputFieldUIState.OPTIONAL -> {
binding.textInputLayoutSecurityCode.isVisible = true
binding.textInputLayoutSecurityCode.hint = localizedContext.getString(
R.string.checkout_card_security_code_optional_hint
)
}
InputFieldUIState.HIDDEN -> {
binding.textInputLayoutSecurityCode.isVisible = false
// We don't expect the hidden status to change back to isVisible, so we don't worry about putting the
// margin back.
val params = binding.textInputLayoutExpiryDate.layoutParams as LayoutParams
params.marginEnd = 0
binding.textInputLayoutExpiryDate.layoutParams = params
}
}
}
private fun handleExpiryDateUIState(expiryDateUIState: InputFieldUIState) {
when (expiryDateUIState) {
InputFieldUIState.REQUIRED -> {
binding.textInputLayoutExpiryDate.isVisible = true
binding.textInputLayoutExpiryDate.setLocalizedHintFromStyle(
R.style.AdyenCheckout_Card_ExpiryDateInput,
localizedContext
)
}
InputFieldUIState.OPTIONAL -> {
binding.textInputLayoutExpiryDate.isVisible = true
binding.textInputLayoutExpiryDate.hint = localizedContext.getString(
R.string.checkout_card_expiry_date_optional_hint
)
}
InputFieldUIState.HIDDEN -> {
binding.textInputLayoutExpiryDate.isVisible = false
val params = binding.textInputLayoutSecurityCode.layoutParams as LayoutParams
params.marginStart = 0
binding.textInputLayoutSecurityCode.layoutParams = params
}
}
}
private fun handleHolderNameUIState(holderNameUIState: InputFieldUIState) {
binding.textInputLayoutCardHolder.isVisible = holderNameUIState != InputFieldUIState.HIDDEN
}
private fun setStorePaymentSwitchVisibility(showStorePaymentField: Boolean) {
binding.switchStorePaymentMethod.isVisible = showStorePaymentField
}
private fun setSocialSecurityNumberVisibility(shouldShowSocialSecurityNumber: Boolean) {
binding.textInputLayoutSocialSecurityNumber.isVisible = shouldShowSocialSecurityNumber
}
private fun setKcpAuthVisibility(shouldShowKCPAuth: Boolean) {
binding.textInputLayoutKcpBirthDateOrTaxNumber.isVisible = shouldShowKCPAuth
binding.textInputLayoutKcpCardPassword.isVisible = shouldShowKCPAuth
}
private fun setKcpHint(kcpBirthDateOrTaxNumberHint: Int?) {
kcpBirthDateOrTaxNumberHint ?: return
binding.textInputLayoutKcpBirthDateOrTaxNumber.hint = localizedContext.getString(kcpBirthDateOrTaxNumberHint)
}
private fun setAddressInputVisibility(addressFormUIState: AddressFormUIState) {
when (addressFormUIState) {
AddressFormUIState.FULL_ADDRESS -> {
binding.addressFormInput.isVisible = true
binding.textInputLayoutPostalCode.isVisible = false
}
AddressFormUIState.POSTAL_CODE -> {
binding.addressFormInput.isVisible = false
binding.textInputLayoutPostalCode.isVisible = true
}
AddressFormUIState.NONE -> {
binding.addressFormInput.isVisible = false
binding.textInputLayoutPostalCode.isVisible = false
}
}
}
private fun updateAddressHint(addressFormUIState: AddressFormUIState, isOptional: Boolean) {
when (addressFormUIState) {
AddressFormUIState.FULL_ADDRESS -> binding.addressFormInput.updateAddressHint(isOptional)
AddressFormUIState.POSTAL_CODE -> {
val postalCodeStyleResId = if (isOptional) {
R.style.AdyenCheckout_PostalCodeInput_Optional
} else {
R.style.AdyenCheckout_PostalCodeInput
}
binding.textInputLayoutPostalCode.setLocalizedHintFromStyle(postalCodeStyleResId, localizedContext)
}
else -> {
// no ops
}
}
}
private fun updateInstallmentSelection(installmentModel: InstallmentModel?) {
installmentModel?.let {
cardDelegate.updateInputData { installmentOption = it }
}
}
private fun getActivity(context: Context): Activity? {
return when (context) {
is Activity -> context
is ContextWrapper -> getActivity(context.baseContext)
else -> null
}
}
private fun setCardList(cards: List<CardListItem>, isCardListVisible: Boolean) {
binding.recyclerViewCardList.isVisible = isCardListVisible
if (isCardListVisible) {
if (cardListAdapter == null) {
cardListAdapter = CardListAdapter()
binding.recyclerViewCardList.adapter = cardListAdapter
}
cardListAdapter?.submitList(cards)
}
}
override fun getView(): View = this
companion object {
private const val UNSELECTED_BRAND_LOGO_ALPHA = 0.2f
private const val SELECTED_BRAND_LOGO_ALPHA = 1f
private const val UNSELECTED_BRAND_INDEX = -1
private const val PRIMARY_BRAND_INDEX = 0
private const val SECONDARY_BRAND_INDEX = 1
}
}
| 31 | null | 66 | 96 | 1f000e27e07467f3a30bb3a786a43de62be003b2 | 33,221 | adyen-android | MIT License |
health/connect/connect-client/src/main/java/androidx/health/connect/client/PermissionController.kt | androidx | 256,589,781 | false | null | /*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.health.connect.client
import androidx.activity.result.contract.ActivityResultContract
import androidx.health.connect.client.HealthConnectClient.Companion.DEFAULT_PROVIDER_PACKAGE_NAME
import androidx.health.connect.client.permission.HealthDataRequestPermissionsInternal
import androidx.health.connect.client.permission.HealthPermission
@JvmDefaultWithCompatibility
/** Interface for operations related to permissions. */
interface PermissionController {
/**
* Returns a set of all health permissions granted by the user to the calling app.
*
* @return set of granted permissions.
* @throws android.os.RemoteException For any IPC transportation failures.
* @throws java.io.IOException For any disk I/O issues.
* @throws IllegalStateException If service is not available.
* @sample androidx.health.connect.client.samples.GetPermissions
*/
suspend fun getGrantedPermissions(): Set<String>
/**
* Revokes all previously granted [HealthPermission] by the user to the calling app.
*
* @throws android.os.RemoteException For any IPC transportation failures.
* @throws java.io.IOException For any disk I/O issues.
* @throws IllegalStateException If service is not available.
*/
suspend fun revokeAllPermissions()
companion object {
/**
* Creates an [ActivityResultContract] to request Health permissions.
*
* @param providerPackageName Optional provider package name to request health permissions
* from.
* @sample androidx.health.connect.client.samples.RequestPermission
* @see androidx.activity.ComponentActivity.registerForActivityResult
*/
@JvmStatic
@JvmOverloads
fun createRequestPermissionResultContract(
providerPackageName: String = DEFAULT_PROVIDER_PACKAGE_NAME
): ActivityResultContract<Set<String>, Set<String>> {
return HealthDataRequestPermissionsInternal(providerPackageName = providerPackageName)
}
}
}
| 29 | null | 945 | 5,321 | 98b929d303f34d569e9fd8a529f022d398d1024b | 2,683 | androidx | Apache License 2.0 |
app/src/main/java/com/example/pavan/galleryview/Utils/Extensions.kt | pavan555 | 235,297,011 | false | null | package com.example.pavan.galleryview.Utils
/* *********************************************************************
* Copyright [<NAME>](https://github.com/pavan555) 2020
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*********************************************************************
*/
import android.app.Activity
import android.content.Context
import android.os.Build
import android.view.View
import android.widget.Toast
import androidx.annotation.ColorInt
import androidx.annotation.ColorRes
import androidx.core.content.ContextCompat
object Extensions {
var toast: Toast? = null
@ColorInt internal fun Context.color(@ColorRes resId: Int): Int {
return ContextCompat.getColor(this,resId)
}
fun getDimension(context: Context, resId: Int): Int {
return context.resources.getDimension(resId).toInt()
}
internal fun Activity.setLightNavBar( ) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val view = window.decorView
var flags = view.systemUiVisibility
flags = flags or View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR
window.decorView.systemUiVisibility = flags
}
}
fun Context.setToast( message: String) {
if (toast != null) {
toast!!.cancel()
}
toast = Toast.makeText(this, message, Toast.LENGTH_SHORT)
toast!!.show()
}
}
| 1 | null | 1 | 1 | 358fc668ef3fd4eb7545238e4dd9b96c0f0a6861 | 1,953 | Gallery-View | Apache License 2.0 |
cloud/oauth-server/src/main/kotlin/pers/acp/admin/oauth/controller/inner/InnerOrgController.kt | zhangbinhub | 162,155,230 | false | null | package pers.acp.admin.controller.inner
import io.github.zhangbinhub.acp.boot.exceptions.ServerException
import io.github.zhangbinhub.acp.boot.interfaces.LogAdapter
import io.swagger.annotations.Api
import io.swagger.annotations.ApiOperation
import org.springframework.beans.BeanUtils
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.security.oauth2.provider.OAuth2Authentication
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import pers.acp.admin.api.CommonPath
import pers.acp.admin.api.OauthApi
import pers.acp.admin.base.BaseController
import pers.acp.admin.domain.OrganizationDomain
import pers.acp.admin.entity.Organization
import pers.acp.admin.vo.OrganizationVo
import springfox.documentation.annotations.ApiIgnore
/**
* @author zhang by 16/01/2019
* @since JDK 11
*/
@Validated
@RestController
@RequestMapping(CommonPath.innerBasePath)
@Api(tags = ["机构信息(内部接口)"])
class InnerOrgController @Autowired
constructor(
logAdapter: LogAdapter,
private val organizationDomain: OrganizationDomain
) : BaseController(logAdapter) {
private fun listToVo(organizationList: List<Organization>): List<OrganizationVo> =
organizationList.map { organization ->
OrganizationVo().apply {
BeanUtils.copyProperties(organization, this)
}
}
@ApiOperation(value = "获取所属机构及其所有子机构列表(所属机构)")
@GetMapping(value = [OauthApi.currAndAllChildrenOrg], produces = [MediaType.APPLICATION_JSON_VALUE])
@Throws(ServerException::class)
fun currAndAllChildrenForOrg(@ApiIgnore user: OAuth2Authentication): ResponseEntity<List<OrganizationVo>> =
ResponseEntity.ok(listToVo(organizationDomain.getCurrAndAllChildrenForOrg(user.name)))
@ApiOperation(value = "获取所属机构及其所有子机构列表(管理机构)")
@GetMapping(value = [OauthApi.currAndAllChildrenMngOrg], produces = [MediaType.APPLICATION_JSON_VALUE])
@Throws(ServerException::class)
fun currAndAllChildrenForMngOrg(@ApiIgnore user: OAuth2Authentication): ResponseEntity<List<OrganizationVo>> =
ResponseEntity.ok(listToVo(organizationDomain.getCurrAndAllChildrenForMngOrg(user.name)))
@ApiOperation(value = "获取所属机构及其所有子机构列表(所有机构)")
@GetMapping(value = [OauthApi.currAndAllChildrenAllOrg], produces = [MediaType.APPLICATION_JSON_VALUE])
@Throws(ServerException::class)
fun currAndAllChildrenForAllOrg(@ApiIgnore user: OAuth2Authentication): ResponseEntity<List<OrganizationVo>> =
ResponseEntity.ok(listToVo(organizationDomain.getCurrAndAllChildrenForAllOrg(user.name)))
} | 0 | Kotlin | 5 | 19 | 564b34c1f10a75dd4c4e822489d4f0efb9d38089 | 2,842 | acp-admin-cloud | Apache License 2.0 |
cloud/oauth-server/src/main/kotlin/pers/acp/admin/oauth/controller/inner/InnerOrgController.kt | zhangbinhub | 162,155,230 | false | null | package pers.acp.admin.controller.inner
import io.github.zhangbinhub.acp.boot.exceptions.ServerException
import io.github.zhangbinhub.acp.boot.interfaces.LogAdapter
import io.swagger.annotations.Api
import io.swagger.annotations.ApiOperation
import org.springframework.beans.BeanUtils
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.security.oauth2.provider.OAuth2Authentication
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import pers.acp.admin.api.CommonPath
import pers.acp.admin.api.OauthApi
import pers.acp.admin.base.BaseController
import pers.acp.admin.domain.OrganizationDomain
import pers.acp.admin.entity.Organization
import pers.acp.admin.vo.OrganizationVo
import springfox.documentation.annotations.ApiIgnore
/**
* @author zhang by 16/01/2019
* @since JDK 11
*/
@Validated
@RestController
@RequestMapping(CommonPath.innerBasePath)
@Api(tags = ["机构信息(内部接口)"])
class InnerOrgController @Autowired
constructor(
logAdapter: LogAdapter,
private val organizationDomain: OrganizationDomain
) : BaseController(logAdapter) {
private fun listToVo(organizationList: List<Organization>): List<OrganizationVo> =
organizationList.map { organization ->
OrganizationVo().apply {
BeanUtils.copyProperties(organization, this)
}
}
@ApiOperation(value = "获取所属机构及其所有子机构列表(所属机构)")
@GetMapping(value = [OauthApi.currAndAllChildrenOrg], produces = [MediaType.APPLICATION_JSON_VALUE])
@Throws(ServerException::class)
fun currAndAllChildrenForOrg(@ApiIgnore user: OAuth2Authentication): ResponseEntity<List<OrganizationVo>> =
ResponseEntity.ok(listToVo(organizationDomain.getCurrAndAllChildrenForOrg(user.name)))
@ApiOperation(value = "获取所属机构及其所有子机构列表(管理机构)")
@GetMapping(value = [OauthApi.currAndAllChildrenMngOrg], produces = [MediaType.APPLICATION_JSON_VALUE])
@Throws(ServerException::class)
fun currAndAllChildrenForMngOrg(@ApiIgnore user: OAuth2Authentication): ResponseEntity<List<OrganizationVo>> =
ResponseEntity.ok(listToVo(organizationDomain.getCurrAndAllChildrenForMngOrg(user.name)))
@ApiOperation(value = "获取所属机构及其所有子机构列表(所有机构)")
@GetMapping(value = [OauthApi.currAndAllChildrenAllOrg], produces = [MediaType.APPLICATION_JSON_VALUE])
@Throws(ServerException::class)
fun currAndAllChildrenForAllOrg(@ApiIgnore user: OAuth2Authentication): ResponseEntity<List<OrganizationVo>> =
ResponseEntity.ok(listToVo(organizationDomain.getCurrAndAllChildrenForAllOrg(user.name)))
} | 0 | Kotlin | 5 | 19 | 564b34c1f10a75dd4c4e822489d4f0efb9d38089 | 2,842 | acp-admin-cloud | Apache License 2.0 |
src/commonMain/kotlin/ai/ConversationAI.kt | adQuid | 307,862,049 | false | null | package ai
import model.shortstate.Communication
import model.shortstate.Message
import model.shortstate.ShortStateCharacter
import model.shortstate.messagetypes.GivePerspective
import model.shortstate.messagetypes.Greeting
import model.shortstate.messagetypes.RequestPerspective
import model.shortstate.messagetypes.SweetCaroline
import ui.UIMain
class ConversationReaction(val response: String, val priority: Int, val messages: List<Message> = listOf()) {
}
class ConversationAI {
val parent: ShortStateCharacter
val memory: MutableList<Communication>
constructor(parent: ShortStateCharacter){
this.parent = parent
this.memory = mutableListOf()
}
fun hear(communication: Communication){
memory.add(communication)
if(UIMain.player == parent){
UIMain.needToUpdateTargetView = true
}
}
fun respondToLine(communication: Communication){
if(communication.speaker == parent || UIMain.player == parent){
return
}
val responseOptions = mutableListOf<ConversationReaction>()
if(communication.target == parent){
parent.longCharacter.culture.politeGreetings.forEach {
if(communication.text.toLowerCase().contains(it.toLowerCase())){
parent.improveMoodTowards(25)
if(parent.mood > 15){
responseOptions.add(ConversationReaction("Thanks, that's very sweet.", 10))
}
}
}
}
communication.messages.forEach{
if(it is SweetCaroline){
responseOptions.add( ConversationReaction("Bah Bah Bah", 9999))
}
if(it is GivePerspective){
val myPerspective = parent.surfacePerspectiveOn(it.perspective.topic)
if(myPerspective != null){
if(it.perspective.opinion - parent.surfacePerspectiveOn(it.perspective.topic)!!.opinion > 50){
responseOptions.add( ConversationReaction(parent.surfacePerspectiveOn(it.perspective.topic)!!.text, 50, listOf(GivePerspective(myPerspective))))
}
}
}
if(communication.target == parent){
if(it is Greeting){
if(thingsIAlreadySaid(communication.speaker).filterIsInstance<Greeting>().isEmpty()){
responseOptions.add( ConversationReaction("Hello", 4))
} else {
responseOptions.add( ConversationReaction("Um... hi", 4))
}
}
if(it is RequestPerspective){
val myPerspective = parent.surfacePerspectiveOn(it.perspective.topic)
if(myPerspective != null){
responseOptions.add( ConversationReaction(parent.surfacePerspectiveOn(it.perspective.topic)!!.text, 50, listOf(GivePerspective(myPerspective))))
} else {
responseOptions.add( ConversationReaction("Huh, I've never heard about that...", 10))
}
}
if(it is GivePerspective){
val truePerspective = parent.deepPerspectiveOn(it.perspective.topic)
if(truePerspective != null){
if(truePerspective!!.opinion > 10 && it.perspective.opinion > 10){
parent.improveMoodTowards(30)
responseOptions.add(ConversationReaction("It is pretty sweet, isn't it?", 15))
} else if(truePerspective!!.opinion < -10 && it.perspective.opinion < -10){
parent.improveMoodTowards(30)
responseOptions.add(ConversationReaction("I know right, it sucks!", 15))
} else {
responseOptions.add(ConversationReaction("Good to hear.", 5))
}
} else {
responseOptions.add( ConversationReaction("Huh, I've never heard about that...", 10))
}
}
}
}
if(responseOptions.isNotEmpty()){
val bestOption = responseOptions.sortedByDescending { it.priority }.first()
if(bestOption.messages.isEmpty()){
parent.say(bestOption.response, null)
} else {
parent.say(bestOption.response, bestOption.messages, null)
}
}
}
fun lastThingSaidToMe(character: ShortStateCharacter?): List<String>{
if(memory.lastOrNull { it.speaker == character } != null){
return memory.last { it.speaker == character }!!.splitIntoLines()
} else {
return listOf()
}
}
private fun thingsIAlreadySaid(character: ShortStateCharacter): Set<Message>{
return memory.filter { it.speaker == parent && it.target == character }.map {it.messages }.flatten().toSet()
}
} | 0 | Kotlin | 0 | 0 | b4724df1674f5e0e795f2b028521389284152066 | 5,066 | teech | MIT License |
app/src/main/java/com/stfalcon/new_uaroads_android/common/injection/modules/ActivityInjectionModule.kt | stfalcon-studio | 49,490,060 | false | null | /*
* Copyright (c) 2017 stfalcon.com
*
* 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.stfalcon.new_uaroads_android.common.injection.modules
import android.app.Activity
import com.stfalcon.new_uaroads_android.features.bestroute.BestRouteActivity
import com.stfalcon.new_uaroads_android.features.main.MainActivity
import com.stfalcon.new_uaroads_android.features.main.MainScreenSubComponent
import com.stfalcon.new_uaroads_android.features.places.BestRouteSubComponent
import com.stfalcon.new_uaroads_android.features.places.LocationChooserActivity
import com.stfalcon.new_uaroads_android.features.places.LocationChooserSubComponent
import com.stfalcon.new_uaroads_android.features.settings.SettingsActivity
import com.stfalcon.new_uaroads_android.features.settings.SettingsScreenSubComponent
import com.stfalcon.new_uaroads_android.features.settings.TracksSubComponent
import com.stfalcon.new_uaroads_android.features.tracks.TracksActivity
import dagger.Binds
import dagger.Module
import dagger.android.ActivityKey
import dagger.android.AndroidInjector
import dagger.multibindings.IntoMap
/*
* Created by <NAME> on 4/5/17.
*/
//TODO rename to "BuildersModule?" or add to package "builders"?
@Module
abstract class ActivityInjectionModule {
@Binds
@IntoMap
@ActivityKey(MainActivity::class)
internal abstract fun bindMainActivityInjectorFactory(
builder: MainScreenSubComponent.Builder): AndroidInjector.Factory<out Activity>
@Binds
@IntoMap
@ActivityKey(LocationChooserActivity::class)
internal abstract fun bindLocationChooserActivityInjectorFactory(
builder: LocationChooserSubComponent.Builder): AndroidInjector.Factory<out Activity>
@Binds
@IntoMap
@ActivityKey(BestRouteActivity::class)
internal abstract fun bindBestRouteInjectorFactory(
builder: BestRouteSubComponent.Builder): AndroidInjector.Factory<out Activity>
@Binds
@IntoMap
@ActivityKey(SettingsActivity::class)
internal abstract fun bindSettingsActivityInjectorFactory(
builder: SettingsScreenSubComponent.Builder): AndroidInjector.Factory<out Activity>
@Binds
@IntoMap
@ActivityKey(TracksActivity::class)
internal abstract fun bindTracksActivityInjectorFactory(
builder: TracksSubComponent.Builder): AndroidInjector.Factory<out Activity>
}
| 1 | null | 6 | 24 | 1332f62043a91206f0c6fdbade6ac31e6864b8cc | 2,910 | uaroads_android | Apache License 2.0 |
app/src/main/java/com/example/arduino/Callbacks.kt | Schrotti17 | 482,303,806 | false | {"Kotlin": 12522, "Java": 60} | package com.example.arduino
interface Callbacks {
fun write(message: String)
fun onBluetoothDeviceSelected(address: String)
//fun read(byte: Array<Byte>)
} | 0 | Kotlin | 0 | 0 | 5c67a06b188ecbf055b9f2ff6d71ce253938177e | 168 | BluetoothArduino | MIT License |
compiler/src/commonMain/kotlin/com.franzmandl.compiler/optimizer/ThreeAddressCode.kt | franzmandl | 512,849,792 | false | null | package com.franzmandl.compiler.optimizer
import com.franzmandl.compiler.ast.*
import com.franzmandl.compiler.ctx.AddCommand
import com.franzmandl.compiler.ctx.ExpressionContext
import com.franzmandl.compiler.ctx.ExpressionReplaceVisitor
import com.franzmandl.compiler.ctx.VariableReplaceExpressionReason
object ThreeAddressCode : ExpressionReplaceVisitor.Factory, ExpressionReplaceVisitor.Replacer {
private val optimization = Optimization.ThreeAddressCode
override fun createExpressionReplaceVisitor(addCommand: AddCommand) = ExpressionReplaceVisitor(addCommand, ThreeAddressCode)
private fun replace(ctx: ExpressionContext<Expression>, old: Expression, expression: Expression) =
if (ctx.isRootExpression()) {
null
} else {
val variable = ctx.statement.basicBlock.addTemporaryVariable(expression.type ?: Type.langObject)
val lhs = VariableAccess(variable)
ctx.replaceExpression(optimization, old, lhs, VariableReplaceExpressionReason(variable), ctx.statement.basicBlock.addStatement(optimization, Assignment(lhs, expression)))
}
override fun replaceArithmeticUnaryOperation(operand: Expression, ctx: ExpressionContext<ArithmeticUnaryOperation>, alt: ArithmeticUnaryOperation) =
replace(ctx, alt, ArithmeticUnaryOperation(ctx.original.operator, operand))
override fun replaceLogicalNotUnaryOperation(operand: Expression, ctx: ExpressionContext<LogicalNotUnaryOperation>, alt: LogicalNotUnaryOperation) =
replace(ctx, alt, LogicalNotUnaryOperation(ctx.original.id, operand))
override fun replaceArithmeticBinaryOperation(operands: BinaryOperands<Expression>, ctx: ExpressionContext<ArithmeticBinaryOperation>, alt: ArithmeticBinaryOperation) =
replace(ctx, alt, ArithmeticBinaryOperation(ctx.original.operator, operands))
override fun replaceLogicalBinaryOperation(operands: BinaryOperands<Expression>, ctx: ExpressionContext<LogicalBinaryOperation>, alt: LogicalBinaryOperation) =
replace(ctx, alt, LogicalBinaryOperation(ctx.original.id, ctx.original.operator, operands))
override fun replaceRelationalBinaryOperation(operands: BinaryOperands<Expression>, ctx: ExpressionContext<RelationalBinaryOperation>, alt: RelationalBinaryOperation) =
replace(ctx, alt, RelationalBinaryOperation(ctx.original.id, ctx.original.operator, operands))
override fun replaceObjectEqualsBinaryOperation(operands: BinaryOperands<Expression>, ctx: ExpressionContext<ObjectEqualsBinaryOperation>, alt: ObjectEqualsBinaryOperation) =
replace(ctx, alt, ObjectEqualsBinaryOperation(ctx.original.id, ctx.original.operator, operands))
override fun replaceTernaryOperation(condition: Expression, operands: BinaryOperands<Expression>, ctx: ExpressionContext<TernaryOperation>, alt: TernaryOperation) =
replace(ctx, alt, TernaryOperation(ctx.original.id, condition, operands))
override fun replaceCoercionExpression(operand: Expression, ctx: ExpressionContext<CoercionExpression>, alt: CoercionExpression) =
replace(ctx, alt, CoercionExpression(ctx.original.id, operand, ctx.original.expectedType, ctx.original.acceptedType))
override fun replaceBuiltinMethodInvocation(arguments: List<Expression>, ctx: ExpressionContext<BuiltinMethodInvocation>, alt: BuiltinMethodInvocation) =
replace(ctx, alt, BuiltinMethodInvocation(ctx.original.method, arguments))
override fun replaceMethodInvocation(operand: Expression, arguments: List<Expression>, ctx: ExpressionContext<MethodInvocation>, alt: MethodInvocation) =
replace(ctx, alt, MethodInvocation(operand, ctx.original.clazz, ctx.original.methodSignature, arguments))
override fun replaceObjectAllocation(arguments: List<Expression>, ctx: ExpressionContext<ObjectAllocation>, alt: ObjectAllocation) =
replace(ctx, alt, ObjectAllocation(ctx.original.type, ctx.original.constructorSignature, arguments))
} | 0 | Kotlin | 0 | 0 | a5004c6fc8fb717e076441ef55e3f8758efe252f | 3,791 | visopt | MIT License |
kotlin/src/main/kotlin/com/spoonacular/client/model/TalkToChatbot200Response.kt | ddsky | 189,444,765 | false | null | /**
*
* Please note:
* This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* Do not edit this file manually.
*
*/
@file:Suppress(
"ArrayInDataClass",
"EnumEntryName",
"RemoveRedundantQualifierName",
"UnusedImport"
)
package com.spoonacular.client.model
import com.spoonacular.client.model.TalkToChatbot200ResponseMediaInner
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
/**
*
*
* @param answerText
* @param media
*/
data class TalkToChatbot200Response (
@Json(name = "answerText")
val answerText: kotlin.String,
@Json(name = "media")
val media: kotlin.collections.List<TalkToChatbot200ResponseMediaInner>
)
| 1 | null | 65 | 41 | 60d83759252522d70fe981b12a20a5f56690617e | 717 | spoonacular-api-clients | MIT License |
modules/jooby-openapi/src/test/kotlin/kt/issues/i2004/Controller2004.kt | jooby-project | 25,446,835 | false | null | package kt.issues.i2004
import io.jooby.annotations.GET
import io.jooby.annotations.Path
import io.jooby.annotations.QueryParam
import io.swagger.v3.oas.annotations.Operation
import io.swagger.v3.oas.annotations.media.Schema
@Schema(description = "This is a company request")
data class CompanyRequest(
val baseYear: Int,
val naceCode: List<String>,
@get:Schema(required = false, description = "blablabla", example = "HEY")
val region: String
)
@Path("/issues/2004")
class Controller2004 {
@Operation(
summary = "Get all companies",
description = "Find all companies defined by the search parameters"
)
@GET
fun getAllCompanies(companyRequest: CompanyRequest): String {
return companyRequest.toString()
}
}
| 51 | null | 175 | 1,439 | 1a0252d5dac7d3730f3e7017008c65a9ae4e5dd3 | 752 | jooby | Apache License 2.0 |
libs/rest/rest-test-common/src/main/kotlin/net/corda/rest/test/TestVersioningRestResourceImpl.kt | corda | 346,070,752 | false | null | package net.corda.rest.test
import net.corda.rest.PluggableRestResource
class TestEndpointVersioningRestResourceImpl :
TestEndpointVersioningRestResource,
PluggableRestResource<TestEndpointVersioningRestResource> {
override val protocolVersion: Int
get() = 3
override val targetInterface: Class<TestEndpointVersioningRestResource>
get() = TestEndpointVersioningRestResource::class.java
override fun getUsingPath(id: String): String {
return "Retrieved using path id: $id"
}
@Deprecated("Deprecated in favour of `getUsingPath()`")
override fun getUsingQuery(id: String): String {
return "Retrieved using query: $id"
}
}
class TestResourceVersioningRestResourceImpl :
TestResourceVersioningRestResource,
PluggableRestResource<TestResourceVersioningRestResource> {
override val protocolVersion: Int
get() = 3
override val targetInterface: Class<TestResourceVersioningRestResource>
get() = TestResourceVersioningRestResource::class.java
@Deprecated("Deprecated in favour of `getUsingPath()`")
override fun getUsingQuery(id: String): String {
return "Retrieved using query: $id"
}
override fun getUsingPath(id: String): String {
return "Retrieved using path id: $id"
}
}
class TestResourceMaxVersioningRestResourceImpl :
TestResourceMaxVersioningRestResource,
PluggableRestResource<TestResourceMaxVersioningRestResource> {
override val protocolVersion: Int
get() = 3
override val targetInterface: Class<TestResourceMaxVersioningRestResource>
get() = TestResourceMaxVersioningRestResource::class.java
@Deprecated("Deprecated in favour of `getUsingPath()`")
override fun getUsingQuery(id: String): String {
return "Retrieved using query: $id"
}
override fun getUsingPath(id: String): String {
return "Retrieved using path id: $id"
}
} | 14 | null | 27 | 69 | 0766222eb6284c01ba321633e12b70f1a93ca04e | 1,944 | corda-runtime-os | Apache License 2.0 |
vuesaxicons/src/commonMain/kotlin/moe/tlaster/icons/vuesax/vuesaxicons/linear/Cloudnotif.kt | Tlaster | 560,394,734 | false | {"Kotlin": 25133302} | package moe.tlaster.icons.vuesax.vuesaxicons.linear
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeCap.Companion.Round
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import moe.tlaster.icons.vuesax.vuesaxicons.LinearGroup
public val LinearGroup.Cloudnotif: ImageVector
get() {
if (_cloudnotif != null) {
return _cloudnotif!!
}
_cloudnotif = Builder(name = "Cloudnotif", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF292D32)),
strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(21.8999f, 13.96f)
curveTo(22.1699f, 15.63f, 21.6999f, 17.42f, 20.2699f, 18.68f)
curveTo(19.2799f, 19.59f, 17.9799f, 20.09f, 16.6299f, 20.08f)
horizontalLineTo(5.5399f)
curveTo(0.8699f, 19.74f, 0.8599f, 12.94f, 5.5399f, 12.6f)
horizontalLineTo(5.5899f)
curveTo(3.3999f, 6.47f, 9.0899f, 2.87f, 13.3799f, 4.25f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF292D32)),
strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(7.2601f, 13.01f)
curveTo(6.7401f, 12.75f, 6.1701f, 12.61f, 5.5901f, 12.6f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF292D32)),
strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(21.97f, 8.5f)
curveTo(21.97f, 9.6f, 21.46f, 10.59f, 20.65f, 11.23f)
curveTo(20.06f, 11.71f, 19.29f, 12.0f, 18.47f, 12.0f)
curveTo(16.54f, 12.0f, 14.97f, 10.43f, 14.97f, 8.5f)
curveTo(14.97f, 7.54f, 15.36f, 6.67f, 16.0f, 6.04f)
verticalLineTo(6.03f)
curveTo(16.63f, 5.39f, 17.51f, 5.0f, 18.47f, 5.0f)
curveTo(20.4f, 5.0f, 21.97f, 6.57f, 21.97f, 8.5f)
close()
}
}
.build()
return _cloudnotif!!
}
private var _cloudnotif: ImageVector? = null
| 0 | Kotlin | 0 | 2 | b8a8231e6637c2008f675ae76a3423b82ee53950 | 3,011 | VuesaxIcons | MIT License |
src/main/kotlin/uk/gov/justice/digital/hmpps/dpssmoketest/service/ProbationSearchService.kt | ministryofjustice | 308,619,038 | false | null | package uk.gov.justice.digital.hmpps.dpssmoketest.service
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.beans.factory.annotation.Value
import org.springframework.core.ParameterizedTypeReference
import org.springframework.http.MediaType
import org.springframework.stereotype.Service
import org.springframework.web.reactive.function.BodyInserters
import org.springframework.web.reactive.function.client.WebClient
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
import uk.gov.justice.digital.hmpps.dpssmoketest.resource.SmokeTestResource
import java.time.Duration
@Service
class ProbationSearchService(
@Value("\${test.maxLengthSeconds}") private val testMaxLengthSeconds: Long,
@Value("\${test.resultPollMs}") private val testResultPollMs: Long,
@Qualifier("probationOffenderSearchWebClient") private val webClient: WebClient
) {
fun waitForOffenderToBeFound(crn: String, firstName: String, surname: String): Flux<SmokeTestResource.TestStatus> =
Flux.interval(Duration.ofMillis(testResultPollMs))
.take(Duration.ofSeconds(testMaxLengthSeconds))
.flatMap { checkSearchTestComplete(crn, firstName, surname) }
.takeUntil(SmokeTestResource.TestStatus::testComplete)
fun checkSearchTestComplete(crn: String, firstName: String, surname: String): Mono<SmokeTestResource.TestStatus> {
fun failOnError(exception: Throwable): Mono<out SmokeTestResource.TestStatus> =
Mono.just(
SmokeTestResource.TestStatus(
"Check test results for $crn failed due to ${exception.message}",
SmokeTestResource.TestStatus.TestProgress.FAIL
)
)
return searchForOffender(crn, firstName, surname)
.map {
if (it.isEmpty()) {
SmokeTestResource.TestStatus("Still waiting for offender $crn to be found with name $firstName $surname")
} else {
SmokeTestResource.TestStatus(
"Offender $crn found with name ${it[0].firstName} ${it[0].surname}",
SmokeTestResource.TestStatus.TestProgress.COMPLETE
)
}
}
.onErrorResume(::failOnError)
}
fun assertTestResult(crn: String, firstName: String, surname: String): Mono<SmokeTestResource.TestStatus> {
fun failOnError(exception: Throwable): Mono<out SmokeTestResource.TestStatus> =
Mono.just(
SmokeTestResource.TestStatus(
"Check test results for $crn failed due to ${exception.message}",
SmokeTestResource.TestStatus.TestProgress.FAIL
)
)
return searchForOffender(crn, firstName, surname).map {
if (it.size != 1) {
SmokeTestResource.TestStatus("Offender $crn was never found with name $firstName $surname", SmokeTestResource.TestStatus.TestProgress.FAIL)
} else {
val offenderDetails = it[0]
if (offenderDetails.firstName == firstName && offenderDetails.surname == surname && offenderDetails.otherIds.crn == crn) {
SmokeTestResource.TestStatus(
"Test for offender $crn finished successfully",
SmokeTestResource.TestStatus.TestProgress.SUCCESS
)
} else {
SmokeTestResource.TestStatus("The offender $crn was not found with name $firstName $surname", SmokeTestResource.TestStatus.TestProgress.FAIL)
}
}
}.onErrorResume(::failOnError)
}
private fun searchForOffender(crn: String, firstName: String, surname: String): Mono<List<OffenderDetails>> {
return webClient.post()
.uri("/search")
.contentType(MediaType.APPLICATION_JSON)
.body(searchByCrnNameBody(crn, firstName, surname))
.retrieve()
.bodyToMono(object : ParameterizedTypeReference<List<OffenderDetails>>() {})
}
private fun searchByCrnNameBody(
crn: String,
firstName: String,
surname: String
) = BodyInserters.fromValue(
"""
{
"crn": "$crn",
"firstName": "$firstName",
"surname": "$surname"
}
""".trimIndent()
)
}
private data class IDs(val crn: String)
private data class OffenderDetails(val firstName: String, val surname: String, val otherIds: IDs)
| 0 | Kotlin | 1 | 0 | f606757b8598f3ac4c3d1ee7ce9ef6d1ea8be756 | 4,186 | dps-smoketest | MIT License |
src/main/kotlin/com/thilux/kblog/domain/CommentEntity.kt | thilux | 114,498,999 | false | null | package com.thilux.kblog.domain
import org.jetbrains.squash.definition.*
/**
* Created by tsantana on 05/01/18.
*/
object CommentEntity : TableDefinition() {
val id = integer("id").autoIncrement().uniqueIndex()
val commentator = varchar("commentator", 100)
val content = blob("content")
val post = reference(PostEntity.id, "post_id")
val commentDate = datetime("comment_date")
} | 9 | Kotlin | 4 | 14 | 70e9b3431a971a917647714ea4255bdb01ed291a | 403 | kblog | Apache License 2.0 |
kt/godot-library/src/main/kotlin/godot/gen/godot/Resource.kt | utopia-rise | 289,462,532 | false | null | // THIS FILE IS GENERATED! DO NOT EDIT IT MANUALLY!
@file:Suppress("PackageDirectoryMismatch", "unused", "FunctionName", "RedundantModalityModifier",
"UNCHECKED_CAST", "JoinDeclarationAndAssignment", "USELESS_CAST",
"RemoveRedundantQualifierName", "NOTHING_TO_INLINE")
package godot
import godot.`annotation`.GodotBaseType
import godot.core.RID
import godot.core.TransferContext
import godot.core.VariantType.BOOL
import godot.core.VariantType.NIL
import godot.core.VariantType.OBJECT
import godot.core.VariantType.STRING
import godot.core.VariantType._RID
import godot.signals.Signal0
import godot.signals.signal
import kotlin.Boolean
import kotlin.String
import kotlin.Suppress
import kotlin.Unit
/**
* Base class for all resources.
*
* Tutorials:
* [https://docs.godotengine.org/en/3.4/tutorials/best_practices/node_alternatives.html](https://docs.godotengine.org/en/3.4/tutorials/best_practices/node_alternatives.html)
*
* Resource is the base class for all Godot-specific resource types, serving primarily as data containers. Since they inherit from [godot.Reference], resources are reference-counted and freed when no longer in use. They are also cached once loaded from disk, so that any further attempts to load a resource from a given path will return the same reference (all this in contrast to a [godot.Node], which is not reference-counted and can be instanced from disk as many times as desired). Resources can be saved externally on disk or bundled into another object, such as a [godot.Node] or another resource.
*
* **Note:** In C#, resources will not be freed instantly after they are no longer in use. Instead, garbage collection will run periodically and will free resources that are no longer in use. This means that unused resources will linger on for a while before being removed.
*/
@GodotBaseType
public open class Resource : Reference() {
/**
* Emitted whenever the resource changes.
*
* **Note:** This signal is not emitted automatically for custom resources, which means that you need to create a setter and emit the signal yourself.
*/
public val changed: Signal0 by signal()
/**
* If `true`, the resource will be made unique in each instance of its local scene. It can thus be modified in a scene instance without impacting other instances of that same scene.
*/
public open var resourceLocalToScene: Boolean
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr,
ENGINEMETHOD_ENGINECLASS_RESOURCE_GET_RESOURCE_LOCAL_TO_SCENE, BOOL)
return TransferContext.readReturnValue(BOOL, false) as Boolean
}
set(`value`) {
TransferContext.writeArguments(BOOL to value)
TransferContext.callMethod(rawPtr,
ENGINEMETHOD_ENGINECLASS_RESOURCE_SET_RESOURCE_LOCAL_TO_SCENE, NIL)
}
/**
* The name of the resource. This is an optional identifier. If [resourceName] is not empty, its value will be displayed to represent the current resource in the editor inspector. For built-in scripts, the [resourceName] will be displayed as the tab name in the script editor.
*/
public open var resourceName: String
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_RESOURCE_GET_RESOURCE_NAME,
STRING)
return TransferContext.readReturnValue(STRING, false) as String
}
set(`value`) {
TransferContext.writeArguments(STRING to value)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_RESOURCE_SET_RESOURCE_NAME, NIL)
}
/**
* The path to the resource. In case it has its own file, it will return its filepath. If it's tied to the scene, it will return the scene's path, followed by the resource's index.
*/
public open var resourcePath: String
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_RESOURCE_GET_RESOURCE_PATH,
STRING)
return TransferContext.readReturnValue(STRING, false) as String
}
set(`value`) {
TransferContext.writeArguments(STRING to value)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_RESOURCE_SET_RESOURCE_PATH, NIL)
}
public override fun __new(): Unit {
callConstructor(ENGINECLASS_RESOURCE)
}
/**
* Virtual function which can be overridden to customize the behavior value of [setupLocalToScene].
*/
public open fun _setupLocalToScene(): Unit {
}
/**
* Duplicates the resource, returning a new resource with the exported members copied. **Note:** To duplicate the resource the constructor is called without arguments. This method will error when the constructor doesn't have default values.
*
* By default, sub-resources are shared between resource copies for efficiency. This can be changed by passing `true` to the `subresources` argument which will copy the subresources.
*
* **Note:** If `subresources` is `true`, this method will only perform a shallow copy. Nested resources within subresources will not be duplicated and will still be shared.
*
* **Note:** When duplicating a resource, only `export`ed properties are copied. Other properties will be set to their default value in the new resource.
*/
public open fun duplicate(subresources: Boolean = false): Resource? {
TransferContext.writeArguments(BOOL to subresources)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_RESOURCE_DUPLICATE, OBJECT)
return TransferContext.readReturnValue(OBJECT, true) as Resource?
}
/**
* Emits the [changed] signal.
*
* If external objects which depend on this resource should be updated, this method must be called manually whenever the state of this resource has changed (such as modification of properties).
*
* The method is equivalent to:
*
* ```
* emit_signal("changed")
* ```
*
* **Note:** This method is called automatically for built-in resources.
*/
public open fun emitChanged(): Unit {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_RESOURCE_EMIT_CHANGED, NIL)
}
/**
* If [resourceLocalToScene] is enabled and the resource was loaded from a [godot.PackedScene] instantiation, returns the local scene where this resource's unique copy is in use. Otherwise, returns `null`.
*/
public open fun getLocalScene(): Node? {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_RESOURCE_GET_LOCAL_SCENE, OBJECT)
return TransferContext.readReturnValue(OBJECT, true) as Node?
}
/**
* Returns the RID of the resource (or an empty RID). Many resources (such as [godot.Texture], [godot.Mesh], etc) are high-level abstractions of resources stored in a server, so this function will return the original RID.
*/
public open fun getRid(): RID {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_RESOURCE_GET_RID, _RID)
return TransferContext.readReturnValue(_RID, false) as RID
}
/**
* This method is called when a resource with [resourceLocalToScene] enabled is loaded from a [godot.PackedScene] instantiation. Its behavior can be customized by overriding [_setupLocalToScene] from script.
*
* For most resources, this method performs no base logic. [godot.ViewportTexture] performs custom logic to properly set the proxy texture and flags in the local viewport.
*/
public open fun setupLocalToScene(): Unit {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_RESOURCE_SETUP_LOCAL_TO_SCENE, NIL)
}
/**
* Sets the path of the resource, potentially overriding an existing cache entry for this path. This differs from setting [resourcePath], as the latter would error out if another resource was already cached for the given path.
*/
public open fun takeOverPath(path: String): Unit {
TransferContext.writeArguments(STRING to path)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_RESOURCE_TAKE_OVER_PATH, NIL)
}
}
| 50 | null | 25 | 301 | 0d33ac361b354b26c31bb36c7f434e6455583738 | 8,126 | godot-kotlin-jvm | MIT License |
library/core/api/src/main/kotlin/de/lise/fluxflow/api/continuation/history/query/filter/WorkflowObjectReferenceFilter.kt | lisegmbh | 740,936,659 | false | {"Kotlin": 732949} | package de.lise.fluxflow.api.continuation.history.query.filter
import de.lise.fluxflow.api.WorkflowObjectKind
import de.lise.fluxflow.query.filter.Filter
data class WorkflowObjectReferenceFilter(
val kind: Filter<WorkflowObjectKind>? = null,
val objectId: Filter<String>? = null
) | 20 | Kotlin | 0 | 7 | b7caae962301480df123da2c541004829d5572fd | 290 | fluxflow | Apache License 2.0 |
charset/src/com/fleeksoft/charset/cs/iso/ISO_8859_9.kt | fleeksoft | 874,918,183 | false | {"Kotlin": 8845941} | package com.fleeksoft.charset.cs.ibm
import com.fleeksoft.charset.Charset
import com.fleeksoft.charset.CharsetDecoder
import com.fleeksoft.charset.CharsetEncoder
import com.fleeksoft.charset.cs.SingleByte
class IBM855 private constructor() : Charset("IBM855") {
fun contains(cs: Charset): Boolean {
return (cs is IBM855)
}
override fun newDecoder(): CharsetDecoder {
return SingleByte.Decoder(this, Holder.b2c, false, false)
}
override fun newEncoder(): CharsetEncoder {
return SingleByte.Encoder(this, Holder.c2b, Holder.c2bIndex, false)
}
private object Holder {
private const val b2cTable = "\u0452\u0402\u0453\u0403\u0451\u0401\u0454\u0404" + // 0x80 - 0x87
"\u0455\u0405\u0456\u0406\u0457\u0407\u0458\u0408" + // 0x88 - 0x8f
"\u0459\u0409\u045A\u040A\u045B\u040B\u045C\u040C" + // 0x90 - 0x97
"\u045E\u040E\u045F\u040F\u044E\u042E\u044A\u042A" + // 0x98 - 0x9f
"\u0430\u0410\u0431\u0411\u0446\u0426\u0434\u0414" + // 0xa0 - 0xa7
"\u0435\u0415\u0444\u0424\u0433\u0413\u00AB\u00BB" + // 0xa8 - 0xaf
"\u2591\u2592\u2593\u2502\u2524\u0445\u0425\u0438" + // 0xb0 - 0xb7
"\u0418\u2563\u2551\u2557\u255D\u0439\u0419\u2510" + // 0xb8 - 0xbf
"\u2514\u2534\u252C\u251C\u2500\u253C\u043A\u041A" + // 0xc0 - 0xc7
"\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u00A4" + // 0xc8 - 0xcf
"\u043B\u041B\u043C\u041C\u043D\u041D\u043E\u041E" + // 0xd0 - 0xd7
"\u043F\u2518\u250C\u2588\u2584\u041F\u044F\u2580" + // 0xd8 - 0xdf
"\u042F\u0440\u0420\u0441\u0421\u0442\u0422\u0443" + // 0xe0 - 0xe7
"\u0423\u0436\u0416\u0432\u0412\u044C\u042C\u2116" + // 0xe8 - 0xef
"\u00AD\u044B\u042B\u0437\u0417\u0448\u0428\u044D" + // 0xf0 - 0xf7
"\u042D\u0449\u0429\u0447\u0427\u00A7\u25A0\u00A0" + // 0xf8 - 0xff
"\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007" + // 0x00 - 0x07
"\b\t\n\u000B\u000c\r\u000E\u000F" + // 0x08 - 0x0f
"\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017" + // 0x10 - 0x17
"\u0018\u0019\u001A\u001B\u001C\u001D\u001E\u001F" + // 0x18 - 0x1f
"\u0020\u0021\"\u0023\u0024\u0025\u0026\'" + // 0x20 - 0x27
"\u0028\u0029\u002A\u002B\u002C\u002D\u002E\u002F" + // 0x28 - 0x2f
"\u0030\u0031\u0032\u0033\u0034\u0035\u0036\u0037" + // 0x30 - 0x37
"\u0038\u0039\u003A\u003B\u003C\u003D\u003E\u003F" + // 0x38 - 0x3f
"\u0040\u0041\u0042\u0043\u0044\u0045\u0046\u0047" + // 0x40 - 0x47
"\u0048\u0049\u004A\u004B\u004C\u004D\u004E\u004F" + // 0x48 - 0x4f
"\u0050\u0051\u0052\u0053\u0054\u0055\u0056\u0057" + // 0x50 - 0x57
"\u0058\u0059\u005A\u005B\\\u005D\u005E\u005F" + // 0x58 - 0x5f
"\u0060\u0061\u0062\u0063\u0064\u0065\u0066\u0067" + // 0x60 - 0x67
"\u0068\u0069\u006A\u006B\u006C\u006D\u006E\u006F" + // 0x68 - 0x6f
"\u0070\u0071\u0072\u0073\u0074\u0075\u0076\u0077" + // 0x70 - 0x77
"\u0078\u0079\u007A\u007B\u007C\u007D\u007E\u007F" // 0x78 - 0x7f
val b2c: CharArray = b2cTable.toCharArray()
val c2b: CharArray = CharArray(0x400)
val c2bIndex: CharArray = CharArray(0x100)
init {
val b2cMap = b2c
val c2bNR: CharArray? = null
SingleByte.initC2B(b2cMap, c2bNR, c2b, c2bIndex)
}
}
companion object {
val INSTANCE = IBM855()
}
}
| 1 | Kotlin | 0 | 2 | a16af685a558ad177749c12d7840a7b67aece66c | 3,711 | charset | MIT License |
app/src/main/java/io/horizontalsystems/bankwallet/core/providers/AppConfigProvider.kt | horizontalsystems | 142,825,178 | false | null | package io.horizontalsystems.bankwallet.core.providers
import io.horizontalsystems.bankwallet.R
import io.horizontalsystems.bankwallet.entities.Currency
class AppConfigProvider {
val companyWebPageLink: String = "https://horizontalsystems.io"
val appWebPageLink: String = "https://unstoppable.money"
val appGithubLink: String = "https://github.com/horizontalsystems/unstoppable-wallet-android"
val appTwitterLink: String = "https://twitter.com/UnstoppableByHS"
val appTelegramLink: String = "https://t.me/unstoppable_announcements"
val appRedditLink: String = "https://www.reddit.com/r/UNSTOPPABLEWallet/"
val reportEmail = "<EMAIL>"
val btcCoreRpcUrl: String = "https://btc.blocksdecoded.com/rpc"
val releaseNotesUrl: String = "https://api.github.com/repos/horizontalsystems/unstoppable-wallet-android/releases/tags/"
val walletConnectUrl = "relay.walletconnect.com"
val walletConnectProjectId by lazy {
Translator.getString(R.string.walletConnectV2Key)
}
val twitterBearerToken by lazy {
Translator.getString(R.string.twitterBearerToken)
}
val cryptoCompareApiKey by lazy {
Translator.getString(R.string.cryptoCompareApiKey)
}
val defiyieldProviderApiKey by lazy {
Translator.getString(R.string.defiyieldProviderApiKey)
}
val infuraProjectId by lazy {
Translator.getString(R.string.infuraProjectId)
}
val infuraProjectSecret by lazy {
Translator.getString(R.string.infuraSecretKey)
}
val etherscanApiKey by lazy {
Translator.getString(R.string.etherscanKey)
}
val bscscanApiKey by lazy {
Translator.getString(R.string.bscscanKey)
}
val polygonscanApiKey by lazy {
Translator.getString(R.string.polygonscanKey)
}
val snowtraceApiKey by lazy {
Translator.getString(R.string.snowtraceApiKey)
}
val optimisticEtherscanApiKey by lazy {
Translator.getString(R.string.optimisticEtherscanApiKey)
}
val arbiscanApiKey by lazy {
Translator.getString(R.string.arbiscanApiKey)
}
val gnosisscanApiKey by lazy {
Translator.getString(R.string.gnosisscanApiKey)
}
val guidesUrl by lazy {
Translator.getString(R.string.guidesUrl)
}
val faqUrl by lazy {
Translator.getString(R.string.faqUrl)
}
val coinsJsonUrl by lazy {
Translator.getString(R.string.coinsJsonUrl)
}
val providerCoinsJsonUrl by lazy {
Translator.getString(R.string.providerCoinsJsonUrl)
}
val marketApiBaseUrl by lazy {
Translator.getString(R.string.marketApiBaseUrl)
}
val marketApiKey by lazy {
Translator.getString(R.string.marketApiKey)
}
val fiatDecimal: Int = 2
val feeRateAdjustForCurrencies: List<String> = listOf("USD", "EUR")
val currencies: List<Currency> = listOf(
Currency("AUD", "A$", 2, R.drawable.icon_32_flag_australia),
Currency("BRL", "R$", 2, R.drawable.icon_32_flag_brazil),
Currency("CAD", "C$", 2, R.drawable.icon_32_flag_canada),
Currency("CHF", "₣", 2, R.drawable.icon_32_flag_switzerland),
Currency("CNY", "¥", 2, R.drawable.icon_32_flag_china),
Currency("EUR", "€", 2, R.drawable.icon_32_flag_europe),
Currency("GBP", "£", 2, R.drawable.icon_32_flag_england),
Currency("HKD", "HK$", 2, R.drawable.icon_32_flag_hongkong),
Currency("ILS", "₪", 2, R.drawable.icon_32_flag_israel),
Currency("INR", "₹", 2, R.drawable.icon_32_flag_india),
Currency("JPY", "¥", 2, R.drawable.icon_32_flag_japan),
Currency("RUB", "₽", 2, R.drawable.icon_32_flag_russia),
Currency("SGD", "S$", 2, R.drawable.icon_32_flag_singapore),
Currency("USD", "$", 2, R.drawable.icon_32_flag_usa),
Currency("ZAR", "R", 2, R.drawable.icon_32_flag_south_africa),
)
}
| 57 | Kotlin | 333 | 665 | b8b4e14953949592e2d73cdaadbc72241278914f | 3,927 | unstoppable-wallet-android | MIT License |
app/src/main/java/com/hypertrack/android/ui/screens/add_integration/AddIntegrationViewModel.kt | hypertrack | 241,723,736 | false | null | package com.hypertrack.android.ui.screens.add_integration
import android.view.View
import androidx.lifecycle.*
import com.hypertrack.android.interactors.app.AppEffectAction
import com.hypertrack.android.interactors.app.ReportAppErrorEffect
import com.hypertrack.android.interactors.app.ShowAndReportAppErrorEffect
import com.hypertrack.android.interactors.app.noAction
import com.hypertrack.android.interactors.app.state.UserLoggedIn
import com.hypertrack.android.models.Integration
import com.hypertrack.android.repository.IntegrationsRepository
import com.hypertrack.android.ui.base.BaseAdapter
import com.hypertrack.android.ui.base.BaseViewModel
import com.hypertrack.android.ui.base.BaseViewModelDependencies
import com.hypertrack.android.ui.base.Consumable
import com.hypertrack.android.ui.common.util.toView
import com.hypertrack.android.ui.common.util.updateAsFlow
import com.hypertrack.android.ui.common.util.updateConsumableAsFlow
import com.hypertrack.android.utils.Failure
import com.hypertrack.android.utils.MyApplication
import com.hypertrack.android.utils.StateMachine
import com.hypertrack.android.utils.Success
import com.hypertrack.android.utils.collections.asSet
import com.hypertrack.android.utils.catchException
import com.hypertrack.android.utils.exception.IllegalActionException
import com.hypertrack.android.utils.state_machine.ReducerResult
import com.hypertrack.android.utils.withEffects
import com.hypertrack.logistics.android.github.R
import kotlinx.android.synthetic.main.item_integration.view.tvDescription
import kotlinx.android.synthetic.main.item_integration.view.tvName
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
@Suppress("EXPERIMENTAL_API_USAGE", "OPT_IN_USAGE")
class AddIntegrationViewModel(
baseDependencies: BaseViewModelDependencies,
private val userStateFlow: StateFlow<UserLoggedIn?>,
private val integrationsRepository: IntegrationsRepository
) : BaseViewModel(baseDependencies) {
val adapter = createAdapter()
val viewState = MutableLiveData<ViewState>()
val integrationSelectedEvent = MutableLiveData<Consumable<Integration>>()
private val stateMachine = StateMachine<Action, State, Effect>(
javaClass.simpleName,
crashReportsProvider,
Loading(query = EMPTY_QUERY),
actionsScope,
this::reduce,
this::applyEffects,
this::stateChangeEffects,
)
fun handleAction(action: Action) {
stateMachine.handleAction(action)
}
private fun reduce(state: State, action: Action): ReducerResult<out State, out Effect> {
return userStateFlow.value?.let {
reduceIfLoggedIn(action, state, it)
} ?: IllegalActionException(action, state).let { exception ->
state.withEffects(
AppEffect(ShowAndReportAppErrorEffect(exception))
)
}
}
private fun reduceIfLoggedIn(
action: Action,
state: State,
userState: UserLoggedIn
): ReducerResult<out State, out Effect> {
return when (state) {
is Loading -> {
when (action) {
is InitAction -> {
reduce(action)
}
is OnIntegrationsResultAction -> {
when (action.result) {
is Success -> {
Loaded(
query = state.query,
integrations = action.result.data.items,
nextPageToken = action.result.data.paginationToken,
newQuery = state.query
).withEffects()
}
is Failure -> {
onLoadingError(action.result.exception)
}
}
}
is OnQueryChangedAction,
OnRefreshAction,
is OnIntegrationClickedAction,
OnLoadMoreAction,
OnInitSearchAction -> {
illegalAction(action, state)
}
}
}
is Loaded -> {
when (action) {
is InitAction -> {
reduce(action)
}
is OnQueryChangedAction -> {
state.copy(newQuery = action.query).withEffects()
}
OnInitSearchAction -> {
Loading(query = state.newQuery).withEffects(
LoadIntegrationsEffect(
query = state.newQuery,
pageToken = null
)
)
}
OnLoadMoreAction -> {
state.withEffects(
state.nextPageToken?.let { pageToken ->
LoadIntegrationsEffect(
query = state.query,
pageToken = pageToken
).asSet()
} ?: setOf()
)
}
is OnIntegrationsResultAction -> {
when (action.result) {
is Success -> {
state.copy(
integrations = state.integrations + action.result.data.items,
nextPageToken = action.result.data.paginationToken
).withEffects()
}
is Failure -> {
onLoadingError(action.result.exception)
}
}
}
is OnIntegrationClickedAction -> {
state.withEffects(
OnIntegrationSelectedEffect(action.integration)
)
}
OnRefreshAction -> {
reduceIfLoggedIn(OnInitSearchAction, state, userState)
}
}
}
}
}
private fun reduce(action: InitAction): ReducerResult<Loading, LoadIntegrationsEffect> {
return Loading(query = EMPTY_QUERY).withEffects(
LoadIntegrationsEffect(query = EMPTY_QUERY, pageToken = null)
)
}
private fun applyEffects(effects: Set<Effect>) {
effects.forEach { effect ->
runInVmEffectsScope {
getEffectFlow(effect)
.catchException { onError(it) }
.collect {
it?.let { handleAction(it) }
}
}
}
}
private fun stateChangeEffects(newState: State): Set<Effect> {
return setOf(UpdateViewStateEffect(newState, getViewState(newState)))
}
private fun onLoadingError(exception: Exception): ReducerResult<State, AppEffect> {
return Loaded(
query = EMPTY_QUERY,
integrations = listOf(),
nextPageToken = null,
newQuery = EMPTY_QUERY
).withEffects(
AppEffect(ShowAndReportAppErrorEffect(exception))
)
}
private fun getEffectFlow(effect: Effect): Flow<Action?> {
return when (effect) {
is AppEffect -> {
appInteractor.handleActionFlow(AppEffectAction(effect.appEffect)).noAction()
}
is LoadIntegrationsEffect -> {
suspend {
integrationsRepository.getIntegrations(effect.query).let {
OnIntegrationsResultAction(it)
}
}.asFlow()
}
is OnIntegrationSelectedEffect -> {
integrationSelectedEvent.updateConsumableAsFlow(effect.integration).noAction()
}
is UpdateViewStateEffect -> {
viewState.updateAsFlow(effect.viewState).map {
adapter.updateItems(effect.state.getIntegrationsIfPresent())
}.flowOn(Dispatchers.Main).noAction()
}
}
}
private fun getViewState(state: State): ViewState {
return when (state) {
is Loading -> {
ViewState(
showProgressbar = true,
showList = false,
showPlaceholder = false,
showSearchButton = false,
showSearchField = false
)
}
is Loaded -> {
ViewState(
showProgressbar = false,
showList = state.integrations.isNotEmpty() && state.newQuery == state.query,
showPlaceholder = state.integrations.isEmpty(),
showSearchButton = state.newQuery != state.query,
showSearchField = true
)
}
}
}
private fun illegalAction(action: Action, state: State): ReducerResult<State, Effect> {
return IllegalActionException(action, state).let {
if (MyApplication.DEBUG_MODE) {
throw it
} else {
state.withEffects(AppEffect(ReportAppErrorEffect(it)))
}
}
}
private fun createAdapter(): BaseAdapter<Integration, BaseAdapter.BaseVh<Integration>> {
return object : BaseAdapter<Integration, BaseAdapter.BaseVh<Integration>>() {
override val itemLayoutResource = R.layout.item_integration
override fun createViewHolder(
view: View,
baseClickListener: (Int) -> Unit
): BaseVh<Integration> {
return object : BaseContainerVh<Integration>(view, baseClickListener) {
override fun bind(item: Integration) {
item.name?.toView(containerView.tvName)
item.id.toView(containerView.tvDescription)
}
}
}
}.apply {
onItemClickListener = {
handleAction(OnIntegrationClickedAction(it))
}
}
}
companion object {
const val EMPTY_QUERY = ""
}
}
| 1 | Kotlin | 17 | 31 | c5dd23621aed11ff188cf98ac037b67f435e9f5b | 10,772 | visits-android | MIT License |
app/src/main/java/com/yamanf/shoppingapp/ui/adapter/SearchAdapter.kt | yamanf | 557,850,840 | false | null | package com.yamanf.shoppingapp.ui.adapter
import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.navigation.findNavController
import androidx.recyclerview.widget.RecyclerView
import com.yamanf.shoppingapp.R
import com.yamanf.shoppingapp.data.model.Products
import com.yamanf.shoppingapp.data.model.ProductsItem
import com.yamanf.shoppingapp.ui.product.list.ProductFragmentDirections
import com.yamanf.shoppingapp.ui.search.SearchFragmentDirections
import com.yamanf.shoppingapp.utils.Utils.downloadFromUrl
class SearchAdapter(private var searchList: Products) : RecyclerView.Adapter<SearchAdapter.SearchViewHolder>(),
Filterable {
class SearchViewHolder(view: View): RecyclerView.ViewHolder(view){
// Items initialize here
private val ivProduct: ImageView = view.findViewById(R.id.ivSearchProduct)
private val tvTitle: TextView = view.findViewById(R.id.tvSearchTitle)
private val tvPrice: TextView = view.findViewById(R.id.tvSearchPrice)
private val container: ConstraintLayout = view.findViewById(R.id.searchContainer)
@SuppressLint("SetTextI18n")
fun bindItems(item: ProductsItem) {
ivProduct.downloadFromUrl(item.image)
tvTitle.text = item.title
tvPrice.text = item.price.toString() + " TL"
container.setOnClickListener{
it.findNavController().navigate(SearchFragmentDirections.actionSearchFragmentToProductDetailFragment(item.id))
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SearchViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_search_list, parent, false)
return SearchViewHolder(view)
}
override fun getItemCount(): Int {
return searchList.size
}
override fun onBindViewHolder(holder: SearchViewHolder, position: Int) {
holder.bindItems(searchList[position])
}
override fun getFilter(): Filter {
TODO("Not yet implemented")
}
} | 0 | Kotlin | 0 | 0 | 6a70f24f614d313e18e69a202ae9e79a93aa8cf7 | 2,200 | PazaramaBootcamp-FinalProject | Apache License 2.0 |
app/src/main/java/com/yamanf/shoppingapp/ui/adapter/SearchAdapter.kt | yamanf | 557,850,840 | false | null | package com.yamanf.shoppingapp.ui.adapter
import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.navigation.findNavController
import androidx.recyclerview.widget.RecyclerView
import com.yamanf.shoppingapp.R
import com.yamanf.shoppingapp.data.model.Products
import com.yamanf.shoppingapp.data.model.ProductsItem
import com.yamanf.shoppingapp.ui.product.list.ProductFragmentDirections
import com.yamanf.shoppingapp.ui.search.SearchFragmentDirections
import com.yamanf.shoppingapp.utils.Utils.downloadFromUrl
class SearchAdapter(private var searchList: Products) : RecyclerView.Adapter<SearchAdapter.SearchViewHolder>(),
Filterable {
class SearchViewHolder(view: View): RecyclerView.ViewHolder(view){
// Items initialize here
private val ivProduct: ImageView = view.findViewById(R.id.ivSearchProduct)
private val tvTitle: TextView = view.findViewById(R.id.tvSearchTitle)
private val tvPrice: TextView = view.findViewById(R.id.tvSearchPrice)
private val container: ConstraintLayout = view.findViewById(R.id.searchContainer)
@SuppressLint("SetTextI18n")
fun bindItems(item: ProductsItem) {
ivProduct.downloadFromUrl(item.image)
tvTitle.text = item.title
tvPrice.text = item.price.toString() + " TL"
container.setOnClickListener{
it.findNavController().navigate(SearchFragmentDirections.actionSearchFragmentToProductDetailFragment(item.id))
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SearchViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_search_list, parent, false)
return SearchViewHolder(view)
}
override fun getItemCount(): Int {
return searchList.size
}
override fun onBindViewHolder(holder: SearchViewHolder, position: Int) {
holder.bindItems(searchList[position])
}
override fun getFilter(): Filter {
TODO("Not yet implemented")
}
} | 0 | Kotlin | 0 | 0 | 6a70f24f614d313e18e69a202ae9e79a93aa8cf7 | 2,200 | PazaramaBootcamp-FinalProject | Apache License 2.0 |
app/src/main/java/work/yeshu/demo/andserverdemo/MainActivity.kt | yeshu-cn | 248,478,705 | false | {"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Git Attributes": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 3, "XML": 17, "Java": 1, "HTML": 1} | /*
*
* * Copyright (c) 2018 yeshu. All Rights Reserved.
*
*/
package work.yeshu.demo.andserverdemo
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.yanzhenjie.andserver.AndServer
import com.yanzhenjie.andserver.Server
import com.yanzhenjie.andserver.Server.ServerListener
import kotlinx.android.synthetic.main.activity_main.*
import java.util.concurrent.TimeUnit
class MainActivity : AppCompatActivity() {
private lateinit var server: Server
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
server = AndServer.webServer(this)
.port(8080)
.timeout(10, TimeUnit.SECONDS)
.listener(object : ServerListener {
override fun onException(e: Exception?) {
}
override fun onStarted() {
tv_status.text = "${tv_status.text}\n server start"
}
override fun onStopped() {
tv_status.text = "${tv_status.text}\n server stop!!"
}
})
.build()
}
override fun onDestroy() {
super.onDestroy()
if (server.isRunning) {
server.shutdown()
}
}
fun onButtonClick(view: View) {
if (server.isRunning) {
server.shutdown()
button.text = "start"
} else {
server.startup()
button.text = "stop"
}
}
}
| 1 | null | 1 | 1 | cfd5ffd757ad7f8dd9fee176d85553f54a722386 | 1,573 | AndServerDemo | MIT License |
ggdsl-echarts/src/main/kotlin/org/jetbrains/kotlinx/ggdsl/echarts/settings/BorderLayearContext.kt | Kotlin | 502,039,936 | false | null | /*
* Copyright 2020-2023 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package org.jetbrains.kotlinx.ggdsl.echarts.settings
import org.jetbrains.kotlinx.ggdsl.dsl.internal.BindingContext
import org.jetbrains.kotlinx.ggdsl.echarts.aes.BorderColorAes
import org.jetbrains.kotlinx.ggdsl.echarts.aes.BorderRadiusAes
import org.jetbrains.kotlinx.ggdsl.echarts.aes.BorderTypeAes
import org.jetbrains.kotlinx.ggdsl.echarts.aes.BorderWidthAes
import org.jetbrains.kotlinx.ggdsl.echarts.layers.BarContextImmutable
import org.jetbrains.kotlinx.ggdsl.echarts.layers.PointContextImmutable
import org.jetbrains.kotlinx.ggdsl.util.color.Color
/**
* Adds [border][BorderLayerContext] settings to [bars][org.jetbrains.kotlinx.ggdsl.echarts.layers.bars].
*/
public fun BarContextImmutable.border(block: BorderLayerContext.() -> Unit) {
BorderLayerContext(this).apply(block)
}
/**
* Adds [border][BorderLayerContext] settings to [points][org.jetbrains.kotlinx.ggdsl.echarts.layers.points].
*/
public fun PointContextImmutable.border(block: BorderLayerContext.() -> Unit) {
BorderLayerContext(this).apply(block)
}
/**
* Border context with aesthetic attribute properties.
*
* @property color border [color][Color].
* @property width border width. By default `0`.
* @property type border [type][LineType]. By default `solid`.
* @property radius border radius. By default `0`.
*
* @see Color
* @see LineType
*/
public class BorderLayerContext(context: BindingContext) {
public val color: BorderColorAes = BorderColorAes(context)
public val width: BorderWidthAes = BorderWidthAes(context)
public val type: BorderTypeAes = BorderTypeAes(context)
public val radius: BorderRadiusAes = BorderRadiusAes(context)
}
| 48 | Kotlin | 1 | 44 | 8a161098d0d946c28bde3cf3c7bea6a1eeba073c | 1,767 | ggdsl | Apache License 2.0 |
vector/src/main/java/im/vector/riotx/features/settings/VectorSettingsSecurityPrivacyFragment.kt | aalzehla | 287,565,471 | false | null | /*
* Copyright 2019 New Vector Ltd
* Copyright 2020 New Vector Ltd
*
* 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 im.vector.riotx.features.settings
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.preference.Preference
import androidx.preference.PreferenceCategory
import androidx.preference.SwitchPreference
import com.google.android.material.textfield.TextInputEditText
import im.vector.matrix.android.api.MatrixCallback
import im.vector.matrix.android.internal.crypto.crosssigning.isVerified
import im.vector.matrix.android.internal.crypto.model.ImportRoomKeysResult
import im.vector.matrix.android.internal.crypto.model.rest.DeviceInfo
import im.vector.matrix.android.internal.crypto.model.rest.DevicesListResponse
import im.vector.matrix.rx.SecretsSynchronisationInfo
import im.vector.matrix.rx.rx
import im.vector.riotx.R
import im.vector.riotx.core.di.ActiveSessionHolder
import im.vector.riotx.core.dialogs.ExportKeysDialog
import im.vector.riotx.core.extensions.queryExportKeys
import im.vector.riotx.core.intent.ExternalIntentData
import im.vector.riotx.core.intent.analyseIntent
import im.vector.riotx.core.intent.getFilenameFromUri
import im.vector.riotx.core.platform.SimpleTextWatcher
import im.vector.riotx.core.preference.VectorPreference
import im.vector.riotx.core.preference.VectorPreferenceCategory
import im.vector.riotx.core.utils.openFileSelection
import im.vector.riotx.core.utils.toast
import im.vector.riotx.features.crypto.keys.KeysExporter
import im.vector.riotx.features.crypto.keys.KeysImporter
import im.vector.riotx.features.crypto.keysbackup.settings.KeysBackupManageActivity
import im.vector.riotx.features.crypto.recover.BootstrapBottomSheet
import im.vector.riotx.features.themes.ThemeUtils
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import javax.inject.Inject
class VectorSettingsSecurityPrivacyFragment @Inject constructor(
private val vectorPreferences: VectorPreferences,
private val activeSessionHolder: ActiveSessionHolder
) : VectorSettingsBaseFragment() {
override var titleRes = R.string.settings_security_and_privacy
override val preferenceXmlRes = R.xml.vector_settings_security_privacy
private var disposables = mutableListOf<Disposable>()
// cryptography
private val mCryptographyCategory by lazy {
findPreference<PreferenceCategory>(VectorPreferences.SETTINGS_CRYPTOGRAPHY_PREFERENCE_KEY)!!
}
private val mCrossSigningStatePreference by lazy {
findPreference<VectorPreference>(VectorPreferences.SETTINGS_ENCRYPTION_CROSS_SIGNING_PREFERENCE_KEY)!!
}
private val manageBackupPref by lazy {
findPreference<VectorPreference>(VectorPreferences.SETTINGS_SECURE_MESSAGE_RECOVERY_PREFERENCE_KEY)!!
}
private val exportPref by lazy {
findPreference<VectorPreference>(VectorPreferences.SETTINGS_ENCRYPTION_EXPORT_E2E_ROOM_KEYS_PREFERENCE_KEY)!!
}
private val importPref by lazy {
findPreference<VectorPreference>(VectorPreferences.SETTINGS_ENCRYPTION_IMPORT_E2E_ROOM_KEYS_PREFERENCE_KEY)!!
}
private val showDeviceListPref by lazy {
findPreference<VectorPreference>(VectorPreferences.SETTINGS_SHOW_DEVICES_LIST_PREFERENCE_KEY)!!
}
// encrypt to unverified devices
private val sendToUnverifiedDevicesPref by lazy {
findPreference<SwitchPreference>(VectorPreferences.SETTINGS_ENCRYPTION_NEVER_SENT_TO_PREFERENCE_KEY)!!
}
override fun onResume() {
super.onResume()
// My device name may have been updated
refreshMyDevice()
refreshXSigningStatus()
session.rx().liveSecretSynchronisationInfo()
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
refresh4SSection(it)
refreshXSigningStatus()
}.also {
disposables.add(it)
}
}
private val secureBackupCategory by lazy {
findPreference<VectorPreferenceCategory>("SETTINGS_CRYPTOGRAPHY_MANAGE_4S_CATEGORY_KEY")!!
}
private val secureBackupPreference by lazy {
findPreference<VectorPreference>("SETTINGS_SECURE_BACKUP_RECOVERY_PREFERENCE_KEY")!!
}
// private val secureBackupResetPreference by lazy {
// findPreference<VectorPreference>(VectorPreferences.SETTINGS_SECURE_BACKUP_RESET_PREFERENCE_KEY)
// }
override fun onPause() {
super.onPause()
disposables.forEach {
it.dispose()
}
disposables.clear()
}
private fun refresh4SSection(info: SecretsSynchronisationInfo) {
// it's a lot of if / else if / else
// But it's not yet clear how to manage all cases
if (!info.isCrossSigningEnabled) {
// There is not cross signing, so we can remove the section
secureBackupCategory.isVisible = false
} else {
if (!info.isBackupSetup) {
if (info.isCrossSigningEnabled && info.allPrivateKeysKnown) {
// You can setup recovery!
secureBackupCategory.isVisible = true
secureBackupPreference.title = getString(R.string.settings_secure_backup_setup)
secureBackupPreference.onPreferenceClickListener = Preference.OnPreferenceClickListener {
BootstrapBottomSheet.show(parentFragmentManager, initCrossSigningOnly = false, forceReset4S = false)
true
}
} else {
// just hide all, you can't setup from here
// you should synchronize to get gossips
secureBackupCategory.isVisible = false
}
} else {
// so here we know that 4S is setup
if (info.isCrossSigningTrusted && info.allPrivateKeysKnown) {
// Looks like we have all cross signing secrets and session is trusted
// Let's see if there is a megolm backup
if (!info.megolmBackupAvailable || info.megolmSecretKnown) {
// Only option here is to create a new backup if you want?
// aka reset
secureBackupCategory.isVisible = true
secureBackupPreference.title = getString(R.string.settings_secure_backup_reset)
secureBackupPreference.onPreferenceClickListener = Preference.OnPreferenceClickListener {
BootstrapBottomSheet.show(parentFragmentManager, initCrossSigningOnly = false, forceReset4S = true)
true
}
} else if (!info.megolmSecretKnown) {
// megolm backup is available but we don't have key
// you could try to synchronize to get missing megolm key ?
secureBackupCategory.isVisible = true
secureBackupPreference.title = getString(R.string.settings_secure_backup_enter_to_setup)
secureBackupPreference.onPreferenceClickListener = Preference.OnPreferenceClickListener {
vectorActivity.let {
it.navigator.requestSelfSessionVerification(it)
}
true
}
} else {
secureBackupCategory.isVisible = false
}
} else {
// there is a backup, but this session is not trusted, or is missing some secrets
// you should enter passphrase to get them or verify against another session
secureBackupCategory.isVisible = true
secureBackupPreference.title = getString(R.string.settings_secure_backup_enter_to_setup)
secureBackupPreference.onPreferenceClickListener = Preference.OnPreferenceClickListener {
vectorActivity.let {
it.navigator.requestSelfSessionVerification(it)
}
true
}
}
}
}
}
override fun bindPref() {
// Push target
refreshPushersList()
// Refresh Key Management section
refreshKeysManagementSection()
// Analytics
// Analytics tracking management
findPreference<SwitchPreference>(VectorPreferences.SETTINGS_USE_ANALYTICS_KEY)!!.let {
// On if the analytics tracking is activated
it.isChecked = vectorPreferences.useAnalytics()
it.onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, newValue ->
vectorPreferences.setUseAnalytics(newValue as Boolean)
true
}
}
refreshXSigningStatus()
secureBackupPreference.icon = activity?.let {
ThemeUtils.tintDrawable(it,
ContextCompat.getDrawable(it, R.drawable.ic_secure_backup)!!, R.attr.vctr_settings_icon_tint_color)
}
}
// Todo this should be refactored and use same state as 4S section
private fun refreshXSigningStatus() {
val crossSigningKeys = session.cryptoService().crossSigningService().getMyCrossSigningKeys()
val xSigningIsEnableInAccount = crossSigningKeys != null
val xSigningKeysAreTrusted = session.cryptoService().crossSigningService().checkUserTrust(session.myUserId).isVerified()
val xSigningKeyCanSign = session.cryptoService().crossSigningService().canCrossSign()
when {
xSigningKeyCanSign -> {
mCrossSigningStatePreference.setIcon(R.drawable.ic_shield_trusted)
mCrossSigningStatePreference.summary = getString(R.string.encryption_information_dg_xsigning_complete)
}
xSigningKeysAreTrusted -> {
mCrossSigningStatePreference.setIcon(R.drawable.ic_shield_custom)
mCrossSigningStatePreference.summary = getString(R.string.encryption_information_dg_xsigning_trusted)
}
xSigningIsEnableInAccount -> {
mCrossSigningStatePreference.setIcon(R.drawable.ic_shield_black)
mCrossSigningStatePreference.summary = getString(R.string.encryption_information_dg_xsigning_not_trusted)
}
else -> {
mCrossSigningStatePreference.setIcon(android.R.color.transparent)
mCrossSigningStatePreference.summary = getString(R.string.encryption_information_dg_xsigning_disabled)
}
}
mCrossSigningStatePreference.isVisible = true
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == REQUEST_CODE_SAVE_MEGOLM_EXPORT) {
val uri = data?.data
if (resultCode == Activity.RESULT_OK && uri != null) {
activity?.let { activity ->
ExportKeysDialog().show(activity, object : ExportKeysDialog.ExportKeyDialogListener {
override fun onPassphrase(passphrase: String) {
displayLoadingView()
KeysExporter(session)
.export(requireContext(),
passphrase,
uri,
object : MatrixCallback<Boolean> {
override fun onSuccess(data: Boolean) {
if (data) {
requireActivity().toast(getString(R.string.encryption_exported_successfully))
} else {
requireActivity().toast(getString(R.string.unexpected_error))
}
hideLoadingView()
}
override fun onFailure(failure: Throwable) {
onCommonDone(failure.localizedMessage)
}
})
}
})
}
}
}
if (resultCode == Activity.RESULT_OK) {
when (requestCode) {
REQUEST_E2E_FILE_REQUEST_CODE -> importKeys(data)
}
}
}
private fun refreshKeysManagementSection() {
// If crypto is not enabled parent section will be removed
// TODO notice that this will not work when no network
manageBackupPref.onPreferenceClickListener = Preference.OnPreferenceClickListener {
context?.let {
startActivity(KeysBackupManageActivity.intent(it))
}
false
}
exportPref.onPreferenceClickListener = Preference.OnPreferenceClickListener {
queryExportKeys(activeSessionHolder.getSafeActiveSession()?.myUserId ?: "", REQUEST_CODE_SAVE_MEGOLM_EXPORT)
true
}
importPref.onPreferenceClickListener = Preference.OnPreferenceClickListener {
importKeys()
true
}
}
/**
* Manage the e2e keys import.
*/
@SuppressLint("NewApi")
private fun importKeys() {
activity?.let { openFileSelection(it, this, false, REQUEST_E2E_FILE_REQUEST_CODE) }
}
/**
* Manage the e2e keys import.
*
* @param intent the intent result
*/
private fun importKeys(intent: Intent?) {
// sanity check
if (null == intent) {
return
}
val sharedDataItems = analyseIntent(intent)
val thisActivity = activity
if (sharedDataItems.isNotEmpty() && thisActivity != null) {
val sharedDataItem = sharedDataItems[0]
val uri = when (sharedDataItem) {
is ExternalIntentData.IntentDataUri -> sharedDataItem.uri
is ExternalIntentData.IntentDataClipData -> sharedDataItem.clipDataItem.uri
else -> null
}
val mimetype = when (sharedDataItem) {
is ExternalIntentData.IntentDataClipData -> sharedDataItem.mimeType
else -> null
}
if (uri == null) {
return
}
val appContext = thisActivity.applicationContext
val filename = getFilenameFromUri(appContext, uri)
val dialogLayout = thisActivity.layoutInflater.inflate(R.layout.dialog_import_e2e_keys, null)
val textView = dialogLayout.findViewById<TextView>(R.id.dialog_e2e_keys_passphrase_filename)
if (filename.isNullOrBlank()) {
textView.isVisible = false
} else {
textView.isVisible = true
textView.text = getString(R.string.import_e2e_keys_from_file, filename)
}
val builder = AlertDialog.Builder(thisActivity)
.setTitle(R.string.encryption_import_room_keys)
.setView(dialogLayout)
val passPhraseEditText = dialogLayout.findViewById<TextInputEditText>(R.id.dialog_e2e_keys_passphrase_edit_text)
val importButton = dialogLayout.findViewById<Button>(R.id.dialog_e2e_keys_import_button)
passPhraseEditText.addTextChangedListener(object : SimpleTextWatcher() {
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
importButton.isEnabled = !passPhraseEditText.text.isNullOrEmpty()
}
})
val importDialog = builder.show()
importButton.setOnClickListener {
val password = passPhraseEditText.text.toString()
displayLoadingView()
KeysImporter(session)
.import(requireContext(),
uri,
mimetype,
password,
object : MatrixCallback<ImportRoomKeysResult> {
override fun onSuccess(data: ImportRoomKeysResult) {
if (!isAdded) {
return
}
hideLoadingView()
AlertDialog.Builder(thisActivity)
.setMessage(getString(R.string.encryption_import_room_keys_success,
data.successfullyNumberOfImportedKeys,
data.totalNumberOfKeys))
.setPositiveButton(R.string.ok) { dialog, _ -> dialog.dismiss() }
.show()
}
override fun onFailure(failure: Throwable) {
appContext.toast(failure.localizedMessage ?: getString(R.string.unexpected_error))
hideLoadingView()
}
})
importDialog.dismiss()
}
}
}
// ==============================================================================================================
// Cryptography
// ==============================================================================================================
/**
* Build the cryptography preference section.
*
* @param aMyDeviceInfo the device info
*/
private fun refreshCryptographyPreference(devices: List<DeviceInfo>) {
showDeviceListPref.isEnabled = devices.isNotEmpty()
showDeviceListPref.summary = resources.getQuantityString(R.plurals.settings_active_sessions_count, devices.size, devices.size)
// val userId = session.myUserId
// val deviceId = session.sessionParams.deviceId
// device name
// if (null != aMyDeviceInfo) {
// cryptoInfoDeviceNamePreference.summary = aMyDeviceInfo.displayName
//
// cryptoInfoDeviceNamePreference.onPreferenceClickListener = Preference.OnPreferenceClickListener {
// // TODO device can be rename only from the device list screen for the moment
// // displayDeviceRenameDialog(aMyDeviceInfo)
// true
// }
//
// cryptoInfoDeviceNamePreference.onPreferenceLongClickListener = object : VectorPreference.OnPreferenceLongClickListener {
// override fun onPreferenceLongClick(preference: Preference): Boolean {
// activity?.let { copyToClipboard(it, aMyDeviceInfo.displayName!!) }
// return true
// }
// }
// }
//
// // crypto section: device ID
// if (!deviceId.isNullOrEmpty()) {
// cryptoInfoDeviceIdPreference.summary = deviceId
//
// cryptoInfoDeviceIdPreference.setOnPreferenceClickListener {
// activity?.let { copyToClipboard(it, deviceId) }
// true
// }
// }
//
// // crypto section: device key (fingerprint)
// if (!deviceId.isNullOrEmpty() && userId.isNotEmpty()) {
// val deviceInfo = session.getDeviceInfo(userId, deviceId)
//
// if (null != deviceInfo && !deviceInfo.fingerprint().isNullOrEmpty()) {
// cryptoInfoTextPreference.summary = deviceInfo.getFingerprintHumanReadable()
//
// cryptoInfoTextPreference.setOnPreferenceClickListener {
// deviceInfo.fingerprint()?.let {
// copyToClipboard(requireActivity(), it)
// }
// true
// }
// }
// }
sendToUnverifiedDevicesPref.isChecked = session.cryptoService().getGlobalBlacklistUnverifiedDevices()
sendToUnverifiedDevicesPref.onPreferenceClickListener = Preference.OnPreferenceClickListener {
session.cryptoService().setGlobalBlacklistUnverifiedDevices(sendToUnverifiedDevicesPref.isChecked)
true
}
}
// ==============================================================================================================
// devices list
// ==============================================================================================================
private fun refreshMyDevice() {
session.cryptoService().getUserDevices(session.myUserId).map {
DeviceInfo(
user_id = session.myUserId,
deviceId = it.deviceId,
displayName = it.displayName()
)
}.let {
refreshCryptographyPreference(it)
}
// TODO Move to a ViewModel...
session.cryptoService().fetchDevicesList(object : MatrixCallback<DevicesListResponse> {
override fun onSuccess(data: DevicesListResponse) {
if (isAdded) {
refreshCryptographyPreference(data.devices.orEmpty())
}
}
override fun onFailure(failure: Throwable) {
if (isAdded) {
refreshCryptographyPreference(emptyList())
}
}
})
}
// ==============================================================================================================
// pushers list management
// ==============================================================================================================
/**
* Refresh the pushers list
*/
private fun refreshPushersList() {
activity?.let { _ ->
/* TODO
val pushManager = Matrix.getInstance(activity).pushManager
val pushersList = ArrayList(pushManager.mPushersList)
if (pushersList.isEmpty()) {
preferenceScreen.removePreference(mPushersSettingsCategory)
preferenceScreen.removePreference(mPushersSettingsDivider)
return
}
// check first if there is an update
var isNewList = true
if (pushersList.size == mDisplayedPushers.size) {
isNewList = !mDisplayedPushers.containsAll(pushersList)
}
if (isNewList) {
// remove the displayed one
mPushersSettingsCategory.removeAll()
// add new emails list
mDisplayedPushers = pushersList
var index = 0
for (pushRule in mDisplayedPushers) {
if (null != pushRule.lang) {
val isThisDeviceTarget = TextUtils.equals(pushManager.currentRegistrationToken, pushRule.pushkey)
val preference = VectorPreference(activity).apply {
mTypeface = if (isThisDeviceTarget) Typeface.BOLD else Typeface.NORMAL
}
preference.title = pushRule.deviceDisplayName
preference.summary = pushRule.appDisplayName
preference.key = PUSHER_PREFERENCE_KEY_BASE + index
index++
mPushersSettingsCategory.addPreference(preference)
// the user cannot remove the self device target
if (!isThisDeviceTarget) {
preference.onPreferenceLongClickListener = object : VectorPreference.OnPreferenceLongClickListener {
override fun onPreferenceLongClick(preference: Preference): Boolean {
AlertDialog.Builder(activity)
.setTitle(R.string.dialog_title_confirmation)
.setMessage(R.string.settings_delete_notification_targets_confirmation)
.setPositiveButton(R.string.remove)
{ _, _ ->
displayLoadingView()
pushManager.unregister(session, pushRule, object : MatrixCallback<Unit> {
override fun onSuccess(info: Void?) {
refreshPushersList()
onCommonDone(null)
}
override fun onNetworkError(e: Exception) {
onCommonDone(e.localizedMessage)
}
override fun onMatrixError(e: MatrixError) {
onCommonDone(e.localizedMessage)
}
override fun onUnexpectedError(e: Exception) {
onCommonDone(e.localizedMessage)
}
})
}
.setNegativeButton(R.string.cancel, null)
.show()
return true
}
}
}
}
}
}
*/
}
}
companion object {
private const val REQUEST_E2E_FILE_REQUEST_CODE = 123
private const val REQUEST_CODE_SAVE_MEGOLM_EXPORT = 124
private const val PUSHER_PREFERENCE_KEY_BASE = "PUSHER_PREFERENCE_KEY_BASE"
private const val DEVICES_PREFERENCE_KEY_BASE = "DEVICES_PREFERENCE_KEY_BASE"
// TODO i18n
const val LABEL_UNAVAILABLE_DATA = "none"
}
}
| 1 | null | 1 | 1 | ee1d5faf0d59f9cc1c058d45fae3e811d97740fd | 27,730 | element-android | Apache License 2.0 |
rxhttp-compiler/src/main/java/com/rxhttp/compiler/Constants.kt | liujingxing | 167,158,553 | false | null | package com.rxhttp.compiler
import com.squareup.javapoet.ClassName
/**
* User: ljx
* Date: 2021/11/23
* Time: 16:10
*/
const val RxHttp = "RxHttp"
const val defaultPackageName = "rxhttp.wrapper.param"
const val rxhttp_rxjava = "rxhttp_rxjava"
const val rxhttp_package = "rxhttp_package"
const val rxhttp_incremental = "rxhttp_incremental"
const val rxhttp_debug = "rxhttp_debug"
const val rxhttp_android_platform = "rxhttp_android_platform"
val rxhttpKClass = com.squareup.kotlinpoet.ClassName(rxHttpPackage, RxHttp)
val rxhttpClass: ClassName = ClassName.get(rxHttpPackage, RxHttp)
| 4 | null | 441 | 3,530 | 1af21b959fd6bd033f7c5d4c1cb78fe5673825b8 | 592 | rxhttp | Apache License 2.0 |
api/src/main/kotlin/de/jnkconsulting/e3dc/easyrscp/api/service/model/PowerState.kt | jnk-cons | 691,762,451 | false | {"Kotlin": 918056} | package de.jnkconsulting.e3dc.easyrscp.api.service.model
import java.time.Instant
/**
* Represents the current status of the home power plant, in which the basic values are mapped.
*
* @param timestamp Timestamp at which the values were measured
* @param pvDelivery Current power supply from the photovoitaik modules in watts
* @param gridDelivery Current power delivery from (positive value) or to (negative value) the grid in watts
* @param batteryDelivery Current power delivery from (positive value) or into (negative value) the battery in watts
* @param houseConsumption Current power consumption of the house in watts
* @param batteryChargingLevel Current battery charge level
* @param wallboxConsumption Current energy consumption of all connected wallboxes. The value is not(!) included in [houseConsumption]. Specified in watts
* @param wallboxProportionateSolarShare Proportion of energy in [wallboxConsumption] that is generated from solar energy. Specified in watts
*
* @since 2.0
*
* @since 2.3
* - Added [wallboxConsumption] and [wallboxProportionateSolarShare]
*/
data class PowerState(
val timestamp: Instant,
val pvDelivery: Int,
val gridDelivery: Int,
val batteryDelivery: Int,
val houseConsumption: Int,
val batteryChargingLevel: Percentage,
val wallboxConsumption: Int,
val wallboxProportionateSolarShare: Int
)
| 5 | Kotlin | 0 | 1 | 8627cdddb76e29624ec4d186f063dd05ff9489da | 1,382 | easy-rscp | MIT License |
app/src/main/java/com/vcheck/sdk/core/presentation/country_stage/ChooseCountryFragment.kt | VCheckOrg | 530,737,486 | false | null | package com.vcheck.sdk.core.presentation.country_stage
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.activity.addCallback
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import com.vcheck.sdk.core.R
import com.vcheck.sdk.core.VCheckSDK
import com.vcheck.sdk.core.databinding.ChooseCountryFragmentBinding
import com.vcheck.sdk.core.di.VCheckDIContainer
import com.vcheck.sdk.core.domain.CountryTO
import com.vcheck.sdk.core.presentation.transferrable_objects.ChooseProviderLogicTO
import com.vcheck.sdk.core.presentation.transferrable_objects.CountriesListTO
import com.vcheck.sdk.core.presentation.transferrable_objects.ProviderLogicCase
import com.vcheck.sdk.core.util.ThemeWrapperFragment
import com.vcheck.sdk.core.util.checkUserInteractionCompletedForResult
import com.vcheck.sdk.core.util.toFlagEmoji
import java.text.Collator
import java.util.*
import kotlin.collections.ArrayList
class ChooseCountryFragment : ThemeWrapperFragment() {
private lateinit var binding: ChooseCountryFragmentBinding
private val args: ChooseCountryFragmentArgs by navArgs()
private lateinit var _viewModel: ChooseCountryViewModel
private var finalCountries: List<CountryTO> = emptyList()
override fun changeColorsToCustomIfPresent() {
VCheckSDK.buttonsColorHex?.let {
binding.chooseCountryContinueButton.setBackgroundColor(Color.parseColor(it))
}
VCheckSDK.backgroundPrimaryColorHex?.let {
binding.chooseCountryBackground.background = ColorDrawable(Color.parseColor(it))
}
VCheckSDK.backgroundSecondaryColorHex?.let {
binding.card.setCardBackgroundColor(Color.parseColor(it))
}
VCheckSDK.backgroundTertiaryColorHex?.let {
binding.chooseCountryCard.setCardBackgroundColor(Color.parseColor(it))
}
VCheckSDK.primaryTextColorHex?.let {
binding.chooseCountryTitle.setTextColor(Color.parseColor(it))
binding.chooseCountryCardTitle.setTextColor(Color.parseColor(it))
binding.countryTitle.setTextColor(Color.parseColor(it))
//binding.chooseCountryContinueButton.setTextColor(Color.parseColor(it))
}
VCheckSDK.secondaryTextColorHex?.let {
binding.chooseCountryDescription.setTextColor(Color.parseColor(it))
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?, savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.choose_country_fragment, container, false)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
_viewModel = ChooseCountryViewModel(VCheckDIContainer.mainRepository)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding = ChooseCountryFragmentBinding.bind(view)
changeColorsToCustomIfPresent()
requireActivity().onBackPressedDispatcher.addCallback {
//Stub; no back press needed here
}
_viewModel.priorityCountriesResponse.observe(viewLifecycleOwner) {
(requireActivity() as AppCompatActivity)
.checkUserInteractionCompletedForResult(it.data?.errorCode)
if (it.data != null) {
setContent(it.data.data ?: emptyList())
}
}
_viewModel.getPriorityCountries()
}
private fun setContent(priorityCountries: List<String>) {
val initialCountryList = args.countriesListTO.countriesList
val providerCountries = initialCountryList.sortedWith { s1, s2 ->
Collator.getInstance(Locale("")).compare(s1.name, s2.name)
}.toList()
val bottomCountries = emptyList<CountryTO>().toMutableList()
val topCountryItems = emptyList<CountryTO>().toMutableList()
providerCountries.forEach { countryTO ->
if (priorityCountries.contains(countryTO.code)) {
topCountryItems += countryTO
} else {
bottomCountries += countryTO
}
}
topCountryItems.addAll(bottomCountries)
finalCountries = ArrayList(topCountryItems)
reloadData()
binding.chooseCountryCard.setOnClickListener {
val action =
ChooseCountryFragmentDirections.actionChooseCountryFragmentToCountryListFragment(
CountriesListTO(finalCountries as ArrayList<CountryTO>))
findNavController().navigate(action)
}
binding.chooseCountryContinueButton.setOnClickListener {
chooseCountryOnProviderLogic()
}
}
private fun chooseCountryOnProviderLogic() {
when(VCheckSDK.getProviderLogicCase()) {
ProviderLogicCase.ONE_PROVIDER_MULTIPLE_COUNTRIES -> {
val action = ChooseCountryFragmentDirections
.actionChooseCountryFragmentToProviderChosenFragment()
findNavController().navigate(action)
}
ProviderLogicCase.MULTIPLE_PROVIDERS_PRESENT_COUNTRIES -> {
val countryCode = VCheckSDK.getOptSelectedCountryCode()!!
//TODO optimize inner loops
val distinctProvidersList = VCheckSDK.getAllAvailableProviders().filter {
it.countries!!.contains(countryCode) }
val action = ChooseCountryFragmentDirections
.actionChooseCountryFragmentToChooseProviderFragment(
ChooseProviderLogicTO(distinctProvidersList))
findNavController().navigate(action)
}
else -> {
Toast.makeText(requireContext(), "Error: country options should not be available for that provider",
Toast.LENGTH_LONG).show()
}
}
}
private fun reloadData() {
val selectedCountryCode : String = if (VCheckSDK.getOptSelectedCountryCode() != null) {
finalCountries.first { it.code == VCheckSDK.getOptSelectedCountryCode() }.code
} else if (finalCountries.map { it.code }.contains("ua")) {
"ua"
} else {
finalCountries.first().code
}
VCheckSDK.setOptSelectedCountryCode(selectedCountryCode)
when (selectedCountryCode) {
"us" -> {
val locale = Locale("", selectedCountryCode)
val flag = locale.country.toFlagEmoji()
binding.countryTitle.text = getString(R.string.united_states_of_america)
binding.flagEmoji.text = flag
}
"bm" -> {
val locale = Locale("", selectedCountryCode)
val flag = locale.country.toFlagEmoji()
binding.countryTitle.text = getString(R.string.bermuda)
binding.flagEmoji.text = flag
}
"tl" -> {
val locale = Locale("", selectedCountryCode)
val flag = locale.country.toFlagEmoji()
binding.countryTitle.text = getString(R.string.east_timor)
binding.flagEmoji.text = flag
}
else -> {
val locale = Locale("", selectedCountryCode)
val flag = locale.country.toFlagEmoji()
binding.countryTitle.text = locale.displayCountry.replace("&", "and")
binding.flagEmoji.text = flag
}
}
}
} | 0 | Kotlin | 0 | 0 | 2b31db28c9b226570a681c048331866cb03ce2ba | 7,814 | vcheck_android | MIT License |
app/src/main/java/org/jmrtd/cert/CSCAMasterList.kt | jllarraz | 151,435,529 | false | null | package org.jmrtd.cert
import org.spongycastle.asn1.*
import org.spongycastle.asn1.pkcs.SignedData
import org.spongycastle.jce.provider.X509CertificateObject
import java.io.ByteArrayInputStream
import java.io.IOException
import java.security.cert.CertSelector
import java.security.cert.Certificate
import java.security.cert.X509CertSelector
import java.security.cert.X509Certificate
import java.util.*
class CSCAMasterList private constructor() {
private val certificates: MutableList<Certificate>
/**
* Constructs a master lsit from a collection of certificates.
*
* @param certificates a collection of certificates
*/
constructor(certificates: Collection<Certificate>?) : this() {
this.certificates.addAll(certificates!!)
}
@JvmOverloads
constructor(binary: ByteArray, selector: CertSelector = IDENTITY_SELECTOR) : this() {
certificates.addAll(searchCertificates(binary, selector))
}
fun getCertificates(): List<Certificate> {
return certificates
}
companion object {
/** Use this to get all certificates, including link certificates. */
private val IDENTITY_SELECTOR: CertSelector = object : X509CertSelector() {
override fun match(cert: Certificate): Boolean {
return if (cert !is X509Certificate) {
false
} else true
}
override fun clone(): Any {
return this
}
}
/** Use this to get self-signed certificates only. (Excludes link certificates.) */
private val SELF_SIGNED_SELECTOR: CertSelector = object : X509CertSelector() {
override fun match(cert: Certificate): Boolean {
if (cert !is X509Certificate) {
return false
}
val x509Cert = cert
val issuer = x509Cert.issuerX500Principal
val subject = x509Cert.subjectX500Principal
return issuer == null && subject == null || subject == issuer
}
override fun clone(): Any {
return this
}
}
/* PRIVATE METHODS BELOW */
private fun searchCertificates(binary: ByteArray, selector: CertSelector): List<Certificate> {
val result: MutableList<Certificate> = ArrayList()
try {
val sequence = ASN1Sequence.getInstance(binary) as ASN1Sequence
val signedDataList: List<SignedData>? = getSignedDataFromDERObject(sequence, null)
for (signedData in signedDataList!!) {
// ASN1Set certificatesASN1Set = signedData.getCertificates();
// Enumeration certificatesEnum = certificatesASN1Set.getObjects();
// while (certificatesEnum.hasMoreElements()) {
// Object certificateObject = certificatesEnum.nextElement();
// // TODO: interpret certificateObject, and check signature
// }
val contentInfo = signedData.contentInfo
val content: Any = contentInfo.content
val certificates: Collection<Certificate>? = getCertificatesFromDERObject(content, null)
for (certificate in certificates!!) {
if (selector.match(certificate)) {
result.add(certificate)
}
}
}
} catch (e: Exception) {
e.printStackTrace()
}
return result
}
private fun getSignedDataFromDERObject(o: Any, result: MutableList<SignedData>?): MutableList<SignedData>? {
var result = result
if (result == null) {
result = ArrayList()
}
try {
val signedData = SignedData.getInstance(o)
if (signedData != null) {
result.add(signedData)
}
return result
} catch (e: Exception) {
}
if (o is DERTaggedObject) {
val childObject = o.getObject()
return getSignedDataFromDERObject(childObject, result)
} else if (o is ASN1Sequence) {
val derObjects = o.objects
while (derObjects.hasMoreElements()) {
val nextObject = derObjects.nextElement()
result = getSignedDataFromDERObject(nextObject, result)
}
return result
} else if (o is ASN1Set) {
val derObjects = o.objects
while (derObjects.hasMoreElements()) {
val nextObject = derObjects.nextElement()
result = getSignedDataFromDERObject(nextObject, result)
}
return result
} else if (o is DEROctetString) {
val octets = o.octets
val derInputStream = ASN1InputStream(ByteArrayInputStream(octets))
try {
while (true) {
val derObject = derInputStream.readObject() ?: break
result = getSignedDataFromDERObject(derObject, result)
}
derInputStream.close()
} catch (ioe: IOException) {
ioe.printStackTrace()
}
return result
}
return result
}
private fun getCertificatesFromDERObject(o: Any, certificates: MutableCollection<Certificate>?): MutableCollection<Certificate>? {
var certificates = certificates
if (certificates == null) {
certificates = ArrayList()
}
try {
val certAsASN1Object = org.spongycastle.asn1.x509.Certificate.getInstance(o)
certificates.add(X509CertificateObject(certAsASN1Object)) // NOTE: >= BC 1.48
// certificates.add(new X509CertificateObject(X509CertificateStructure.getInstance(certAsASN1Object))); // NOTE: <= BC 1.47
return certificates
} catch (e: Exception) {
}
if (o is DERTaggedObject) {
val childObject = o.getObject()
return getCertificatesFromDERObject(childObject, certificates)
} else if (o is ASN1Sequence) {
val derObjects = o.objects
while (derObjects.hasMoreElements()) {
val nextObject = derObjects.nextElement()
certificates = getCertificatesFromDERObject(nextObject, certificates)
}
return certificates
} else if (o is ASN1Set) {
val derObjects = o.objects
while (derObjects.hasMoreElements()) {
val nextObject = derObjects.nextElement()
certificates = getCertificatesFromDERObject(nextObject, certificates)
}
return certificates
} else if (o is DEROctetString) {
val octets = o.octets
val derInputStream = ASN1InputStream(ByteArrayInputStream(octets))
try {
while (true) {
val derObject = derInputStream.readObject() ?: break
certificates = getCertificatesFromDERObject(derObject, certificates)
}
} catch (ioe: IOException) {
ioe.printStackTrace()
}
return certificates
} else if (o is SignedData) {
// ASN1Set certificatesASN1Set = signedData.getCertificates();
// Enumeration certificatesEnum = certificatesASN1Set.getObjects();
// while (certificatesEnum.hasMoreElements()) {
// Object certificateObject = certificatesEnum.nextElement();
// // TODO: interpret certificateObject, and check signature
// }
val contentInfo = o.contentInfo
val content: Any = contentInfo.content
return getCertificatesFromDERObject(content, certificates)
}
return certificates
}
}
/** Private constructor, only used locally. */
init {
certificates = ArrayList(256)
}
} | 10 | null | 37 | 91 | 787d3d3206b4855163784ff4fc6d643bb3743830 | 8,641 | AndroidPassportReader | Apache License 2.0 |
testing/test-db/src/main/kotlin/net/corda/testing/internal/db/NoOpTestDatabaseContext.kt | corda | 70,137,417 | false | {"Kotlin": 10675960, "Java": 275115, "C++": 239894, "Python": 37811, "Shell": 28324, "CSS": 23544, "Groovy": 14725, "CMake": 5393, "Dockerfile": 2574, "Batchfile": 1777, "PowerShell": 660, "C": 454} | package net.corda.testing.internal.db
/**
* An implementation of [TestDatabaseContext] which does nothing.
*/
class NoOpTestDatabaseContext : TestDatabaseContext {
override fun initialize(groupName: String) {}
override fun beforeClass(setupSql: List<String>) {}
override fun afterClass(teardownSql: List<String>) {}
override fun beforeTest(setupSql: List<String>) {}
override fun afterTest(teardownSql: List<String>) {}
override fun close() {}
} | 62 | Kotlin | 1077 | 3,989 | d27aa0e6850d3804d0982024054376d452e7073a | 478 | corda | Apache License 2.0 |
kool-core/src/commonMain/kotlin/de/fabmax/kool/scene/geometry/MeshBuilder.kt | kool-engine | 81,503,047 | false | null | package de.fabmax.kool.scene.geometry
import de.fabmax.kool.KoolException
import de.fabmax.kool.math.*
import de.fabmax.kool.modules.ui2.MsdfUiShader
import de.fabmax.kool.pipeline.Attribute
import de.fabmax.kool.util.*
import kotlin.math.*
/**
* @author fabmax
*/
open class MeshBuilder(val geometry: IndexedVertexList) {
val transform = Mat4fStack()
var isInvertFaceOrientation = false
var color = Color.GRAY
var emissiveColor = Color.BLACK
var metallic = 0f
var roughness = 0.5f
var vertexModFun: (VertexView.() -> Unit)? = null
val hasNormals = geometry.hasAttribute(Attribute.NORMALS)
inline fun vertex(block: VertexView.() -> Unit): Int {
return geometry.addVertex {
color.set([email protected])
setEmissiveColor([email protected])
setMetallic([email protected])
setRoughness([email protected])
block()
transform.transform(position)
if (hasNormals && normal.sqrLength() != 0f) {
transform.transform(normal, 0f)
normal.norm()
}
vertexModFun?.invoke(this)
}
}
open fun vertex(pos: Vec3f, nrm: Vec3f, uv: Vec2f = Vec2f.ZERO) = vertex {
position.set(pos)
normal.set(nrm)
texCoord.set(uv)
}
fun addTriIndices(i0: Int, i1: Int, i2: Int) {
if (isInvertFaceOrientation) {
geometry.addTriIndices(i2, i1, i0)
} else {
geometry.addTriIndices(i0, i1, i2)
}
}
inline fun withTransform(block: MeshBuilder.() -> Unit) {
transform.push()
this.block()
transform.pop()
}
inline fun withColor(color: Color, block: MeshBuilder.() -> Unit) {
val c = this.color
this.color = color
this.block()
this.color = c
}
inline fun withEmissiveColor(emissiveColor: Color, block: MeshBuilder.() -> Unit) {
val c = this.emissiveColor
this.emissiveColor = emissiveColor
this.block()
this.emissiveColor = c
}
inline fun withMetallicRoughness(metallic: Float, roughness: Float, block: MeshBuilder.() -> Unit) {
val m = this.metallic
val r = this.roughness
this.metallic = metallic
this.roughness = roughness
this.block()
this.metallic = m
this.roughness = r
}
fun clear() {
geometry.clear()
identity()
}
fun identity() = transform.setIdentity()
fun translate(t: Vec3f) = transform.translate(t.x, t.y, t.z)
fun translate(x: Float, y: Float, z: Float) = transform.translate(x, y, z)
fun rotate(angleDeg: Float, axis: Vec3f) = transform.rotate(angleDeg, axis)
fun rotate(angleDeg: Float, axX: Float, axY: Float, axZ: Float) = transform.rotate(angleDeg, axX, axY, axZ)
fun rotate(eulerX: Float, eulerY: Float, eulerZ: Float) = transform.rotate(eulerX, eulerY, eulerZ)
fun scale(s: Float) = transform.scale(s, s, s)
fun scale(x: Float, y: Float, z: Float) = transform.scale(x, y, z)
fun setCoordSystem(origin: Vec3f, right: Vec3f, up: Vec3f, top: Vec3f? = null) {
var topV = top
if (topV == null) {
topV = right.cross(up, MutableVec3f())
}
transform.setIdentity()
transform[0, 0] = right.x
transform[1, 0] = right.y
transform[2, 0] = right.z
transform[0, 1] = up.x
transform[1, 1] = up.y
transform[2, 1] = up.z
transform[0, 2] = topV.x
transform[1, 2] = topV.y
transform[2, 2] = topV.z
transform[0, 3] = origin.x
transform[1, 3] = origin.y
transform[2, 3] = origin.z
}
inline fun profile(block: Profile.() -> Unit): Profile {
val profile = Profile()
profile.block()
return profile
}
fun ShapeContainer.circleShape(radius: Float = 1f, steps: Int = 40): SimpleShape {
return simpleShape(true) {
for (a in 0 until steps) {
val rad = 2f * PI.toFloat() * a / steps
xy(cos(rad) * radius, sin(rad) * radius)
}
}
}
fun Profile.sample(connect: Boolean = true, inverseOrientation: Boolean = false) {
sample(this@MeshBuilder, connect, inverseOrientation)
}
fun Profile.sampleAndFillBottom(connect: Boolean = false, inverseOrientation: Boolean = false) {
sample(this@MeshBuilder, connect, inverseOrientation)
fillBottom(this@MeshBuilder)
}
fun Profile.fillBottom() {
fillBottom(this@MeshBuilder)
}
fun Profile.sampleAndFillTop(connect: Boolean = false, inverseOrientation: Boolean = false) {
sample(this@MeshBuilder, connect, inverseOrientation)
fillTop(this@MeshBuilder)
}
fun Profile.fillTop() {
fillTop(this@MeshBuilder)
}
inline fun circle(block: CircleProps.() -> Unit) {
val props = CircleProps()
props.block()
circle(props)
}
fun fillPolygon(poly: PolyUtil.TriangulatedPolygon) {
val meshIndices = IntArray(poly.vertices.size)
poly.vertices.forEachIndexed { i, v ->
meshIndices[i] = vertex {
set(v)
normal.set(poly.normal)
}
}
for (i in poly.indices.indices step 3) {
addTriIndices(meshIndices[poly.indices[i]], meshIndices[poly.indices[i + 1]], meshIndices[poly.indices[i + 2]])
}
}
fun fillPolygon(points: List<Vec3f>, normal: Vec3f? = null) {
val indices = points.map { pt ->
vertex {
position.set(pt)
color.set([email protected])
normal?.let { this.normal.set(it) }
}
}
fillPolygon(indices)
}
fun fillPolygon(indices: List<Int>) {
val points = indices.map { Vec3f(geometry.vertexIt.apply { index = it }.position) }
val poly = PolyUtil.fillPolygon(points)
for (i in 0 until poly.numTriangles) {
val i0 = indices[poly.indices[i * 3]]
val i1 = indices[poly.indices[i * 3 + 1]]
val i2 = indices[poly.indices[i * 3 + 2]]
addTriIndices(i0, i1, i2)
}
}
fun circle(props: CircleProps) {
var i1 = 0
val iCenter = vertex(props.center, Vec3f.Z_AXIS, props.uvCenter)
for (i in 0..props.steps) {
val ang = (props.startDeg + props.sweepDeg * i / props.steps).toRad()
val cos = cos(ang)
val sin = sin(ang)
val px = props.center.x + props.radius * cos
val py = props.center.y + props.radius * sin
val idx = vertex {
position.set(px, py, props.center.z)
normal.set(Vec3f.Z_AXIS)
texCoord.set(cos, -sin).mul(props.uvRadius).add(props.uvCenter)
}
if (i > 0) {
addTriIndices(iCenter, i1, idx)
}
i1 = idx
}
}
inline fun uvSphere(block: SphereProps.() -> Unit) {
val props = SphereProps().uvDefaults()
props.block()
uvSphere(props)
}
fun uvSphere(props: SphereProps) {
val steps = max(props.steps / 2, 4)
var prevIndices = IntArray(steps * 2 + 1)
var rowIndices = IntArray(steps * 2 + 1)
// bottom cap
var theta = PI * (steps - 1) / steps
var r = sin(theta).toFloat() * props.radius
var y = cos(theta).toFloat() * props.radius
for (i in 0..(steps * 2)) {
val phi = PI * i / steps
val x = cos(-phi).toFloat() * r
val z = sin(-phi).toFloat() * r
rowIndices[i] = vertex {
position.set(x, y, z).add(props.center)
normal.set(x, y, z).mul(1f / props.radius)
texCoord.set(props.texCoordGenerator(theta.toFloat(), phi.toFloat()))
}
if (i > 0) {
val iCenter = vertex {
position.set(props.center.x, props.center.y-props.radius, props.center.z)
normal.set(Vec3f.NEG_Y_AXIS)
texCoord.set(props.texCoordGenerator(PI.toFloat(), phi.toFloat()))
}
addTriIndices(iCenter, rowIndices[i], rowIndices[i - 1])
}
}
// belt
for (row in 2..steps-1) {
val tmp = prevIndices
prevIndices = rowIndices
rowIndices = tmp
theta = PI * (steps - row) / steps
r = sin(theta).toFloat() * props.radius
y = cos(theta).toFloat() * props.radius
for (i in 0..(steps * 2)) {
val phi = PI * i / steps
val x = cos(-phi).toFloat() * r
val z = sin(-phi).toFloat() * r
rowIndices[i] = vertex {
position.set(x, y, z).add(props.center)
normal.set(x, y, z).mul(1f / props.radius)
texCoord.set(props.texCoordGenerator(theta.toFloat(), phi.toFloat()))
}
if (i > 0) {
addTriIndices(prevIndices[i - 1], rowIndices[i], rowIndices[i - 1])
addTriIndices(prevIndices[i - 1], prevIndices[i], rowIndices[i])
}
}
}
// top cap
for (i in 1..(steps * 2)) {
val iCenter = vertex {
position.set(props.center.x, props.center.y + props.radius, props.center.z)
normal.set(Vec3f.Y_AXIS)
texCoord.set(props.texCoordGenerator(0f, (PI * i / steps).toFloat()))
}
addTriIndices(iCenter, rowIndices[i - 1], rowIndices[i])
}
}
inline fun icoSphere(block: SphereProps.() -> Unit) {
val props = SphereProps().icoDefaults()
props.block()
icoSphere(props)
}
/*
* Based on https://schneide.blog/2016/07/15/generating-an-icosphere-in-c/
*/
class IcoGenerator {
val x = 0.525731112f
val z = 0.850650808f
val n = 0f
val verts = mutableListOf(
Vec3f(-x, n, z), Vec3f(x, n, z), Vec3f(-x, n, -z), Vec3f(x, n, -z),
Vec3f(n, z, x), Vec3f(n, z, -x), Vec3f(n, -z, x), Vec3f(n, -z, -x),
Vec3f(z, x, n), Vec3f(-z, x, n), Vec3f(z, -x, n), Vec3f(-z, -x, n)
)
var uvVerts = mutableListOf<Pair<Vec3f, Vec2f>>()
var faces = mutableListOf(
4,0,1, 9,0,4, 5,9,4, 5,4,8, 8,4,1,
10,8,1, 3,8,10, 3,5,8, 2,5,3, 7,2,3,
10,7,3, 6,7,10, 11,7,6, 0,11,6, 1,0,6,
1,6,10, 0,9,11, 11,9,2, 2,9,5, 2,7,11
)
fun subdivide(steps: Int) {
val its = if (steps <= 8) { steps } else {
logW { "clamping too large number of iterations for ico-sphere (${steps}) to 8" }
8
}
for (i in 0 until its) {
Subdivide.subdivideTris(verts, faces) { a, b -> MutableVec3f(a).add(b).norm() }
}
}
fun generateUvs() {
val pif = PI.toFloat()
val uvVerts = verts.map { v -> v to Vec2f((atan2(v.x, v.z) + pif) / (2 * pif), stableAcos(v.y) / pif) }.toMutableList()
this.uvVerts = uvVerts
// duplicate vertices at texture border
for (i in faces.indices step 3) {
// check if triangle stretches across texture border and duplicate vertex with adjusted uv if it does
for (j in 0..2) {
val i1 = i + j
val i2 = i + (j+1) % 3
val i3 = i + (j+2) % 3
val u1 = uvVerts[faces[i1]].second.x
val u2 = uvVerts[faces[i2]].second.x
val u3 = uvVerts[faces[i3]].second.x
if (u1 - u2 > 0.5f && u1 - u3 > 0.5f) {
val dv1 = Vec3f(uvVerts[faces[i1]].first)
val du1 = MutableVec2f(uvVerts[faces[i1]].second).apply { this.x -= 1f }
faces[i1] = uvVerts.size
uvVerts += dv1 to du1
} else if (u2 - u1 > 0.5f && u3 - u1 > 0.5f) {
val dv1 = Vec3f(uvVerts[faces[i1]].first)
val du1 = MutableVec2f(uvVerts[faces[i1]].second).apply { this.x += 1f }
faces[i1] = uvVerts.size
uvVerts += dv1 to du1
}
}
}
}
}
fun icoSphere(props: SphereProps) {
val icoGenerator = IcoGenerator()
icoGenerator.subdivide(props.steps)
icoGenerator.generateUvs()
// insert geometry
val pif = PI.toFloat()
val i0 = geometry.numVertices
for (v in icoGenerator.uvVerts) {
vertex {
normal.set(v.first).norm()
position.set(v.first).mul(props.radius).add(props.center)
texCoord.set(props.texCoordGenerator(v.second.y * pif, v.second.x * 2 * pif))
}
}
for (i in icoGenerator.faces.indices step 3) {
addTriIndices(i0 + icoGenerator.faces[i], i0 + icoGenerator.faces[1 + i], i0 + icoGenerator.faces[2 + i])
}
}
inline fun centeredRect(block: RectProps.() -> Unit) {
val props = RectProps()
props.block()
rect(props)
}
@Deprecated("Default behavior will change to centered origin", ReplaceWith("centeredRect { block() }"))
inline fun rect(block: RectProps.() -> Unit) {
val props = RectProps()
props.isCenteredOrigin = false
props.block()
rect(props)
}
fun rect(props: RectProps) {
props.fixNegativeSize()
val hx = props.size.x * 0.5f
val hy = props.size.y * 0.5f
if (!props.isCenteredOrigin) {
transform.push()
translate(hx, hy, 0f)
}
if (props.cornerRadius == 0f) {
val i0 = vertex {
position.set(props.origin.x - hx, props.origin.y - hy, props.origin.z)
normal.set(Vec3f.Z_AXIS)
texCoord.set(props.texCoordLowerLeft)
}
val i1 = vertex {
position.set(props.origin.x + hx, props.origin.y - hy, props.origin.z)
normal.set(Vec3f.Z_AXIS)
texCoord.set(props.texCoordLowerRight)
}
val i2 = vertex {
position.set(props.origin.x + hx, props.origin.y + hy, props.origin.z)
normal.set(Vec3f.Z_AXIS)
texCoord.set(props.texCoordUpperRight)
}
val i3 = vertex {
position.set(props.origin.x - hx, props.origin.y + hy, props.origin.z)
normal.set(Vec3f.Z_AXIS)
texCoord.set(props.texCoordUpperLeft)
}
addTriIndices(i0, i1, i2)
addTriIndices(i0, i2, i3)
} else {
val x = props.origin.x - hx
val y = props.origin.y - hy
val z = props.origin.z
val w = props.size.x
val h = props.size.y
val xI = x + props.cornerRadius
val yI = y + props.cornerRadius
val wI = w - props.cornerRadius * 2
val hI = h - props.cornerRadius * 2
val nrm = Vec3f.Z_AXIS
// compute tex coord insets, this only works for axis aligned tex coords...
val uI = (props.texCoordUpperRight.x - props.texCoordUpperLeft.x) * props.cornerRadius / w
val vI = (props.texCoordUpperRight.y - props.texCoordLowerRight.y) * props.cornerRadius / h
val tmpPos = MutableVec3f()
val tmpUv = MutableVec2f()
if (hI > 0) {
val i0 = vertex(tmpPos.set(x, yI, z), nrm, tmpUv.set(0f, vI).add(props.texCoordLowerLeft))
val i1 = vertex(tmpPos.set(x + w, yI, z), nrm, tmpUv.set(0f, vI).add(props.texCoordLowerRight))
val i2 = vertex(tmpPos.set(x + w, yI + hI, z), nrm, tmpUv.set(0f, -vI).add(props.texCoordUpperRight))
val i3 = vertex(tmpPos.set(x, yI + hI, z), nrm, tmpUv.set(0f, -vI).add(props.texCoordUpperLeft))
addTriIndices(i0, i1, i2)
addTriIndices(i0, i2, i3)
}
if (wI > 0) {
var i0 = vertex(tmpPos.set(xI, y, z), nrm, tmpUv.set(uI, 0f).add(props.texCoordLowerLeft))
var i1 = vertex(tmpPos.set(xI + wI, y, z), nrm, tmpUv.set(-uI, 0f).add(props.texCoordLowerRight))
var i2 = vertex(tmpPos.set(xI + wI, yI, z), nrm, tmpUv.set(-uI, vI).add(props.texCoordLowerRight))
var i3 = vertex(tmpPos.set(xI, yI, z), nrm, tmpUv.set(uI, vI).add(props.texCoordLowerLeft))
addTriIndices(i0, i1, i2)
addTriIndices(i0, i2, i3)
i0 = vertex(tmpPos.set(xI, yI + hI, z), nrm, tmpUv.set(uI, -vI).add(props.texCoordUpperLeft))
i1 = vertex(tmpPos.set(xI + wI, yI + hI, z), nrm, tmpUv.set(-uI, -vI).add(props.texCoordUpperRight))
i2 = vertex(tmpPos.set(xI + wI, y + h, z), nrm, tmpUv.set(-uI, 0f).add(props.texCoordUpperRight))
i3 = vertex(tmpPos.set(xI, y + h, z), nrm, tmpUv.set(uI, 0f).add(props.texCoordUpperLeft))
addTriIndices(i0, i1, i2)
addTriIndices(i0, i2, i3)
}
circle {
center.set(xI + wI, yI + hI, z)
startDeg = 0f
sweepDeg = 90f
radius = props.cornerRadius
steps = props.cornerSteps
uvCenter.set(-uI, -vI).add(props.texCoordUpperRight)
uvRadius = uI
}
circle {
center.set(xI, yI + hI, z)
startDeg = 90f
sweepDeg = 90f
radius = props.cornerRadius
steps = props.cornerSteps
uvCenter.set(uI, -vI).add(props.texCoordUpperLeft)
uvRadius = uI
}
circle {
center.set(xI, yI, z)
startDeg = 180f
sweepDeg = 90f
radius = props.cornerRadius
steps = props.cornerSteps
uvCenter.set(uI, vI).add(props.texCoordLowerLeft)
uvRadius = uI
}
circle {
center.set(xI + wI, yI, z)
startDeg = 270f
sweepDeg = 90f
radius = props.cornerRadius
steps = props.cornerSteps
uvCenter.set(-uI, vI).add(props.texCoordLowerRight)
uvRadius = uI
}
}
if (!props.isCenteredOrigin) {
transform.pop()
}
}
fun line(pt1: Vec2f, pt2: Vec2f, width: Float) {
line(pt1.x, pt1.y, pt2.x, pt2.y, width)
}
fun line(x1: Float, y1: Float, x2: Float, y2: Float, width: Float) {
var dx = x2 - x1
var dy = y2 - y1
var len = sqrt((dx * dx + dy * dy).toDouble()).toFloat()
val addX = width * 0.25f * dx / len
val addY = width * 0.25f * dy / len
dx += addX + addX
dy += addY + addY
len += width * 0.5f
val dxu = dx / len * width / 2
val dyu = dy / len * width / 2
val qx0 = x1 - addX + dyu
val qy0 = y1 - addY - dxu
val qx1 = x2 + addX + dyu
val qy1 = y2 + addY - dxu
val qx2 = x2 + addX - dyu
val qy2 = y2 + addY + dxu
val qx3 = x1 - addX - dyu
val qy3 = y1 - addY + dxu
val i0 = vertex { position.set(qx0, qy0, 0f); normal.set(Vec3f.Z_AXIS) }
val i1 = vertex { position.set(qx1, qy1, 0f); normal.set(Vec3f.Z_AXIS) }
val i2 = vertex { position.set(qx2, qy2, 0f); normal.set(Vec3f.Z_AXIS) }
val i3 = vertex { position.set(qx3, qy3, 0f); normal.set(Vec3f.Z_AXIS) }
addTriIndices(i0, i1, i2)
addTriIndices(i0, i2, i3)
}
fun lineArc(centerX: Float, centerY: Float, radius: Float, startDeg: Float, sweepDeg: Float, width: Float, resolution: Float = 3f) {
val steps = max(1, round(abs(sweepDeg) / resolution).toInt())
val step = sweepDeg / steps
val startRad = startDeg.toRad()
val stepRad = step.toRad()
for (i in 0 until steps) {
val a0 = startRad + stepRad * i
val a1 = a0 + stepRad
val x0 = centerX + cos(a0) * radius
val y0 = centerY + sin(a0) * radius
val x1 = centerX + cos(a1) * radius
val y1 = centerY + sin(a1) * radius
line(x0, y0, x1, y1, width)
}
}
fun line3d(p1: Vec3f, p2: Vec3f, normal: Vec3f, width: Float) {
val d = p2.subtract(p1, MutableVec3f()).norm()
val o = d.cross(normal, MutableVec3f()).norm().mul(width * 0.5f)
val i0 = vertex { position.set(p1).add(o); this.normal.set(normal) }
val i1 = vertex { position.set(p1).subtract(o); this.normal.set(normal) }
val i2 = vertex { position.set(p2).subtract(o); this.normal.set(normal) }
val i3 = vertex { position.set(p2).add(o); this.normal.set(normal) }
addTriIndices(i0, i1, i2)
addTriIndices(i0, i2, i3)
}
inline fun cube(centered: Boolean = true, block: CubeProps.() -> Unit) {
val props = CubeProps()
props.block()
if (!centered) {
logE { "non-centered cube origin is not supported anymore" }
}
cube(props)
}
fun cube(props: CubeProps) {
val tmpPos = MutableVec3f()
val oX = props.origin.x
val oY = props.origin.y
val oZ = props.origin.z
val eX = props.size.x * 0.5f
val eY = props.size.y * 0.5f
val eZ = props.size.z * 0.5f
// front
withColor(props.colors.getOrElse(CubeProps.FACE_FRONT) { color }) {
val uv = props.uvs.getOrElse(CubeProps.FACE_FRONT) { RectUvs.ZERO }
val i0 = vertex(tmpPos.set(oX - eX, oY - eY, oZ + eZ), Vec3f.Z_AXIS, uv.lowLt)
val i1 = vertex(tmpPos.set(oX + eX, oY - eY, oZ + eZ), Vec3f.Z_AXIS, uv.lowRt)
val i2 = vertex(tmpPos.set(oX + eX, oY + eY, oZ + eZ), Vec3f.Z_AXIS, uv.upRt)
val i3 = vertex(tmpPos.set(oX - eX, oY + eY, oZ + eZ), Vec3f.Z_AXIS, uv.upLt)
addTriIndices(i0, i1, i2)
addTriIndices(i0, i2, i3)
}
// right
withColor(props.colors.getOrElse(CubeProps.FACE_RIGHT) { color }) {
val uv = props.uvs.getOrElse(CubeProps.FACE_RIGHT) { RectUvs.ZERO }
val i0 = vertex(tmpPos.set(oX + eX, oY - eY, oZ - eZ), Vec3f.X_AXIS, uv.lowLt)
val i1 = vertex(tmpPos.set(oX + eX, oY + eY, oZ - eZ), Vec3f.X_AXIS, uv.lowRt)
val i2 = vertex(tmpPos.set(oX + eX, oY + eY, oZ + eZ), Vec3f.X_AXIS, uv.upRt)
val i3 = vertex(tmpPos.set(oX + eX, oY - eY, oZ + eZ), Vec3f.X_AXIS, uv.upLt)
addTriIndices(i0, i1, i2)
addTriIndices(i0, i2, i3)
}
// back
withColor(props.colors.getOrElse(CubeProps.FACE_BACK) { color }) {
val uv = props.uvs.getOrElse(CubeProps.FACE_BACK) { RectUvs.ZERO }
val i0 = vertex(tmpPos.set(oX - eX, oY + eY, oZ - eZ), Vec3f.NEG_Z_AXIS, uv.lowLt)
val i1 = vertex(tmpPos.set(oX + eX, oY + eY, oZ - eZ), Vec3f.NEG_Z_AXIS, uv.lowRt)
val i2 = vertex(tmpPos.set(oX + eX, oY - eY, oZ - eZ), Vec3f.NEG_Z_AXIS, uv.upRt)
val i3 = vertex(tmpPos.set(oX - eX, oY - eY, oZ - eZ), Vec3f.NEG_Z_AXIS, uv.upLt)
addTriIndices(i0, i1, i2)
addTriIndices(i0, i2, i3)
}
// left
withColor(props.colors.getOrElse(CubeProps.FACE_LEFT) { color }) {
val uv = props.uvs.getOrElse(CubeProps.FACE_LEFT) { RectUvs.ZERO }
val i0 = vertex(tmpPos.set(oX - eX, oY - eY, oZ + eZ), Vec3f.NEG_X_AXIS, uv.lowLt)
val i1 = vertex(tmpPos.set(oX - eX, oY + eY, oZ + eZ), Vec3f.NEG_X_AXIS, uv.lowRt)
val i2 = vertex(tmpPos.set(oX - eX, oY + eY, oZ - eZ), Vec3f.NEG_X_AXIS, uv.upRt)
val i3 = vertex(tmpPos.set(oX - eX, oY - eY, oZ - eZ), Vec3f.NEG_X_AXIS, uv.upLt)
addTriIndices(i0, i1, i2)
addTriIndices(i0, i2, i3)
}
// top
withColor(props.colors.getOrElse(CubeProps.FACE_TOP) { color }) {
val uv = props.uvs.getOrElse(CubeProps.FACE_TOP) { RectUvs.ZERO }
val i0 = vertex(tmpPos.set(oX - eX, oY + eY, oZ + eZ), Vec3f.Y_AXIS, uv.lowLt)
val i1 = vertex(tmpPos.set(oX + eX, oY + eY, oZ + eZ), Vec3f.Y_AXIS, uv.lowRt)
val i2 = vertex(tmpPos.set(oX + eX, oY + eY, oZ - eZ), Vec3f.Y_AXIS, uv.upRt)
val i3 = vertex(tmpPos.set(oX - eX, oY + eY, oZ - eZ), Vec3f.Y_AXIS, uv.upLt)
addTriIndices(i0, i1, i2)
addTriIndices(i0, i2, i3)
}
// bottom
withColor(props.colors.getOrElse(CubeProps.FACE_BOTTOM) { color }) {
val uv = props.uvs.getOrElse(CubeProps.FACE_BOTTOM) { RectUvs.ZERO }
val i0 = vertex(tmpPos.set(oX - eX, oY - eY, oZ - eZ), Vec3f.NEG_Y_AXIS, uv.lowLt)
val i1 = vertex(tmpPos.set(oX + eX, oY - eY, oZ - eZ), Vec3f.NEG_Y_AXIS, uv.lowRt)
val i2 = vertex(tmpPos.set(oX + eX, oY - eY, oZ + eZ), Vec3f.NEG_Y_AXIS, uv.upRt)
val i3 = vertex(tmpPos.set(oX - eX, oY - eY, oZ + eZ), Vec3f.NEG_Y_AXIS, uv.upLt)
addTriIndices(i0, i1, i2)
addTriIndices(i0, i2, i3)
}
}
inline fun cylinder(block: CylinderProps.() -> Unit) {
val props = CylinderProps()
props.block()
cylinder(props)
}
fun cylinder(props: CylinderProps) = withTransform {
val tmpNrm = MutableVec3f()
translate(props.origin)
val yb = props.height * -0.5f
val yt = props.height * 0.5f
// bottom
if (props.bottomFill) {
withTransform {
translate(0f, yb, 0f)
rotate(90f, Vec3f.X_AXIS)
circle {
steps = props.steps
radius = props.bottomRadius
}
}
}
// top
if (props.topFill) {
withTransform {
translate(0f, yt, 0f)
rotate(-90f, Vec3f.X_AXIS)
circle {
steps = props.steps
radius = props.topRadius
}
}
}
val dr = props.bottomRadius - props.topRadius
val nrmAng = 90f - stableAcos(dr / sqrt(dr * dr + props.height * props.height)).toDeg()
var i0 = 0
var i1 = 0
for (i in 0..props.steps) {
val c = cos(i * PI * 2 / props.steps).toFloat()
val s = sin(i * PI * 2 / props.steps).toFloat()
val px2 = props.bottomRadius * c
val pz2 = props.bottomRadius * s
val px3 = props.topRadius * c
val pz3 = props.topRadius * s
tmpNrm.set(c, 0f, s).rotate(nrmAng.deg, Vec3f(s, 0f, c))
val i2 = vertex {
position.set(px2, yb, pz2)
normal.set(tmpNrm)
}
val i3 = vertex {
position.set(px3, yt, pz3)
normal.set(tmpNrm)
}
if (i > 0) {
addTriIndices(i0, i1, i2)
addTriIndices(i1, i3, i2)
}
i0 = i2
i1 = i3
}
}
inline fun grid(block: GridProps.() -> Unit) {
val props = GridProps()
props.block()
grid(props)
}
fun grid(props: GridProps) {
val gridNormal = MutableVec3f()
val bx = -props.sizeX / 2
val by = -props.sizeY / 2
val sx = props.sizeX / props.stepsX
val sy = props.sizeY / props.stepsY
val nx = props.stepsX + 1
props.xDir.cross(props.yDir, gridNormal).norm()
for (y in 0 .. props.stepsY) {
for (x in 0 .. props.stepsX) {
val px = bx + x * sx
val py = by + y * sy
val h = props.heightFun(x, y)
val idx = vertex {
position.set(props.center)
position.x += props.xDir.x * px + props.yDir.x * py + gridNormal.x * h
position.y += props.xDir.y * px + props.yDir.y * py + gridNormal.y * h
position.z += props.xDir.z * px + props.yDir.z * py + gridNormal.z * h
texCoord.set(x / props.stepsX.toFloat() * props.texCoordScale.x + props.texCoordOffset.x,
(1f - y / props.stepsY.toFloat()) * props.texCoordScale.y + props.texCoordOffset.y)
}
if (x > 0 && y > 0) {
if (x % 2 == y % 2) {
addTriIndices(idx - nx - 1, idx, idx - 1)
addTriIndices(idx - nx, idx, idx - nx - 1)
} else {
addTriIndices(idx - nx, idx, idx - 1)
addTriIndices(idx - nx, idx - 1, idx - nx - 1)
}
}
}
}
val iTri = geometry.numIndices - props.stepsX * props.stepsY * 6
val e1 = MutableVec3f()
val e2 = MutableVec3f()
val v1 = geometry[0]
val v2 = geometry[0]
val v3 = geometry[0]
for (i in iTri until geometry.numIndices step 3) {
v1.index = geometry.indices[i]
v2.index = geometry.indices[i+1]
v3.index = geometry.indices[i+2]
v2.position.subtract(v1.position, e1).norm()
v3.position.subtract(v1.position, e2).norm()
e1.cross(e2, gridNormal).norm()
v1.normal.add(gridNormal)
v2.normal.add(gridNormal)
v3.normal.add(gridNormal)
}
val iVert = geometry.numVertices - (props.stepsX + 1) * (props.stepsY + 1)
for (i in iVert until geometry.numVertices) {
v1.index = i
v1.normal.norm()
}
}
fun geometry(geometry: IndexedVertexList, keepVertexColor: Boolean = false) {
if (geometry.primitiveType == PrimitiveType.TRIANGLES) {
val i0 = this.geometry.numVertices
val beforeColor = color
geometry.forEach {
if (keepVertexColor) {
color = it.color
}
vertex(it.position, it.normal, it.texCoord)
}
for (i in 0 until geometry.numIndices) {
this.geometry.addIndex(i0 + geometry.indices[i])
}
color = beforeColor
} else {
throw KoolException("Only triangle geometry can be added")
}
}
inline fun text(font: Font, block: TextProps.() -> Unit) {
val props = TextProps(font)
props.block()
text(props)
}
fun text(props: TextProps) {
when (val font = props.font) {
is AtlasFont -> renderAtlasFont(font, props)
is MsdfFont -> renderMsdfFont(font, props)
}
}
private fun renderMsdfFont(font: MsdfFont, props: TextProps) {
withTransform {
if (props.roundOriginToUnits) {
translate(round(props.origin.x), round(props.origin.y), props.origin.z)
} else {
translate(props.origin)
}
val meta = font.data.meta
val s = props.scale * font.scale * font.sizePts
val us = 1f / meta.atlas.width
val vs = 1f / meta.atlas.height
val pxRange = (s / meta.atlas.size) * meta.atlas.distanceRange
var advanced = 0f
var prevC = 0
for (c in props.text) {
if (c == '\n') {
if (props.isYAxisUp) {
translate(0f, -round(font.lineHeight), 0f)
} else {
translate(0f, round(font.lineHeight), 0f)
}
advanced = 0f
}
val g = font.data.glyphMap[c] ?: continue
var adv = g.advance
if (c.isDigit() && props.enforceSameWidthDigits) {
val digitAdv = font.data.maxWidthDigit?.advance ?: adv
val delta = digitAdv - adv
adv += delta * 0.5f
advanced += delta * 0.5f
} else {
val kerningKey = (prevC shl 16) or c.code
font.data.kerning[kerningKey]?.let { advanced += it }
}
prevC = c.code
val yTop = if (props.isYAxisUp) g.planeBounds.top * s else -g.planeBounds.top * s
val yBot = if (props.isYAxisUp) g.planeBounds.bottom * s else -g.planeBounds.bottom * s
val h = yTop - yBot
val lt = (advanced + g.planeBounds.left) * s
// individual char positions are currently not rounded for MSDF fonts, as it's not really needed
// and can produce artefacts
// if (props.roundOriginToUnits) {
// lt = round(lt)
// yBot = round(yBot) + 0.5f
// }
val w = (g.planeBounds.right - g.planeBounds.left) * s
val msdfProps = geometry.vertexIt.getVec4fAttribute(MsdfUiShader.ATTRIB_MSDF_PROPS)
val glowColor = geometry.vertexIt.getVec4fAttribute(MsdfUiShader.ATTRIB_GLOW_COLOR)
val iBtLt = vertex {
set(lt, yBot, 0f)
texCoord.set(g.atlasBounds.left * us, 1f - g.atlasBounds.bottom * vs)
msdfProps?.set(pxRange, font.weight, font.cutoff, 0f)
glowColor?.let { font.glowColor?.toMutableVec4f(it) }
}
val iBtRt = vertex {
set(lt + w, yBot, 0f)
texCoord.set(g.atlasBounds.right * us, 1f - g.atlasBounds.bottom * vs)
msdfProps?.set(pxRange, font.weight, font.cutoff, 0f)
glowColor?.let { font.glowColor?.toMutableVec4f(it) }
}
val iTpLt = vertex {
set(lt - h * font.italic, yBot + h, 0f)
texCoord.set(g.atlasBounds.left * us, 1f - g.atlasBounds.top * vs)
msdfProps?.set(pxRange, font.weight, font.cutoff, 0f)
glowColor?.let { font.glowColor?.toMutableVec4f(it) }
}
val iTpRt = vertex {
set(lt + w - h * font.italic, yBot + h, 0f)
texCoord.set(g.atlasBounds.right * us, 1f - g.atlasBounds.top * vs)
msdfProps?.set(pxRange, font.weight, font.cutoff, 0f)
glowColor?.let { font.glowColor?.toMutableVec4f(it) }
}
addTriIndices(iBtLt, iBtRt, iTpRt)
addTriIndices(iBtLt, iTpRt, iTpLt)
advanced += adv
}
}
}
private fun renderAtlasFont(font: AtlasFont, props: TextProps) {
val charMap = font.map
if (charMap == null) {
logE { "Font char map has not yet been initialized" }
return
}
withTransform {
if (props.roundOriginToUnits) {
translate(round(props.origin.x), round(props.origin.y), props.origin.z)
} else {
translate(props.origin)
}
if (props.scale != 1f) {
scale(props.scale, props.scale, props.scale)
}
val ct = props.charTransform
var advanced = 0f
val rectProps = RectProps()
for (c in props.text) {
if (c == '\n') {
val lineHeight = font.lineHeight
if (props.isYAxisUp) {
translate(0f, -round(lineHeight), 0f)
} else {
translate(0f, round(lineHeight), 0f)
}
advanced = 0f
}
val metrics = charMap[c]
if (metrics != null) {
var adv = metrics.advance
if (c.isDigit() && props.enforceSameWidthDigits) {
val digitAdv = font.map?.maxWidthDigit?.advance ?: adv
val delta = digitAdv - adv
adv += delta * 0.5f
advanced += delta * 0.5f
}
var advOffset = 0f
if (ct == null) {
advOffset = advanced
} else {
ct(advanced)
}
rect(rectProps.apply {
val x = advOffset - metrics.xOffset
val y = if (props.isYAxisUp) metrics.yBaseline - metrics.height else -metrics.yBaseline
if (props.roundOriginToUnits) {
origin.set(round(x), round(y), 0f)
} else {
origin.set(x, y, 0f)
}
size.set(metrics.width, metrics.height)
if (props.isYAxisUp) {
texCoordUpperLeft.set(metrics.uvMin)
texCoordUpperRight.set(metrics.uvMax.x, metrics.uvMin.y)
texCoordLowerLeft.set(metrics.uvMin.x, metrics.uvMax.y)
texCoordLowerRight.set(metrics.uvMax)
} else {
texCoordLowerLeft.set(metrics.uvMin)
texCoordLowerRight.set(metrics.uvMax.x, metrics.uvMin.y)
texCoordUpperLeft.set(metrics.uvMin.x, metrics.uvMax.y)
texCoordUpperRight.set(metrics.uvMax)
}
})
advanced += adv
}
}
}
}
}
class CircleProps {
var radius = 1f
var steps = 20
val center = MutableVec3f()
var startDeg = 0f
var sweepDeg = 360f
val uvCenter = MutableVec2f()
var uvRadius = 0f
init {
fullTexCoords()
}
fun zeroTexCoords() {
uvCenter.set(Vec2f.ZERO)
uvRadius = 0f
}
fun fullTexCoords() {
uvCenter.set(0.5f, 0.5f)
uvRadius = 0.5f
}
}
class GridProps {
val center = MutableVec3f()
val xDir = MutableVec3f(Vec3f.X_AXIS)
val yDir = MutableVec3f(Vec3f.NEG_Z_AXIS)
val texCoordOffset = MutableVec2f(0f, 0f)
val texCoordScale = MutableVec2f(1f, 1f)
var sizeX = 10f
var sizeY = 10f
var stepsX = 10
var stepsY = 10
var heightFun: (Int, Int) -> Float = ZERO_HEIGHT
fun useHeightMap(heightMap: HeightMap) {
stepsX = heightMap.width - 1
stepsY = heightMap.height - 1
heightFun = { x, y -> heightMap.getHeight(x, y) }
}
companion object {
val ZERO_HEIGHT: (Int, Int) -> Float = { _, _ -> 0f }
}
}
class SphereProps {
var radius = 1f
var steps = 5
val center = MutableVec3f()
private val uv = MutableVec2f()
var texCoordGenerator: (Float, Float) -> Vec2f = { t, p -> defaultTexCoordGenerator(t, p) }
private fun defaultTexCoordGenerator(theta: Float, phi: Float): Vec2f {
return uv.set(phi / (PI.toFloat() * 2f), theta / PI.toFloat())
}
fun icoDefaults(): SphereProps {
radius = 1f
steps = 2
center.set(Vec3f.ZERO)
texCoordGenerator = { t, p -> defaultTexCoordGenerator(t, p) }
return this
}
fun uvDefaults(): SphereProps {
radius = 1f
steps = 20
center.set(Vec3f.ZERO)
texCoordGenerator = { t, p -> defaultTexCoordGenerator(t, p) }
return this
}
}
class RectProps {
var cornerRadius = 0f
var cornerSteps = 8
var isCenteredOrigin = true
val origin = MutableVec3f()
val size = MutableVec2f(1f, 1f)
var width: Float
get() = size.x
set(value) { size.x = value }
var height: Float
get() = size.y
set(value) { size.y = value }
val texCoordUpperLeft = MutableVec2f()
val texCoordUpperRight = MutableVec2f()
val texCoordLowerLeft = MutableVec2f()
val texCoordLowerRight = MutableVec2f()
init {
generateTexCoords(1f)
}
fun fixNegativeSize() {
if (size.x < 0) {
origin.x += size.x
size.x = -size.x
}
if (size.y < 0) {
origin.y += size.y
size.y = -size.y
}
}
fun zeroTexCoords() = generateTexCoords(0f)
fun generateTexCoords(scale: Float = 1f) {
texCoordUpperLeft.set(0f, 0f)
texCoordUpperRight.set(scale, 0f)
texCoordLowerLeft.set(0f, scale)
texCoordLowerRight.set(scale, scale)
}
fun mirrorTexCoordsX() {
texCoordUpperRight.x = texCoordUpperLeft.x.also {
texCoordUpperLeft.x = texCoordUpperRight.x
}
texCoordLowerRight.x = texCoordLowerLeft.x.also {
texCoordLowerLeft.x = texCoordLowerRight.x
}
}
fun mirrorTexCoordsY() {
texCoordLowerLeft.y = texCoordUpperLeft.y.also {
texCoordUpperLeft.y = texCoordLowerLeft.y
}
texCoordLowerRight.y = texCoordUpperRight.y.also {
texCoordUpperRight.y = texCoordLowerRight.y
}
}
}
class CubeProps {
val origin = MutableVec3f()
val size = MutableVec3f(1f, 1f, 1f)
var width: Float
get() = size.x
set(value) { size.x = value }
var height: Float
get() = size.y
set(value) { size.y = value }
var depth: Float
get() = size.z
set(value) { size.z = value }
var colors: List<Color> = emptyList()
var uvs: List<RectUvs> = fullFaceUvs
fun colored(linearSpace: Boolean = true) {
colors = if (linearSpace) defaultColorsLinear else defaultColorsSrgb
}
companion object {
const val FACE_TOP = 0
const val FACE_BOTTOM = 1
const val FACE_LEFT = 2
const val FACE_RIGHT = 3
const val FACE_FRONT = 4
const val FACE_BACK = 5
val defaultColorsSrgb = listOf(
MdColor.RED,
MdColor.AMBER,
MdColor.INDIGO,
MdColor.CYAN,
MdColor.PURPLE,
MdColor.GREEN
)
val defaultColorsLinear = listOf(
MdColor.RED.toLinear(),
MdColor.AMBER.toLinear(),
MdColor.INDIGO.toLinear(),
MdColor.CYAN.toLinear(),
MdColor.PURPLE.toLinear(),
MdColor.GREEN.toLinear()
)
val fullFaceUvs = listOf(
RectUvs(Vec2f(0f, 0f), Vec2f(1f, 0f), Vec2f(0f, 1f), Vec2f(1f, 1f)),
RectUvs(Vec2f(0f, 0f), Vec2f(1f, 0f), Vec2f(0f, 1f), Vec2f(1f, 1f)),
RectUvs(Vec2f(0f, 0f), Vec2f(1f, 0f), Vec2f(0f, 1f), Vec2f(1f, 1f)),
RectUvs(Vec2f(0f, 0f), Vec2f(1f, 0f), Vec2f(0f, 1f), Vec2f(1f, 1f)),
RectUvs(Vec2f(0f, 0f), Vec2f(1f, 0f), Vec2f(0f, 1f), Vec2f(1f, 1f)),
RectUvs(Vec2f(0f, 0f), Vec2f(1f, 0f), Vec2f(0f, 1f), Vec2f(1f, 1f))
)
}
}
class RectUvs(
val upLt: Vec2f,
val upRt: Vec2f,
val lowLt: Vec2f,
val lowRt: Vec2f
) {
companion object {
val ZERO = RectUvs(Vec2f.ZERO, Vec2f.ZERO, Vec2f.ZERO, Vec2f.ZERO)
}
}
class CylinderProps {
var bottomRadius = 1f
var topRadius = 1f
var steps = 20
var height = 1f
var topFill = true
var bottomFill = true
val origin = MutableVec3f()
var radius: Float
get() = (bottomRadius + topRadius) / 2f
set(value) {
bottomRadius = value
topRadius = value
}
}
class TextProps(var font: Font) {
var text = ""
val origin = MutableVec3f()
var scale = 1f
var roundOriginToUnits = true
var isYAxisUp = true
var enforceSameWidthDigits = true
var charTransform: (MeshBuilder.(Float) -> Unit)? = null
} | 9 | null | 20 | 303 | 8d05acd3e72ff2fc115d0939bf021a5f421469a5 | 44,518 | kool | Apache License 2.0 |
src/main/kotlin/y2023/day04/Day04.kt | TimWestmark | 571,510,211 | false | {"Kotlin": 89101, "Shell": 1067} | package y2023.day04
import kotlin.math.pow
fun main() {
AoCGenerics.printAndMeasureResults(
part1 = { part1() },
part2 = { part2() }
)
}
data class ScratchCard(
val winningNumber: Set<Int>,
val drawnNumbers: Set<Int>,
var copies: Int,
)
fun input() =
AoCGenerics.getInputLines("/y2023/day04/input.txt")
.map {
val winning = it.split(":")[1].split("|")[0]
val drawn = it.split(":")[1].split("|")[1]
ScratchCard(
copies = 1,
winningNumber = winning.trim().split(" ").filter { number -> number != "" }.map { number -> number.trim().toInt() }.toSet(),
drawnNumbers = drawn.trim().split(" ").filter { number -> number != "" }.map { number -> number.trim().toInt() }.toSet()
)
}
fun part1() =
input().sumOf { card ->
val matches = card.drawnNumbers.intersect(card.winningNumber)
when {
matches.isEmpty() -> 0.0
else -> 2.0.pow((matches.size - 1).toDouble())
}
}.toInt()
fun part2(): Int {
val cards = input()
cards.forEachIndexed { index, card ->
val matches = card.winningNumber.intersect(card.drawnNumbers).size
repeat(matches) {
if (index + 1 + it < cards.size) {
cards[index + 1 + it].copies += card.copies
}
}
}
return cards.sumOf { it.copies }
}
| 0 | Kotlin | 0 | 0 | 1f87833a58a410a3cec01474ae29f3c0b183f2a4 | 1,443 | AdventOfCode | MIT License |
app/src/main/java/com/music/player/bhandari/m/trackInfo/FetchTrackInfo.kt | amit-bhandari | 118,368,128 | false | null | package com.music.player.wakili.cool.trackInfo.models
import android.os.Handler
import android.os.Looper
import android.util.Log
import java.lang.Exception
/*
Thread to fetch track info
*/
class FetchTrackInfo(var artist: String, var track: String, val callback: TrackInfo.Callback) : Thread() {
var handler: Handler = Handler(Looper.getMainLooper())
private lateinit var trackInfoService: TrackInfoService
private var trackInfo = TrackInfo()
override fun run() {
try{
//perform all 3 network calls (if track info comes null, send out negative response otherwise positive no matter if we got similar tracks or not)
trackInfoService = RetrofitInstance.getTrackInfoService()
val track = trackInfoService.getTrackInfo(artist, track).execute()
Log.v("Track info", trackInfo.toString())
if(track.body()?.track==null) {
handler.post {
//guaranteed to be called on UI thread
trackInfo.result = RESULT.NEGATIVE
callback.onTrackInfoReady(trackInfo)
}
return
}
trackInfo.track = track.body()?.track!!
Thread.sleep(500) ///to do not hit api in rapid pace
val similarTracks = trackInfoService.getSimilarTracks(track.body()?.track?.mbid ?: "").execute()
if(similarTracks.body()?.similartracks!=null) {
trackInfo.similarTracks = similarTracks.body()?.similartracks!!
}
Thread.sleep(500)
val album = trackInfoService.getAlbumInfo(track.body()?.track?.album?.mbid ?: "").execute()
if(album.body()?.album!=null) {
trackInfo.album = album.body()?.album!!
}
//extract actual data that will be useful for UI
handler.post {
//guaranteed to be called on UI thread
callback.onTrackInfoReady(trackInfo)
}
Log.d("FetchTrackInfo", "Track Info : ${track.body()}")
Log.d("FetchTrackInfo", "Similar Tracks : ${similarTracks.body()}")
Log.d("FetchTrackInfo", "Track Album : ${album.body()}")
}catch (e: Exception) {
Log.v("Error" , "${e.localizedMessage}")
handler.post {
//guaranteed to be called on UI thread
trackInfo.result = RESULT.NEGATIVE
callback.onTrackInfoReady(trackInfo)
}
}
}
} | 9 | null | 44 | 83 | f82e1fcbf2ec550e93558a4e5761a91944a29050 | 2,523 | AB-Music-Player | Apache License 2.0 |
teacher/rest-client/src/main/kotlin/io/drevezadur/scylla/teacher/client/service/model/GridOrientation.kt | drevezerezh | 672,485,652 | false | null | /*
* Copyright (c) 2023. gofannon.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.gofannon.scylla.homework.lang
/**
* Orientation of a ship in the grid
*/
enum class GridOrientation {
ROW,
COLUMN
} | 0 | Kotlin | 0 | 0 | 5b252105940bee53350039c479aabcc479f3c894 | 738 | scylla | Apache License 2.0 |
cupertino-adaptive/src/nonAndroidMain/kotlin/io/github/alexzhirkevich/cupertino/adaptive/SystemTheme.kt | alexzhirkevich | 636,411,288 | false | {"Kotlin": 5215549, "Ruby": 2329, "Swift": 2101, "HTML": 2071, "Shell": 868} | /*
* Copyright (c) 2023 Compose Cupertino project and open source contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.alexzhirkevich.cupertino.adaptive
import androidx.compose.material3.ColorScheme
import androidx.compose.runtime.Composable
@Composable
internal actual fun systemMaterialColorScheme(dark : Boolean) : ColorScheme? {
val r :ColorScheme?= null // https://github.com/JetBrains/compose-multiplatform/issues/3900
return r
}
| 5 | Kotlin | 31 | 848 | 54bfbb58f6b36248c5947de343567903298ee308 | 989 | compose-cupertino | Apache License 2.0 |
nlp/core/shared/src/main/kotlin/EntityType.kt | theopenconversationkit | 84,538,053 | false | null | /*
* Copyright (C) 2017 VSCT
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package fr.vsct.tock.nlp.core
/**
* A type of entity.
*/
data class EntityType(
/**
* The qualified name of the entity (ie namespace:name)
*/
val name: String,
/**
* The sub entities of this entity if any.
*/
val subEntities: List<Entity> = emptyList(),
/**
* The entity predefined values if any.
*/
@Deprecated("will be removed in 20.03 - use DictionaryData")
val predefinedValues: List<PredefinedValue> = emptyList(),
/**
* Is the entity based on a dictionary (predefined set of data)?
*/
val dictionary: Boolean = predefinedValues.isNotEmpty()
) {
fun hasSubEntities(): Boolean = subEntities.isNotEmpty()
fun findSubEntity(role: String): Entity? = subEntities.first { it.role == role }
} | 163 | null | 127 | 475 | 890f69960997ae9146747d082d808d92ee407fcb | 1,370 | tock | Apache License 2.0 |
plugins/configuration-script/src/providers/ConfigurationScriptProjectStoreFactory.kt | JetBrains | 2,489,216 | false | null | package com.intellij.configurationScript.providers
import com.intellij.configurationScript.ConfigurationFileManager
import com.intellij.configurationScript.readIntoObject
import com.intellij.configurationStore.*
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.openapi.components.BaseState
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.StateStorage
import com.intellij.openapi.components.stateStore
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.project.Project
import com.intellij.util.ReflectionUtil
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicBoolean
private class ConfigurationScriptProjectStoreFactory : ProjectStoreFactoryBase() {
override fun createStore(project: Project) = MyProjectStore(project)
}
private class MyProjectStore(project: Project) : ProjectWithModuleStoreImpl(project) {
@JvmField
val isConfigurationFileListenerAdded: AtomicBoolean = AtomicBoolean()
private val storages = ConcurrentHashMap<Class<Any>, ReadOnlyStorage>()
fun configurationFileChanged() {
if (storages.isNotEmpty()) {
StoreReloadManager.getInstance(project).storageFilesChanged(store = project.stateStore, storages = storages.values.toList())
}
}
override fun unloadComponent(component: Any) {
super.unloadComponent(component)
if (component is PersistentStateComponent<*>) {
storages.remove(component.javaClass)
}
}
override fun getReadOnlyStorage(componentClass: Class<Any>, stateClass: Class<Any>, configurationSchemaKey: String): StateStorage {
// service container ensures that one key is never requested from different threads
return storages.computeIfAbsent(componentClass) {
ReadOnlyStorage(configurationSchemaKey = configurationSchemaKey, componentClass = componentClass, store = this)
}
}
override fun doCreateStateGetter(
reloadData: Boolean,
storage: StateStorage,
info: ComponentInfo,
componentName: String,
stateClass: Class<Any>,
useLoadedStateAsExisting: Boolean,
): StateGetter<Any> {
val stateGetter = super.doCreateStateGetter(
reloadData = reloadData,
storage = storage,
info = info,
componentName = componentName,
stateClass = stateClass,
useLoadedStateAsExisting = false,
)
val configurationSchemaKey = info.configurationSchemaKey ?: return stateGetter
val configurationFileManager = ConfigurationFileManager.getInstance(project)
val node = configurationFileManager.findValueNode(configurationSchemaKey) ?: return stateGetter
return object : StateGetter<Any> {
override fun getState(mergeInto: Any?): Any {
val state = stateGetter.getState(mergeInto) ?: ReflectionUtil.newInstance(stateClass, false)
val affectedProperties = mutableListOf<String>()
readIntoObject(instance = state as BaseState, nodes = node) { affectedProperties.add(it.name!!) }
info.affectedPropertyNames = affectedProperties
return state
}
override fun archiveState(): Any? {
// feature "preventing inappropriate state modification" is disabled for workspace components,
// also, this feature makes little sense for properly implemented PersistenceStateComponent using BaseState
return null
}
}
}
// Generally, this method isn't required in this form
// because SaveSessionBase.setState accepts serialized state (Element) without any side effects or performance degradation.
// However, it's preferable to express contracts explicitly in the code to ensure they aren't inadvertently broken in the future.
override fun setStateToSaveSessionProducer(
state: Any?,
info: ComponentInfo,
effectiveComponentName: String,
sessionProducer: SaveSessionProducer,
) {
val configurationSchemaKey = info.configurationSchemaKey
if (state == null ||
configurationSchemaKey == null ||
info.affectedPropertyNames.isEmpty() ||
sessionProducer !is SaveSessionProducerBase) {
super.setStateToSaveSessionProducer(
state = state,
info = info,
effectiveComponentName = effectiveComponentName,
sessionProducer = sessionProducer,
)
}
else {
val serializedState = deserializeBaseStateWithCustomNameFilter(state as BaseState, info.affectedPropertyNames)
sessionProducer.setSerializedState(componentName = effectiveComponentName, element = serializedState)
}
}
override fun reload(changedStorages: Set<StateStorage>): Collection<String>? {
val result = super.reload(changedStorages)
for (storage in changedStorages) {
if (storage !is ReadOnlyStorage) {
continue
}
@Suppress("IncorrectServiceRetrieving")
val component = project.getServiceIfCreated(storage.componentClass)
if (component == null) {
logger<ConfigurationScriptProjectStoreFactory>().error("Cannot find component by ${storage.componentClass.name}")
continue
}
@Suppress("UNCHECKED_CAST")
initComponentWithoutStateSpec(
component = component as PersistentStateComponent<Any>,
configurationSchemaKey = storage.configurationSchemaKey,
// todo not clear, is it ok, anyway, configuration script is used mostly for Core
pluginId = PluginManagerCore.CORE_ID,
)
}
return result
}
}
private class ReadOnlyStorage(
@JvmField val configurationSchemaKey: String,
@JvmField val componentClass: Class<Any>,
private val store: MyProjectStore,
) : StateStorage {
override fun <T : Any> getState(
component: Any?,
componentName: String,
pluginId: PluginId,
stateClass: Class<T>,
mergeInto: T?,
reload: Boolean,
): T {
val state = ReflectionUtil.newInstance(stateClass, false) as BaseState
val configurationFileManager = ConfigurationFileManager.getInstance(store.project)
if (store.isConfigurationFileListenerAdded.compareAndSet(false, true)) {
configurationFileManager.registerClearableLazyValue {
store.configurationFileChanged()
}
}
val node = configurationFileManager.findValueNode(configurationSchemaKey)
if (node != null) {
readIntoObject(state, node)
}
@Suppress("UNCHECKED_CAST")
return state as T
}
override fun createSaveSessionProducer(): SaveSessionProducer? = null
override fun analyzeExternalChangesAndUpdateIfNeeded(componentNames: MutableSet<in String>) {
}
}
| 284 | null | 5162 | 16,707 | def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0 | 6,602 | intellij-community | Apache License 2.0 |
domain/src/main/java/com/sedsoftware/yaptalker/domain/repository/ActiveTopicsRepository.kt | alerm-sml | 123,927,915 | true | {"Kotlin": 509954, "IDL": 1260, "Shell": 1229, "Prolog": 939, "Java": 823, "CSS": 50} | package com.sedsoftware.yaptalker.domain.repository
import com.sedsoftware.yaptalker.domain.entity.BaseEntity
import io.reactivex.Single
/**
* Interface that represents a Repository for getting active topics related data.
*/
interface ActiveTopicsRepository {
fun getActiveTopics(hash: String, page: Int): Single<List<BaseEntity>>
}
| 0 | Kotlin | 0 | 0 | 6c06171d2af44b0bb9b7809221b2f594d2354102 | 340 | YapTalker | Apache License 2.0 |
src/main/kotlin/com/baulsupp/okurl/tracing/ZipkinConfig.kt | yschimke | 48,341,449 | false | {"Kotlin": 515385, "Shell": 843, "Smarty": 777} | package com.baulsupp.okurl.tracing
import brave.propagation.TraceContext
import java.io.File
import java.io.FileReader
import java.util.Properties
class ZipkinConfig(private val senderUri: String?, private val displayUrl: String?) {
fun zipkinSenderUri(): String? {
return senderUri
}
fun openFunction(): (TraceContext) -> String? {
return { traceContext -> displayUrl?.replace(Regex("""\{traceid}"""), traceContext.traceIdString()) }
}
companion object {
private val zipkinRc = File(System.getenv("HOME"), ".zipkinrc")
fun load(): ZipkinConfig {
if (zipkinRc.exists()) {
FileReader(zipkinRc).use { r ->
val p = Properties()
p.load(r)
val sender = p.getProperty("SENDER")
val display = p.getProperty("DISPLAY")
return ZipkinConfig(sender, display)
}
} else {
return unconfigured()
}
}
fun unconfigured(): ZipkinConfig {
return ZipkinConfig(null, null)
}
}
}
| 16 | Kotlin | 15 | 126 | 32ad9f89d17500399ac16b735f1398ad6ca32f41 | 1,003 | okurl | Apache License 2.0 |
src/test/kotlin/com/github/vhromada/catalog/utils/GenreUtils.kt | vhromada | 795,933,875 | false | null | package com.github.vhromada.catalog.utils
import com.github.vhromada.catalog.entity.ChangeGenreRequest
import com.github.vhromada.catalog.entity.Genre
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.SoftAssertions.assertSoftly
import javax.persistence.EntityManager
/**
* Updates genre fields.
*
* @return updated genre
*/
fun com.github.vhromada.catalog.domain.Genre.updated(): com.github.vhromada.catalog.domain.Genre {
name = "Name"
return this
}
/**
* Updates genre fields.
*
* @return updated genre
*/
fun Genre.updated(): Genre {
return copy(name = "Name")
}
/**
* A class represents utility class for genres.
*
* @author Vladimir Hromada
*/
object GenreUtils {
/**
* Count of genres
*/
const val GENRES_COUNT = 4
/**
* Position
*/
const val POSITION = 10
/**
* Returns genres.
*
* @return genres
*/
fun getDomainGenres(): List<com.github.vhromada.catalog.domain.Genre> {
val genres = mutableListOf<com.github.vhromada.catalog.domain.Genre>()
for (i in 1..GENRES_COUNT) {
genres.add(getDomainGenre(index = i))
}
return genres
}
/**
* Returns genres.
*
* @return genres
*/
fun getGenres(): List<Genre> {
val genres = mutableListOf<Genre>()
for (i in 1..GENRES_COUNT) {
genres.add(getGenre(index = i))
}
return genres
}
/**
* Returns genre for index.
*
* @param index index
* @return genre for index
*/
fun getDomainGenre(index: Int): com.github.vhromada.catalog.domain.Genre {
return com.github.vhromada.catalog.domain.Genre(
id = index,
uuid = getUuid(index = index),
name = "Genre $index name",
position = index + 9
).fillAudit(audit = AuditUtils.getAudit())
}
/**
* Returns UUID for index.
*
* @param index index
* @return UUID for index
*/
private fun getUuid(index: Int): String {
return when (index) {
1 -> "859dd213-d9f9-4223-a5a8-77abf5c7f4ca"
2 -> "34797673-6f5f-455d-a348-7b76786911b6"
3 -> "7833d261-77ce-427a-86f7-a59b2ec604f0"
4 -> "daad5c2a-941a-449a-93ef-0724d4283b43"
else -> throw IllegalArgumentException("Bad index")
}
}
/**
* Returns genre.
*
* @param entityManager entity manager
* @param id genre ID
* @return genre
*/
fun getDomainGenre(entityManager: EntityManager, id: Int): com.github.vhromada.catalog.domain.Genre? {
return entityManager.find(com.github.vhromada.catalog.domain.Genre::class.java, id)
}
/**
* Returns genre for index.
*
* @param index index
* @return genre for index
*/
fun getGenre(index: Int): Genre {
return Genre(
uuid = getUuid(index = index),
name = "Genre $index name"
)
}
/**
* Returns count of genres.
*
* @param entityManager entity manager
* @return count of genres
*/
@Suppress("JpaQlInspection")
fun getGenresCount(entityManager: EntityManager): Int {
return entityManager.createQuery("SELECT COUNT(g.id) FROM Genre g", java.lang.Long::class.java).singleResult.toInt()
}
/**
* Returns genre.
*
* @param id ID
* @return genre
*/
fun newDomainGenre(id: Int?): com.github.vhromada.catalog.domain.Genre {
return com.github.vhromada.catalog.domain.Genre(
id = id,
uuid = TestConstants.UUID,
name = "",
position = if (id == null) Int.MAX_VALUE else id - 1
).updated()
}
/**
* Returns genre.
*
* @return genre
*/
fun newGenre(): Genre {
return Genre(
uuid = TestConstants.UUID,
name = ""
).updated()
}
/**
* Returns request for changing genre.
*
* @return request for changing genre
*/
fun newRequest(): ChangeGenreRequest {
return ChangeGenreRequest(name = "Name")
}
/**
* Asserts list of genres deep equals.
*
* @param expected expected list of genres
* @param actual actual list of genres
*/
fun assertDomainGenresDeepEquals(expected: List<com.github.vhromada.catalog.domain.Genre>, actual: List<com.github.vhromada.catalog.domain.Genre>) {
assertThat(expected.size).isEqualTo(actual.size)
if (expected.isNotEmpty()) {
for (i in expected.indices) {
assertGenreDeepEquals(expected = expected[i], actual = actual[i])
}
}
}
/**
* Asserts genre deep equals.
*
* @param expected expected genre
* @param actual actual genre
*/
fun assertGenreDeepEquals(expected: com.github.vhromada.catalog.domain.Genre?, actual: com.github.vhromada.catalog.domain.Genre?) {
if (expected == null) {
assertThat(actual).isNull()
} else {
assertThat(actual).isNotNull
assertSoftly {
it.assertThat(actual!!.id).isEqualTo(expected.id)
it.assertThat(actual.uuid).isEqualTo(expected.uuid)
it.assertThat(actual.name).isEqualTo(expected.name)
it.assertThat(actual.position).isEqualTo(expected.position)
}
AuditUtils.assertAuditDeepEquals(expected = expected, actual = actual!!)
}
}
/**
* Asserts list of genres deep equals.
*
* @param expected expected list of genres
* @param actual actual list of genres
*/
fun assertGenresDeepEquals(expected: List<com.github.vhromada.catalog.domain.Genre>, actual: List<Genre>) {
assertThat(expected.size).isEqualTo(actual.size)
if (expected.isNotEmpty()) {
for (i in expected.indices) {
assertGenreDeepEquals(expected = expected[i], actual = actual[i])
}
}
}
/**
* Asserts genre deep equals.
*
* @param expected expected genre
* @param actual actual genre
*/
fun assertGenreDeepEquals(expected: com.github.vhromada.catalog.domain.Genre, actual: Genre) {
assertSoftly {
it.assertThat(actual.uuid).isEqualTo(expected.uuid)
it.assertThat(actual.name).isEqualTo(expected.name)
}
}
/**
* Asserts list of genres deep equals.
*
* @param expected expected list of genres
* @param actual actual list of genres
*/
fun assertGenreListDeepEquals(expected: List<Genre>, actual: List<Genre>) {
assertThat(expected.size).isEqualTo(actual.size)
if (expected.isNotEmpty()) {
for (i in expected.indices) {
assertGenreDeepEquals(expected = expected[i], actual = actual[i])
}
}
}
/**
* Asserts genre deep equals.
*
* @param expected expected genre
* @param actual actual genre
*/
fun assertGenreDeepEquals(expected: Genre, actual: Genre) {
assertSoftly {
it.assertThat(actual.uuid).isEqualTo(expected.uuid)
it.assertThat(actual.name).isEqualTo(expected.name)
}
}
/**
* Asserts request and genre deep equals.
*
* @param expected expected request for changing genre
* @param actual actual genre
* @param uuid UUID
*/
fun assertRequestDeepEquals(expected: ChangeGenreRequest, actual: com.github.vhromada.catalog.domain.Genre, uuid: String) {
assertSoftly {
it.assertThat(actual.id).isNull()
it.assertThat(actual.uuid).isEqualTo(uuid)
it.assertThat(actual.name).isEqualTo(expected.name)
it.assertThat(actual.position).isEqualTo(Int.MAX_VALUE)
it.assertThat(actual.createdUser).isNull()
it.assertThat(actual.createdTime).isNull()
it.assertThat(actual.updatedUser).isNull()
it.assertThat(actual.updatedTime).isNull()
}
}
}
| 0 | Kotlin | 0 | 0 | e9358777ae3f6d94ed564f68e59126bbd639b325 | 8,157 | catalog-be | MIT License |
Example/src/main/kotlin/com/example/game/mods/MoveMessage.kt | jstuyts | 213,739,601 | false | {"Markdown": 7, "Gradle Kotlin DSL": 71, "Shell": 2, "Ignore List": 85, "Batchfile": 1, "EditorConfig": 1, "INI": 2, "YAML": 1, "HTML": 56, "Kotlin": 575, "Java": 1, "Text": 4, "Perl": 2, "CSS": 6, "JavaScript": 14, "XML": 7, "Ruby": 2, "JSON": 63, "SVG": 2, "Makefile": 2, "PHP": 2, "Roff": 1, "Diff": 1, "Git Attributes": 1} | package com.example.game.mods
import org.elkoserver.json.JsonLiteral
import org.elkoserver.json.JsonLiteralFactory
import org.elkoserver.json.Referenceable
internal fun msgMove(who: Referenceable, x: Int, y: Int, into: Referenceable?): JsonLiteral =
JsonLiteralFactory.targetVerb(who, "move").apply {
addParameter("x", x)
addParameter("y", y)
addParameterOpt("into", into)
finish()
}
| 5 | null | 1 | 1 | d18864aaa29914c50edcb9ccfbd074a45d3d0498 | 450 | Elko | MIT License |
app/src/main/java/com/food/ordering/zinger/ui/order/OrderViewModel.kt | shrikanth7698 | 240,738,577 | false | null | package com.food.ordering.zinger.ui.order
import androidx.lifecycle.*
import com.food.ordering.zinger.data.local.Resource
import com.food.ordering.zinger.data.model.*
import com.food.ordering.zinger.data.retrofit.OrderRepository
import kotlinx.coroutines.launch
import java.net.UnknownHostException
class OrderViewModel(private val orderRepository: OrderRepository) : ViewModel() {
//get order detail by order id
private val orderByIdRequest = MutableLiveData<Resource<Response<OrderItemListModel>>>()
val orderByIdResponse: LiveData<Resource<Response<OrderItemListModel>>>
get() = orderByIdRequest
fun getOrderById(orderId: Int, isSilent: Boolean = false) {
viewModelScope.launch {
try {
if(!isSilent) {
orderByIdRequest.value = Resource.loading()
}
val response = orderRepository.getOrderById(orderId)
if (response.code == 1)
orderByIdRequest.value = Resource.success(response)
else {
orderByIdRequest.value = Resource.error(message = response.message)
}
} catch (e: Exception) {
if (e is UnknownHostException) {
orderByIdRequest.value = Resource.offlineError()
} else {
orderByIdRequest.value = Resource.error(e)
}
}
}
}
//fetch orders
private val performFetchOrders = MutableLiveData<Resource<List<OrderItemListModel>>>()
val performFetchOrdersStatus: LiveData<Resource<List<OrderItemListModel>>>
get() = performFetchOrders
fun getOrders(mobile: String, pageNum: Int, pageCount: Int) {
viewModelScope.launch {
try {
performFetchOrders.value = Resource.loading()
val response = orderRepository.getOrders(mobile, pageNum, pageCount)
if (response != null) {
if (!response.data.isNullOrEmpty()) {
performFetchOrders.value = Resource.success(response.data)
} else {
performFetchOrders.value = Resource.empty()
}
}
} catch (e: Exception) {
println("fetch orders failed ${e.message}")
if (e is UnknownHostException) {
performFetchOrders.value = Resource.offlineError()
} else {
performFetchOrders.value = Resource.error(e)
}
}
}
}
//rate order
private val rateOrder = MutableLiveData<Resource<Response<String>>>()
val rateOrderStatus: LiveData<Resource<Response<String>>>
get() = rateOrder
fun rateOrder(ratingRequest: RatingRequest) {
viewModelScope.launch {
try {
rateOrder.value = Resource.loading()
val response = orderRepository.rateOrder(ratingRequest)
if (response != null) {
if (response.data != null) {
rateOrder.value = Resource.success(response)
} else {
rateOrder.value = Resource.error(null, response.message)
}
}
} catch (e: Exception) {
println("rate order failed ${e.message}")
if (e is UnknownHostException) {
rateOrder.value = Resource.offlineError()
} else {
rateOrder.value = Resource.error(e)
}
}
}
}
//cancel order
private val cancelOrder = MutableLiveData<Resource<Response<String>>>()
val cancelOrderStatus: LiveData<Resource<Response<String>>>
get() = cancelOrder
fun cancelOrder(orderStatusRequest: OrderStatusRequest) {
viewModelScope.launch {
try {
cancelOrder.value = Resource.loading()
val response = orderRepository.cancelOrder(orderStatusRequest)
if (response != null) {
if (response.data != null) {
cancelOrder.value = Resource.success(response)
} else {
cancelOrder.value = Resource.error(null, response.message)
}
}
} catch (e: Exception) {
println("cancel order failed ${e.message}")
if (e is UnknownHostException) {
cancelOrder.value = Resource.offlineError()
} else {
cancelOrder.value = Resource.error(e)
}
}
}
}
} | 7 | Kotlin | 79 | 99 | b8612ccb23057592cb6097dbfc04811cb3b1865e | 4,755 | Zinger-Android-App | MIT License |
thimble/src/main/kotlin/com/infinum/thimble/models/BundleKeys.kt | infinum | 291,794,084 | false | null | package com.infinum.thimble.models
internal enum class BundleKeys {
CONFIGURATION,
HORIZONTAL_LINE_COLOR,
VERTICAL_LINE_COLOR,
HORIZONTAL_GAP_SIZE,
VERTICAL_GAP_SIZE,
OPACITY,
PORTRAIT_URI,
LANDSCAPE_URI,
COLOR_MODEL,
TOGGLE,
RECORDER_DELAY,
SCREENSHOT_COMPRESSION,
RECORDER_AUDIO,
VIDEO_QUALITY,
SCREEN_SIZE
}
| 0 | Kotlin | 0 | 0 | 8da055d449a4b5805620af5bf4f9d7be7f275373 | 372 | android-thimble | Apache License 2.0 |
src/main/kotlin/ru/stersh/bookcrawler/module/litnet/LitnetLibraryCheckTask.kt | siper | 720,533,744 | false | {"Kotlin": 98608, "Dockerfile": 361} | package ru.stersh.bookcrawler.module.litnet
import kotlinx.coroutines.delay
import org.jetbrains.exposed.sql.insert
import org.jetbrains.exposed.sql.select
import org.jetbrains.exposed.sql.selectAll
import org.jetbrains.exposed.sql.transactions.transaction
import org.jetbrains.exposed.sql.update
import ru.stersh.bookcrawler.Properties
import ru.stersh.bookcrawler.core.*
import ru.stersh.bookcrawler.logger
import ru.stersh.bookcrawler.module.litnet.api.*
import ru.stersh.bookcrawler.module.litnet.api.Book
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
import kotlin.time.Duration.Companion.minutes
class LitnetLibraryCheckTask : TaskManager.Task {
override val name: String = LITNET_PROVIDER_NAME
private val libraryCheckDelay = Properties.get("litnet.libraryCheckPeriod")?.toLongOrNull() ?: DELAY
override suspend fun onInvokeJob() {
val authResult = runCatching { Litnet.checkAuth() }
.onFailure { logger.warn("[Litnet] Filed to login, fix auth credentials and restart app") }
if (authResult.isFailure) {
return
}
while (true) {
val remoteLibrary = runCatching { Litnet.library() }
.onFailure { logger.warn("[Litnet] Filed to fetch library") }
.getOrNull()
if (remoteLibrary == null) {
delay(libraryCheckDelay.minutes)
continue
}
checkNewBooks(remoteLibrary)
checkBooksInSeries()
delay(libraryCheckDelay.minutes)
}
}
private suspend fun checkNewBooks(remoteLibrary: List<LibraryItem>) {
val localLibrary = transaction {
LitnetBookDb
.selectAll()
.map { LitnetBook.fromRow(it) }
}
for (libraryItem in remoteLibrary) {
val localBook = localLibrary.firstOrNull { it.id == libraryItem.book.id }
if (localBook == null) {
val isRead = libraryItem.libInfo.type == LibInfo.TYPE_ARCHIVE
val inSeries = libraryItem.book.priorityCycle != 0
insertBookIntoLibrary(libraryItem.book, inSeries, isRead)
NotificationManager.onNewNotification(
Notification(
id = BookId(libraryItem.book.id, LITNET_PROVIDER_NAME),
title = libraryItem.book.title,
coverUrl = libraryItem.book.cover,
authors = listOfNotNull(libraryItem.book.authorName, libraryItem.book.coAuthorName),
series = null,
type = MessageType.NEW_BOOK_IN_LIBRARY,
availableActions = if (libraryItem.libInfo.type == LibInfo.TYPE_ARCHIVE) {
emptyList()
} else {
listOf(Action.MARK_READ)
}
)
)
handleBook(libraryItem.book.id)
continue
}
if (!localBook.purchased && libraryItem.book.isPurchased) {
transaction {
LitnetBookDb.update(
{ LitnetBookDb.id eq libraryItem.book.id }
) {
it[purchased] = true
it[lastModificationTime] = libraryItem.book.lastUpdate
}
}
NotificationManager.onNewNotification(
Notification(
id = BookId(libraryItem.book.id, LITNET_PROVIDER_NAME),
title = libraryItem.book.title,
coverUrl = libraryItem.book.cover,
authors = listOfNotNull(libraryItem.book.authorName, libraryItem.book.coAuthorName),
series = null,
type = MessageType.BOOK_PURCHASED,
availableActions = if (libraryItem.libInfo.type == LibInfo.TYPE_ARCHIVE) {
emptyList()
} else {
listOf(Action.MARK_READ)
}
)
)
handleBook(libraryItem.book.id)
continue
}
if (localBook.lastModificationTime != libraryItem.book.lastUpdate) {
transaction {
LitnetBookDb.update(
{ LitnetBookDb.id eq libraryItem.book.id }
) {
it[purchased] = libraryItem.book.isPurchased
it[completed] = libraryItem.book.status == "fulltext"
it[coverUrl] = libraryItem.book.cover
it[updatedAt] = DateTimeFormatter.ISO_ZONED_DATE_TIME.format(ZonedDateTime.now())
it[lastModificationTime] = libraryItem.book.lastUpdate
}
}
NotificationManager.onNewNotification(
Notification(
id = BookId(libraryItem.book.id, LITNET_PROVIDER_NAME),
title = libraryItem.book.title,
coverUrl = libraryItem.book.cover,
authors = listOfNotNull(libraryItem.book.authorName, libraryItem.book.coAuthorName),
series = null,
type = MessageType.UPDATES_IN_READING_BOOK,
availableActions = if (libraryItem.libInfo.type == LibInfo.TYPE_ARCHIVE) {
emptyList()
} else {
listOf(Action.MARK_READ)
}
)
)
handleBook(libraryItem.book.id)
continue
}
}
}
private suspend fun checkBooksInSeries() {
val localLibraryIds = transaction {
LitnetBookDb
.select { LitnetBookDb.inSeries eq true }
.map { it[LitnetBookDb.id] }
}
val newBookIds = mutableSetOf<Long>()
for (localId in localLibraryIds) {
val allSeriesBookResult = runCatching { Litnet.getAllSeriesBooks(localId) }
.onFailure {
logger.warn("[Litnet] Filed to get all series books for $localId")
}
val allSeriesBookIds = allSeriesBookResult
.getOrNull()
?.map { it.id }
?: continue
for (bookId in allSeriesBookIds) {
if (bookId !in localLibraryIds) {
newBookIds.add(bookId)
}
}
}
for (newBookId in newBookIds) {
val bookDetailsResult = runCatching { Litnet.getBookDetails(newBookId) }
.onFailure {
logger.warn("[Litnet] Filed to fetch book details $newBookId")
}
val bookDetails = bookDetailsResult.getOrNull() ?: continue
insertBookIntoLibrary(bookDetails)
NotificationManager.onNewNotification(
Notification(
id = BookId(bookDetails.id, LITNET_PROVIDER_NAME),
title = bookDetails.title,
coverUrl = bookDetails.cover,
authors = listOfNotNull(bookDetails.authorName, bookDetails.coAuthorName),
series = null,
type = MessageType.NEW_BOOK_IN_SERIES,
availableActions = listOf(Action.ADD_TO_LIBRARY)
)
)
}
}
private suspend fun handleBook(bookId: Long) {
runCatching {
val book = Litnet.getBook(bookId)
BookHandlerManager.onBookCreated(book)
}.onFailure {
logger.warn("[Litnet] Filed to download book $bookId")
}
}
private fun insertBookIntoLibrary(
book: Book,
inSeries: Boolean,
isRead: Boolean
) = transaction {
LitnetBookDb.insert {
it[title] = book.title
it[LitnetBookDb.inSeries] = inSeries
it[author] = book.authorName
it[authorId] = book.authorId
it[completed] = book.status == "fulltext"
it[coverUrl] = book.cover
it[purchased] = book.isPurchased
it[read] = isRead
it[id] = book.id
it[inLibrary] = true
it[updatedAt] = DateTimeFormatter.ISO_ZONED_DATE_TIME.format(ZonedDateTime.now())
it[lastModificationTime] = book.lastUpdate
}
}
private fun insertBookIntoLibrary(bookDetails: BookDetails) = transaction {
LitnetBookDb.insert {
it[title] = bookDetails.title
it[inSeries] = true
it[author] = bookDetails.authorName
it[authorId] = bookDetails.authorId
it[completed] = bookDetails.status == "fulltext"
it[coverUrl] = bookDetails.cover
it[purchased] = bookDetails.isPurchased
it[read] = false
it[id] = bookDetails.id
it[inLibrary] = false
it[updatedAt] = DateTimeFormatter.ISO_ZONED_DATE_TIME.format(ZonedDateTime.now())
it[lastModificationTime] = bookDetails.lastUpdate
}
}
companion object {
private const val DELAY = 10L
}
} | 13 | Kotlin | 0 | 0 | f50d3ebe7bb58420cf72165b4aa0d1918e530575 | 9,482 | BookCrawler | MIT License |
src/iterator/dinermenu/scratch/iterable/DinerMenu.kt | Devansh-Maurya | 290,240,330 | false | null | package iterator.dinermenu.scratch.iterable
import iterator.dinermenu.scratch.data.MenuItem
import iterator.dinermenu.scratch.iterator.DinerMenuIterator
import iterator.dinermenu.scratch.iterator.Iterator
/**
* Created by devansh on 21/09/20.
*/
class DinerMenu {
companion object {
const val MAX_ITEMS = 6
}
private var numberOfItems = 0
private val menuItems = arrayOfNulls<MenuItem>(MAX_ITEMS)
init {
addItem("Vegetarian BLT",
" (Fakin') Bacon with lettuce & tomato on whole wheat", true, 2.99)
addItem("BLT",
"Bacon with lettuce & tomato on whole wheat", false, 2.99)
addItem("Soup of the day",
"Soup of the day, with a side of potato salad", false, 3.29)
addItem("Hotdog",
"A hot dog with saurkraut, relish, onions, topped with cheese", false, 3.05)
}
fun addItem(name: String, description: String, vegetarian: Boolean, price: Double) {
val menuItem = MenuItem(name, description, vegetarian, price)
if (numberOfItems >= MAX_ITEMS) {
System.err.println("Sorry, menu is full! Can't add item to menu")
} else {
menuItems[numberOfItems++] = menuItem
}
}
fun createIterator(): Iterator<MenuItem> = DinerMenuIterator(menuItems)
} | 2 | Kotlin | 12 | 89 | 6de47075205b7de24e1d19bb514b4a0c4f1c7cbd | 1,334 | Design-Patterns-And-Principles | MIT License |
screen/core/src/main/java/kasem/sm/ui_core/UiText.kt | kasem-sm | 456,508,892 | false | {"Kotlin": 432676, "Procfile": 53, "Shell": 10} | /*
* Copyright (C) 2022, Kasem S.M
* All rights reserved.
*/
package kasem.sm.ui_core
import android.content.Context
import androidx.annotation.StringRes
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
sealed class UiText {
data class StringText(val value: String) : UiText()
data class ResourceText(@StringRes val value: Int) : UiText()
companion object {
/**
* Evaluates the value of [UiText] based on it's type.
* @param[context] is necessary to evaluate a string resource.
*/
fun UiText.get(context: Context): String {
return when (this) {
is StringText -> this.value
is ResourceText -> context.getString(this.value)
}
}
/**
* Mini Helper function that allows us to get strings
* from a [Composable] function
* easily!
*/
@Composable
fun UiText.get(): String {
return when (this) {
is StringText -> this.value
is ResourceText -> LocalContext.current.getString(this.value)
}
}
}
}
| 25 | Kotlin | 49 | 570 | 02543400476bac4248914c5e943ef58bac5a318a | 1,185 | SlimeKT | Apache License 2.0 |
telekt/src/main/kotlin/telekt/types/payment/ShippingQuery.kt | telekt | 173,566,083 | false | null | package rocks.waffle.telekt.types
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import rocks.waffle.telekt.dispatcher.TelegramEvent
/** This object contains information about an incoming shipping query. */
@Serializable data class ShippingQuery(
val id: String,
val from: User,
@SerialName("invoice_payload") val invoicePayload: String,
@SerialName("shipping_address") val shippingAddress: ShippingAddress
) : TelegramEvent | 0 | Kotlin | 3 | 12 | 6e337e863884c875f3032fd60bbdf4bf537bb17e | 477 | telekt | MIT License |
platform/platform-impl/src/com/intellij/ide/cds/CDSManager.kt | ingokegel | 284,920,751 | false | null | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.cds
import com.intellij.diagnostic.VMOptions
import com.intellij.execution.CommandLineWrapperUtil
import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.process.OSProcessUtil
import com.intellij.execution.util.ExecUtil
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.progress.PerformInBackgroundOption
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.text.StringUtil
import com.intellij.util.TimeoutUtil
import com.intellij.util.text.VersionComparatorUtil
import com.sun.management.OperatingSystemMXBean
import com.sun.tools.attach.VirtualMachine
import java.io.File
import java.lang.management.ManagementFactory
import java.nio.charset.StandardCharsets
import java.util.concurrent.TimeUnit
import kotlin.system.measureTimeMillis
sealed class CDSTaskResult(val statusName: String) {
object Success : CDSTaskResult("success")
abstract class Cancelled(statusName: String) : CDSTaskResult(statusName)
object InterruptedForRetry : Cancelled("cancelled")
object TerminatedByUser : Cancelled("terminated-by-user")
object PluginsChanged : Cancelled("plugins-changed")
data class Failed(val error: String) : CDSTaskResult("failed")
}
object CDSManager {
private val LOG = Logger.getInstance(javaClass)
val isValidEnv: Boolean by lazy {
// AppCDS requires classes packed into JAR files, not from the out folder
if (PluginManagerCore.isRunningFromSources()) return@lazy false
// CDS features are only available on 64 bit JVMs
if (!SystemInfo.is64Bit) return@lazy false
// The AppCDS (JEP 310) is only added in JDK10,
// The closest JRE we ship/support is 11
if (!SystemInfo.isJavaVersionAtLeast(11)) return@lazy false
//AppCDS does not support Windows and macOS
if (!SystemInfo.isLinux) {
//Specific patches are included into JetBrains runtime
//to support Windows and macOS
if (!SystemInfo.isJetBrainsJvm) return@lazy false
if (VersionComparatorUtil.compare(SystemInfo.JAVA_RUNTIME_VERSION, "11.0.4+10-b520.2") < 0) return@lazy false
}
// we do not like to overload a potentially small computer with our process
val osBean = ManagementFactory.getPlatformMXBean(OperatingSystemMXBean::class.java)
if (osBean.totalPhysicalMemorySize < 4L * 1024 * 1024 * 1024) return@lazy false
if (osBean.availableProcessors < 4) return@lazy false
if (!VMOptions.canWriteOptions()) return@lazy false
true
}
val currentCDSArchive: File? by lazy {
val arguments = ManagementFactory.getRuntimeMXBean().inputArguments
val xShare = arguments.any { it == "-Xshare:auto" || it == "-Xshare:on" }
if (!xShare) return@lazy null
val key = "-XX:SharedArchiveFile="
return@lazy arguments.firstOrNull { it.startsWith(key) }?.removePrefix(key)?.let(::File)
}
fun cleanupStaleCDSFiles(isCDSEnabled: Boolean): CDSTaskResult {
val paths = CDSPaths.current
val currentCDSPath = currentCDSArchive
val files = paths.baseDir.listFiles() ?: arrayOf()
if (files.isEmpty()) return CDSTaskResult.Success
for (path in files) {
if (path == currentCDSPath) continue
if (isCDSEnabled && paths.isOurFile(path)) continue
FileUtil.delete(path)
}
return CDSTaskResult.Success
}
fun removeCDS() {
if (currentCDSArchive?.isFile != true ) return
VMOptions.writeDisableCDSArchiveOption()
LOG.warn("Disabled CDS")
}
private interface CDSProgressIndicator {
/// returns non-null value if cancelled
val cancelledStatus: CDSTaskResult.Cancelled?
var text2: String?
}
fun installCDS(canStillWork: () -> Boolean, onResult: (CDSTaskResult) -> Unit) {
CDSFUSCollector.logCDSBuildingStarted()
val startTime = System.nanoTime()
ProgressManager.getInstance().run(object : Task.Backgroundable(
null,
"Optimizing startup performance...",
true,
PerformInBackgroundOption.ALWAYS_BACKGROUND
) {
override fun run(indicator: ProgressIndicator) {
indicator.isIndeterminate = true
val progress = object : CDSProgressIndicator {
override val cancelledStatus: CDSTaskResult.Cancelled?
get() {
if (!canStillWork()) return CDSTaskResult.InterruptedForRetry
if (indicator.isCanceled) return CDSTaskResult.TerminatedByUser
if (ApplicationManager.getApplication().isDisposed) return CDSTaskResult.InterruptedForRetry
return null
}
override var text2: String?
get() = indicator.text2
set(value) {
indicator.text2 = value
}
}
val paths = CDSPaths.current
val result = try {
installCDSImpl(progress, paths)
} catch (t: Throwable) {
LOG.warn("Settings up CDS Archive crashed unexpectedly. ${t.message}", t)
val message = "Unexpected crash $t"
paths.markError(message)
CDSTaskResult.Failed(message)
}
val installTime = TimeoutUtil.getDurationMillis(startTime)
CDSFUSCollector.logCDSBuildingCompleted(installTime, result)
onResult(result)
}
})
}
private fun installCDSImpl(indicator: CDSProgressIndicator, paths: CDSPaths): CDSTaskResult {
if (paths.isSame(currentCDSArchive)) {
val message = "CDS archive is already generated and being used. Nothing to do"
LOG.debug(message)
return CDSTaskResult.Success
}
if (paths.classesErrorMarkerFile.isFile) {
return CDSTaskResult.Failed("CDS archive has already failed, skipping")
}
LOG.info("Starting generation of CDS archive to the ${paths.classesArchiveFile} and ${paths.classesArchiveFile} files")
paths.mkdirs()
val listResult = generateFileIfNeeded(indicator, paths, paths.classesListFile, ::generateClassList) { t ->
"Failed to attach CDS Java Agent to the running IDE instance. ${t.message}"
}
if (listResult != CDSTaskResult.Success) return listResult
val archiveResult = generateFileIfNeeded(indicator, paths, paths.classesArchiveFile, ::generateSharedArchive) { t ->
"Failed to generated CDS archive. ${t.message}"
}
if (archiveResult != CDSTaskResult.Success) return archiveResult
VMOptions.writeEnableCDSArchiveOption(paths.classesArchiveFile.absolutePath)
LOG.warn("Enabled CDS archive from ${paths.classesArchiveFile}, VMOptions were updated")
return CDSTaskResult.Success
}
private val agentPath: File
get() {
val libPath = File(PathManager.getLibPath()) / "cds" / "classesLogAgent.jar"
if (libPath.isFile) return libPath
LOG.warn("Failed to find bundled CDS classes agent in $libPath")
//consider local debug IDE case
val probe = File(PathManager.getHomePath()) / "out" / "classes" / "artifacts" / "classesLogAgent_jar" / "classesLogAgent.jar"
if (probe.isFile) return probe
error("Failed to resolve path to the CDS agent")
}
private fun generateClassList(indicator: CDSProgressIndicator, paths: CDSPaths) {
indicator.text2 = "Collecting classes list..."
val selfAttachKey = "jdk.attach.allowAttachSelf"
if (!System.getProperties().containsKey(selfAttachKey)) {
throw RuntimeException("Please make sure you have -D$selfAttachKey=true set in the VM options")
}
val duration = measureTimeMillis {
val vm = VirtualMachine.attach(OSProcessUtil.getApplicationPid())
try {
vm.loadAgent(agentPath.path, "${paths.classesListFile}")
}
finally {
vm.detach()
}
}
LOG.info("CDS classes file is generated in ${StringUtil.formatDuration(duration)}")
}
private fun generateSharedArchive(indicator: CDSProgressIndicator, paths: CDSPaths) {
indicator.text2 = "Generating classes archive..."
val logLevel = if (LOG.isDebugEnabled) "=debug" else ""
val args = listOf(
"-Djava.class.path=${ManagementFactory.getRuntimeMXBean().classPath}",
"-Xlog:cds$logLevel",
"-Xlog:class+path$logLevel",
"-Xshare:dump",
"-XX:+UnlockDiagnosticVMOptions",
"-XX:SharedClassListFile=${paths.classesListFile}",
"-XX:SharedArchiveFile=${paths.classesArchiveFile}"
)
CommandLineWrapperUtil.writeArgumentsFile(paths.classesPathFile, args, StandardCharsets.UTF_8)
val durationLink = measureTimeMillis {
val ext = if (SystemInfo.isWindows) ".exe" else ""
val javaExe = File(System.getProperty("java.home")!!) / "bin" / "java$ext"
val javaArgs = listOf(
javaExe.path,
"@${paths.classesPathFile}"
)
val cwd = File(".").canonicalFile
LOG.info("Running CDS generation process: $javaArgs in $cwd with classpath: ${args}")
//recreate files for sanity
FileUtil.delete(paths.dumpOutputFile)
FileUtil.delete(paths.classesArchiveFile)
val commandLine = object : GeneralCommandLine() {
override fun buildProcess(builder: ProcessBuilder) : ProcessBuilder {
return super.buildProcess(builder)
.redirectErrorStream(true)
.redirectInput(ProcessBuilder.Redirect.PIPE)
.redirectOutput(paths.dumpOutputFile)
}
}
commandLine.workDirectory = cwd
commandLine.exePath = javaExe.absolutePath
commandLine.addParameter("@${paths.classesPathFile}")
if (!SystemInfo.isWindows) {
// the utility does not recover process exit code from the call on Windows
ExecUtil.setupLowPriorityExecution(commandLine)
}
val timeToWaitFor = System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(10)
fun shouldWaitForProcessToComplete() = timeToWaitFor > System.currentTimeMillis()
val process = commandLine.createProcess()
try {
runCatching { process.outputStream.close() }
while (shouldWaitForProcessToComplete()) {
if (indicator.cancelledStatus != null) throw InterruptedException()
if (process.waitFor(200, TimeUnit.MILLISECONDS)) break
}
}
finally {
if (process.isAlive) {
process.destroyForcibly()
}
}
if (!shouldWaitForProcessToComplete()) {
throw RuntimeException("The process took too long and will be killed. See ${paths.dumpOutputFile} for details")
}
val exitValue = process.exitValue()
if (exitValue != 0) {
val outputLines = runCatching {
paths.dumpOutputFile.readLines().takeLast(30).joinToString("\n")
}.getOrElse { "" }
throw RuntimeException("The process existed with code $exitValue. See ${paths.dumpOutputFile} for details:\n$outputLines")
}
}
LOG.info("Generated CDS archive in ${paths.classesArchiveFile}, " +
"size = ${StringUtil.formatFileSize(paths.classesArchiveFile.length())}, " +
"it took ${StringUtil.formatDuration(durationLink)}")
}
private operator fun File.div(s: String) = File(this, s)
private val File.isValidFile get() = isFile && length() > 42
private inline fun generateFileIfNeeded(indicator: CDSProgressIndicator,
paths: CDSPaths,
theOutputFile: File,
generate: (CDSProgressIndicator, CDSPaths) -> Unit,
errorMessage: (Throwable) -> String): CDSTaskResult {
try {
if (theOutputFile.isValidFile) return CDSTaskResult.Success
indicator.cancelledStatus?.let { return it }
if (!paths.hasSameEnvironmentToBuildCDSArchive()) return CDSTaskResult.PluginsChanged
generate(indicator, paths)
LOG.assertTrue(theOutputFile.isValidFile, "Result file must be generated and be valid")
return CDSTaskResult.Success
}
catch (t: Throwable) {
FileUtil.delete(theOutputFile)
indicator.cancelledStatus?.let { return it }
if (t is InterruptedException) {
return CDSTaskResult.InterruptedForRetry
}
val message = errorMessage(t)
LOG.warn(message, t)
paths.markError(message)
return CDSTaskResult.Failed(message)
}
}
} | 1 | null | 1 | 2 | dc846ecb926c9d9589c1ed8a40fdb20e47874db9 | 12,735 | intellij-community | Apache License 2.0 |
app/src/main/java/com/mrkaz/tokoin/presentation/ui/main/MainVM.kt | mrkazansky | 348,208,334 | false | {"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "Kotlin": 94, "JSON": 3, "XML": 28, "Java": 2} | package com.mrkaz.tokoin.presentation.ui.main
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.mrkaz.tokoin.data.database.entity.ReferenceEntity
import com.mrkaz.tokoin.usecase.reference.ReferenceUseCase
import kotlinx.coroutines.*
import org.koin.core.KoinComponent
class MainVM(
mainDispatcher: CoroutineDispatcher,
ioDispatcher: CoroutineDispatcher,
private val useCase: ReferenceUseCase
) : ViewModel(), KoinComponent {
private val job = SupervisorJob()
private val uiScope = CoroutineScope(mainDispatcher + job)
private val ioScope = CoroutineScope(ioDispatcher + job)
val loadingLiveData = MutableLiveData<Boolean>()
fun setupData() {
uiScope.launch {
setLoadingVisibility(true)
try {
val data = ioScope.async {
return@async useCase.insert(mockReference().map { ReferenceEntity(it) })
}.await()
setLoadingVisibility(false)
} catch (e: Exception) {
setLoadingVisibility(false)
}
}
}
private fun mockReference() = listOf("bitcoin", "apple", "earthquake", "animal")
private fun setLoadingVisibility(visible: Boolean) {
loadingLiveData.postValue(visible)
}
} | 1 | null | 1 | 1 | 4b4df194cbf375ec057d61f57516b5a45f27c1b1 | 1,311 | mvvm-template | Apache License 2.0 |
app/src/main/java/io/horizontalsystems/bankwallet/modules/nft/collection/NftAssetItemsPricedWithCurrencyRepository.kt | horizontalsystems | 142,825,178 | false | null | package io.horizontalsystems.bankwallet.modules.nft.collection
import io.horizontalsystems.bankwallet.core.subscribeIO
import io.horizontalsystems.bankwallet.entities.CurrencyValue
import io.horizontalsystems.bankwallet.modules.balance.BalanceXRateRepository
import io.horizontalsystems.bankwallet.modules.nft.DataWithError
import io.horizontalsystems.bankwallet.modules.nft.NftCollectionRecord
import io.horizontalsystems.marketkit2.models.CoinPrice
import io.reactivex.disposables.CompositeDisposable
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.asSharedFlow
class NftAssetItemsPricedWithCurrencyRepository(
private val xRateRepository: BalanceXRateRepository
) {
private val _itemsDataFlow =
MutableSharedFlow<DataWithError<Map<NftCollectionRecord, List<NftAssetItemPricedWithCurrency>>?>>(
replay = 1,
onBufferOverflow = BufferOverflow.DROP_OLDEST
)
val itemsDataFlow = _itemsDataFlow.asSharedFlow()
val baseCurrency by xRateRepository::baseCurrency
private val disposables = CompositeDisposable()
fun start() {
xRateRepository.itemObservable
.subscribeIO {
handleUpdatedRates(it)
}
.let {
disposables.add(it)
}
}
private fun handleUpdatedRates(latestRates: Map<String, CoinPrice?>) {
val currentData = _itemsDataFlow.replayCache.lastOrNull() ?: return
val updatedValue = currentData.value?.map { (collectionRecord, items) ->
collectionRecord to items.map { item ->
val coinPrice = item.coinPrice
val itemCoinUid = coinPrice?.coin?.uid
if (latestRates.containsKey(itemCoinUid)) {
val currencyPrice = latestRates[itemCoinUid]?.let { latestRate ->
coinPrice?.let {
CurrencyValue(xRateRepository.baseCurrency, coinPrice.value.multiply(latestRate.value))
}
}
item.copy(currencyPrice = currencyPrice)
} else {
item
}
}
}?.toMap()
_itemsDataFlow.tryEmit(currentData.copy(value = updatedValue))
}
fun setItems(data: DataWithError<Map<NftCollectionRecord, List<NftAssetItemPriced>>?>) {
val items = data.value?.let { value ->
val coinUids = value.map { (_, items) ->
items.mapNotNull {
it.coinPrice?.coin?.uid
}
}.flatten()
xRateRepository.setCoinUids(coinUids)
val latestRates = xRateRepository.getLatestRates()
value.map { (collectionRecord, assetItemsPriced) ->
collectionRecord to assetItemsPriced.map {
val currencyPrice = it.coinPrice?.let { coinPrice ->
latestRates[coinPrice.coin.uid]?.let { latestRate ->
CurrencyValue(xRateRepository.baseCurrency, coinPrice.value.multiply(latestRate.value))
}
}
NftAssetItemPricedWithCurrency(
assetItem = it.assetItem,
coinPrice = it.coinPrice,
currencyPrice = currencyPrice
)
}
}.toMap()
}
_itemsDataFlow.tryEmit(DataWithError(items, data.error))
}
fun stop() {
disposables.clear()
}
fun refresh() {
xRateRepository.refresh()
}
}
| 153 | null | 190 | 348 | fea4c5d96759a865408f92e661a13e10faa66226 | 3,675 | unstoppable-wallet-android | MIT License |
Notification/src/main/java/com/sdk/notification/model/notification/InPlayerAccessRevokedNotificationEntity.kt | inplayer-org | 161,477,099 | false | null | package com.sdk.notification.model.notification
data class InPlayerAccessRevokedNotification(val resource: InPlayerAccessRevokedNotificationResource,
override val type: String, override val timestamp: Long) : InPlayerNotificationEntity
data class InPlayerAccessRevokedNotificationResource(val item_id: Int) | 2 | Kotlin | 1 | 5 | d11faf61aee6e75a1be8bccb63c17e257282725b | 354 | inplayer-android-sdk | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.