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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
tabler-icons/src/commonMain/kotlin/compose/icons/tablericons/SquarePlus.kt
|
DevSrSouza
| 311,134,756
| false
| null |
package compose.icons.tablericons
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.PathFillType.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeCap.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 compose.icons.TablerIcons
public val TablerIcons.SquarePlus: ImageVector
get() {
if (_squarePlus != null) {
return _squarePlus!!
}
_squarePlus = Builder(name = "SquarePlus", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(6.0f, 4.0f)
lineTo(18.0f, 4.0f)
arcTo(2.0f, 2.0f, 0.0f, false, true, 20.0f, 6.0f)
lineTo(20.0f, 18.0f)
arcTo(2.0f, 2.0f, 0.0f, false, true, 18.0f, 20.0f)
lineTo(6.0f, 20.0f)
arcTo(2.0f, 2.0f, 0.0f, false, true, 4.0f, 18.0f)
lineTo(4.0f, 6.0f)
arcTo(2.0f, 2.0f, 0.0f, false, true, 6.0f, 4.0f)
close()
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(9.0f, 12.0f)
lineTo(15.0f, 12.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(12.0f, 9.0f)
lineTo(12.0f, 15.0f)
}
}
.build()
return _squarePlus!!
}
private var _squarePlus: ImageVector? = null
| 17
| null |
25
| 571
|
a660e5f3033e3222e3553f5a6e888b7054aed8cd
| 2,482
|
compose-icons
|
MIT License
|
platform/core-api/src/com/intellij/openapi/progress/cancellation.kt
|
JetBrains
| 2,489,216
| false
| null |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Internal
package com.intellij.openapi.progress
import com.intellij.concurrency.withThreadContext
import com.intellij.openapi.application.asContextElement
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.util.ThrowableComputable
import com.intellij.util.ConcurrencyUtil
import kotlinx.coroutines.*
import org.jetbrains.annotations.ApiStatus.Internal
import kotlin.coroutines.EmptyCoroutineContext
private val LOG: Logger = Logger.getInstance("#com.intellij.openapi.progress")
fun <X> withCurrentJob(job: Job, action: () -> X): X = Cancellation.withCurrentJob(job, ThrowableComputable(action))
@Deprecated(
"Renamed to `withCurrentJob`",
replaceWith = ReplaceWith(
"withCurrentJob(job, action)",
"com.intellij.openapi.progress.withCurrentJob"
)
)
fun <X> withJob(job: Job, action: () -> X): X = withCurrentJob(job, action)
/**
* Ensures that the current thread has an [associated job][Cancellation.currentJob].
*
* If there is a [global indicator][ProgressManager.getGlobalProgressIndicator], then the new job is created,
* and it becomes a "child" of the global progress indicator
* (the cancellation of the indicator is cancels the job).
* Otherwise, if there is already an associated job, then it's used as is.
* Otherwise, when the current thread does not have an associated job or indicator, then the [IllegalStateException] is thrown.
*
* This method is designed as a bridge to run the code, which is relying on the newer [Cancellation] mechanism,
* from the code, which is run under older progress indicators.
* This method is expected to continue working when the progress indicator is replaced with a current job.
*
* @throws ProcessCanceledException if there was a global indicator and it was cancelled
* @throws CancellationException if there was a current job it was cancelled
*/
@Internal
fun <T> ensureCurrentJob(action: (Job) -> T): T {
return ensureCurrentJob(allowOrphan = false, action)
}
@Internal
fun <T> ensureCurrentJobAllowingOrphan(action: (Job) -> T): T {
return ensureCurrentJob(allowOrphan = true, action)
}
internal fun <T> ensureCurrentJob(allowOrphan: Boolean, action: (Job) -> T): T {
val indicator = ProgressManager.getGlobalProgressIndicator()
if (indicator != null) {
return ensureCurrentJob(indicator, action)
}
val currentJob = Cancellation.currentJob()
if (currentJob != null) {
return action(currentJob)
}
if (!allowOrphan) {
LOG.error("There is no ProgressIndicator or Job in this thread, the current job is not cancellable.")
}
val orphanJob = Job(parent = null)
return executeWithJobAndCompleteIt(orphanJob) {
action(orphanJob)
}
}
/**
* @throws ProcessCanceledException if [indicator] is cancelled,
* or a child coroutine is started and failed
*/
internal fun <T> ensureCurrentJob(indicator: ProgressIndicator, action: (currentJob: Job) -> T): T {
val currentJob = Job(parent = null) // no job parent, the "parent" is the indicator
val indicatorWatcher = cancelWithIndicator(currentJob, indicator)
val progressModality = ProgressManager.getInstance().currentProgressModality?.asContextElement()
?: EmptyCoroutineContext
return try {
ProgressManager.getInstance().silenceGlobalIndicator {
executeWithJobAndCompleteIt(currentJob) {
withThreadContext(progressModality).use {
action(currentJob)
}
}
}
}
catch (ce: IndicatorCancellationException) {
throw ProcessCanceledException(ce)
}
catch (ce: CurrentJobCancellationException) {
throw ProcessCanceledException(ce)
}
finally {
indicatorWatcher.cancel()
}
}
private fun cancelWithIndicator(job: Job, indicator: ProgressIndicator): Job {
return CoroutineScope(Dispatchers.IO).launch(CoroutineName("indicator watcher")) {
while (!indicator.isCanceled) {
delay(ConcurrencyUtil.DEFAULT_TIMEOUT_MS)
}
try {
indicator.checkCanceled()
error("A cancelled indicator must throw PCE")
}
catch (pce: ProcessCanceledException) {
job.cancel(IndicatorCancellationException(pce))
}
}
}
/**
* Associates the calling thread with a [job], invokes [action], and completes the job.
* @return action result
*/
@Internal
fun <X> executeWithJobAndCompleteIt(
job: CompletableJob,
action: () -> X,
): X {
try {
val result: X = withCurrentJob(job, action)
job.complete()
return result
}
catch (ce: CancellationException) {
job.cancel(ce)
throw ce
}
catch (e: Throwable) {
// `job.completeExceptionally(e)` will fail parent Job,
// which is not desired when this Job is a read action Job.
//
// ReadAction.computeCancellable {
// throw X
// }
// X will be re-thrown, but the caller is not expected to become cancelled
// since it might catch X and act accordingly.
//
// Ideally, completeExceptionally should be used because it's more correct semantically,
// but read job must not fail its parent regardless of whether the parent is supervisor:
// https://github.com/Kotlin/kotlinx.coroutines/issues/3409
job.cancel(CancellationException(null, e))
throw e
}
}
| 191
| null |
4372
| 13,319
|
4d19d247824d8005662f7bd0c03f88ae81d5364b
| 5,311
|
intellij-community
|
Apache License 2.0
|
fontawesome/src/de/msrd0/fontawesome/icons/FA_BABY.kt
|
msrd0
| 363,665,023
| false
| null |
/* @generated
*
* This file is part of the FontAwesome Kotlin library.
* https://github.com/msrd0/fontawesome-kt
*
* This library is not affiliated with FontAwesome.
*
* 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 de.msrd0.fontawesome.icons
import de.msrd0.fontawesome.Icon
import de.msrd0.fontawesome.Style
import de.msrd0.fontawesome.Style.SOLID
/** Baby */
object FA_BABY: Icon {
override val name get() = "Baby"
override val unicode get() = "f77c"
override val styles get() = setOf(SOLID)
override fun svg(style: Style) = when(style) {
SOLID -> """<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><path d="M156.8 411.8l31.22-31.22l-60.04-53.09l-52.29 52.28C61.63 393.8 60.07 416.1 72 432l48 64C127.9 506.5 139.9 512 152 512c8.345 0 16.78-2.609 23.97-8c17.69-13.25 21.25-38.33 8-56L156.8 411.8zM224 159.1c44.25 0 79.99-35.75 79.99-79.1S268.3 0 224 0S144 35.75 144 79.1S179.8 159.1 224 159.1zM408.7 145c-12.75-18.12-37.63-22.38-55.76-9.75l-40.63 28.5c-52.63 37-124.1 37-176.8 0l-40.63-28.5C76.84 122.6 51.97 127 39.22 145C26.59 163.1 30.97 188 48.97 200.8l40.63 28.5C101.7 237.7 114.7 244.3 128 250.2L128 288h192l.0002-37.71c13.25-5.867 26.22-12.48 38.34-21.04l40.63-28.5C417.1 188 421.4 163.1 408.7 145zM320 327.4l-60.04 53.09l31.22 31.22L264 448c-13.25 17.67-9.689 42.75 8 56C279.2 509.4 287.6 512 295.1 512c12.16 0 24.19-5.516 32.03-16l48-64c11.94-15.92 10.38-38.2-3.719-52.28L320 327.4z"/></svg>"""
else -> null
}
}
| 0
|
Kotlin
|
0
| 0
|
b2fdb74278104be68c95e8f083fc75ab74395112
| 1,985
|
fontawesome-kt
|
Apache License 2.0
|
app/src/main/java/it/ilker/repeatcard/ui/home/HomeViewModel.kt
|
guuilp
| 304,411,948
| true
|
{"Kotlin": 113244}
|
package it.ilker.repeatcard.ui.home
import android.content.Context
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import it.ilker.repeatcard.db.FlashcardDatabase
import it.ilker.repeatcard.db.flashcard.Flashcard
import it.ilker.repeatcard.db.flashcard.FlashcardRepository
import it.ilker.repeatcard.ui.util.exhaustive
import kotlinx.coroutines.launch
sealed class FlashcardEvent {
object Load : FlashcardEvent()
}
sealed class FlashcardState {
object Error : FlashcardState()
data class Success(val flashcards: List<Flashcard>) : FlashcardState()
}
class HomeViewModel(context: Context) : ViewModel() {
private val repository: FlashcardRepository
var state: MutableLiveData<FlashcardState> = MutableLiveData()
init {
val flashcardsDao = FlashcardDatabase.getDatabase(context).flashcardDao()
repository = FlashcardRepository(flashcardsDao)
}
fun send(event: FlashcardEvent) {
when (event) {
is FlashcardEvent.Load -> loadContent()
}.exhaustive
}
private fun loadContent() = viewModelScope.launch {
val allFlashcards = repository.getFlashcards()
if (allFlashcards.isEmpty()) {
state.postValue(FlashcardState.Error)
} else {
state.postValue(FlashcardState.Success(allFlashcards))
}
}
}
| 0
| null |
0
| 0
|
2288281bedfcccb73933a36f5f07fb9b7e4f0b70
| 1,407
|
repeatcard
|
MIT License
|
demo-kotlin/src/main/java/com/skydoves/preferenceroomdemo/components/UserProfileComponent.kt
|
skydoves
| 111,425,878
| false
| null |
/*
* Copyright (C) 2017 skydoves
*
* 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.skydoves.preferenceroomdemo.components
import com.skydoves.preferenceroom.PreferenceComponent
import com.skydoves.preferenceroomdemo.LoginActivity
import com.skydoves.preferenceroomdemo.MainActivity
import com.skydoves.preferenceroomdemo.entities.Device
import com.skydoves.preferenceroomdemo.entities.Profile
/**
* Developed by skydoves on 2017-11-20.
* Copyright (c) 2017 skydoves rights reserved.
*/
/**
* Component integrates entities.
*/
@PreferenceComponent(entities = [Profile::class, Device::class])
interface UserProfileComponent {
/**
* declare dependency injection targets.
*/
fun inject(target: MainActivity)
fun inject(target: LoginActivity)
}
| 2
| null |
25
| 374
|
b67eb5279422b203888db71af48bb1fda5382a04
| 1,292
|
PreferenceRoom
|
Apache License 2.0
|
credentials/credentials-play-services-auth/src/androidTest/java/androidx/credentials/playservices/getdigitalcredential/CredentialProviderGetDigitalCredentialControllerTest.kt
|
androidx
| 256,589,781
| false
|
{"Kotlin": 112114129, "Java": 66594571, "C++": 9132142, "AIDL": 635065, "Python": 325169, "Shell": 194520, "TypeScript": 40647, "HTML": 35176, "Groovy": 27178, "ANTLR": 26700, "Svelte": 20397, "CMake": 15512, "C": 15043, "GLSL": 3842, "Swift": 3153, "JavaScript": 3019}
|
/*
* Copyright 2024 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.credentials.playservices.getdigitalcredential
import android.content.ComponentName
import androidx.credentials.ExperimentalDigitalCredentialApi
import androidx.credentials.GetCredentialRequest
import androidx.credentials.GetDigitalCredentialOption
import androidx.credentials.playservices.TestCredentialsActivity
import androidx.credentials.playservices.TestUtils
import androidx.credentials.playservices.controllers.GetRestoreCredential.CredentialProviderGetDigitalCredentialController
import androidx.test.core.app.ActivityScenario
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
import com.google.common.truth.Truth.assertThat
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
@SmallTest
@OptIn(ExperimentalDigitalCredentialApi::class)
class CredentialProviderGetDigitalCredentialControllerTest {
@Test
fun convertRequestToPlayServices_success() {
val request =
GetCredentialRequest(
credentialOptions =
listOf(
GetDigitalCredentialOption("{\"request\":{\"json\":{\"test\":\"val\"}}}"),
GetDigitalCredentialOption("{\"request\":\"val\",\"key2\":\"val2\"}"),
),
origin = "origin",
preferIdentityDocUi = true,
preferUiBrandingComponentName = ComponentName("pkg", "cls"),
preferImmediatelyAvailableCredentials = true,
)
val activityScenario = ActivityScenario.launch(TestCredentialsActivity::class.java)
activityScenario.onActivity { activity: TestCredentialsActivity? ->
val convertedRequest =
CredentialProviderGetDigitalCredentialController(activity!!)
.convertRequestToPlayServices(request)
assertThat(convertedRequest.origin).isEqualTo(request.origin)
TestUtils.equals(
convertedRequest.data,
GetCredentialRequest.getRequestMetadataBundle(request)
)
request.credentialOptions.forEachIndexed { idx, expectedOption ->
val actualOption = convertedRequest.credentialOptions[idx]
assertThat(actualOption.type).isEqualTo(expectedOption.type)
if (expectedOption is GetDigitalCredentialOption) {
assertThat(actualOption.requestMatcher).isEqualTo(expectedOption.requestJson)
}
TestUtils.equals(actualOption.credentialRetrievalData, expectedOption.requestData)
TestUtils.equals(actualOption.candidateQueryData, expectedOption.candidateQueryData)
}
}
}
}
| 29
|
Kotlin
|
1011
| 5,321
|
98b929d303f34d569e9fd8a529f022d398d1024b
| 3,358
|
androidx
|
Apache License 2.0
|
src/main/kotlin/arsmagna/utils/Utils.kt
|
amironov73
| 636,496,925
| false
| null |
@file:Suppress("unused")
package arsmagna.utils
/*
* Вспомогательные константы и методы, не вошедшие в прочие классы.
*/
import arsmagna.SubField
import org.jetbrains.annotations.Contract
/**
* Максимальное количество записей в пакете.
*/
const val MAX_PACKET = 32758
/**
* Список баз данных для администратора.
*/
const val ADMINISTRATOR_DATABASE_LIST = "dbnam1.mnu"
/**
* Список баз данных для каталогизатора.
*/
const val CATALOGER_DATABASE_LIST = "dbnam2.mnu"
/**
* Список баз данных для читателя.
*/
const val READER_DATABASE_LIST = "dbnam3.mnu"
/**
* Carriage return and line feed symbols.
*/
val CRLF = byteArrayOf(0x0D, 0x0A)
/**
* Line feed symbol.
*/
val LF = byteArrayOf(0x0A)
/**
* Return codes that are valid for the ReadRecord command.
*/
val READ_RECORD_CODES = intArrayOf(-201, -600, -602, -603)
/**
* Return codes that are valid for the ReadTerms command.
*/
val READ_TERMS_CODES = intArrayOf(-202, -203, -204)
// ОБЩИЕ РАЗДЕЛИТЕЛИ
/**
* Запятая.
*/
val comma = charArrayOf(',')
/**
* Запятая или точка с запятой.
*/
val commaOrSemicolon = charArrayOf(',', ';')
/**
* Двоеточие.
*/
val colon = charArrayOf(':')
/**
* Точка.
*/
val dot = charArrayOf('.')
/**
* Знак "минус".
*/
val minus = charArrayOf('-')
/**
* Перевод строки.
*/
val newLine = charArrayOf('\r', '\n')
/**
* Перевод строки или символ процента.
*/
val newLineOrPercent = charArrayOf('\r', '\n', '%')
/**
* Решетка.
*/
val numberSign = charArrayOf('#')
/**
* Точка с запятой.
*/
val semicolon = charArrayOf(';')
/**
* Слэш.
*/
val slash = charArrayOf('/')
/**
* Пробел.
*/
val space = charArrayOf(' ')
/**
* Пробел или символ табуляции.
*/
val spaceOrTab = charArrayOf(' ', '\t')
/**
* Символ табуляции.
*/
val tab = charArrayOf('\t')
/**
* Вертикальная черта.
*/
val verticalLine = charArrayOf('|')
// КОДЫ АРМ
/**
* АРМ "Администратор".
*/
const val Administrator: Byte = 65 // 'A'
/**
* АРМ "Книговыдача".
*/
const val Bookland: Byte = 66 // 'B'
/**
* АРМ "Книговыдача". Еще разок :)
*/
const val Circulation: Byte = 66 // 'B'
/**
* АРМ "Каталогизатор".
*/
const val Cataloger: Byte = 67 // 'C'
/**
* Апплет Java.
*/
const val JavaAppllet: Byte = 74 // 'J'
/**
* АРМ "Книгообеспеченность".
*/
const val Provision: Byte = 75 // 'K'
/**
* АРМ "Комплектатор".
*/
const val Acquisitions: Byte = 77 // 'M'
/**
* АРМ "Читатель".
*/
const val Reader: Byte = 82 // 'R'
// СТАТУСЫ ЗАПИСЕЙ
/**
* Нет статуса записи (все нули).
*/
const val NO_STATUS = 0
/**
* Запись логически удалена.
*/
const val LOGICALLY_DELETED = 1
/**
* Запись физически удалена.
*/
const val PHYSICALLY_DELETED = 2
/**
* Запись отсутствует.
*/
const val ABSENT = 4
/**
* Запись не актуализирована.
*/
const val NON_ACTUALIZED = 8
/**
* Последняя версия записи.
*/
const val LAST_VERSION = 32
/**
* Запись заблокирована.
*/
const val LOCKED = 64
/**
* Ошибка в Autoin.gbl.
*/
const val AutoinError = 128
/**
* Полный текст не актуализирован.
*/
const val FullTextNotActualized = 256
// ОТДЕЛЬНЫЕ СИМВОЛЫ
/**
* Is digit from 0 to 9?
*/
@Contract(pure = true)
fun isArabicDigit(c: Char) = c in '0'..'9'
/**
* Is letter from A to Z or a to z?
*/
@Contract(pure = true)
fun isLatinLetter(c: Char) = (c in 'A'..'Z' || c in 'a'..'z')
/**
* Is digit from 0 to 9
* or letter from A to Z or a to z?
*/
@Contract(pure = true)
fun isLatinLetterOrArabicDigit(c: Char) = c in '0'..'9'
|| c in 'A'..'Z' || c in 'a'..'z'
/**
* Is letter from А to Я or а to я?
*/
@Contract(pure = true)
fun isRussianLetter(c: Char) = c in 'А'..'я' || c == 'Ё' || c == 'ё'
// СТРОКИ
/**
* Превращаем пустую строку в null.
*
* @param text Текст для проверки.
* @return Тот же текст либо null.
*/
@Contract(value = "null -> null", pure = true)
fun emptyToNull(text: String?): String? {
return if (text == null || text == "") {
null
} else text
}
/**
* Выбираем строку, не равную null (если такая вообще есть).
*
* @param first Первая строка.
* @param second Вторая строка.
* @return Та, которая не равна null.
*/
@Contract(value = "!null, _ -> !null", pure = true)
fun iif(first: String?, second: String?): String? {
return first ?: second
}
/**
* Выбираем строку, не равную null (если такая вообще есть).
*
* @param first Первая строка.
* @param second Вторая строка.
* @param third Третья строка.
* @return Та, которая не равна null.
*/
@Contract(value = "!null, _, _ -> !null; null, !null, _ -> !null", pure = true)
fun iif(first: String?, second: String?, third: String?): String? {
return first ?: (second ?: third)
}
/**
* Строка пустая или равна null?
*
* @param text Проверяемая строка.
* @return true, если пустая или равна null.
*/
@Contract(value = "null -> true", pure = true)
fun isNullOrEmpty(text: String?): Boolean {
return text == null || text.length == 0
}
@Contract(pure = true)
fun sameString(s1: String?, s2: String?): Boolean {
if (s1 === s2) {
return true
}
return if (s1 == null || s2 == null) {
false
} else s1.compareTo(s2, ignoreCase = true) == 0
}
/**
* Безопасное сравнение строк (любая из них может быть равна null).
*
* @param left Первая строка.
* @param right Вторая строка.
* @return Результат сравнения.
*/
@Contract(pure = true)
fun safeCompare(left: String?, right: String?): Int {
if (left == null) {
return if (right == null) {
0
} else -1
}
return if (right == null) {
1
} else left.compareTo(right)
}
/**
* Безопасное преобразование строки в целое число.
*
* @param text Строка
* @return Результат преобразования
*/
fun safeParseInt32(text: String?): Int {
if (isNullOrEmpty(text)) {
return 0
}
val result: Int
result = try {
text!!.toInt()
} catch (ex: Exception) {
0
}
return result
}
@Contract(pure = true)
fun nullToEmpty(value: String?): String {
return value ?: ""
}
fun nullableToString(value: Any?): String? {
return value?.toString()
}
fun toVisible(value: Any?): String {
return value?.toString() ?: "(null)"
}
/**
* Сравнение подполей для сортировки.
*
* @param subField1 Первое подполе.
* @param subField2 Второе подполе.
* @return Результат сравнения.
*/
@Contract(pure = true)
fun compareSubFields(subField1: SubField, subField2: SubField): Int {
var result = compareCodes(subField1.code, subField2.code)
if (result != 0) {
return result
}
result = subField1.value!!.compareTo(subField2.value!!)
return result
}
/**
* Сравнение кодов подполей.
*
* @param code1 Первый код.
* @param code2 Второй код.
* @return Результат сравнения.
*/
@Contract(pure = true)
fun compareCodes(code1: Char, code2: Char): Int {
return Character.compare(normalizeCode(code1), normalizeCode(code2))
}
/**
* Нормализация кода подполя.
*
* @param code Исходный код.
* @return Нормализованный код.
*/
@Contract(pure = true)
fun normalizeCode(code: Char): Char {
return code.lowercaseChar()
}
| 0
|
Kotlin
|
0
| 0
|
f408f3d6c983143aa2f263f50009e42407118753
| 7,059
|
KotIrbis
|
MIT License
|
app/src/main/java/com/sorbonne/atom_d/adapters/double_column/AdapterDoubleColumn.kt
|
tlagos1
| 555,409,019
| false
|
{"Kotlin": 158625, "Java": 4277}
|
package com.sorbonne.atom_d.adapters.double_column
import android.annotation.SuppressLint
import android.util.Log
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.RadioButton
import androidx.recyclerview.widget.ListAdapter
import com.sorbonne.atom_d.R
import com.sorbonne.atom_d.adapters.EntityComparator
import com.sorbonne.atom_d.adapters.AdapterType
import com.sorbonne.atom_d.entities.custom_queries.CustomQueriesDao
import com.sorbonne.atom_d.view_holders.DoubleColumnViewHolder
class AdapterDoubleColumn(
private val doubleColumnType: DoubleColumnViewHolder.DoubleColumnType,
private val adapterType: AdapterType
): ListAdapter<Any, DoubleColumnViewHolder>(EntityComparator(adapterType)) {
private var TAG = AdapterDoubleColumn::class.simpleName
private var lastCheckedPosition = mutableMapOf<String, Int>()
private val checkedBoxes = mutableListOf<String>()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DoubleColumnViewHolder {
return DoubleColumnViewHolder.create(parent, doubleColumnType)
}
@SuppressLint("RecyclerView")
override fun onBindViewHolder(holder: DoubleColumnViewHolder, position: Int) {
val current = getItem(position)
when(adapterType){
AdapterType.CustomQueries ->{
current as CustomQueriesDao.AllExperimentsName
when(doubleColumnType){
DoubleColumnViewHolder.DoubleColumnType.RadioButtonTextView -> {
holder.bind(current.experiment_name, current.type, doubleColumnType,position == lastCheckedPosition[adapterType.name])
val item: RadioButton = holder.itemView.findViewById(R.id.Data_Radio)
item.setOnClickListener{
lastCheckedPosition[adapterType.name]?.let { mLastCheckedPosition ->
notifyItemChanged(mLastCheckedPosition)
}
notifyItemChanged(position)
lastCheckedPosition[adapterType.name] = position
}
}
DoubleColumnViewHolder.DoubleColumnType.TextViewTextView -> {
holder.bind(current.experiment_name, current.type, doubleColumnType)
}
else -> {
TODO()
}
}
}
AdapterType.DynamicList -> {
when(doubleColumnType) {
DoubleColumnViewHolder.DoubleColumnType.CheckBoxTextView -> {
current as List<*>
holder.bind(current, doubleColumnType, checkedBoxes.contains(current[0].toString()))
val item: CheckBox = holder.itemView.findViewById(R.id.Data_checkBox)
item.setOnClickListener{ mCheckBox ->
mCheckBox as CheckBox
if(mCheckBox.isChecked){
if(!checkedBoxes.contains(current[0].toString())){
checkedBoxes.add(current[0].toString())
}
} else {
checkedBoxes.remove(current[0].toString())
}
}
}
DoubleColumnViewHolder.DoubleColumnType.RadioButtonTextView -> {
current as List<*>
holder.bind(current, doubleColumnType, position == lastCheckedPosition[adapterType.name])
val item: RadioButton = holder.itemView.findViewById(R.id.Data_Radio)
item.setOnClickListener{
lastCheckedPosition[adapterType.name]?.let { mLastCheckedPosition ->
notifyItemChanged(mLastCheckedPosition)
}
notifyItemChanged(position)
lastCheckedPosition[adapterType.name] = position
}
}
else -> {
TODO()
}
}
}
else -> {
TODO()
}
}
}
override fun onCurrentListChanged(previousList: MutableList<Any>, currentList: MutableList<Any>) {
super.onCurrentListChanged(previousList, currentList)
when(adapterType){
AdapterType.DynamicList ->{
val currentListIds = mutableListOf<String>()
currentList.forEach {
it as List<*>
currentListIds.add(it[0].toString())
}
for (index in 0 until checkedBoxes.size){
if(!currentListIds.contains(checkedBoxes[index])){
checkedBoxes.removeAt(index)
break
}
}
}
else ->{
}
}
}
fun updateBandwidthItem(endPointId: String, data: Int){
for(index in 0 until itemCount){
val item = getItem(index) as MutableList<String>
if(item[0] == endPointId){
item[2] = data.toString()
notifyItemChanged(index, item)
}
}
}
fun getLastCheckedPosition(): Int {
lastCheckedPosition[adapterType.name]?.let {
return it
}
return -1
}
fun getCheckedBoxes(): List<String> {
return checkedBoxes
}
}
| 0
|
Kotlin
|
0
| 0
|
9852f4d9926f077cf613f14705f890f417060daa
| 5,726
|
AtomD
|
MIT License
|
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppsmanageadjudicationsapi/services/migrate/MigrateNewRecordService.kt
|
ministryofjustice
| 416,301,250
| false
| null |
package uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.services.migrate
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.controllers.ChargeNumberMapping
import uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.controllers.HearingMapping
import uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.controllers.MigrateResponse
import uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.controllers.PunishmentMapping
import uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.dtos.AdjudicationMigrateDto
import uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.dtos.MigrateDamage
import uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.dtos.MigrateEvidence
import uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.dtos.MigrateHearing
import uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.dtos.MigrateHearingResult
import uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.dtos.MigrateOffence
import uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.dtos.MigratePrisoner
import uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.dtos.MigratePunishment
import uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.dtos.MigrateWitness
import uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.dtos.NomisGender
import uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.entities.Gender
import uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.entities.Hearing
import uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.entities.HearingOutcome
import uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.entities.HearingOutcomeAdjournReason
import uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.entities.HearingOutcomeCode
import uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.entities.HearingOutcomePlea
import uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.entities.Outcome
import uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.entities.OutcomeCode
import uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.entities.PrivilegeType
import uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.entities.Punishment
import uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.entities.PunishmentComment
import uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.entities.PunishmentSchedule
import uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.entities.PunishmentType
import uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.entities.ReportedAdjudication
import uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.entities.ReportedAdjudicationStatus
import uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.entities.ReportedDamage
import uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.entities.ReportedEvidence
import uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.entities.ReportedOffence
import uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.entities.ReportedWitness
import uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.gateways.Finding
import uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.gateways.OicSanctionCode
import uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.gateways.Plea
import uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.gateways.Status
import uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.repositories.ReportedAdjudicationRepository
import uk.gov.justice.digital.hmpps.hmppsmanageadjudicationsapi.services.draft.DraftAdjudicationService
@Transactional
@Service
class MigrateNewRecordService(
private val reportedAdjudicationRepository: ReportedAdjudicationRepository,
) {
fun accept(adjudicationMigrateDto: AdjudicationMigrateDto): MigrateResponse {
val chargeNumber = adjudicationMigrateDto.getChargeNumber()
val punishmentsAndComments = adjudicationMigrateDto.punishments.toPunishments()
val punishments = punishmentsAndComments.first
val punishmentComments = punishmentsAndComments.second
val hearingsAndResultsAndOutcomes = adjudicationMigrateDto.hearings.sortedBy { it.hearingDateTime }.toHearingsAndResultsAndOutcomes(
agencyId = adjudicationMigrateDto.agencyId,
chargeNumber = chargeNumber,
)
val hearingsAndResults = hearingsAndResultsAndOutcomes.first
val outcomes = hearingsAndResultsAndOutcomes.second
val reportedAdjudication = ReportedAdjudication(
chargeNumber = chargeNumber,
agencyIncidentId = adjudicationMigrateDto.agencyIncidentId,
prisonerNumber = adjudicationMigrateDto.prisoner.prisonerNumber,
offenderBookingId = adjudicationMigrateDto.bookingId,
originatingAgencyId = adjudicationMigrateDto.agencyId,
overrideAgencyId = adjudicationMigrateDto.getOverrideAgencyId(),
dateTimeOfDiscovery = adjudicationMigrateDto.incidentDateTime,
dateTimeOfIncident = adjudicationMigrateDto.incidentDateTime,
incidentRoleCode = null,
incidentRoleAssociatedPrisonersNumber = null,
incidentRoleAssociatedPrisonersName = null,
damages = adjudicationMigrateDto.damages.toDamages(),
evidence = adjudicationMigrateDto.evidence.toEvidence(),
witnesses = adjudicationMigrateDto.witnesses.toWitnesses(),
disIssueHistory = mutableListOf(),
status = ReportedAdjudicationStatus.UNSCHEDULED,
handoverDeadline = DraftAdjudicationService.daysToActionFromIncident(adjudicationMigrateDto.incidentDateTime),
gender = adjudicationMigrateDto.prisoner.getGender(),
hearings = hearingsAndResults.toMutableList(),
isYouthOffender = adjudicationMigrateDto.offence.getIsYouthOffender(),
locationId = adjudicationMigrateDto.locationId,
outcomes = outcomes.toMutableList(),
statement = adjudicationMigrateDto.statement,
offenceDetails = mutableListOf(adjudicationMigrateDto.offence.getOffenceDetails()),
migrated = true,
punishments = punishments.toMutableList(),
punishmentComments = punishmentComments.toMutableList(),
).also {
it.calculateStatus()
}
val saved = reportedAdjudicationRepository.save(reportedAdjudication).also {
it.createDateTime = adjudicationMigrateDto.reportedDateTime
it.createdByUserId = adjudicationMigrateDto.reportingOfficer.username
}
return MigrateResponse(
chargeNumberMapping = adjudicationMigrateDto.toChargeMapping(chargeNumber),
hearingMappings = saved.hearings.toHearingMappings(),
punishmentMappings = saved.getPunishments().toPunishmentMappings(adjudicationMigrateDto.bookingId),
)
}
companion object {
fun createAdjourn(adjudicator: String?): HearingOutcome =
HearingOutcome(
code = HearingOutcomeCode.ADJOURN,
adjudicator = adjudicator ?: "",
plea = HearingOutcomePlea.NOT_ASKED,
reason = HearingOutcomeAdjournReason.OTHER,
details = "No hearing result created in NOMIS",
)
fun AdjudicationMigrateDto.toChargeMapping(chargeNumber: String) = ChargeNumberMapping(
oicIncidentId = this.oicIncidentId,
chargeNumber = chargeNumber,
offenceSequence = this.offenceSequence,
)
fun List<Hearing>.toHearingMappings() = this.map {
HearingMapping(hearingId = it.id!!, oicHearingId = it.oicHearingId!!)
}
fun List<Punishment>.toPunishmentMappings(offenderBookingId: Long) = this.map {
PunishmentMapping(punishmentId = it.id!!, sanctionSeq = it.sanctionSeq!!, bookingId = offenderBookingId)
}
fun AdjudicationMigrateDto.getChargeNumber(): String = "${this.oicIncidentId}-${this.offenceSequence}"
fun MigrateOffence.getIsYouthOffender(): Boolean = this.offenceCode.startsWith("55:")
fun MigratePrisoner.getGender(): Gender =
when (this.gender) {
NomisGender.F.name -> Gender.FEMALE
else -> Gender.MALE
}
fun AdjudicationMigrateDto.getOverrideAgencyId(): String? {
this.prisoner.currentAgencyId ?: return null
return if (this.agencyId != this.prisoner.currentAgencyId) this.prisoner.currentAgencyId else null
}
fun List<MigrateDamage>.toDamages(): MutableList<ReportedDamage> =
this.map {
ReportedDamage(
code = it.damageType,
details = it.details ?: "No recorded details",
reporter = it.createdBy,
)
}.toMutableList()
fun List<MigrateEvidence>.toEvidence(): MutableList<ReportedEvidence> =
this.map {
ReportedEvidence(
code = it.evidenceCode,
details = it.details,
reporter = it.reporter,
)
}.toMutableList()
fun List<MigrateWitness>.toWitnesses(): MutableList<ReportedWitness> =
this.map {
ReportedWitness(
firstName = it.firstName,
lastName = it.lastName,
reporter = it.createdBy,
code = it.witnessType,
)
}.toMutableList()
fun MigrateOffence.getOffenceDetails(): ReportedOffence {
return ReportedOffence(
offenceCode = 0,
victimPrisonersNumber = null,
victimStaffUsername = null,
nomisOffenceCode = this.offenceCode,
nomisOffenceDescription = this.offenceDescription,
)
}
fun List<MigrateHearing>.toHearingsAndResultsAndOutcomes(agencyId: String, chargeNumber: String): Pair<List<Hearing>, List<Outcome>> {
this.validate()
val hearingsAndResults = mutableListOf<Hearing>()
val outcomes = mutableListOf<Outcome>()
for ((index, oicHearing) in this.withIndex()) {
val hasAdditionalHearings = index < this.size - 1
val hasAdditionalHearingOutcomes = this.hasAdditionalOutcomesAndFinalOutcomeIsNotQuashed(index)
val hearingOutcomeAndOutcome = when (oicHearing.hearingResult) {
null -> if (hasAdditionalHearings) Pair(createAdjourn(oicHearing.adjudicator), null) else null
else -> {
val hearingOutcomeCode = oicHearing.hearingResult.finding.mapToHearingOutcomeCode(hasAdditionalHearingOutcomes)
Pair(
HearingOutcome(
code = hearingOutcomeCode,
adjudicator = oicHearing.adjudicator ?: "",
plea = oicHearing.hearingResult.plea.mapToPlea(),
),
oicHearing.hearingResult.mapToOutcome(hearingOutcomeCode),
)
}
}
hearingOutcomeAndOutcome?.second.let {
it?.let { outcome ->
outcomes.add(outcome)
oicHearing.hearingResult!!.createAdditionalOutcome(hasAdditionalHearings)?.let { additionalOutcome ->
outcomes.add(additionalOutcome)
}
}
}
hearingsAndResults.add(
Hearing(
dateTimeOfHearing = oicHearing.hearingDateTime,
locationId = oicHearing.locationId,
oicHearingType = oicHearing.oicHearingType,
oicHearingId = oicHearing.oicHearingId,
agencyId = agencyId,
chargeNumber = chargeNumber,
hearingOutcome = hearingOutcomeAndOutcome?.first,
),
)
}
return Pair(hearingsAndResults, outcomes)
}
fun List<MigratePunishment>.toPunishments(): Pair<List<Punishment>, List<PunishmentComment>> {
val punishments = mutableListOf<Punishment>()
val punishmentComments = mutableListOf<PunishmentComment>()
this.forEach { sanction ->
punishments.add(sanction.mapToPunishment())
sanction.comment?.let {
punishmentComments.add(PunishmentComment(comment = it))
}
}
return Pair(punishments, punishmentComments)
}
fun List<MigrateHearing>.hasAdditionalOutcomesAndFinalOutcomeIsNotQuashed(index: Int): Boolean =
index < this.size - 1 && this.none { it.hearingResult == null } && this.last().hearingResult?.finding != Finding.QUASHED.name
/*
Note: this is a placeholder, awaiting further discovery of nomis data to expand on rules
Currently allows REF_POLICE and QUASHED to be processed, pending discovery
*/
private fun List<MigrateHearing>.validate() {
val listOfExceptionStatus = listOf(Finding.PROVED.name, Finding.D.name, Finding.NOT_PROCEED.name).toMutableList()
if (this.count { it.hearingResult != null } < 2) return
if (this.filter { it.hearingResult != null }.any { listOf(Finding.REF_POLICE.name, Finding.QUASHED.name).contains(it.hearingResult!!.finding) }) return
val firstResult = this.first { it.hearingResult != null }
listOfExceptionStatus.removeIf { it == firstResult.hearingResult!!.finding }
if (this.filter { it.hearingResult != null }.any { listOfExceptionStatus.contains(it.hearingResult!!.finding) }) {
throw UnableToMigrateException("Currently unable to migrate due to results structure")
}
}
fun MigrateHearingResult.mapToOutcome(hearingOutcomeCode: HearingOutcomeCode): Outcome? =
when (hearingOutcomeCode) {
HearingOutcomeCode.ADJOURN, HearingOutcomeCode.NOMIS -> null
else -> Outcome(code = this.finding.mapToOutcomeCode(), actualCreatedDate = this.createdDateTime)
}
private fun String.mapToOutcomeCode(): OutcomeCode = when (this) {
Finding.PROVED.name, Finding.QUASHED.name -> OutcomeCode.CHARGE_PROVED
Finding.D.name -> OutcomeCode.DISMISSED
Finding.NOT_PROCEED.name -> OutcomeCode.NOT_PROCEED
Finding.REF_POLICE.name, Finding.PROSECUTED.name -> OutcomeCode.REFER_POLICE
else -> throw UnableToMigrateException("issue with outcome code mapping $this")
}
fun MigrateHearingResult.createAdditionalOutcome(hasAdditionalHearings: Boolean): Outcome? = when (this.finding) {
Finding.QUASHED.name -> Outcome(code = OutcomeCode.QUASHED, actualCreatedDate = this.createdDateTime.plusMinutes(1))
Finding.PROSECUTED.name -> Outcome(code = OutcomeCode.PROSECUTION, actualCreatedDate = this.createdDateTime.plusMinutes(1))
Finding.REF_POLICE.name -> if (hasAdditionalHearings) Outcome(code = OutcomeCode.SCHEDULE_HEARING, actualCreatedDate = this.createdDateTime.plusMinutes(1)) else null
else -> null
}
fun String.mapToHearingOutcomeCode(hasAdditionalHearingOutcomes: Boolean): HearingOutcomeCode = when (this) {
Finding.QUASHED.name -> HearingOutcomeCode.COMPLETE // TODO further discovery around nomis UNQUASHED
Finding.PROVED.name, Finding.D.name, Finding.NOT_PROCEED.name ->
if (hasAdditionalHearingOutcomes) HearingOutcomeCode.ADJOURN else HearingOutcomeCode.COMPLETE
Finding.PROSECUTED.name, Finding.REF_POLICE.name -> HearingOutcomeCode.REFER_POLICE
else -> throw UnableToMigrateException("To confirm default with John, given appeals and other such statuses")
}
private fun String.mapToPlea(): HearingOutcomePlea = when (this) {
Plea.NOT_GUILTY.name -> HearingOutcomePlea.NOT_GUILTY
Plea.GUILTY.name -> HearingOutcomePlea.GUILTY
Plea.NOT_ASKED.name -> HearingOutcomePlea.NOT_ASKED
Plea.UNFIT.name -> HearingOutcomePlea.UNFIT
Plea.REFUSED.name -> HearingOutcomePlea.ABSTAIN
else -> TODO("TO confirm with John default case, and issue where result can also be a plea")
}
private fun MigratePunishment.mapToPunishment(): Punishment {
val prospectiveStatuses = listOf(Status.PROSPECTIVE.name, Status.SUSP_PROSP.name)
val typesWithoutDates = PunishmentType.additionalDays().plus(PunishmentType.CAUTION)
val type = when (this.sanctionCode) {
OicSanctionCode.ADA.name -> if (prospectiveStatuses.contains(this.sanctionStatus)) PunishmentType.PROSPECTIVE_DAYS else PunishmentType.ADDITIONAL_DAYS
OicSanctionCode.EXTRA_WORK.name -> PunishmentType.EXCLUSION_WORK
OicSanctionCode.EXTW.name -> PunishmentType.EXTRA_WORK
OicSanctionCode.CAUTION.name -> PunishmentType.CAUTION
OicSanctionCode.CC.name -> PunishmentType.CONFINEMENT
OicSanctionCode.REMACT.name -> PunishmentType.REMOVAL_ACTIVITY
OicSanctionCode.REMWIN.name -> PunishmentType.REMOVAL_WING
OicSanctionCode.STOP_PCT.name -> PunishmentType.EARNINGS
else -> PunishmentType.PRIVILEGE
}
val suspendedUntil = when (this.sanctionStatus) {
Status.SUSPENDED.name, Status.SUSP_PROSP.name -> this.effectiveDate
else -> null
}
val startDate = when (this.sanctionStatus) {
Status.SUSPENDED.name, Status.SUSP_PROSP.name -> null
else -> if (typesWithoutDates.contains(type)) null else this.effectiveDate
}
val endDate = when (this.sanctionStatus) {
Status.SUSPENDED.name, Status.SUSP_PROSP.name -> null
else -> if (typesWithoutDates.contains(type)) null else this.effectiveDate.plusDays((this.days ?: 0).toLong())
}
val stoppagePercentage = when (type) {
PunishmentType.EARNINGS -> this.compensationAmount
else -> null
}
val privilegeType = when (type) {
PunishmentType.PRIVILEGE -> PrivilegeType.OTHER
else -> null
}
val otherPrivilege = when (type) {
PunishmentType.PRIVILEGE -> this.sanctionCode
else -> null
}
return Punishment(
type = type,
consecutiveChargeNumber = this.consecutiveChargeNumber,
stoppagePercentage = stoppagePercentage?.toInt(),
sanctionSeq = this.sanctionSeq,
suspendedUntil = suspendedUntil,
privilegeType = privilegeType,
otherPrivilege = otherPrivilege,
schedule = mutableListOf(
PunishmentSchedule(days = this.days ?: 0, startDate = startDate, endDate = endDate, suspendedUntil = suspendedUntil),
),
)
}
}
}
| 2
|
Kotlin
|
0
| 3
|
fc46931a8d940ffe3d2f14b497fc6d23f81212fa
| 17,786
|
hmpps-manage-adjudications-api
|
MIT License
|
audio-recording-server-api/src/main/kotlin/com/project/audiorecording/audiorecordingserver/domain/dto/DiscDto.kt
|
kshchuk
| 701,072,615
| false
|
{"Kotlin": 88429, "PLpgSQL": 2408}
|
package com.project.audiorecording.audiorecordingserver.domain.dto
import java.io.Serializable
import java.time.Duration
import java.util.*
/**
* DTO for {@link com.project.audiorecording.audiorecordingserver.domain.entity.Disc}
*/
data class DiscDto(
var id: UUID? = null,
var name: String? = null,
var trackNumber: Int? = null,
var totalDuration: Duration? = null
) : Serializable
| 0
|
Kotlin
|
0
| 0
|
ec0f5b595b955b49c1ad06d21059c046f669a799
| 402
|
audio-recording-app
|
Apache License 2.0
|
skiko/src/jvmMain/kotlin/org/jetbrains/skija/paragraph/PositionWithAffinity.kt
|
pa-dieter
| 403,520,837
| true
|
{"Kotlin": 948892, "C++": 478268, "Objective-C++": 20299, "Dockerfile": 2368, "Shell": 555}
|
package org.jetbrains.skia.paragraph
class PositionWithAffinity(val position: Int, affinity: Affinity) {
val _affinity: Affinity
val affinity: Affinity
get() = _affinity
override fun equals(o: Any?): Boolean {
if (o === this) return true
if (o !is PositionWithAffinity) return false
val other = o
if (!other.canEqual(this as Any)) return false
if (position != other.position) return false
val `this$_affinity`: Any = affinity
val `other$_affinity`: Any = other.affinity
return `this$_affinity` == `other$_affinity`
}
protected fun canEqual(other: Any?): Boolean {
return other is PositionWithAffinity
}
override fun hashCode(): Int {
val PRIME = 59
var result = 1
result = result * PRIME + position
val `$_affinity`: Any = affinity
result = result * PRIME + (`$_affinity`?.hashCode())
return result
}
override fun toString(): String {
return "PositionWithAffinity(_position=$position, _affinity=$affinity)"
}
init {
_affinity = affinity
}
}
| 0
| null |
0
| 0
|
c9dda21dea90abfa68db1fdf8932d8f12141c1f8
| 1,138
|
skiko
|
Apache License 2.0
|
backend/app/src/test/kotlin/io/tolgee/repository/dataImport/ImportRepositoryTest.kt
|
tolgee
| 303,766,501
| false
| null |
package io.tolgee.repository.dataImport
import io.tolgee.AbstractSpringTest
import io.tolgee.model.dataImport.Import
import io.tolgee.testing.assertions.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.transaction.annotation.Transactional
@SpringBootTest
@Transactional
class ImportRepositoryTest : AbstractSpringTest() {
@Autowired
lateinit var importRepository: ImportRepository
@Test
fun `creates, saves and gets Import entity`() {
val base = dbPopulator.createBase("hello", "importUser")
Import(author = base.userOwner!!, project = base).let {
importRepository.save(it).let {
importRepository.getOne(it.id).let { got ->
assertThat(got.author).isEqualTo(base.userOwner)
assertThat(got.project).isEqualTo(base)
assertThat(got.id).isGreaterThan(0L)
}
}
}
}
}
| 50
|
Kotlin
|
4
| 292
|
9896609f260b1ff073134e672303ff8810afc5a1
| 1,000
|
server
|
Apache License 2.0
|
app/src/main/java/ch/abwesend/privatecontacts/view/screens/contactedit/components/ContactEditCommonComponents.kt
|
fgubler
| 462,182,037
| false
|
{"Kotlin": 1163443, "Java": 369326}
|
/*
* Private Contacts
* Copyright (c) 2022.
* <NAME>
*/
package ch.abwesend.privatecontacts.view.screens.contactedit.components
import androidx.annotation.StringRes
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material.Icon
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import ch.abwesend.privatecontacts.view.components.ExpandableCard
import ch.abwesend.privatecontacts.view.theme.AppColors
object ContactEditCommonComponents {
private val primaryIconModifier = Modifier.width(60.dp)
private val iconHorizontalPadding = 20.dp
val secondaryIconModifier = Modifier.width(40.dp)
val textFieldModifier = Modifier.padding(bottom = 2.dp)
@Composable
fun ContactCategory(
@StringRes categoryTitle: Int,
icon: ImageVector,
modifier: Modifier = Modifier,
initiallyExpanded: Boolean = true,
alignContentWithTitle: Boolean = true,
content: @Composable () -> Unit
) {
var expanded by remember { mutableStateOf(initiallyExpanded) }
ExpandableCard(
expanded = expanded,
modifier = modifier,
onToggleExpanded = { expanded = it },
header = { ContactCategoryHeader(title = categoryTitle, icon = icon) }
) {
Row(modifier = Modifier.fillMaxWidth()) {
if (alignContentWithTitle) {
Spacer(modifier = primaryIconModifier.padding(end = iconHorizontalPadding))
} else {
Spacer(modifier = Modifier.padding(end = 5.dp))
}
Surface(modifier = Modifier.padding(end = 5.dp)) {
content()
}
}
}
}
@Composable
fun ContactCategoryHeader(
@StringRes title: Int,
icon: ImageVector,
) {
Row {
Icon(
imageVector = icon,
contentDescription = stringResource(id = title),
modifier = primaryIconModifier.padding(end = iconHorizontalPadding),
tint = AppColors.greyText
)
Column(modifier = Modifier.weight(1.0f)) {
Text(text = stringResource(id = title))
}
}
}
}
| 0
|
Kotlin
|
1
| 9
|
49b98707f8cd250f7f15279c4b9e61fef41f1fb1
| 2,925
|
PrivateContacts
|
Apache License 2.0
|
src/main/kotlin/com/aphisiit/springkafka/service/KafkaProducer.kt
|
aphisiit
| 744,406,846
| false
|
{"Kotlin": 20431, "Dockerfile": 267}
|
package com.aphisiit.springkafka.service
import org.springframework.stereotype.Service
@Service
class KafkaProducer {
fun send() {
}
}
| 0
|
Kotlin
|
0
| 0
|
2545d30f5507cc3d29c70d36173b8d38d63e648b
| 140
|
spring-kafka-producer
|
MIT License
|
src/main/kotlin/com/miguel/rucoyapi/controllers/CreatureProfileController.kt
|
MiguelJeronimo
| 705,820,521
| false
|
{"Kotlin": 132389, "Dockerfile": 869}
|
package com.miguel.rucoyapi.controllers
import com.miguel.rucoyapi.model.responses
import com.miguel.rucoyapi.repository.Repository
import org.apache.coyote.Response
import org.apache.logging.log4j.LogManager
import org.apache.logging.log4j.Logger
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RestController
import kotlin.math.log
@RestController
class CreatureProfileController {
private val logger: Logger = LogManager.getLogger(CreatureProfileController::class.java)
@GetMapping("api/v1/creature/{name}")
fun getCreatureProfile(@PathVariable name: String): Any {
logger.info("init petition: api/v1/creature/${name}")
return try {
if (name != null){
val searchCharacters = Repository().creatureProfile(name)
return when(searchCharacters?.name){
null->{
logger.error("Error: ${responses.Errors(400, "Creature is not exist")}")
ResponseEntity.badRequest().body(responses.Errors(400, "Creature is not exist"))
}
else->{
logger.info("Final response success:")
ResponseEntity.ok().body(responses.response(200, searchCharacters))
}
}
} else{
logger.error("Error: ${responses.Errors(400, "Insert Name Character")}")
ResponseEntity.badRequest().body(responses.Errors(400, "Insert Name Character"))
}
} catch (e: Exception){
logger.fatal("Failure by: ${e.stackTraceToString()}")
ResponseEntity.internalServerError().body(responses.Errors(500, e.stackTraceToString()))
}
}
@GetMapping("api/v1/creature")
fun getCreature(): Any {
logger.info("init petition: api/v1/creature")
return try {
logger.error("Error: ${responses.Errors(400, "Not creature name valid")}")
ResponseEntity.badRequest().body(responses.Errors(400, "Not creature name valid"))
} catch (e: Exception){
logger.fatal("Failure by: ${e.stackTraceToString()}")
ResponseEntity.internalServerError().body(responses.Errors(500, e.stackTraceToString()))
}
}
}
| 0
|
Kotlin
|
0
| 0
|
c05ea4415138a2c6b032f9576079b2b7d955f0d0
| 2,436
|
rucoy-api
|
MIT License
|
data/src/main/java/com/nemesis/rio/data/database/asset/AssetDatabaseChecksumStorage.kt
|
N3-M3-S1S
| 370,791,918
| false
| null |
package com.nemesis.rio.data.database.asset
import android.content.SharedPreferences
import androidx.core.content.edit
class AssetDatabaseChecksumStorage(private val sharedPreferences: SharedPreferences) {
private val assetDatabaseChecksumKey = "asset_db_checksum"
fun getLastSavedChecksum(): String? =
sharedPreferences.getString(assetDatabaseChecksumKey, null)
fun saveChecksum(checksum: String) {
sharedPreferences.edit { putString(assetDatabaseChecksumKey, checksum) }
}
}
| 0
|
Kotlin
|
0
| 0
|
62dc309a7b4b80ff36ea624bacfa7b00b5d8607e
| 513
|
rio
|
MIT License
|
src/main/kotlin/edu/antevortadb/patient/stain/BaseStain.kt
|
spg63
| 115,169,375
| false
| null |
package edu.antevortadb.patient.stain
// Allow inheritance
open class BaseStain {
protected val abbrev: String
protected val fullName: String
constructor(shortName: String, fullName: String){
this.abbrev = shortName
this.fullName = fullName
}
}
| 0
|
Kotlin
|
0
| 0
|
f6e44c140b8828f00d184b19b3d4e3466af52dff
| 278
|
antevorta-db
|
MIT License
|
src/main/kotlin/Vector.kt
|
AnnaPivetta
| 346,299,009
| false
| null |
import java.lang.IndexOutOfBoundsException
import kotlin.math.abs
import kotlin.math.sqrt
data class Vector(var x: Float = 0.0F, var y: Float = 0.0F, var z: Float = 0.0F) {
override fun toString(): String {
return "Vector ($x, $y, $z)"
}
fun isClose(other: Vector, epsilon: Float = 1e-10F): Boolean {
return abs(x - other.x) < epsilon && abs(y - other.y) < epsilon && abs(z - other.z) < epsilon
}
fun toNormal(): Normal {
return Normal (x, y, z)
}
operator fun plus(other: Vector): Vector {
return Vector(x + other.x, y + other.y, z + other.z)
}
operator fun minus(other: Vector): Vector {
return Vector(x - other.x, y - other.y, z - other.z)
}
operator fun unaryMinus(): Vector {
return Vector(-x, -y, -z)
}
operator fun times(scalar: Float): Vector {
return Vector(x * scalar, y * scalar, z * scalar)
}
operator fun times(other: Vector): Float {
return x * other.x + y * other.y + z * other.z
}
//Same implementation for multiple choice of usage
fun dot (other: Vector): Float {
return x * other.x + y * other.y + z * other.z
}
operator fun get(i : Int) : Float {
return when (i) {
0 -> x
1 -> y
2 -> z
else -> {
throw IndexOutOfBoundsException()
}
}
}
fun cross(other: Vector): Vector {
return Vector(
y * other.z - z * other.y,
z * other.x - x * other.z,
x * other.y - y * other.x
)
}
fun norm2(): Float {
return x * x + y * y + z * z
}
fun norm(): Float {
return sqrt(norm2())
}
fun normalize() {
val n = norm()
x /= n
y /= n
z /= n
}
}
| 2
|
Kotlin
|
0
| 3
|
a5a8dcc0dca404e45b5e1abdac91c7ddc4eb4945
| 1,837
|
KTracer
|
Apache License 2.0
|
app/src/main/java/net/skyscanner/backpack/demo/compose/CardStory.kt
|
Skyscanner
| 117,813,847
| false
| null |
/**
* Backpack for Android - Skyscanner's Design System
*
* Copyright 2018 Skyscanner 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 net.skyscanner.backpack.demo.compose
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import net.skyscanner.backpack.compose.card.BpkCard
import net.skyscanner.backpack.compose.card.BpkCardCorner
import net.skyscanner.backpack.compose.card.BpkCardElevation
import net.skyscanner.backpack.compose.card.BpkCardPadding
import net.skyscanner.backpack.compose.dividedcard.BpkDividedCard
import net.skyscanner.backpack.compose.text.BpkText
import net.skyscanner.backpack.compose.theme.BpkTheme
import net.skyscanner.backpack.compose.tokens.BpkSpacing
import net.skyscanner.backpack.demo.R
@Composable
@Preview
fun CardStory() {
Column(
modifier = Modifier
.background(BpkTheme.colors.line)
.padding(horizontal = BpkSpacing.Base, vertical = BpkSpacing.Xxl),
verticalArrangement = Arrangement.spacedBy(BpkSpacing.Base),
) {
val cardModifier = Modifier
.fillMaxWidth()
.weight(1f)
SmallCornersCardExample(cardModifier)
LargeCornersCardExample(cardModifier)
NoPaddingCardExample(Modifier.fillMaxWidth())
NonClickableCardExample(cardModifier)
NoElevationCardExample(cardModifier)
FocusableCardExample(cardModifier)
DividedCardExample(cardModifier)
}
}
@Composable
@Preview
fun SmallCornersCardExample(
modifier: Modifier = Modifier,
) {
BpkCard(
modifier = modifier,
onClick = {},
contentAlignment = Alignment.Center,
) {
BpkText("Small corners")
}
}
@Composable
@Preview
fun LargeCornersCardExample(
modifier: Modifier = Modifier,
) {
BpkCard(
modifier = modifier,
onClick = {},
corner = BpkCardCorner.Large,
contentAlignment = Alignment.Center,
) {
BpkText("Large corners")
}
}
@Composable
@Preview
fun NoPaddingCardExample(
modifier: Modifier = Modifier,
) {
BpkCard(
modifier = modifier,
onClick = {},
padding = BpkCardPadding.None,
contentAlignment = Alignment.Center,
) {
BpkText("No padding")
}
}
@Composable
@Preview
fun NonClickableCardExample(
modifier: Modifier = Modifier,
) {
BpkCard(modifier, contentAlignment = Alignment.Center) {
BpkText("Non clickable")
}
}
@Composable
@Preview
fun FocusableCardExample(
modifier: Modifier = Modifier,
) {
var elevation by remember { mutableStateOf(BpkCardElevation.Focus) }
BpkCard(
modifier = modifier,
elevation = elevation,
contentAlignment = Alignment.Center,
onClick = {
elevation = when (elevation) {
BpkCardElevation.None, BpkCardElevation.Default -> BpkCardElevation.Focus
BpkCardElevation.Focus -> BpkCardElevation.Default
}
},
) {
BpkText(if (elevation == BpkCardElevation.Focus) "Tap to unfocus" else "Tap to focus")
}
}
@Composable
@Preview
fun NoElevationCardExample(
modifier: Modifier = Modifier,
) {
BpkCard(
modifier = modifier,
onClick = {},
contentAlignment = Alignment.Center,
elevation = BpkCardElevation.None,
) {
BpkText("No elevation")
}
}
@Composable
@Preview
fun DividedCardExample(
modifier: Modifier = Modifier,
) {
BpkDividedCard(
modifier = Modifier.fillMaxWidth(),
primaryContent = {
Spacer(modifier = Modifier.height(BpkSpacing.Xxl))
BpkText(
modifier = Modifier.fillMaxWidth(),
text = stringResource(id = R.string.divided_card_primary_content),
style = BpkTheme.typography.bodyDefault,
textAlign = TextAlign.Center,
)
},
secondaryContent = {
Spacer(modifier = Modifier.height(BpkSpacing.Xxl))
BpkText(
modifier = Modifier.fillMaxWidth(),
text = stringResource(id = R.string.divided_card_secondary_content),
style = BpkTheme.typography.bodyDefault,
textAlign = TextAlign.Center,
)
},
onClick = {},
)
}
| 5
|
Kotlin
|
31
| 80
|
47cfa7ac90005c9680eebcddb96fb50fb4e35d78
| 5,169
|
backpack-android
|
Apache License 2.0
|
presentation/src/main/kotlin/land/sungbin/faketoss/android/activity/IntroActivity.kt
|
faketoss
| 448,180,373
| false
|
{"Kotlin": 7660}
|
package land.sungbin.faketoss.android.activity
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.Text
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
class IntroActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
Text(text = "Bye world.")
}
}
}
}
| 0
|
Kotlin
|
0
| 2
|
bcb6089ed0deab1991cdacc991cb19243628ecab
| 701
|
faketoss-android
|
MIT License
|
src/test/kotlin/com/sbeins/DateparsingTest.kt
|
sbeins55
| 658,024,293
| false
| null |
package com.sbeins
import io.micronaut.runtime.EmbeddedApplication
import io.micronaut.test.extensions.kotest.annotation.MicronautTest
import io.kotest.core.spec.style.StringSpec
@MicronautTest
class DateparsingTest(private val application: EmbeddedApplication<*>) : StringSpec({
"test the server is running" {
assert(application.isRunning)
}
})
| 0
|
Kotlin
|
0
| 0
|
b2c5763e12acbb24415fd68edd5f6d51ead566b5
| 365
|
micronaut-aws-lambda
|
Apache License 2.0
|
app/src/main/java/com/serdar/rickandmorty_graphql/data/client/RickAndMortyClientImpl.kt
|
srdrakcay
| 619,132,116
| false
| null |
package com.serdar.rickandmorty_graphql.data.client
import com.apollographql.apollo3.ApolloClient
import com.rickandmorty_graphql.RickAndMortyCharacterQuery
import com.serdar.rickandmorty_graphql.data.NetworkResponse
import com.serdar.rickandmorty_graphql.data.dto.Character
import com.serdar.rickandmorty_graphql.data.mapper.toMap
import com.serdar.rickandmorty_graphql.domain.client.RickAndMortyClient
import javax.inject.Inject
class RickAndMortyClientImpl
@Inject constructor(
private val apolloClient: ApolloClient
): RickAndMortyClient {
override suspend fun getAllCharacterQuery(): List<Character>?{
return apolloClient
.query(RickAndMortyCharacterQuery())
.execute()
.data
?.characters
?.results
?.map {
it!!.toMap()
}
}
}
| 0
|
Kotlin
|
0
| 3
|
41c75091b1cad20baf33c5a64b1966b36782a475
| 857
|
RickAndMorty-GraphQL
|
MIT License
|
packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/text/internal/span/ReactAbsoluteSizeSpan.kt
|
react-native-tvos
| 177,633,560
| false
| null |
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.react.views.text.internal.span
import android.text.style.AbsoluteSizeSpan
/** Wraps [AbsoluteSizeSpan] as a [ReactSpan]. */
public class ReactAbsoluteSizeSpan(size: Int) : AbsoluteSizeSpan(size), ReactSpan
| 7
| null |
147
| 942
|
692bc66a98c8928c950bece9a22d04c13f0c579d
| 420
|
react-native-tvos
|
MIT License
|
src/main/kotlin/net/lfn3/leth/LogWriter.kt
|
lfn3
| 198,299,889
| false
| null |
package net.lfn3.leth
interface LogWriter<T> {
fun record(entry: T) : Long
/**
* This is a no-op if the returned value is null, or if the updated value == the existing one.
*/
fun update(getSequence: () -> Long, fn: (T) -> T): Pair<Long, T>
fun batchRecord(entries: Collection<T>) : Collection<Long> {
return entries.map { record(it) }
}
}
| 0
|
Kotlin
|
0
| 0
|
4c123098b1fccea9e3cea7220ea449df94a5703b
| 379
|
leth
|
Apache License 2.0
|
src/main/kotlin/zielu/gittoolbox/GitToolBoxPrj.kt
|
koalazub
| 341,766,854
| true
|
{"Java": 355922, "Kotlin": 312085, "HTML": 7800}
|
package zielu.gittoolbox
import com.intellij.openapi.Disposable
import com.intellij.openapi.project.Project
import zielu.gittoolbox.util.AppUtil
internal class GitToolBoxPrj : Disposable {
override fun dispose() {
// do nothing
}
companion object {
@JvmStatic
fun getInstance(project: Project): GitToolBoxPrj {
return AppUtil.getServiceInstance(project, GitToolBoxPrj::class.java)
}
}
}
| 0
| null |
0
| 0
|
c9dc7d2f7d77d5130288ae4d6ba3a9a8867314ba
| 420
|
GitToolBox
|
Apache License 2.0
|
app/src/main/java/com/arjanvlek/oxygenupdater/models/ServerStatus.kt
|
iGotYourBackMr
| 254,597,651
| true
|
{"Kotlin": 640563, "Java": 101703}
|
package com.arjanvlek.oxygenupdater.models
import android.content.Context
import androidx.core.content.ContextCompat
import com.arjanvlek.oxygenupdater.BuildConfig
import com.arjanvlek.oxygenupdater.R
import com.arjanvlek.oxygenupdater.utils.Utils
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonProperty
@JsonIgnoreProperties(ignoreUnknown = true)
data class ServerStatus(
var status: Status? = null,
var latestAppVersion: String? = null,
var automaticInstallationEnabled: Boolean = false,
var pushNotificationDelaySeconds: Int = 0
) : Banner {
@JsonProperty("push_notification_delay_seconds")
fun setPushNotificationDelaySeconds(pushNotificationDelaySeconds: String?) {
if (pushNotificationDelaySeconds != null && Utils.isNumeric(pushNotificationDelaySeconds)) {
this.pushNotificationDelaySeconds = pushNotificationDelaySeconds.toInt()
}
}
override fun getBannerText(context: Context) = when (status) {
Status.WARNING -> context.getString(R.string.server_status_warning)
Status.ERROR -> context.getString(R.string.server_status_error)
Status.MAINTENANCE -> ""
Status.OUTDATED -> ""
Status.UNREACHABLE -> context.getString(R.string.server_status_unreachable)
else -> ""
}
override fun getColor(context: Context) = when (status) {
Status.WARNING -> ContextCompat.getColor(context, R.color.colorWarn)
Status.ERROR -> ContextCompat.getColor(context, R.color.colorPrimary)
Status.MAINTENANCE -> 0
Status.OUTDATED -> 0
Status.UNREACHABLE -> ContextCompat.getColor(context, R.color.colorPrimary)
else -> 0
}
override fun getDrawableRes(context: Context) = when (status) {
Status.WARNING -> R.drawable.warning
Status.ERROR -> R.drawable.error_outline
Status.MAINTENANCE -> 0
Status.OUTDATED -> 0
Status.UNREACHABLE -> R.drawable.info
else -> 0
}
fun checkIfAppIsUpToDate() = try {
val appVersionNumeric = BuildConfig.VERSION_NAME.replace(".", "")
// handle custom buildConfigs
.split("-")[0]
.toInt()
val appVersionFromResultNumeric = latestAppVersion!!.replace(".", "").toInt()
appVersionFromResultNumeric <= appVersionNumeric
} catch (e: Exception) {
true
}
enum class Status {
NORMAL,
WARNING,
ERROR,
MAINTENANCE,
OUTDATED,
UNREACHABLE;
val isUserRecoverableError
get() = equals(WARNING) || equals(ERROR) || equals(UNREACHABLE)
val isNonRecoverableError
get() = !isUserRecoverableError && !equals(NORMAL)
}
}
| 0
| null |
0
| 0
|
884766371e62969831f2933ba790bbec4c2c1613
| 2,773
|
oxygen-updater
|
MIT License
|
kotlin-typescript/src/jsMain/generated/typescript/isAwaitExpression.kt
|
JetBrains
| 93,250,841
| false
|
{"Kotlin": 12635434, "JavaScript": 423801}
|
// Automatically generated - do not modify!
@file:JsModule("typescript")
package typescript
@JsName("isAwaitExpression")
external fun isAwaitExpressionRaw(node: Node): Boolean /* node is AwaitExpression */
| 38
|
Kotlin
|
162
| 1,347
|
997ed3902482883db4a9657585426f6ca167d556
| 210
|
kotlin-wrappers
|
Apache License 2.0
|
src/main/kotlin/com/pineypiney/game_engine/resources/shaders/uniforms/Uniforms.kt
|
PineyPiney
| 491,900,499
| false
|
{"Kotlin": 673164, "GLSL": 33407}
|
package com.pineypiney.game_engine.resources.shaders.uniforms
import com.pineypiney.game_engine.rendering.RendererI
import com.pineypiney.game_engine.resources.shaders.uniforms.mats.*
import com.pineypiney.game_engine.resources.shaders.uniforms.vecs.*
import glm_.mat2x2.Mat2
import glm_.mat2x2.Mat2d
import glm_.mat2x3.Mat2x3
import glm_.mat2x3.Mat2x3d
import glm_.mat2x4.Mat2x4
import glm_.mat2x4.Mat2x4d
import glm_.mat3x2.Mat3x2
import glm_.mat3x2.Mat3x2d
import glm_.mat3x3.Mat3
import glm_.mat3x3.Mat3d
import glm_.mat3x4.Mat3x4
import glm_.mat3x4.Mat3x4d
import glm_.mat4x2.Mat4x2
import glm_.mat4x2.Mat4x2d
import glm_.mat4x3.Mat4x3
import glm_.mat4x3.Mat4x3d
import glm_.mat4x4.Mat4
import glm_.mat4x4.Mat4d
import glm_.vec2.Vec2t
import glm_.vec3.Vec3t
import glm_.vec4.Vec4t
class Uniforms(val uniforms: Array<Uniform<*>>) {
fun setBoolUniformR(name: String, getter: (RendererI<*>) -> Boolean){
set<BoolUniform, Boolean>(name, getter)
}
fun setBoolUniform(name: String, getter: () -> Boolean){
set<BoolUniform, Boolean>(name, getter)
}
fun setBoolsUniformR(name: String, getter: (RendererI<*>) -> BooleanArray){
set<BoolsUniform, BooleanArray>(name, getter)
}
fun setBoolsUniform(name: String, getter: () -> BooleanArray){
set<BoolsUniform, BooleanArray>(name, getter)
}
fun setIntUniformR(name: String, getter: (RendererI<*>) -> Int){
set<IntUniform, Int>(name, getter)
}
fun setIntUniform(name: String, getter: () -> Int){
set<IntUniform, Int>(name, getter)
}
fun setIntsUniformR(name: String, getter: (RendererI<*>) -> IntArray){
set<IntsUniform, IntArray>(name, getter)
}
fun setIntsUniform(name: String, getter: () -> IntArray){
set<IntsUniform, IntArray>(name, getter)
}
fun setUIntUniformR(name: String, getter: (RendererI<*>) -> UInt){
set<UIntUniform, UInt>(name, getter)
}
fun setUIntUniform(name: String, getter: () -> UInt){
set<UIntUniform, UInt>(name, getter)
}
fun setUIntsUniformR(name: String, getter: (RendererI<*>) -> IntArray){
set<UIntsUniform, IntArray>(name, getter)
}
fun setUIntsUniform(name: String, getter: () -> IntArray){
set<UIntsUniform, IntArray>(name, getter)
}
fun setFloatUniformR(name: String, getter: (RendererI<*>) -> Float){
set<FloatUniform, Float>(name, getter)
}
fun setFloatUniform(name: String, getter: () -> Float){
set<FloatUniform, Float>(name, getter)
}
fun setFloatsUniformR(name: String, getter: (RendererI<*>) -> FloatArray){
set<FloatsUniform, FloatArray>(name, getter)
}
fun setFloatsUniform(name: String, getter: () -> FloatArray){
set<FloatsUniform, FloatArray>(name, getter)
}
fun setDoubleUniformR(name: String, getter: (RendererI<*>) -> Double){
set<DoubleUniform, Double>(name, getter)
}
fun setDoubleUniform(name: String, getter: () -> Double){
set<DoubleUniform, Double>(name, getter)
}
fun setDoublesUniformR(name: String, getter: (RendererI<*>) -> DoubleArray){
set<DoublesUniform, DoubleArray>(name, getter)
}
fun setDoublesUniform(name: String, getter: () -> DoubleArray){
set<DoublesUniform, DoubleArray>(name, getter)
}
fun setVec2iUniformR(name: String, getter: (RendererI<*>) -> Vec2t<*>){
set<Vec2iUniform, Vec2t<*>>(name, getter)
}
fun setVec2iUniform(name: String, getter: () -> Vec2t<*>){
set<Vec2iUniform, Vec2t<*>>(name, getter)
}
fun setVec2uiUniformR(name: String, getter: (RendererI<*>) -> Vec2t<*>){
set<Vec2uiUniform, Vec2t<*>>(name, getter)
}
fun setVec2uiUniform(name: String, getter: () -> Vec2t<*>){
set<Vec2uiUniform, Vec2t<*>>(name, getter)
}
fun setVec2UniformR(name: String, getter: (RendererI<*>) -> Vec2t<*>){
set<Vec2Uniform, Vec2t<*>>(name, getter)
}
fun setVec2Uniform(name: String, getter: () -> Vec2t<*>){
set<Vec2Uniform, Vec2t<*>>(name, getter)
}
fun setVec2dUniformR(name: String, getter: (RendererI<*>) -> Vec2t<*>){
set<Vec2dUniform, Vec2t<*>>(name, getter)
}
fun setVec2dUniform(name: String, getter: () -> Vec2t<*>){
set<Vec2dUniform, Vec2t<*>>(name, getter)
}
fun setVec2isUniformR(name: String, getter: (RendererI<*>) -> List<Vec2t<*>>){
set<Vec2isUniform, List<Vec2t<*>>>(name, getter)
}
fun setVec2isUniform(name: String, getter: () -> List<Vec2t<*>>){
set<Vec2isUniform, List<Vec2t<*>>>(name, getter)
}
fun setVec2uisUniformR(name: String, getter: (RendererI<*>) -> List<Vec2t<*>>){
set<Vec2uisUniform, List<Vec2t<*>>>(name, getter)
}
fun setVec2uisUniform(name: String, getter: () -> List<Vec2t<*>>){
set<Vec2uisUniform, List<Vec2t<*>>>(name, getter)
}
fun setVec2sUniformR(name: String, getter: (RendererI<*>) -> List<Vec2t<*>>){
set<Vec2sUniform, List<Vec2t<*>>>(name, getter)
}
fun setVec2sUniform(name: String, getter: () -> List<Vec2t<*>>){
set<Vec2sUniform, List<Vec2t<*>>>(name, getter)
}
fun setVec2dsUniformR(name: String, getter: (RendererI<*>) -> List<Vec2t<*>>){
set<Vec2dsUniform, List<Vec2t<*>>>(name, getter)
}
fun setVec2dsUniform(name: String, getter: () -> List<Vec2t<*>>){
set<Vec2dsUniform, List<Vec2t<*>>>(name, getter)
}
fun setVec3iUniformR(name: String, getter: (RendererI<*>) -> Vec3t<*>){
set<Vec3iUniform, Vec3t<*>>(name, getter)
}
fun setVec3iUniform(name: String, getter: () -> Vec3t<*>){
set<Vec3iUniform, Vec3t<*>>(name, getter)
}
fun setVec3uiUniformR(name: String, getter: (RendererI<*>) -> Vec3t<*>){
set<Vec3uiUniform, Vec3t<*>>(name, getter)
}
fun setVec3uiUniform(name: String, getter: () -> Vec3t<*>){
set<Vec3uiUniform, Vec3t<*>>(name, getter)
}
fun setVec3UniformR(name: String, getter: (RendererI<*>) -> Vec3t<*>){
set<Vec3Uniform, Vec3t<*>>(name, getter)
}
fun setVec3Uniform(name: String, getter: () -> Vec3t<*>){
set<Vec3Uniform, Vec3t<*>>(name, getter)
}
fun setVec3dUniformR(name: String, getter: (RendererI<*>) -> Vec3t<*>){
set<Vec3dUniform, Vec3t<*>>(name, getter)
}
fun setVec3dUniform(name: String, getter: () -> Vec3t<*>){
set<Vec3dUniform, Vec3t<*>>(name, getter)
}
fun setVec3isUniformR(name: String, getter: (RendererI<*>) -> List<Vec3t<*>>){
set<Vec3isUniform, List<Vec3t<*>>>(name, getter)
}
fun setVec3isUniform(name: String, getter: () -> List<Vec3t<*>>){
set<Vec3isUniform, List<Vec3t<*>>>(name, getter)
}
fun setVec3uisUniformR(name: String, getter: (RendererI<*>) -> List<Vec3t<*>>){
set<Vec3uisUniform, List<Vec3t<*>>>(name, getter)
}
fun setVec3uisUniform(name: String, getter: () -> List<Vec3t<*>>){
set<Vec3uisUniform, List<Vec3t<*>>>(name, getter)
}
fun setVec3sUniformR(name: String, getter: (RendererI<*>) -> List<Vec3t<*>>){
set<Vec3sUniform, List<Vec3t<*>>>(name, getter)
}
fun setVec3sUniform(name: String, getter: () -> List<Vec3t<*>>){
set<Vec3sUniform, List<Vec3t<*>>>(name, getter)
}
fun setVec3dsUniformR(name: String, getter: (RendererI<*>) -> List<Vec3t<*>>){
set<Vec3dsUniform, List<Vec3t<*>>>(name, getter)
}
fun setVec3dsUniform(name: String, getter: () -> List<Vec3t<*>>){
set<Vec3dsUniform, List<Vec3t<*>>>(name, getter)
}
fun setVec4iUniformR(name: String, getter: (RendererI<*>) -> Vec4t<*>){
set<Vec4iUniform, Vec4t<*>>(name, getter)
}
fun setVec4iUniform(name: String, getter: () -> Vec4t<*>){
set<Vec4iUniform, Vec4t<*>>(name, getter)
}
fun setVec4uiUniformR(name: String, getter: (RendererI<*>) -> Vec4t<*>){
set<Vec4uiUniform, Vec4t<*>>(name, getter)
}
fun setVec4uiUniform(name: String, getter: () -> Vec4t<*>){
set<Vec4uiUniform, Vec4t<*>>(name, getter)
}
fun setVec4UniformR(name: String, getter: (RendererI<*>) -> Vec4t<*>){
set<Vec4Uniform, Vec4t<*>>(name, getter)
}
fun setVec4Uniform(name: String, getter: () -> Vec4t<*>){
set<Vec4Uniform, Vec4t<*>>(name, getter)
}
fun setVec4dUniformR(name: String, getter: (RendererI<*>) -> Vec4t<*>){
set<Vec4dUniform, Vec4t<*>>(name, getter)
}
fun setVec4dUniform(name: String, getter: () -> Vec4t<*>){
set<Vec4dUniform, Vec4t<*>>(name, getter)
}
fun setVec4isUniformR(name: String, getter: (RendererI<*>) -> List<Vec4t<*>>){
set<Vec4isUniform, List<Vec4t<*>>>(name, getter)
}
fun setVec4isUniform(name: String, getter: () -> List<Vec4t<*>>){
set<Vec4isUniform, List<Vec4t<*>>>(name, getter)
}
fun setVec4uisUniformR(name: String, getter: (RendererI<*>) -> List<Vec4t<*>>){
set<Vec4uisUniform, List<Vec4t<*>>>(name, getter)
}
fun setVec4uisUniform(name: String, getter: () -> List<Vec4t<*>>){
set<Vec4uisUniform, List<Vec4t<*>>>(name, getter)
}
fun setVec4sUniformR(name: String, getter: (RendererI<*>) -> List<Vec4t<*>>){
set<Vec4sUniform, List<Vec4t<*>>>(name, getter)
}
fun setVec4sUniform(name: String, getter: () -> List<Vec4t<*>>){
set<Vec4sUniform, List<Vec4t<*>>>(name, getter)
}
fun setVec4dsUniformR(name: String, getter: (RendererI<*>) -> List<Vec4t<*>>){
set<Vec4dsUniform, List<Vec4t<*>>>(name, getter)
}
fun setVec4dsUniform(name: String, getter: () -> List<Vec4t<*>>){
set<Vec4dsUniform, List<Vec4t<*>>>(name, getter)
}
fun setMat2UniformR(name: String, getter: (RendererI<*>) -> Mat2){
set<Mat2Uniform, Mat2>(name, getter)
}
fun setMat2Uniform(name: String, getter: () -> Mat2){
set<Mat2Uniform, Mat2>(name, getter)
}
fun setMat2dUniformR(name: String, getter: (RendererI<*>) -> Mat2d){
set<Mat2dUniform, Mat2d>(name, getter)
}
fun setMat2dUniform(name: String, getter: () -> Mat2d){
set<Mat2dUniform, Mat2d>(name, getter)
}
fun setMat2sUniformR(name: String, getter: (RendererI<*>) -> Array<Mat2>){
set<Mat2sUniform, Array<Mat2>>(name, getter)
}
fun setMat2sUniform(name: String, getter: () -> Array<Mat2>){
set<Mat2sUniform, Array<Mat2>>(name, getter)
}
fun setMat2dsUniformR(name: String, getter: (RendererI<*>) -> Array<Mat2d>){
set<Mat2dsUniform, Array<Mat2d>>(name, getter)
}
fun setMat2dsUniform(name: String, getter: () -> Array<Mat2d>){
set<Mat2dsUniform, Array<Mat2d>>(name, getter)
}
fun setMat2x3UniformR(name: String, getter: (RendererI<*>) -> Mat2x3){
set<Mat2x3Uniform, Mat2x3>(name, getter)
}
fun setMat2x3Uniform(name: String, getter: () -> Mat2x3){
set<Mat2x3Uniform, Mat2x3>(name, getter)
}
fun setMat2x3dUniformR(name: String, getter: (RendererI<*>) -> Mat2x3d){
set<Mat2x3dUniform, Mat2x3d>(name, getter)
}
fun setMat2x3dUniform(name: String, getter: () -> Mat2x3d){
set<Mat2x3dUniform, Mat2x3d>(name, getter)
}
fun setMat2x3sUniformR(name: String, getter: (RendererI<*>) -> Array<Mat2x3>){
set<Mat2x3sUniform, Array<Mat2x3>>(name, getter)
}
fun setMat2x3sUniform(name: String, getter: () -> Array<Mat2x3>){
set<Mat2x3sUniform, Array<Mat2x3>>(name, getter)
}
fun setMat2x3dsUniformR(name: String, getter: (RendererI<*>) -> Array<Mat2x3d>){
set<Mat2x3dsUniform, Array<Mat2x3d>>(name, getter)
}
fun setMat2x3dsUniform(name: String, getter: () -> Array<Mat2x3d>){
set<Mat2x3dsUniform, Array<Mat2x3d>>(name, getter)
}
fun setMat2x4UniformR(name: String, getter: (RendererI<*>) -> Mat2x4){
set<Mat2x4Uniform, Mat2x4>(name, getter)
}
fun setMat2x4Uniform(name: String, getter: () -> Mat2x4){
set<Mat2x4Uniform, Mat2x4>(name, getter)
}
fun setMat2x4dUniformR(name: String, getter: (RendererI<*>) -> Mat2x4d){
set<Mat2x4dUniform, Mat2x4d>(name, getter)
}
fun setMat2x4dUniform(name: String, getter: () -> Mat2x4d){
set<Mat2x4dUniform, Mat2x4d>(name, getter)
}
fun setMat2x4sUniformR(name: String, getter: (RendererI<*>) -> Array<Mat2x4>){
set<Mat2x4sUniform, Array<Mat2x4>>(name, getter)
}
fun setMat2x4sUniform(name: String, getter: () -> Array<Mat2x4>){
set<Mat2x4sUniform, Array<Mat2x4>>(name, getter)
}
fun setMat2x4dsUniformR(name: String, getter: (RendererI<*>) -> Array<Mat2x4d>){
set<Mat2x4dsUniform, Array<Mat2x4d>>(name, getter)
}
fun setMat2x4dsUniform(name: String, getter: () -> Array<Mat2x4d>){
set<Mat2x4dsUniform, Array<Mat2x4d>>(name, getter)
}
fun setMat3x2UniformR(name: String, getter: (RendererI<*>) -> Mat3x2){
set<Mat3x2Uniform, Mat3x2>(name, getter)
}
fun setMat3x2Uniform(name: String, getter: () -> Mat3x2){
set<Mat3x2Uniform, Mat3x2>(name, getter)
}
fun setMat3x2dUniformR(name: String, getter: (RendererI<*>) -> Mat3x2d){
set<Mat3x2dUniform, Mat3x2d>(name, getter)
}
fun setMat3x2dUniform(name: String, getter: () -> Mat3x2d){
set<Mat3x2dUniform, Mat3x2d>(name, getter)
}
fun setMat3x2sUniformR(name: String, getter: (RendererI<*>) -> Array<Mat3x2>){
set<Mat3x2sUniform, Array<Mat3x2>>(name, getter)
}
fun setMat3x2sUniform(name: String, getter: () -> Array<Mat3x2>){
set<Mat3x2sUniform, Array<Mat3x2>>(name, getter)
}
fun setMat3x2dsUniformR(name: String, getter: (RendererI<*>) -> Array<Mat3x2d>){
set<Mat3x2dsUniform, Array<Mat3x2d>>(name, getter)
}
fun setMat3x2dsUniform(name: String, getter: () -> Array<Mat3x2d>){
set<Mat3x2dsUniform, Array<Mat3x2d>>(name, getter)
}
fun setMat3UniformR(name: String, getter: (RendererI<*>) -> Mat3){
set<Mat3Uniform, Mat3>(name, getter)
}
fun setMat3Uniform(name: String, getter: () -> Mat3){
set<Mat3Uniform, Mat3>(name, getter)
}
fun setMat3dUniformR(name: String, getter: (RendererI<*>) -> Mat3d){
set<Mat3dUniform, Mat3d>(name, getter)
}
fun setMat3dUniform(name: String, getter: () -> Mat3d){
set<Mat3dUniform, Mat3d>(name, getter)
}
fun setMat3sUniformR(name: String, getter: (RendererI<*>) -> Array<Mat3>){
set<Mat3sUniform, Array<Mat3>>(name, getter)
}
fun setMat3sUniform(name: String, getter: () -> Array<Mat3>){
set<Mat3sUniform, Array<Mat3>>(name, getter)
}
fun setMat3dsUniformR(name: String, getter: (RendererI<*>) -> Array<Mat3d>){
set<Mat3dsUniform, Array<Mat3d>>(name, getter)
}
fun setMat3dsUniform(name: String, getter: () -> Array<Mat3d>){
set<Mat3dsUniform, Array<Mat3d>>(name, getter)
}
fun setMat3x4UniformR(name: String, getter: (RendererI<*>) -> Mat3x4){
set<Mat3x4Uniform, Mat3x4>(name, getter)
}
fun setMat3x4Uniform(name: String, getter: () -> Mat3x4){
set<Mat3x4Uniform, Mat3x4>(name, getter)
}
fun setMat3x4dUniformR(name: String, getter: (RendererI<*>) -> Mat3x4d){
set<Mat3x4dUniform, Mat3x4d>(name, getter)
}
fun setMat3x4dUniform(name: String, getter: () -> Mat3x4d){
set<Mat3x4dUniform, Mat3x4d>(name, getter)
}
fun setMat3x4sUniformR(name: String, getter: (RendererI<*>) -> Array<Mat3x4>){
set<Mat3x4sUniform, Array<Mat3x4>>(name, getter)
}
fun setMat3x4sUniform(name: String, getter: () -> Array<Mat3x4>){
set<Mat3x4sUniform, Array<Mat3x4>>(name, getter)
}
fun setMat3x4dsUniformR(name: String, getter: (RendererI<*>) -> Array<Mat3x4d>){
set<Mat3x4dsUniform, Array<Mat3x4d>>(name, getter)
}
fun setMat3x4dsUniform(name: String, getter: () -> Array<Mat3x4d>){
set<Mat3x4dsUniform, Array<Mat3x4d>>(name, getter)
}
fun setMat4x2UniformR(name: String, getter: (RendererI<*>) -> Mat4x2){
set<Mat4x2Uniform, Mat4x2>(name, getter)
}
fun setMat4x2Uniform(name: String, getter: () -> Mat4x2){
set<Mat4x2Uniform, Mat4x2>(name, getter)
}
fun setMat4x2dUniformR(name: String, getter: (RendererI<*>) -> Mat4x2d){
set<Mat4x2dUniform, Mat4x2d>(name, getter)
}
fun setMat4x2dUniform(name: String, getter: () -> Mat4x2d){
set<Mat4x2dUniform, Mat4x2d>(name, getter)
}
fun setMat4x2sUniformR(name: String, getter: (RendererI<*>) -> Array<Mat4x2>){
set<Mat4x2sUniform, Array<Mat4x2>>(name, getter)
}
fun setMat4x2sUniform(name: String, getter: () -> Array<Mat4x2>){
set<Mat4x2sUniform, Array<Mat4x2>>(name, getter)
}
fun setMat4x2dsUniformR(name: String, getter: (RendererI<*>) -> Array<Mat4x2d>){
set<Mat4x2dsUniform, Array<Mat4x2d>>(name, getter)
}
fun setMat4x2dsUniform(name: String, getter: () -> Array<Mat4x2d>){
set<Mat4x2dsUniform, Array<Mat4x2d>>(name, getter)
}
fun setMat4x3UniformR(name: String, getter: (RendererI<*>) -> Mat4x3){
set<Mat4x3Uniform, Mat4x3>(name, getter)
}
fun setMat4x3Uniform(name: String, getter: () -> Mat4x3){
set<Mat4x3Uniform, Mat4x3>(name, getter)
}
fun setMat4x3dUniformR(name: String, getter: (RendererI<*>) -> Mat4x3d){
set<Mat4x3dUniform, Mat4x3d>(name, getter)
}
fun setMat4x3dUniform(name: String, getter: () -> Mat4x3d){
set<Mat4x3dUniform, Mat4x3d>(name, getter)
}
fun setMat4x3sUniformR(name: String, getter: (RendererI<*>) -> Array<Mat4x3>){
set<Mat4x3sUniform, Array<Mat4x3>>(name, getter)
}
fun setMat4x3sUniform(name: String, getter: () -> Array<Mat4x3>){
set<Mat4x3sUniform, Array<Mat4x3>>(name, getter)
}
fun setMat4x3dsUniformR(name: String, getter: (RendererI<*>) -> Array<Mat4x3d>){
set<Mat4x3dsUniform, Array<Mat4x3d>>(name, getter)
}
fun setMat4x3dsUniform(name: String, getter: () -> Array<Mat4x3d>){
set<Mat4x3dsUniform, Array<Mat4x3d>>(name, getter)
}
fun setMat4UniformR(name: String, getter: (RendererI<*>) -> Mat4){
set<Mat4Uniform, Mat4>(name, getter)
}
fun setMat4Uniform(name: String, getter: () -> Mat4){
set<Mat4Uniform, Mat4>(name, getter)
}
fun setMat4dUniformR(name: String, getter: (RendererI<*>) -> Mat4d){
set<Mat4dUniform, Mat4d>(name, getter)
}
fun setMat4dUniform(name: String, getter: () -> Mat4d){
set<Mat4dUniform, Mat4d>(name, getter)
}
fun setMat4sUniformR(name: String, getter: (RendererI<*>) -> Array<Mat4>){
set<Mat4sUniform, Array<Mat4>>(name, getter)
}
fun setMat4sUniform(name: String, getter: () -> Array<Mat4>){
set<Mat4sUniform, Array<Mat4>>(name, getter)
}
fun setMat4dsUniformR(name: String, getter: (RendererI<*>) -> Array<Mat4d>){
set<Mat4dsUniform, Array<Mat4d>>(name, getter)
}
fun setMat4dsUniform(name: String, getter: () -> Array<Mat4d>){
set<Mat4dsUniform, Array<Mat4d>>(name, getter)
}
inline fun <reified U: Uniform<E>, E> set(name: String, noinline getter: (RendererI<*>) -> E){
val uniform = this[name] ?: return
if(uniform is U){
uniform.getter = getter
}
}
inline fun <reified U: Uniform<E>, E> set(name: String, noinline getter: () -> E){
val uniform = this[name] ?: return
if(uniform is U){
uniform.getter = { getter() }
}
}
operator fun get(name: String) = uniforms.firstOrNull{ it.name == name }
override fun toString(): String {
return "Uniforms[" + uniforms.joinToString { it.name } + ']'
}
fun allValues(rendererI: RendererI<*>): Map<String, Any?>{
return uniforms.associate { it.name to it.getter(rendererI) }
}
companion object{
val default = Uniforms(arrayOf())
}
}
| 0
|
Kotlin
|
0
| 0
|
7e9b57404bb4433f13301294ca41c002622e757e
| 19,969
|
GameEngine
|
MIT License
|
src/main/kotlin/extensions/StringContexts.kts
|
gorttar
| 171,255,058
| false
| null |
package extensions
/**
* extensions/StringContexts.kts
*/
class StringConcatLog(
private val log: StringBuilder = StringBuilder()
) {
private fun String.logPlus(element: Any?) =
log.append(this).append(" + ").append(element).append("\n")
// не работает. Перекрыт методом класса kotlin.String
operator fun String.plus(tail: Any?) = logPlus(tail).let { this.plus(tail) }
override fun toString(): String = log.toString()
}
print(
StringConcatLog().apply {
"foo" + "bar"
})
| 0
|
Kotlin
|
0
| 0
|
bc1bc4b22c891cb9e5395ecfb6ee91b7297304d0
| 519
|
break_kotlin
|
MIT License
|
compiler/tests-common-new/tests/org/jetbrains/kotlin/test/utils/FirErrorsDefaultMessagesHelper.kt
|
JetBrains
| 3,432,266
| false
| null |
/*
* Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.test.utils
import org.jetbrains.kotlin.diagnostics.*
import org.junit.Assert
import kotlin.reflect.KProperty
import kotlin.reflect.full.memberProperties
fun KtDiagnosticFactoryToRendererMap.verifyMessages(objectWithErrors: Any) {
val errors = mutableListOf<String>()
for (property in objectWithErrors::class.memberProperties) {
when (val factory = property.getter.call(objectWithErrors)) {
is AbstractKtDiagnosticFactory -> {
errors += verifyMessageForFactory(factory, property)
}
is KtDiagnosticFactoryForDeprecation<*> -> {
errors += verifyMessageForFactory(factory.warningFactory, property)
errors += verifyMessageForFactory(factory.errorFactory, property)
}
else -> {}
}
}
if (errors.isNotEmpty()) {
Assert.fail(errors.joinToString("\n", prefix = "\n"))
}
}
private val messageParameterRegex = """\{\d.*?}""".toRegex()
fun KtDiagnosticFactoryToRendererMap.verifyMessageForFactory(factory: AbstractKtDiagnosticFactory, property: KProperty<*>) = buildList {
if (!containsKey(factory)) {
add("No default diagnostic renderer is provided for ${property.name}")
return@buildList
}
val renderer = get(factory)!!
val parameterCount = when (renderer) {
is KtDiagnosticWithParameters4Renderer<*, *, *, *> -> 4
is KtDiagnosticWithParameters3Renderer<*, *, *> -> 3
is KtDiagnosticWithParameters2Renderer<*, *> -> 2
is KtDiagnosticWithParameters1Renderer<*> -> 1
else -> 0
}
for (parameter in messageParameterRegex.findAll(renderer.message)) {
val index = parameter.value.substring(1, 2).toInt()
if (index >= parameterCount) {
add("Message for ${property.name} references wrong parameter {$index}")
}
}
if (parameterCount > 0 && renderer.message.contains("(?<!')'(?!')".toRegex())) {
add("Renderer for ${property.name} has parameters and contains single quote. Text inside single quotes is not formatted in MessageFormat. Use double quote instead.")
}
if (parameterCount == 0 && renderer.message.contains("(?<!')''(?!')".toRegex())) {
add("Renderer for ${property.name} has no parameters and contains double quote. Single quote should be used.")
}
}
| 179
| null |
5706
| 48,889
|
c46c3c26038158cf80a739431ac8807ac4bbbc0c
| 2,593
|
kotlin
|
Apache License 2.0
|
app/src/main/java/com/eyebrows/video/sample/MainActivity.kt
|
Moosphan
| 200,388,260
| false
| null |
package com.eyebrows.video.sample
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.View
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
initialize()
}
private fun initialize() {
videoUploadBtn.setOnClickListener {
Toast.makeText(this, "Upload video", Toast.LENGTH_SHORT).show()
}
val videos = arrayListOf(
VideoData(R.raw.video1, R.drawable.thumbnail1, "just now", "但愿人长久,千里共婵娟🌛"),
VideoData(R.raw.video2, R.drawable.thumbnail2, "an hour ago", "Long time no see so happy moment in my life, it reminds me of my childhood."),
VideoData(R.raw.video3, R.drawable.thumbnail3, "10 hours ago", "The AR is so cool! I am glad to play this type games."),
VideoData(R.raw.video4, R.drawable.thumbnail4, "2 days ago", "There is something just like this... "),
VideoData(R.raw.video5, R.drawable.thumbnail5, "September 9, 2019", "Tomorrow is always fresh, with no mistakes in it yet.")
)
val mLayoutManager = LinearLayoutManager(this)
val videoListAdapter = VideoListAdapter(videos)
videoRecyclerView.layoutManager = mLayoutManager
videoRecyclerView.adapter = videoListAdapter
videoRecyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener(){
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
val firstVisibleItem = mLayoutManager . findFirstVisibleItemPosition ()
val firstView = mLayoutManager.findViewByPosition (firstVisibleItem)
var playPosition = 0
if (null != firstView) {
if (dy > 0) {
if (firstView.height + firstView.top <= firstView.height / 3) {
if (playPosition == firstVisibleItem + 1) {
return
}
playPosition = firstVisibleItem + 1
videoListAdapter.playVideo(playPosition)
} else {
if (playPosition == firstVisibleItem) {
return
}
playPosition = firstVisibleItem
videoListAdapter.playVideo(playPosition)
}
}else if (dy < 0) {
if (firstView.height + firstView.top >= firstView.height * 2 / 3) {
//video stop or play second
if (playPosition == firstVisibleItem) {
return
}
playPosition = firstVisibleItem
videoListAdapter.playVideo(playPosition)
} else {
if (playPosition == firstVisibleItem + 1) {
return
}
playPosition = firstVisibleItem + 1
videoListAdapter.playVideo(playPosition)
}
}else {
playPosition = 0
videoListAdapter.playVideo(playPosition)
}
}
}
})
}
}
| 0
|
Kotlin
|
2
| 12
|
031b2db1a0f77bed25f5fe37985ffc27c211c199
| 3,788
|
EyebrowsVideoView
|
MIT License
|
src/main/kotlin/no/nav/syfo/oppfolgingsplan/converter/HodemeldingConverter.kt
|
navikt
| 378,118,189
| false
| null |
package no.nav.syfo.oppfolgingsplan.converter
import no.kith.xmlstds.msghead._2006_05_24.ObjectFactory
import no.kith.xmlstds.msghead._2006_05_24.XMLMsgHead
import no.nav.syfo.oppfolgingsplan.domain.RSHodemelding
fun createMsgHead(
rsHodemelding: RSHodemelding,
): XMLMsgHead {
val factory = ObjectFactory()
return factory.createXMLMsgHead()
.withMsgInfo(createMsgInfo(rsMeldingInfo = rsHodemelding.meldingInfo))
.withDocument(createDialogmeldingDocument())
.withDocument(createVedleggDocument(rsVedlegg = rsHodemelding.vedlegg))
}
| 1
|
Kotlin
|
1
| 0
|
dd12b992684acda2da79c73c5364ece6d58f3dbd
| 570
|
isdialogmelding
|
MIT License
|
app/src/main/java/com/github/kotlin_mvpro/ui/presenter/MainActivityPresenter.kt
|
vihuela
| 95,213,546
| false
| null |
/*
* Copyright (C) 2017 Ricky.yao https://github.com/vihuela
*
* 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
*
*/
package com.github.kotlin_mvpro.ui.presenter
import android.os.Bundle
import com.github.kotlin_mvpro.model.UserInfo
import com.ricky.mvp_core.base.BasePresenter
import com.ricky.mvp_core.base.interfaces.IView
class MainActivityPresenter : BasePresenter<IView>() {
override fun onViewCreated(view: IView, arguments: Bundle?, savedInstanceState: Bundle?) {
val userInfo = savedInstanceState?.getParcelable<UserInfo>("person")
print(userInfo ?: return)
}
override fun onSaveInstanceState(outState: Bundle) {
val user = UserInfo("ricky", "vihuela")
outState?.putParcelable("person", user)
super.onSaveInstanceState(outState)
}
}
| 2
| null |
16
| 62
|
c6fb6729e303862412cc0a5b35155edb3f8923d3
| 985
|
Kotlin-mvpro
|
Apache License 2.0
|
compiler/frontend/src/org/jetbrains/kotlin/psi/KtSimpleNameExpression.kt
|
erokhins
| 44,854,854
| true
|
{"Markdown": 33, "XML": 665, "Ant Build System": 45, "Ignore List": 7, "Git Attributes": 1, "Kotlin": 20967, "Java": 4534, "Protocol Buffer": 7, "Text": 4663, "JavaScript": 63, "JAR Manifest": 3, "Roff": 46, "Roff Manpage": 11, "INI": 17, "HTML": 152, "Groovy": 23, "Java Properties": 14, "Maven POM": 49, "Gradle": 74, "CSS": 2, "Proguard": 1, "JFlex": 2, "Shell": 11, "Batchfile": 10, "ANTLR": 1}
|
/*
* Copyright 2010-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.psi
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiReference
import com.intellij.psi.tree.IElementType
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.Name
public interface KtSimpleNameExpression : KtReferenceExpression {
public fun getReferencedName(): String
public fun getReferencedNameAsName(): Name
public fun getReferencedNameElement(): PsiElement
public fun getIdentifier(): PsiElement?
public fun getReferencedNameElementType(): IElementType
}
abstract class KtSimpleNameExpressionImpl(node: ASTNode) : KtExpressionImpl(node), KtSimpleNameExpression {
override fun getIdentifier(): PsiElement? = findChildByType(KtTokens.IDENTIFIER)
override fun getReferencedNameElementType() = getReferencedNameElementTypeImpl(this)
override fun <R, D> accept(visitor: KtVisitor<R, D>, data: D): R {
return visitor.visitSimpleNameExpression(this, data)
}
override fun getReferencedNameAsName() = getReferencedNameAsNameImpl(this)
override fun getReferencedName() = getReferencedNameImpl(this)
//NOTE: an unfortunate way to share an implementation between stubbed and not stubbed tree
companion object {
fun getReferencedNameElementTypeImpl(expression: KtSimpleNameExpression): IElementType {
return expression.getReferencedNameElement().getNode()!!.getElementType()
}
fun getReferencedNameAsNameImpl(expresssion: KtSimpleNameExpression): Name {
val name = expresssion.getReferencedName()
return Name.identifier(name)
}
fun getReferencedNameImpl(expression: KtSimpleNameExpression): String {
val text = expression.getReferencedNameElement().getNode()!!.getText()
return KtPsiUtil.unquoteIdentifierOrFieldReference(text)
}
}
}
| 0
|
Java
|
0
| 1
|
ff00bde607d605c4eba2d98fbc9e99af932accb6
| 2,512
|
kotlin
|
Apache License 2.0
|
client_dashboard/common/src/commonMain/kotlin/org/thechance/common/data/gateway/fake/RestaurantFakeGateway.kt
|
TheChance101
| 671,967,732
| false
|
{"Kotlin": 2473455, "Ruby": 8872, "HTML": 6083, "Swift": 4726, "JavaScript": 3082, "CSS": 1436, "Dockerfile": 1407, "Shell": 1140}
|
package com.angus.common.data.gateway.fake
import com.angus.common.data.gateway.remote.mapper.toEntity
import com.angus.common.data.gateway.remote.model.DataWrapperDto
import com.angus.common.data.gateway.remote.model.LocationDto
import com.angus.common.data.gateway.remote.model.RestaurantDto
import com.angus.common.data.gateway.remote.model.toEntity
import com.angus.common.domain.entity.*
import com.angus.common.domain.getway.IRestaurantGateway
import java.util.UUID
import kotlin.math.ceil
class RestaurantFakeGateway : IRestaurantGateway {
override suspend fun getRestaurants(
pageNumber: Int,
numberOfRestaurantsInPage: Int,
restaurantName: String,
rating: Double,
priceLevel: Int,
): DataWrapper<Restaurant> {
var restaurants = restaurants.toEntity()
val priceLevelFilter = if (priceLevel != 0) "$".repeat(priceLevel) else null
if (restaurantName.isNotEmpty()) {
restaurants = restaurants.filter {
it.name.startsWith(
restaurantName,
true
)
}
}
if (rating > 0.0) {
restaurants = restaurants.filter {
it.rate == rating
}
}
if (priceLevel > 0) {
restaurants = restaurants.filter {
it.priceLevel == priceLevelFilter
}
}
val startIndex = (pageNumber - 1) * numberOfRestaurantsInPage
val endIndex = startIndex + numberOfRestaurantsInPage
val numberOfPages = ceil(restaurants.size / (numberOfRestaurantsInPage * 1.0)).toInt()
return try {
DataWrapperDto(
totalPages = numberOfPages,
result = restaurants.subList(startIndex, endIndex.coerceAtMost(restaurants.size)),
totalResult = restaurants.size
).toEntity()
} catch (e: Exception) {
DataWrapperDto(
totalPages = numberOfPages,
result = restaurants,
totalResult = restaurants.size
).toEntity()
}
}
override suspend fun getRestaurantById(id: String): Restaurant {
return restaurants.first { it.id == id }.toEntity()
}
override suspend fun updateRestaurant(
restaurantId: String,
ownerId: String,
restaurant: RestaurantInformation
): Restaurant {
val index = restaurants.indexOfFirst { it.id == restaurantId }
restaurants[index] = restaurants[index].copy(
name = restaurant.name,
phone = restaurant.phoneNumber,
openingTime = restaurant.openingTime,
closingTime = restaurant.closingTime,
location = LocationDto(
latitude = restaurant.location.split(",")[0].toDouble(),
longitude = restaurant.location.split(",")[1].toDouble()
)
)
return restaurants[index].toEntity()
}
override suspend fun createRestaurant(restaurant: RestaurantInformation): Restaurant {
return Restaurant(
id = "7",
name = restaurant.name,
ownerId = restaurant.ownerUsername,
phone = restaurant.phoneNumber,
openingTime = restaurant.openingTime,
closingTime = restaurant.closingTime,
rate = 0.0,
priceLevel = "",
ownerUsername = restaurant.ownerUsername,
location = Location(
latitude = restaurant.location.split(",")[0].toDouble(),
longitude = restaurant.location.split(",")[1].toDouble()
)
)
}
override suspend fun deleteRestaurant(id: String): Boolean {
restaurants.remove(restaurants.find { it.id == id })
return true
}
override suspend fun getCuisines(): List<Cuisine> {
return cuisines
}
override suspend fun getOffers(): List<Offer> {
return offers
}
override suspend fun createCuisine(cuisineName: String,image:ByteArray): Cuisine {
val newCuisine = Cuisine(UUID.randomUUID().toString(), cuisineName, image.toString())
cuisines.add(newCuisine)
return newCuisine
}
override suspend fun deleteCuisine(cuisineId: String) {
cuisines.find { it.id == cuisineId }?.let {
cuisines.remove(it)
}
}
override suspend fun createOffer(offerName: String, image: ByteArray): Offer {
val newOffer =Offer(UUID.randomUUID().toString(), offerName, image.toString())
offers.add(newOffer)
return newOffer
}
private val cuisines = mutableListOf<Cuisine>(
Cuisine("1", "Angolan cuisine",""),
Cuisine("", "Cameroonian cuisine",""),
Cuisine("", "Chadian cuisine",""),
Cuisine("", "Congolese cuisine",""),
Cuisine("", "Centrafrican cuisine",""),
Cuisine("", "Equatorial Guinea cuisine",""),
Cuisine("", "Gabonese cuisine",""),
Cuisine("", "Santomean cuisine",""),
Cuisine("", "Burundian cuisine",""),
Cuisine("", "Djiboutian cuisine",""),
Cuisine("", "Eritrean cuisine",""),
Cuisine("", "Ethiopian cuisine",""),
Cuisine("", "Kenyan cuisine",""),
Cuisine("", "Maasai cuisine",""),
Cuisine("", "Rwandan cuisine",""),
Cuisine("", "Somali cuisine","")
)
private val offers = mutableListOf<Offer>(
Offer("1", "Angolan cuisine",""),
Offer("2", "Cameroonian cuisine",""),
Offer("3", "Chadian cuisine",""),
Offer("4", "Congolese cuisine",""),
Offer("5", "Centrafrican cuisine",""),
Offer("6", "Equatorial Guinea cuisine",""),
Offer("7", "Gabonese cuisine",""),
Offer("8", "Santomean cuisine",""),
Offer("9", "Burundian cuisine",""),
)
private val restaurants = mutableListOf(
RestaurantDto(
id = "8c90c4c6-1e69-47f3-aa59-2edcd6f0057b",
name = "Mujtaba Restaurant",
ownerId = "mujtaba",
phone = "0532465722",
rate = 0.4,
priceLevel = "",
openingTime = "06:30 - 22:30"
),
RestaurantDto(
id = "6e21s4f-aw32-fs3e-fe43-aw56g4yr324",
name = "Karrar Restaurant",
ownerId = "karrar",
phone = "0535232154",
rate = 3.5,
priceLevel = "",
openingTime = "12:00 - 23:00"
),
RestaurantDto(
id = "7a33sax-aw32-fs3e-12df-42ad6x352zse",
name = "Saif Restaurant",
ownerId = "saif",
phone = "0554627893",
rate = 4.0,
priceLevel = "",
openingTime = "09:00 - 23:00"
),
RestaurantDto(
id = "7y1z47c-s2df-76de-dwe2-42ad6x352zse",
name = "Nada Restaurant",
ownerId = "nada",
phone = "0524242766",
rate = 3.4,
priceLevel = "",
openingTime = "01:00 - 23:00"
),
RestaurantDto(
id = "3e1f5d4a-8317-4f13-aa89-2c094652e6a3",
name = "Asia Restaurant",
ownerId = "asia",
phone = "0528242165",
rate = 2.9,
priceLevel = "",
openingTime = "09:30 - 21:30"
),
RestaurantDto(
id = "7a1bfe39-4b2c-4f76-bde0-82da2eaf9e99",
name = "Kamel Restaurant",
ownerId = "kamel",
phone = "0528242235",
rate = 3.0,
priceLevel = "",
openingTime = "06:30 - 22:30"
),
RestaurantDto(
id = "7a1bfe39-4b2c-4f76-bde0-82da2eaf9e55",
name = "Kamel Restaurant",
ownerId = "kamel",
phone = "0528242235",
rate = 4.9,
priceLevel = "$",
openingTime = "06:30 - 22:30"
),
RestaurantDto(
id = "7a1bfe39-4b2c-4f76-bde0-82da2eaf9e89",
name = "Kamel Restaurant",
ownerId = "kamel",
phone = "0528242235",
rate = 5.0,
priceLevel = "$$",
openingTime = "06:30 - 22:30"
),
)
}
| 4
|
Kotlin
|
55
| 572
|
1d2e72ba7def605529213ac771cd85cbab832241
| 8,251
|
beep-beep
|
Apache License 2.0
|
components/src/commonMain/kotlin/me/lincolnstuart/funblocks/components/misc/notification/BasicNotification.kt
|
LincolnStuart
| 645,064,211
| false
|
{"Kotlin": 451042}
|
package me.lincolnstuart.funblocks.essentials.misc.notification
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.padding
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import me.lincolnstuart.funblocks.foundation.ui.token.content.spacing.FunBlocksInset
import me.lincolnstuart.funblocks.foundation.ui.token.content.spacing.FunBlocksSpacing
/**
* Base component that organize the main content and notification indicator.
*
* @param displacement it is recommended to use [FunBlocksSpacing] or [FunBlocksInset].
* @param content the content inside.
* @param notification the indicator.
*/
@Composable
internal fun BasicNotification(
displacement: PaddingValues,
content: @Composable () -> Unit,
notification: @Composable BoxScope.() -> Unit
) {
Box {
Box(
modifier = Modifier.padding(displacement)
) {
content()
}
Box(
modifier = Modifier.align(Alignment.BottomEnd)
) {
notification()
}
}
}
| 1
|
Kotlin
|
0
| 4
|
5a9d60f062132df12a6022530dfa10692fbf6c6d
| 1,227
|
fun-blocks
|
MIT License
|
app/src/main/java/com/hackathon/emergency/EmergencyContactViewModel.kt
|
ShivarajMbhagoji
| 840,589,414
| false
|
{"Kotlin": 113087}
|
package com.hackathon.emergency
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.cachedIn
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
@HiltViewModel
class EmergencyContactViewModel @Inject constructor(
private val emergencyUseCases: EmergencyUseCases
): ViewModel(){
val datas=emergencyUseCases.getContacts(
).cachedIn(viewModelScope)
}
| 0
|
Kotlin
|
1
| 0
|
12cb94f302007c4c298324407568d43766957383
| 436
|
CodeFury_7.0
|
MIT License
|
src/main/kotlin/ee/bjarn/ktify/model/Episode.kt
|
warriorzz
| 384,555,118
| false
|
{"Kotlin": 77840}
|
package ee.bjarn.ktify.model
import ee.bjarn.ktify.model.external.ExternalUrl
import ee.bjarn.ktify.model.util.Image
import ee.bjarn.ktify.model.util.ObjectType
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.JsonObject
@Serializable
data class Episode(
@SerialName("audio_preview_url")
val audioPreviewUrl: String? = null,
val description: String,
@SerialName("duration_ms")
val durationMs: Long,
val explicit: Boolean,
@SerialName("external_urls")
val externalUrl: ExternalUrl,
val href: String,
@SerialName("html_description")
val htmlDescription: String,
val id: String,
val images: List<Image>,
@SerialName("is_externally_hosted")
val isExternallyHosted: Boolean,
@SerialName("is_playable")
val isPlayable: Boolean,
val languages: List<String>,
val name: String,
@SerialName("release_date")
val releaseDate: String,
@SerialName("release_date_precision")
val releaseDatePrecision: ReleaseDatePrecision,
val restrictions: EpisodeRestriction,
@SerialName("resume_point")
val resumePoint: ResumePoint? = null,
val show: JsonObject,
override val type: ObjectType = ObjectType.EPISODE,
val uri: String,
) : KtifyObject()
@Serializable
data class SavedEpisodeObject(
@SerialName("added_at")
val addedAt: String,
val episode: Episode,
)
@Serializable
data class EpisodeRestriction(
val reason: RestrictionType,
)
@Serializable
data class ResumePoint(
@SerialName("fully_played")
val fullyPlayed: Boolean,
@SerialName("resume_position_ms")
val resumePositionMs: Long,
)
| 1
|
Kotlin
|
4
| 7
|
78124af971281342dc5bc30aaf2974646e17d97c
| 1,687
|
ktify
|
MIT License
|
owntracks-android-2.5/project/app/src/main/java/org/owntracks/android/support/ContactImageBindingAdapter.kt
|
wir3z
| 737,346,188
| false
|
{"Kotlin": 928031, "Groovy": 378082, "Java": 12862, "Shell": 4540}
|
package org.owntracks.android.support
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.PorterDuff
import android.graphics.PorterDuffXfermode
import android.graphics.Rect
import android.graphics.RectF
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.util.Base64
import android.widget.ImageView
import androidx.databinding.BindingAdapter
import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.owntracks.android.model.Contact
import org.owntracks.android.support.widgets.TextDrawable
import timber.log.Timber
class ContactImageBindingAdapter
@Inject
constructor(
@ApplicationContext context: Context,
private val memoryCache: ContactBitmapAndNameMemoryCache
) {
@BindingAdapter(value = ["contact", "coroutineScope"])
fun ImageView.displayFaceInViewAsync(contact: Contact?, scope: CoroutineScope) {
contact?.also { scope.launch(Dispatchers.Main) { setImageBitmap(getBitmapFromCache(it)) } }
}
private val faceDimensions = (48 * (context.resources.displayMetrics.densityDpi / 160f)).toInt()
suspend fun getBitmapFromCache(contact: Contact): Bitmap {
Timber.v("Getting face bitmap for ${contact.id}")
return withContext(Dispatchers.IO) {
val contactBitMapAndName = memoryCache[contact.id]
if (contactBitMapAndName != null &&
contactBitMapAndName is ContactBitmapAndName.CardBitmap &&
contactBitMapAndName.bitmap != null) {
Timber.v("Retruning face bitmap for ${contact.id} from cache")
return@withContext contactBitMapAndName.bitmap
}
return@withContext contact.face?.run {
// There's a base64 face pic. Decode and cache it.
toByteArray()
.run { Base64.decode(this, Base64.DEFAULT) }
.run { BitmapFactory.decodeByteArray(this, 0, size) }
.run {
getRoundedShape(Bitmap.createScaledBitmap(this, faceDimensions, faceDimensions, true))
}
.also { bitmap ->
memoryCache.put(
contact.id, ContactBitmapAndName.CardBitmap(contact.displayName, bitmap))
}
}
?: run {
// No face pic. Generate a fallback bitmap and cache it.
memoryCache[contact.id]?.run {
if (this is ContactBitmapAndName.TrackerIdBitmap &&
this.trackerId == contact.trackerId) {
this.bitmap
} else {
null
}
}
?: run {
getFallbackBitmap(contact.trackerId, contact.id).also { bitmap ->
memoryCache.put(
contact.id, ContactBitmapAndName.TrackerIdBitmap(contact.trackerId, bitmap))
}
}
}
}
}
private fun getFallbackBitmap(text: String, colorKey: String): Bitmap =
drawableToBitmap(
TextDrawable.Builder()
.buildRoundRect(
text, TextDrawable.ColorGenerator.MATERIAL.getColor(colorKey), faceDimensions))
private fun getRoundedShape(bitmap: Bitmap): Bitmap {
val output = Bitmap.createBitmap(bitmap.width, bitmap.height, Bitmap.Config.ARGB_8888)
val canvas = Canvas(output)
val color = -0xbdbdbe
val paint = Paint()
val rect = Rect(0, 0, bitmap.width, bitmap.height)
val rectF = RectF(rect)
val roundPx = bitmap.width.toFloat()
paint.isAntiAlias = true
canvas.drawARGB(0, 0, 0, 0)
paint.color = color
canvas.drawRoundRect(rectF, roundPx, roundPx, paint)
paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN)
canvas.drawBitmap(bitmap, rect, rect, paint)
return output
}
private fun drawableToBitmap(drawable: Drawable): Bitmap {
if (drawable is BitmapDrawable) {
return drawable.bitmap
}
var width = drawable.intrinsicWidth
width = if (width > 0) width else faceDimensions
var height = drawable.intrinsicHeight
height = if (height > 0) height else faceDimensions
val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
drawable.setBounds(0, 0, canvas.width, canvas.height)
drawable.draw(canvas)
return bitmap
}
}
| 0
|
Kotlin
|
3
| 5
|
110c39d811a1074b2e9288cfe70d3089b5658806
| 4,557
|
hubitat
|
Apache License 2.0
|
app/common/src/main/kotlin/me/zhanghai/android/files/fileproperties/FilePropertiesFileViewModel.kt
|
overphoenix
| 621,371,055
| false
| null |
/*
* Copyright (c) 2019 <NAME> <<EMAIL>>
* All Rights Reserved.
*/
package me.zhanghai.android.files.fileproperties
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import me.zhanghai.android.files.file.FileItem
import me.zhanghai.android.files.util.Stateful
class FilePropertiesFileViewModel(file: FileItem) : ViewModel() {
private val _fileLiveData = FileLiveData(file)
val fileLiveData: LiveData<Stateful<FileItem>>
get() = _fileLiveData
fun reload() {
_fileLiveData.loadValue()
}
override fun onCleared() {
_fileLiveData.close()
}
}
| 0
|
Kotlin
|
0
| 0
|
64264f261c2138d5f1932789702661917bbfae28
| 615
|
phoenix-android
|
Apache License 2.0
|
straight/src/commonMain/kotlin/me/localx/icons/straight/filled/PeopleDress.kt
|
localhostov
| 808,861,591
| false
|
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
|
package me.localx.icons.straight.filled
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.Filled.PeopleDress: ImageVector
get() {
if (_peopleDress != null) {
return _peopleDress!!
}
_peopleDress = Builder(name = "PeopleDress", defaultWidth = 512.0.dp, defaultHeight =
512.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) {
moveTo(3.5f, 2.5f)
curveToRelative(0.0f, -1.38f, 1.12f, -2.5f, 2.5f, -2.5f)
reflectiveCurveToRelative(2.5f, 1.12f, 2.5f, 2.5f)
reflectiveCurveToRelative(-1.12f, 2.5f, -2.5f, 2.5f)
reflectiveCurveToRelative(-2.5f, -1.12f, -2.5f, -2.5f)
close()
moveTo(11.13f, 20.0f)
horizontalLineToRelative(-2.13f)
verticalLineToRelative(4.0f)
horizontalLineToRelative(-2.0f)
verticalLineToRelative(-4.0f)
horizontalLineToRelative(-2.0f)
verticalLineToRelative(4.0f)
lineTo(3.0f, 24.0f)
verticalLineToRelative(-4.0f)
lineTo(0.87f, 20.0f)
lineToRelative(1.42f, -11.37f)
curveToRelative(0.19f, -1.5f, 1.47f, -2.63f, 2.98f, -2.63f)
horizontalLineToRelative(1.47f)
curveToRelative(1.51f, 0.0f, 2.79f, 1.13f, 2.98f, 2.63f)
lineToRelative(1.42f, 11.37f)
close()
moveTo(18.0f, 5.0f)
curveToRelative(1.38f, 0.0f, 2.5f, -1.12f, 2.5f, -2.5f)
reflectiveCurveToRelative(-1.12f, -2.5f, -2.5f, -2.5f)
reflectiveCurveToRelative(-2.5f, 1.12f, -2.5f, 2.5f)
reflectiveCurveToRelative(1.12f, 2.5f, 2.5f, 2.5f)
close()
moveTo(21.0f, 20.0f)
verticalLineToRelative(4.0f)
horizontalLineToRelative(-2.0f)
verticalLineToRelative(-4.0f)
horizontalLineToRelative(-2.0f)
verticalLineToRelative(4.0f)
horizontalLineToRelative(-2.0f)
verticalLineToRelative(-4.0f)
horizontalLineToRelative(-2.13f)
lineToRelative(1.42f, -11.37f)
curveToRelative(0.19f, -1.5f, 1.47f, -2.63f, 2.98f, -2.63f)
horizontalLineToRelative(1.47f)
curveToRelative(1.51f, 0.0f, 2.79f, 1.13f, 2.98f, 2.63f)
lineToRelative(1.42f, 11.37f)
horizontalLineToRelative(-2.13f)
close()
}
}
.build()
return _peopleDress!!
}
private var _peopleDress: ImageVector? = null
| 1
|
Kotlin
|
0
| 5
|
cbd8b510fca0e5e40e95498834f23ec73cc8f245
| 3,436
|
icons
|
MIT License
|
sdk/mfa/src/main/java/com/ibm/security/verifysdk/mfa/onprem/model/EnrollmentResult.kt
|
ibm-security-verify
| 430,929,749
| false
|
{"Kotlin": 558859}
|
/*
* Copyright contributors to the IBM Security Verify SDK for Android project
*/
package com.ibm.security.verifysdk.mfa.model.onprem
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class EnrollmentResult(
val totalResults: Int,
val schemas: List<String>,
@SerialName("Resources")
val resources: List<Resources>
)
@Serializable
data class Resources(
val meta: Meta,
val id: String,
val userName: String,
@SerialName("urn:ietf:params:scim:schemas:extension:isam:1.0:MMFA:Authenticator")
val authenticator: Authenticator
)
@Serializable
data class Meta(
val location: String,
val resourceType: String
)
@Serializable
data class Authenticator(
val userPresenceMethods: List<UserPresenceMethod>? = null,
val fingerprintMethods: List<FingerprintMethod>? = null
)
@Serializable
data class UserPresenceMethod(
val id: String,
val keyHandle: String,
val authenticator: String,
val enabled: Boolean,
val algorithm: String
)
@Serializable
data class FingerprintMethod(
val id: String,
val keyHandle: String,
val authenticator: String,
val enabled: Boolean,
val algorithm: String
)
| 1
|
Kotlin
|
4
| 0
|
612fed1c3206e3b952c86df44109aeab8b7e7ae7
| 1,229
|
verify-sdk-android
|
MIT License
|
random/src/commonTest/kotlin/diglol/crypto/random/RandomTest.kt
|
diglol
| 398,510,327
| false
|
{"C": 284748, "Kotlin": 239933, "Objective-C": 44341, "JavaScript": 684}
|
package diglol.crypto.random
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertTrue
import kotlin.test.fail
class RandomTest {
@Test
fun nextInt() {
assertFailsWith<IllegalArgumentException> { nextInt(0) }
assertFailsWith<IllegalArgumentException> { nextInt(-1) }
assertFailsWith<IllegalArgumentException> { nextInt(Int.MIN_VALUE) }
repeat(100) {
assertEquals(0, nextInt(1))
}
for (bound in arrayOf(1, 9, 29, 0x900_0000, Int.MAX_VALUE)) {
repeat(100) {
val x = nextInt(bound)
if (x !in 0 until bound)
fail("Value $x must be in range [0, $bound)")
}
}
}
@Test
fun nextEmptyBytes() {
assertTrue(nextBytes(0).isEmpty())
}
fun nextBytesCheckLastBytes() {
assertFalse(nextBytes(4).takeLast(4).all { it.toInt() == 0 })
assertFalse(nextBytes(65540).takeLast(4).all { it.toInt() == 0 })
}
@Test
fun nextBytes() {
val size = 100
val bytes1 = nextBytes(size)
assertEquals(bytes1.size, size)
val result = mutableSetOf<ByteArray>()
repeat(100) {
assertTrue(result.add(nextBytes(10)))
}
assertTrue(nextBytes(65535).size == 65535)
assertTrue(nextBytes(65536).size == 65536)
assertTrue(nextBytes(65537).size == 65537)
assertTrue(nextBytes(100000).size == 100000)
}
}
| 4
|
C
|
4
| 21
|
3ee370a5be809789cee99c155e59dede23d37230
| 1,410
|
crypto
|
Apache License 2.0
|
app/src/main/java/mk/webfactory/template/feature/launcher/ui/LauncherActivity.kt
|
tstefanovska
| 239,505,295
| true
|
{"Kotlin": 68280, "Java": 8476}
|
package mk.webfactory.template.feature.launcher.ui
import android.content.Intent
import android.os.Bundle
import mk.webfactory.template.R
import mk.webfactory.template.feature.common.ui.BaseActivity
import mk.webfactory.template.feature.home.ui.HomeActivity
import mk.webfactory.template.model.user.UserSession
import mk.webfactory.template.user.UserManager
import javax.inject.Inject
class LauncherActivity : BaseActivity() {
@Inject
lateinit var userManager: UserManager<UserSession>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_container)
startActivity(Intent(this@LauncherActivity, HomeActivity::class.java))
if (userManager.isLoggedIn()) {
//startActivity(new Intent(LauncherActivity.this, HomeActivity.class));
//finish();
}
}
}
| 0
| null |
0
| 0
|
7176532a94fbbcf6729fb8e4871b9c619f77f02a
| 894
|
android-template
|
MIT License
|
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/quicksight/CfnDataSetStringDatasetParameterPropertyDsl.kt
|
cloudshiftinc
| 667,063,030
| false
|
{"Kotlin": 63959868}
|
@file:Suppress(
"RedundantVisibilityModifier",
"RedundantUnitReturnType",
"RemoveRedundantQualifierName",
"unused",
"UnusedImport",
"ClassName",
"REDUNDANT_PROJECTION",
"DEPRECATION"
)
package cloudshift.awscdk.dsl.services.quicksight
import cloudshift.awscdk.common.CdkDslMarker
import kotlin.String
import software.amazon.awscdk.IResolvable
import software.amazon.awscdk.services.quicksight.CfnDataSet
/**
* A parameter created in the dataset of string data type.</p>.
*
* Example:
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import software.amazon.awscdk.services.quicksight.*;
* StringDatasetParameterProperty stringDatasetParameterProperty =
* StringDatasetParameterProperty.builder()
* .id("id")
* .name("name")
* .valueType("valueType")
* // the properties below are optional
* .defaultValues(StringDatasetParameterDefaultValuesProperty.builder()
* .staticValues(List.of("staticValues"))
* .build())
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-quicksight-dataset-stringdatasetparameter.html)
*/
@CdkDslMarker
public class CfnDataSetStringDatasetParameterPropertyDsl {
private val cdkBuilder: CfnDataSet.StringDatasetParameterProperty.Builder =
CfnDataSet.StringDatasetParameterProperty.builder()
/**
* @param defaultValues List of default values defined for a given string dataset parameter
* type. Currently only static values are supported.</p>
*/
public fun defaultValues(defaultValues: IResolvable) {
cdkBuilder.defaultValues(defaultValues)
}
/**
* @param defaultValues List of default values defined for a given string dataset parameter
* type. Currently only static values are supported.</p>
*/
public fun defaultValues(
defaultValues: CfnDataSet.StringDatasetParameterDefaultValuesProperty
) {
cdkBuilder.defaultValues(defaultValues)
}
/** @param id Identifier of the parameter created in the dataset.</p>. */
public fun id(id: String) {
cdkBuilder.id(id)
}
/** @param name Name of the parameter created in the dataset.</p>. */
public fun name(name: String) {
cdkBuilder.name(name)
}
/**
* @param valueType Every parameter value could be either a single value or multi value which
* helps to validate before evaluation.</p>.
*/
public fun valueType(valueType: String) {
cdkBuilder.valueType(valueType)
}
public fun build(): CfnDataSet.StringDatasetParameterProperty = cdkBuilder.build()
}
| 3
|
Kotlin
|
0
| 3
|
c59c6292cf08f0fc3280d61e7f8cff813a608a62
| 2,701
|
awscdk-dsl-kotlin
|
Apache License 2.0
|
extension-compose/src/main/java/com/mapbox/maps/extension/compose/style/layers/generated/RasterParticleLayer.kt
|
mapbox
| 330,365,289
| false
|
{"Kotlin": 3551866, "Java": 89114, "Python": 18705, "Shell": 11465, "C++": 10129, "JavaScript": 4344, "Makefile": 2847, "CMake": 1201, "EJS": 1194}
|
// This file is generated.
package com.mapbox.maps.extension.compose.style.layers.generated
import androidx.compose.runtime.Composable
import androidx.compose.runtime.ComposeNode
import androidx.compose.runtime.currentComposer
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import com.mapbox.maps.MapboxExperimental
import com.mapbox.maps.extension.compose.MapboxMapComposable
import com.mapbox.maps.extension.compose.internal.MapApplier
import com.mapbox.maps.extension.compose.style.ColorValue
import com.mapbox.maps.extension.compose.style.DoubleValue
import com.mapbox.maps.extension.compose.style.IdGenerator.generateRandomLayerId
import com.mapbox.maps.extension.compose.style.LongValue
import com.mapbox.maps.extension.compose.style.StringValue
import com.mapbox.maps.extension.compose.style.Transition
import com.mapbox.maps.extension.compose.style.layers.Filter
import com.mapbox.maps.extension.compose.style.layers.internal.LayerNode
import com.mapbox.maps.extension.compose.style.sources.SourceState
/**
* Particle animation driven by textures such as wind maps.
*
* @see [The online documentation](https://docs.mapbox.com/style-spec/reference/layers#raster-particle)
*
* @param sourceState the source that drives this layer.
* @param layerId the ID of the layer, by default, a random id will be generated with UUID.
* @param rasterParticleArrayBand Displayed band of raster array source layer
* @param rasterParticleColor Defines a color map by which to colorize a raster particle layer, parameterized by the `["raster-particle-speed"]` expression and evaluated at 256 uniformly spaced steps over the range specified by `raster-particle-max-speed`.
* @param rasterParticleCount Defines the amount of particles per tile.
* @param rasterParticleFadeOpacityFactor Defines defines the opacity coefficient applied to the faded particles in each frame. In practice, this property controls the length of the particle tail.
* @param rasterParticleFadeOpacityFactorTransition Defines the transition of [rasterParticleFadeOpacityFactor].
* @param rasterParticleMaxSpeed Defines the maximum speed for particles. Velocities with magnitudes equal to or exceeding this value are clamped to the max value.
* @param rasterParticleResetRateFactor Defines a coefficient for a time period at which particles will restart at a random position, to avoid degeneration (empty areas without particles).
* @param rasterParticleSpeedFactor Defines a coefficient for the speed of particles’ motion.
* @param rasterParticleSpeedFactorTransition Defines the transition of [rasterParticleSpeedFactor].
* @param visibility Whether this layer is displayed.
* @param minZoom The minimum zoom level for the layer. At zoom levels less than the minzoom, the layer will be hidden.
* @param maxZoom The maximum zoom level for the layer. At zoom levels equal to or greater than the maxzoom, the layer will be hidden.
* @param sourceLayer Layer to use from a vector tile source. Required for vector tile sources; prohibited for all other source types, including GeoJSON sources.
* @param filter An expression specifying conditions on source features. Only features that match the filter are displayed. Zoom expressions in filters are only evaluated at integer zoom levels. The `["feature-state", ...]` expression is not supported in filter expressions. The `["pitch"]` and `["distance-from-center"]` expressions are supported only for filter expressions on the symbol layer.
*/
@MapboxExperimental
@Composable
@MapboxMapComposable
public fun RasterParticleLayer(
sourceState: SourceState,
layerId: String = remember {
generateRandomLayerId("raster-particle")
},
rasterParticleArrayBand: StringValue = StringValue.INITIAL,
rasterParticleColor: ColorValue = ColorValue.INITIAL,
rasterParticleCount: LongValue = LongValue.INITIAL,
rasterParticleFadeOpacityFactor: DoubleValue = DoubleValue.INITIAL,
rasterParticleFadeOpacityFactorTransition: Transition = Transition.INITIAL,
rasterParticleMaxSpeed: DoubleValue = DoubleValue.INITIAL,
rasterParticleResetRateFactor: DoubleValue = DoubleValue.INITIAL,
rasterParticleSpeedFactor: DoubleValue = DoubleValue.INITIAL,
rasterParticleSpeedFactorTransition: Transition = Transition.INITIAL,
visibility: VisibilityValue = VisibilityValue.INITIAL,
minZoom: LongValue = LongValue.INITIAL,
maxZoom: LongValue = LongValue.INITIAL,
sourceLayer: StringValue = StringValue.INITIAL,
filter: Filter = Filter.INITIAL,
) {
val mapApplier = currentComposer.applier as? MapApplier
?: throw IllegalStateException("Illegal use of RasterParticleLayer inside unsupported composable function")
val coroutineScope = rememberCoroutineScope()
ComposeNode<LayerNode, MapApplier>(
factory = {
LayerNode(
map = mapApplier.mapView.mapboxMap,
layerType = "raster-particle",
sourceState = sourceState,
layerId = layerId,
coroutineScope = coroutineScope
)
},
update = {
init {
if (rasterParticleArrayBand.notInitial) {
setProperty("raster-particle-array-band", rasterParticleArrayBand.value)
}
if (rasterParticleColor.notInitial) {
setProperty("raster-particle-color", rasterParticleColor.value)
}
if (rasterParticleCount.notInitial) {
setProperty("raster-particle-count", rasterParticleCount.value)
}
if (rasterParticleFadeOpacityFactor.notInitial) {
setProperty("raster-particle-fade-opacity-factor", rasterParticleFadeOpacityFactor.value)
}
if (rasterParticleFadeOpacityFactorTransition.notInitial) {
setProperty("raster-particle-fade-opacity-factor-transition", rasterParticleFadeOpacityFactorTransition.value)
}
if (rasterParticleMaxSpeed.notInitial) {
setProperty("raster-particle-max-speed", rasterParticleMaxSpeed.value)
}
if (rasterParticleResetRateFactor.notInitial) {
setProperty("raster-particle-reset-rate-factor", rasterParticleResetRateFactor.value)
}
if (rasterParticleSpeedFactor.notInitial) {
setProperty("raster-particle-speed-factor", rasterParticleSpeedFactor.value)
}
if (rasterParticleSpeedFactorTransition.notInitial) {
setProperty("raster-particle-speed-factor-transition", rasterParticleSpeedFactorTransition.value)
}
if (visibility.notInitial) {
setProperty("visibility", visibility.value)
}
if (minZoom.notInitial) {
setProperty("min-zoom", minZoom.value)
}
if (maxZoom.notInitial) {
setProperty("max-zoom", maxZoom.value)
}
if (sourceLayer.notInitial) {
setProperty("source-layer", sourceLayer.value)
}
if (filter.notInitial) {
setProperty("filter", filter.value)
}
}
update(sourceState) {
updateSource(sourceState)
}
update(layerId) {
updateLayerId(layerId)
}
update(rasterParticleArrayBand) {
setProperty("raster-particle-array-band", rasterParticleArrayBand.value)
}
update(rasterParticleColor) {
setProperty("raster-particle-color", rasterParticleColor.value)
}
update(rasterParticleCount) {
setProperty("raster-particle-count", rasterParticleCount.value)
}
update(rasterParticleFadeOpacityFactor) {
setProperty("raster-particle-fade-opacity-factor", rasterParticleFadeOpacityFactor.value)
}
update(rasterParticleFadeOpacityFactorTransition) {
setProperty("raster-particle-fade-opacity-factor-transition", rasterParticleFadeOpacityFactorTransition.value)
}
update(rasterParticleMaxSpeed) {
setProperty("raster-particle-max-speed", rasterParticleMaxSpeed.value)
}
update(rasterParticleResetRateFactor) {
setProperty("raster-particle-reset-rate-factor", rasterParticleResetRateFactor.value)
}
update(rasterParticleSpeedFactor) {
setProperty("raster-particle-speed-factor", rasterParticleSpeedFactor.value)
}
update(rasterParticleSpeedFactorTransition) {
setProperty("raster-particle-speed-factor-transition", rasterParticleSpeedFactorTransition.value)
}
update(visibility) {
setProperty("visibility", visibility.value)
}
update(minZoom) {
setProperty("min-zoom", minZoom.value)
}
update(maxZoom) {
setProperty("max-zoom", maxZoom.value)
}
update(sourceLayer) {
setProperty("source-layer", sourceLayer.value)
}
update(filter) {
setProperty("filter", filter.value)
}
}
)
sourceState.UpdateProperties()
}
// End of generated file.
| 216
|
Kotlin
|
126
| 435
|
7faf620b4694bd50f4b4399abcf6eca29e3173ba
| 8,830
|
mapbox-maps-android
|
Apache License 2.0
|
stencil/src/main/kotlin/io/ight/gradle/stencil/Stencil.kt
|
WOCOMLABS
| 796,096,413
| false
|
{"Kotlin": 38345}
|
package io.ight.gradle.stencil
object Stencil {
object Gitignore
object Gradle
object Html
object Kt
object Md
object Yml
object Kts
object Properties
}
| 3
|
Kotlin
|
0
| 0
|
eb5afa7cfe7187297787539721d50ea4891b8767
| 187
|
artesano
|
MIT License
|
src/me/egorand/kotlin/playground/misc/ThisExpression.kt
|
Egorand
| 53,359,960
| false
| null |
/*
* Copyright 2016 <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 me.egorand.kotlin.playground.misc
class AA {
inner class B {
fun Int.foo() {
val a = this@AA
val b = this@B
val c = this
val c1 = this@foo
val funLit = lambda@ fun String.() {
val d = this
}
val funLit2 = { s: String ->
val d = this
}
}
}
}
| 0
|
Kotlin
|
1
| 0
|
4c82596c75a8dc4046df565e08f75bafd0365887
| 967
|
kotlin-playground
|
Apache License 2.0
|
sebenza 2/app/src/main/java/com/example/myapplication/VideoActivity.kt
|
FeliciaFeli
| 402,631,186
| false
|
{"Kotlin": 8288}
|
package com.example.myapplication
import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.provider.MediaStore
import android.widget.Button
import android.widget.ImageView
import android.widget.VideoView
class VideoActivity : AppCompatActivity() {
private val REQUEST_CODE_VIDEO=100
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_video)
val button =findViewById<Button>(R.id.button)
val videoView=findViewById<VideoView>(R.id.videoView)
button.setOnClickListener {
this.CaptureVideo()
}
private fun CaptureVideo() {
val cameraIntent = Intent(MediaStore.ACTION_VIDEO_CAPTURE)
startActivityForResult(cameraIntent,REQUEST_CODE_VIDEO)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode== RESULT_OK && requestCode==REQUEST_CODE_VIDEO&&data!=null){
val videoView = null
videoView.run {
setVideoBitmap.Bitmap(data.extras?.get("data") as Bitmap)
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
4cc8bcdbc1b402404de8ab6faeef294319b59dca
| 1,339
|
sebenza
|
Boost Software License 1.0
|
app/src/main/java/org/citruscircuits/viewer/convertToFilteredTeamsList.kt
|
frc1678
| 648,314,733
| false
| null |
package org.citruscircuits.viewer
/**
* @param teamsList The list of teams to be converted to a map of current rankings
*/
fun convertToFilteredTeamsList(teamsList: List<String>): List<String> {
val unsortedMap = HashMap<String, Double?>()
for (team in teamsList) {
unsortedMap[team] =
if (getTeamObjectByKey(team, "current_rank") != null)
getTeamObjectByKey(team, "current_rank")?.toDouble()
else 1000.0
}
return unsortedMap.toList().sortedBy { (_, value) -> value }.toMap().keys.toList()
}
| 0
|
Kotlin
|
0
| 0
|
466d49fc47e6d7cd7ae9f11140a208942b621f63
| 558
|
viewer-2023-public
|
MIT License
|
vpn/src/test/java/com/duckduckgo/mobile/android/vpn/breakage/ReportBreakageContractTest.kt
|
cmonfortep
| 252,403,423
| false
| null |
/*
* Copyright (c) 2021 DuckDuckGo
*
* 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.duckduckgo.mobile.android.vpn.breakage
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class ReportBreakageContractTest {
private val context = InstrumentationRegistry.getInstrumentation().targetContext
@Test
fun whenCreateIntentForIssueDescriptionFormThenReturnCorrectIntent() {
val intent = ReportBreakageContract().createIntent(context, ReportBreakageScreen.IssueDescriptionForm("myApp", "my.package.com"))
assertEquals(ReportBreakageCategorySingleChoiceActivity::class.java.canonicalName, intent.component?.className)
}
@Test
fun whenCreateIntentForListOfInstalledAppsThenReturnCorrectIntent() {
val intent = ReportBreakageContract().createIntent(context, ReportBreakageScreen.ListOfInstalledApps)
assertEquals(ReportBreakageAppListActivity::class.java.canonicalName, intent.component?.className)
}
}
| 51
| null |
786
| 3
|
228a1217aad96d19f90750d94664b7a4a5744c9a
| 1,666
|
Android
|
Apache License 2.0
|
core/ui/components/src/main/kotlin/top/chengdongqing/weui/core/ui/components/steps/Steps.kt
|
chengdongqing
| 782,566,304
| false
|
{"Kotlin": 894390}
|
package top.chengdongqing.weui.core.ui.components.steps
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.sizeIn
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.unit.dp
@Composable
fun WeSteps(
options: List<(@Composable () -> Unit)?>,
value: Int = 0,
isVertical: Boolean = true
) {
if (isVertical) {
Column {
StepList(options, value, true)
}
} else {
Row {
StepList(options, value, false)
}
}
}
@Composable
fun StepList(items: List<(@Composable () -> Unit)?>, value: Int, isVertical: Boolean) {
items.forEachIndexed { index, content ->
StepItem(
isActive = index <= value,
isFirst = index == 0,
isLast = index == items.lastIndex,
isLastActive = index == value,
isVertical,
content
)
}
}
@Composable
private fun StepItem(
isActive: Boolean,
isFirst: Boolean,
isLast: Boolean,
isLastActive: Boolean,
isVertical: Boolean,
content: (@Composable () -> Unit)?
) {
val activeColor = MaterialTheme.colorScheme.primary
val defaultColor = MaterialTheme.colorScheme.outline
Box(
contentAlignment = if (isVertical) Alignment.TopStart else Alignment.TopCenter,
modifier = Modifier
.drawBehind {
val color = if (isActive) activeColor else defaultColor
val offset = 12.dp.toPx()
// 绘制小圆点
drawCircle(
color = color,
radius = 4.dp.toPx(),
center = Offset(if (isVertical) offset else size.width / 2, offset)
)
// 绘制连接线
if (isVertical) {
if (!isLast) {
drawLine(
color = if (isLastActive) defaultColor else color,
start = Offset(offset, offset * 2),
end = Offset(offset, size.height),
strokeWidth = 1.dp.toPx()
)
}
} else {
if (!isFirst) {
drawLine(
color = color,
start = Offset(0f, offset),
end = Offset(size.width / 2 - offset, offset),
strokeWidth = 1.dp.toPx()
)
}
if (!isLast) {
drawLine(
color = if (isLastActive) defaultColor else color,
start = Offset(size.width / 2 + offset, offset),
end = Offset(size.width, offset),
strokeWidth = 1.dp.toPx()
)
}
}
}
.padding(if (isVertical) PaddingValues(start = 36.dp) else PaddingValues(top = 36.dp))
.sizeIn(
if (isVertical) 0.dp else 80.dp,
if (!isVertical) 0.dp else 80.dp
)
) {
content?.invoke()
}
}
| 0
|
Kotlin
|
3
| 8
|
eb773e75aacb801cb24adb41db9fe17224eb883a
| 3,649
|
WeUI
|
Apache License 2.0
|
src/main/kotlin/org/valkyrienskies/core/util/serialization/JOMLSerializationModule.kt
|
ValkyrienSkies
| 329,044,944
| false
| null |
package org.valkyrienskies.core.util.serialization
import com.fasterxml.jackson.annotation.JsonAutoDetect
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.ANY
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.NONE
import com.fasterxml.jackson.databind.module.SimpleModule
import org.joml.Matrix3d
import org.joml.Matrix3dc
import org.joml.Matrix3f
import org.joml.Matrix3fc
import org.joml.Matrix4d
import org.joml.Matrix4dc
import org.joml.Matrix4f
import org.joml.Matrix4fc
import org.joml.Quaterniond
import org.joml.Quaterniondc
import org.joml.Quaternionf
import org.joml.Quaternionfc
import org.joml.Vector3d
import org.joml.Vector3dc
import org.joml.Vector3f
import org.joml.Vector3fc
import org.joml.Vector3i
import org.joml.Vector3ic
import org.joml.primitives.AABBd
import org.joml.primitives.AABBdc
import org.joml.primitives.AABBf
import org.joml.primitives.AABBfc
import org.joml.primitives.AABBi
import org.joml.primitives.AABBic
class JOMLSerializationModule : SimpleModule() {
@JsonAutoDetect(fieldVisibility = ANY, setterVisibility = NONE, getterVisibility = NONE, isGetterVisibility = NONE)
private object JOMLMixin
init {
setupJOMLClass<Vector3ic, Vector3i>()
setupJOMLClass<Vector3fc, Vector3f>()
setupJOMLClass<Vector3dc, Vector3d>()
setupJOMLClass<Quaternionfc, Quaternionf>()
setupJOMLClass<Quaterniondc, Quaterniond>()
setupJOMLClass<Matrix4fc, Matrix4f>()
setupJOMLClass<Matrix4dc, Matrix4d>()
setupJOMLClass<Matrix3fc, Matrix3f>()
setupJOMLClass<Matrix3dc, Matrix3d>()
setupJOMLClass<AABBic, AABBi>()
setupJOMLClass<AABBfc, AABBf>()
setupJOMLClass<AABBdc, AABBd>()
}
private inline fun <reified A, reified B : A> setupJOMLClass() {
addAbstractTypeMapping<A, B>()
setMixInAnnotation<B, JOMLMixin>()
}
}
| 2
|
Kotlin
|
0
| 1
|
a9623e844643f6fa3cb38cbaed6ef1f349aaa205
| 1,906
|
vs-core
|
Apache License 2.0
|
common/build/generated/sources/schemaCode/kotlin/main/io/portone/sdk/server/schemas/IdentityVerificationAlreadySentError.kt
|
portone-io
| 809,427,199
| false
|
{"Kotlin": 385115, "Java": 331}
|
package io.portone.sdk.server.schemas
import kotlin.String
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
/**
* 본인인증 건이 이미 API로 요청된 상태인 경우
*/
@Serializable
@SerialName("IDENTITY_VERIFICATION_ALREADY_SENT")
internal data class IdentityVerificationAlreadySentError(
override val message: String? = null,
) : SendIdentityVerificationError
| 0
|
Kotlin
|
0
| 2
|
f984c4cc31aa64aad5cd0fa0497bdd490a0fe33a
| 377
|
server-sdk-jvm
|
MIT License
|
app/src/main/java/com/azhar/newsapp/model/ModelNews.kt
|
AzharRivaldi
| 357,422,469
| false
| null |
package itts.bayu.newsapp.model
import com.google.gson.annotations.SerializedName
/**
* Created by <NAME> on 10-04-2021
* Github : https://github.com/AzharRivaldi
* Linkedin : https://www.linkedin.com/in/azhar-rivaldi
* Instagram : https://www.instagram.com/azhardvls_
* Twitter : https://twitter.com/azharrvldi_
* Youtube Channel : https://bit.ly/2PJMowZ
*/
data class ModelNews(
@SerializedName("status")
val status: String = "",
@SerializedName("totalResults")
val totalResults: Int = 0,
@SerializedName("articles")
val modelArticle: List<ModelArticle> = emptyList()
)
data class ModelResultToken(
@SerializedName("status")
val status: String = ""
)
| 1
|
Kotlin
|
9
| 9
|
247346cd10abfcc496c8b314560f971610d959c6
| 730
|
NewsApp
|
Apache License 2.0
|
src/main/kotlin/br/com/zup/academy/dto/KeyAddRequest.kt
|
Vitorodriguesantos
| 385,240,400
| true
|
{"Kotlin": 35306}
|
package br.com.zup.academy.dto
import br.com.zup.academy.KeyManagerRequest
import br.com.zup.academy.TipoDeChave
import br.com.zup.academy.TipoDeConta
import br.com.zup.academy.validacao.notacoes.ValidaTipoChave
import br.com.zup.academy.validacao.notacoes.ValidaTipoConta
import br.com.zup.academy.validacao.notacoes.ValidaUUID
import io.micronaut.core.annotation.Introspected
import javax.validation.constraints.NotBlank
@Introspected
data class KeyAddRequest(
@field:NotBlank @field:ValidaUUID val clienteId: String,
@field:NotBlank @field:ValidaTipoChave val tipoChave: String,
val valorChave: String?,
@field:NotBlank @field:ValidaTipoConta val tipoConta: String,
) {
fun converterGrpc(): KeyManagerRequest {
return KeyManagerRequest.newBuilder()
.setId(clienteId)
.setTipoDeChave(TipoDeChave.valueOf(tipoChave))
.setValorChave(valorChave)
.setTipoDeConta(TipoDeConta.valueOf(tipoConta))
.build()
}
}
| 0
|
Kotlin
|
0
| 0
|
3ac11be88a41eb31173b54c78960eba40fdf3213
| 1,000
|
orange-talents-05-template-pix-keymanager-rest
|
Apache License 2.0
|
app/src/main/java/es/animaldevs/app/network/AccuWeatherApi.kt
|
AnimalDevs
| 150,321,265
| false
| null |
package es.animaldevs.app.network
import es.animaldevs.app.model.network.weatherday.WeatherResponse
import io.reactivex.Observable
import retrofit2.http.GET
import retrofit2.http.Path
import retrofit2.http.Query
/**
* The interface which provides methods to get result of webservices
*/
interface AccuWeatherApi {
@GET("/forecasts/v1/daily/5day/{location_key}")
fun getWeatherDays(
@Path("location_key") locationKey: String,
@Query("apikey") apiKey: String,
@Query("language") language: String,
@Query("details") details: String,
@Query("metric") metric: String
): Observable<WeatherResponse>
}
| 0
|
Kotlin
|
0
| 0
|
89e5801043aded82d0d8c88fa83a1bf6841724eb
| 671
|
weather-kotlin-aac-mvvm
|
MIT License
|
core/src/main/kotlin/net/corda/core/utilities/ByteArrays.kt
|
corda
| 70,137,417
| false
| null |
@file:JvmName("ByteArrays")
@file:KeepForDJVM
package net.corda.core.utilities
import net.corda.core.KeepForDJVM
import net.corda.core.serialization.CordaSerializable
import java.io.ByteArrayInputStream
import java.io.OutputStream
import java.lang.Math.max
import java.lang.Math.min
import java.nio.ByteBuffer
/**
* An abstraction of a byte array, with offset and size that does no copying of bytes unless asked to.
*
* The data of interest typically starts at position [offset] within the [bytes] and is [size] bytes long.
*
* @property offset The start position of the sequence within the byte array.
* @property size The number of bytes this sequence represents.
*/
@KeepForDJVM
sealed class ByteSequence(private val _bytes: ByteArray, val offset: Int, val size: Int) : Comparable<ByteSequence> {
/**
* The underlying bytes. Some implementations may choose to make a copy of the underlying [ByteArray] for
* security reasons. For example, [OpaqueBytes].
*/
abstract val bytes: ByteArray
/** Returns a [ByteArrayInputStream] of the bytes. */
fun open() = ByteArrayInputStream(_bytes, offset, size)
/**
* Create a sub-sequence of this sequence. A copy of the underlying array may be made, if a subclass overrides
* [bytes] to do so, as [OpaqueBytes] does.
*
* @param offset The offset within this sequence to start the new sequence. Note: not the offset within the backing array.
* @param size The size of the intended sub sequence.
*/
@Suppress("MemberVisibilityCanBePrivate")
fun subSequence(offset: Int, size: Int): ByteSequence {
// Intentionally use bytes rather than _bytes, to mirror the copy-or-not behaviour of that property.
return if (offset == 0 && size == this.size) this else of(bytes, this.offset + offset, size)
}
companion object {
/**
* Construct a [ByteSequence] given a [ByteArray] and optional offset and size, that represents that potentially
* sub-sequence of bytes.
*/
@JvmStatic
@JvmOverloads
fun of(bytes: ByteArray, offset: Int = 0, size: Int = bytes.size): ByteSequence {
return OpaqueBytesSubSequence(bytes, offset, size)
}
}
/**
* Take the first n bytes of this sequence as a sub-sequence. See [subSequence] for further semantics.
*/
fun take(n: Int): ByteSequence = subSequence(0, n)
/**
* A new read-only [ByteBuffer] view of this sequence or part of it.
* If [start] or [end] are negative then [IllegalArgumentException] is thrown, otherwise they are clamped if necessary.
* This method cannot be used to get bytes before [offset] or after [offset]+[size], and never makes a new array.
*/
fun slice(start: Int = 0, end: Int = size): ByteBuffer {
require(start >= 0) { "Starting index must be greater than or equal to 0" }
require(end >= 0){"End index must be greater or equal to 0"}
val clampedStart = min(start, size)
val clampedEnd = min(end, size)
return ByteBuffer.wrap(_bytes, offset + clampedStart, max(0, clampedEnd - clampedStart)).asReadOnlyBuffer()
}
/** Write this sequence to an [OutputStream]. */
fun writeTo(output: OutputStream) = output.write(_bytes, offset, size)
/** Write this sequence to a [ByteBuffer]. */
fun putTo(buffer: ByteBuffer): ByteBuffer = buffer.put(_bytes, offset, size)
/**
* Copy this sequence, complete with new backing array. This can be helpful to break references to potentially
* large backing arrays from small sub-sequences.
*/
fun copy(): ByteSequence = of(copyBytes())
/** Same as [copy] but returns just the new byte array. */
fun copyBytes(): ByteArray = _bytes.copyOfRange(offset, offset + size)
/**
* Compare byte arrays byte by byte. Arrays that are shorter are deemed less than longer arrays if all the bytes
* of the shorter array equal those in the same position of the longer array.
*/
override fun compareTo(other: ByteSequence): Int {
val min = minOf(this.size, other.size)
val thisBytes = this._bytes
val otherBytes = other._bytes
// Compare min bytes
for (index in 0 until min) {
val unsignedThis = java.lang.Byte.toUnsignedInt(thisBytes[this.offset + index])
val unsignedOther = java.lang.Byte.toUnsignedInt(otherBytes[other.offset + index])
if (unsignedThis != unsignedOther) {
return Integer.signum(unsignedThis - unsignedOther)
}
}
// First min bytes is the same, so now resort to size.
return Integer.signum(this.size - other.size)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is ByteSequence) return false
if (this.size != other.size) return false
return subArraysEqual(this._bytes, this.offset, this.size, other._bytes, other.offset)
}
private fun subArraysEqual(a: ByteArray, aOffset: Int, length: Int, b: ByteArray, bOffset: Int): Boolean {
var bytesRemaining = length
var aPos = aOffset
var bPos = bOffset
while (bytesRemaining-- > 0) {
if (a[aPos++] != b[bPos++]) return false
}
return true
}
override fun hashCode(): Int {
val thisBytes = _bytes
var result = 1
for (index in offset until (offset + size)) {
result = 31 * result + thisBytes[index]
}
return result
}
override fun toString(): String = "[${copyBytes().toHexString()}]"
}
/**
* A simple class that wraps a byte array and makes the equals/hashCode/toString methods work as you actually expect.
* In an ideal JVM this would be a value type and be completely overhead free. Project Valhalla is adding such
* functionality to Java, but it won't arrive for a few years yet!
*/
@KeepForDJVM
@CordaSerializable
open class OpaqueBytes(bytes: ByteArray) : ByteSequence(bytes, 0, bytes.size) {
companion object {
/**
* Create [OpaqueBytes] from a sequence of [Byte] values.
*/
@JvmStatic
fun of(vararg b: Byte) = OpaqueBytes(byteArrayOf(*b))
}
init {
require(bytes.isNotEmpty()) { "Byte Array must not be empty" }
}
/**
* The bytes are always cloned so that this object becomes immutable. This has been done
* to prevent tampering with entities such as [net.corda.core.crypto.SecureHash] and [net.corda.core.contracts.PrivacySalt], as well as
* preserve the integrity of our hash constants [net.corda.core.crypto.SecureHash.zeroHash] and [net.corda.core.crypto.SecureHash.allOnesHash].
*
* Cloning like this may become a performance issue, depending on whether or not the JIT
* compiler is ever able to optimise away the clone. In which case we may need to revisit
* this later.
*/
final override val bytes: ByteArray = bytes
get() = field.clone()
}
/**
* Wrap [size] bytes from this [ByteArray] starting from [offset] into a new [ByteArray].
*/
fun ByteArray.sequence(offset: Int = 0, size: Int = this.size) = ByteSequence.of(this, offset, size)
/**
* Converts this [ByteArray] into a [String] of hexadecimal digits.
*/
fun ByteArray.toHexString(): String = printHexBinary(this)
private val hexCode = "0123456789ABCDEF".toCharArray()
private fun printHexBinary(data: ByteArray): String {
val r = StringBuilder(data.size * 2)
for (b in data) {
r.append(hexCode[(b.toInt() shr 4) and 0xF])
r.append(hexCode[b.toInt() and 0xF])
}
return r.toString()
}
/**
* Converts this [String] of hexadecimal digits into a [ByteArray].
* @throws IllegalArgumentException if the [String] contains incorrectly-encoded characters.
*/
fun String.parseAsHex(): ByteArray = parseHexBinary(this)
private fun parseHexBinary(s: String): ByteArray {
val len = s.length
// "111" is not a valid hex encoding.
if (len % 2 != 0) {
throw IllegalArgumentException("hexBinary needs to be even-length: $s")
}
val out = ByteArray(len / 2)
fun hexToBin(ch: Char): Int {
if (ch in '0'..'9') {
return ch - '0'
}
if (ch in 'A'..'F') {
return ch - 'A' + 10
}
return if (ch in 'a'..'f') {
ch - 'a' + 10
} else -1
}
var i = 0
while (i < len) {
val h = hexToBin(s[i])
val l = hexToBin(s[i + 1])
if (h == -1 || l == -1) {
throw IllegalArgumentException("contains illegal character for hexBinary: $s")
}
out[i / 2] = (h * 16 + l).toByte()
i += 2
}
return out
}
/**
* Class is public for serialization purposes.
*/
@KeepForDJVM
class OpaqueBytesSubSequence(override val bytes: ByteArray, offset: Int, size: Int) : ByteSequence(bytes, offset, size) {
init {
require(offset >= 0 && offset < bytes.size) { "Offset must be greater than or equal to 0, and less than the size of the backing array" }
require(size >= 0 && offset + size <= bytes.size) { "Sub-sequence size must be greater than or equal to 0, and less than the size of the backing array" }
}
}
| 62
| null |
1089
| 3,989
|
d27aa0e6850d3804d0982024054376d452e7073a
| 9,281
|
corda
|
Apache License 2.0
|
straight/src/commonMain/kotlin/me/localx/icons/straight/filled/TachometerFast.kt
|
localhostov
| 808,861,591
| false
|
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
|
package me.localx.icons.straight.filled
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.Filled.TachometerFast: ImageVector
get() {
if (_tachometerFast != null) {
return _tachometerFast!!
}
_tachometerFast = Builder(name = "TachometerFast", defaultWidth = 512.0.dp, defaultHeight =
512.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) {
moveTo(12.0f, 1.0f)
curveTo(0.374f, 0.982f, -4.414f, 16.17f, 5.112f, 22.818f)
lineToRelative(0.639f, 0.449f)
lineTo(8.0f, 20.0f)
horizontalLineToRelative(8.0f)
lineToRelative(2.249f, 3.267f)
lineToRelative(0.639f, -0.449f)
curveTo(28.418f, 16.166f, 23.621f, 0.98f, 12.0f, 1.0f)
close()
moveTo(10.586f, 14.414f)
arcToRelative(2.005f, 2.005f, 0.0f, false, true, 1.925f, -3.339f)
lineToRelative(5.146f, -5.146f)
lineToRelative(1.414f, 1.414f)
lineToRelative(-5.146f, 5.146f)
arcTo(2.005f, 2.005f, 0.0f, false, true, 10.586f, 14.414f)
close()
}
}
.build()
return _tachometerFast!!
}
private var _tachometerFast: ImageVector? = null
| 1
|
Kotlin
|
0
| 5
|
cbd8b510fca0e5e40e95498834f23ec73cc8f245
| 2,047
|
icons
|
MIT License
|
codebase/android/feature/accounts/src/main/java/com/makeappssimple/abhimanyu/financemanager/android/feature/accounts/edit_account/viewmodel/EditAccountScreenUIStateDelegate.kt
|
Abhimanyu14
| 429,663,688
| false
|
{"Kotlin": 1876553}
|
package com.makeappssimple.abhimanyu.financemanager.android.feature.accounts.edit_account.viewmodel
import androidx.compose.ui.text.input.TextFieldValue
import com.makeappssimple.abhimanyu.financemanager.android.core.model.Account
import com.makeappssimple.abhimanyu.financemanager.android.core.model.AccountType
import com.makeappssimple.abhimanyu.financemanager.android.feature.accounts.edit_account.bottomsheet.EditAccountScreenBottomSheetType
import com.makeappssimple.abhimanyu.financemanager.android.feature.accounts.edit_account.snackbar.EditAccountScreenSnackbarType
import kotlinx.collections.immutable.ImmutableList
import kotlinx.coroutines.flow.MutableSharedFlow
internal interface EditAccountScreenUIStateDelegate {
// region initial data
var currentAccount: Account?
val validAccountTypesForNewAccount: ImmutableList<AccountType>
// endregion
// region UI state
val refreshSignal: MutableSharedFlow<Unit>
val isLoading: Boolean
val balanceAmountValue: TextFieldValue
val minimumAccountBalanceAmountValue: TextFieldValue
val name: TextFieldValue
val screenBottomSheetType: EditAccountScreenBottomSheetType
val screenSnackbarType: EditAccountScreenSnackbarType
val selectedAccountTypeIndex: Int
// endregion
// region refresh
fun refresh()
// endregion
// region state events
fun clearBalanceAmountValue()
fun clearMinimumAccountBalanceAmountValue()
fun clearName()
fun completeLoading(
refresh: Boolean = true,
)
fun navigateUp()
fun resetScreenBottomSheetType()
fun startLoading(
refresh: Boolean = true,
)
fun updateAccount()
fun updateBalanceAmountValue(
updatedBalanceAmountValue: TextFieldValue,
refresh: Boolean = true,
)
fun updateMinimumAccountBalanceAmountValue(
updatedMinimumAccountBalanceAmountValue: TextFieldValue,
refresh: Boolean = true,
)
fun updateName(
updatedName: TextFieldValue,
refresh: Boolean = true,
)
fun updateScreenBottomSheetType(
updatedEditAccountScreenBottomSheetType: EditAccountScreenBottomSheetType,
refresh: Boolean = true,
)
fun updateScreenSnackbarType(
updatedEditAccountScreenSnackbarType: EditAccountScreenSnackbarType,
refresh: Boolean = true,
)
fun updateSelectedAccountTypeIndex(
updatedSelectedAccountTypeIndex: Int,
refresh: Boolean = true,
)
// endregion
}
| 11
|
Kotlin
|
0
| 3
|
7e080a68bc038bd64d2d406b75a49e8f1ea2a791
| 2,512
|
finance-manager
|
Apache License 2.0
|
idea/tests/testData/intentions/addNameToArgument/mixingPositionedAndNamedDisabled.kt
|
JetBrains
| 278,369,660
| false
| null |
// IS_APPLICABLE: false
// COMPILER_ARGUMENTS: -XXLanguage:-MixedNamedArgumentsInTheirOwnPosition
fun foo(s: String, b: Boolean){}
fun bar() {
foo(<caret>"", true)
}
| 1
|
Kotlin
|
37
| 71
|
b6789690db56407ae2d6d62746fb69dc99d68c84
| 171
|
intellij-kotlin
|
Apache License 2.0
|
backend/src/main/kotlin/com/denchic45/studiversity/setup/DatabaseSetup.kt
|
denchic45
| 435,895,363
| false
|
{"Kotlin": 2100300, "Vue": 10384, "JavaScript": 2497, "CSS": 1496, "HTML": 867}
|
package com.denchic45.studiversity.setup
import com.denchic45.studiversity.database.table.*
import org.jetbrains.exposed.sql.Column
import org.jetbrains.exposed.sql.SchemaUtils
import org.jetbrains.exposed.sql.Table
import org.jetbrains.exposed.sql.batchUpsert
import org.jetbrains.exposed.sql.transactions.transaction
import org.jetbrains.kotlinx.dataframe.DataFrame
import org.jetbrains.kotlinx.dataframe.api.rows
import org.jetbrains.kotlinx.dataframe.io.readCSV
import java.io.File
fun setupDatabase() = transaction {
// add tables
SchemaUtils.createMissingTablesAndColumns(
// user tables
Users, UsersRolesScopes, Roles, Scopes, Capabilities, // 5
// RolesScopes,
RolesCapabilities, RolesAssignments, ScopeTypes, RefreshTokens, MagicLinks, // 5
// study group tables
StudyGroups, StudyGroupsMembers, Specialties, // 3
// courses tables
Courses, CourseTopics, CourseElements, CourseWorks, CoursesStudyGroups, // 5
Subjects, Submissions, Grades, Enrollments, UserEnrollments, // 5
// timetable
Events, Lessons, Periods, PeriodsMembers, Rooms, // 5
// attachments
Attachments, AttachmentReferences // 2
)
// add scope types
// val scopeTypeId by column<Long>("scope_type_id")
// val scopeTypeName by column<String>("scope_type_name")
// val scopeTypeParent by column<Long?>("parent")
// val scopeTypesTable = DataFrame.readCSV(File("resources/installdata/scope_type.csv"))
// scopeTypesTable.forEach { row ->
// ScopeTypeDao.new(row[scopeTypeId]) {
// name = row[scopeTypeName]
// parent = row[scopeTypeParent]?.let { ScopeTypeDao[it] }
// }
// }
// add roles
// val roleId by column<Long>("role_id")
// val roleName by column<String>("role_name")
// val roleShortname by column<String>("shortname")
// val roleScopeTypeId by column<Long>("scope_type_id")
// val roleParent by column<Long?>("parent")
// val roleOrder by column<Int?>("role_order")
// val rolesTable = DataFrame.readCSV(File("resources/installdata/role.csv"))
// rolesTable.forEach { row ->
// RoleDao.new(row[roleId]) {
// name = row[roleName]
// shortname = row[roleShortname]
// scopeType = ScopeTypeDao[row[roleScopeTypeId]]
// parent = row[roleParent]?.let { RoleDao[it] }
// order = row[roleOrder]
// }
// }
// add capabilities
// val capabilityId by column<Long>("capability_id")
// val capabilityName by column<String>("capability_name")
// val capabilityResource by column<String>("capability_resource")
// val capabilityScopeTypeId by column<Long>("scope_type_id")
// val capabilitiesTable = DataFrame.readCSV(File("resources/installdata/capability.csv"))
// Capabilities.batchUpsert(capabilitiesTable.rows()) { row ->
// this[Capabilities.id] = row[capabilityId]
// this[Capabilities.name] = row[capabilityName]
// this[Capabilities.resource] = row[capabilityResource]
// this[Capabilities.scopeType] = row[capabilityScopeTypeId]
// }
// add role capabilities
// val permission by column<Permission>()
// val rolesCapabilitiesTable = DataFrame.readCSV(File("resources/installdata/role_capability.csv"))
// RolesCapabilities.batchUpsert(rolesCapabilitiesTable.rows()) { row ->
// this[RolesCapabilities.roleId] = row[roleId]
// this[RolesCapabilities.capabilityResource] = row[capabilityResource]
// this[RolesCapabilities.permission] = row[permission]
// }
// add roles assignments
// val assignableRoleId by column<Long>()
// val rolesAssignments = DataFrame.readCSV(File("resources/installdata/role_assignment.csv"))
// RolesAssignments.batchUpsert(rolesAssignments.rows()) { row ->
// this[RolesAssignments.roleId] = row[roleId]
// this[RolesAssignments.assignableRoleId] = row[assignableRoleId]
// }
// add roles capabilities
ScopeTypes.importFromCSV(DataFrame.readCSV(getFileWithCSV("scope_type")))
Roles.importFromCSV(DataFrame.readCSV(getFileWithCSV("role")))
Capabilities.importFromCSV(DataFrame.readCSV(getFileWithCSV("capability")))
RolesCapabilities.importFromCSV(DataFrame.readCSV(getFileWithCSV("role_capability")))
RolesAssignments.importFromCSV(DataFrame.readCSV(getFileWithCSV("role_assignment")))
}
private fun getFileWithCSV(tableName: String) = File("resources/installdata/$tableName.csv")
fun Table.importFromCSV(
dataframe: DataFrame<*>
) {
batchUpsert(dataframe.rows()) { row ->
columns.forEach { column ->
this[column as Column<Any?>] = row.get(column.name)
}
}
}
| 0
|
Kotlin
|
0
| 5
|
8ebbe8dfa5e6f590bf2c2f22a08867177a7abf60
| 4,734
|
Studiversity
|
Apache License 2.0
|
app/src/main/java/io/aethibo/kart/features/products/presentation/components/SearchProductItem.kt
|
primepixel
| 626,035,115
| false
| null |
package io.aethibo.kart.features.products.presentation.components
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Icon
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.unit.dp
import io.aethibo.kart.R
@Composable
fun SearchProductItem() {
var searchFieldText by remember { mutableStateOf(TextFieldValue("")) }
OutlinedTextField(
modifier = Modifier.fillMaxWidth(),
shape = RoundedCornerShape(12.dp),
leadingIcon = {
Icon(
painterResource(id = R.drawable.ic_search),
contentDescription = stringResource(R.string.search_content_description)
)
},
value = searchFieldText,
label = { Text(text = stringResource(R.string.search_for_product)) },
onValueChange = { searchFieldText = it }
)
}
| 0
|
Kotlin
|
0
| 0
|
e4a6bc4c1c00d8e681c1172dbd864a2984ac1547
| 1,344
|
Kart
|
Apache License 2.0
|
src/main/kotlin/com/github/vhromada/catalog/common/RegisterType.kt
|
vhromada
| 23,755,847
| false
| null |
package com.github.vhromada.catalog.common
/**
* An enumeration represents type of register.
*
* @author <NAME>
*/
enum class RegisterType(
/**
* Number of register
*/
val number: Int
) {
/**
* Formats
*/
FORMATS(number = 1),
/**
* Languages
*/
LANGUAGES(number = 2),
/**
* Subtitles
*/
SUBTITLES(number = 3)
}
| 0
|
Kotlin
|
0
| 0
|
43511beaf8b774e415b87307ea9bbd3c857db163
| 390
|
Catalog
|
MIT License
|
compiler/testData/diagnostics/tests/regressions/kt32792.kt
|
JetBrains
| 3,432,266
| false
| null |
inline fun <T> tryLambdas(lamb : () -> T) : T{
return lamb.invoke()
}
fun main() {
tryLambdas<String> {
<!ARGUMENT_TYPE_MISMATCH!>return@tryLambdas<!>
}
}
| 181
| null |
5748
| 49,172
|
33eb9cef3d146062c103f9853d772f0a1da0450e
| 176
|
kotlin
|
Apache License 2.0
|
app/src/main/java/com/example/quotedroid/adapters/QuoteAdapter.kt
|
alfianandinugraha
| 445,186,140
| false
|
{"Kotlin": 4451}
|
package com.example.quotedroid.adapters
import android.text.Layout
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.quotedroid.R
import com.example.quotedroid.models.Quote
class QuoteAdapter(val quotes: List<Quote>): RecyclerView.Adapter<QuoteAdapter.Holder>() {
class Holder(view: View) : RecyclerView.ViewHolder(view) {
val textQuote = view.findViewById<TextView>(R.id.textQuote)
val textAuthor = view.findViewById<TextView>(R.id.textAuthor)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder {
return Holder(LayoutInflater.from(parent.context).inflate(R.layout.quote_item, parent, false))
}
override fun onBindViewHolder(holder: Holder, position: Int) {
val quote = quotes[position]
holder.textQuote.text = "\"${quote.text}\""
holder.textAuthor.text = "- ${quote.author}"
}
override fun getItemCount(): Int {
return quotes.size;
}
}
| 0
|
Kotlin
|
0
| 1
|
e3ca340502b0ca862de600cc2fce47c34048d633
| 1,094
|
quotedroid
|
MIT License
|
paymentsheet/src/main/java/com/stripe/android/paymentsheet/PaymentOptionUi.kt
|
stripe
| 6,926,049
| false
| null |
package com.stripe.android.paymentsheet
import androidx.annotation.DrawableRes
import androidx.annotation.VisibleForTesting
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.Icon
import androidx.compose.material.MaterialTheme
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Check
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.constraintlayout.compose.ConstraintLayout
import com.stripe.android.paymentsheet.ui.LpmSelectorText
import com.stripe.android.ui.core.elements.SimpleDialogElementUI
import com.stripe.android.uicore.elements.SectionCard
import com.stripe.android.uicore.shouldUseDarkDynamicColor
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
const val PAYMENT_OPTION_CARD_TEST_TAG = "PAYMENT_OPTION_CARD_TEST_TAG"
@Composable
internal fun PaymentOptionUi(
viewWidth: Dp,
isSelected: Boolean,
isEditing: Boolean,
isEnabled: Boolean,
iconRes: Int,
modifier: Modifier = Modifier,
iconTint: Color? = null,
@DrawableRes labelIcon: Int? = null,
labelText: String = "",
removePmDialogTitle: String = "",
description: String,
onRemoveListener: (() -> Unit)? = null,
onRemoveAccessibilityDescription: String = "",
onItemSelectedListener: (() -> Unit),
) {
// An attempt was made to not use constraint layout here but it was unsuccessful in
// precisely positioning the check and delete icons to match the mocks.
ConstraintLayout(
modifier = modifier
.padding(top = 12.dp)
.width(viewWidth)
.alpha(alpha = if (isEnabled) 1.0F else 0.6F)
) {
val (checkIcon, deleteIcon, label, card) = createRefs()
SectionCard(
isSelected = isSelected,
modifier = Modifier
.height(64.dp)
.padding(horizontal = 6.dp)
.fillMaxWidth()
.constrainAs(card) {
top.linkTo(parent.top)
start.linkTo(parent.start)
end.linkTo(parent.end)
}
) {
Column(
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier
.fillMaxSize()
.testTag("${PAYMENT_OPTION_CARD_TEST_TAG}_$labelText")
.selectable(
selected = isSelected,
enabled = isEnabled,
onClick = onItemSelectedListener,
),
) {
Image(
painter = painterResource(iconRes),
contentDescription = null,
colorFilter = iconTint?.let { ColorFilter.tint(it) },
modifier = Modifier
.height(40.dp)
.width(56.dp)
)
}
}
if (isSelected) {
val iconColor = MaterialTheme.colors.primary
val checkSymbolColor = if (iconColor.shouldUseDarkDynamicColor()) {
Color.Black
} else {
Color.White
}
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
.clip(CircleShape)
.size(24.dp)
.background(MaterialTheme.colors.primary)
.constrainAs(checkIcon) {
top.linkTo(card.bottom, (-18).dp)
end.linkTo(card.end)
}
) {
Icon(
imageVector = Icons.Filled.Check,
contentDescription = null,
tint = checkSymbolColor,
modifier = Modifier
.size(12.dp)
)
}
}
if (isEditing && onRemoveListener != null) {
val openDialog = remember { mutableStateOf(false) }
SimpleDialogElementUI(
openDialog = openDialog,
titleText = removePmDialogTitle,
messageText = description,
confirmText = stringResource(R.string.remove),
dismissText = stringResource(R.string.cancel),
onConfirmListener = onRemoveListener
)
// tint the delete symbol so it contrasts well with the error color around it.
val iconColor = MaterialTheme.colors.error
val deleteIconColor = if (iconColor.shouldUseDarkDynamicColor()) {
Color.Black
} else {
Color.White
}
Image(
painter = painterResource(R.drawable.stripe_ic_delete_symbol),
contentDescription = onRemoveAccessibilityDescription,
colorFilter = ColorFilter.tint(deleteIconColor),
modifier = Modifier
.constrainAs(deleteIcon) {
top.linkTo(card.top, margin = (-9).dp)
end.linkTo(card.end)
}
.size(20.dp)
.clip(CircleShape)
.background(color = iconColor)
.clickable(
onClick = {
openDialog.value = true
}
)
)
}
LpmSelectorText(
icon = labelIcon,
text = labelText,
textColor = MaterialTheme.colors.onSurface,
isEnabled = isEnabled,
modifier = Modifier
.constrainAs(label) {
top.linkTo(card.bottom)
start.linkTo(card.start)
}
.padding(
top = 4.dp,
start = 6.dp,
end = 6.dp
)
.semantics {
// This makes the screen reader read out numbers digit by digit
// one one one one vs one thousand one hundred eleven
this.contentDescription =
description.replace("\\d".toRegex(), "$0 ")
}
)
}
}
| 79
|
Kotlin
|
580
| 1,055
|
21ceca79b2403414939d561c446ef4344b5bf03f
| 7,630
|
stripe-android
|
MIT License
|
app/src/test/java/org/simple/clinic/login/applock/BCryptPasswordHasherTest.kt
|
pratul
| 151,071,054
| false
| null |
package org.simple.clinic.login.applock
import org.junit.Test
class BCryptPasswordHasherTest {
@Test
fun `comparison test`() {
val bcryptHasher = BCryptPasswordHasher()
val password = "12341234"
bcryptHasher.hash(password)
.flatMap { bcryptHasher.compare(it, password) }
.test()
.assertValue { it == PasswordHasher.ComparisonResult.SAME }
}
}
| 0
|
Kotlin
|
0
| 1
|
fa311d989cac0a167070f2e1e466191919b659b8
| 390
|
citest
|
MIT License
|
src/main/kotlin/com/gmail/blueboxware/libgdxplugin/filetypes/skin/highlighting/SkinSyntaxHighlighterFactory.kt
|
BlueBoxWare
| 64,067,118
| false
|
{"Kotlin": 1214125, "Java": 14963, "Lex": 5475, "HTML": 1368, "Dockerfile": 66}
|
package com.gmail.blueboxware.libgdxplugin.filetypes.skin.highlighting
import com.gmail.blueboxware.libgdxplugin.filetypes.skin.SkinElementTypes
import com.gmail.blueboxware.libgdxplugin.filetypes.skin.SkinLexer
import com.intellij.json.highlighting.JsonSyntaxHighlighterFactory.*
import com.intellij.lexer.LayeredLexer
import com.intellij.lexer.Lexer
import com.intellij.lexer.StringLiteralLexer
import com.intellij.openapi.editor.DefaultLanguageHighlighterColors
import com.intellij.openapi.editor.HighlighterColors
import com.intellij.openapi.editor.colors.TextAttributesKey
import com.intellij.openapi.fileTypes.SyntaxHighlighterBase
import com.intellij.openapi.fileTypes.SyntaxHighlighterFactory
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.StringEscapesTokenTypes
import com.intellij.psi.TokenType
import com.intellij.psi.tree.IElementType
/*
* Copyright 2016 <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.
*/
class SkinSyntaxHighlighterFactory : SyntaxHighlighterFactory() {
companion object {
val SKIN_BRACKETS = TextAttributesKey.createTextAttributesKey("SKIN.BRACKETS", JSON_BRACKETS)
val SKIN_BRACES = TextAttributesKey.createTextAttributesKey("SKIN.BRACES", JSON_BRACES)
val SKIN_COMMA = TextAttributesKey.createTextAttributesKey("SKIN.COMMA", JSON_COMMA)
val SKIN_COLON = TextAttributesKey.createTextAttributesKey("SKIN.COLON", JSON_COLON)
val SKIN_NUMBER = TextAttributesKey.createTextAttributesKey("SKIN.NUMBER", JSON_NUMBER)
val SKIN_STRING = TextAttributesKey.createTextAttributesKey("SKIN.STRING", JSON_STRING)
val SKIN_KEYWORD = TextAttributesKey.createTextAttributesKey("SKIN.KEYWORD", JSON_KEYWORD)
val SKIN_LINE_COMMENT = TextAttributesKey.createTextAttributesKey("SKIN.LINE_COMMENT", JSON_LINE_COMMENT)
val SKIN_BLOCK_COMMENT = TextAttributesKey.createTextAttributesKey("SKIN.BLOCK_COMMENT", JSON_BLOCK_COMMENT)
val SKIN_CLASS_NAME = TextAttributesKey.createTextAttributesKey("SKIN.CLASSNAME", JSON_KEYWORD)
val SKIN_RESOURCE_NAME = TextAttributesKey.createTextAttributesKey("SKIN.RESOURCENAME", JSON_IDENTIFIER)
val SKIN_PROPERTY_NAME = TextAttributesKey.createTextAttributesKey("SKIN.PROPERTY_NAME", JSON_PROPERTY_KEY)
val SKIN_PARENT_PROPERTY =
TextAttributesKey.createTextAttributesKey("SKIN.PARENT_PROPERTY", DefaultLanguageHighlighterColors.KEYWORD)
val SKIN_VALID_ESCAPE = TextAttributesKey.createTextAttributesKey("SKIN.VALID_ESCAPE", JSON_VALID_ESCAPE)
val SKIN_INVALID_ESCAPE = TextAttributesKey.createTextAttributesKey("SKIN.INVALID_ESCAPE", JSON_INVALID_ESCAPE)
}
override fun getSyntaxHighlighter(project: Project?, virtualFile: VirtualFile?) = SkinHighlighter()
class SkinHighlighter : SyntaxHighlighterBase() {
companion object {
val attributes = mapOf(
SkinElementTypes.L_CURLY to SKIN_BRACES,
SkinElementTypes.R_CURLY to SKIN_BRACES,
SkinElementTypes.L_BRACKET to SKIN_BRACKETS,
SkinElementTypes.R_BRACKET to SKIN_BRACKETS,
SkinElementTypes.COMMA to SKIN_COMMA,
SkinElementTypes.COLON to SKIN_COLON,
SkinElementTypes.DOUBLE_QUOTED_STRING to SKIN_STRING,
SkinElementTypes.UNQUOTED_STRING to SKIN_STRING,
SkinElementTypes.LINE_COMMENT to SKIN_LINE_COMMENT,
SkinElementTypes.BLOCK_COMMENT to SKIN_BLOCK_COMMENT,
SkinElementTypes.PROPERTY_NAME to SKIN_PROPERTY_NAME,
SkinElementTypes.RESOURCE_NAME to SKIN_RESOURCE_NAME,
TokenType.BAD_CHARACTER to HighlighterColors.BAD_CHARACTER,
StringEscapesTokenTypes.VALID_STRING_ESCAPE_TOKEN to SKIN_VALID_ESCAPE,
StringEscapesTokenTypes.INVALID_CHARACTER_ESCAPE_TOKEN to SKIN_INVALID_ESCAPE,
StringEscapesTokenTypes.INVALID_UNICODE_ESCAPE_TOKEN to SKIN_INVALID_ESCAPE
)
}
override fun getTokenHighlights(tokenType: IElementType?): Array<TextAttributesKey> {
return pack(attributes[tokenType])
}
override fun getHighlightingLexer(): Lexer {
val layeredLexer = LayeredLexer(SkinLexer())
layeredLexer.registerSelfStoppingLayer(
StringLiteralLexer('\"', SkinElementTypes.DOUBLE_QUOTED_STRING, false, "/", false, false),
arrayOf(SkinElementTypes.DOUBLE_QUOTED_STRING), IElementType.EMPTY_ARRAY
)
return layeredLexer
}
}
}
| 2
|
Kotlin
|
9
| 145
|
bcb911e0c3f3e9319bc8ee2d5b6b554c6090fd6c
| 5,167
|
LibGDXPlugin
|
Apache License 2.0
|
core/src/main/java/com/jclibs/safetime/SafeTimeException.kt
|
kaungkhantjc
| 871,416,839
| false
|
{"Kotlin": 37633}
|
package com.jclibs.safetime
import java.util.Locale
@Suppress("MemberVisibilityCanBePrivate")
/**
* A custom exception class for handling errors related to SafeTime operations.
*
* This exception is used to report discrepancies between expected and actual values,
* or to provide detailed error messages during SafeTime operations.
*
* @property property The name of the property where the error occurred, or `null` if not applicable.
* @property expectedValue The expected value of the property that caused the exception.
* @property actualValue The actual value of the property that caused the exception.
*/
class SafeTimeException : Exception {
val property: String?
val expectedValue: Int
val actualValue: Int
/**
* Constructor for creating a [SafeTimeException] with just a detailed error message.
*
* @param detailMessage The error message describing what went wrong.
*/
internal constructor(detailMessage: String) : super(detailMessage) {
this.property = null
this.expectedValue = 0
this.actualValue = 0
}
/**
* Constructor for creating a [SafeTimeException] with detailed error message and property details.
*
* This constructor is used when there is a mismatch between an expected and actual value for
* a given property. The error message is formatted using the provided details.
*
* @param message The error message template, which includes placeholders for the property name, actual value,
* and expected value.
* @param property The name of the property that caused the error.
* @param actualValue The actual value encountered during the operation.
* @param expectedValue The value that was expected for the property.
*/
internal constructor(
message: String,
property: String,
actualValue: Int,
expectedValue: Int
) : super(String.format(Locale.ENGLISH, message, property, actualValue, expectedValue)) {
this.property = property
this.actualValue = actualValue
this.expectedValue = expectedValue
}
}
| 0
|
Kotlin
|
1
| 0
|
941dc535d581567a7df2fea4ab78058c745e8104
| 2,121
|
SafeTime
|
Apache License 2.0
|
filetree/src/main/kotlin/com/zyron/filetree/events/FileTreeEventListener.kt
|
Zyron-Official
| 824,960,784
| false
| null |
/**
* Copyright 2024 Zyron Official.
*
* 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.zyron.orbit.events
import java.io.File
/**
* Interface to listen for events within a file tree, including clicks and updates.
*/
interface FileListEventListener {
/**
* Called when a file is clicked.
*
* @param file The file that was clicked.
*/
fun onFileClick(file: File)
/**
* Called when a folder is clicked.
*
* @param folder The folder that was clicked.
*/
fun onFolderClick(folder: File)
/**
* Called when a file is long-clicked.
*
* @param file The file that was long-clicked.
* @return True if the long-click event was handled, false otherwise.
*/
fun onFileLongClick(file: File): Boolean
/**
* Called when a folder is long-clicked.
*
* @param folder The folder that was long-clicked.
* @return True if the long-click event was handled, false otherwise.
*/
fun onFolderLongClick(folder: File): Boolean
}
| 1
| null |
0
| 5
|
da290b379cabdf418cbfd52bc01fb3ffcbebc72e
| 1,551
|
FileTree
|
Apache License 2.0
|
server/server-app/src/test/kotlin/projektor/incomingresults/SaveResultsParentXmlApplicationTest.kt
|
craigatk
| 226,096,594
| false
| null |
package projektor.incomingresults
import io.ktor.http.*
import io.ktor.server.testing.*
import org.junit.jupiter.api.Test
import projektor.ApplicationTestCase
import strikt.api.expectThat
import strikt.assertions.hasSize
import strikt.assertions.isEqualTo
import kotlin.test.assertNotNull
class SaveResultsParentXmlApplicationTest : ApplicationTestCase() {
@Test
fun shouldParseRequestAndSaveResultsWithMultipleResultsWrappedInParentXmlTest() {
val requestBody = listOf(resultsXmlLoader.passing(), resultsXmlLoader.failing()).joinToString("\n")
withTestApplication(::createTestApplication) {
handleRequest(HttpMethod.Post, "/results") {
addHeader(HttpHeaders.ContentType, "text/plain")
setBody(requestBody)
}.apply {
val (_, testRun) = waitForTestRunSaveToComplete(response)
val testSuites = testSuiteDao.fetchByTestRunId(testRun.id)
expectThat(testSuites).hasSize(2)
val passingTestSuite = testSuites.find { it.className.contains("PassingSpec") }
assertNotNull(passingTestSuite)
expectThat(passingTestSuite.testCount).isEqualTo(1)
expectThat(passingTestSuite.failureCount).isEqualTo(0)
val passingSuiteTestCases = testCaseDao.fetchByTestSuiteId(passingTestSuite.id)
expectThat(passingSuiteTestCases).hasSize(1)
val failingTestSuite = testSuites.find { it.className.contains("FailingSpec") }
assertNotNull(failingTestSuite)
expectThat(failingTestSuite.testCount).isEqualTo(2)
expectThat(failingTestSuite.failureCount).isEqualTo(2)
val failingSuiteTestCases = testCaseDao.fetchByTestSuiteId(failingTestSuite.id)
expectThat(failingSuiteTestCases).hasSize(2)
}
}
}
}
| 14
| null |
15
| 47
|
d6e166d7f017d296a846120ac964b880ab19df95
| 1,914
|
projektor
|
MIT License
|
kamper/modules/cpu/src/androidTest/kotlin/com/smellouk/kamper/cpu/repository/source/ShellCpuInfoSourceTest.kt
|
smellouk
| 442,266,308
| false
| null |
package com.smellouk.kamper.cpu.repository.source
import com.smellouk.kamper.api.Logger
import com.smellouk.kamper.cpu.repository.CpuInfoDto
import io.mockk.confirmVerified
import io.mockk.every
import io.mockk.mockk
import io.mockk.mockkStatic
import io.mockk.unmockkStatic
import io.mockk.verify
import org.junit.After
import org.junit.Before
import org.junit.Test
import java.io.ByteArrayInputStream
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
class ShellCpuInfoSourceTest {
private val logger = mockk<Logger>(relaxed = true)
private val classToTest: ShellCpuInfoSource = ShellCpuInfoSource(logger)
@Before
fun setup() {
mockkStatic(Runtime::class)
mockkStatic(android.os.Process::class)
every { android.os.Process.myPid() } returns PID
}
@After
fun tearDown() {
unmockkStatic(Runtime::class)
unmockkStatic(android.os.Process::class)
}
@Test
fun `readAllLines should read all lines from InputStream`() {
val anyInputStream = ByteArrayInputStream(TOP_N_1_CMD_OUTPUT.toByteArray())
val lines = anyInputStream.readAllLine()
assertEquals(EXPECTED_LINES, lines)
}
@Test
fun `isCpuInfoUsageLine should return true when line is CPU_USAGE_LINE`() {
assertTrue(CPU_USAGE_LINE.isCpuInfoUsageLine())
}
@Test
fun `isCpuInfoUsageLine should return false when line is not CPU_USAGE_LINE`() {
assertFalse(PROCESS_LABELS_LINE.isCpuInfoUsageLine())
}
@Test
fun `toCpuInfoUsageMap should create correct cpu usage map`() {
val map = CPU_USAGE_LINE.toCpuInfoUsageMap()
assertEquals(EXPECTED_CPU_USAGE_MAP, map)
}
@Test
fun `toCpuInfoUsageMap should create empty map when line is not parsable`() {
val map = TOP_N_1_CMD_OUTPUT.toCpuInfoUsageMap()
assertEquals(emptyMap(), map)
}
@Test
fun `isProcessLabelLine should return true when line is PROCESS_LABELS_LINE`() {
assertTrue(PROCESS_LABELS_LINE.isProcessLabelLine())
}
@Test
fun `isProcessLabelLine should return false when line is not PROCESS_LABELS_LINE`() {
assertFalse(CPU_USAGE_LINE.isProcessLabelLine())
}
@Test
fun `getCpuLabelIndex should return CPU_INDEX`() {
val index = PROCESS_LABELS_LINE.getCpuLabelIndex()
assertEquals(EXPECTED_CPU_INDEX, index)
}
@Test
fun `isProcessAppDetailsLine should return true when line start with PID`() {
assertTrue(APP_PROCESS_DETAILS_LINE.isProcessAppDetailsLine(PID))
}
@Test
fun `isProcessAppDetailsLine should return false when line does not start with PID`() {
assertFalse(PROCESS_LABELS_LINE.isProcessAppDetailsLine(PID))
}
@Test
fun `getCpuInfoDto should return invalid cpu info when cmdOutputLines is empty`() {
val process = mockRuntimeProcess()
val dto = classToTest.getCpuInfoDto()
assertEquals(CpuInfoDto.INVALID, dto)
verify { process.inputStream }
verify { process.destroy() }
confirmVerified(process)
}
@Test
fun `getCpuInfoDto should return invalid cpu info when cmdOutputLines is any cmd output`() {
val process = mockRuntimeProcess("ANY_COMMAND_OUTPUT")
val dto = classToTest.getCpuInfoDto()
assertEquals(CpuInfoDto.INVALID, dto)
verify { process.inputStream }
verify { process.destroy() }
confirmVerified(process)
}
@Test
fun `getCpuInfoDto should return valid cpu info when cmdOutputLines is valid output`() {
val process = mockRuntimeProcess(TOP_N_1_CMD_OUTPUT)
val dto = classToTest.getCpuInfoDto()
assertEquals(EXPECTED_VALID_DTO, dto)
verify { Runtime.getRuntime().exec("top -n 1") }
verify { android.os.Process.myPid() }
verify { process.inputStream }
verify { process.destroy() }
confirmVerified(process)
}
@Test
fun `getCpuInfoDto should return invalid cpu info when exception is thrown`() {
every { Runtime.getRuntime().exec("top -n 1") } throws Exception("ANY_EXCEPTION")
val dto = classToTest.getCpuInfoDto()
assertEquals(CpuInfoDto.INVALID, dto)
}
private fun mockRuntimeProcess(
cmdLineOutput: String = ""
) = mockk<Process>(relaxed = true).apply {
every { inputStream } returns ByteArrayInputStream(cmdLineOutput.toByteArray())
every { destroy() } returns Unit
}.also { process ->
every { Runtime.getRuntime().exec("top -n 1") } returns process
}
}
private const val CPU_USAGE_LINE =
"400%cpu 11%user 0%nice 11%sys 379%idle 0%iow 0%irq 0%sirq 0%host"
private const val PROCESS_LABELS_LINE =
"\u001B[7m PID USER PR NI VIRT RES SHR S[%CPU] %MEM TIME+ ARGS \u001B[0m"
private const val PID = 11916
private const val APP_PROCESS_DETAILS_LINE =
"$PID u0_a149 10 -10 13G 149M 90M S 40.0 7.5 0:02.61 com.smellouk.k+"
private const val TOP_N_1_CMD_OUTPUT = """
[s[999C[999B[6n[u[H[J[?25l[H[J[s[999C[999B[6n[uTasks: 2 total, 1 running, 1 sleeping, 0 stopped, 0 zombie
Mem: 2015364K total, 1776196K used, 239168K free, 20132K buffers
Swap: 1511516K total, 355328K used, 1156188K free, 800780K cached
400%cpu 11%user 0%nice 11%sys 379%idle 0%iow 0%irq 0%sirq 0%host
[7m PID USER PR NI VIRT RES SHR S[%CPU] %MEM TIME+ ARGS [0m
11916 u0_a149 10 -10 13G 149M 90M S 40.0 7.5 0:02.61 com.smellouk.k+
[1m 11951 u0_a149 20 0 10G 3.4M 2.7M R 0.0 0.1 0:00.02 top -n 1
[m[?25h[0m[1000;1H[K[?25h[?25h[0m[1000;1H[K
"""
private val EXPECTED_LINES = listOf(
"\u001B[s\u001B[999C\u001B[999B\u001B[6n\u001B[u\u001B[H\u001B[J\u001B[?25l\u001B[H\u001B[J\u001B[s\u001B[999C\u001B[999B\u001B[6n\u001B[uTasks: 2 total, 1 running, 1 sleeping, 0 stopped, 0 zombie",
"Mem: 2015364K total, 1776196K used, 239168K free, 20132K buffers",
"Swap: 1511516K total, 355328K used, 1156188K free, 800780K cached",
CPU_USAGE_LINE,
PROCESS_LABELS_LINE,
APP_PROCESS_DETAILS_LINE,
"\u001B[1m 11951 u0_a149 20 0 10G 3.4M 2.7M R 0.0 0.1 0:00.02 top -n 1",
"\u001B[m\u001B[?25h\u001B[0m\u001B[1000;1H\u001B[K\u001B[?25h\u001B[?25h\u001B[0m\u001B[1000;1H\u001B[K"
)
private val EXPECTED_CPU_USAGE_MAP = mapOf(
"cpu" to 400.0,
"user" to 11.0,
"nice" to 0.0,
"sys" to 11.0,
"idle" to 379.0,
"iow" to 0.0,
"irq" to 0.0,
"sirq" to 0.0,
"host" to 0.0
)
private const val EXPECTED_CPU_INDEX = 8
private val EXPECTED_VALID_DTO = CpuInfoDto(
totalTime = 400.0,
userTime = 11.0,
systemTime = 11.0,
idleTime = 379.0,
ioWaitTime = 0.0,
appTime = 40.0
)
| 8
|
Kotlin
|
0
| 31
|
bbc4cad11c11e578a4017b04a1c66f51790a4e88
| 6,884
|
kamper
|
Apache License 2.0
|
app/src/main/kotlin/com/pusher/chatkitdemo/parallel/LifecycleReceiverChannel.kt
|
pusher
| 131,029,165
| false
| null |
package com.pusher.chatkitdemo.parallel
import android.arch.lifecycle.Lifecycle
import android.arch.lifecycle.Lifecycle.Event.*
import android.arch.lifecycle.LifecycleObserver
import android.arch.lifecycle.LifecycleOwner
import android.arch.lifecycle.OnLifecycleEvent
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.BroadcastChannel
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.ReceiveChannel
import kotlinx.coroutines.channels.toChannel
import kotlinx.coroutines.launch
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.ObsoleteCoroutinesApi
@ExperimentalCoroutinesApi
fun <A> LifecycleOwner.onLifecycle(block: () -> ReceiveChannel<A>): ReceiveChannel<A> =
LifecycleReceiverChannel(this.lifecycle, block)
private class LifecycleReceiverChannel<out A> @ExperimentalCoroutinesApi constructor(
lifecycle: Lifecycle,
private val block: () -> ReceiveChannel<A>,
private val broadcastChannel: BroadcastChannel<A> = BroadcastChannel(Channel.CONFLATED),
private val subscription: ReceiveChannel<A> = broadcastChannel.openSubscription()
) : ReceiveChannel<A> by subscription, LifecycleObserver {
private var channel: ReceiveChannel<A>? = null
init {
lifecycle.addObserver(this)
}
@ObsoleteCoroutinesApi
@OnLifecycleEvent(ON_START)
fun onStart() {
channel?.cancel()
channel = block()
GlobalScope.launch { channel?.toChannel(broadcastChannel) }
}
@OnLifecycleEvent(ON_STOP)
fun onStop() {
channel?.cancel()
}
@OnLifecycleEvent(ON_DESTROY)
fun onDestroy() {
subscription.cancel()
}
}
| 4
|
Kotlin
|
6
| 9
|
8419084d0a2c9f7e32d0dbf14a269994ccd73354
| 1,708
|
android-slack-clone
|
MIT License
|
app/src/main/java/com/yuhang/novel/pirate/viewholder/ItemBooksListVH.kt
|
yuhanghate
| 200,383,190
| false
|
{"Java": 1605624, "Kotlin": 875945, "HTML": 3256}
|
package com.yuhang.novel.pirate.viewholder
import android.view.ViewGroup
import com.yuhang.novel.pirate.R
import com.yuhang.novel.pirate.base.BaseViewHolder
import com.yuhang.novel.pirate.databinding.ItemBooksListBinding
import com.yuhang.novel.pirate.extension.niceCoverPic
import com.yuhang.novel.pirate.extension.niceCrossFade
import com.yuhang.novel.pirate.extension.niceDefaultImageVertical
import com.yuhang.novel.pirate.repository.database.entity.ShuDanEntity
import com.yuhang.novel.pirate.repository.network.data.kanshu.result.BooksKSResult
import com.yuhang.novel.pirate.repository.network.data.kanshu.result.BooksListDataResult
class ItemBooksListVH(parent:ViewGroup):BaseViewHolder<ShuDanEntity, ItemBooksListBinding>(parent, R.layout.item_books_list) {
override fun onBindViewHolder(obj: ShuDanEntity, position: Int) {
super.onBindViewHolder(obj, position)
mBinding.nameTv.text = obj.Title
mBinding.descTv.text = obj.Description
mBinding.bookCountTv.text = "收藏${obj.BookCount}本"
getGlide().load(obj.Cover.niceCoverPic())
.apply(niceDefaultImageVertical())
.transition(niceCrossFade())
.into(mBinding.coverIv)
}
}
| 1
|
Java
|
1
| 2
|
8c72fc787a2927efb10c8c03b714195c7b1a6c76
| 1,214
|
Pirate
|
Apache License 2.0
|
eco-api/src/main/kotlin/com/willfp/eco/core/entities/Entities.kt
|
Auxilor
| 325,856,799
| false
|
{"Kotlin": 781861, "Java": 739885}
|
@file:JvmName("EntityExtensions")
package com.willfp.eco.core.entities
import com.willfp.eco.core.entities.ai.EntityController
import org.bukkit.entity.Mob
/** @see EntityController.getFor */
val <T : Mob> T.controller: EntityController<T>
get() = EntityController.getFor(this)
| 80
|
Kotlin
|
51
| 151
|
4e6960fab57522afb7e07189bb706fbd3afa45f4
| 285
|
eco
|
MIT License
|
app/src/main/kotlin/com/vsouhrada/kotlin/android/anko/fibo/core/session/ISession.kt
|
vsouhrada
| 77,144,360
| false
| null |
package com.vsouhrada.kotlin.android.anko.fibo.core.session
/**
* @author vsouhrada
* @since 0.1.0
*/
interface ISession {
/**
* Method is call when session should be open and in case of that method *refresh* was called on [ISessionManager]
* @since 0.1.0
*/
fun openSession()
/**
* Called when session should be close.
* @since 0.1.0
*/
fun closeSession()
/**
* Method is call when validation of the session is required.
* @return true in case of that session is valid, otherwise false is returned
* @since 1.0.0
*/
fun isValid(): Boolean
/**
* Returned Object stored in session under the value *key*.
* @param key the key value
* @return data contained under the *key* value
* @since 0.1.0
*/
fun getData(key: Int): Any
/**
* Store Object in session under the value *key*.
* @param key the key value
* @param value the Object which you want to store
* @since 0.1.0
*/
fun putData(key: Int, value: Any)
/**
* Delete the Object stored in session under the value *key*.
* @param key the key value
* @since 0.1.0
*/
fun removeData(key: Int)
}
| 1
|
Kotlin
|
6
| 29
|
f13d80e93f3075708fc5e3bfd92799b51f12ada2
| 1,148
|
kotlin-anko-demo
|
Apache License 2.0
|
vector/src/main/java/im/vector/fragments/keysbackup/restore/KeysBackupRestoreFromPassphraseFragment.kt
|
LiMium
| 119,702,511
| true
|
{"Java": 2804410, "Kotlin": 1162710, "JavaScript": 141316, "HTML": 21094, "Shell": 18894}
|
/*
* Copyright 2019 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.app.features.crypto.keysbackup.restore
import android.os.Bundle
import android.text.Editable
import android.text.SpannableString
import android.text.style.ClickableSpan
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import androidx.core.text.set
import androidx.lifecycle.Observer
import butterknife.BindView
import butterknife.OnClick
import butterknife.OnTextChanged
import com.google.android.material.textfield.TextInputLayout
import im.vector.app.R
import im.vector.app.core.extensions.showPassword
import im.vector.app.core.platform.VectorBaseFragment
import javax.inject.Inject
class KeysBackupRestoreFromPassphraseFragment @Inject constructor() : VectorBaseFragment() {
override fun getLayoutResId() = R.layout.fragment_keys_backup_restore_from_passphrase
private lateinit var viewModel: KeysBackupRestoreFromPassphraseViewModel
private lateinit var sharedViewModel: KeysBackupRestoreSharedViewModel
@BindView(R.id.keys_backup_passphrase_enter_til)
lateinit var mPassphraseInputLayout: TextInputLayout
@BindView(R.id.keys_backup_passphrase_enter_edittext)
lateinit var mPassphraseTextEdit: EditText
@BindView(R.id.keys_backup_view_show_password)
lateinit var mPassphraseReveal: ImageView
@BindView(R.id.keys_backup_passphrase_help_with_link)
lateinit var helperTextWithLink: TextView
@OnClick(R.id.keys_backup_view_show_password)
fun toggleVisibilityMode() {
viewModel.showPasswordMode.value = !(viewModel.showPasswordMode.value ?: false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
viewModel = fragmentViewModelProvider.get(KeysBackupRestoreFromPassphraseViewModel::class.java)
sharedViewModel = activityViewModelProvider.get(KeysBackupRestoreSharedViewModel::class.java)
viewModel.passphraseErrorText.observe(viewLifecycleOwner, Observer { newValue ->
mPassphraseInputLayout.error = newValue
})
helperTextWithLink.text = spannableStringForHelperText()
viewModel.showPasswordMode.observe(viewLifecycleOwner, Observer {
val shouldBeVisible = it ?: false
mPassphraseTextEdit.showPassword(shouldBeVisible)
mPassphraseReveal.setImageResource(if (shouldBeVisible) R.drawable.ic_eye_closed else R.drawable.ic_eye)
})
mPassphraseTextEdit.setOnEditorActionListener { _, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_DONE) {
onRestoreBackup()
return@setOnEditorActionListener true
}
return@setOnEditorActionListener false
}
}
private fun spannableStringForHelperText(): SpannableString {
val clickableText = getString(R.string.keys_backup_restore_use_recovery_key)
val helperText = getString(R.string.keys_backup_restore_with_passphrase_helper_with_link, clickableText)
val spanString = SpannableString(helperText)
// used just to have default link representation
val clickableSpan = object : ClickableSpan() {
override fun onClick(widget: View) {}
}
val start = helperText.indexOf(clickableText)
val end = start + clickableText.length
spanString[start, end] = clickableSpan
return spanString
}
@OnTextChanged(R.id.keys_backup_passphrase_enter_edittext)
fun onPassphraseTextEditChange(s: Editable?) {
s?.toString()?.let { viewModel.updatePassphrase(it) }
}
@OnClick(R.id.keys_backup_passphrase_help_with_link)
fun onUseRecoveryKey() {
sharedViewModel.moveToRecoverWithKey()
}
@OnClick(R.id.keys_backup_restore_with_passphrase_submit)
fun onRestoreBackup() {
val value = viewModel.passphrase.value
if (value.isNullOrBlank()) {
viewModel.passphraseErrorText.value = getString(R.string.passphrase_empty_error_message)
} else {
viewModel.recoverKeys(sharedViewModel)
}
}
}
| 5
|
Java
|
4
| 44
|
09bf4c527429fe2c8283c71988efa5796dcc854b
| 4,767
|
mini-vector-android
|
Apache License 2.0
|
kerberus/src/main/java/com/eaglesakura/kerberus/Semaphore.kt
|
eaglesakura
| 140,512,537
| false
|
{"Kotlin": 442196, "Ruby": 2418, "Dockerfile": 2227, "Java": 678}
|
@file:Suppress("unused")
package com.eaglesakura.kerberus
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlin.coroutines.CoroutineContext
/**
* Semaphore for coroutines.
*
* It is use to the TaskQueue or such else.
*
* @author @eaglesakura
* @link https://github.com/eaglesakura/army-knife
*/
interface Semaphore {
@Throws(CancellationException::class)
suspend fun <R> run(block: suspend () -> R): R
companion object {
val NonBlocking: Semaphore = object : Semaphore {
override suspend fun <R> run(block: suspend () -> R): R {
return block()
}
}
/**
* For network input/output semaphore.
*/
val Network: Semaphore = SemaphoreImpl(Runtime.getRuntime().availableProcessors() * 2 + 1)
/**
* For storage input/output semaphore.
*/
val IO: Semaphore = SemaphoreImpl(Runtime.getRuntime().availableProcessors() * 2 + 1)
/**
* Global queue.
*/
val Queue: Semaphore = SemaphoreImpl(1)
/**
* new instance for Task Queue.
*/
fun newQueue(): Semaphore {
return newInstance(1)
}
/**
* new instance with parallel.
*/
@Suppress("MemberVisibilityCanBePrivate")
fun newInstance(maxParallel: Int): Semaphore {
return SemaphoreImpl(maxParallel)
}
}
private class SemaphoreImpl(maxParallel: Int) : Semaphore {
private val channel: Channel<Unit> = Channel(maxParallel)
override suspend fun <R> run(block: suspend () -> R): R {
channel.send(Unit)
try {
return block()
} finally {
withContext(NonCancellable) {
channel.receive()
}
}
}
}
}
@Deprecated("Replace to com.eaglesakura.kerberus.CoroutineScope.launch", ReplaceWith(""))
fun Semaphore.launch(context: CoroutineContext, block: suspend CoroutineScope.() -> Unit): Job {
val self = this
return GlobalScope.launch(context) {
self.run { block() }
}
}
@Deprecated("Replace to com.eaglesakura.kerberus.withSemaphore", ReplaceWith("withSemaphore"))
suspend fun <T> Semaphore.runWith(
context: CoroutineContext,
block: suspend CoroutineScope.() -> T
): T {
return withContext(context) {
block()
}
}
| 3
|
Kotlin
|
0
| 0
|
6be9a21c69e9f01654e4586615124363d82908a9
| 2,700
|
army-knife
|
MIT License
|
android/app/src/main/kotlin/com/commons/views/MyDialogViewPager.kt
|
AkioUnity
| 233,186,718
| false
| null |
package com.simplemobiletools.commons.views
import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import androidx.viewpager.widget.ViewPager
class MyDialogViewPager : ViewPager {
var allowSwiping = true
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
// disable manual swiping of viewpager at the dialog by swiping over the pattern
override fun onInterceptTouchEvent(ev: MotionEvent) = false
override fun onTouchEvent(ev: MotionEvent): Boolean {
if (!allowSwiping)
return false
try {
return super.onTouchEvent(ev)
} catch (ignored: Exception) {
}
return false
}
// https://stackoverflow.com/a/20784791/1967672
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
var height = 0
for (i in 0 until childCount) {
val child = getChildAt(i)
child.measure(widthMeasureSpec, View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED))
val h = child.measuredHeight
if (h > height) height = h
}
val newHeightMeasureSpec = View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY)
super.onMeasure(widthMeasureSpec, newHeightMeasureSpec)
}
}
| 16
| null |
3
| 2
|
b97a2be548342359c047a498beffbc976ccf854b
| 1,409
|
Calendar-Widget
|
MIT License
|
countryinfo/src/main/kotlin/com/olaaref/countryinfo/CountryinfoApplication.kt
|
OlaAref
| 628,533,894
| false
|
{"Java": 123474, "Kotlin": 31932}
|
package com.olaaref.countryinfo
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
@SpringBootApplication
class CountryinfoApplication
fun main(args: Array<String>) {
runApplication<CountryinfoApplication>(*args)
}
| 1
| null |
1
| 1
|
f9e9ec76bbcce7058ee89eb898ed94fd0cdb0463
| 283
|
Spring-country-Soap-client
|
MIT License
|
extensions/parcelize/src/main/kotlin/TimeZone.kt
|
erikc5000
| 202,192,185
| false
|
{"Kotlin": 1524883, "Java": 1132}
|
package io.islandtime.parcelize
import android.os.Parcel
import io.islandtime.TimeZone
import kotlinx.parcelize.Parceler
object TimeZoneParceler : Parceler<TimeZone> {
override fun create(parcel: Parcel): TimeZone {
return TimeZone(parcel.readString().orEmpty())
}
override fun TimeZone.write(parcel: Parcel, flags: Int) {
parcel.writeString(id)
}
}
object NullableTimeZoneParceler : Parceler<TimeZone?> {
override fun create(parcel: Parcel): TimeZone? {
return parcel.readString()?.let { TimeZone(it) }
}
override fun TimeZone?.write(parcel: Parcel, flags: Int) {
parcel.writeString(this?.id)
}
}
| 14
|
Kotlin
|
6
| 76
|
b234241ab7bb7a803bb8b2b0dd71a3fd84a12afa
| 667
|
island-time
|
Apache License 2.0
|
app/src/main/java/org/simple/clinic/facility/change/FacilityChangeEffect.kt
|
simpledotorg
| 132,515,649
| false
|
{"Kotlin": 6103689, "Shell": 1660, "HTML": 545}
|
package org.simple.clinic.facility.change
import org.simple.clinic.facility.Facility
sealed class FacilityChangeEffect
object LoadCurrentFacility : FacilityChangeEffect()
data class OpenConfirmFacilityChangeSheet(val facility: Facility) : FacilityChangeEffect()
object GoBack : FacilityChangeEffect()
| 8
|
Kotlin
|
74
| 226
|
d2cf8277d37aabb6bce00f74b1467b9e859a37fd
| 306
|
simple-android
|
MIT License
|
whisper_android/app/src/main/cpp/tf-lite-api/include/flatbuffers/java/src/test/java/NamespaceA/NamespaceB/StructInNestedNS.kt
|
nyadla-sys
| 684,225,721
| false
| null |
// automatically generated by the FlatBuffers compiler, do not modify
package NamespaceA.NamespaceB
import java.nio.*
import kotlin.math.sign
import com.google.flatbuffers.*
@Suppress("unused")
@ExperimentalUnsignedTypes
class StructInNestedNS : Struct() {
fun __init(_i: Int, _bb: ByteBuffer) {
__reset(_i, _bb)
}
fun __assign(_i: Int, _bb: ByteBuffer) : StructInNestedNS {
__init(_i, _bb)
return this
}
val a : Int get() = bb.getInt(bb_pos + 0)
fun mutateA(a: Int) : ByteBuffer = bb.putInt(bb_pos + 0, a)
val b : Int get() = bb.getInt(bb_pos + 4)
fun mutateB(b: Int) : ByteBuffer = bb.putInt(bb_pos + 4, b)
companion object {
fun createStructInNestedNS(builder: FlatBufferBuilder, a: Int, b: Int) : Int {
builder.prep(4, 8)
builder.putInt(b)
builder.putInt(a)
return builder.offset()
}
}
}
| 14
| null |
20
| 74
|
5eaa87f3af07e580d6b79172433e460fca017224
| 925
|
whisper.tflite
|
MIT License
|
app/src/main/java/ru/whalemare/sample/CounterView.kt
|
whalemare
| 93,920,111
| false
| null |
package ru.whalemare.sample
import android.content.Context
import android.support.v7.widget.LinearLayoutCompat
import android.util.AttributeSet
import android.view.View
/**
* @since 2017
* @author <NAME> - whalemare
*/
class CounterView @JvmOverloads constructor(
context: Context,
attributeSet: AttributeSet? = null,
defStyle: Int = 0)
: LinearLayoutCompat(context, attributeSet, defStyle) {
val mainView = View.inflate(context, R.layout.counter_view, this)
}
| 0
|
Kotlin
|
1
| 0
|
a49bfa7d80246b0435bea13906fb0e1ef2521d0b
| 500
|
cell-adapter
|
Apache License 2.0
|
apiservice/src/main/java/nl/testchamber/apiservice/interfaces/MilkTypeServiceResponseListener.kt
|
rutgurk
| 174,993,339
| false
| null |
package nl.testchamber.apiservice.interfaces
import nl.testchamber.apiservice.data.MilkTypeService
import retrofit2.Response
interface MilkTypeServiceResponseListener {
fun onSuccess(response: MilkTypeService)
fun onFailure(message: String)
}
| 3
|
Kotlin
|
9
| 1
|
a7ea829cff0d01d06e39dfa5c15b21b66e8cb482
| 254
|
mailordercoffee-workshop
|
MIT License
|
compiler/tests-spec/testData/diagnostics/notLinked/dfa/neg/41.fir.kt
|
JetBrains
| 3,432,266
| false
| null |
// !LANGUAGE: +NewInference
// !DIAGNOSTICS: -UNUSED_EXPRESSION -ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE -UNUSED_PARAMETER -UNUSED_VARIABLE -UNUSED_VALUE -VARIABLE_WITH_REDUNDANT_INITIALIZER
// SKIP_TXT
// TESTCASE NUMBER: 1
inline fun <reified T> case_1(x: Any?) {
when (x) {
is T -> {
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any? & T!!")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any? & T!!")!>x<!>.equals(10)
}
else -> return
}
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any? & T!!")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any? & T!!")!>x<!>.equals(10)
}
// TESTCASE NUMBER: 2
inline fun <reified T> case_2(x: Any?) {
when (x) {
is Any -> {
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any? & kotlin.Any")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any? & kotlin.Any")!>x<!>.equals(10)
}
is T -> {
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any? & T!!")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any? & T!!")!>x<!>.equals(10)
}
else -> return
}
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any? & kotlin.Any")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any? & kotlin.Any")!>x<!>.equals(10)
}
// TESTCASE NUMBER: 3
inline fun <reified T> case_3(x: Any?) {
when (x) {
is T? -> return
else -> {
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any?")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any?")!>x<!><!UNSAFE_CALL!>.<!>equals(10)
}
}
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any?")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any?")!>x<!><!UNSAFE_CALL!>.<!>equals(10)
}
// TESTCASE NUMBER: 4
inline fun <reified T> case_4(x: Any?) {
when (x) {
is T -> return
else -> {
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any?")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any?")!>x<!><!UNSAFE_CALL!>.<!>equals(10)
}
}
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any?")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any?")!>x<!><!UNSAFE_CALL!>.<!>equals(10)
}
// TESTCASE NUMBER: 5
inline fun <reified T> case_5(x: Any?) {
if (x is T) {
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any? & T!!")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any? & T!!")!>x<!>.equals(10)
} else return
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any? & T!!")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any? & T!!")!>x<!>.equals(10)
}
// TESTCASE NUMBER: 6
inline fun <reified T> case_6(x: Any?) {
if (x is T?) return
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any?")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any?")!>x<!><!UNSAFE_CALL!>.<!>equals(10)
}
// TESTCASE NUMBER: 7
inline fun <reified T> case_7(x: Any?) {
if (x is Any) {
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any? & kotlin.Any")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any? & kotlin.Any")!>x<!>.equals(10)
} else if (x is T) {
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any? & T!!")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any? & T!!")!>x<!>.equals(10)
} else return
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any? & kotlin.Any")!>x<!>
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any? & kotlin.Any")!>x<!>.equals(10)
}
| 157
| null |
5563
| 44,965
|
e6633d3d9214402fcf3585ae8c24213a4761cc8b
| 3,259
|
kotlin
|
Apache License 2.0
|
toothpick-sample/src/main/java/com/example/toothpick/adapter/IBackpackAdapter.kt
|
zawadz88
| 204,247,003
| true
|
{"INI": 16, "YAML": 1, "Markdown": 3, "Text": 3, "Gradle": 21, "Shell": 4, "Batchfile": 2, "Ignore List": 1, "Java": 192, "XML": 13, "Kotlin": 40, "Java Properties": 2}
|
package com.example.toothpick.adapter
import androidx.recyclerview.widget.RecyclerView
open abstract class IBackpackAdapter: RecyclerView.Adapter<BackpackAdapter.ItemHolder>()
| 0
|
Java
|
0
| 0
|
87d89c15b5bc15c3a698b9d42a4adf0ceebb0ae3
| 177
|
toothpick
|
Apache License 2.0
|
app/src/main/java/lt/vilnius/tvarkau/dagger/module/ReportDetailsActivityModule.kt
|
vilnius
| 45,076,585
| false
| null |
package lt.vilnius.tvarkau.dagger.module
import dagger.Module
import dagger.android.ContributesAndroidInjector
import lt.vilnius.tvarkau.fragments.ReportDetailsFragment
@Module
abstract class ReportDetailsActivityModule {
@ContributesAndroidInjector
abstract fun reportDetailsFragment(): ReportDetailsFragment
}
| 7
|
Kotlin
|
15
| 24
|
3d546e1e70b5b05514f47e7cb6c1c2e03a7da093
| 323
|
tvarkau-vilniu
|
MIT License
|
lib_common/src/main/java/com/yunzhu/module/common/extensions/ImageViewExt.kt
|
esligh
| 374,030,175
| false
|
{"Java": 629194, "Kotlin": 226783}
|
package com.yunzhu.module.common.extensions
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.widget.ImageView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
/**
* @author: lisc
* @desc: ImageView的简单拓展
* */
fun ImageView.load(url: String?) {
url?.let {
var requestOptions = RequestOptions()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.placeholder(ColorDrawable(Color.TRANSPARENT))
.error(ColorDrawable(Color.TRANSPARENT))
.centerCrop()
Glide.with(this.context)
.load(url)
.apply(requestOptions)
.into(this)
}
}
fun ImageView.load(url:String?,options:RequestOptions)
{
url?.let {
Glide.with(this.context)
.load(url)
.apply(options)
.into(this)
}
}
fun ImageView.load(url: String?, holder: Int) {
url?.let {
var requestOptions = RequestOptions()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.placeholder(holder)
.error(ColorDrawable(Color.TRANSPARENT))
.centerCrop()
Glide.with(this.context)
.load(url)
.apply(requestOptions)
.into(this)
}
}
fun ImageView.load(url:String?,roundCorners: RoundedCorners)
{
url?.let {
var requestOptions = RequestOptions.bitmapTransform(roundCorners)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.placeholder(ColorDrawable(Color.TRANSPARENT))
.error(ColorDrawable(Color.TRANSPARENT))
Glide.with(this.context)
.load(url)
.apply(requestOptions)
.into(this)
}
}
fun ImageView.load(url: Any) {
var requestOptions = RequestOptions()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.placeholder(ColorDrawable(Color.TRANSPARENT))
.error(ColorDrawable(Color.TRANSPARENT))
.centerCrop()
Glide.with(this.context)
.load(url)
.apply(requestOptions)
.into(this)
}
fun ImageView.load(url:Any,options:RequestOptions)
{
Glide.with(this.context)
.load(url)
.apply(options)
.into(this)
}
fun ImageView.load(url: Any, holder: Int) {
var requestOptions = RequestOptions()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.placeholder(holder)
.error(ColorDrawable(Color.TRANSPARENT))
.centerCrop()
Glide.with(this.context)
.load(url)
.apply(requestOptions)
.into(this)
}
fun ImageView.load(url:Any,roundCorners: RoundedCorners)
{
var requestOptions = RequestOptions.bitmapTransform(roundCorners)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.placeholder(ColorDrawable(Color.TRANSPARENT))
.error(ColorDrawable(Color.TRANSPARENT))
Glide.with(this.context)
.load(url)
.apply(requestOptions)
.into(this)
}
| 1
|
Java
|
1
| 2
|
23cf0022ee02d18d4cc4f8400ae4c0036519d3d1
| 3,083
|
zygote
|
Apache License 2.0
|
baselibrary/src/main/java/com/ballastlane/android/baselibrary/common/ext/StringExtensions.kt
|
Ballastlane-LLC
| 123,138,312
| false
| null |
package com.ballastlane.android.baselibrary.common.ext
import android.content.Context
import android.content.Intent
import java.util.regex.Pattern
/**
* Created by Mariangela Salcedo (mariangelasalcedo@ballastlane.com) on 3/8/18.
* Copyright (c) 2018 Ballast Lane Applications LLC. All rights reserved.
*/
fun String?.empty() = this == null || this.trim().isEmpty()
fun String.isEmail(): Boolean {
val regex = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"
val pattern = Pattern.compile(regex)
val matcher = pattern.matcher(this)
return matcher.matches()
}
fun String?.ifEmptyThenReturn(blankDefault: CharSequence): String {
return if (this == null || this.toString().trim { it <= ' ' }.isEmpty() ||
this.toString().equals("null", ignoreCase = true)) blankDefault.toString()
else this.toString()
}
fun String?.ifNotEmptyThenPrefix(prefix: CharSequence, blankDefault: CharSequence): String {
return if (this == null || this.toString().trim { it <= ' ' }.isEmpty() ||
this.toString().equals("null", ignoreCase = true)) blankDefault.toString()
else prefix.toString() + this.toString()
}
fun String?.ifNotEmptyThenSuffix(suffix: CharSequence, blankDefault: CharSequence): String {
return if (this == null || this.toString().trim { it <= ' ' }.isEmpty() ||
this.toString().equals("null", ignoreCase = true)) blankDefault.toString()
else this.toString() + suffix.toString()
}
fun String?.ifNotEmptyThenPrefixAndSuffix(prefix: CharSequence, suffix: CharSequence, blankDefault: CharSequence): String {
return if (this == null || this.toString().trim { it <= ' ' }.isEmpty() ||
this.toString().equals("null", ignoreCase = true)) blankDefault.toString()
else prefix.toString() + (this.toString() + suffix.toString())
}
fun String?.share(ctx: Context, title: String) {
val sharingIntent = Intent(Intent.ACTION_SEND)
sharingIntent.type = "text/plain"
sharingIntent.putExtra(Intent.EXTRA_TEXT, this)
ctx.startActivity(Intent.createChooser(sharingIntent, title))
}
| 1
| null |
1
| 1
|
7b45852160a7ef9c6ae04e7225cd14d5335b300a
| 2,120
|
AndroidBaseLibrary
|
Apache License 2.0
|
gremlin-kore/src/main/kotlin/org/apache/tinkerpop4/gremlin/process/traversal/strategy/optimization/PathProcessorStrategy.kt
|
phreed
| 449,920,526
| false
| null |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.tinkerpop4.gremlin.process.traversal.strategy.optimization
import org.apache.tinkerpop4.gremlin.process.computer.traversal.step.map.VertexProgramStep
/**
* `PathProcessStrategy` is an OLAP strategy that does its best to turn non-local children in `where()`
* and `select()` into local children by inlining components of the non-local child. In this way,
* `PathProcessStrategy` helps to ensure that more traversals meet the local child constraint imposed on OLAP
* traversals.
*
* @author <NAME> (http://markorodriguez.com)
* @example <pre>
* __.select(a).by(x) // is replaced by select(a).map(x)
* __.select(a,b).by(x).by(y) // is replaced by select(a).by(x).as(a).select(b).by(y).as(b).select(a,b)
* __.where(as(a).out().as(b)) // is replaced by as(xyz).select(a).where(out().as(b)).select(xyz)
* __.where(as(a).out()) // is replaced by as(xyz).select(a).filter(out()).select(xyz)
</pre> *
*/
class PathProcessorStrategy private constructor() : AbstractTraversalStrategy<OptimizationStrategy?>(),
OptimizationStrategy {
@Override
fun applyPrior(): Set<Class<out OptimizationStrategy?>> {
return Collections.singleton(MatchPredicateStrategy::class.java)
}
@Override
fun applyPost(): Set<Class<out OptimizationStrategy?>> {
return Collections.singleton(InlineFilterStrategy::class.java)
}
@Override
fun apply(traversal: Traversal.Admin<*, *>) {
// using a hidden label marker to denote whether the traversal should not be processed by this strategy
if ((traversal.getParent() is EmptyStep || traversal.getParent() is VertexProgramStep) &&
TraversalHelper.hasStepOfAssignableClassRecursively(INVALIDATING_STEP_CLASSES, traversal)
) TraversalHelper.applyTraversalRecursively({ t ->
t.getStartStep().addLabel(
MARKER
)
}, traversal)
if (traversal.getStartStep().getLabels().contains(MARKER)) {
traversal.getStartStep().removeLabel(MARKER)
return
}
// process where(as("a").out()...) => select("a").where(out()...)
val whereTraversalSteps: List<WhereTraversalStep> =
TraversalHelper.getStepsOfClass(WhereTraversalStep::class.java, traversal)
for (whereTraversalStep in whereTraversalSteps) {
val localChild: Traversal.Admin<*, *> = whereTraversalStep.getLocalChildren().get(0)
if (localChild.getStartStep() is WhereStartStep &&
!(localChild.getStartStep() as WhereStartStep).getScopeKeys().isEmpty()
) {
var done = false
while (!done) {
done = true
val index: Int = TraversalHelper.stepIndex(whereTraversalStep, traversal)
if (whereTraversalStep.getPreviousStep() is SelectStep) {
done = false
traversal.removeStep(index)
traversal.addStep(index - 1, whereTraversalStep)
}
}
val whereStartStep: WhereStartStep<*> = localChild.getStartStep() as WhereStartStep<*>
var index: Int = TraversalHelper.stepIndex(whereTraversalStep, traversal)
val selectOneStep: SelectOneStep<*, *> =
SelectOneStep(traversal, Pop.last, whereStartStep.getScopeKeys().iterator().next())
traversal.addStep(index, selectOneStep)
val generatedLabel = generateLabel()
if (selectOneStep.getPreviousStep() is EmptyStep) {
TraversalHelper.insertBeforeStep(IdentityStep(traversal), selectOneStep, traversal)
index++
}
selectOneStep.getPreviousStep().addLabel(generatedLabel)
TraversalHelper.insertAfterStep(
SelectOneStep(traversal, Pop.last, generatedLabel),
whereTraversalStep,
traversal
)
whereStartStep.removeScopeKey()
// process where(as("a").out()) => as('xyz').select("a").filter(out()).select('xyz')
if (localChild.getEndStep() !is WhereEndStep) {
localChild.removeStep(localChild.getStartStep())
traversal.addStep(index + 1, TraversalFilterStep(traversal, localChild))
traversal.removeStep(whereTraversalStep)
}
}
}
// process select("a","b").by(...).by(...)
val selectSteps: List<SelectStep> = TraversalHelper.getStepsOfClass(SelectStep::class.java, traversal)
for (selectStep in selectSteps) {
if (selectStep.getPop() !== Pop.all && selectStep.getPop() !== Pop.mixed && // TODO: necessary?
selectStep.getMaxRequirement().compareTo(PathProcessor.ElementRequirement.ID) > 0
) {
var oneLabel = true
for (key in selectStep.getScopeKeys()) {
if (labelCount(key, TraversalHelper.getRootTraversal(traversal)) > 1) {
oneLabel = false
break
}
}
if (!oneLabel) continue
val index: Int = TraversalHelper.stepIndex(selectStep, traversal)
val byTraversals: Map<String, Traversal.Admin<Object, Object>> = selectStep.getByTraversals()
val keys = arrayOfNulls<String>(byTraversals.size())
var counter = 0
for (entry in byTraversals.entrySet()) {
val selectOneStep = SelectOneStep(traversal, selectStep.getPop(), entry.getKey())
val mapStep: TraversalMapStep<*, *> = TraversalMapStep(traversal, entry.getValue().clone())
mapStep.addLabel(entry.getKey())
traversal.addStep(index + 1, mapStep)
traversal.addStep(index + 1, selectOneStep)
keys[counter++] = entry.getKey()
}
traversal.addStep(index + 1 + byTraversals.size() * 2, SelectStep(traversal, Pop.last, keys))
traversal.removeStep(index)
}
}
// process select("a").by(...)
//
// unfortunately, this strategy needs to know about ProductiveByStrategy. the ordering of strategies
// doesn't have enough flexibility to handle this situation where ProductiveByStrategy can run prior
// to this but also after ByModulatorOptimizationStrategy.
if (!traversal.getStrategies().getStrategy(ProductiveByStrategy::class.java).isPresent()) {
val selectOneSteps: List<SelectOneStep> =
TraversalHelper.getStepsOfClass(SelectOneStep::class.java, traversal)
for (selectOneStep in selectOneSteps) {
if (selectOneStep.getPop() !== Pop.all && selectOneStep.getPop() !== Pop.mixed && // TODO: necessary?
selectOneStep.getMaxRequirement().compareTo(PathProcessor.ElementRequirement.ID) > 0 && labelCount(
selectOneStep.getScopeKeys().iterator().next(),
TraversalHelper.getRootTraversal(traversal)
) <= 1
) {
val index: Int = TraversalHelper.stepIndex(selectOneStep, traversal)
val localChild: Traversal.Admin<*, *> = selectOneStep.getLocalChildren().get(0)
selectOneStep.removeLocalChild(localChild)
val mapStep: TraversalMapStep<*, *> = TraversalMapStep(traversal, localChild.clone())
traversal.addStep(index + 1, mapStep)
}
}
}
}
companion object {
private val INSTANCE = PathProcessorStrategy()
private val IS_TESTING: Boolean = Boolean.valueOf(System.getProperty("is.testing", "false"))
private val MARKER: String = Graph.Hidden.hide("gremlin.pathProcessor")
private val INVALIDATING_STEP_CLASSES: Set<Class> =
HashSet(Arrays.asList(PathStep::class.java, TreeStep::class.java, LambdaHolder::class.java))
fun instance(): PathProcessorStrategy {
return INSTANCE
}
private fun generateLabel(): String {
return if (IS_TESTING) "xyz" else UUID.randomUUID().toString()
}
private fun labelCount(label: String, traversal: Traversal.Admin<*, *>): Int {
var count = 0
for (step in traversal.getSteps()) {
if (step.getLabels().contains(label)) count++
if (step is TraversalParent) {
count =
count + (step as TraversalParent).getLocalChildren().stream().map { t -> labelCount(label, t) }
.reduce(0) { a, b -> a + b }
count =
count + (step as TraversalParent).getGlobalChildren().stream().map { t -> labelCount(label, t) }
.reduce(0) { a, b -> a + b }
}
}
return count
}
}
}
| 4
| null |
1
| 1
|
cb6805d686e9a27caa8e597b0728a50a63dc9092
| 10,023
|
tinkerpop4
|
Apache License 2.0
|
Mobile/Android/app/src/main/java/com/razvantmz/onemove/ui/addEvent/AddEventActivity.kt
|
razvantmzz
| 315,075,478
| false
|
{"Text": 1, "Markdown": 1, "Gradle": 3, "Java Properties": 2, "Shell": 1, "Ignore List": 2, "Batchfile": 1, "Proguard": 1, "JSON": 1, "Kotlin": 125, "XML": 114, "Java": 1}
|
package com.razvantmz.onemove.ui.addEvent
import android.annotation.SuppressLint
import android.app.Activity
import android.app.DatePickerDialog
import android.app.TimePickerDialog
import android.content.Intent
import android.content.res.Configuration
import android.os.Bundle
import android.text.Html
import android.util.Log
import androidx.core.widget.doAfterTextChanged
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import coil.api.load
import coil.transform.RoundedCornersTransformation
import com.github.irshulx.Editor
import com.razvantmz.onemove.R
import com.razvantmz.onemove.adapters.addPrice.PriceEntryListAdapter
import com.razvantmz.onemove.adapters.addSchedule.ScheduleListAdapter
import com.razvantmz.onemove.constants.RepositoryConstants
import com.razvantmz.onemove.core.extensions.setHoursMin
import com.razvantmz.onemove.core.extensions.showDateDialog
import com.razvantmz.onemove.core.extensions.showTimePickerDialog
import com.razvantmz.onemove.core.helpers.HtmlTagHandler
import com.razvantmz.onemove.core.managers.ImageManager.copyStream
import com.razvantmz.onemove.core.managers.ImageManager.createImageFile
import com.razvantmz.onemove.core.responseHandlers.ResponseCode
import com.razvantmz.onemove.core.utils.toHourMinFormat
import com.razvantmz.onemove.core.utils.toScheduleFormat
import com.razvantmz.onemove.databinding.ActivityAddEventBinding
import com.razvantmz.onemove.extensions.hideAnimated
import com.razvantmz.onemove.extensions.showAnimated
import com.razvantmz.onemove.ui.base.BaseActivity
import com.razvantmz.onemove.ui.base.CoreApplication
import com.razvantmz.onemove.ui.textEditor.TextEditorActivity
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream
class AddEventActivity : BaseActivity<ActivityAddEventBinding, AddEventViewModel>() {
companion object
{
const val RULES_RESULT = 6
const val DESCRIPTION_RESULT = 7
}
private lateinit var scheduleListAdapter:ScheduleListAdapter
private lateinit var priceListAdapter:PriceEntryListAdapter
override fun onCreate(savedInstanceState: Bundle?) {
binding = ActivityAddEventBinding.inflate(layoutInflater)
viewModel = ViewModelProviders.of(this).get(AddEventViewModel::class.java)
super.onCreate(savedInstanceState)
scheduleListAdapter = ScheduleListAdapter(viewModel.schedule.value!!)
priceListAdapter = PriceEntryListAdapter(this, viewModel.feesList.value!!)
setTitleSection();
setUpScheduleRecycler()
setUpPriceRecycler()
setTimeSection()
setFormSection()
setDescriptionSection()
setRulesSection()
setCoverPhotoSection()
setToolbar()
setValidation()
}
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
priceListAdapter.context = this
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if(resultCode == Activity.RESULT_CANCELED)
{
return
}
if(resultCode == RULES_RESULT)
{
val text = data?.extras?.getString(TextEditorActivity.TEXT_INPUT)
if(!text.isNullOrEmpty())
{
viewModel.rules.value = text
}
return
}
if(resultCode == DESCRIPTION_RESULT)
{
val text = data?.extras?.getString(TextEditorActivity.TEXT_INPUT)
if(!text.isNullOrEmpty())
{
viewModel.description.value = text
}
return
}
try {
// Creating file
var photoFile: File? = null
try {
photoFile = createImageFile(RepositoryConstants.UserProfileImageName)
if(photoFile == null)
{
viewModel.onErrorCode.setValue(ResponseCode.AnErrorOccurred)
return
}
viewModel.setCoverPhoto(photoFile)
} catch (ex: IOException) {
Log.d("Debug", "Error occurred while creating the file")
}
val inputStream: InputStream? = contentResolver.openInputStream(data?.data!!)
val fileOutputStream = FileOutputStream(photoFile)
// Copying
copyStream(inputStream!!, fileOutputStream)
fileOutputStream.close()
inputStream.close()
} catch (e: Exception) {
Log.d("Debug", "onActivityResult: $e")
}
}
fun setValidation()
{
viewModel.addValidationFields(
binding.eventTitleEt,
binding.formLinkET
)
}
@SuppressLint("ClickableViewAccessibility")
private fun setUpScheduleRecycler()
{
binding.scrollView.setOnTouchListener { v, event ->
binding.coordinatorLayout.requestFocusFromTouch()
return@setOnTouchListener false
}
binding.addScheduleIv.setOnClickListener{
scheduleListAdapter.addNextEntry()
}
binding.scheduleRecyclerView.layoutManager = LinearLayoutManager(baseContext)
binding.scheduleRecyclerView.adapter = scheduleListAdapter
}
private fun setUpPriceRecycler()
{
binding.priceRecyclerView.layoutManager = LinearLayoutManager(baseContext)
binding.priceRecyclerView.adapter = priceListAdapter
}
private fun setCoverPhotoSection()
{
binding.uploadPhotoTv.setOnClickListener {
val photoPickerIntent = Intent(Intent.ACTION_PICK)
photoPickerIntent.type = "image/*"
startActivityForResult(photoPickerIntent, 1)
}
binding.deleteCoverImageIv.setOnClickListener {
binding.coverImageContainer.hideAnimated(true)
binding.deleteCoverImageIv.hideAnimated(true)
binding.uploadPhotoTv.showAnimated()
viewModel.setCoverPhoto(null)
}
viewModel.getCoverPhoto().observe(this, Observer { url->
if(viewModel.getCoverPhoto().value == null)
{
// binding.coverImageContainer.forceLoad(url) {
// transformations(CircleCropTransformation())
// }
}
else
{
binding.coverImageContainer.showAnimated()
binding.deleteCoverImageIv.showAnimated()
binding.uploadPhotoTv.hideAnimated()
binding.coverImageContainer.load(viewModel.getCoverPhoto().value) {
transformations(RoundedCornersTransformation(5f, 5f, 5f, 5f))
}
}
})
}
private fun setTimeSection()
{
viewModel.startDate.observe(this, androidx.lifecycle.Observer {
binding.timeStartDateTv.text = it.time.toScheduleFormat()
binding.timeStartHourTv.text = it.time.toHourMinFormat()
})
viewModel.endDate.observe(this, androidx.lifecycle.Observer {
binding.timeEndDateTv.text = it.time.toScheduleFormat()
binding.timeEndHourTv.text = it.time.toHourMinFormat()
})
viewModel.isAllDay.observe(this, androidx.lifecycle.Observer {isChecked->
if(isChecked)
{
binding.timeStartHourTv.hideAnimated()
binding.timeEndHourTv.hideAnimated()
}
else
{
binding.timeStartHourTv.showAnimated()
binding.timeEndHourTv.showAnimated()
}
})
binding.timeStartDateTv.setOnClickListener {
showDateDialog()
{
onDateSetListener =
DatePickerDialog.OnDateSetListener { _, year, month, dayOfMonth ->
val cal = viewModel.startDate.value
cal?.set(year, month, dayOfMonth)
viewModel.startDate.value = cal
}
}
}
binding.timeEndDateTv.setOnClickListener {
showDateDialog()
{
onDateSetListener =
DatePickerDialog.OnDateSetListener { _, year, month, dayOfMonth ->
val cal = viewModel.endDate.value
cal?.set(year, month, dayOfMonth)
viewModel.endDate.value = cal
}
}
}
binding.timeStartHourTv.setOnClickListener {
showTimePickerDialog()
{
onDateSetListener =
TimePickerDialog.OnTimeSetListener { _, hourOfDay, minute ->
val cal = viewModel.startDate.value
viewModel.startDate.value = cal?.setHoursMin(hourOfDay, minute)
}
}
}
binding.timeEndHourTv.setOnClickListener {
showTimePickerDialog()
{
onDateSetListener =
TimePickerDialog.OnTimeSetListener { _, hourOfDay, minute ->
val cal = viewModel.endDate.value
viewModel.endDate.value = cal?.setHoursMin(hourOfDay, minute)
}
}
}
binding.btnAllDay.setOnClickListener {
viewModel.isAllDay.value = binding.btnAllDay.isChecked
}
}
private fun setFormSection()
{
viewModel.formLink.observe(this, androidx.lifecycle.Observer {
binding.formLinkET.setText(it)
binding.formLinkET.setSelection(it.length)
})
binding.formLinkET.doAfterTextChanged {
viewModel.formLink.value = it.toString()
}
}
private fun setDescriptionSection()
{
viewModel.description.observe(this, androidx.lifecycle.Observer {
val editor = Editor(this, null)
val mSerializedHtml = editor.getContentAsHTML(it)
binding.descriptionHtmlRendered.text = Html.fromHtml(mSerializedHtml, null, HtmlTagHandler())
})
binding.descriptionContainer.setOnClickListener {
val intent = Intent(this, TextEditorActivity::class.java)
CoreApplication.Instance.intentData = viewModel.rules.value
intent.putExtra(TextEditorActivity.REQUEST_CODE, DESCRIPTION_RESULT)
intent.putExtra(TextEditorActivity.TOOLBAR_TITLE, getString(R.string.description))
startActivityForResult(intent, DESCRIPTION_RESULT)
}
}
private fun setRulesSection()
{
viewModel.rules.observe(this, androidx.lifecycle.Observer {
val editor = Editor(this, null)
val mSerializedHtml = editor.getContentAsHTML(it)
binding.rulesHtmlRendered.text = Html.fromHtml(mSerializedHtml, null, HtmlTagHandler())
})
binding.rulesContainer.setOnClickListener {
val intent = Intent(this, TextEditorActivity::class.java)
CoreApplication.Instance.intentData = viewModel.rules.value
intent.putExtra(TextEditorActivity.REQUEST_CODE, RULES_RESULT)
intent.putExtra(TextEditorActivity.TOOLBAR_TITLE, getString(R.string.rules))
startActivityForResult(intent, RULES_RESULT)
}
}
private fun setTitleSection()
{
viewModel.eventTitle.observe(this, androidx.lifecycle.Observer {
binding.eventTitleEt.setText(it)
binding.eventTitleEt.setSelection(it.length)
})
binding.eventTitleEt.doAfterTextChanged {
viewModel.eventTitle.value = it.toString()
}
}
private fun setToolbar()
{
binding.toolbar.toolbarTitle.setText(R.string.title_add_event)
binding.toolbar.saveBtn.setOnClickListener {
viewModel.addEventAsync()
}
binding.toolbar.cancelBtn.setOnClickListener {
finish()
}
}
}
| 1
| null |
1
| 1
|
05bde5b64e54f6091dedcdd2da7093c3bfa4f522
| 12,174
|
gym-app
|
MIT License
|
kotlin/udacity-kotlin-bootcamp/HelloKotlin/src/playcollections.kt
|
hermantai
| 24,401,146
| false
|
{"Java": 1360692, "Kotlin": 1179906, "JavaScript": 516570, "Swift": 393329, "CSS": 135262, "Go": 63056, "Python": 52652, "Rust": 49486, "Jupyter Notebook": 32258, "HTML": 22692, "Dart": 17950, "Pug": 5366, "Shell": 2280, "Ruby": 1929, "C": 369, "Procfile": 15}
|
fun main(args: Array<String>) {
val allBooks = setOf("Macbeth", "Romeo and Juliet", "Hamlet", "A Midsummer Night's Dream")
val library = mapOf("Shakespeare" to allBooks)
println(library.any { it.value.contains("Hamlet") })
val moreBooks = mutableMapOf<String, String>("Wilhelm Tell" to "Schiller")
moreBooks.getOrPut("Jungle Book") { "Kipling" }
moreBooks.getOrPut("Hamlet") { "Shakespeare" }
println(moreBooks)
}
| 2
| null |
1
| 1
|
87f62edef85ff947c8b8f014dfd231cbf7cab021
| 428
|
samples
|
Apache License 2.0
|
compiler/psi/src/org/jetbrains/kotlin/parsing/util/parseFileUtils.kt
|
zhangdinet
| 128,026,457
| true
|
{"Kotlin": 27944627, "Java": 9967432, "JavaScript": 157318, "HTML": 61896, "Lex": 18174, "Groovy": 14207, "ANTLR": 9797, "IDL": 8102, "Shell": 5436, "CSS": 4679, "Batchfile": 4437}
|
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.parsing.util
import com.intellij.core.CoreApplicationEnvironment
import com.intellij.core.CoreProjectEnvironment
import com.intellij.lang.MetaLanguage
import com.intellij.openapi.Disposable
import com.intellij.openapi.extensions.Extensions
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vfs.StandardFileSystems
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.openapi.vfs.local.CoreLocalFileSystem
import com.intellij.psi.PsiManager
import com.intellij.psi.SingleRootFileViewProvider
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.parsing.KotlinParserDefinition
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.script.KotlinScriptDefinition
import org.jetbrains.kotlin.script.ScriptDefinitionProvider
import java.io.File
import java.util.*
fun classesFqNames(files: Set<File>): Set<String> = withPsiSetup {
val psiManager = PsiManager.getInstance(project)
val fileManager = VirtualFileManager.getInstance()
val localFS = fileManager.getFileSystem(StandardFileSystems.FILE_PROTOCOL) as CoreLocalFileSystem
classesFqNames(files, psiManager, localFS)
}
private fun classesFqNames(files: Collection<File>, psiManager: PsiManager, localFS: CoreLocalFileSystem): Set<String> {
val result = HashSet<String>()
for (file in files) {
if (!file.name.endsWith(".kt", ignoreCase = true)) continue
val virtualFile = localFS.findFileByIoFile(file) ?: continue
for (psiFile in SingleRootFileViewProvider(psiManager, virtualFile).allFiles) {
if (psiFile !is KtFile) continue
val classes = ArrayDeque<KtClassOrObject>()
psiFile.declarations.filterClassesTo(classes)
while (classes.isNotEmpty()) {
val klass = classes.pollFirst()
klass.fqName?.let {
result.add(it.asString())
}
klass.declarations.filterClassesTo(classes)
}
}
}
return result
}
private fun Collection<KtDeclaration>.filterClassesTo(classes: Deque<KtClassOrObject>) {
filterIsInstanceTo<KtClassOrObject, Deque<KtClassOrObject>>(classes)
}
private data class PsiSetup(
val applicationEnvironment: CoreApplicationEnvironment,
val projectEnvironment: CoreProjectEnvironment,
val project: Project,
val disposable: Disposable
)
private inline fun <T> withPsiSetup(fn: PsiSetup.() -> T): T {
val disposable = Disposer.newDisposable()
return try {
val applicationEnvironment = CoreApplicationEnvironment(disposable, false)
val projectEnvironment = CoreProjectEnvironment(disposable, applicationEnvironment)
CoreApplicationEnvironment.registerExtensionPoint(Extensions.getRootArea(), MetaLanguage.EP_NAME, MetaLanguage::class.java)
applicationEnvironment.registerApplicationService(ScriptDefinitionProvider::class.java, NoopScriptDefinitionProvider())
applicationEnvironment.registerFileType(KotlinFileType.INSTANCE, "kt")
applicationEnvironment.registerParserDefinition(KotlinParserDefinition())
val project = projectEnvironment.project
val setup = PsiSetup(applicationEnvironment, projectEnvironment, project, disposable)
setup.fn()
} finally {
Disposer.dispose(disposable)
}
}
private class NoopScriptDefinitionProvider : ScriptDefinitionProvider {
override fun isScript(fileName: String): Boolean {
return false
}
override fun findScriptDefinition(fileName: String): KotlinScriptDefinition? {
return null
}
}
| 0
|
Kotlin
|
0
| 1
|
0439abba462a67e10c2fb73f2ae01d2a03892103
| 3,946
|
kotlin
|
Apache License 2.0
|
app/src/main/java/com/openclassrooms/realestatemanager/data/database/dao/PictureDao.kt
|
mutwakilmo
| 284,513,894
| false
|
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Java": 6, "XML": 88, "JSON": 6, "Kotlin": 110}
|
package com.openclassrooms.realestatemanager.data.database.dao
import android.database.Cursor
import androidx.room.*
import com.openclassrooms.realestatemanager.data.entity.Picture
import com.openclassrooms.realestatemanager.utils.PICTURE_TABLE_NAME
/**
* Created by Mutwakil-Mo 🤩
* Android Engineer,
* Brussels
*/
@Dao
interface PictureDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertPicture(pictures: List<Picture>)
@Query("DELETE FROM $PICTURE_TABLE_NAME WHERE picture_id IN (:pictureId)")
suspend fun deletePictures(pictureId: List<String>)
@Update
suspend fun updatePicture(pictures: List<Picture>)
@Query("SELECT * FROM $PICTURE_TABLE_NAME WHERE picture_id = :pictureId")
fun getPictureWithCursor(pictureId: String): Cursor
@Query("SELECT * FROM $PICTURE_TABLE_NAME WHERE id_property = :propertyId")
fun getPropertyPicturesWithCursor(propertyId: String): Cursor
}
| 0
|
Kotlin
|
0
| 0
|
85115879ceee2a6e64d7730875998c115785915b
| 947
|
RealEstateManager
|
Apache License 2.0
|
app/src/main/java/com/wavesplatform/wallet/v2/ui/home/quick_action/receive/bank/BankPresenter.kt
|
luffy97
| 185,141,897
| true
|
{"Kotlin": 1222636, "Java": 270135, "HTML": 25816}
|
package com.wavesplatform.wallet.v2.ui.home.quick_action.receive.bank
import com.arellomobile.mvp.InjectViewState
import com.wavesplatform.wallet.v2.ui.base.presenter.BasePresenter
import javax.inject.Inject
@InjectViewState
class BankPresenter @Inject constructor() : BasePresenter<BankView>()
| 1
|
Kotlin
|
0
| 0
|
82539c029333ba3d9981493e771d1d273d436b20
| 297
|
WavesWallet-android
|
MIT License
|
idea/testData/intentions/conventionNameCalls/replaceContains/missingArgument.kt
|
staltz
| 50,323,841
| false
| null |
// IS_APPLICABLE: false
// ERROR: No value passed for parameter b
fun test() {
class Test{
fun contains(a: Int, b: Int): Boolean = true
}
val test = Test()
test.cont<caret>ains(0)
}
| 0
| null |
0
| 1
|
ff00bde607d605c4eba2d98fbc9e99af932accb6
| 206
|
kotlin
|
Apache License 2.0
|
app/src/main/kotlin/org/misumirize/speechtoamazon/ScreenReceiver.kt
|
MisumiRize
| 61,784,912
| false
|
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Java": 2, "XML": 7, "Kotlin": 6, "JSON": 1, "Dockerfile": 1, "JavaScript": 1}
|
package org.misumirize.speechtoamazon
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
class ScreenReceiver : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
if (context != null) {
val i = Intent(context, AccelerometerService::class.java)
i.action = intent?.action
context.startService(i)
}
}
}
| 1
| null |
1
| 1
|
fedc8319fa833c1042da644de496c9f6aaf980dc
| 447
|
SpeechToAmazon
|
MIT License
|
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/autonomy/AutoParkDreapta.kt
|
cosmin-26
| 665,761,061
| false
|
{"Java": 223224, "Kotlin": 157107}
|
package org.firstinspires.ftc.teamcode.autonomy
import com.acmerobotics.dashboard.config.Config
import com.acmerobotics.roadrunner.geometry.Pose2d
import com.acmerobotics.roadrunner.geometry.Vector2d
import com.qualcomm.robotcore.eventloop.opmode.Autonomous
import com.qualcomm.robotcore.util.ElapsedTime
import org.firstinspires.ftc.teamcode.drive.DriveConstants
import org.firstinspires.ftc.teamcode.drive.SampleMecanumDrive
import org.firstinspires.ftc.teamcode.hardware.Hardware
import org.firstinspires.ftc.teamcode.waitMillis
import java.util.concurrent.TimeUnit
@Autonomous
@Config
class AutoParkDreapta : AutoBase() {
//TODO de pus pus o auto care e autobluebluenopreload2 care are y mai mult pe - cu cam 2 3 poz + auto doar parcat
// asta e dreapta jos si stanga sus terenul nostru dinspre masa cu unelte inspre chestia cu awards
private val n : Int = 5
private val startPose = Pose2d(0.0, 0.0, Math.toRadians(0.0))
private val interConeTakePose = Pose2d(35.0,0.0,Math.toRadians(-92.0)) //private val interConeTakePose = Pose2d(35.0,0.0,Math.toRadians(-92.0))
private val vecConeTakePose = Vector2d(48.0,-8.0) //private val vecConeTakePose = Vector2d(48.0,-10.0)
private val tag11 = Vector2d(48.0, 22.0) // cel cu un punct stanga
private val tag14 = Vector2d(48.0, -20.0) // cel cu 3 puncte dreapta
private val tag19 = Vector2d(48.0, 0.0) // cel cu 2 puncte fata
val i = 1
override fun preInit() {
super.preInit()
telemetry.addLine("Initializing...")
telemetry.update()
drive.poseEstimate = startPose
}
override fun Hardware.run() {
telemetry.addLine(String.format("\nAm detectat un tag ID=%d", tagOfInterest?.id))
telemetry.update()
drive.followTrajectory(
drive.trajectoryBuilder(startPose)
.splineToSplineHeading(interConeTakePose,Math.toRadians(0.0))
.splineToConstantHeading(vecConeTakePose,Math.toRadians(0.0))
.build()
)
waitMillis(1000)
if (tagOfInterest?.id == 11) { // in stanga (fata de poz de start)
drive.followTrajectory(
drive.trajectoryBuilder(drive.poseEstimate)
.lineTo(tag11)
.build()
)
telemetry.addLine(String.format("\nAm ajuns la tag ID=%d", tagOfInterest?.id))
telemetry.update()
}
if (tagOfInterest?.id == 14) { // in dreapta (fata de poz de start)
drive.followTrajectory(
drive.trajectoryBuilder(drive.poseEstimate)
.lineTo(tag14)
.build()
)
telemetry.addLine(String.format("\nAm ajuns la tag ID=%d", tagOfInterest?.id))
telemetry.update()
}
if (tagOfInterest?.id == 19) { // in fata (fata de poz de start)
drive.followTrajectory(
drive.trajectoryBuilder(drive.poseEstimate)
.lineToConstantHeading(tag19)
.build()
)
telemetry.addLine(String.format("\nAm ajuns la tag ID=%d", tagOfInterest?.id))
telemetry.update()
}
intake.autoArmInter()
waitMillis(3000)
intake.holdCone()
waitMillis(3000)
outtake.holdCone()
waitMillis(3000)
outtake.armInter()
waitMillis(3000)
outtake.armDrop()
waitMillis(3000)
outtake.armInter()
waitMillis(3000)
outtake.armDrop()
waitMillis(3000)
outtake.armInter()
waitMillis(3000)
outtake.armDrop()
waitMillis(3000)
}
}
| 1
| null |
1
| 1
|
8d8ec1a95afa1fb15f82f272ee6838d814db6018
| 3,673
|
ftc-qube
|
BSD 3-Clause Clear License
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.