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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
plugins/korge-intellij-plugin/src/com/soywiz/korge/intellij/IdeaAdaptorVfs.kt
|
phyrian
| 209,852,647
| true
|
{"Kotlin": 958944, "Java": 182756, "ActionScript": 7295, "HTML": 174}
|
package com.soywiz.korge.intellij
import com.intellij.openapi.vfs.VirtualFile
import com.soywiz.korio.async.AsyncSequence
import com.soywiz.korio.async.asyncGenerate
import com.soywiz.korio.lang.Closeable
import com.soywiz.korio.stream.AsyncInputStream
import com.soywiz.korio.stream.AsyncStream
import com.soywiz.korio.file.*
import java.io.File
import java.io.FileNotFoundException
import kotlin.reflect.KClass
fun VirtualFile.toVfs(): VfsFile {
val file = this
val url = file.canonicalPath ?: ""
println("VirtualFile.toVfs: path=${file.path}, canonicalPath=${file.url}")
val root = this.root
println("VirtualFile.toVfs.root: path=${root.path}, canonicalPath=${root.canonicalPath}")
//return File(URI(url)).toVfs()
return File(url).toVfs()
}
val VirtualFile.root: VirtualFile get() = this.parent?.root ?: this
// @TODO: Do this properly
class IdeaAdaptorVfs(val file: VirtualFile) : Vfs() {
override val absolutePath: String = file.toString()
private fun access(path: String): VirtualFile? {
var current: VirtualFile? = file
for (component in path.split("/")) {
when (component) {
".", "" -> {
current = current
}
".." -> {
current = current?.parent
}
else -> {
current = current?.findChild(component)
}
}
}
return current
}
private fun accessSure(path: String): VirtualFile =
access(path) ?: throw FileNotFoundException("$absolutePath/$path")
suspend override fun delete(path: String): Boolean {
return super.delete(path)
}
suspend override fun exec(path: String, cmdAndArgs: List<String>, handler: VfsProcessHandler): Int {
return super.exec(path, cmdAndArgs, handler)
}
suspend override fun exec(
path: String,
cmdAndArgs: List<String>,
env: Map<String, String>,
handler: VfsProcessHandler
): Int {
return super.exec(path, cmdAndArgs, env, handler)
}
override fun getAbsolutePath(path: String): String = accessSure(path).toString()
suspend override fun list(path: String): AsyncSequence<VfsFile> = asyncGenerate {
val children = accessSure(path).children
for (item in children.map { VfsFile(this@IdeaAdaptorVfs, "$path/${it.name}") }) {
yield(item)
}
}
suspend override fun mkdir(path: String, attributes: List<Attribute>): Boolean {
return super.mkdir(path, attributes)
}
suspend override fun open(path: String, mode: VfsOpenMode): AsyncStream {
return super.open(path, mode)
}
suspend override fun put(path: String, content: AsyncInputStream, attributes: List<Attribute>): Long {
return super.put(path, content, attributes)
}
suspend override fun readRange(path: String, range: LongRange): ByteArray {
return super.readRange(path, range)
}
suspend override fun <T : Any> readSpecial(path: String, clazz: KClass<T>): T {
return super.readSpecial(path, clazz)
}
suspend override fun rename(src: String, dst: String): Boolean {
return super.rename(src, dst)
}
suspend override fun setAttributes(path: String, attributes: List<Attribute>) {
super.setAttributes(path, attributes)
}
suspend override fun setSize(path: String, size: Long) {
super.setSize(path, size)
}
suspend override fun stat(path: String): VfsStat {
return super.stat(path)
}
suspend override fun touch(path: String, time: Long, atime: Long) {
super.touch(path, time, atime)
}
suspend override fun watch(path: String, handler: (VfsFileEvent) -> Unit): Closeable {
return super.watch(path, handler)
}
}
| 0
|
Kotlin
|
0
| 0
|
cee8132dd63f168cdcc186c5510afd6985a53b3f
| 3,438
|
korge
|
Apache License 2.0
|
platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/XDebugSessionTab3.kt
|
xieguanliang
| 261,644,228
| false
| null |
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.xdebugger.impl.ui
import com.intellij.debugger.ui.DebuggerContentInfo
import com.intellij.execution.runners.ExecutionEnvironment
import com.intellij.execution.runners.PreferredPlace
import com.intellij.execution.runners.RunTab
import com.intellij.execution.ui.layout.LayoutAttractionPolicy
import com.intellij.execution.ui.layout.PlaceInGrid
import com.intellij.execution.ui.layout.impl.RunnerLayoutUiImpl
import com.intellij.icons.AllIcons
import com.intellij.ide.util.PropertiesComponent
import com.intellij.idea.ActionsBundle
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.impl.MoreActionGroup
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.wm.ToolWindowAnchor
import com.intellij.openapi.wm.impl.InternalDecoratorImpl
import com.intellij.openapi.wm.impl.content.SingleContentSupplier
import com.intellij.ui.OnePixelSplitter
import com.intellij.ui.content.tabs.PinToolwindowTabAction
import com.intellij.util.ui.UIUtil
import com.intellij.xdebugger.XDebuggerBundle
import com.intellij.xdebugger.impl.XDebugSessionImpl
import com.intellij.xdebugger.impl.actions.XDebuggerActions
import com.intellij.xdebugger.impl.frame.XFramesView
import com.intellij.xdebugger.impl.frame.XVariablesView
import com.intellij.xdebugger.impl.frame.XWatchesViewImpl
import java.awt.Dimension
import javax.swing.Icon
class XDebugSessionTab3(
session: XDebugSessionImpl,
icon: Icon?,
environment: ExecutionEnvironment?
) : XDebugSessionTab(session, icon, environment, false) {
companion object {
private const val threadsIsVisibleKey = "threadsIsVisibleKey"
private const val viewProportionKey = "debugger.layout.watches.defaultThreadsProportion"
private const val debuggerContentId = "DebuggerView"
}
private val project = session.project
private var threadsIsVisible
get() = PropertiesComponent.getInstance(project).getBoolean(threadsIsVisibleKey, true)
set(value) = PropertiesComponent.getInstance(project).setValue(threadsIsVisibleKey, value, true)
private val lifetime = Disposer.newDisposable()
private val splitter = OnePixelSplitter(viewProportionKey, 0.35f).apply {
addPropertyChangeListener {
if ("ancestor" == it.propertyName && it.newValue != null) {
updateSplitterOrientation()
}
}
}
private val xThreadsFramesView = XFramesView(myProject)
private var variables: XVariablesView? = null
private var mySingleContentSupplier: SingleContentSupplier? = null
override fun getWatchesContentId() = debuggerContentId
override fun getFramesContentId() = debuggerContentId
override fun addVariablesAndWatches(session: XDebugSessionImpl) {
val variablesView: XVariablesView?
val watchesView: XVariablesView?
if (isWatchesInVariables) {
variablesView = XWatchesViewImpl(session, true, true, false)
registerView(DebuggerContentInfo.VARIABLES_CONTENT, variablesView)
variables = variablesView
myWatchesView = variablesView
} else {
variablesView = XVariablesView(session)
registerView(DebuggerContentInfo.VARIABLES_CONTENT, variablesView)
variables = variablesView
watchesView = XWatchesViewImpl(session, false, true, false)
registerView(DebuggerContentInfo.WATCHES_CONTENT, watchesView)
myWatchesView = watchesView
myUi.addContent(createWatchesContent(session), 0, PlaceInGrid.right, false)
}
splitter.secondComponent = variablesView.panel
UIUtil.removeScrollBorder(splitter)
}
override fun initDebuggerTab(session: XDebugSessionImpl) {
val framesView = xThreadsFramesView
registerView(DebuggerContentInfo.FRAME_CONTENT, framesView)
splitter.firstComponent = xThreadsFramesView.mainPanel.apply {
minimumSize = Dimension(20, 0)
}
addVariablesAndWatches(session)
val name = debuggerContentId
val content = myUi.createContent(name, splitter, XDebuggerBundle.message("xdebugger.threads.vars.tab.title"), null, framesView.defaultFocusedComponent).apply {
isCloseable = false
}
myUi.addContent(content, 0, PlaceInGrid.center, false)
ui.defaults.initContentAttraction(debuggerContentId, XDebuggerUIConstants.LAYOUT_VIEW_BREAKPOINT_CONDITION, LayoutAttractionPolicy.FocusOnce())
}
override fun initToolbars(session: XDebugSessionImpl) {
(myUi as? RunnerLayoutUiImpl)?.setLeftToolbarVisible(false)
val gearActions = DefaultActionGroup().apply {
templatePresentation.text = ActionsBundle.message("group.XDebugger.settings.text")
templatePresentation.icon = AllIcons.General.Settings
isPopup = true
addAll(*myUi.options.settingsActionsList)
registerAdditionalActions(DefaultActionGroup(), DefaultActionGroup(), this)
}
val toolbar = DefaultActionGroup()
toolbar.addAll(getCustomizedActionGroup(XDebuggerActions.TOOL_WINDOW_TOP_TOOLBAR_3_GROUP))
val more = MoreActionGroup()
more.addAll(getCustomizedActionGroup(XDebuggerActions.TOOL_WINDOW_TOP_TOOLBAR_3_EXTRA_GROUP))
toolbar.add(more)
more.addSeparator()
fun addWithConstraints(actions: List<AnAction>, constraints: Constraints) {
actions.asSequence()
.forEach {
if (it.templatePresentation.getClientProperty(RunTab.PREFERRED_PLACE) == PreferredPlace.MORE_GROUP) {
more.add(it)
} else {
toolbar.add(it, constraints)
}
}
}
// reversed because it was like this in the original tab
addWithConstraints(session.restartActions.asReversed(), Constraints(Anchor.AFTER, IdeActions.ACTION_RERUN))
addWithConstraints(session.extraActions.asReversed(), Constraints(Anchor.AFTER, IdeActions.ACTION_STOP_PROGRAM))
addWithConstraints(session.extraStopActions, Constraints(Anchor.AFTER, IdeActions.ACTION_STOP_PROGRAM))
more.addSeparator()
more.add(gearActions)
myUi.options.setTopLeftToolbar(toolbar, ActionPlaces.DEBUGGER_TOOLBAR)
mySingleContentSupplier = object : RunTabSupplier(toolbar) {
override fun getContentActions(): List<AnAction> {
return super.getContentActions() + PinToolwindowTabAction.getPinAction()
}
}
}
override fun getSupplier(): SingleContentSupplier? = mySingleContentSupplier
override fun registerAdditionalActions(leftToolbar: DefaultActionGroup, topLeftToolbar: DefaultActionGroup, settings: DefaultActionGroup) {
leftToolbar.apply {
val constraints = Constraints(Anchor.BEFORE, XDebuggerActions.VIEW_BREAKPOINTS)
add(object : ToggleAction() {
override fun setSelected(e: AnActionEvent, state: Boolean) {
if (threadsIsVisible != state) {
threadsIsVisible = state
}
//xThreadsFramesView.setThreadsVisible(state)
Toggleable.setSelected(e.presentation, state)
}
override fun isSelected(e: AnActionEvent) = threadsIsVisible
override fun update(e: AnActionEvent) {
e.presentation.icon = AllIcons.Actions.SplitVertically
if (threadsIsVisible) {
e.presentation.text = XDebuggerBundle.message("session.tab.hide.threads.view")
}
else {
e.presentation.text = XDebuggerBundle.message("session.tab.show.threads.view")
}
setSelected(e, threadsIsVisible)
}
}, constraints)
add(ActionManager.getInstance().getAction(XDebuggerActions.FRAMES_TOP_TOOLBAR_GROUP), constraints)
add(Separator.getInstance(), constraints)
}
super.registerAdditionalActions(leftToolbar, topLeftToolbar, settings)
}
private fun updateSplitterOrientation() {
splitter.orientation = UIUtil.getParentOfType(InternalDecoratorImpl::class.java, splitter)
?.let(PlatformDataKeys.TOOL_WINDOW::getData)
?.let {
it.anchor == ToolWindowAnchor.LEFT || it.anchor == ToolWindowAnchor.RIGHT
} ?: false
}
override fun dispose() {
Disposer.dispose(lifetime)
super.dispose()
}
}
| 1
| null |
1
| 1
|
d39c1b5060e799de1911c3a04a46bbd0669a7dd6
| 8,214
|
intellij-community
|
Apache License 2.0
|
device/src/main/java/org/watsi/device/db/daos/IdentificationEventDao.kt
|
Meso-Health
| 227,514,539
| false
|
{"Gradle": 7, "Java Properties": 2, "Shell": 3, "Text": 1, "Ignore List": 4, "Markdown": 1, "Proguard": 2, "JSON": 25, "Kotlin": 419, "YAML": 3, "XML": 153, "Java": 1}
|
package org.watsi.device.db.daos
import android.arch.persistence.room.Dao
import android.arch.persistence.room.Insert
import android.arch.persistence.room.OnConflictStrategy
import android.arch.persistence.room.Query
import android.arch.persistence.room.Transaction
import io.reactivex.Flowable
import io.reactivex.Single
import org.watsi.device.db.models.DeltaModel
import org.watsi.device.db.models.IdentificationEventModel
import java.util.UUID
@Dao
interface IdentificationEventDao {
@Query("SELECT * FROM identification_events")
fun all(): Flowable<List<IdentificationEventModel>>
@Query("SELECT * FROM identification_events WHERE id = :id LIMIT 1")
fun find(id: UUID): Single<IdentificationEventModel>
@Insert
fun insert(model: IdentificationEventModel)
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun upsert(models: List<IdentificationEventModel>)
@Query("DELETE FROM identification_events WHERE id IN (:ids)")
fun delete(ids: List<UUID>)
@Insert
fun insertWithDelta(model: IdentificationEventModel, delta: DeltaModel)
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun upsertWithDelta(model: IdentificationEventModel, delta: DeltaModel)
@Query("SELECT identification_events.* FROM identification_events\n" +
"INNER JOIN deltas ON\n" +
"(identification_events.id = deltas.modelId AND\n" +
"deltas.synced = 0 AND\n" +
"deltas.modelName = 'IDENTIFICATION_EVENT')")
fun unsynced(): Single<List<IdentificationEventModel>>
//TODO: change query to use submissionState = "started" instead of preparedAt = null once submissionState is added
@Transaction
@Query("SELECT identification_events.*\n" +
"FROM identification_events\n" +
"LEFT OUTER JOIN encounters ON encounters.identificationEventId = identification_events.id\n" +
"WHERE (encounters.identificationEventId IS NULL OR encounters.preparedAt IS NULL)\n" +
" AND identification_events.dismissed = 0\n" +
"ORDER BY identification_events.occurredAt")
fun activeCheckIns(): Flowable<List<IdentificationEventModel>>
}
| 2
|
Kotlin
|
3
| 6
|
6e1da182073088f28230fe60a2e09d6f38aab957
| 2,179
|
meso-clinic
|
Apache License 2.0
|
generator/src/main/kotlin/fixie/generator/quantity/FixedQuantityClass.kt
|
knokko
| 687,847,559
| false
|
{"Kotlin": 421410}
|
package fixie.generator.quantity
import fixie.generator.number.NumberClass
import fixie.generator.roundBigDecimal
import java.math.BigDecimal
import java.math.BigInteger
import kotlin.math.abs
abstract class FixedQuantityClass(
className: String,
val number: NumberClass,
createNumberExtensions: Boolean
) : QuantityClass(className, createNumberExtensions) {
override fun toString() = "$className($number)"
protected fun determineRawValue(divisor: BigDecimal) = determineRawValue(divisor, number)
companion object {
internal fun determineRawValue(divisor: BigDecimal, number: NumberClass): BigInteger? {
val rawValue = roundBigDecimal(number.oneValue.toBigDecimal() / divisor)
val revertedValue = roundBigDecimal(rawValue.toBigDecimal() * divisor)
val lostPrecision = ((number.oneValue - revertedValue).toBigDecimal() / number.oneValue.toBigDecimal()).toDouble()
return if (number.internalType.canRepresent(rawValue) && abs(lostPrecision) < 0.1) rawValue
else null
}
}
}
| 0
|
Kotlin
|
0
| 0
|
5ad29202e30e0779bccc7147670342bd08066132
| 1,092
|
fixie
|
MIT License
|
project-system-gradle-psd/src/com/android/tools/idea/gradle/structure/configurables/ui/properties/manipulation/ExtractVariableDialog.kt
|
JetBrains
| 60,701,247
| false
| null |
/*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.idea.gradle.structure.configurables.ui.properties.manipulation
import com.android.tools.idea.gradle.structure.configurables.ui.properties.ModelPropertyEditorFactory
import com.android.tools.idea.gradle.structure.model.PsProject
import com.android.tools.idea.gradle.structure.model.PsVariablesScope
import com.android.tools.idea.gradle.structure.model.helpers.ExtractVariableWorker
import com.android.tools.idea.gradle.structure.model.meta.ModelPropertyCore
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.ui.JBColor
import javax.swing.JComponent
class ExtractVariableDialog<PropertyT : Any, ModelPropertyCoreT : ModelPropertyCore<PropertyT>>(
project: PsProject,
scope: PsVariablesScope,
refactoredProperty: ModelPropertyCoreT,
private var editorFactory: ModelPropertyEditorFactory<PropertyT, ModelPropertyCoreT>
) : DialogWrapper(project.ideProject) {
private var form: ExtractVariableForm? = null
private val name: String get() = form?.myNameField?.text ?: ""
private val scopes = scope.getVariableScopes().associateBy { it.title }
private val worker = ExtractVariableWorker(refactoredProperty)
init {
title = "Extract Variable"
init()
}
override fun createCenterPanel(): JComponent? {
val form = ExtractVariableForm()
scopes.forEach { scope, _ -> form.myScopeField!!.addItem(scope) }
// Prefer Project scope. (The first scope in the list is expected to be the build script scope.)
val defaultScope = scopes.keys.drop(1).firstOrNull() ?: scopes.keys.first()
configureFormFor(form, defaultScope)
form.myScopeField.addActionListener {
configureFormFor(form, form.myScopeField.selectedItem as String)
}
form.myScopeField.background = JBColor.background()
this.form = form
return form.myPanel
}
private fun configureFormFor(form: ExtractVariableForm, scope: String) {
val (newName, property) = worker.changeScope(scopes[scope]!!, form.myNameField.text)
val editor = editorFactory.createNew(property, isPropertyContext = false)
form.myNameField.text = newName
form.setValueEditor(editor.component)
form.myScopeField.selectedItem = scope
}
override fun doValidate(): ValidationInfo? =
worker.validate(name)?.let { ValidationInfo(it).withOKEnabled() }
override fun doCancelAction() {
super.doCancelAction()
worker.cancel()
}
override fun doOKAction() {
super.doOKAction()
worker.commit(name)
}
override fun getPreferredFocusedComponent(): JComponent? {
return form?.myNameField
}
}
| 5
| null |
227
| 948
|
10110983c7e784122d94c7467e9d243aba943bf4
| 3,240
|
android
|
Apache License 2.0
|
app/src/main/kotlin/_4_classes/_5_Delegations.kt
|
PrashantSPol
| 110,964,845
| false
| null |
package _4_classes
/**
* Created by prashantspol on 11/10/2017.
*/
interface Callable {
fun call()
}
class Phone : Callable {
override fun call() {
}
}
class Tablet(c: Callable) : Callable by c
fun letsCall(tablet : Tablet) {
tablet.call()
}
| 1
| null |
1
| 1
|
12738832473a05e3d919a5d2e2dc5c5621d125c2
| 264
|
KotlinSamples
|
Apache License 2.0
|
android_client/app/src/main/java/com/microsoft/hydralab/android/client/vpn/protocol/TCBStatus.kt
|
microsoft
| 486,525,050
| false
| null |
package studio.attect.demo.vpnservice.protocol
enum class TCBStatus {
SYN_SENT,
SYN_RECEIVED,
ESTABLISHED,
CLOSE_WAIT,
LAST_ACK,
CLOSED
}
| 46
| null |
94
| 997
|
4d24a7064464d90dd624a0bb120872fab0cdb89e
| 162
|
HydraLab
|
MIT License
|
app/src/main/java/ajar/huzefa/olaplay/data/HistoryDao.kt
|
huzefaraja
| 115,239,147
| false
| null |
package ajar.huzefa.olaplay.data
import android.arch.persistence.room.*
@Dao
interface HistoryDao {
@Query("SELECT * FROM history")
fun all(): List<History>
@Insert(onConflict = OnConflictStrategy.ABORT)
fun insert(vararg Histories: History): Array<Long>
@Insert(onConflict = OnConflictStrategy.ABORT)
fun insert(Histories: History): Long
@Update(onConflict = OnConflictStrategy.REPLACE)
fun update(vararg Histories: History)
@Delete
fun delete(History: History)
}
| 1
| null |
1
| 1
|
779098baaf99b5a31389ec08ef33dff4a959f19e
| 505
|
ola_play
|
MIT License
|
feature/autodiscovery/service/src/main/kotlin/app/k9mail/autodiscovery/service/RealAutoDiscoveryService.kt
|
thunderbird
| 1,326,671
| false
|
{"Kotlin": 4766001, "Java": 2159946, "Shell": 2768, "AIDL": 1946}
|
package app.k9mail.autodiscovery.service
import app.k9mail.autodiscovery.api.AutoDiscoveryRegistry
import app.k9mail.autodiscovery.api.AutoDiscoveryResult
import app.k9mail.autodiscovery.api.AutoDiscoveryService
import app.k9mail.core.common.mail.EmailAddress
/**
* Uses Thunderbird's Autoconfig mechanism to find mail server settings for a given email address.
*/
class RealAutoDiscoveryService(
private val autoDiscoveryRegistry: AutoDiscoveryRegistry,
) : AutoDiscoveryService {
override suspend fun discover(email: EmailAddress): AutoDiscoveryResult {
val runner = PriorityParallelRunner(
runnables = autoDiscoveryRegistry.getAutoDiscoveries().flatMap { it.initDiscovery(email) },
)
return runner.run()
}
}
| 846
|
Kotlin
|
2467
| 9,969
|
8b3932098cfa53372d8a8ae364bd8623822bd74c
| 764
|
thunderbird-android
|
Apache License 2.0
|
bugsnag-android-core/src/androidTest/java/com/bugsnag/android/ThreadStateTest.kt
|
AllanWang
| 199,244,341
| true
|
{"Java": 608807, "C": 274520, "Kotlin": 140929, "Gherkin": 115095, "C++": 38356, "Ruby": 20243, "Shell": 6349, "CMake": 5105, "Makefile": 2290}
|
package com.bugsnag.android
import android.support.test.filters.SmallTest
import android.support.test.runner.AndroidJUnit4
import com.bugsnag.android.BugsnagTestUtils.streamableToJsonArray
import org.json.JSONArray
import org.json.JSONObject
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
@SmallTest
class ThreadStateTest {
private val configuration = Configuration("api-key")
private val threadState = ThreadState(configuration, Thread.currentThread(), Thread.getAllStackTraces(), null)
private val json = streamableToJsonArray(threadState)
/**
* Verifies that the required values for 'thread' are serialised as an array
*/
@Test
fun testSerialisation() {
for (k in 0 until json.length()) {
val thread = json[k] as JSONObject
assertNotNull(thread.getString("id"))
assertNotNull(thread.getString("name"))
assertNotNull(thread.getString("stacktrace"))
assertEquals("android", thread.getString("type"))
}
}
/**
* Verifies that the current thread is serialised as an object, and that only this value
* contains the errorReportingThread boolean flag
*/
@Test
fun testCurrentThread() {
verifyCurrentThreadStructure(json, Thread.currentThread().id)
}
/**
* Verifies that a thread different from the current thread is serialised as an object,
* and that only this value contains the errorReportingThread boolean flag
*/
@Test
fun testDifferentThread() {
val otherThread = Thread.getAllStackTraces()
.filter { it.key != Thread.currentThread() }
.map { it.key }
.first()
val state = ThreadState(configuration, otherThread, Thread.getAllStackTraces(), null)
val json = streamableToJsonArray(state)
verifyCurrentThreadStructure(json, otherThread.id)
}
/**
* Verifies that if the current thread is missing from the available traces as reported by
* [Thread.getAllStackTraces], its stacktrace will still be serialised
*/
@Test
fun testMissingCurrentThread() {
val currentThread = Thread.currentThread()
val missingTraces = Thread.getAllStackTraces()
missingTraces.remove(currentThread)
val state = ThreadState(configuration, currentThread, missingTraces, null)
val json = streamableToJsonArray(state)
verifyCurrentThreadStructure(json, currentThread.id) {
assertTrue(it.getJSONArray("stacktrace").length() > 0)
}
}
/**
* Verifies that a handled error uses [Thread] for the reporting thread stacktrace
*/
@Test
fun testHandledStacktrace() {
val currentThread = Thread.currentThread()
val allStackTraces = Thread.getAllStackTraces()
val state = ThreadState(configuration, currentThread, allStackTraces, null)
val json = streamableToJsonArray(state)
// find the stack trace for the current thread that was passed as a parameter
val expectedTrace = allStackTraces.filter {
it.key.id == currentThread.id
}.map { it.value }.first()
verifyCurrentThreadStructure(json, currentThread.id) {
// the thread id + name should always be used
assertEquals(currentThread.name, it.getString("name"))
assertEquals(currentThread.id, it.getLong("id"))
// stacktrace should come from the thread (check same length and line numbers)
val serialisedTrace = it.getJSONArray("stacktrace")
assertEquals(expectedTrace.size, serialisedTrace.length())
expectedTrace.forEachIndexed { index, element ->
val jsonObject = serialisedTrace.getJSONObject(index)
assertEquals(element.lineNumber, jsonObject.getInt("lineNumber"))
}
}
}
/**
* * Verifies that an unhandled error uses [Exception] for the reporting thread stacktrace
*/
@Test
fun testUnhandledStacktrace() {
val currentThread = Thread.currentThread()
val allStackTraces = Thread.getAllStackTraces()
val exc: Throwable = RuntimeException("Whoops")
val expectedTrace = exc.stackTrace
val state = ThreadState(configuration, currentThread, allStackTraces, exc)
val json = streamableToJsonArray(state)
verifyCurrentThreadStructure(json, currentThread.id) {
// the thread id + name should always be used
assertEquals(currentThread.name, it.getString("name"))
assertEquals(currentThread.id, it.getLong("id"))
// stacktrace should come from the exception (check different length)
val serialisedTrace = it.getJSONArray("stacktrace")
assertEquals(expectedTrace.size, serialisedTrace.length())
expectedTrace.forEachIndexed { index, element ->
val jsonObject = serialisedTrace.getJSONObject(index)
assertEquals(element.lineNumber, jsonObject.getInt("lineNumber"))
}
}
}
private fun verifyCurrentThreadStructure(json: JSONArray,
currentThreadId: Long,
action: ((thread: JSONObject) -> Unit)? = null) {
var currentThreadCount = 0
for (k in 0 until json.length()) {
val thread = json[k] as JSONObject
val threadId = thread.getLong("id")
if (threadId == currentThreadId) {
assertTrue(thread.getBoolean("errorReportingThread"))
currentThreadCount++
action?.invoke(thread)
} else {
assertFalse(thread.has("errorReportingThread"))
}
}
assertEquals("Expected one error reporting thread", 1, currentThreadCount)
}
}
| 0
|
Java
|
0
| 1
|
8f490e66a287d0b55a3c114f7c3b7e45c5c4dcae
| 5,957
|
bugsnag-android
|
MIT License
|
src/test/kotlin/com/github/erosb/jsonsKema/ReadWriteContextTest.kt
|
erosb
| 314,666,360
| false
|
{"Kotlin": 262694}
|
package com.github.erosb.jsonsKema
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertNull
import org.junit.jupiter.api.Test
class ReadWriteContextTest {
@Test
fun `validation in write context fails on readonly prop`() {
val schema = SchemaLoader(JsonParser("""
{
"properties": {
"id": {
"type": "integer",
"readOnly": true
}
}
}
""")())()
val validator = Validator.create(schema, ValidatorConfig(
readWriteContext = ReadWriteContext.WRITE
))
val actual = validator.validate(JsonParser("""
{
"id": 3
}
""")())
println(actual?.toJSON())
assertEquals("read-only property \"id\" should not be present in write context", actual!!.message)
}
@Test
fun `validation in read context succeeds on readonly prop`() {
val schema = SchemaLoader(JsonParser("""
{
"properties": {
"id": {
"type": "integer",
"readOnly": true
}
}
}
""")())()
val validator = Validator.create(schema, ValidatorConfig(
readWriteContext = ReadWriteContext.READ
))
val actual = validator.validate(JsonParser("""
{
"id": 3
}
""")())
assertNull(actual)
}
@Test
fun `validation in read context fails on writeonly prop`() {
val schema = SchemaLoader(JsonParser("""
{
"properties": {
"id": {
"type": "integer",
"writeOnly": true
}
}
}
""")())()
val validator = Validator.create(schema, ValidatorConfig(
readWriteContext = ReadWriteContext.READ
))
val actual = validator.validate(JsonParser("""
{
"id": 3
}
""")())
println(actual?.toJSON())
assertEquals("write-only property \"id\" should not be present in read context", actual!!.message)
}
@Test
fun `validation in write context succeeds on writeonly prop`() {
val schema = SchemaLoader(JsonParser("""
{
"properties": {
"id": {
"type": "integer",
"writeOnly": true
}
}
}
""")())()
val validator = Validator.create(schema, ValidatorConfig(
readWriteContext = ReadWriteContext.WRITE
))
val actual = validator.validate(JsonParser("""
{
"id": 3
}
""")())
assertNull(actual)
}
@Test
fun `readOnly false does not impact validation`() {
val schema = SchemaLoader(JsonParser("""
{
"properties": {
"id": {
"type": "integer",
"readOnly": false
}
}
}
""")())()
val validator = Validator.create(schema, ValidatorConfig(
readWriteContext = ReadWriteContext.WRITE
))
val actual = validator.validate(JsonParser("""
{
"id": 3
}
""")())
assertNull(actual)
}
@Test
fun `writeOnly false does not impact validation`() {
val schema = SchemaLoader(JsonParser("""
{
"properties": {
"id": {
"type": "integer",
"writeOnly": false
}
}
}
""")())()
val validator = Validator.create(schema, ValidatorConfig(
readWriteContext = ReadWriteContext.READ
))
val actual = validator.validate(JsonParser("""
{
"id": 3
}
""")())
assertNull(actual)
}
@Test
fun `readOnly and writeOnly does not impact NONE context`() {
val schema = SchemaLoader(JsonParser("""
{
"properties": {
"id": {
"type": "integer",
"writeOnly": true
},
"name": {
"readOnly": true
}
}
}
""")())()
val validator = Validator.forSchema(schema)
val actual = validator.validate(JsonParser("""
{
"id": 3, "name": "asd"
}
""")())
assertNull(actual)
}
}
| 19
|
Kotlin
|
8
| 49
|
26060fbad7917fc05d58b21184cba45ef97b53ba
| 4,939
|
json-sKema
|
MIT License
|
example/kotlin/save-command-kt/src/test/kotlin/org/babyfish/jimmer/example/save/TriggerTest.kt
|
babyfish-ct
| 488,154,823
| false
| null |
package org.babyfish.jimmer.example.save
import org.babyfish.jimmer.example.save.common.AbstractMutationWithTriggerTest
import org.babyfish.jimmer.example.save.model.BookStore
import org.babyfish.jimmer.example.save.model.addBy
import org.babyfish.jimmer.example.save.model.by
import org.babyfish.jimmer.kt.new
import org.junit.jupiter.api.Test
import java.math.BigDecimal
/**
* Recommended learning sequence: 7
*
*
* SaveModeTest -> IncompleteObjectTest -> ManyToOneTest ->
* OneToManyTest -> ManyToManyTest -> RecursiveTest -> [Current: TriggerTest]
*/
class TriggerTest : AbstractMutationWithTriggerTest() {
@Test
fun test() {
jdbc("insert into book_store(name) values(?)", "MANNING")
jdbc(
"insert into book(name, edition, price, store_id) values" +
"(?, ?, ?, ?)," +
"(?, ?, ?, ?)",
"Microservices Security in Action", 1, BigDecimal("33.59"), 1L,
"LINQ in Action", 1, BigDecimal("21.59"), 1L
)
jdbc(
("insert into author(first_name, last_name, gender) values" +
"(?, ?, ?), (?, ?, ?)," +
"(?, ?, ?), (?, ?, ?), (?, ?, ?)"),
"Prabath", "Siriwardena", "M",
"Nuwan", "Dias", "M",
"Fabrice", "Marguerie", "M",
"Steve", "Eichert", "M",
"Jim", "Wooley", "M"
)
jdbc(
("insert into book_author_mapping(book_id, author_id) values" +
"(?, ?), (?, ?), " +
"(?, ?), (?, ?), (?, ?)"),
10L, 100L, 10L, 200L,
20L, 300L, 20L, 400L, 20L, 500L
)
sql
.entities
.save(
new(BookStore::class).by {
name = "TURING"
books().addBy {
name = "Microservices Security in Action"
edition = 1
price = BigDecimal("43.59")
authors().addBy {
id = 100L
}
authors().addBy {
id = 200L
}
authors().addBy {
id = 300L
}
}
books().addBy {
name = "LINQ in Action"
edition = 1
price = BigDecimal("31.59")
authors().addBy {
id = 400L
}
authors().addBy {
id = 500L
}
}
}
) {
/*
* If you use jimmer-spring-starter, it is unnecessary to
* do it because this switch is turned on.
*/
setAutoAttachingAll()
}
/*
* This example focuses on triggers, so we don't assert SQL statements,
* but directly assert events
*/
assertEvents(
"The entity \"org.babyfish.jimmer.example.save.model.BookStore\" is changed, " +
"old: null, " +
"new: {\"id\":2,\"name\":\"TURING\"}",
"The entity \"org.babyfish.jimmer.example.save.model.Book\" is changed, " +
"old: {\"id\":10,\"name\":\"Microservices Security in Action\",\"edition\":1,\"price\":33.59,\"store\":{\"id\":1}}, " +
"new: {\"id\":10,\"name\":\"Microservices Security in Action\",\"edition\":1,\"price\":43.59,\"store\":{\"id\":2}}",
"The association \"org.babyfish.jimmer.example.save.model.Book.store\" is changed, " +
"source id: 10, " +
"detached target id: 1, " +
"attached target id: 2",
"The association \"org.babyfish.jimmer.example.save.model.BookStore.books\" is changed, " +
"source id: 1, " +
"detached target id: 10, " +
"attached target id: null",
"The association \"org.babyfish.jimmer.example.save.model.BookStore.books\" is changed, " +
"source id: 2, " +
"detached target id: null, " +
"attached target id: 10",
"The association \"org.babyfish.jimmer.example.save.model.Book.authors\" is changed, " +
"source id: 10, " +
"detached target id: null, " +
"attached target id: 300",
"The association \"org.babyfish.jimmer.example.save.model.Author.books\" is changed, " +
"source id: 300, " +
"detached target id: null, " +
"attached target id: 10",
"The entity \"org.babyfish.jimmer.example.save.model.Book\" is changed, " +
"old: {\"id\":20,\"name\":\"LINQ in Action\",\"edition\":1,\"price\":21.59,\"store\":{\"id\":1}}, " +
"new: {\"id\":20,\"name\":\"LINQ in Action\",\"edition\":1,\"price\":31.59,\"store\":{\"id\":2}}",
"The association \"org.babyfish.jimmer.example.save.model.Book.store\" is changed, " +
"source id: 20, " +
"detached target id: 1, " +
"attached target id: 2",
"The association \"org.babyfish.jimmer.example.save.model.BookStore.books\" is changed, " +
"source id: 1, " +
"detached target id: 20, " +
"attached target id: null",
"The association \"org.babyfish.jimmer.example.save.model.BookStore.books\" is changed, " +
"source id: 2, " +
"detached target id: null, " +
"attached target id: 20",
"The association \"org.babyfish.jimmer.example.save.model.Book.authors\" is changed, " +
"source id: 20, " +
"detached target id: 300, " +
"attached target id: null",
"The association \"org.babyfish.jimmer.example.save.model.Author.books\" is changed, " +
"source id: 300, " +
"detached target id: 20, " +
"attached target id: null"
)
}
}
| 12
| null |
66
| 569
|
59e868ed92902f4dd797b4974993f579682a5213
| 6,363
|
jimmer
|
Apache License 2.0
|
KotlinBasico/src/main/kotlin/ControleFluxoIF.kt
|
kbmbarreto
| 471,227,065
| false
| null |
fun main() {
var a = 10
var b = 5
var c = 0
// IF ELSE
if(a < b) else c = b
println("O valor de C é $c.")
// IF ELSE
c = if (a < b) a else b
println("O valor de C é $c")
// IF ELSE
var num = 0
var num1 = 1
if (num > num1) {
println("Num é maior que Num1.")
} else {
println("Num1 é maior que Num.")
}
}
| 0
|
Kotlin
|
0
| 0
|
4800e170fc0a1461b356f521e8d500cb75a706ee
| 382
|
EstudosKotlinAndroid
|
MIT License
|
lib_common/src/main/java/com/cmj/wanandroid/common/kt/Coroutine.kt
|
mikechenmj
| 590,477,705
| false
| null |
package com.cmj.wanandroid.kt
import com.cmj.wanandroid.base.log.LogMan
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext
private const val FATAL = "FATAL"
private const val COROUTINE_EXCEPTION = "CoroutineCatchFatal"
val coroutineExFatalHandler = CoroutineExceptionHandler { _, e ->
LogMan.e(FATAL, "coroutineExceptionHandler exception: ${LogMan.getStackTraceString(e)}")
throw e
}
val coroutineExceptionHandler = CoroutineExceptionHandler { _, e ->
LogMan.e(COROUTINE_EXCEPTION, "coroutineExceptionHandler exception: ${LogMan.getStackTraceString(e)}")
}
fun CoroutineScope.safeLaunch(context: CoroutineContext = EmptyCoroutineContext, block: suspend CoroutineScope.() -> Unit): Job {
return launch(context + coroutineExceptionHandler) {
block()
}
}
| 0
|
Kotlin
|
0
| 0
|
b6ba391b5925a5ebff3040575a813ce9e140cbd3
| 979
|
WanAndroid
|
Apache License 2.0
|
data/src/main/java/com/ericampire/android/androidstudycase/data/room/AnimatorDao.kt
|
eric-ampire
| 402,759,023
| false
|
{"Kotlin": 212488}
|
package com.ericampire.android.androidstudycase.data.room
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import com.ericampire.android.androidstudycase.domain.entity.Animator
import kotlinx.coroutines.flow.Flow
@Dao
interface AnimatorDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun save(animator: Animator)
@Query("SELECT * FROM Animator")
fun findAll(): Flow<List<Animator>>
}
| 0
|
Kotlin
|
4
| 26
|
5a5f87658071da4b64a6563db7ae59c7bf0fa497
| 481
|
lottiefiles-app
|
Apache License 2.0
|
app/src/main/java/me/rosuh/easywatermark/ui/widget/WaterMarkImageView.kt
|
rosuH
| 281,094,148
| false
| null |
package me.rosuh.easywatermark.ui.widget
import android.animation.Animator
import android.animation.ObjectAnimator
import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapShader
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Matrix
import android.graphics.Paint
import android.graphics.RectF
import android.graphics.Shader
import android.net.Uri
import android.os.Build
import android.text.Layout
import android.text.StaticLayout
import android.text.TextPaint
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import android.view.ScaleGestureDetector
import androidx.core.animation.doOnEnd
import androidx.core.graphics.withSave
import androidx.palette.graphics.Palette
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import me.rosuh.easywatermark.data.model.ImageInfo
import me.rosuh.easywatermark.data.model.WaterMark
import me.rosuh.easywatermark.data.repo.WaterMarkRepository
import me.rosuh.easywatermark.data.repo.WaterMarkRepository.Companion.DEFAULT_TEXT_SIZE
import me.rosuh.easywatermark.data.repo.WaterMarkRepository.Companion.MAX_TEXT_SIZE
import me.rosuh.easywatermark.data.repo.WaterMarkRepository.Companion.MIN_TEXT_SIZE
import me.rosuh.easywatermark.ui.widget.utils.WaterMarkShader
import me.rosuh.easywatermark.utils.bitmap.decodeSampledBitmapFromResource
import me.rosuh.easywatermark.utils.ktx.applyConfig
import java.util.concurrent.Executors
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.coroutines.CoroutineContext
import kotlin.math.abs
import kotlin.math.absoluteValue
import kotlin.math.cos
import kotlin.math.max
import kotlin.math.min
import kotlin.math.pow
import kotlin.math.sin
import kotlin.math.sqrt
class WaterMarkImageView : androidx.appcompat.widget.AppCompatImageView, CoroutineScope {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
context,
attrs,
defStyleAttr
)
override val coroutineContext: CoroutineContext
get() = Dispatchers.Main
@Volatile
private var curImageInfo: ImageInfo = ImageInfo(Uri.EMPTY)
private var decodedUri: Uri = Uri.EMPTY
@Volatile
private var localIconUri: Uri = Uri.EMPTY
@Volatile
private var iconBitmap: Bitmap? = null
private var enableWaterMark = AtomicBoolean(false)
val drawableBounds = RectF()
private var onBgReady: (palette: Palette) -> Unit = {}
private var onOffsetChanged: (info: ImageInfo) -> Unit = { _ -> }
private var onScaleEnd: (textSize: Float) -> Unit = { _ -> }
private var exceptionHandler: CoroutineExceptionHandler =
CoroutineExceptionHandler { _: CoroutineContext, throwable: Throwable ->
Log.e(
this::class.simpleName,
"Throw Exception in WaterMarkImageView ${throwable.message}"
)
throwable.printStackTrace()
generateBitmapJob?.cancel()
}
/**
* Using single thread to making all building bitmap working serially. Avoiding concurrency problem about [Bitmap.recycle].
* 使用额外的单线程上下文来避免 [buildIconBitmapShader] 方法因并发导致的问题。因为 Bitmap 需要适时回收。
*/
private val generateBitmapCoroutineCtx by lazy {
Executors.newSingleThreadExecutor().asCoroutineDispatcher()
}
private var generateBitmapJob: Job? = null
fun updateUri(init: Boolean, imageInfo: ImageInfo) {
config?.let {
applyNewConfig(init, it, imageInfo)
} ?: kotlin.run {
curImageInfo = imageInfo
}
}
var config: WaterMark? = null
set(value) {
if (field == value) {
return
}
field = value
if (curImageInfo.uri.toString().isBlank()) return
field?.let { applyNewConfig(false, it, curImageInfo) }
}
private val drawableAlphaAnimator by lazy {
ObjectAnimator.ofInt(0, 255).apply {
addUpdateListener {
val alpha = it.animatedValue as Int
this@WaterMarkImageView.drawable?.alpha = alpha
}
duration = ANIMATION_DURATION
}
}
private fun applyNewConfig(
isInit: Boolean,
newConfig: WaterMark,
imageInfo: ImageInfo,
) {
val uri = imageInfo.uri
// if (newConfig == config && uri == decodedUri && imageInfo == curImageInfo && isInit.not()) {
// return
// }
generateBitmapJob?.cancel()
generateBitmapJob = launch(exceptionHandler) {
// quick check is the same image
if (decodedUri != uri) {
// hide iv
this@WaterMarkImageView.drawable?.alpha = 0
drawableAlphaAnimator.cancel()
// decode with inSample
val decodeResult = decodeSampledBitmapFromResource(
context.contentResolver,
uri,
calculateDrawLimitWidth(
this@WaterMarkImageView.measuredWidth,
this@WaterMarkImageView.paddingStart
),
calculateDrawLimitHeight(
this@WaterMarkImageView.measuredHeight,
this@WaterMarkImageView.paddingTop
)
)
val bitmapValue = decodeResult.data
if (decodeResult.isFailure() || bitmapValue == null) {
return@launch
}
// setting the bitmap of image
val imageBitmap = bitmapValue.bitmap
// adjust bitmap via matrix
setImageBitmap(imageBitmap)
val matrix = adjustMatrix(
imageMatrix,
measuredWidth,
measuredHeight,
paddingLeft,
paddingTop,
imageBitmap.width,
imageBitmap.height
)
imageMatrix = matrix
// setting background color via Palette
applyBg(imageBitmap)
// animate to show
// when showing first bitmap we need to wait the imageview prepared.
if (isInit) {
enableWaterMark.set(false)
}
drawableAlphaAnimator.start()
if (isInit) {
invalidate()
delay(drawableAlphaAnimator.duration - 30)
enableWaterMark.set(true)
}
// collect the drawable of new image in ImageView
generateDrawableBounds()
// the scale factor which of real image and render bitmap
imageInfo.inSample = bitmapValue.inSample
curImageInfo = imageInfo
curImageInfo.width = drawableBounds.width().toInt()
curImageInfo.height = drawableBounds.height().toInt()
decodedUri = uri
}
curImageInfo = imageInfo
// apply new config to paint
textPaint.applyConfig(curImageInfo, newConfig)
layoutShader = when (newConfig.markMode) {
WaterMarkRepository.MarkMode.Text -> {
buildTextBitmapShader(
curImageInfo,
newConfig,
textPaint,
generateBitmapCoroutineCtx
)
}
WaterMarkRepository.MarkMode.Image -> {
if (iconBitmap == null
|| localIconUri != newConfig.iconUri
|| (iconBitmap!!.width != newConfig.textSize.toInt() && iconBitmap!!.height != newConfig.textSize.toInt())
) {
// if uri was changed, create a new bitmap
// Here would decode a inSampled bitmap, the max size was imageView's width and height
val iconBitmapRect = decodeSampledBitmapFromResource(
context.contentResolver,
newConfig.iconUri,
measuredWidth,
measuredHeight,
)
if (iconBitmapRect.isFailure() || iconBitmapRect.data == null) {
return@launch
}
iconBitmap = iconBitmapRect.data!!.bitmap
// and flagging the old one should be recycled
}
localIconUri = newConfig.iconUri
layoutPaint.shader = null
buildIconBitmapShader(
curImageInfo,
iconBitmap!!,
newConfig,
textPaint,
scale = false,
generateBitmapCoroutineCtx
)
}
}
postInvalidate()
}
}
private fun applyBg(imageBitmap: Bitmap?) {
launch {
generatePalette(imageBitmap)?.let { palette ->
setBackgroundColor(Color.TRANSPARENT)
this@WaterMarkImageView.onBgReady.invoke(palette)
}
}
}
private suspend fun generatePalette(imageBitmap: Bitmap?): Palette? =
withContext(Dispatchers.Default) {
return@withContext imageBitmap?.let { Palette.Builder(it).generate() }
}
private val textPaint: TextPaint by lazy {
TextPaint().applyConfig(curImageInfo, config)
}
private val layoutPaint: Paint by lazy {
Paint()
}
private var layoutShader: WaterMarkShader? = null
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
Log.i("onSizeChanged", "$w, $h, $oldh, $oldh")
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
if (config?.text.isNullOrEmpty()
|| decodedUri.toString().isEmpty()
|| layoutShader == null
|| drawableAlphaAnimator.isRunning
) {
return
}
layoutPaint.shader = layoutShader?.bitmapShader
canvas?.withSave {
if (config?.obtainTileMode() == Shader.TileMode.CLAMP) {
translate(
drawableBounds.left + curImageInfo.offsetX * drawableBounds.width(),
drawableBounds.top + curImageInfo.offsetY * drawableBounds.height()
)
drawRect(
0f,
0f,
(layoutShader?.width ?: 0).toFloat(),
(layoutShader?.height ?: 0).toFloat(),
layoutPaint
)
} else {
translate(drawableBounds.left, drawableBounds.top)
drawRect(
0f,
0f,
drawableBounds.right - drawableBounds.left,
drawableBounds.bottom - drawableBounds.top,
layoutPaint
)
}
}
}
private fun generateDrawableBounds() {
val bounds = drawableBounds
imageMatrix.mapRect(bounds, RectF(drawable.bounds))
bounds.set(
bounds.left + paddingLeft,
bounds.top + paddingTop,
bounds.right + paddingRight,
bounds.bottom + paddingBottom,
)
}
fun onBgReady(block: (palette: Palette) -> Unit) {
this.onBgReady = block
}
fun onOffsetChanged(block: (info: ImageInfo) -> Unit) {
this.onOffsetChanged = block
}
fun onScaleEnd(block: (textSize: Float) -> Unit) {
this.onScaleEnd = block
}
fun reset() {
curImageInfo = ImageInfo(Uri.EMPTY)
localIconUri = Uri.EMPTY
setImageBitmap(null)
setBackgroundColor(Color.TRANSPARENT)
decodedUri = Uri.EMPTY
}
private fun updateWaterMarkOffset(deltaX: Float, deltaY: Float): ImageInfo {
if (config?.obtainTileMode() != Shader.TileMode.CLAMP) {
return curImageInfo
}
val newOffsetX = (curImageInfo.offsetX + deltaX / drawableBounds.width())
val newOffsetY = (curImageInfo.offsetY + deltaY / drawableBounds.height())
curImageInfo = curImageInfo.copy(
offsetX = newOffsetX,
offsetY = newOffsetY
)
invalidate()
return curImageInfo
}
private var touchRect = RectF()
fun isOutOfDrawable(deltaX: Float, deltaY: Float): Boolean {
if (config?.obtainTileMode() != Shader.TileMode.CLAMP) {
return false
}
val newOffsetX = (curImageInfo.offsetX + deltaX / drawableBounds.width())
val newOffsetY = (curImageInfo.offsetY + deltaY / drawableBounds.height())
val newX = drawableBounds.left + newOffsetX * drawableBounds.width()
val newY = drawableBounds.top + newOffsetY * drawableBounds.height()
val bitmapWith = layoutShader?.width ?: 0
val bitmapHeight = layoutShader?.height ?: 0
touchRect.set(
newX,
newY,
newX + bitmapWith,
newY + bitmapHeight
)
Log.i(TAG, "isOutOfDrawable $touchRect, drawableBounds: $drawableBounds")
return touchRect.right < drawableBounds.left
|| touchRect.left > drawableBounds.right
|| touchRect.top > drawableBounds.bottom
|| touchRect.bottom < drawableBounds.top
}
fun isTouchWaterMark(event: MotionEvent): Boolean {
if (config?.obtainTileMode() != Shader.TileMode.CLAMP) {
return false
}
val shader = layoutShader ?: return false
val bounds = drawableBounds
val waterMarkX = bounds.left + curImageInfo.offsetX * bounds.width()
val waterMarkY = bounds.top + curImageInfo.offsetY * bounds.height()
return event.x > waterMarkX
&& event.x < waterMarkX + shader.width
&& event.y > waterMarkY
&& event.y < waterMarkY + shader.height
}
private var animator: Animator? = null
fun backToCenter(
post: (info: ImageInfo, x: Float, y: Float) -> Unit,
) {
animator?.cancel()
val curOffsetX = curImageInfo.offsetX
val curOffsetY = curImageInfo.offsetY
val centerOffsetX = ((drawableBounds.width() - (layoutShader?.width ?: 0)) / 2)
val centerOffsetY = ((drawableBounds.height() - (layoutShader?.height ?: 0)) / 2)
val centerOffsetXP = (centerOffsetX) / drawableBounds.width()
val centerOffsetYP = (centerOffsetY) / drawableBounds.height()
val info = curImageInfo.copy(
offsetX = centerOffsetXP,
offsetY = centerOffsetYP
)
curImageInfo = info
animator = ValueAnimator.ofFloat(0f, 1f).apply {
duration = 300
addUpdateListener {
val value = it.animatedValue as Float
val offsetX = curOffsetX + (centerOffsetXP - curOffsetX) * value
val offsetY = curOffsetY + (centerOffsetYP - curOffsetY) * value
curImageInfo = curImageInfo.copy(
offsetX = offsetX,
offsetY = offsetY
)
invalidate()
}
doOnEnd {
post(info, centerOffsetX, centerOffsetY)
}
start()
}
}
private var mScaleFactor = 1f
private val mScaleDetector by lazy {
ScaleGestureDetector(context, scaleListener)
}
private val scaleListener = object : ScaleGestureDetector.SimpleOnScaleGestureListener() {
override fun onScale(detector: ScaleGestureDetector): Boolean {
mScaleFactor *= detector.scaleFactor
mScaleFactor = mScaleFactor.coerceAtLeast(0.1f).coerceAtMost(5.0f)
// Don't let the object get too small or too large.
val textSize = (config?.textSize ?: DEFAULT_TEXT_SIZE) * if (mScaleFactor > 1f) {
((1 - mScaleFactor).absoluteValue * 0.1f + 1f)
} else {
1 - (1 - mScaleFactor).absoluteValue * 0.1f
}
if (textSize > MAX_TEXT_SIZE && mScaleFactor > 1f) {
Log.i(TAG, "onScale: $textSize, $mScaleFactor, to max")
return true
}
if (textSize < MIN_TEXT_SIZE && mScaleFactor < 1f) {
Log.i(TAG, "onScale: $textSize, $mScaleFactor, to min")
return true
}
Log.i(TAG, "onScale $mScaleFactor, textSize: ${config?.textSize} ==> $textSize")
config = config?.copy(textSize = textSize)
invalidate()
return true
}
override fun onScaleEnd(detector: ScaleGestureDetector) {
super.onScaleEnd(detector)
Log.i(TAG, "onScaleEnd $mScaleFactor")
val textSize = (config?.textSize ?: DEFAULT_TEXT_SIZE)
// config = config?.copy(textSize = textSize)
// mScaleFactor = 1f
this@WaterMarkImageView.onScaleEnd(textSize)
}
}
private var startX = 0f
private var startY = 0f
private var enableTouch = true
override fun onTouchEvent(event: MotionEvent): Boolean {
// Let the ScaleGestureDetector inspect all events.
Log.i(TAG, "onTouch $event")
if (enableTouch.not()) {
return false
}
// mScaleDetector.onTouchEvent(event)
// if (mScaleDetector.isInProgress) {
// return true
// }
if (isTouchWaterMark(event).not() || event.pointerCount > 1) {
return true
}
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> {
startX = event.x
startY = event.y
}
MotionEvent.ACTION_MOVE -> {
val endX = event.x
val endY = event.y
val deltaX = endX - startX
val deltaY = endY - startY
updateWaterMarkOffset(deltaX, deltaY)
this.startX = endX
this.startY = endY
}
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
val endX = event.x
val endY = event.y
val deltaX = endX - startX
val deltaY = endY - startY
if (isOutOfDrawable(deltaX, deltaY)) {
// disable touch
enableTouch = false
// begin back to center animation
backToCenter { info, x, y ->
this.startX = x
this.startY = y
enableTouch = true
onOffsetChanged(info)
}
} else {
this.startX = endX
this.startY = endY
onOffsetChanged(curImageInfo)
}
}
}
return true
}
companion object {
private const val TAG = "WatermarkImageView"
const val ANIMATION_DURATION = 450L
/**
* Very simple way to fit the image into the canvas
*/
fun adjustMatrix(
srcMatrix: Matrix,
viewWidth: Int,
viewHeight: Int,
paddingLeft: Int,
paddingTop: Int,
bitmapWidth: Int,
bitmapHeight: Int,
): Matrix {
Log.i(
TAG,
"width = $viewWidth, height = $viewHeight, bitmapWidth = $bitmapWidth, bitmapHeight = $bitmapHeight"
)
val matrix = Matrix(srcMatrix)
matrix.reset()
val canvasWidth = calculateDrawLimitWidth(viewWidth, paddingLeft).toFloat()
val canvasHeight = calculateDrawLimitHeight(viewHeight, paddingTop).toFloat()
val scaleX = canvasWidth / bitmapWidth
val scaleY = canvasHeight / bitmapHeight
val scale = min(scaleX, scaleY)
matrix.postScale(scale, scale)
matrix.postTranslate(
(canvasWidth - bitmapWidth * scale) / 2,
(canvasHeight - bitmapHeight * scale) / 2
)
return matrix
}
private fun adjustHorizonalGap(config: WaterMark, maxSize: Int): Int {
return (maxSize * ((config.hGap / 100f) + 1)).toInt()
}
private fun adjustVerticalGap(config: WaterMark, maxSize: Int): Int {
return (maxSize * ((config.vGap / 100f) + 1)).toInt()
}
private fun calculateMaxSize(w: Float, h: Float): Int {
return sqrt(w.pow(2) + h.pow(2)).toInt()
}
fun calculateDrawLimitWidth(w: Int, ps: Int) = (w - ps * 2)
fun calculateDrawLimitHeight(h: Int, pt: Int) = (h - pt * 2)
suspend fun buildIconBitmapShader(
imageInfo: ImageInfo,
srcBitmap: Bitmap,
config: WaterMark,
textPaint: Paint,
scale: Boolean,
coroutineContext: CoroutineContext,
): WaterMarkShader? = withContext(coroutineContext) {
if (srcBitmap.isRecycled) {
return@withContext null
}
val tileMode = config.obtainTileMode()
val showDebugRect = config.enableBounds
val rawWidth = srcBitmap.width.toFloat().coerceAtLeast(1f)
val rawHeight = srcBitmap.height.toFloat().coerceAtLeast(1f)
val maxSize = calculateMaxSize(rawHeight, rawWidth)
val finalWidth = adjustHorizonalGap(config, maxSize)
val finalHeight = adjustVerticalGap(config, maxSize)
// textSize represents scale ratio of icon.
val scaleRatio = if (scale) {
imageInfo.scaleX
} else {
1f
} * config.textSize / 14f
val targetBitmap = Bitmap.createBitmap(
(finalWidth * scaleRatio).toInt(),
(finalHeight * scaleRatio).toInt(),
Bitmap.Config.ARGB_8888
)
val canvas = Canvas(targetBitmap)
val scaleBitmap = Bitmap.createScaledBitmap(
srcBitmap,
(rawWidth * scaleRatio).toInt(), (rawHeight * scaleRatio).toInt(),
false
)!!
if (showDebugRect) {
val tmpPaint = Paint().apply {
color = Color.RED
strokeWidth = 1f
style = Paint.Style.STROKE
}
canvas.drawRect(0f, 0f, finalWidth * scaleRatio, finalHeight * scaleRatio, tmpPaint)
canvas.save()
}
canvas.rotate(
config.degree,
(finalWidth * scaleRatio / 2),
(finalHeight * scaleRatio / 2)
)
canvas.drawBitmap(
scaleBitmap,
(finalWidth * scaleRatio - scaleBitmap.width) / 2.toFloat(),
(finalHeight * scaleRatio - scaleBitmap.height) / 2.toFloat(),
textPaint
)
if (showDebugRect) {
canvas.restore()
}
val bitmapShader = BitmapShader(
targetBitmap,
tileMode,
tileMode
)
return@withContext WaterMarkShader(
bitmapShader,
targetBitmap.width,
targetBitmap.height
)
}
/**
* Generate bitmap shader from input text.
* Text watermark implemented by bitmap shader.
* Using [StaticLayout] to draw multi line text.
* @author <EMAIL>
*/
suspend fun buildTextBitmapShader(
imageInfo: ImageInfo,
config: WaterMark,
textPaint: TextPaint,
coroutineContext: CoroutineContext,
): WaterMarkShader? = withContext(coroutineContext) {
if (config.text.isBlank()) {
return@withContext null
}
val showDebugRect = config.enableBounds
var maxLineWidth = 0
val tileMode = config.obtainTileMode()
// calculate the max width of all lines
config.text.split("\n").forEach {
val startIndex = config.text.indexOf(it).coerceAtLeast(0)
val lineWidth = textPaint.measureText(
config.text,
startIndex,
(startIndex + it.length).coerceAtMost(config.text.length)
).toInt()
maxLineWidth = max(maxLineWidth, lineWidth)
}
val staticLayout =
StaticLayout.Builder.obtain(
config.text,
0,
config.text.length,
textPaint,
maxLineWidth
)
.setAlignment(Layout.Alignment.ALIGN_NORMAL)
.build()
val textWidth = staticLayout.width.toFloat().coerceAtLeast(1f)
val textHeight = staticLayout.height.toFloat().coerceAtLeast(1f)
val radians = Math.toRadians(
when (config.degree) {
in 0.0..90.0 -> config.degree.toDouble()
in 90.0..270.0 -> {
abs(180 - config.degree.toDouble())
}
else -> 360 - config.degree.toDouble()
}
)
// Generate tmp size from rotation degree, all degree have it's own size.
val fixWidth = textWidth * cos(radians) + textHeight * sin(radians)
val fixHeight = textWidth * sin(radians) + textHeight * cos(radians)
val finalWidth = adjustHorizonalGap(config, fixWidth.toInt())
val finalHeight = adjustVerticalGap(config, fixHeight.toInt())
val bitmap = Bitmap.createBitmap(finalWidth, finalHeight, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
if (showDebugRect) {
val tmpPaint = Paint().apply {
color = Color.RED
strokeWidth = 1f
style = Paint.Style.STROKE
}
canvas.drawRect(0f, 0f, finalWidth.toFloat(), finalHeight.toFloat(), tmpPaint)
canvas.save()
}
// rotate by user input
canvas.rotate(
config.degree,
(finalWidth / 2).toFloat(),
(finalHeight / 2).toFloat()
)
// draw text
canvas.withSave {
this.translate(
((finalWidth) / 2).toFloat(),
((finalHeight - staticLayout.getLineBottom(0) - staticLayout.getLineTop(0)) / 2).toFloat()
)
staticLayout.draw(canvas)
}
if (showDebugRect) {
canvas.restore()
}
val bitmapShader = BitmapShader(
bitmap,
tileMode,
tileMode
)
return@withContext WaterMarkShader(
bitmapShader,
bitmap.width,
bitmap.height
)
}
}
}
| 24
| null |
131
| 1,550
|
5f479829d5a5f8ad2ef5c1576674ae9dfac2b90b
| 28,147
|
EasyWatermark
|
MIT License
|
lib/src/test/kotlin/com/maltaisn/icondialog/StringNormalizeTest.kt
|
maltaisn
| 129,983,346
| false
| null |
/*
* Copyright 2019 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.maltaisn.icondialog
import org.junit.Test
import kotlin.test.assertEquals
internal class StringNormalizeTest {
@Test
fun `should remove whitespace`() {
assertEquals("ab", "a \t\n\rb".normalize())
}
@Test
fun `should put to lowercase`() {
assertEquals("abcdefghi", "AbCdEfGHI".normalize())
}
@Test
fun `should remove diacritics`() {
assertEquals("aei", "äéì".normalize())
}
@Test
fun `should keep digits`() {
assertEquals("0123456789", "0123456789".normalize())
}
@Test
fun `should flatten unicode`() {
assertEquals("1720", "⑰⑳".normalize())
}
@Test
fun `should keep cyrillic`() {
assertEquals("модульное", "Модульное".normalize())
}
}
| 1
| null |
15
| 111
|
c561f68bf302a94626631d1930b88f4faf45528c
| 1,368
|
icondialoglib
|
Apache License 2.0
|
schoolData/src/main/kotlin/com/intelligentbackpack/schooldata/api/CalendarApi.kt
|
IntelligentBackpack
| 629,745,884
| false
| null |
package com.intelligentbackpack.schooldata.api
import calendar.communication.BasicMessage
import calendar.communication.Lessons
import calendar.communication.Subjects
import calendar.communication.UserInformations
import okhttp3.RequestBody
import retrofit2.Call
import retrofit2.http.Body
import retrofit2.http.GET
import retrofit2.http.HTTP
import retrofit2.http.POST
import retrofit2.http.PUT
import retrofit2.http.Query
/**
* API for the calendar microservice.
*/
interface CalendarApi {
/**
* Gets all the years.
*
* @return the years as a [BasicMessage], field [BasicMessage.message2List] contains the years.
*/
@GET("/utility/getAllYears")
fun getYears(): Call<BasicMessage>
/**
* Gets all the subjects.
*
* @return the subjects as a [Subjects].
*/
@GET("/utility/getAllSubjects")
fun getSubjects(): Call<Subjects>
/**
* Gets all the lessons for a student.
*
* @param email the email of the student.
* @param year the year.
* @return the lessons as a [Lessons].
*/
@GET("/utility/lessons/Student")
fun getLessonsForStudent(@Query("email") email: String, @Query("year") year: String): Call<Lessons>
/**
* Gets all the lessons for a professor.
*
* @param email the email of the professor.
* @param year the year.
* @return the lessons as a [Lessons].
*/
@GET("/utility/lessons/Professor")
fun getLessonsForProfessor(@Query("email") email: String, @Query("year") year: String): Call<Lessons>
/**
* Gets the information of a professor.
*
* @param email the email of the professor.
* @param year the year.
* @return the informations as a [UserInformations].
*/
@GET("/utility/getProfessorInformations")
fun getProfessorInformation(@Query("email") email: String, @Query("year") year: String): Call<UserInformations>
/**
* Gets the information of a student.
*
* @param email the email of the student.
* @param year the year.
* @return the informations as a [UserInformations].
*/
@GET("/utility/getStudentInformations")
fun getStudentInformation(@Query("email") email: String, @Query("year") year: String): Call<UserInformations>
/**
* Gets the lessons for a class.
*
* @param email the email of the professor.
* @param year the year.
* @param schoolName the name of the school.
* @param schoolCity the city of the school.
* @return the lessons as a [Lessons].
*/
@GET("/utility/lessons")
fun getLessonsForClass(
@Query("email") email: String,
@Query("year") year: String,
@Query("istitutoNome") schoolName: String,
@Query("istitutoCitta") schoolCity: String,
): Call<Lessons>
/**
* Gets the class from a lesson.
*
* @param lesson the lesson.
* @return the class as a [BasicMessage], field [BasicMessage.message] contains the class.
*/
@POST("/utility/getClass_ByLesson/")
fun getClassByLesson(@Body lesson: RequestBody): Call<BasicMessage>
/**
* Gets the books for a lesson.
*
* @param lessons the lessons.
* @return the books as a [BasicMessage], field [BasicMessage.message2List] contains the books.
*/
@POST("/utility/booksforLesson/")
fun getBooksForLesson(@Body lessons: RequestBody): Call<BasicMessage>
/**
* Creates a reminder for a lesson.
*
* @param remainderForLesson the reminder.
* @return the result as a [BasicMessage].
*/
@PUT("/create/bookForLesson/")
fun createReminderForLesson(@Body remainderForLesson: RequestBody): Call<BasicMessage>
/**
* Deletes a reminder for a lesson.
*
* @param remainderForLesson the reminder.
* @return the result as a [BasicMessage].
*/
@HTTP(method = "DELETE", path = "/remove/bookForLesson", hasBody = true)
fun deleteReminderForLesson(@Body remainderForLesson: RequestBody): Call<BasicMessage>
/**
* Modifies a reminder for a lesson, its period of validity.
*
* @param remainderForLesson the object containing the reminder and the new period of validity.
* @return the result as a [BasicMessage].
*/
@POST("/modify/bookForTimePeriod/")
fun modifyReminderForLesson(@Body remainderForLesson: RequestBody): Call<BasicMessage>
}
| 3
|
Kotlin
|
1
| 0
|
61bfdc8c21801a14d67c62b69a07a0fb341aab6d
| 4,396
|
IntelligentBackpackApp
|
MIT License
|
promptkt/src/main/kotlin/tri/util/Utils.kt
|
aplpolaris
| 663,584,917
| false
| null |
/*-
* #%L
* promptkt-0.1.0-SNAPSHOT
* %%
* Copyright (C) 2023 Johns Hopkins University Applied Physics Laboratory
* %%
* 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.
* #L%
*/
package tri.util
val ANSI_RESET = "\u001B[0m"
val ANSI_RED = "\u001B[31m"
val ANSI_YELLOW = "\u001B[33m"
val ANSI_GREEN = "\u001B[32m"
val ANSI_CYAN = "\u001B[36m"
val ANSI_GRAY = "\u001B[37m"
fun <X> String?.ifNotBlank(op: (String) -> X): X? =
if (isNullOrBlank()) {
null
} else {
op(this)
}
| 20
| null |
0
| 8
|
be010bc7e1b303852280b3a503e3ab03a60888d2
| 1,016
|
promptfx
|
Apache License 2.0
|
promptkt/src/main/kotlin/tri/util/Utils.kt
|
aplpolaris
| 663,584,917
| false
| null |
/*-
* #%L
* promptkt-0.1.0-SNAPSHOT
* %%
* Copyright (C) 2023 Johns Hopkins University Applied Physics Laboratory
* %%
* 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.
* #L%
*/
package tri.util
val ANSI_RESET = "\u001B[0m"
val ANSI_RED = "\u001B[31m"
val ANSI_YELLOW = "\u001B[33m"
val ANSI_GREEN = "\u001B[32m"
val ANSI_CYAN = "\u001B[36m"
val ANSI_GRAY = "\u001B[37m"
fun <X> String?.ifNotBlank(op: (String) -> X): X? =
if (isNullOrBlank()) {
null
} else {
op(this)
}
| 20
| null |
0
| 8
|
be010bc7e1b303852280b3a503e3ab03a60888d2
| 1,016
|
promptfx
|
Apache License 2.0
|
app/src/main/java/com/jetpackcompose/playground/compose_game_bench/domain/util/RayCastMathUtils.kt
|
StefanWyszynski
| 765,607,090
| false
|
{"Kotlin": 183920}
|
package com.jetpackcompose.playground.compose_game_bench.domain.util
import androidx.core.math.MathUtils
object RayCastMathUtils {
fun calculateColorIntensityByDistance(distance: Double, maxViewDistance: Double): Int {
val wallMaxFactpr = 1.0 - MathUtils.clamp(distance / maxViewDistance, 0.0, 1.0)
val colorIntensity = lerp(0.0, 255.0, wallMaxFactpr).toInt()
return colorIntensity
}
fun lerp(start: Double, stop: Double, amount: Double): Double {
return (1.0 - amount) * start + amount * stop
}
}
| 0
|
Kotlin
|
0
| 0
|
d573b5b30cd286a99df564c16ec97d1f61c16eed
| 549
|
2024_JetpackComposePlayground
|
MIT License
|
app/src/main/java/com/sheryv/tubegripper/ui/Logger.kt
|
Sheryv
| 137,062,786
| false
|
{"Kotlin": 49093, "HTML": 7662}
|
package com.sheryv.tubegripper.ui
import android.app.Activity
import android.app.Application
import android.util.Log
import android.view.View
import java.lang.ref.WeakReference
class Logger {
private val listener: WeakReference<OnMsgReceived?>
private val app: WeakReference<Application>
private val startTime: Long = System.currentTimeMillis()
public val minLogLevel: LogLevel
constructor(application: Application, listener: OnMsgReceived? = null) {
this.listener = WeakReference(listener)
app = WeakReference(application)
this.minLogLevel = LogLevel.DEBUG
}
fun d(s: String, sender: Any? = null, offset: Int = 0) {
if (LogLevel.DEBUG.moreVerbose(minLogLevel)) {
val id = sender(sender, offset)
Log.d(String.format("> %.1f | %s== =>", getSecFromStart(), id), logging(s, null))
}
}
fun i(s: String, sender: Any? = null, offset: Int = 0) {
if (LogLevel.INFO.moreVerbose(minLogLevel)) {
val id = sender(sender, offset)
Log.i(String.format("> %.1f | %s** =>", getSecFromStart(), id), logging(s, null))
}
}
fun w(s: String, sender: Any? = null, offset: Int = 0) {
if (LogLevel.WARN.moreVerbose(minLogLevel)) {
val id = sender(sender, offset)
Log.w(String.format("> %.1f | %s@@ =>", getSecFromStart(), id), logging(s, null))
}
}
fun e(s: String, t: Exception?, sender: Any?, offset: Int) {
if (LogLevel.ERROR.moreVerbose(minLogLevel)) {
var st: String? = null
val id = sender(sender, offset)
if (t == null) {
Log.e(String.format("> %.1f | %s## =>", getSecFromStart(), id), logging(s, null))
} else {
Log.e(String.format("> %.1f | %s## =>", getSecFromStart(), id), logging(s, t), t)
// Log.e("> - | ########## =>",t.getMessage());
st = t.message
for (tr in t.stackTrace) {
st += "\n" + tr.toString()
}
Log.e("> ## =>", st)
}
}
}
private fun logging(s: String, t: Throwable?): String {
return s
}
private fun sender(sender: Any?, offset: Int): String {
if (sender != null){
var s:String
if (sender is Class<*>){
s=sender.simpleName
}else
{
s=sender::class.java.simpleName
}
return "$s[$offset]"
}
return ""
}
/**
* Show snackbar for long time with msg
*
* @param m message
* @param v view of caller
*/
fun msgl(m: String, v: View) {
listener.get()?.onMsgLongRec(m, v)
}
/**
* Show snackbar for short time with msg
*
* @param m message
* @param v view of caller
*/
fun msg(m: String, v: View) {
listener.get()?.onMsgShortRec(m, v)
}
/**
* Show toast for short time with msg
*
* @param m message
*/
fun t(m: String) {
listener.get()?.onToastShortRec(m, app.get())
}
/**
* Show toast for long time with msg
*
* @param m message
*/
fun tl(m: String) {
listener.get()?.onToastLongRec(m, app.get())
}
/**
* Change status
*
* @param m message
* @param activity activity
*/
fun st(m: String, activity: Activity) {
listener.get()?.onStatusChange(m, activity)
}
private fun getSecFromStart(): Float {
return (System.currentTimeMillis() - startTime) / 100 / 10.0f
}
interface OnMsgReceived {
fun onTgLogReceived(msg: String, t: Throwable?, application: Application?)
fun onMsgLongRec(msg: String, v: View)
fun onMsgShortRec(msg: String, v: View)
fun onToastShortRec(msg: String, application: Application?)
fun onToastLongRec(msg: String, application: Application?)
fun onStatusChange(msg: String, activity: Activity)
/*
static void msgl(String m)
{
Snackbar.make(null,m, Snackbar.LENGTH_LONG)
.setAction("MessageL", null).show();
}
static void msg(String m, View v)
{
Snackbar.make(v,m, Snackbar.LENGTH_SHORT)
.setAction("MessageS", null).show();
}
static void t(String m)
{
Toast.makeText(getApp(), m,
Toast.LENGTH_SHORT).show();
}
* */
}
enum class LogLevel(private val level: Int) {
DEBUG(1),
INFO(2),
WARN(4),
DISABLED(128),
ERROR(8);
fun moreVerbose(log: LogLevel): Boolean {
return log.level <= level
}
}
}
| 0
|
Kotlin
|
0
| 0
|
c801afc94d8f5554b54b45c3bec35af8e60381c9
| 4,903
|
TubeGripper
|
Apache License 2.0
|
app/src/main/java/com/sheryv/tubegripper/ui/Logger.kt
|
Sheryv
| 137,062,786
| false
|
{"Kotlin": 49093, "HTML": 7662}
|
package com.sheryv.tubegripper.ui
import android.app.Activity
import android.app.Application
import android.util.Log
import android.view.View
import java.lang.ref.WeakReference
class Logger {
private val listener: WeakReference<OnMsgReceived?>
private val app: WeakReference<Application>
private val startTime: Long = System.currentTimeMillis()
public val minLogLevel: LogLevel
constructor(application: Application, listener: OnMsgReceived? = null) {
this.listener = WeakReference(listener)
app = WeakReference(application)
this.minLogLevel = LogLevel.DEBUG
}
fun d(s: String, sender: Any? = null, offset: Int = 0) {
if (LogLevel.DEBUG.moreVerbose(minLogLevel)) {
val id = sender(sender, offset)
Log.d(String.format("> %.1f | %s== =>", getSecFromStart(), id), logging(s, null))
}
}
fun i(s: String, sender: Any? = null, offset: Int = 0) {
if (LogLevel.INFO.moreVerbose(minLogLevel)) {
val id = sender(sender, offset)
Log.i(String.format("> %.1f | %s** =>", getSecFromStart(), id), logging(s, null))
}
}
fun w(s: String, sender: Any? = null, offset: Int = 0) {
if (LogLevel.WARN.moreVerbose(minLogLevel)) {
val id = sender(sender, offset)
Log.w(String.format("> %.1f | %s@@ =>", getSecFromStart(), id), logging(s, null))
}
}
fun e(s: String, t: Exception?, sender: Any?, offset: Int) {
if (LogLevel.ERROR.moreVerbose(minLogLevel)) {
var st: String? = null
val id = sender(sender, offset)
if (t == null) {
Log.e(String.format("> %.1f | %s## =>", getSecFromStart(), id), logging(s, null))
} else {
Log.e(String.format("> %.1f | %s## =>", getSecFromStart(), id), logging(s, t), t)
// Log.e("> - | ########## =>",t.getMessage());
st = t.message
for (tr in t.stackTrace) {
st += "\n" + tr.toString()
}
Log.e("> ## =>", st)
}
}
}
private fun logging(s: String, t: Throwable?): String {
return s
}
private fun sender(sender: Any?, offset: Int): String {
if (sender != null){
var s:String
if (sender is Class<*>){
s=sender.simpleName
}else
{
s=sender::class.java.simpleName
}
return "$s[$offset]"
}
return ""
}
/**
* Show snackbar for long time with msg
*
* @param m message
* @param v view of caller
*/
fun msgl(m: String, v: View) {
listener.get()?.onMsgLongRec(m, v)
}
/**
* Show snackbar for short time with msg
*
* @param m message
* @param v view of caller
*/
fun msg(m: String, v: View) {
listener.get()?.onMsgShortRec(m, v)
}
/**
* Show toast for short time with msg
*
* @param m message
*/
fun t(m: String) {
listener.get()?.onToastShortRec(m, app.get())
}
/**
* Show toast for long time with msg
*
* @param m message
*/
fun tl(m: String) {
listener.get()?.onToastLongRec(m, app.get())
}
/**
* Change status
*
* @param m message
* @param activity activity
*/
fun st(m: String, activity: Activity) {
listener.get()?.onStatusChange(m, activity)
}
private fun getSecFromStart(): Float {
return (System.currentTimeMillis() - startTime) / 100 / 10.0f
}
interface OnMsgReceived {
fun onTgLogReceived(msg: String, t: Throwable?, application: Application?)
fun onMsgLongRec(msg: String, v: View)
fun onMsgShortRec(msg: String, v: View)
fun onToastShortRec(msg: String, application: Application?)
fun onToastLongRec(msg: String, application: Application?)
fun onStatusChange(msg: String, activity: Activity)
/*
static void msgl(String m)
{
Snackbar.make(null,m, Snackbar.LENGTH_LONG)
.setAction("MessageL", null).show();
}
static void msg(String m, View v)
{
Snackbar.make(v,m, Snackbar.LENGTH_SHORT)
.setAction("MessageS", null).show();
}
static void t(String m)
{
Toast.makeText(getApp(), m,
Toast.LENGTH_SHORT).show();
}
* */
}
enum class LogLevel(private val level: Int) {
DEBUG(1),
INFO(2),
WARN(4),
DISABLED(128),
ERROR(8);
fun moreVerbose(log: LogLevel): Boolean {
return log.level <= level
}
}
}
| 0
|
Kotlin
|
0
| 0
|
c801afc94d8f5554b54b45c3bec35af8e60381c9
| 4,903
|
TubeGripper
|
Apache License 2.0
|
base_android/src/androidMain/kotlin/siarhei/luskanau/iot/doorbell/data/AndroidThisDeviceRepository.kt
|
siarhei-luskanau
| 79,257,367
| false
| null |
package siarhei.luskanau.iot.doorbell.data
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import androidx.core.content.ContextCompat
import siarhei.luskanau.iot.doorbell.common.AppConstants
import siarhei.luskanau.iot.doorbell.common.DeviceInfoProvider
import siarhei.luskanau.iot.doorbell.common.IpAddressProvider
import siarhei.luskanau.iot.doorbell.data.model.DoorbellData
import siarhei.luskanau.iot.doorbell.data.repository.CameraRepository
import siarhei.luskanau.iot.doorbell.data.repository.ThisDeviceRepository
import timber.log.Timber
class AndroidThisDeviceRepository(
private val context: Context,
private val deviceInfoProvider: DeviceInfoProvider,
private val cameraRepository: CameraRepository,
private val ipAddressProvider: IpAddressProvider
) : ThisDeviceRepository {
override fun isEmulator(): Boolean =
Build.FINGERPRINT.contains("generic")
private val doorbellData = DoorbellData(
deviceInfoProvider.buildDoorbellId(),
deviceInfoProvider.buildDeviceName(),
deviceInfoProvider.buildDeviceInfo()
)
override suspend fun doorbellId() =
deviceInfoProvider.buildDoorbellId()
override suspend fun doorbellData() =
doorbellData
override suspend fun getCamerasList() =
cameraRepository.getCamerasList()
override suspend fun getIpAddressList() =
ipAddressProvider.getIpAddressList()
override fun reboot() {
runCatching {
Timber.d("reboot")
Runtime.getRuntime().exec("reboot")
}.onFailure {
Timber.e(it)
}
}
override fun isPermissionsGranted(): Boolean {
for (permission in AppConstants.PERMISSIONS) {
if (ContextCompat.checkSelfPermission(
context,
permission
) != PackageManager.PERMISSION_GRANTED
) {
return false
}
}
return true
}
}
| 0
| null |
0
| 2
|
0e4dd38c61feee92a688eda968ba06c64ef3a95c
| 2,022
|
android-iot-doorbell
|
MIT License
|
walletlibrary/src/main/java/com/microsoft/did/sdk/util/log/DefaultLogConsumer.kt
|
microsoft
| 567,422,889
| false
| null |
// Copyright (c) Microsoft Corporation. All rights reserved
package com.microsoft.did.sdk.util.log
import android.util.Log
internal class DefaultLogConsumer : SdkLog.Consumer {
override fun log(logLevel: SdkLog.Level, message: String, throwable: Throwable?, tag: String) {
if (throwable == null) {
Log.println(getAndroidLogLevel(logLevel), tag, message)
} else {
Log.println(getAndroidLogLevel(logLevel), tag, message + "\n" + Log.getStackTraceString(throwable))
}
}
override fun event(name: String, properties: Map<String, String>?) {
val sb = StringBuilder()
properties?.forEach {
sb.append("${it.key}: ${it.value}\n")
}
Log.i(name, sb.toString())
}
private fun getAndroidLogLevel(logLevel: SdkLog.Level): Int {
return logLevel.severity() + 2
}
}
| 5
| null |
8
| 9
|
5978f33741ddf4dcd51533552487eaeb81ee6e75
| 878
|
entra-verifiedid-wallet-library-android
|
MIT License
|
graphql-dgs-subscriptions-websockets-autoconfigure/src/main/kotlin/com/netflix/graphql/dgs/subscriptions/websockets/DgsWebSocketAutoConfig.kt
|
Netflix
| 317,375,887
| false
| null |
/*
* Copyright 2020 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.graphql.dgs.subscriptions.websockets
import com.netflix.graphql.dgs.DgsQueryExecutor
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication
import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.web.socket.WebSocketHandler
import org.springframework.web.socket.config.annotation.EnableWebSocket
import org.springframework.web.socket.config.annotation.WebSocketConfigurer
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry
import org.springframework.web.socket.server.HandshakeInterceptor
import org.springframework.web.socket.server.support.DefaultHandshakeHandler
@Configuration
@ConditionalOnWebApplication
@EnableConfigurationProperties(DgsWebSocketConfigurationProperties::class)
open class DgsWebSocketAutoConfig {
@Bean
open fun webSocketHandler(@Suppress("SpringJavaInjectionPointsAutowiringInspection") dgsQueryExecutor: DgsQueryExecutor): WebSocketHandler {
return DgsWebSocketHandler(dgsQueryExecutor)
}
@Configuration
@EnableWebSocket
internal open class WebSocketConfig(
@Suppress("SpringJavaInjectionPointsAutowiringInspection") private val webSocketHandler: WebSocketHandler,
private val handshakeInterceptor: HandshakeInterceptor,
private val configProps: DgsWebSocketConfigurationProperties
) : WebSocketConfigurer {
override fun registerWebSocketHandlers(registry: WebSocketHandlerRegistry) {
val handshakeHandler = DefaultHandshakeHandler()
registry.addHandler(webSocketHandler, configProps.path).setHandshakeHandler(handshakeHandler)
.addInterceptors(handshakeInterceptor)
.setAllowedOrigins("*")
}
}
@Bean
open fun handshakeInterceptor(): HandshakeInterceptor {
return DgsHandshakeInterceptor()
}
}
| 88
| null |
289
| 3,037
|
bd2d0c524e70a9d1d625d518a94926c7b53a7e7c
| 2,620
|
dgs-framework
|
Apache License 2.0
|
app/src/main/java/com/example/shoestoreinventory/utils/Utils.kt
|
PackHg
| 328,856,748
| false
| null |
package com.example.shoestoreinventory.utils
import android.app.Activity
import android.content.Context
import android.view.View
import android.view.inputmethod.InputMethodManager
import androidx.fragment.app.Fragment
object Utils {
/**
* The following utility functions for hiding the keyboard are by Gunham in:
* https://stackoverflow.com/questions/41790357/close-hide-the-android-soft-keyboard-with-kotlin
*/
fun Fragment.hideKeyboard() {
view?.let { activity?.hideKeyboard(it) }
}
fun Activity.hideKeyboard() {
hideKeyboard(currentFocus ?: View(this))
}
fun Context.hideKeyboard(view: View) {
val inputMethodManager = getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.hideSoftInputFromWindow(view.windowToken, 0)
}
}
| 0
|
Kotlin
|
0
| 0
|
26a4ccf80153e5c04b21ca7f6ea52245a9d6c30c
| 838
|
Udacity-ShoeStoreInventory
|
Apache License 2.0
|
Froom-Backend/src/main/kotlin/com/froom/util/retrofit/category/CategoryAPI.kt
|
Damian2057
| 715,183,107
| false
|
{"Kotlin": 59970, "Python": 9937, "Dockerfile": 2266}
|
package com.froom.util.retrofit.category
import com.froom.util.retrofit.category.model.CategoryResponseDto
import okhttp3.MultipartBody
import org.springframework.stereotype.Component
import retrofit2.Call
import retrofit2.http.Multipart
import retrofit2.http.POST
import retrofit2.http.Part
@Component
interface CategoryAPI {
@Multipart
@POST("/predict")
fun predict(@Part file: MultipartBody.Part): Call<CategoryResponseDto>
}
| 0
|
Kotlin
|
0
| 0
|
fe8fc93b5cf5ea28a2572cf467374e58f993be37
| 443
|
Froom
|
Apache License 2.0
|
app/src/main/java/com/edricchan/studybuddy/ui/modules/task/ViewTaskActivity.kt
|
Animesh-Barai
| 258,812,917
| true
|
{"Kotlin": 539305, "Ruby": 202}
|
package com.edricchan.studybuddy.ui.modules.task
import android.os.Bundle
import android.util.Log
import android.view.MenuItem
import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.annotation.StringRes
import androidx.appcompat.app.AppCompatActivity
import com.edricchan.studybuddy.R
import com.edricchan.studybuddy.extensions.TAG
import com.edricchan.studybuddy.extensions.firebase.toDateFormat
import com.edricchan.studybuddy.extensions.startActivity
import com.edricchan.studybuddy.interfaces.TodoItem
import com.edricchan.studybuddy.ui.modules.auth.LoginActivity
import com.edricchan.studybuddy.ui.modules.auth.RegisterActivity
import com.edricchan.studybuddy.ui.modules.task.utils.TodoUtils
import com.google.android.material.chip.Chip
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.snackbar.BaseTransientBottomBar.Duration
import com.google.android.material.snackbar.Snackbar
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import com.google.firebase.firestore.DocumentReference
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.ktx.firestore
import com.google.firebase.firestore.ktx.toObject
import com.google.firebase.ktx.Firebase
import kotlinx.android.synthetic.main.activity_view_task.*
import io.noties.markwon.Markwon
import io.noties.markwon.ext.strikethrough.StrikethroughPlugin
import io.noties.markwon.ext.tasklist.TaskListPlugin
import io.noties.markwon.image.glide.GlideImagesPlugin
import io.noties.markwon.linkify.LinkifyPlugin
class ViewTaskActivity : AppCompatActivity(R.layout.activity_view_task) {
private lateinit var auth: FirebaseAuth
private lateinit var firestore: FirebaseFirestore
private lateinit var taskDocument: DocumentReference
private lateinit var taskId: String
private lateinit var todoUtils: TodoUtils
private var currentUser: FirebaseUser? = null
private var todoItem: TodoItem? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
firestore = Firebase.firestore
auth = FirebaseAuth.getInstance()
currentUser = auth.currentUser
todoUtils = TodoUtils.getInstance(auth, firestore)
taskId = intent.getStringExtra(EXTRA_TASK_ID) ?: ""
if (taskId.isEmpty()) {
Log.e(TAG, "No task ID was specified!")
Toast.makeText(
this, "An unknown error occurred while attempting to retrieve the" +
"task. Try again later.", Toast.LENGTH_LONG
).show()
finish()
} else {
taskDocument = todoUtils.getTask(taskId)
}
Log.d(TAG, "Task ID: $taskId")
bottomAppBar.replaceMenu(R.menu.menu_view_task)
if (todoItem?.archived == true) {
// Task has already been archived - show the unarchive menu item instead
bottomAppBar.menu.findItem(R.id.action_unarchive).isVisible = true
bottomAppBar.menu.findItem(R.id.action_archive).isVisible = false
}
bottomAppBar.setOnMenuItemClickListener {
return@setOnMenuItemClickListener when (it.itemId) {
android.R.id.home -> {
onBackPressed()
true
}
R.id.action_delete -> {
val builder = MaterialAlertDialogBuilder(this)
builder.setTitle("Delete todo?")
.setPositiveButton(R.string.dialog_action_ok) { _, _ ->
todoUtils.removeTask(taskId)
.addOnCompleteListener { task ->
if (task.isSuccessful) {
Toast.makeText(
this,
"Successfully deleted todo!",
Toast.LENGTH_SHORT
).show()
finish()
} else {
Toast.makeText(
this,
"An error occurred while deleting the todo. Try again later.",
Toast.LENGTH_LONG
).show()
Log.e(
TAG,
"An error occurred while deleting the todo.",
task.exception
)
}
}
}
.setNegativeButton(R.string.dialog_action_cancel) { dialog, _ -> dialog.dismiss() }
.show()
true
}
R.id.action_edit -> {
startActivity<EditTaskActivity> {
putExtra(EditTaskActivity.EXTRA_TASK_ID, taskId)
}
true
}
R.id.action_mark_as_done -> {
taskDocument
.update("done", !todoItem?.done!!)
.addOnCompleteListener { task ->
if (task.isSuccessful) {
showSnackbar(
"Successfully marked task as " +
if (!todoItem!!.done!!) "done" else "undone",
Snackbar.LENGTH_SHORT
)
Log.d(
TAG,
"Task marked as " + if (!todoItem!!.done!!) "done" else "undone"
)
} else {
showSnackbar(
"An error occurred while marking the todo as " +
if (!todoItem!!.done!!) "done" else "undone",
Snackbar.LENGTH_LONG
)
Log.e(
TAG,
"An error occurred while marking the todo as " +
if (!todoItem!!.done!!) "done" else "undone",
task.exception
)
}
}
true
}
R.id.action_archive -> {
// Variable to indicate whether task was already archived
val hasArchived = todoItem?.archived ?: false
Log.d(TAG, "Archived state: $hasArchived")
taskDocument
.update("archived", !hasArchived)
.addOnCompleteListener { task ->
if (task.isSuccessful) {
showSnackbar("Successfully archived task!", Snackbar.LENGTH_SHORT)
Log.d(TAG, "Successfully archived task!")
} else {
Toast.makeText(
this,
"An error occurred while attempting to archive the task",
Toast.LENGTH_SHORT
).show()
Log.e(
TAG,
"An error occurred while attempting to archive the task:",
task.exception
)
}
}
bottomAppBar.menu.findItem(R.id.action_unarchive).isVisible = true
bottomAppBar.menu.findItem(R.id.action_archive).isVisible = false
true
}
R.id.action_unarchive -> {
// Variable to indicate whether task was already archived
val hasArchived = todoItem?.archived ?: true
Log.d(TAG, "Archived state: $hasArchived")
taskDocument
.update("archived", !hasArchived)
.addOnCompleteListener { task ->
if (task.isSuccessful) {
showSnackbar("Successfully unarchived task!", Snackbar.LENGTH_SHORT)
Log.d(TAG, "Successfully unarchived task!")
} else {
Toast.makeText(
this,
"An error occurred while attempting to unarchive the task",
Toast.LENGTH_SHORT
).show()
Log.e(
TAG,
"An error occurred while attempting to unarchive the task:",
task.exception
)
}
}
bottomAppBar.menu.findItem(R.id.action_archive).isVisible = true
bottomAppBar.menu.findItem(R.id.action_unarchive).isVisible = false
return@setOnMenuItemClickListener true
}
else -> return@setOnMenuItemClickListener super.onOptionsItemSelected(it)
}
}
editTaskFab.setOnClickListener {
startActivity<EditTaskActivity> {
putExtra(EditTaskActivity.EXTRA_TASK_ID, taskId)
}
}
}
override fun onStart() {
super.onStart()
if (currentUser == null) {
Log.d(TAG, "Not logged in")
val signInDialogBuilder = MaterialAlertDialogBuilder(this)
signInDialogBuilder
.setTitle("Sign in")
.setMessage("To access the content, please login or register for an account.")
.setCancelable(false)
.setPositiveButton(R.string.dialog_action_login) { dialogInterface, _ ->
startActivity<LoginActivity>()
dialogInterface.dismiss()
}
.setNeutralButton(R.string.dialog_action_sign_up) { dialogInterface, _ ->
startActivity<RegisterActivity>()
dialogInterface.dismiss()
}
.setNegativeButton(R.string.dialog_action_cancel) { dialogInterface, _ ->
dialogInterface.cancel()
}
.show()
} else {
loadTask()
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
android.R.id.home -> {
onBackPressed()
true
}
else -> super.onOptionsItemSelected(item)
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
if (todoItem != null && todoItem?.title != null) {
outState.putString(TASK_TITLE_TAG, todoItem?.title)
}
}
override fun onRestoreInstanceState(savedInstanceState: Bundle) {
super.onRestoreInstanceState(savedInstanceState)
if (savedInstanceState.getString(TASK_TITLE_TAG) != null) {
title = savedInstanceState.getString(TASK_TITLE_TAG)
}
}
/**
* Loads the task that was supplied via `taskId`
*/
private fun loadTask() {
taskDocument
.addSnapshotListener { documentSnapshot, e ->
if (e != null) {
Log.e(TAG, "An error occurred while retrieving the task:", e)
showSnackbar(
R.string.view_task_unsuccessful_snackbar_text,
Snackbar.LENGTH_LONG
)
} else {
if (documentSnapshot != null && documentSnapshot.exists()) {
setViews(documentSnapshot.toObject<TodoItem>())
todoItem = documentSnapshot.toObject<TodoItem>()
Log.d(TAG, "Task item: $todoItem")
Log.d(TAG, "Document snapshot data: ${documentSnapshot.data}")
title = todoItem?.title
}
}
}
/*.addOnCompleteListener(task -> {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
mItem = document.toObject(TaskItem.class);
findViewById(R.id.progressBar).setVisibility(View.GONE);
findViewById(R.id.taskView).setVisibility(View.VISIBLE);
mTaskTitle.setText(mItem.title);
if (mItem.content != null) {
mTaskContent.setText(mItem.content);
}
} else {
// TODO: Add handler for document not existing
}
} else {
Snackbar.make(findViewById(R.id.mainView), R.string.view_task_unsuccessful_snackbar_text, Snackbar.LENGTH_INDEFINITE)
.setBehavior(new NoSwipeBehavior())
.setAction(R.string.view_task_unsuccessful_snackbar_btn_text, v -> loadTask());
}
});*/
}
/**
* Toggles the visiblity of a view to `visibility`
*
* @param view The view to toggle the visibility of
* @param initialVisibility The visibility to check against the view. Can be [View.GONE], [View.INVISIBLE] or [View.VISIBLE]
* @param visibility The visibility to toggle the view to. Can be [View.GONE], [View.INVISIBLE] or [View.VISIBLE]
*/
private fun toggleViewVisibility(view: View, initialVisibility: Int, visibility: Int) {
if (view.visibility == initialVisibility) {
view.visibility = visibility
}
}
/**
* Sets all of the [TextView] and [com.google.android.material.chip.ChipGroup] values
*
* @param item The task item
*/
private fun setViews(item: TodoItem?) {
if (item?.content != null) {
Markwon.builder(this)
.usePlugin(GlideImagesPlugin.create(this))
.usePlugin(LinkifyPlugin.create())
.usePlugin(StrikethroughPlugin.create())
.usePlugin(TaskListPlugin.create(this))
.build()
.setMarkdown(taskContent, item.content)
toggleViewVisibility(taskContent, View.GONE, View.VISIBLE)
} else {
toggleViewVisibility(taskContent, View.VISIBLE, View.GONE)
}
if (item?.dueDate != null) {
taskDate.text = item.dueDate.toDateFormat(getString(R.string.date_format_pattern))
toggleViewVisibility(taskDate, View.GONE, View.VISIBLE)
} else {
toggleViewVisibility(taskDate, View.VISIBLE, View.GONE)
}
if (item?.project != null) {
item.project
.get()
.addOnCompleteListener { task ->
if (task.isSuccessful && task.result != null && task.result!!.exists()) {
taskProject.text = task.result!!.getString("name")
} else {
Toast.makeText(
this,
"An error occurred while attempting to retrieve the project. Please try again later.",
Toast.LENGTH_SHORT
).show()
Log.e(
TAG,
"An error occurred while attempting to retrieve the project:",
task.exception
)
}
}
toggleViewVisibility(taskProject, View.GONE, View.VISIBLE)
} else {
toggleViewVisibility(taskProject, View.VISIBLE, View.GONE)
}
/*if (item?.title != null) {
taskTitle.text = item.title
toggleViewVisibility(taskTitle, View.GONE, View.VISIBLE)
} else {
toggleViewVisibility(taskTitle!!, View.VISIBLE, View.GONE)
}*/
if (item?.tags != null && item.tags.isNotEmpty()) {
// Remove all chips or this will cause duplicate tags
taskTags.removeAllViews()
for (tag in item.tags) {
val tempChip = Chip(this)
tempChip.text = tag
taskTags.addView(tempChip)
}
toggleViewVisibility(taskTagsParentView, View.GONE, View.VISIBLE)
} else {
toggleViewVisibility(taskTagsParentView, View.VISIBLE, View.GONE)
}
toggleViewVisibility(progressBar, View.VISIBLE, View.GONE)
toggleViewVisibility(scrollTaskView, View.GONE, View.VISIBLE)
}
private fun showSnackbar(text: String, @Duration duration: Int) {
Snackbar.make(mainView, text, duration)
.setAnchorView(editTaskFab)
.show()
}
private fun showSnackbar(@StringRes textRes: Int, @Duration duration: Int) {
showSnackbar(getString(textRes), duration)
}
companion object {
// Tag to be used for saving the task item's title
private const val TASK_TITLE_TAG = "taskTitle"
/** The extra tag for the task's ID. */
const val EXTRA_TASK_ID = "taskId"
}
}
| 0
| null |
0
| 0
|
61b1ba1a7ee46837ddba56d82e4fec3e70862c68
| 18,360
|
StudyBuddy-android
|
MIT License
|
beam-ui/src/jsMain/kotlin/dev/d1s/beam/ui/state/ObservableLauncher.kt
|
d1snin
| 632,895,652
| false
| null |
/*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.d1s.beam.ui.state
import kotlinx.coroutines.Job
import org.koin.core.component.KoinComponent
interface ObservableLauncher {
fun launchMonitors(): List<Job>
}
class DefaultObservableLauncher : ObservableLauncher, KoinComponent {
private val observables by lazy {
getKoin().getAll<Observable<*>>()
}
override fun launchMonitors() =
observables.map {
it.monitor()
}
}
| 6
| null |
0
| 5
|
934806a6a5315092922478995aa0390c3fae4727
| 1,025
|
beam
|
Apache License 2.0
|
app/src/main/java/id/samai/mymedcure/activities/FireBase_registration.kt
|
samba-rgb
| 588,846,571
| false
| null |
package id.samai.mymedcure.activities
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.widget.Button
import android.widget.EditText
import android.widget.ImageView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.android.gms.tasks.Continuation
import com.google.android.gms.tasks.Task
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.storage.FirebaseStorage
import com.google.firebase.storage.StorageReference
import com.google.firebase.storage.UploadTask
import id.samai.mymedcure.R
import id.samai.mymedcure.models.firebase_regis
import java.util.*
class FireBase_registration : AppCompatActivity() {
//URI
private val PICK_PDF_REQUEST = 2342
private var filePath: Uri? = null
private var firebaseStore: FirebaseStorage? = null
private var storageReference: StorageReference? = null
private var mainImageURI: Uri? = null
//REQUEST CODE
val REQUEST = 1
val FUCK_UP = 2
private lateinit var auth : FirebaseAuth
private lateinit var databaseReference: DatabaseReference
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_fire_base_registration)
auth = FirebaseAuth.getInstance()
storageReference = FirebaseStorage.getInstance().reference
val uid = auth.currentUser?.uid
databaseReference = FirebaseDatabase.getInstance().getReference("csv_data2")
val profile = findViewById<ImageView>(R.id.user_profile_icon)
profile.setOnClickListener {
// CHOOSEFOTO()
chosp()
}
findViewById<Button>(R.id.button_regis)?.setOnClickListener {
SAVE_NAME_AND_PHOTO()
}
}
private fun CHOOSEFOTO() {
val intent = Intent()
intent.type = "image/*"
intent.action = Intent.ACTION_GET_CONTENT
startActivityForResult(
Intent.createChooser(intent, "Select Picture"),
REQUEST
)
}
private fun chosp(){
val pickPhoto = Intent(
Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI
)
startActivityForResult(pickPhoto, 1)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode ==REQUEST && resultCode == RESULT_OK) {
if (data != null) {
if (data.data != null) {
mainImageURI = data.data
val profile = findViewById<ImageView>(R.id.user_profile_icon)
profile.setImageURI(mainImageURI)
}else{
Toast.makeText(this, "No file chosen", Toast.LENGTH_SHORT).show();
}
}
}
}
//GETS THE URI FROM THE FOTO AND SETS THE FOTO INTO THE IMAGEVIEW
fun uploadImage() = if(mainImageURI != null){
val user_id = FirebaseAuth.getInstance().currentUser!!.uid
val ref = storageReference?.child("uploads/" + user_id.toString())
val uploadTask = ref?.putFile(mainImageURI!!)
val urlTask = uploadTask?.continueWithTask(Continuation<UploadTask.TaskSnapshot, Task<Uri>> { task ->
if (!task.isSuccessful) {
Toast.makeText(this, "uploading", Toast.LENGTH_SHORT).show()
task.exception?.let {
throw it
}
}
return@Continuation ref.downloadUrl
})
?.addOnCompleteListener { task ->
if (task.isSuccessful) {
filePath = task.result
val firstname = findViewById<EditText>(R.id.user_name).text
val gmail = findViewById<EditText>(R.id.user_gmail).text
val dob = findViewById<EditText>(R.id.user_dob).text
val blood = findViewById<EditText>(R.id.user_bloodgroup).text
val version = 0
val link = "dont know"
val user = firebase_regis(
firstname.toString(), filePath.toString(),
version, link, gmail.toString(), dob.toString(), blood.toString()
)
auth = FirebaseAuth.getInstance()
storageReference = FirebaseStorage.getInstance().reference
val uid = auth.currentUser?.uid
if (uid!= null){
databaseReference.child(uid).setValue(user).addOnCompleteListener{
if(it.isSuccessful){
finish()
}
else{
Toast.makeText(
this@FireBase_registration,
"failed bro",
Toast.LENGTH_SHORT
).show()
}
}
}
} else {
Toast.makeText(this, "uploading IMG", Toast.LENGTH_SHORT).show()
// Handle failures
}
}?.addOnFailureListener {
}
}else{
Toast.makeText(this, "Please Upload an IMG", Toast.LENGTH_SHORT).show()
}
private fun SAVE_NAME_AND_PHOTO() {
val user_id = FirebaseAuth.getInstance().currentUser!!.uid
val ImagesPath: StorageReference =
storageReference?.child("profile_images")!!.child("$user_id.jpg")
ImagesPath.putFile(mainImageURI!!).continueWithTask { task ->
if (!task.isSuccessful) {
throw task.exception!!
}
ImagesPath.downloadUrl
}.addOnCompleteListener { task ->
if (task.isSuccessful) {
filePath = task.result
val firstname = findViewById<EditText>(R.id.user_name).text
val gmail = findViewById<EditText>(R.id.user_gmail).text
val dob = findViewById<EditText>(R.id.user_dob).text
val blood = findViewById<EditText>(R.id.user_bloodgroup).text
val version = 0
val link = "dont know"
val user = firebase_regis(
firstname.toString(), filePath.toString(),
version, link, gmail.toString(), dob.toString(), blood.toString()
)
auth = FirebaseAuth.getInstance()
storageReference = FirebaseStorage.getInstance().reference
val uid = auth.currentUser?.uid
if (uid!= null){
databaseReference.child(uid).setValue(user).addOnCompleteListener{
if(it.isSuccessful){
finish()
}
else{
Toast.makeText(
this@FireBase_registration,
"failed bro",
Toast.LENGTH_SHORT
).show()
}
}
}
} else {
val ERROR = task.exception!!.message
Toast.makeText(this@FireBase_registration, ERROR, Toast.LENGTH_SHORT).show()
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
ac1bad8693cfdae021e18621d57878cec87f7c27
| 7,873
|
my_medicure_app
|
Apache License 2.0
|
android_env/apps/java/com/google/androidenv/accessibilityforwarder/FlagsBroadcastReceiverTest.kt
|
google-deepmind
| 360,111,507
| false
|
{"Python": 561122, "Kotlin": 52487}
|
// Copyright 2024 DeepMind Technologies Limited.
//
// 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.google.androidenv.accessibilityforwarder
import android.content.Intent
import com.google.common.truth.Truth.assertThat
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
class FlagsBroadcastReceiverTest {
@Test
fun onReceive_nullIntent_shouldNotLogAnything() {
// Arrange.
LogFlags.logAccessibilityTree = false
val receiver = FlagsBroadcastReceiver()
// Act.
receiver.onReceive(context = null, intent = null)
// Assert.
assertThat(LogFlags.logAccessibilityTree).isFalse()
}
@Test
fun onReceive_nullIntent_actionShouldNotLogAnything() {
// Arrange.
LogFlags.logAccessibilityTree = false
val receiver = FlagsBroadcastReceiver()
val intent = Intent()
// Act.
receiver.onReceive(context = null, intent = intent)
// Assert.
assertThat(LogFlags.logAccessibilityTree).isFalse()
}
@Test
fun onReceive_unknownIntent_actionShouldIssueWarning() {
// Arrange.
LogFlags.logAccessibilityTree = false
val receiver = FlagsBroadcastReceiver()
val intent = Intent("SOME_WEIRD_ACTION")
// Act.
receiver.onReceive(context = null, intent = intent)
// Assert.
assertThat(LogFlags.logAccessibilityTree).isFalse()
}
@Test
fun onReceive_intentWithDisableAction_shouldDisableTreeLogging() {
// Arrange.
LogFlags.logAccessibilityTree = true
val receiver = FlagsBroadcastReceiver()
val intent = Intent("accessibility_forwarder.intent.action.DISABLE_ACCESSIBILITY_TREE_LOGS")
// Act.
receiver.onReceive(context = null, intent = intent)
// Assert.
assertThat(LogFlags.logAccessibilityTree).isFalse()
}
@Test
fun onReceive_intentWithEnableAction_shouldEnableTreeLogging() {
// Arrange.
LogFlags.logAccessibilityTree = false
val receiver = FlagsBroadcastReceiver()
val intent = Intent("accessibility_forwarder.intent.action.ENABLE_ACCESSIBILITY_TREE_LOGS")
// Act.
receiver.onReceive(context = null, intent = intent)
// Assert.
assertThat(LogFlags.logAccessibilityTree).isTrue()
}
@Test
fun onReceive_intentWithSetGrpcActionNoArgs_shouldDefaultToEmuIpAndPortZero() {
// Arrange.
LogFlags.grpcHost = "some_host"
LogFlags.grpcPort = 9999
val receiver = FlagsBroadcastReceiver()
val intent = Intent("accessibility_forwarder.intent.action.SET_GRPC")
// Act.
receiver.onReceive(context = null, intent = intent)
// Assert.
assertThat(LogFlags.grpcHost).isEqualTo("10.0.2.2")
assertThat(LogFlags.grpcPort).isEqualTo(0)
}
@Test
fun onReceive_intentWithSetGrpcActionWithHostNoPort_shouldDefaultPortToZero() {
// Arrange.
LogFlags.grpcHost = "some_host"
LogFlags.grpcPort = 9999
val receiver = FlagsBroadcastReceiver()
val intent =
Intent("accessibility_forwarder.intent.action.SET_GRPC").apply {
putExtra("host", "awesome.server.ca")
}
// Act.
receiver.onReceive(context = null, intent = intent)
// Assert.
assertThat(LogFlags.grpcHost).isEqualTo("awesome.server.ca")
assertThat(LogFlags.grpcPort).isEqualTo(0)
}
@Test
fun onReceive_intentWithSetGrpcActionWithPortNoHost_shouldDefaultHostToEmuIp() {
// Arrange.
LogFlags.grpcHost = "some_host"
LogFlags.grpcPort = 9999
val receiver = FlagsBroadcastReceiver()
val intent =
Intent("accessibility_forwarder.intent.action.SET_GRPC").apply { putExtra("port", 54321) }
// Act.
receiver.onReceive(context = null, intent = intent)
// Assert.
assertThat(LogFlags.grpcHost).isEqualTo("10.0.2.2")
assertThat(LogFlags.grpcPort).isEqualTo(54321)
}
@Test
fun onReceive_intentWithSetGrpcActionWithHostAndPort_shouldSetBoth() {
// Arrange.
LogFlags.grpcHost = "some_host"
LogFlags.grpcPort = 9999
val receiver = FlagsBroadcastReceiver()
val intent =
Intent("accessibility_forwarder.intent.action.SET_GRPC").apply {
putExtra("host", "grpc.ca")
putExtra("port", 54321)
}
// Act.
receiver.onReceive(context = null, intent = intent)
// Assert.
assertThat(LogFlags.grpcHost).isEqualTo("grpc.ca")
assertThat(LogFlags.grpcPort).isEqualTo(54321)
}
}
| 8
|
Python
|
73
| 1,007
|
746e0e9649a5ff90d9513b7f4d857fc71c167037
| 4,895
|
android_env
|
Apache License 2.0
|
data/barcode/src/main/java/com/awscherb/cardkeeper/barcode/db/ScannedCodeDao.kt
|
LateNightProductions
| 66,697,395
| false
|
{"Kotlin": 186882}
|
package com.awscherb.cardkeeper.barcode.db
import androidx.room.*
import com.awscherb.cardkeeper.barcode.entity.ScannedCodeEntity
import kotlinx.coroutines.flow.Flow
@Dao
interface ScannedCodeDao {
@Query("SELECT * FROM scannedCode WHERE id = :id LIMIT 1")
fun getScannedCode(id: Int): Flow<List<ScannedCodeEntity>>
@Query("SELECT * FROM scannedCode")
fun listScannedCodes(): Flow<List<ScannedCodeEntity>>
@Query("SELECT * FROM scannedCode WHERE title LIKE '%' || :query || '%'")
fun listScannedCodes(query: String): Flow<List<ScannedCodeEntity>>
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertCode(code: ScannedCodeEntity): Long
@Update(onConflict = OnConflictStrategy.REPLACE)
fun updateCode(code: ScannedCodeEntity): Int
@Query("DELETE FROM scannedCode WHERE id = :id")
suspend fun deleteCode(id: Int): Int
}
| 1
|
Kotlin
|
18
| 102
|
b13a05f9967071b69b52abc1d8ae4a8280a97d0e
| 887
|
CardKeeper
|
Apache License 2.0
|
data/barcode/src/main/java/com/awscherb/cardkeeper/barcode/db/ScannedCodeDao.kt
|
LateNightProductions
| 66,697,395
| false
|
{"Kotlin": 186882}
|
package com.awscherb.cardkeeper.barcode.db
import androidx.room.*
import com.awscherb.cardkeeper.barcode.entity.ScannedCodeEntity
import kotlinx.coroutines.flow.Flow
@Dao
interface ScannedCodeDao {
@Query("SELECT * FROM scannedCode WHERE id = :id LIMIT 1")
fun getScannedCode(id: Int): Flow<List<ScannedCodeEntity>>
@Query("SELECT * FROM scannedCode")
fun listScannedCodes(): Flow<List<ScannedCodeEntity>>
@Query("SELECT * FROM scannedCode WHERE title LIKE '%' || :query || '%'")
fun listScannedCodes(query: String): Flow<List<ScannedCodeEntity>>
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertCode(code: ScannedCodeEntity): Long
@Update(onConflict = OnConflictStrategy.REPLACE)
fun updateCode(code: ScannedCodeEntity): Int
@Query("DELETE FROM scannedCode WHERE id = :id")
suspend fun deleteCode(id: Int): Int
}
| 1
|
Kotlin
|
18
| 102
|
b13a05f9967071b69b52abc1d8ae4a8280a97d0e
| 887
|
CardKeeper
|
Apache License 2.0
|
app/src/main/java/com/teamnoyes/majorparksinseoul/adapter/DetailParkAdapter.kt
|
kjh9589
| 373,385,554
| false
| null |
package com.teamnoyes.majorparksinseoul.adapter
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.teamnoyes.majorparksinseoul.model.ModelDetailPark
import com.teamnoyes.majorparksinseoul.views.DetailParkView
class DetailParkAdapter: ListAdapter<ModelDetailPark, DetailParkAdapter.ViewHolder>(diffUtil) {
companion object {
val diffUtil = object : DiffUtil.ItemCallback<ModelDetailPark>() {
override fun areItemsTheSame(
oldItem: ModelDetailPark,
newItem: ModelDetailPark
): Boolean {
return oldItem.headString == newItem.headString
}
override fun areContentsTheSame(
oldItem: ModelDetailPark,
newItem: ModelDetailPark
): Boolean {
return oldItem == newItem
}
}
}
inner class ViewHolder(private val detailParkView: DetailParkView): RecyclerView.ViewHolder(detailParkView.binding.root) {
fun bind(modelDetailPark: ModelDetailPark) {
detailParkView.modelDetailPark = modelDetailPark
detailParkView.binding.executePendingBindings()
}
}
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): ViewHolder {
return ViewHolder(DetailParkView(parent.context, attachToRoot = false))
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(currentList[position])
}
}
| 0
|
Kotlin
|
0
| 0
|
0c12c5b787730eb36263afcc3de0ab7163c8692a
| 1,624
|
Android-Major-Parks-In-Seoul
|
Apache License 2.0
|
app/src/main/java/io/exzocoin/wallet/modules/blockchainsettings/BlockchainSettingsModule.kt
|
rexdev0211
| 403,525,735
| false
|
{"Kotlin": 2356794, "Shell": 2039, "Ruby": 966}
|
package io.exzocoin.wallet.modules.blockchainsettings
import io.exzocoin.wallet.entities.AccountType.Derivation
import io.exzocoin.wallet.entities.BitcoinCashCoinType
import io.exzocoin.wallet.ui.extensions.BottomSheetSelectorViewItem
import io.exzocoin.coinkit.models.Coin
object BlockchainSettingsModule {
data class Request(val coin: Coin, val type: RequestType)
sealed class RequestType {
class DerivationType(val derivations: List<Derivation>, val current: Derivation) : RequestType()
class BitcoinCashType(val types: List<BitcoinCashCoinType>, val current: BitcoinCashCoinType) : RequestType()
}
data class Config(
val coin: Coin,
val title: String,
val subtitle: String,
val selectedIndexes: List<Int>,
val viewItems: List<BottomSheetSelectorViewItem>,
val description: String
)
}
| 0
|
Kotlin
|
1
| 0
|
1ed5d80490ecf1574499cafa5aad922c4ea9a362
| 902
|
exzo-android-wallet-main
|
MIT License
|
vuesaxicons/src/commonMain/kotlin/moe/tlaster/icons/vuesax/vuesaxicons/bold/Volumelow1.kt
|
Tlaster
| 560,394,734
| false
|
{"Kotlin": 25133302}
|
package moe.tlaster.icons.vuesax.vuesaxicons.bold
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin
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 moe.tlaster.icons.vuesax.vuesaxicons.BoldGroup
public val BoldGroup.Volumelow1: ImageVector
get() {
if (_volumelow1 != null) {
return _volumelow1!!
}
_volumelow1 = Builder(name = "Volumelow1", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(19.3284f, 16.7503f)
curveTo(19.1684f, 16.7503f, 19.0184f, 16.7003f, 18.8784f, 16.6003f)
curveTo(18.5484f, 16.3503f, 18.4784f, 15.8803f, 18.7284f, 15.5503f)
curveTo(20.2984f, 13.4603f, 20.2984f, 10.5403f, 18.7284f, 8.4503f)
curveTo(18.4784f, 8.1203f, 18.5484f, 7.6503f, 18.8784f, 7.4003f)
curveTo(19.2084f, 7.1503f, 19.6784f, 7.2203f, 19.9284f, 7.5503f)
curveTo(21.8984f, 10.1703f, 21.8984f, 13.8303f, 19.9284f, 16.4503f)
curveTo(19.7884f, 16.6503f, 19.5584f, 16.7503f, 19.3284f, 16.7503f)
close()
}
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(15.3481f, 3.7817f)
curveTo(14.2281f, 3.1617f, 12.7981f, 3.3217f, 11.3381f, 4.2317f)
lineTo(8.4181f, 6.0617f)
curveTo(8.2181f, 6.1817f, 7.9881f, 6.2517f, 7.7581f, 6.2517f)
horizontalLineTo(6.8281f)
horizontalLineTo(6.3281f)
curveTo(3.9081f, 6.2517f, 2.5781f, 7.5817f, 2.5781f, 10.0017f)
verticalLineTo(14.0017f)
curveTo(2.5781f, 16.4217f, 3.9081f, 17.7517f, 6.3281f, 17.7517f)
horizontalLineTo(6.8281f)
horizontalLineTo(7.7581f)
curveTo(7.9881f, 17.7517f, 8.2181f, 17.8217f, 8.4181f, 17.9417f)
lineTo(11.3381f, 19.7717f)
curveTo(12.2181f, 20.3217f, 13.0781f, 20.5917f, 13.8781f, 20.5917f)
curveTo(14.3981f, 20.5917f, 14.8981f, 20.4717f, 15.3481f, 20.2217f)
curveTo(16.4581f, 19.6017f, 17.0781f, 18.3117f, 17.0781f, 16.5917f)
verticalLineTo(7.4117f)
curveTo(17.0781f, 5.6917f, 16.4581f, 4.4017f, 15.3481f, 3.7817f)
close()
}
}
.build()
return _volumelow1!!
}
private var _volumelow1: ImageVector? = null
| 0
|
Kotlin
|
0
| 2
|
b8a8231e6637c2008f675ae76a3423b82ee53950
| 3,411
|
VuesaxIcons
|
MIT License
|
medeia-validator-core/src/main/kotlin/com/worldturner/medeia/schema/validation/EnumValidator.kt
|
crunchyroll
| 193,698,964
| true
|
{"Kotlin": 359249, "Java": 18810}
|
package com.worldturner.medeia.schema.validation
import com.worldturner.medeia.api.FailedValidationResult
import com.worldturner.medeia.api.OkValidationResult
import com.worldturner.medeia.api.ValidationResult
import com.worldturner.medeia.parser.ArrayNode
import com.worldturner.medeia.parser.JsonTokenData
import com.worldturner.medeia.parser.JsonTokenLocation
import com.worldturner.medeia.parser.JsonTokenType
import com.worldturner.medeia.parser.TreeNode
import com.worldturner.medeia.parser.ObjectNode
import com.worldturner.medeia.parser.SimpleNode
import com.worldturner.medeia.schema.validation.stream.SchemaValidatorInstance
import com.worldturner.util.iterate
import java.net.URI
import java.util.ArrayDeque
import java.util.Deque
class EnumValidator(
val enum: Set<TreeNode>
) : SchemaValidator {
override fun createInstance(startLevel: Int): SchemaValidatorInstance =
EnumValidatorInstance(startLevel, enum)
override fun recordUnknownRefs(unknownRefs: MutableCollection<URI>) = Unit
companion object {
fun create(enum: Set<TreeNode>? = null): SchemaValidator? =
enum?.let {
if (enum.all { it is SimpleNode })
@Suppress("UNCHECKED_CAST")
TokenOnlyEnumValidator(enum as Set<SimpleNode>)
else
EnumValidator(enum)
}
}
}
internal class TokenOnlyEnumValidator(
val enum: Set<SimpleNode>
) : SchemaValidator, SchemaValidatorInstance {
override fun createInstance(startLevel: Int): SchemaValidatorInstance = this
override fun recordUnknownRefs(unknownRefs: MutableCollection<URI>) = Unit
override fun validate(token: JsonTokenData, location: JsonTokenLocation): ValidationResult? {
if (!token.type.nonStructureToken) {
return fail(location, "None of the non-structured enum values matched data $token")
}
return if (enum.any { it.token == token })
OkValidationResult
else
fail(location, "None of the non-structured enum values matched data $token")
}
}
class EnumValueState(enumValue: TreeNode) {
internal val constStack: Deque<TreeNode> = ArrayDeque()
internal var currentConst: TreeNode? = enumValue
}
class EnumValidatorInstance(
val startLevel: Int,
val enum: Set<TreeNode>
) : SchemaValidatorInstance {
private val verificationStack: Deque<ConstVerifier> = ArrayDeque()
private var currentProperty: String? = null
private val enumValueStates = enum.mapTo(mutableListOf()) { EnumValueState(it) }
override fun validate(token: JsonTokenData, location: JsonTokenLocation): ValidationResult? {
if (token.type == JsonTokenType.FIELD_NAME) {
currentProperty = token.text!!
return null
}
if (token.type.firstToken) {
val top = if (verificationStack.isEmpty()) null else verificationStack.peek()
when (top) {
is ObjectVerifier -> {
top.propertyNames.add(currentProperty!!)
enumValueStates.iterate { enumValueState, iterator ->
val currentConst = enumValueState.currentConst
if (currentConst is ObjectNode) {
enumValueState.constStack.push(currentConst)
currentConst.nodes[currentProperty!!]?.let { enumValueState.currentConst = it }
?: iterator.remove()
} else {
iterator.remove()
}
}
}
is ArrayVerifier -> {
enumValueStates.iterate { enumValueState, iterator ->
val currentConst = enumValueState.currentConst
if (currentConst is ArrayNode) {
if (currentConst.nodes.size <= top.itemCount) {
iterator.remove()
} else {
enumValueState.constStack.push(currentConst)
enumValueState.currentConst = currentConst.nodes[top.itemCount]
}
} else {
iterator.remove()
}
}
top.itemCount++
}
}
val verifier =
when (token.type) {
JsonTokenType.START_OBJECT -> ObjectVerifier()
JsonTokenType.START_ARRAY -> ArrayVerifier()
else -> SingleVerifier(token)
}
verificationStack.push(verifier)
}
if (token.type.lastToken) {
val top = verificationStack.pop()!!
enumValueStates.iterate { enumValueState, iterator ->
val result = top.verify(enumValueState.currentConst!!, location)
if (!result.valid)
iterator.remove()
else
enumValueState.currentConst =
if (enumValueState.constStack.isEmpty()) null else enumValueState.constStack.pop()
}
if (location.level == startLevel) {
return if (enumValueStates.isNotEmpty())
OkValidationResult
else
fail(location, "None of the enum values matched")
}
}
return null
}
}
private fun fail(
location: JsonTokenLocation,
message: String
) =
FailedValidationResult(
location = location,
rule = "enum",
message = message
)
| 1
|
Kotlin
|
0
| 0
|
9f435c57f5a31cc5f7fbde6cdae747c38a2ed9ec
| 5,737
|
medeia-validator
|
Apache License 2.0
|
app/src/main/java/com/yggdralisk/koinspotifysample/presentation/releases/ReleasesViewModel.kt
|
JanStoltman
| 145,439,418
| false
| null |
package com.yggdralisk.koinspotifysample.presentation.releases
import android.app.Activity
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.yggdralisk.koinspotifysample.R
import com.yggdralisk.koinspotifysample.data.model.ReleaseModel
import com.yggdralisk.koinspotifysample.domain.ReleasesInteractor
import com.yggdralisk.koinspotifysample.presentation.base.BaseViewModel
import com.yggdralisk.koinspotifysample.presentation.release.ReleaseDetailsActivity
import com.yggdralisk.koinspotifysample.presentation.user.UserProfileActivity
import com.yggdralisk.koinspotifysample.util.common.SingleLiveEvent
import io.reactivex.rxkotlin.addTo
class ReleasesViewModel(private val releasesInteractor: ReleasesInteractor) : BaseViewModel() {
private val newReleases = MutableLiveData<List<ReleaseModel>>()
private val fetchErrorResId = MutableLiveData<Int?>()
private val classToLaunch = SingleLiveEvent<Class<out Activity>>()
private val chosenRelease = MutableLiveData<ReleaseModel>()
fun getNewReleases(): LiveData<List<ReleaseModel>> {
releasesInteractor.getReleases().subscribe({
handleResponse(it)
}, {
handleError()
}).addTo(subscriptions)
return newReleases
}
private fun handleResponse(response: List<ReleaseModel>) {
fetchErrorResId.value = null
newReleases.value = response
}
private fun handleError() {
fetchErrorResId.value = R.string.fetch_def_error
}
fun getFetchErrorResId(): LiveData<Int?> = fetchErrorResId
fun getClassToLaunch(): SingleLiveEvent<Class<out Activity>> = classToLaunch
fun getChosenRelease(): LiveData<ReleaseModel> = chosenRelease
fun onUserProfileButtonClick() {
classToLaunch.value = UserProfileActivity::class.java
}
fun onReleaseRowClick(release: ReleaseModel) {
chosenRelease.value = release
classToLaunch.value = ReleaseDetailsActivity::class.java
}
}
| 0
|
Kotlin
|
1
| 4
|
af87049819152bd2239963f2e78590ef76288bda
| 2,004
|
koin-spotify-sample
|
Apache License 2.0
|
bukkit/rpk-chat-bukkit/src/main/kotlin/com/rpkit/chat/bukkit/discord/command/DiscordVersionCommand.kt
|
RP-Kit
| 54,840,905
| false
| null |
/*
* Copyright 2022 Ren Binden
*
* 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.rpkit.chat.bukkit.discord.command
import com.rpkit.chat.bukkit.RPKChatBukkit
import net.dv8tion.jda.api.entities.User
import net.dv8tion.jda.api.entities.channel.middleman.MessageChannel
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent
import net.dv8tion.jda.api.interactions.commands.OptionMapping
import net.dv8tion.jda.api.interactions.commands.OptionType.STRING
import net.dv8tion.jda.api.interactions.commands.build.OptionData
class DiscordVersionCommand(private val plugin: RPKChatBukkit) : DiscordCommand(
"version",
"Views the version of the server or a plugin",
OptionData(
STRING,
"plugin",
"The plugin to get the version of",
false
)
) {
override fun execute(
channel: MessageChannel,
sender: User,
command: DiscordCommand,
label: String,
args: List<OptionMapping>,
event: SlashCommandInteractionEvent
) {
val pluginName = args.singleOrNull { it.name == "plugin" }
if (pluginName != null) {
val pluginToShow = plugin.server.pluginManager.getPlugin(pluginName.asString)
if (pluginToShow == null) {
event.reply(plugin.messages.versionInvalidPlugin).queue()
return
}
val response = StringBuilder()
response.append(plugin.messages.pluginVersion.withParameters(
name = pluginToShow.name,
version = pluginToShow.description.version
)).append("\n")
val description = pluginToShow.description.description
if (description != null) {
response.append(plugin.messages.pluginDescription.withParameters(
description = description
)).append("\n")
}
val website = pluginToShow.description.website
if (website != null) {
response.append(plugin.messages.pluginWebsite.withParameters(
website = website
)).append("\n")
}
if (pluginToShow.description.authors.isNotEmpty()) {
if (pluginToShow.description.authors.size == 1) {
response.append(plugin.messages.pluginAuthor.withParameters(
author = pluginToShow.description.authors.single()
)).append("\n")
} else {
response.append(plugin.messages.pluginAuthors.withParameters(
authors = pluginToShow.description.authors
)).append("\n")
}
}
if (pluginToShow.description.contributors.isNotEmpty()) {
response.append(plugin.messages.pluginContributors.withParameters(
contributors = pluginToShow.description.contributors
)).append("\n")
}
event.reply(response.toString()).queue()
} else {
event.reply(plugin.messages.serverVersion.withParameters(
name = plugin.server.name,
version = plugin.server.version,
apiVersion = plugin.server.bukkitVersion
)).queue()
}
}
}
| 51
|
Kotlin
|
11
| 22
|
aee4060598dc25cd8e4f3976ed5e70eb1bf874a2
| 3,854
|
RPKit
|
Apache License 2.0
|
SleepestMaster/app/src/main/java/com/sleepestapp/sleepest/ui/history/HistoryDayFragment.kt
|
vanthomiy
| 334,247,111
| false
| null |
package com.sleepestapp.sleepest.ui.history
import android.content.Context
import android.graphics.Color
import android.os.Bundle
import android.transition.TransitionManager
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.sleepestapp.sleepest.R
import com.sleepestapp.sleepest.databinding.FragmentHistoryDayBinding
import com.sleepestapp.sleepest.model.data.ActivityOnDay
import com.sleepestapp.sleepest.model.data.MobilePosition
import com.sleepestapp.sleepest.model.data.SleepState
import com.sleepestapp.sleepest.sleepcalculation.model.UserSleepRating
import com.sleepestapp.sleepest.util.SmileySelectorUtil
import com.sleepestapp.sleepest.util.TimeConverterUtil
import com.github.mikephil.charting.animation.Easing
import com.github.mikephil.charting.charts.BarChart
import com.github.mikephil.charting.charts.PieChart
import com.github.mikephil.charting.components.Legend
import com.github.mikephil.charting.components.LegendEntry
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.data.*
import com.sleepestapp.sleepest.sleepcalculation.SleepCalculationHandler
import com.sleepestapp.sleepest.util.DesignUtil
import com.sleepestapp.sleepest.util.SleepTimeValidationUtil.is24HourFormat
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import java.time.Instant
import java.time.LocalDateTime
import java.time.ZoneOffset
import java.time.format.DateTimeFormatter
import kotlin.collections.ArrayList
import kotlin.math.roundToInt
class HistoryDayFragment : Fragment() {
private val scope: CoroutineScope = MainScope()
private val actualContext: Context by lazy { requireActivity().applicationContext }
/**
* Base ViewModel which contains relevant information for the whole history fragment.
*/
private val viewModel by lazy { ViewModelProvider(requireActivity()).get(HistoryViewModel::class.java) }
/**
* ViewModel for the daily sleep analysis.
*/
private val viewModelDay by lazy { ViewModelProvider(requireActivity(), factory).get(HistoryDayViewModel::class.java) }
var factory = object : ViewModelProvider.Factory {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
@Suppress("UNCHECKED_CAST")
return HistoryDayViewModel(
SleepCalculationHandler(actualContext)
) as T
}
}
/**
* Binding for daily history analysis fragment.
*/
private lateinit var binding: FragmentHistoryDayBinding
/**
* [PieChart] for the daily sleep analysis.
*/
private lateinit var pieChartSleepAnalysis: PieChart
/**
* [BarChart] for the daily sleep analysis.
*/
private lateinit var barChartSleepAnalysis: BarChart
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
// Listener for changes in the analysis date.
viewModel.analysisDate.observe(viewLifecycleOwner) {
viewModelDay.getSleepSessionId(it)
updateCharts()
}
binding = FragmentHistoryDayBinding.inflate(inflater, container, false)
binding.historyDayViewModel = viewModelDay
binding.lifecycleOwner = this
viewModelDay.is24HourFormat = is24HourFormat(actualContext)
// Initial set up for the daily sleep analysis bar chart.
barChartSleepAnalysis = setBarChart(
DesignUtil.colorDarkMode(
DesignUtil.checkDarkModeActive(
actualContext,
viewModel.appSettingsDarkMode,
viewModel.appAutoDarkMode
)
)
)
updateBarChart(
barChartSleepAnalysis,
DesignUtil.colorDarkMode(
DesignUtil.checkDarkModeActive(
actualContext,
viewModel.appSettingsDarkMode,
viewModel.appAutoDarkMode
)
)
)
binding.lLSleepAnalysisChartsDaySleepPhases.addView(barChartSleepAnalysis)
barChartSleepAnalysis.layoutParams.height = TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
150F,
resources.displayMetrics
).toInt()
barChartSleepAnalysis.layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT
barChartSleepAnalysis.invalidate()
// Initial set up for the daily sleep analysis pie chart.
pieChartSleepAnalysis = setPieChart(
DesignUtil.determineHoleColorPieChart(
DesignUtil.checkDarkModeActive(
actualContext,
viewModel.appSettingsDarkMode,
viewModel.appAutoDarkMode
)
)
)
binding.lLSleepAnalysisChartsDaySleepPhasesAmount.addView(pieChartSleepAnalysis)
pieChartSleepAnalysis.layoutParams.height = TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
175F,
resources.displayMetrics
).toInt()
pieChartSleepAnalysis.layoutParams.width = TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
175F,
resources.displayMetrics
).toInt()
pieChartSleepAnalysis.invalidate()
// Listener for changes in the sleepMoodSmiley
viewModelDay.sleepMoodSmiley.observe(viewLifecycleOwner) {
saveSleepRatingDaily()
}
// Listener for new data which was extracted from the database.
viewModel.dataReceived.observe(viewLifecycleOwner) {
if (viewModel.dataReceived.value == true && !viewModelDay.sleepRatingUpdate) {
updateCharts()
viewModel.dataReceived.value = false
}
viewModelDay.sleepRatingUpdate = false
}
// Listener for the actual information button which was selected.
viewModelDay.actualExpand.observe(viewLifecycleOwner) {
TransitionManager.beginDelayedTransition(binding.lLLinearAnimationLayoutDailyAnalysis)
}
return binding.root
}
/**
* Calls all update functions for the charts in this fragment.
* [updateBarChart], [updatePieChart], [updateActivitySmiley].
*/
private fun updateCharts() {
updateBarChart(
barChartSleepAnalysis,
DesignUtil.colorDarkMode(
DesignUtil.checkDarkModeActive(
actualContext,
viewModel.appSettingsDarkMode,
viewModel.appAutoDarkMode
)
)
)
barChartSleepAnalysis.invalidate()
updatePieChart(
pieChartSleepAnalysis,
DesignUtil.determineHoleColorPieChart(
DesignUtil.checkDarkModeActive(
actualContext,
viewModel.appSettingsDarkMode,
viewModel.appAutoDarkMode
)
)
)
pieChartSleepAnalysis.invalidate()
updateActivitySmiley()
}
/**
* Maintains the visibility settings of the daily sleep analysis.
* If no data is to be shown, the diagrams disappear and an information will appear.
*/
private fun maintainVisibilityDayHistory(
setVisibility: Boolean
) {
if (setVisibility) {
binding.iVNoDataAvailable.visibility = View.GONE
binding.tVNoDataAvailable.visibility = View.GONE
binding.tVActivitySmileyNoSleepDataAvailable.visibility = View.GONE
binding.sVSleepAnalysisChartsDays.visibility = View.VISIBLE
}
else {
binding.sVSleepAnalysisChartsDays.visibility = View.GONE
binding.iVNoDataAvailable.visibility = View.VISIBLE
binding.tVNoDataAvailable.visibility = View.VISIBLE
binding.tVActivitySmileyNoSleepDataAvailable.visibility = View.VISIBLE
}
}
/**
* Save user input for the [UserSleepRating.moodAfterSleep] into the database.
* Alters the current value of this day in the [HistoryViewModel.sleepAnalysisData].
*/
private fun saveSleepRatingDaily() {
// Save to database.
scope.launch {
viewModelDay.sleepMoodSmiley.value?.let {
viewModel.dataBaseRepository.updateMoodAfterSleep(
it,
viewModelDay.sessionId
)
}
}
// Alter value in the currently used sleepAnalysisData.
viewModel.sleepAnalysisData.firstOrNull {
x -> x.sleepSessionId == viewModelDay.sessionId
}?.let { session ->
viewModelDay.sleepMoodSmiley.value?.let {rating ->
session.userSleepSessionEntity.userSleepRating.moodAfterSleep = rating
}
}
}
/**
* Auxiliary function for [setTimeStamps] which formats the strings for time information.
*/
private fun generateSleepValueInformation(
time: Int
): String {
return kotlin.math.floor((time.toFloat() / 60f).toDouble()).toInt().toString() +
"h " +
(time % 60).toString() +
"min"
}
/**
* Tells the user the exact fall asleep time and wakeup time which is to be shown on top of the [barChartSleepAnalysis].
*/
private fun setTimeStamps() {
// In case the session is available, set values.
viewModel.sleepAnalysisData.firstOrNull {
x -> x.sleepSessionId == viewModelDay.sessionId
}?.let {
val sleepTimeStart = LocalDateTime.ofInstant(
Instant.ofEpochMilli((it.userSleepSessionEntity.sleepTimes.sleepTimeStart.toLong()) * 1000),
ZoneOffset.systemDefault()
)
val sleepTimeEnd = LocalDateTime.ofInstant(
Instant.ofEpochMilli((it.userSleepSessionEntity.sleepTimes.sleepTimeEnd.toLong()) * 1000),
ZoneOffset.systemDefault()
)
viewModelDay.beginOfSleep.value = (TimeConverterUtil.toTimeFormat(sleepTimeStart.hour, sleepTimeStart.minute))
viewModelDay.beginOfSleepEpoch.value = (it.userSleepSessionEntity.sleepTimes.sleepTimeStart.toLong() * 1000)
viewModelDay.endOfSeep.value = (TimeConverterUtil.toTimeFormat(sleepTimeEnd.hour, sleepTimeEnd.minute))
viewModelDay.endOfSleepEpoch.value = (it.userSleepSessionEntity.sleepTimes.sleepTimeEnd.toLong() * 1000)
viewModelDay.awakeTime.value = (
actualContext.getString(R.string.history_day_timeInPhase_awake) + " " + generateSleepValueInformation(it.userSleepSessionEntity.sleepTimes.awakeTime)
)
viewModelDay.lightSleepTime.value = (
actualContext.getString(R.string.history_day_timeInPhase_lightSleep) + " " + generateSleepValueInformation(it.userSleepSessionEntity.sleepTimes.lightSleepDuration)
)
viewModelDay.deepSleepTime.value = (
actualContext.getString(R.string.history_day_timeInPhase_deepSleep) + " " + generateSleepValueInformation(it.userSleepSessionEntity.sleepTimes.deepSleepDuration)
)
viewModelDay.remSleepTime.value = (
actualContext.getString(R.string.history_day_timeInPhase_remSleep) + " " + generateSleepValueInformation(it.userSleepSessionEntity.sleepTimes.remSleepDuration)
)
viewModelDay.sleepTime.value = (
actualContext.getString(R.string.history_day_timeInPhase_sleepSum) + " " + generateSleepValueInformation(it.userSleepSessionEntity.sleepTimes.sleepDuration)
)
// Manage visibility of the text information based on the mobile position
if (it.userSleepSessionEntity.mobilePosition == MobilePosition.INBED) {
viewModelDay.timeInSleepPhaseTextField.value = (View.VISIBLE)
}
else {
viewModelDay.timeInSleepPhaseTextField.value = (View.INVISIBLE)
}
} ?: run {
val time = LocalDateTime.of(1970, 1, 1, 0, 0, 0).format(DateTimeFormatter.ISO_TIME)
viewModelDay.beginOfSleep.value = time
viewModelDay.endOfSeep.value = time
viewModelDay.awakeTime.value = (
actualContext.getString(R.string.history_day_timeInPhase_awake) + " " + generateSleepValueInformation(0)
)
viewModelDay.lightSleepTime.value = (
actualContext.getString(R.string.history_day_timeInPhase_lightSleep) + " " + generateSleepValueInformation(0)
)
viewModelDay.deepSleepTime.value = (
actualContext.getString(R.string.history_day_timeInPhase_deepSleep) + " " + generateSleepValueInformation(0)
)
viewModelDay.remSleepTime.value = (
actualContext.getString(R.string.history_day_timeInPhase_remSleep) + " " + generateSleepValueInformation(0)
)
viewModelDay.sleepTime.value = (
actualContext.getString(R.string.history_day_timeInPhase_sleepSum) + " " + generateSleepValueInformation(0)
)
}
}
/**
* Auxiliary function for generating entries for the [barChartSleepAnalysis].
* Analysis the [HistoryViewModel.sleepAnalysisData] for the currently selected date and creates a [BarEntry] in a timely fitting manner.
*/
fun generateDataBarChart(): ArrayList<BarEntry> {
val entries = ArrayList<BarEntry>()
var xIndex = 0.5f
viewModel.sleepAnalysisData.firstOrNull {
x -> x.sleepSessionId == viewModelDay.sessionId
}?.let {
setTimeStamps()
maintainVisibilityDayHistory(true)
it.sleepApiRawDataEntity.forEach { rawData ->
for (minute in 0..((it.userSleepSessionEntity.sleepTimes.sleepDuration / 60).toDouble()).roundToInt()) {
when (rawData.sleepState) {
SleepState.AWAKE -> {
entries.add(BarEntry(xIndex, 1f))
}
SleepState.LIGHT -> {
entries.add(BarEntry(xIndex, 2f))
}
SleepState.DEEP -> {
entries.add(BarEntry(xIndex, 3f))
}
SleepState.REM -> {
entries.add(BarEntry(xIndex, 4f))
}
SleepState.SLEEPING -> {
entries.add(BarEntry(xIndex, 5f))
}
else -> entries.add(BarEntry(xIndex, 6f))
}
xIndex += 1f
if (it.userSleepSessionEntity.sleepTimes.sleepTimeStart == 0) {
maintainVisibilityDayHistory(false)
}
}
}
} ?: kotlin.run {
maintainVisibilityDayHistory(false)
}
return entries
}
/**
* Auxiliary function for generating a [BarDataSet] for the [barChartSleepAnalysis].
* Adds fitting colors for every [BarEntry] of the diagram.
*/
private fun generateBarDataSet(
barEntries: ArrayList<BarEntry>
) : BarDataSet {
val barDataSet = BarDataSet(barEntries, "")
val colorList = mutableListOf<Int>()
for (ent in barEntries) {
when (ent.y) {
1f -> colorList.add(ContextCompat.getColor(actualContext, R.color.awake_sleep_color))
2f -> colorList.add(ContextCompat.getColor(actualContext, R.color.light_sleep_color))
3f -> colorList.add(ContextCompat.getColor(actualContext, R.color.deep_sleep_color))
4f -> colorList.add(ContextCompat.getColor(actualContext, R.color.rem_sleep_color))
5f -> colorList.add(ContextCompat.getColor(actualContext, R.color.sleep_sleep_color))
else -> colorList.add(ContextCompat.getColor(actualContext, R.color.warning_color))
}
}
barDataSet.colors = colorList
barDataSet.setDrawValues(false)
return barDataSet
}
/**
* Auxiliary function to determine the height of the [barChartSleepAnalysis].
* */
private fun getBarChartYAxisProportion(
entries: ArrayList<BarEntry>
) : Float {
var size = 0f
for (ent in entries) {
if (size < ent.y) {
size = ent.y
}
}
return size
}
/**
* Function for creating a new [BarChart] entity.
* */
fun setBarChart(
colorDarkMode: Int
): BarChart {
val barChart = BarChart(context)
val diagramData = generateDataBarChart()
val barData = BarData(
generateBarDataSet(
diagramData
)
)
barChart.data = barData
visualSetUpBarChart(
barChart,
diagramData,
colorDarkMode
)
return barChart
}
/**
* Function for updating an existing [BarChart] entity.
* */
private fun updateBarChart(
barChart: BarChart,
colorDarkMode: Int
) {
val diagramData = generateDataBarChart()
val barData = BarData(
generateBarDataSet(
diagramData
)
)
barChart.data = barData
barChart.notifyDataSetChanged()
visualSetUpBarChart(
barChart,
diagramData,
colorDarkMode
)
}
/**
* Auxiliary function for setting up or updating the visual settings of a [BarChart].
*/
private fun visualSetUpBarChart(
barChart: BarChart,
diagramData: ArrayList<BarEntry>,
colorDarkMode: Int
) {
val proportion = getBarChartYAxisProportion(diagramData)
val legendEntryList = mutableListOf<LegendEntry>()
val sleepStates = SleepState.getListOfSleepStates()
sleepStates.forEach {
legendEntryList.add(
LegendEntry(
viewModel.sleepStateString[it],
Legend.LegendForm.SQUARE,
8f,
8f,
null,
viewModel.sleepStateColor[it]?: 1
)
)
}
barChart.xAxis.position = XAxis.XAxisPosition.BOTTOM
barChart.xAxis.axisMinimum = 0f
barChart.xAxis.axisMaximum = diagramData.size.toFloat()
barChart.xAxis.setDrawGridLines(false)
barChart.xAxis.setDrawLabels(false)
barChart.legend.textSize = 12f
barChart.legend.textColor = colorDarkMode
barChart.legend.verticalAlignment = Legend.LegendVerticalAlignment.BOTTOM
barChart.legend.horizontalAlignment = Legend.LegendHorizontalAlignment.RIGHT
barChart.legend.orientation = Legend.LegendOrientation.HORIZONTAL
barChart.legend.setDrawInside(false)
barChart.legend.setCustom(legendEntryList)
barChart.axisRight.isEnabled = true
barChart.axisRight.spaceTop = 1f
barChart.axisRight.axisMinimum = 0f
barChart.axisRight.axisMaximum = proportion
barChart.axisRight.labelCount = 0
barChart.axisRight.setDrawGridLines(false)
barChart.axisRight.setDrawLabels(false)
barChart.axisLeft.isEnabled = true
barChart.axisLeft.axisMinimum = 0f
barChart.axisLeft.axisMaximum = proportion
barChart.axisLeft.labelCount = proportion.toInt()
barChart.axisLeft.setDrawGridLines(false)
barChart.axisLeft.setDrawLabels(false)
barChart.description.isEnabled = false
barChart.data.isHighlightEnabled = false
barChart.barData.barWidth = 1.1f
barChart.isDragEnabled = false
barChart.isDoubleTapToZoomEnabled = false
barChart.setFitBars(true)
barChart.setScaleEnabled(false)
barChart.setTouchEnabled(false)
barChart.setPinchZoom(false)
}
/**
* Auxiliary function for generating entries for the [pieChartSleepAnalysis].
* Analysis the [HistoryViewModel.sleepAnalysisData] for the currently selected date and creates a [PieEntry] for each sleep phase.
* */
private fun generateDataPieChart() : Pair<ArrayList<PieEntry>, BooleanArray> {
val entries = ArrayList<PieEntry>()
val sleepTypes = booleanArrayOf(false, false, false, false, false) //awake, sleep, light, deep, rem
viewModel.sleepAnalysisData.firstOrNull {
x -> x.sleepSessionId == viewModelDay.sessionId
}?.let {
val awake = it.userSleepSessionEntity.sleepTimes.awakeTime
val sleep = it.userSleepSessionEntity.sleepTimes.sleepDuration
val lightSleep = it.userSleepSessionEntity.sleepTimes.lightSleepDuration
val deepSleep = it.userSleepSessionEntity.sleepTimes.deepSleepDuration
val remSleep = it.userSleepSessionEntity.sleepTimes.remSleepDuration
if (it.userSleepSessionEntity.mobilePosition == MobilePosition.ONTABLE) {
if (awake > 0) {
entries.add(PieEntry(awake.toFloat(), actualContext.getString(R.string.history_day_timeInPhase_awake)))
sleepTypes[0] = true
}
if (sleep > 0) {
entries.add(PieEntry(sleep.toFloat(), actualContext.getString(R.string.history_day_timeInPhase_sleepSum)))
sleepTypes[1] = true
}
}
else if (it.userSleepSessionEntity.mobilePosition == MobilePosition.INBED) {
if (awake > 0) {
entries.add(PieEntry(awake.toFloat(), actualContext.getString(R.string.history_day_timeInPhase_awake)))
sleepTypes[0] = true
}
if (lightSleep > 0) {
entries.add(PieEntry(lightSleep.toFloat(), actualContext.getString(R.string.history_day_timeInPhase_lightSleep)))
sleepTypes[2] = true
}
if (deepSleep > 0) {
entries.add(PieEntry(deepSleep.toFloat(), actualContext.getString(R.string.history_day_timeInPhase_deepSleep)))
sleepTypes[3] = true
}
if (remSleep > 0) {
entries.add(PieEntry(remSleep.toFloat(), actualContext.getString(R.string.history_day_timeInPhase_remSleep)))
sleepTypes[4] = true
}
}
}
return Pair(entries, sleepTypes)
}
/**
* Function for creating a new [PieChart] entity.
*/
private fun setPieChart(
holeColorPieChart: Int
): PieChart {
val chart = PieChart(actualContext)
val data = generateDataPieChart()
val pieDataSet = PieDataSet(data.first, "")
visualSetUpPieChart(chart, pieDataSet, data.second, holeColorPieChart)
chart.data = PieData(pieDataSet)
return chart
}
/**
* Function for updating an existing [PieChart] entity.
*/
private fun updatePieChart(
chart: PieChart,
holeColorPieChart: Int
) {
val data = generateDataPieChart()
val pieDataSet = PieDataSet(data.first, "")
visualSetUpPieChart(chart, pieDataSet, data.second, holeColorPieChart)
chart.data = PieData(pieDataSet)
chart.notifyDataSetChanged()
}
/**
* Auxiliary function for setting up or updating the visual settings of a [PieChart].
*/
private fun visualSetUpPieChart(
chart: PieChart,
pieDataSet: PieDataSet,
sleepTypes: BooleanArray,
holeColorPieChart: Int
) {
val listColors = ArrayList<Int>()
//sleepTypes[0] = awake, sleepTypes[1] = sleep, sleepTypes[2] = light, sleepTypes[3] = deep, sleepTypes[4] = rem
if (sleepTypes[0]) {
listColors.add(ContextCompat.getColor(actualContext, R.color.awake_sleep_color))
}
if (sleepTypes[1]) {
listColors.add(ContextCompat.getColor(actualContext, R.color.sleep_sleep_color))
}
if (sleepTypes[2]) {
listColors.add(ContextCompat.getColor(actualContext, R.color.light_sleep_color))
}
if (sleepTypes[3]) {
listColors.add(ContextCompat.getColor(actualContext, R.color.deep_sleep_color))
}
if (sleepTypes[4]) {
listColors.add(ContextCompat.getColor(actualContext, R.color.rem_sleep_color))
}
pieDataSet.colors = listColors
pieDataSet.setDrawValues(false)
//chart.legend.horizontalAlignment = Legend.LegendHorizontalAlignment.CENTER
chart.legend.isEnabled = false
//chart.legend.textColor = viewModel.checkDarkMode()
chart.description.isEnabled = false
chart.setEntryLabelColor(Color.WHITE)
chart.isDrawHoleEnabled = true
chart.setHoleColor(holeColorPieChart)
chart.setTouchEnabled(false)
chart.animateY(500, Easing.EaseInOutQuad)
//chart.setEntryLabelColor(viewModel.checkDarkMode())
}
/**
* Accesses the value of the [ActivityOnDay] from [HistoryViewModel.sleepAnalysisData].
* Accesses the value of the [UserSleepRating.moodAfterSleep] from [HistoryViewModel.sleepAnalysisData].
*/
private fun updateActivitySmiley() {
var activityOnDay = 0
viewModel.sleepAnalysisData.firstOrNull {
x -> x.sleepSessionId == viewModelDay.sessionId
}?.let {
activityOnDay = when (it.userSleepSessionEntity.userSleepRating.activityOnDay) {
ActivityOnDay.NOACTIVITY -> 1
ActivityOnDay.SMALLACTIVITY -> 1
ActivityOnDay.NORMALACTIVITY -> 2
ActivityOnDay.MUCHACTIVITY -> 2
ActivityOnDay.EXTREMACTIVITY -> 3
else -> 0
}
viewModelDay.sleepMoodSmileyTag.value = it.userSleepSessionEntity.userSleepRating.moodAfterSleep.ordinal
}
viewModelDay.activitySmileyTag.value = (SmileySelectorUtil.getSmileyActivity(activityOnDay))
}
}
| 8
|
Kotlin
|
0
| 2
|
ef3d037fbc4a2997e1339f9419d13d56d1a9f379
| 26,858
|
Sleepest
|
MIT License
|
app/src/main/java/com/example/tictactoe/ui/board/GameBoard.kt
|
Rahula-12
| 695,938,700
| false
|
{"Kotlin": 59476}
|
package com.example.tictactoe.ui.board
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
@Composable
fun GameBoard(
modifier:Modifier=Modifier,
direction:Int=-1
){
Canvas(
modifier = modifier
.fillMaxSize()
.background(Color.Transparent)
,
onDraw = {
drawLine(
color = Color.DarkGray,
strokeWidth=30f,
start = Offset(size.width*1/3,0f),
end = Offset(size.width*1/3,size.height)
)
drawLine(
color = Color.DarkGray,
strokeWidth=30f,
start = Offset(size.width*2/3,0f),
end = Offset(size.width*2/3,size.height)
)
drawLine(
color = Color.DarkGray,
strokeWidth=30f,
start = Offset(0f,(size.height*1)/3),
end = Offset(size.width,(size.height*1)/3)
)
drawLine(
color = Color.DarkGray,
strokeWidth=30f,
start = Offset(0f,(size.height*2)/3),
end = Offset(size.width,(size.height*2)/3)
)
when(direction){
1->drawLine(
color= Color.Red,
strokeWidth=20f,
start = Offset(0f,size.height/6),
end= Offset(size.width,size.height/6)
)
2->drawLine(
color= Color.Red,
strokeWidth=20f,
start = Offset(0f,size.height/2),
end= Offset(size.width,size.height/2)
)
3->drawLine(
color= Color.Red,
strokeWidth=20f,
start = Offset(0f,size.height*5/6),
end= Offset(size.width,size.height*5/6)
)
4->drawLine(
color= Color.Red,
strokeWidth=20f,
start = Offset(size.width/6,0f),
end= Offset(size.width/6,size.height)
)
5->drawLine(
color= Color.Red,
strokeWidth=20f,
start = Offset(size.width/2,0f),
end= Offset(size.width/2,size.height)
)
6->drawLine(
color= Color.Red,
strokeWidth=20f,
start = Offset(size.width*5/6,0f),
end= Offset(size.width*5/6,size.height)
)
7->drawLine(
color= Color.Red,
strokeWidth=20f,
start=Offset(0f,0f),
end=Offset(size.width,size.height)
)
8->drawLine(
color= Color.Red,
strokeWidth=20f,
start=Offset(0f,size.height),
end=Offset(size.width,0f)
)
}
}
)
}
@Preview
@Composable
fun Previews(){
GameBoard()
}
| 0
|
Kotlin
|
0
| 0
|
27867eb2bdb4dc42b3245753161e71886b068050
| 3,779
|
TicTacToeGame
|
MIT License
|
kotlin/examples/src/main/kotlin/examples/utils/visualization/meshvis2d/viewport/Viewport.kt
|
facebookresearch
| 495,505,391
| 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 examples.utils.visualization.meshvis2d.viewport
import examples.utils.visualization.meshvis2d.math.Vector2
abstract class Viewport(
val width: Int,
val height: Int,
var camera: Camera = Camera(),
private var _worldCenter: Vector2 = Vector2(0f, 0f),
) {
val worldCenter get() = _worldCenter
fun lookAt(worldCenter: Vector2) {
camera = camera.lookAtWithWorldToViewportScale(
worldCenter, camera.inferWorldToViewportScale(),
width, height
)
_worldCenter = worldCenter
}
fun lookAt(worldCenter: Vector2, worldWidth: Float) {
camera = camera.lookAtWithWorldWidth(worldCenter, worldWidth, width, height)
this._worldCenter = worldCenter
}
fun zoom(viewportCenter: Vector2, dScale: Float) {
val worldToViewportScale = camera.inferWorldToViewportScale()
val newWorldToViewportScale = worldToViewportScale + dScale
camera = camera.lookAtViewportPos(viewportCenter, newWorldToViewportScale)
_worldCenter = camera.viewportToWorld(
Vector2(width * 0.5f, height * 0.5f)
)
}
abstract fun show(
initialScene: Scene,
update: (Scene, List<DragEvent>) -> Scene
)
}
| 62
|
Jupyter Notebook
|
3
| 55
|
710f403719bb89e3bcf00d72e53313f8571d5230
| 1,434
|
diffkt
|
MIT License
|
app/src/main/java/org/tokend/template/features/clients/repository/CompanyClientsRepository.kt
|
tokend
| 192,905,357
| false
|
{"Kotlin": 1830732, "HTML": 58776, "Java": 21685}
|
package org.tokend.template.features.clients.repository
import io.reactivex.Single
import io.reactivex.functions.BiFunction
import org.tokend.rx.extensions.toSingle
import org.tokend.sdk.api.base.model.DataPage
import org.tokend.sdk.api.base.params.PagingOrder
import org.tokend.sdk.api.base.params.PagingParamsV2
import org.tokend.sdk.api.integrations.dns.model.ClientBalanceResource
import org.tokend.sdk.api.integrations.dns.model.ClientResource
import org.tokend.sdk.api.integrations.dns.params.ClientsPageParams
import org.tokend.template.data.repository.base.pagination.PagedDataRepository
import org.tokend.template.di.providers.ApiProvider
import org.tokend.template.di.providers.WalletInfoProvider
import org.tokend.template.features.assets.storage.AssetsRepository
import org.tokend.template.features.clients.model.CompanyClientRecord
class CompanyClientsRepository(
private val apiProvider: ApiProvider,
private val walletInfoProvider: WalletInfoProvider,
private val assetsRepository: AssetsRepository
) : PagedDataRepository<CompanyClientRecord>(PagingOrder.DESC, null) {
override fun getRemotePage(nextCursor: Long?,
requiredOrder: PagingOrder): Single<DataPage<CompanyClientRecord>> {
val accountId = walletInfoProvider.getWalletInfo()?.accountId
?: return Single.error(IllegalStateException("No wallet info found"))
val signedApi = apiProvider.getSignedApi()
?: return Single.error(IllegalStateException("No signed API instance found"))
val getPage = signedApi
.integrations
.dns
.getBusinessClients(
businessId = accountId,
params = ClientsPageParams(
include = listOf(ClientsPageParams.Includes.BALANCES),
pagingParams = PagingParamsV2(
order = requiredOrder,
page = nextCursor?.toString(),
limit = pageLimit
)
)
)
.toSingle()
val updateAssets = assetsRepository.updateIfNotFreshDeferred().toSingleDefault(true)
return Single.zip(
getPage,
updateAssets,
BiFunction { page: DataPage<ClientResource>, _: Boolean -> page }
)
.flatMap { clientsPage ->
assetsRepository.ensureAssets(
clientsPage
.items
.map {
it.balances?.map(ClientBalanceResource::getAssetCode)
?: emptyList()
}
.flatten()
)
.map { clientsPage to it }
}
.map { (clientsPage, assetsMap) ->
DataPage(
clientsPage.nextCursor,
clientsPage.items.map { CompanyClientRecord(it, assetsMap)},
clientsPage.isLast
)
}
}
}
| 1
|
Kotlin
|
1
| 6
|
05bb971859713830a9c229206dc9f525ce80f754
| 3,374
|
conto-android-client
|
Apache License 2.0
|
services/csm.cloud.project.activity/src/main/kotlin/com/bosch/pt/csm/cloud/projectmanagement/user/repository/impl/UserRepositoryExtensionImpl.kt
|
boschglobal
| 805,348,245
| false
|
{"Kotlin": 13156190, "HTML": 274761, "Go": 184388, "HCL": 158560, "Shell": 117666, "Java": 52634, "Python": 51306, "Dockerfile": 10348, "Vim Snippet": 3969, "CSS": 344}
|
/*
* ************************************************************************
*
* Copyright: <NAME> Power Tools GmbH, 2018 - 2021
*
* ************************************************************************
*/
package com.bosch.pt.csm.cloud.projectmanagement.user.repository.impl
import com.bosch.pt.csm.cloud.projectmanagement.common.repository.AttributeNames.Common.ID
import com.bosch.pt.csm.cloud.projectmanagement.common.repository.AttributeNames.User.DISPLAY_NAME
import com.bosch.pt.csm.cloud.projectmanagement.common.repository.AttributeNames.User.USER_PICTURE_IDENTIFIER
import com.bosch.pt.csm.cloud.projectmanagement.common.repository.Collections.USER_STATE
import com.bosch.pt.csm.cloud.projectmanagement.user.model.User
import com.bosch.pt.csm.cloud.projectmanagement.user.repository.UserRepositoryExtension
import java.util.UUID
import org.springframework.data.mongodb.core.MongoOperations
import org.springframework.data.mongodb.core.query.Criteria.where
import org.springframework.data.mongodb.core.query.Query
import org.springframework.data.mongodb.core.query.Update
open class UserRepositoryExtensionImpl(private val mongoOperations: MongoOperations) :
UserRepositoryExtension {
override fun findDisplayNameCached(identifier: UUID): String? {
val query = findUserQuery(identifier).apply { fields().include(DISPLAY_NAME).exclude(ID) }
return mongoOperations.findOne(query, FindDisplayNameProjection::class.java, USER_STATE)
?.displayName
}
override fun deleteUser(identifier: UUID) {
mongoOperations.remove(findUserQuery(identifier), USER_STATE)
}
override fun savePicture(identifier: UUID, pictureIdentifier: UUID) {
mongoOperations.updateFirst(
findUserQuery(identifier),
Update().set(USER_PICTURE_IDENTIFIER, pictureIdentifier),
User::class.java)
}
override fun deletePicture(identifier: UUID) {
mongoOperations.updateFirst(
findUserQuery(identifier), Update().unset(USER_PICTURE_IDENTIFIER), User::class.java)
}
private fun findUserQuery(identifier: UUID) = Query().addCriteria(where(ID).`is`(identifier))
data class FindDisplayNameProjection(val displayName: String? = null)
}
| 0
|
Kotlin
|
3
| 9
|
9f3e7c4b53821bdfc876531727e21961d2a4513d
| 2,207
|
bosch-pt-refinemysite-backend
|
Apache License 2.0
|
app/src/main/java/com/example/composepokedex/data/remote/dto/GenerationViii.kt
|
zprima
| 486,766,592
| false
|
{"Kotlin": 47829}
|
package com.example.composepokedex.data.remote.dto
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class GenerationViii(
@SerialName("icons")
val icons: IconsX?
)
| 0
|
Kotlin
|
0
| 0
|
22c4188b0070a2e6e30184003d065edf8e4be40c
| 226
|
compose-pokedex-clean
|
MIT License
|
src/jvmMain/kotlin/com/sdercolin/vlabeler/ui/App.kt
|
sdercolin
| 503,365,242
| false
| null |
package com.sdercolin.vlabeler.ui
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.MaterialTheme
import androidx.compose.material.SnackbarHostState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import com.sdercolin.vlabeler.model.Plugin
import com.sdercolin.vlabeler.ui.common.CircularProgress
import com.sdercolin.vlabeler.ui.common.WarningTextStyle
import com.sdercolin.vlabeler.ui.dialog.EmbeddedDialog
import com.sdercolin.vlabeler.ui.dialog.QuickLaunchManagerDialog
import com.sdercolin.vlabeler.ui.dialog.TrackingSettingsDialog
import com.sdercolin.vlabeler.ui.dialog.WarningDialog
import com.sdercolin.vlabeler.ui.dialog.customization.CustomizableItemManagerDialog
import com.sdercolin.vlabeler.ui.dialog.importentries.ImportEntriesDialog
import com.sdercolin.vlabeler.ui.dialog.plugin.MacroPluginDialog
import com.sdercolin.vlabeler.ui.dialog.plugin.MacroPluginReportDialog
import com.sdercolin.vlabeler.ui.dialog.preferences.PreferencesDialog
import com.sdercolin.vlabeler.ui.dialog.prerender.PrerenderDialog
import com.sdercolin.vlabeler.ui.dialog.project.ProjectSettingDialog
import com.sdercolin.vlabeler.ui.dialog.sample.SampleListDialog
import com.sdercolin.vlabeler.ui.dialog.syncsample.EntrySampleSyncDialog
import com.sdercolin.vlabeler.ui.editor.Editor
import com.sdercolin.vlabeler.ui.starter.ProjectCreator
import com.sdercolin.vlabeler.ui.starter.Starter
import com.sdercolin.vlabeler.ui.string.*
import com.sdercolin.vlabeler.util.getLocalizedMessage
import com.sdercolin.vlabeler.video.Video
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
@Composable
fun App(
mainScope: CoroutineScope,
appState: AppState,
) {
LaunchedEffect(appState) {
appState.checkAutoSavedProject()
}
LaunchedEffect(appState, appState.anyDialogOpening()) {
if (appState.anyDialogOpening()) return@LaunchedEffect
if (appState.trackingState.hasNotAskedForTrackingPermission()) {
appState.openTrackingSettingsDialog()
} else if (appState.appRecordStore.value.hasCheckedRosettaCompatibleMode.not()) {
appState.showCompatibleModeWarningIfNeeded()
}
}
LaunchedEffect(appState.appConf.autoSave) {
appState.enableAutoSaveProject(appState.appConf.autoSave, appState)
}
LaunchedEffect(appState) {
appState.checkUpdates(isAuto = true)
}
Box(Modifier.fillMaxSize().background(MaterialTheme.colors.background)) {
when (val screen = appState.screen) {
is Screen.Starter -> Starter(mainScope, appState)
is Screen.ProjectCreator ->
ProjectCreator(
appState = appState,
cancel = { appState.closeProjectCreator() },
activeLabelerConfs = appState.activeLabelerConfs,
activeTemplatePlugins = appState.getActivePlugins(Plugin.Type.Template),
appRecordStore = appState.appRecordStore,
initialFile = screen.initialFile,
)
is Screen.Editor -> Editor(screen.state, appState)
}
if (appState.isShowingProjectSettingDialog) {
ProjectSettingDialog(appState, finish = { appState.closeProjectSettingDialog() })
}
if (appState.isShowingPrerenderDialog) {
appState.editor?.let { editor ->
PrerenderDialog(
editor.project,
appState.appConf,
editor.chartStore,
onError = { if (it !is CancellationException) appState.showError(it) },
finish = { appState.closePrerenderDialog() },
)
}
}
if (appState.isShowingEntrySampleSyncDialog) {
EntrySampleSyncDialog(
appState.appConf,
appState,
onError = { if (it !is CancellationException) appState.showError(it) },
finish = { appState.closeEntrySampleSyncDialog() },
)
}
if (appState.isShowingSampleListDialog) {
appState.editor?.let { SampleListDialog(it, finish = { appState.closeSampleListDialog() }) }
}
if (appState.isShowingPreferencesDialog) {
PreferencesDialog(appState)
}
appState.macroPluginShownInDialog?.let { args ->
val snackbarHostState = remember { SnackbarHostState() }
MacroPluginDialog(
appConf = appState.appConf,
appRecordStore = appState.appRecordStore,
snackbarHostState = snackbarHostState,
args = args,
project = appState.requireProject(),
submit = {
mainScope.launch {
appState.closeMacroPluginDialog()
if (it != null) {
appState.showProgress()
withContext(Dispatchers.IO) {
args.plugin.saveMacroParams(
it,
args.plugin.getSavedParamsFile(),
appState.appRecordStore,
slot = args.slot,
)
appState.executeMacroPlugin(args.plugin, it, args.slot)
}
appState.hideProgress()
}
}
},
save = {
mainScope.launch(Dispatchers.IO) {
appState.updateMacroPluginDialogInputParams(it)
args.plugin.saveMacroParams(
it,
args.plugin.getSavedParamsFile(),
appState.appRecordStore,
slot = args.slot,
)
}
},
load = { appState.updateMacroPluginDialogInputParams(it) },
)
}
appState.macroPluginReport?.let { report ->
MacroPluginReportDialog(
report = report,
finish = { appState.closeMacroPluginReport() },
)
}
appState.customizableItemManagerTypeShownInDialog?.let {
CustomizableItemManagerDialog(
it,
appState,
)
}
if (appState.isShowingQuickLaunchManagerDialog) {
QuickLaunchManagerDialog(appState = appState)
}
appState.embeddedDialog?.let { request ->
EmbeddedDialog(request)
}
if (appState.isShowingTrackingSettingsDialog) {
TrackingSettingsDialog(
appState.trackingState,
finish = {
appState.closeTrackingSettingsDialog()
appState.trackingState.finishSettings()
},
)
}
if (appState.isShowingVideo) {
Video(
videoState = appState.videoState,
playerState = appState.playerState,
projectStore = appState,
appConf = appState.appConf,
)
}
appState.importEntriesDialogArgs?.let {
ImportEntriesDialog(
finish = { appState.closeImportEntriesDialog() },
projectStore = appState,
args = it,
)
}
appState.error?.let { error ->
WarningDialog(
message = error.getLocalizedMessage(LocalLanguage.current),
finish = {
appState.handleErrorPendingAction(appState.errorPendingAction)
appState.clearError()
},
style = WarningTextStyle.Error,
)
}
}
if (appState.isBusy) {
CircularProgress()
}
}
| 8
| null |
22
| 147
|
f4e47b6c386e1446f9e311549156a6d29aa8d3da
| 8,360
|
vlabeler
|
Apache License 2.0
|
app/src/main/java/com/example/missingpets/utils/storage/preferences/Prefs.kt
|
UTN-FRBA-Mobile
| 409,980,590
| false
|
{"Kotlin": 140503, "Java": 13882}
|
package com.example.missingpets.utils.storage.preferences
import android.content.Context
import android.content.SharedPreferences
class Prefs (context: Context) {
val PREFS_NAME = "com.cursokotlin.sharedpreferences"
val SHARED_LATITUDE = "shared_latitude"
val SHARED_LONGITUDE = "shared_longitude"
val prefs: SharedPreferences = context.getSharedPreferences(PREFS_NAME, 0)
var latitude: Float
get() = prefs.getFloat(SHARED_LATITUDE, 0f)
set(value) = prefs.edit().putFloat(SHARED_LATITUDE, value).apply()
var longitude: Float
get() = prefs.getFloat(SHARED_LONGITUDE, 0f)
set(value) = prefs.edit().putFloat(SHARED_LONGITUDE, value).apply()
fun inicializar(){
prefs.edit().putFloat(SHARED_LATITUDE, 0f).apply()
prefs.edit().putFloat(SHARED_LONGITUDE, 0f).apply()
}
}
| 0
|
Kotlin
|
0
| 0
|
e2c3332e28877d23b15ce92bc29adda82e707bee
| 850
|
MissingPets
|
MIT License
|
app/src/main/java/edu/rosehulman/andersc7/androidsalewaypoint/ui/listing/ListingViewHolder.kt
|
petersjl
| 468,592,926
| false
|
{"Kotlin": 52083}
|
package edu.rosehulman.andersc7.androidsalewaypoint.ui.listing
import android.graphics.Color
import android.opengl.Visibility
import android.view.View
import androidx.core.graphics.drawable.DrawableCompat
import androidx.core.view.isVisible
import androidx.recyclerview.widget.RecyclerView
import edu.rosehulman.andersc7.androidsalewaypoint.R
import kotlinx.android.synthetic.main.item_game.view.*
import kotlinx.android.synthetic.main.item_listing.view.*
import kotlin.math.floor
class ListingViewHolder(itemView: View, var adapter: ListingAdapter) :
RecyclerView.ViewHolder(itemView) {
var view: View = itemView
fun bind(listing: Listing) {
val img = when (listing.store) {
StoreType.STEAM -> R.drawable.ic_steam
StoreType.PLAYSTATION -> R.drawable.ic_playstation
StoreType.XBOX -> R.drawable.ic_xbox
StoreType.NINTENDO -> R.drawable.ic_nintendo
StoreType.ITCH -> R.drawable.ic_itch
}
val sale = (listing.sale * 100).toInt()
this.view.listing_store.setImageResource(img)
this.view.listing_price_default.text = String.format("$%.2f", listing.price)
this.view.listing_sale.text = String.format("%d%% Off",(listing.sale * 100).toInt())
val priceSale = floor((listing.price * (1 - listing.sale)) * 100) / 100
this.view.listing_price_sale.text = String.format("$%.2f", priceSale)
if (sale == 0){
this.view.listing_sale.isVisible = false
this.view.listing_sale.background.setTint(Color.parseColor("#202125"))
this.view.listing_price_sale.isVisible = false
}else{
this.view.listing_sale.isVisible = true
this.view.listing_sale.background.setTint(Color.parseColor("#00A273"))
this.view.listing_price_sale.isVisible = true
}
}
}
| 0
|
Kotlin
|
0
| 1
|
94ed0dfca2ff57478e9cf9609f39f6111f185913
| 1,684
|
AndroidSaleWaypoint
|
Apache License 2.0
|
plugins/kotlin/idea/tests/testData/quickfix/suppress/inspections/codeStructure/parameterSuppressedOnParameter.kt
|
JetBrains
| 2,489,216
| false
| null |
// "Suppress 'DelegationToVarProperty' for parameter text" "true"
class ParameterSuppressedOnParameter(var <caret>text: CharSequence): CharSequence by text
// K1_TOOL: org.jetbrains.kotlin.idea.codeInsight.inspections.shared.DelegationToVarPropertyInspection
// K2_TOOL: org.jetbrains.kotlin.idea.codeInsight.inspections.shared.DelegationToVarPropertyInspection
// FUS_K2_QUICKFIX_NAME: com.intellij.codeInspection.SuppressIntentionActionFromFix
// FUS_QUICKFIX_NAME: com.intellij.codeInspection.SuppressIntentionActionFromFix
| 284
| null |
5162
| 16,707
|
def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0
| 529
|
intellij-community
|
Apache License 2.0
|
src/main/java/com/github/ai/autokpass/presentation/ui/core/strings/StringResourcesImpl.kt
|
aivanovski
| 473,610,974
| false
|
{"Kotlin": 288569}
|
package com.github.ai.autokpass.presentation.ui.core.strings
import java.util.Locale
import java.util.ResourceBundle
class StringResourcesImpl : StringResources {
private val resourceMap = ResourceBundleMap(
resources = ResourceBundle.getBundle("strings", Locale.getDefault())
)
override val appName: String by resourceMap
override val cancel: String by resourceMap
override val password: String by resourceMap
override val unlock: String by resourceMap
override val exit: String by resourceMap
override val selectPattern: String by resourceMap
override val selectEntry: String by resourceMap
override val autotyping: String by resourceMap
override val autotypeSelectWindowMessage: String by resourceMap
override val autotypeCountDownMessage: String by resourceMap
override val invalidCredentialsMessage: String by resourceMap
override val greetingsMessage: String by resourceMap
override val noEntriesInDatabase: String by resourceMap
override val entryIsEmpty: String by resourceMap
override val errorFailedToDetermineOsType: String by resourceMap
override val errorFailedToCompileAutotypeSequence: String by resourceMap
override val errorHasBeenOccurred: String by resourceMap
override val errorFailedToGetWindowName: String by resourceMap
override val errorFailedToGetWindowFocus: String by resourceMap
override val errorWindowFocusAwaitTimeout: String by resourceMap
override val errorFailedToParseConfigFile: String by resourceMap
override val errorNoArgumentsWereSpecified: String by resourceMap
override val errorOptionCanNotBeEmpty: String by resourceMap
override val errorFileDoesNotExist: String by resourceMap
override val errorFileIsNotFile: String by resourceMap
override val errorFailedToParseArgument: String by resourceMap
override val errorFailedToGetEnvironmentVariable: String by resourceMap
}
| 1
|
Kotlin
|
0
| 1
|
4f9d3bebbde84056b8d721dae71aca15932d0b5c
| 1,941
|
autokpass
|
Apache License 2.0
|
compiler/testData/codegen/box/multiDecl/ValCapturedInFunctionLiteral.kt
|
udalov
| 10,645,710
| false
|
{"Java": 9931656, "Kotlin": 2142480, "JavaScript": 942412, "C++": 613791, "C": 193807, "Objective-C": 22634, "Shell": 12589, "Groovy": 1267}
|
class A {
fun component1() = 1
fun component2() = 2
}
fun box() : String {
var (a, b) = A()
a = b
return if (a == 2 && b == 2) "OK" else "fail"
}
| 0
|
Java
|
1
| 6
|
3958b4a71d8f9a366d8b516c4c698aae80ecfe57
| 167
|
kotlin-objc-diploma
|
Apache License 2.0
|
compiler/testData/codegen/box/multiDecl/ValCapturedInFunctionLiteral.kt
|
udalov
| 10,645,710
| false
|
{"Java": 9931656, "Kotlin": 2142480, "JavaScript": 942412, "C++": 613791, "C": 193807, "Objective-C": 22634, "Shell": 12589, "Groovy": 1267}
|
class A {
fun component1() = 1
fun component2() = 2
}
fun box() : String {
var (a, b) = A()
a = b
return if (a == 2 && b == 2) "OK" else "fail"
}
| 0
|
Java
|
1
| 6
|
3958b4a71d8f9a366d8b516c4c698aae80ecfe57
| 167
|
kotlin-objc-diploma
|
Apache License 2.0
|
tiny-event-sourcing-lib/src/main/kotlin/ru/quipy/streams/AggregateSubscriptionsManager.kt
|
andrsuh
| 498,475,206
| false
|
{"Kotlin": 420728, "PLpgSQL": 1840, "Dockerfile": 242}
|
package ru.quipy.streams
import org.slf4j.LoggerFactory
import org.springframework.core.annotation.AnnotationUtils
import ru.quipy.core.AggregateRegistry
import ru.quipy.domain.Aggregate
import ru.quipy.domain.Event
import ru.quipy.mapper.EventMapper
import ru.quipy.streams.EventStreamSubscriber.EventStreamSubscriptionBuilder
import ru.quipy.streams.annotation.AggregateSubscriber
import ru.quipy.streams.annotation.RetryConf
import ru.quipy.streams.annotation.RetryFailedStrategy
import ru.quipy.streams.annotation.SubscribeEvent
import kotlin.reflect.KClass
import kotlin.reflect.full.findAnnotations
import kotlin.reflect.full.isSuperclassOf
import kotlin.reflect.full.memberFunctions
/**
* Creates [EventStreamSubscriber]s holds them and allows to destroy them all.
*
* Using this class is a preferable way to create and initialize [EventStreamSubscriber]s.
*
* There are two options to do that:
* - Pass some [Any] object of class that is marked with [AggregateSubscriber] to [AggregateSubscriptionsManager.subscribe].
* [AggregateSubscriptionsManager] will create a subscriber for the class.
* Also, the class will be automatically scanned to find methods that are marked with [SubscribeEvent] and create handlers
* for subscriber to deal with events of type that matches the argument type of the method.
* - Use [AggregateSubscriptionsManager.createSubscriber] method which alloes you to instantiate subscriber with
* explicitly passed config and configure handlers.
*/
class AggregateSubscriptionsManager(
private val eventsStreamManager: AggregateEventStreamManager,
private val aggregateRegistry: AggregateRegistry,
private val eventMapper: EventMapper
) {
private val logger = LoggerFactory.getLogger(AggregateSubscriptionsManager::class.java)
private val subscribers: MutableList<EventStreamSubscriber<*>> = mutableListOf()
/**
* Subscribes given object to the aggregate event stream.
*
* Automatically scans the class
* - Looking for [AggregateSubscriber] annotation. If not found throw the exception.
* - Looking for methods in class that are marked with [SubscribeEvent] and analyses its arguments that should be a
* type of aggregate [Event].
* - Creates the subscriber of the aggregate and configure the corresponding methods-handlers
* - Starts the subscriber
*/
@OptIn(ExperimentalStdlibApi::class)
fun <A : Aggregate> subscribe(subscriberInstance: Any) {
val subscriberClass = subscriberInstance::class
val subscriberInfo = AnnotationUtils.findAnnotation(subscriberClass.java, AggregateSubscriber::class.java)
?: throw IllegalStateException("No annotation ${AggregateSubscriber::class.simpleName} provided on class ${subscriberClass.simpleName}")
val aggregateClass = try {
subscriberInfo.aggregateClass as KClass<A>
} catch (e: ClassCastException) {
throw IllegalArgumentException(
"Type parameter (aggregate type) doesn't match those provided " +
"in ${AggregateSubscriber::class.simpleName} annotation"
)
}
val eventInfo = aggregateRegistry.getEventInfo(aggregateClass)
?: throw IllegalArgumentException("Couldn't find aggregate class ${aggregateClass.simpleName} in registry")
val streamName = subscriberInfo.subscriberName.ifBlank {
throw IllegalStateException("There is no name for subscriber provided in ${AggregateSubscriber::class.simpleName} annotation")
}
logger.info("Start creating subscription to aggregate: ${aggregateClass.simpleName} for ${subscriberClass.simpleName}")
val subscriptionBuilder =
eventsStreamManager.createEventStream(streamName, aggregateClass, subscriberInfo.retry)
.toSubscriptionBuilder(eventMapper, eventInfo::getEventTypeByName)
subscriberClass.memberFunctions.filter { // method has annotation filter
it.findAnnotations(SubscribeEvent::class).size == 1
}.filter {// method has only one arg and this is subtype of Event filter
it.parameters.size == 2
&& Event::class.isSuperclassOf(it.parameters[1].type.classifier as KClass<*>)
}.filter { // event (method arg) is parametrised with correct aggregate type filter
val eventType = it.parameters[1].type.classifier as KClass<Event<*>>
eventType.supertypes.size == 1
&& (eventType.supertypes[0].arguments[0].type?.classifier) == aggregateClass
}.map {
it to (it.parameters[1].type.classifier as KClass<Event<A>>)
}.forEach { (method, event) ->
subscriptionBuilder.`when`(event) {
method.call(subscriberInstance, it)
}
logger.info(
"Subscribing method ${subscriberClass.simpleName}#${method.name} " +
"to event ${event.simpleName} of aggregate ${aggregateClass.simpleName}"
)
}
subscriptionBuilder.subscribe().also {
subscribers.add(it)
}
}
/**
* Creates the subscriber of the aggregate event stream configuring it with an explicitly passed parameters.
*
* [handlersBlock] - lambda function. Library passes the newly created object of [EventHandlersRegistrar] as a
* receiver of the lambda. This [EventHandlersRegistrar] contains methods that help you to define handlers for
* certain types of events. So that you could use following syntax to create and initialize subscribers:
*
* ```
* subscriptionsManager.createSubscriber(UserAggregate::class, "payment-service:user-view-subscriber") {
* `when`(UserCreatedEvent::class) { event ->
* logger.info("User created: {}", event.userName)
* }
* `when`(UserNameChanged`event::class) { event ->
* logger.info("User {} name changed from {} to {} ", event.userId, event.oldName, event.updatedName)
* }
* }
* ```
*/
fun <A : Aggregate> createSubscriber(
aggregateClass: KClass<A>,
subscriberName: String,
retryConf: RetryConf = RetryConf(3, RetryFailedStrategy.SKIP_EVENT),
handlersBlock: EventHandlersRegistrar<A>.() -> Unit
): EventStreamSubscriber<A> {
logger.info("Start creating subscription to aggregate: ${aggregateClass.simpleName}, subscriber name $subscriberName")
val eventInfo = aggregateRegistry.getEventInfo(aggregateClass)
?: throw IllegalArgumentException("Couldn't find aggregate class ${aggregateClass.simpleName} in registry")
val subscriptionBuilder =
eventsStreamManager.createEventStream(subscriberName, aggregateClass, retryConf)
.toSubscriptionBuilder(eventMapper, eventInfo::getEventTypeByName)
handlersBlock.invoke(EventHandlersRegistrar(subscriptionBuilder)) // todo sukhoa maybe extension? .createRegistrar?
return subscriptionBuilder.subscribe().also {
subscribers.add(it)
}
}
fun destroy() {
subscribers.forEach {
it.stopAndDestroy()
}
}
/**
* This class is used to pass as a receiver (like implicit this) to the trailing lambda parameter of the
* [AggregateSubscriptionsManager.createSubscriber] method. It allows the caller code to invoke its
* [EventHandlersRegistrar.when] method to register the handlers for the aggregate events.
*
* This class is supposed for only helping purposes. It abstracts away the process of creating the subscriber and
* make syntax more concise.
*/
class EventHandlersRegistrar<A : Aggregate>(
private val subscriptionBuilder: EventStreamSubscriptionBuilder<A>
) {
fun <E : Event<A>> `when`(
eventType: KClass<E>,
eventHandler: suspend (E) -> Unit
) {
subscriptionBuilder.`when`(eventType, eventHandler)
}
}
}
| 14
|
Kotlin
|
8
| 34
|
880796f04bb6e27aab615c8efccd709d5ca22193
| 8,037
|
tiny-event-sourcing
|
Apache License 2.0
|
analytics/src/main/java/io/appmetrica/analytics/impl/core/CoreImplFirstCreateTaskLauncher.kt
|
appmetrica
| 650,662,094
| false
| null |
package io.appmetrica.analytics.impl.core
import io.appmetrica.analytics.impl.GlobalServiceLocator
import io.appmetrica.analytics.logger.appmetrica.internal.DebugLogger
import java.util.concurrent.TimeUnit
private const val TAG = "[MetricaCoreImplFirstCreateTaskLauncher]"
class CoreImplFirstCreateTaskLauncher(private val tasks: List<Runnable>) : Runnable {
private val executor = GlobalServiceLocator.getInstance().serviceExecutorProvider.defaultExecutor
private val activationBarrier = GlobalServiceLocator.getInstance().activationBarrier
override fun run() {
DebugLogger.info(TAG, "Run and subscriber on activation barrier")
activationBarrier.subscribe(TimeUnit.SECONDS.toMillis(10), executor) {
DebugLogger.info(TAG, "Run ${tasks.size} tasks")
tasks.forEach { it.run() }
}
}
}
| 3
| null |
5
| 54
|
81572296e16423617822fbc19c2465d6b7b4713e
| 851
|
appmetrica-sdk-android
|
MIT License
|
src/commonMain/kotlin/com/jeffpdavidson/kotwords/formats/unidecode/xb9.kt
|
jpd236
| 143,651,464
| false
|
{"Kotlin": 4431127, "HTML": 41941, "Rouge": 3731, "Perl": 1705, "Shell": 744, "JavaScript": 618}
|
package com.jeffpdavidson.kotwords.formats.unidecode
internal val xb9 = arrayOf(
// 0xb900: 뤀 => ruk
"\u0072\u0075\u006b",
// 0xb901: 뤁 => rut
"\u0072\u0075\u0074",
// 0xb902: 뤂 => rup
"\u0072\u0075\u0070",
// 0xb903: 뤃 => ruh
"\u0072\u0075\u0068",
// 0xb904: 뤄 => rweo
"\u0072\u0077\u0065\u006f",
// 0xb905: 뤅 => rweog
"\u0072\u0077\u0065\u006f\u0067",
// 0xb906: 뤆 => rweogg
"\u0072\u0077\u0065\u006f\u0067\u0067",
// 0xb907: 뤇 => rweogs
"\u0072\u0077\u0065\u006f\u0067\u0073",
// 0xb908: 뤈 => rweon
"\u0072\u0077\u0065\u006f\u006e",
// 0xb909: 뤉 => rweonj
"\u0072\u0077\u0065\u006f\u006e\u006a",
// 0xb90a: 뤊 => rweonh
"\u0072\u0077\u0065\u006f\u006e\u0068",
// 0xb90b: 뤋 => rweod
"\u0072\u0077\u0065\u006f\u0064",
// 0xb90c: 뤌 => rweol
"\u0072\u0077\u0065\u006f\u006c",
// 0xb90d: 뤍 => rweolg
"\u0072\u0077\u0065\u006f\u006c\u0067",
// 0xb90e: 뤎 => rweolm
"\u0072\u0077\u0065\u006f\u006c\u006d",
// 0xb90f: 뤏 => rweolb
"\u0072\u0077\u0065\u006f\u006c\u0062",
// 0xb910: 뤐 => rweols
"\u0072\u0077\u0065\u006f\u006c\u0073",
// 0xb911: 뤑 => rweolt
"\u0072\u0077\u0065\u006f\u006c\u0074",
// 0xb912: 뤒 => rweolp
"\u0072\u0077\u0065\u006f\u006c\u0070",
// 0xb913: 뤓 => rweolh
"\u0072\u0077\u0065\u006f\u006c\u0068",
// 0xb914: 뤔 => rweom
"\u0072\u0077\u0065\u006f\u006d",
// 0xb915: 뤕 => rweob
"\u0072\u0077\u0065\u006f\u0062",
// 0xb916: 뤖 => rweobs
"\u0072\u0077\u0065\u006f\u0062\u0073",
// 0xb917: 뤗 => rweos
"\u0072\u0077\u0065\u006f\u0073",
// 0xb918: 뤘 => rweoss
"\u0072\u0077\u0065\u006f\u0073\u0073",
// 0xb919: 뤙 => rweong
"\u0072\u0077\u0065\u006f\u006e\u0067",
// 0xb91a: 뤚 => rweoj
"\u0072\u0077\u0065\u006f\u006a",
// 0xb91b: 뤛 => rweoc
"\u0072\u0077\u0065\u006f\u0063",
// 0xb91c: 뤜 => rweok
"\u0072\u0077\u0065\u006f\u006b",
// 0xb91d: 뤝 => rweot
"\u0072\u0077\u0065\u006f\u0074",
// 0xb91e: 뤞 => rweop
"\u0072\u0077\u0065\u006f\u0070",
// 0xb91f: 뤟 => rweoh
"\u0072\u0077\u0065\u006f\u0068",
// 0xb920: 뤠 => rwe
"\u0072\u0077\u0065",
// 0xb921: 뤡 => rweg
"\u0072\u0077\u0065\u0067",
// 0xb922: 뤢 => rwegg
"\u0072\u0077\u0065\u0067\u0067",
// 0xb923: 뤣 => rwegs
"\u0072\u0077\u0065\u0067\u0073",
// 0xb924: 뤤 => rwen
"\u0072\u0077\u0065\u006e",
// 0xb925: 뤥 => rwenj
"\u0072\u0077\u0065\u006e\u006a",
// 0xb926: 뤦 => rwenh
"\u0072\u0077\u0065\u006e\u0068",
// 0xb927: 뤧 => rwed
"\u0072\u0077\u0065\u0064",
// 0xb928: 뤨 => rwel
"\u0072\u0077\u0065\u006c",
// 0xb929: 뤩 => rwelg
"\u0072\u0077\u0065\u006c\u0067",
// 0xb92a: 뤪 => rwelm
"\u0072\u0077\u0065\u006c\u006d",
// 0xb92b: 뤫 => rwelb
"\u0072\u0077\u0065\u006c\u0062",
// 0xb92c: 뤬 => rwels
"\u0072\u0077\u0065\u006c\u0073",
// 0xb92d: 뤭 => rwelt
"\u0072\u0077\u0065\u006c\u0074",
// 0xb92e: 뤮 => rwelp
"\u0072\u0077\u0065\u006c\u0070",
// 0xb92f: 뤯 => rwelh
"\u0072\u0077\u0065\u006c\u0068",
// 0xb930: 뤰 => rwem
"\u0072\u0077\u0065\u006d",
// 0xb931: 뤱 => rweb
"\u0072\u0077\u0065\u0062",
// 0xb932: 뤲 => rwebs
"\u0072\u0077\u0065\u0062\u0073",
// 0xb933: 뤳 => rwes
"\u0072\u0077\u0065\u0073",
// 0xb934: 뤴 => rwess
"\u0072\u0077\u0065\u0073\u0073",
// 0xb935: 뤵 => rweng
"\u0072\u0077\u0065\u006e\u0067",
// 0xb936: 뤶 => rwej
"\u0072\u0077\u0065\u006a",
// 0xb937: 뤷 => rwec
"\u0072\u0077\u0065\u0063",
// 0xb938: 뤸 => rwek
"\u0072\u0077\u0065\u006b",
// 0xb939: 뤹 => rwet
"\u0072\u0077\u0065\u0074",
// 0xb93a: 뤺 => rwep
"\u0072\u0077\u0065\u0070",
// 0xb93b: 뤻 => rweh
"\u0072\u0077\u0065\u0068",
// 0xb93c: 뤼 => rwi
"\u0072\u0077\u0069",
// 0xb93d: 뤽 => rwig
"\u0072\u0077\u0069\u0067",
// 0xb93e: 뤾 => rwigg
"\u0072\u0077\u0069\u0067\u0067",
// 0xb93f: 뤿 => rwigs
"\u0072\u0077\u0069\u0067\u0073",
// 0xb940: 륀 => rwin
"\u0072\u0077\u0069\u006e",
// 0xb941: 륁 => rwinj
"\u0072\u0077\u0069\u006e\u006a",
// 0xb942: 륂 => rwinh
"\u0072\u0077\u0069\u006e\u0068",
// 0xb943: 륃 => rwid
"\u0072\u0077\u0069\u0064",
// 0xb944: 륄 => rwil
"\u0072\u0077\u0069\u006c",
// 0xb945: 륅 => rwilg
"\u0072\u0077\u0069\u006c\u0067",
// 0xb946: 륆 => rwilm
"\u0072\u0077\u0069\u006c\u006d",
// 0xb947: 륇 => rwilb
"\u0072\u0077\u0069\u006c\u0062",
// 0xb948: 륈 => rwils
"\u0072\u0077\u0069\u006c\u0073",
// 0xb949: 륉 => rwilt
"\u0072\u0077\u0069\u006c\u0074",
// 0xb94a: 륊 => rwilp
"\u0072\u0077\u0069\u006c\u0070",
// 0xb94b: 륋 => rwilh
"\u0072\u0077\u0069\u006c\u0068",
// 0xb94c: 륌 => rwim
"\u0072\u0077\u0069\u006d",
// 0xb94d: 륍 => rwib
"\u0072\u0077\u0069\u0062",
// 0xb94e: 륎 => rwibs
"\u0072\u0077\u0069\u0062\u0073",
// 0xb94f: 륏 => rwis
"\u0072\u0077\u0069\u0073",
// 0xb950: 륐 => rwiss
"\u0072\u0077\u0069\u0073\u0073",
// 0xb951: 륑 => rwing
"\u0072\u0077\u0069\u006e\u0067",
// 0xb952: 륒 => rwij
"\u0072\u0077\u0069\u006a",
// 0xb953: 륓 => rwic
"\u0072\u0077\u0069\u0063",
// 0xb954: 륔 => rwik
"\u0072\u0077\u0069\u006b",
// 0xb955: 륕 => rwit
"\u0072\u0077\u0069\u0074",
// 0xb956: 륖 => rwip
"\u0072\u0077\u0069\u0070",
// 0xb957: 륗 => rwih
"\u0072\u0077\u0069\u0068",
// 0xb958: 류 => ryu
"\u0072\u0079\u0075",
// 0xb959: 륙 => ryug
"\u0072\u0079\u0075\u0067",
// 0xb95a: 륚 => ryugg
"\u0072\u0079\u0075\u0067\u0067",
// 0xb95b: 륛 => ryugs
"\u0072\u0079\u0075\u0067\u0073",
// 0xb95c: 륜 => ryun
"\u0072\u0079\u0075\u006e",
// 0xb95d: 륝 => ryunj
"\u0072\u0079\u0075\u006e\u006a",
// 0xb95e: 륞 => ryunh
"\u0072\u0079\u0075\u006e\u0068",
// 0xb95f: 륟 => ryud
"\u0072\u0079\u0075\u0064",
// 0xb960: 률 => ryul
"\u0072\u0079\u0075\u006c",
// 0xb961: 륡 => ryulg
"\u0072\u0079\u0075\u006c\u0067",
// 0xb962: 륢 => ryulm
"\u0072\u0079\u0075\u006c\u006d",
// 0xb963: 륣 => ryulb
"\u0072\u0079\u0075\u006c\u0062",
// 0xb964: 륤 => ryuls
"\u0072\u0079\u0075\u006c\u0073",
// 0xb965: 륥 => ryult
"\u0072\u0079\u0075\u006c\u0074",
// 0xb966: 륦 => ryulp
"\u0072\u0079\u0075\u006c\u0070",
// 0xb967: 륧 => ryulh
"\u0072\u0079\u0075\u006c\u0068",
// 0xb968: 륨 => ryum
"\u0072\u0079\u0075\u006d",
// 0xb969: 륩 => ryub
"\u0072\u0079\u0075\u0062",
// 0xb96a: 륪 => ryubs
"\u0072\u0079\u0075\u0062\u0073",
// 0xb96b: 륫 => ryus
"\u0072\u0079\u0075\u0073",
// 0xb96c: 륬 => ryuss
"\u0072\u0079\u0075\u0073\u0073",
// 0xb96d: 륭 => ryung
"\u0072\u0079\u0075\u006e\u0067",
// 0xb96e: 륮 => ryuj
"\u0072\u0079\u0075\u006a",
// 0xb96f: 륯 => ryuc
"\u0072\u0079\u0075\u0063",
// 0xb970: 륰 => ryuk
"\u0072\u0079\u0075\u006b",
// 0xb971: 륱 => ryut
"\u0072\u0079\u0075\u0074",
// 0xb972: 륲 => ryup
"\u0072\u0079\u0075\u0070",
// 0xb973: 륳 => ryuh
"\u0072\u0079\u0075\u0068",
// 0xb974: 르 => reu
"\u0072\u0065\u0075",
// 0xb975: 륵 => reug
"\u0072\u0065\u0075\u0067",
// 0xb976: 륶 => reugg
"\u0072\u0065\u0075\u0067\u0067",
// 0xb977: 륷 => reugs
"\u0072\u0065\u0075\u0067\u0073",
// 0xb978: 른 => reun
"\u0072\u0065\u0075\u006e",
// 0xb979: 륹 => reunj
"\u0072\u0065\u0075\u006e\u006a",
// 0xb97a: 륺 => reunh
"\u0072\u0065\u0075\u006e\u0068",
// 0xb97b: 륻 => reud
"\u0072\u0065\u0075\u0064",
// 0xb97c: 를 => reul
"\u0072\u0065\u0075\u006c",
// 0xb97d: 륽 => reulg
"\u0072\u0065\u0075\u006c\u0067",
// 0xb97e: 륾 => reulm
"\u0072\u0065\u0075\u006c\u006d",
// 0xb97f: 륿 => reulb
"\u0072\u0065\u0075\u006c\u0062",
// 0xb980: 릀 => reuls
"\u0072\u0065\u0075\u006c\u0073",
// 0xb981: 릁 => reult
"\u0072\u0065\u0075\u006c\u0074",
// 0xb982: 릂 => reulp
"\u0072\u0065\u0075\u006c\u0070",
// 0xb983: 릃 => reulh
"\u0072\u0065\u0075\u006c\u0068",
// 0xb984: 름 => reum
"\u0072\u0065\u0075\u006d",
// 0xb985: 릅 => reub
"\u0072\u0065\u0075\u0062",
// 0xb986: 릆 => reubs
"\u0072\u0065\u0075\u0062\u0073",
// 0xb987: 릇 => reus
"\u0072\u0065\u0075\u0073",
// 0xb988: 릈 => reuss
"\u0072\u0065\u0075\u0073\u0073",
// 0xb989: 릉 => reung
"\u0072\u0065\u0075\u006e\u0067",
// 0xb98a: 릊 => reuj
"\u0072\u0065\u0075\u006a",
// 0xb98b: 릋 => reuc
"\u0072\u0065\u0075\u0063",
// 0xb98c: 릌 => reuk
"\u0072\u0065\u0075\u006b",
// 0xb98d: 릍 => reut
"\u0072\u0065\u0075\u0074",
// 0xb98e: 릎 => reup
"\u0072\u0065\u0075\u0070",
// 0xb98f: 릏 => reuh
"\u0072\u0065\u0075\u0068",
// 0xb990: 릐 => ryi
"\u0072\u0079\u0069",
// 0xb991: 릑 => ryig
"\u0072\u0079\u0069\u0067",
// 0xb992: 릒 => ryigg
"\u0072\u0079\u0069\u0067\u0067",
// 0xb993: 릓 => ryigs
"\u0072\u0079\u0069\u0067\u0073",
// 0xb994: 릔 => ryin
"\u0072\u0079\u0069\u006e",
// 0xb995: 릕 => ryinj
"\u0072\u0079\u0069\u006e\u006a",
// 0xb996: 릖 => ryinh
"\u0072\u0079\u0069\u006e\u0068",
// 0xb997: 릗 => ryid
"\u0072\u0079\u0069\u0064",
// 0xb998: 릘 => ryil
"\u0072\u0079\u0069\u006c",
// 0xb999: 릙 => ryilg
"\u0072\u0079\u0069\u006c\u0067",
// 0xb99a: 릚 => ryilm
"\u0072\u0079\u0069\u006c\u006d",
// 0xb99b: 릛 => ryilb
"\u0072\u0079\u0069\u006c\u0062",
// 0xb99c: 릜 => ryils
"\u0072\u0079\u0069\u006c\u0073",
// 0xb99d: 릝 => ryilt
"\u0072\u0079\u0069\u006c\u0074",
// 0xb99e: 릞 => ryilp
"\u0072\u0079\u0069\u006c\u0070",
// 0xb99f: 릟 => ryilh
"\u0072\u0079\u0069\u006c\u0068",
// 0xb9a0: 릠 => ryim
"\u0072\u0079\u0069\u006d",
// 0xb9a1: 릡 => ryib
"\u0072\u0079\u0069\u0062",
// 0xb9a2: 릢 => ryibs
"\u0072\u0079\u0069\u0062\u0073",
// 0xb9a3: 릣 => ryis
"\u0072\u0079\u0069\u0073",
// 0xb9a4: 릤 => ryiss
"\u0072\u0079\u0069\u0073\u0073",
// 0xb9a5: 릥 => rying
"\u0072\u0079\u0069\u006e\u0067",
// 0xb9a6: 릦 => ryij
"\u0072\u0079\u0069\u006a",
// 0xb9a7: 릧 => ryic
"\u0072\u0079\u0069\u0063",
// 0xb9a8: 릨 => ryik
"\u0072\u0079\u0069\u006b",
// 0xb9a9: 릩 => ryit
"\u0072\u0079\u0069\u0074",
// 0xb9aa: 릪 => ryip
"\u0072\u0079\u0069\u0070",
// 0xb9ab: 릫 => ryih
"\u0072\u0079\u0069\u0068",
// 0xb9ac: 리 => ri
"\u0072\u0069",
// 0xb9ad: 릭 => rig
"\u0072\u0069\u0067",
// 0xb9ae: 릮 => rigg
"\u0072\u0069\u0067\u0067",
// 0xb9af: 릯 => rigs
"\u0072\u0069\u0067\u0073",
// 0xb9b0: 린 => rin
"\u0072\u0069\u006e",
// 0xb9b1: 릱 => rinj
"\u0072\u0069\u006e\u006a",
// 0xb9b2: 릲 => rinh
"\u0072\u0069\u006e\u0068",
// 0xb9b3: 릳 => rid
"\u0072\u0069\u0064",
// 0xb9b4: 릴 => ril
"\u0072\u0069\u006c",
// 0xb9b5: 릵 => rilg
"\u0072\u0069\u006c\u0067",
// 0xb9b6: 릶 => rilm
"\u0072\u0069\u006c\u006d",
// 0xb9b7: 릷 => rilb
"\u0072\u0069\u006c\u0062",
// 0xb9b8: 릸 => rils
"\u0072\u0069\u006c\u0073",
// 0xb9b9: 릹 => rilt
"\u0072\u0069\u006c\u0074",
// 0xb9ba: 릺 => rilp
"\u0072\u0069\u006c\u0070",
// 0xb9bb: 릻 => rilh
"\u0072\u0069\u006c\u0068",
// 0xb9bc: 림 => rim
"\u0072\u0069\u006d",
// 0xb9bd: 립 => rib
"\u0072\u0069\u0062",
// 0xb9be: 릾 => ribs
"\u0072\u0069\u0062\u0073",
// 0xb9bf: 릿 => ris
"\u0072\u0069\u0073",
// 0xb9c0: 맀 => riss
"\u0072\u0069\u0073\u0073",
// 0xb9c1: 링 => ring
"\u0072\u0069\u006e\u0067",
// 0xb9c2: 맂 => rij
"\u0072\u0069\u006a",
// 0xb9c3: 맃 => ric
"\u0072\u0069\u0063",
// 0xb9c4: 맄 => rik
"\u0072\u0069\u006b",
// 0xb9c5: 맅 => rit
"\u0072\u0069\u0074",
// 0xb9c6: 맆 => rip
"\u0072\u0069\u0070",
// 0xb9c7: 맇 => rih
"\u0072\u0069\u0068",
// 0xb9c8: 마 => ma
"\u006d\u0061",
// 0xb9c9: 막 => mag
"\u006d\u0061\u0067",
// 0xb9ca: 맊 => magg
"\u006d\u0061\u0067\u0067",
// 0xb9cb: 맋 => mags
"\u006d\u0061\u0067\u0073",
// 0xb9cc: 만 => man
"\u006d\u0061\u006e",
// 0xb9cd: 맍 => manj
"\u006d\u0061\u006e\u006a",
// 0xb9ce: 많 => manh
"\u006d\u0061\u006e\u0068",
// 0xb9cf: 맏 => mad
"\u006d\u0061\u0064",
// 0xb9d0: 말 => mal
"\u006d\u0061\u006c",
// 0xb9d1: 맑 => malg
"\u006d\u0061\u006c\u0067",
// 0xb9d2: 맒 => malm
"\u006d\u0061\u006c\u006d",
// 0xb9d3: 맓 => malb
"\u006d\u0061\u006c\u0062",
// 0xb9d4: 맔 => mals
"\u006d\u0061\u006c\u0073",
// 0xb9d5: 맕 => malt
"\u006d\u0061\u006c\u0074",
// 0xb9d6: 맖 => malp
"\u006d\u0061\u006c\u0070",
// 0xb9d7: 맗 => malh
"\u006d\u0061\u006c\u0068",
// 0xb9d8: 맘 => mam
"\u006d\u0061\u006d",
// 0xb9d9: 맙 => mab
"\u006d\u0061\u0062",
// 0xb9da: 맚 => mabs
"\u006d\u0061\u0062\u0073",
// 0xb9db: 맛 => mas
"\u006d\u0061\u0073",
// 0xb9dc: 맜 => mass
"\u006d\u0061\u0073\u0073",
// 0xb9dd: 망 => mang
"\u006d\u0061\u006e\u0067",
// 0xb9de: 맞 => maj
"\u006d\u0061\u006a",
// 0xb9df: 맟 => mac
"\u006d\u0061\u0063",
// 0xb9e0: 맠 => mak
"\u006d\u0061\u006b",
// 0xb9e1: 맡 => mat
"\u006d\u0061\u0074",
// 0xb9e2: 맢 => map
"\u006d\u0061\u0070",
// 0xb9e3: 맣 => mah
"\u006d\u0061\u0068",
// 0xb9e4: 매 => mae
"\u006d\u0061\u0065",
// 0xb9e5: 맥 => maeg
"\u006d\u0061\u0065\u0067",
// 0xb9e6: 맦 => maegg
"\u006d\u0061\u0065\u0067\u0067",
// 0xb9e7: 맧 => maegs
"\u006d\u0061\u0065\u0067\u0073",
// 0xb9e8: 맨 => maen
"\u006d\u0061\u0065\u006e",
// 0xb9e9: 맩 => maenj
"\u006d\u0061\u0065\u006e\u006a",
// 0xb9ea: 맪 => maenh
"\u006d\u0061\u0065\u006e\u0068",
// 0xb9eb: 맫 => maed
"\u006d\u0061\u0065\u0064",
// 0xb9ec: 맬 => mael
"\u006d\u0061\u0065\u006c",
// 0xb9ed: 맭 => maelg
"\u006d\u0061\u0065\u006c\u0067",
// 0xb9ee: 맮 => maelm
"\u006d\u0061\u0065\u006c\u006d",
// 0xb9ef: 맯 => maelb
"\u006d\u0061\u0065\u006c\u0062",
// 0xb9f0: 맰 => maels
"\u006d\u0061\u0065\u006c\u0073",
// 0xb9f1: 맱 => maelt
"\u006d\u0061\u0065\u006c\u0074",
// 0xb9f2: 맲 => maelp
"\u006d\u0061\u0065\u006c\u0070",
// 0xb9f3: 맳 => maelh
"\u006d\u0061\u0065\u006c\u0068",
// 0xb9f4: 맴 => maem
"\u006d\u0061\u0065\u006d",
// 0xb9f5: 맵 => maeb
"\u006d\u0061\u0065\u0062",
// 0xb9f6: 맶 => maebs
"\u006d\u0061\u0065\u0062\u0073",
// 0xb9f7: 맷 => maes
"\u006d\u0061\u0065\u0073",
// 0xb9f8: 맸 => maess
"\u006d\u0061\u0065\u0073\u0073",
// 0xb9f9: 맹 => maeng
"\u006d\u0061\u0065\u006e\u0067",
// 0xb9fa: 맺 => maej
"\u006d\u0061\u0065\u006a",
// 0xb9fb: 맻 => maec
"\u006d\u0061\u0065\u0063",
// 0xb9fc: 맼 => maek
"\u006d\u0061\u0065\u006b",
// 0xb9fd: 맽 => maet
"\u006d\u0061\u0065\u0074",
// 0xb9fe: 맾 => maep
"\u006d\u0061\u0065\u0070",
// 0xb9ff: 맿 => maeh
"\u006d\u0061\u0065\u0068",
)
| 8
|
Kotlin
|
6
| 25
|
0c94260c3e9472db2e89f6c62ba715e85e1539f4
| 15,271
|
kotwords
|
Apache License 2.0
|
application/module/module_splash/src/main/java/afkt_replace/module/splash/SplashViewModel.kt
|
afkT
| 343,177,221
| false
| null |
package novalinx.module.splash
import novalinx.core.lib.base.app.BaseViewModel
import novalinx.core.lib.bean.splash.SplashAds
import novalinx.core.lib.config.KeyConst
import novalinx.core.lib.router.module.AppRouter
import novalinx.core.lib.router.module.splash.SplashNav
import android.app.Activity
import androidx.lifecycle.LiveData
import dev.expand.engine.json.toJson
import dev.mvvm.utils.toResString
import dev.utils.app.toast.ToastTintUtils
class SplashViewModel(
private val repository: SplashRepository = SplashRepository()
) : BaseViewModel() {
// ==============
// = 对外公开方法 =
// ==============
/**
* 查询广告数据
* @return LiveData<SplashAds>
*/
fun queryAds(): LiveData<SplashAds> {
return repository.queryAds()
}
/**
* 路由跳转 App 首页入口
* @param ads 广告数据
* 进入首页后打开
*/
fun routerAppMain(
activity: Activity,
ads: SplashAds? = null
) {
if (BuildConfig.isModular) {
ToastTintUtils.success(R.string.str_modular_app.toResString())
} else {
// 直接通过 postcard.navigation() 跳转会显示 AppTheme.Launcher style windowBackground
val postcard = SplashNav.buildAppMain()
ads?.let {
if (it.previewTime > 0L) {
postcard.withString(KeyConst.ADS, it.toJson())
}
}
// 获取跳转 Intent
AppRouter.routerIntent(activity, postcard)?.let { intent ->
activity.startActivity(intent)
}
activity.finish()
}
}
}
| 2
| null |
17
| 72
|
710033ee53928e30f8dc7b37aacdbde7283a7841
| 1,583
|
DevComponent
|
Apache License 2.0
|
app/src/main/java/com/cubivue/camera/app/CameraActivity.kt
|
embraceitmobile
| 535,972,537
| false
| null |
package com.cubivue.camera.app
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.WindowInsets
import android.view.WindowInsetsController
import android.view.WindowManager
import androidx.activity.compose.setContent
import androidx.camera.core.CameraSelector
import androidx.camera.core.ImageCapture
import androidx.camera.core.ImageCaptureException
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.camera.view.PreviewView
import androidx.compose.foundation.Image
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.sharp.Lens
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.core.content.ContextCompat
import androidx.core.view.WindowCompat
import coil.compose.rememberImagePainter
import com.cubivue.camera.app.base.BaseCameraActivity
import com.cubivue.camera.app.ui.theme.CameraCubiVueTheme
import java.io.File
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.Executor
import java.util.concurrent.Executors
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine
class MainCameraActivity : BaseCameraActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
CameraCubiVueTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
if (shouldShowCamera.value) {
CameraView(
outputDirectory = outputDirectoryFile,
executor = cameraExecutor,
onImageCaptured = {
val intent = intent
intent.putExtra("URI", it.toString())
setResult(RESULT_OK, intent)
finish()
},
onError = { Log.e("CameraView", "View error:", it) }
)
}
if (shouldShowPhoto.value) {
Image(
painter = rememberImagePainter(photoUri),
contentDescription = null,
modifier = Modifier.fillMaxSize()
)
}
}
}
}
outputDirectoryFile = getOutputDirectory()
cameraExecutor = Executors.newSingleThreadExecutor()
hideSystemUI()
}
fun hideSystemUI() {
actionBar?.hide()
WindowCompat.setDecorFitsSystemWindows(window, false)
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
} else {
window.insetsController?.apply {
hide(WindowInsets.Type.statusBars())
systemBarsBehavior = WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
}
}
}
}
fun takePhoto(
filenameFormat: String,
imageCapture: ImageCapture,
outputDirectory: File,
executor: Executor,
onImageCaptured: (Uri) -> Unit,
onError: (ImageCaptureException) -> Unit
) {
val photoFile = File(
outputDirectory,
SimpleDateFormat(filenameFormat, Locale.US).format(System.currentTimeMillis()) + ".jpg"
)
val outputOptions = ImageCapture.OutputFileOptions.Builder(photoFile).build()
imageCapture.takePicture(outputOptions, executor, object : ImageCapture.OnImageSavedCallback {
override fun onError(exception: ImageCaptureException) {
Log.e("takePicture", "Take photo error:", exception)
onError(exception)
}
override fun onImageSaved(outputFileResults: ImageCapture.OutputFileResults) {
val savedUri = Uri.fromFile(photoFile)
onImageCaptured(savedUri)
}
})
}
suspend fun Context.getCameraProvider(): ProcessCameraProvider = suspendCoroutine { continuation ->
ProcessCameraProvider.getInstance(this).also { cameraProvider ->
cameraProvider.addListener({
continuation.resume(cameraProvider.get())
}, ContextCompat.getMainExecutor(this))
}
}
@Composable
fun CameraView(
outputDirectory: File,
executor: Executor,
onImageCaptured: (Uri) -> Unit,
onError: (ImageCaptureException) -> Unit
) {
val lensFacing = CameraSelector.LENS_FACING_BACK
val context = LocalContext.current
val lifecycleOwner = LocalLifecycleOwner.current
val preview = Preview.Builder().build()
val previewView = remember { PreviewView(context) }
val imageCapture: ImageCapture = remember { ImageCapture.Builder().build() }
val cameraSelector = CameraSelector.Builder()
.requireLensFacing(lensFacing)
.build()
LaunchedEffect(lensFacing) {
val cameraProvider = context.getCameraProvider()
cameraProvider.unbindAll()
cameraProvider.bindToLifecycle(
lifecycleOwner,
cameraSelector,
preview,
imageCapture
)
preview.setSurfaceProvider(previewView.surfaceProvider)
}
Box(contentAlignment = Alignment.BottomCenter, modifier = Modifier.fillMaxSize()) {
AndroidView({ previewView }, modifier = Modifier.fillMaxSize())
IconButton(
modifier = Modifier.padding(bottom = 70.dp),
onClick = {
takePhoto(
filenameFormat = "yyyy-MM-dd-HH-mm-ss-SSS",
imageCapture = imageCapture,
outputDirectory = outputDirectory,
executor = executor,
onImageCaptured = onImageCaptured,
onError = onError
)
},
content = {
Icon(
imageVector = Icons.Sharp.Lens,
contentDescription = "Take picture",
tint = Color.White,
modifier = Modifier
.size(300.dp)
.padding(1.dp)
.border(1.dp, Color.White, CircleShape)
)
}
)
}
}
| 0
|
Kotlin
|
0
| 0
|
059e7b8be28a4e9d61cea9c2f903ac4771c66a6c
| 7,201
|
Camera_CubiVue
|
Apache License 2.0
|
zircon.core/src/commonMain/kotlin/org/hexworks/zircon/api/component/builder/ComponentBuilder.kt
|
EdaKalabak
| 385,504,580
| true
|
{"Kotlin": 1760072, "Java": 118844, "Shell": 152}
|
package org.hexworks.zircon.api.component.builder
import org.hexworks.zircon.api.ComponentAlignments.alignmentAround
import org.hexworks.zircon.api.ComponentAlignments.alignmentWithin
import org.hexworks.zircon.api.ComponentAlignments.positionalAlignment
import org.hexworks.zircon.api.builder.Builder
import org.hexworks.zircon.api.component.AlignmentStrategy
import org.hexworks.zircon.api.component.ColorTheme
import org.hexworks.zircon.api.component.Component
import org.hexworks.zircon.api.component.ComponentAlignment
import org.hexworks.zircon.api.component.ComponentProperties
import org.hexworks.zircon.api.component.ComponentStyleSet
import org.hexworks.zircon.api.component.Container
import org.hexworks.zircon.api.component.renderer.ComponentDecorationRenderer
import org.hexworks.zircon.api.component.renderer.ComponentRenderContext
import org.hexworks.zircon.api.component.renderer.ComponentRenderer
import org.hexworks.zircon.api.data.Position
import org.hexworks.zircon.api.data.Size
import org.hexworks.zircon.api.graphics.TileGraphics
import org.hexworks.zircon.api.grid.TileGrid
import org.hexworks.zircon.api.resource.TilesetResource
import org.hexworks.zircon.api.tileset.Tileset
@Suppress("UNCHECKED_CAST")
interface ComponentBuilder<T : Component, U : ComponentBuilder<T, U>> : Builder<T> {
var name: String
var position: Position
var alignment: AlignmentStrategy
var colorTheme: ColorTheme?
/**
* Shorthand for `decorations = listOf(decoration)`
*/
var decoration: ComponentDecorationRenderer?
/**
* Sets the decorations that should be used for the component.
* This also forces a recalculation of [contentSize]
*/
var decorations: List<ComponentDecorationRenderer>
/**
* Returns the [title] or an empty string if it is not present.
*/
val title: String
var componentStyleSet: ComponentStyleSet
var tileset: TilesetResource
var updateOnAttach: Boolean
var componentRenderer: ComponentRenderer<out T>
var renderFunction: (TileGraphics, ComponentRenderContext<T>) -> Unit
var preferredSize: Size
var preferredContentSize: Size
val contentSize: Size
val contentWidth: Int
get() = contentSize.width
val contentHeight: Int
get() = contentSize.height
/**
* The final [Size] of the [Component] that is being built. Size is calculated this way:
* - If [preferredSize] is set it will be used
* - If [preferredSize] is not set but [preferredContentSize] is set, then it will be calculated
* based on [preferredContentSize] and the size of the [decorations]
* - If neither one of those are set size will be calculated based on [contentSize] and the size
* of [decorations]
*/
val size: Size
fun withName(name: String): U {
this.name = name
return this as U
}
/**
* Sets if the [Component] should be updated when it is attached to a parent
* or not. By default the [Component]'s common properties ([ComponentProperties])
* will be updated from its parent.
*/
fun withUpdateOnAttach(updateOnAttach: Boolean): U {
this.updateOnAttach = updateOnAttach
return this as U
}
/**
* Sets the [ComponentStyleSet] the [Component] will use.
*/
fun withComponentStyleSet(componentStyleSet: ComponentStyleSet): U {
this.componentStyleSet = componentStyleSet
return this as U
}
/**
* Sets the [Tileset] to use for the [Component].
*/
fun withTileset(tileset: TilesetResource): U {
this.tileset = tileset
return this as U
}
/**
* Sets the [ColorTheme] to use for the [Component].
*/
fun withColorTheme(colorTheme: ColorTheme): U {
this.colorTheme = colorTheme
return this as U
}
/**
* Sets the [AlignmentStrategy] to use for the [Component].
*/
fun withAlignment(alignmentStrategy: AlignmentStrategy): U {
this.alignment = alignmentStrategy
return this as U
}
/**
* Sets the [ComponentDecorationRenderer]s for the resulting [Component].
* The component will be decorated with the given decorators in the given
* order.
*/
fun withDecorations(vararg renderers: ComponentDecorationRenderer): U {
this.decorations = renderers.asList()
return this as U
}
/**
* Sets the [ComponentRenderer] for the resulting [Component].
*/
fun withComponentRenderer(componentRenderer: ComponentRenderer<T>): U {
this.componentRenderer = componentRenderer
return this as U
}
/**
* Creates a [ComponentRenderer] for the resulting [Component] using the
* given component renderer [fn].
*/
fun withRendererFunction(fn: (TileGraphics, ComponentRenderContext<T>) -> Unit): U {
this.renderFunction = fn
return this as U
}
/**
* Sets the [Size] of the resulting [Component].
*/
@Deprecated("The name is misleading, use preferred size instead", ReplaceWith("withPreferredSize(size)"))
fun withSize(size: Size): U = withPreferredSize(size)
/**
* Sets the [Size] of the resulting [Component].
*/
@Deprecated("The name is misleading, use preferred size instead", ReplaceWith("withPreferredSize(width, height)"))
fun withSize(width: Int, height: Int): U = withSize(Size.create(width, height))
/**
* Sets the preferred [Size] of the resulting [Component].
* The preferred size contains the content and the decorations.
*/
fun withPreferredSize(size: Size): U {
preferredSize = size
return this as U
}
/**
* Shorthand for [withPreferredSize].
*/
fun withPreferredSize(width: Int, height: Int): U = withPreferredSize(Size.create(width, height))
/**
* Sets the preferred content [Size] of the resulting [Component].
* The preferred content size contains the content only and doesn't contain the decorations.
*/
fun withPreferredContentSize(size: Size): U {
preferredContentSize = size
return this as U
}
fun withPreferredContentSize(width: Int, height: Int): U = withPreferredSize(Size.create(width, height))
/**
* Aligns the resulting [Component] positionally, relative to its parent.
* Same as calling `withAlignment(positionalAlignment(position))`
*/
fun withPosition(position: Position): U = withAlignment(positionalAlignment(position))
/**
* Aligns the resulting [Component] positionally, relative to its parent.
* Same as calling `withAlignment(positionalAlignment(x, y))`
*/
fun withPosition(x: Int, y: Int): U = withPosition(Position.create(x, y))
/**
* Aligns the resulting [Component] within the [tileGrid] using the
* given [alignment].
* Same as calling `withAlignment(alignmentWithin(tileGrid, alignment))`
*/
fun withAlignmentWithin(tileGrid: TileGrid, alignment: ComponentAlignment): U =
withAlignment(alignmentWithin(tileGrid, alignment))
/**
* Aligns the resulting [Component] within the [container] using the
* given [alignment].
* Same as calling `withAlignment(alignmentWithin(container, alignment))`
*/
fun withAlignmentWithin(container: Container, alignment: ComponentAlignment): U =
withAlignment(alignmentWithin(container, alignment))
/**
* Aligns the resulting [Component] around the [component] using the
* given [alignment].
* Same as calling `withAlignment(alignmentWithin(container, alignment))`
*/
fun withAlignmentAround(component: Component, alignment: ComponentAlignment): U =
withAlignment(alignmentAround(component, alignment))
}
| 0
| null |
0
| 0
|
8143a56d9c82c07cb1a91dcb4cf355bd2afe45cc
| 7,792
|
zircon
|
Apache License 2.0
|
core/src/main/java/com/serious/exception/RegisterExceptionHandler.kt
|
coolsamson7
| 700,938,199
| false
|
{"Kotlin": 196440}
|
package com.serious.exception
/*
* @COPYRIGHT (C) 2023 Andreas Ernst
*
* All rights reserved
*/
import org.springframework.stereotype.Component
@MustBeDocumented
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.CLASS)
@Component
annotation class RegisterExceptionHandler()
| 0
|
Kotlin
|
0
| 1
|
7f8e95fa9c395f12c076d9e1219718592439858f
| 295
|
service
|
Apache License 2.0
|
timer/d2v-timer-js/src/test/kotlin/io/data2viz/timer/TimerTests.kt
|
yijunwu
| 207,939,886
| true
|
{"Kotlin": 1700165, "JavaScript": 42307, "HTML": 38481, "Java": 386}
|
package io.data2viz.timer
import io.data2viz.test.TestBase
import kotlinx.coroutines.experimental.delay
import kotlinx.coroutines.experimental.promise
import kotlin.test.Ignore
import kotlin.test.Test
@Suppress("unused")
class TimerTests : TestBase() {
@Test
fun keepOneTest() {
true shouldBe true
}
@Test @Ignore
fun timerStop() = promise {
var count = 0
timer {
if (++count == 2) {
stop()
}
}
delay(50)
count shouldBe 2
}
@Test @Ignore
@JsName("callbackMeanTime")
fun `timer(callback) invokes the callback about every 17ms`() = promise {
val then = now()
var elapsedTime = 0.0
var count = 0
timer {
if (count++ > 10) {
stop()
elapsedTime = now() - then
}
}
delay(200)
elapsedTime shouldBe (17.0 * count plusOrMinus 5.0 * count)
}
@Test @Ignore
@JsName("callbackDelayed")
fun `timer(callback, delay) first invokes the callback after the specified delay`() = promise {
val then = now()
val delay = 100.0
timer(delay = delay) {
stop()
val elapsed = now() - then
elapsed shouldBe (delay plusOrMinus 10.0)
}
delay(10 + delay.toInt())
}
@Test @Ignore
@JsName("elapsedRelativeToDelay")
fun `computes the elapsed time relative to the delay`() = promise {
val delay = 100.0
timer(delay = delay) { elapsed ->
stop()
elapsed shouldBe (.0 plusOrMinus 10.0)
}
delay(delay.toInt() + 10)
}
@Test @Ignore
@JsName("elapsedRelativeToDelayAndTime")
fun `timer(callback, delay, time) computes the effective delay relative to the specified time`() = promise {
val delay = 100.0
val skew = 200.0
timer(delay = delay, startTime = now() - skew) { elapsed ->
stop()
elapsed shouldBe (skew - delay plusOrMinus 10.0)
}
delay(delay.toInt() + 10)
}
@Test @Ignore
@JsName("flushTimers")
fun `timer(callback) invokes callbacks in scheduling order during synchronous flush`() {
val results = mutableListOf<Int>()
timer { results.add(1); stop() }
timer { results.add(2); stop() }
timer { results.add(3); stop() }
timerFlush()
results shouldBe listOf(1, 2, 3)
}
@Test @Ignore
@JsName("flushTimersAsync")
fun `timer(callback) invokes callbacks in scheduling order during asynchronous flush`() = promise {
val results = mutableListOf<Int>()
timer { results.add(1); stop() }
timer { results.add(2); stop() }
timer { results.add(3); stop() }
timer {
stop()
results shouldBe listOf(1, 2, 3)
}
delay(50)
}
@Test @Ignore
@JsName("flushTimersAsyncWithDelay")
// @Ignore
fun `timer(callback, delay) invokes callbacks in scheduling order during asynchronous flush`() = promise {
val results = mutableListOf<Int>()
timer { results.add(1); stop() }
timer { results.add(2); stop() }
timer { results.add(3); stop() }
timer {
stop()
println(results)
results shouldBe listOf(1, 2, 3)
}
delay(50)
}
@Test @Ignore
@JsName("timerWithinAFrame")
fun `timer(callback) within a frame invokes the callback at the end of the same frame`() = promise {
timer {
timer { elapsed2 ->
stop()
elapsed2 shouldBeClose 0.0
}
stop()
}
delay(30)
}
}
| 0
| null |
0
| 0
|
733f9ac458755ab065becd16d7f001be21080f59
| 3,763
|
data2viz
|
Apache License 2.0
|
embrace-android-core/src/main/kotlin/io/embrace/android/embracesdk/internal/config/behavior/AppExitInfoBehavior.kt
|
embrace-io
| 704,537,857
| false
|
{"Kotlin": 2981564, "C": 189341, "Java": 150268, "C++": 13140, "CMake": 4261}
|
package io.embrace.android.embracesdk.internal.config.behavior
interface AppExitInfoBehavior {
fun getTraceMaxLimit(): Int
/**
* Whether the feature is enabled or not.
*/
fun isAeiCaptureEnabled(): Boolean
fun appExitInfoMaxNum(): Int
sealed class CollectTracesResult(val result: String?) {
class Success(result: String?) : CollectTracesResult(result)
class TooLarge(result: String?) : CollectTracesResult(result)
class TraceException(message: String?) : CollectTracesResult(message)
}
}
| 11
|
Kotlin
|
11
| 134
|
896e9aadf568ba527c76ec66f6f440baed29d1ee
| 551
|
embrace-android-sdk
|
Apache License 2.0
|
embrace-android-sdk/src/test/java/io/embrace/android/embracesdk/fakes/FakeInternalNetworkApi.kt
|
embrace-io
| 704,537,857
| false
| null |
package io.embrace.android.embracesdk.fakes
import io.embrace.android.embracesdk.internal.config.instrumented.NetworkCaptureConfig
import io.embrace.android.embracesdk.internal.network.http.InternalNetworkApi
import io.embrace.android.embracesdk.network.EmbraceNetworkRequest
internal class FakeInternalNetworkApi(
var internalInterface: FakeEmbraceInternalInterface = FakeEmbraceInternalInterface(),
var time: Long = 0,
var started: Boolean = true,
var traceHeader: String = NetworkCaptureConfig.CONFIG_TRACE_ID_HEADER_DEFAULT_VALUE,
var w3cTraceparent: String? = "00-3c72a77a7b51af6fb3778c06d4c165ce-4c1d710fffc88e35-01"
) : InternalNetworkApi {
override fun getSdkCurrentTime(): Long = time
override fun isStarted(): Boolean = started
override fun getTraceIdHeader(): String = traceHeader
override fun generateW3cTraceparent(): String? = w3cTraceparent
override fun isNetworkSpanForwardingEnabled(): Boolean = internalInterface.isNetworkSpanForwardingEnabled()
override fun recordNetworkRequest(
embraceNetworkRequest: EmbraceNetworkRequest
) = internalInterface.recordNetworkRequest(
embraceNetworkRequest
)
override fun shouldCaptureNetworkBody(
url: String,
method: String
): Boolean = internalInterface.shouldCaptureNetworkBody(url, method)
override fun logInternalError(error: Throwable) = internalInterface.logInternalError(error)
}
| 20
| null |
8
| 134
|
896e9aadf568ba527c76ec66f6f440baed29d1ee
| 1,440
|
embrace-android-sdk
|
Apache License 2.0
|
src/main/kotlin/org/nield/kotlinstatistics/SimpleRegression.kt
|
thomasnield
| 84,361,977
| false
| null |
package org.nield.kotlinstatistics
interface SimpleRegression {
val n: Long
val intercept: Double
val slope: Double
val sumSquaredErrors: Double
val totalSumSqaures: Double
val xSumSquares: Double
val sumOfCrossProducts: Double
val regressionSumSquares: Double
val meanSquareError: Double
val r: Double
val rSquare: Double
val intereptStdErr: Double
val slopeStdErr: Double
val slopeConfidenceInterval: Double
val significance: Double
fun predict(x: Double): Double
}
class ApacheSimpleRegression(val sr: org.apache.commons.math3.stat.regression.SimpleRegression): SimpleRegression {
override val n get() = sr.n
override val intercept get() = sr.intercept
override val slope get() = sr.slope
override val sumSquaredErrors get() = sr.sumSquaredErrors
override val totalSumSqaures get() = sr.totalSumSquares
override val xSumSquares get() = sr.xSumSquares
override val sumOfCrossProducts get() = sr.sumOfCrossProducts
override val regressionSumSquares get() = sr.regressionSumSquares
override val meanSquareError get() = sr.meanSquareError
override val r get() = sr.r
override val rSquare get() = sr.rSquare
override val intereptStdErr get() = sr.interceptStdErr
override val slopeStdErr get() = sr.slopeStdErr
override val slopeConfidenceInterval get() = sr.slopeConfidenceInterval
override val significance get() = sr.significance
override fun predict(x: Double) = sr.predict(x)
}
| 3
| null |
48
| 842
|
17f64bae2a3cea2e85f05c08172d19a290561e3b
| 1,513
|
kotlin-statistics
|
Apache License 2.0
|
examples/example-kotlin/services/intermediary-service/src/main/kotlin/Main.kt
|
konigsoftware
| 690,328,441
| false
|
{"Kotlin": 31037}
|
package example.services.intermediary
import example.services.balance.BalanceServiceGrpcKt.BalanceServiceCoroutineStub
import example.services.shared.GlobalAuthContextKey
import io.grpc.ManagedChannelBuilder
import io.grpc.ServerBuilder
import org.konigsoftware.kontext.KonigKontextServerInterceptor
import org.konigsoftware.kontext.withKonigKontextInterceptor
fun main() {
println("Starting Intermediary Service...")
val serviceCClient =
BalanceServiceCoroutineStub(
ManagedChannelBuilder.forTarget("0.0.0.0:50052").usePlaintext().build()
).withKonigKontextInterceptor(GlobalAuthContextKey)
val server = ServerBuilder
.forPort(50051)
.addService(IntermediaryService(serviceCClient))
.intercept(KonigKontextServerInterceptor(GlobalAuthContextKey))
.build()
server.start()
println("Started Intermediary Service on port: ${server.port}")
server.awaitTermination()
}
| 5
|
Kotlin
|
0
| 1
|
cdfe2ab61f32625d5300c9dcd3c17c82079cc6ec
| 955
|
konig-kontext
|
MIT License
|
app/src/main/java/com/luiz/thenews/presentation/NewsApp.kt
|
Felipeecp
| 641,915,241
| false
| null |
package com.luiz.thenews.presentation
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class NewsApp:Application()
| 0
|
Kotlin
|
0
| 0
|
e78de1fb46118ac3a9a950b653ca9ef2902b6844
| 156
|
TheNewsApp
|
MIT License
|
src/nl/hannahsten/texifyidea/action/group/ZathuraActionGroup.kt
|
bdudelsack
| 296,719,900
| true
|
{"Gradle Kotlin DSL": 2, "Java Properties": 1, "Markdown": 7, "Shell": 1, "Text": 2, "Ignore List": 1, "Batchfile": 1, "EditorConfig": 1, "YAML": 3, "Kotlin": 592, "Java": 93, "TeX": 38, "BibTeX": 3, "INI": 1, "XML": 5, "JFlex": 2, "CODEOWNERS": 1, "SVG": 74, "HTML": 98, "Python": 1}
|
package nl.hannahsten.texifyidea.action.group
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.actionSystem.DefaultActionGroup
import nl.hannahsten.texifyidea.run.linuxpdfviewer.PdfViewer
class SkimActionGroup : DefaultActionGroup() {
override fun canBePerformed(context: DataContext) = PdfViewer.SKIM.isAvailable()
override fun hideIfNoVisibleChildren(): Boolean = true
}
| 0
| null |
0
| 0
|
afb253cfce2159660097792682e05c147851afe9
| 416
|
TeXiFy-IDEA
|
MIT License
|
app/src/test/java/com/example/stylo/data/database/NotesMetaDataDatabaseTest.kt
|
Evan-Coulter
| 501,509,725
| false
| null |
package com.example.stylo.data.database
import android.content.Context
import androidx.room.Room
import androidx.test.core.app.ApplicationProvider
import com.example.stylo.data.model.BelongsToBuilder
import com.example.stylo.data.model.RoomFolder
import com.example.stylo.data.model.RoomFolderBuilder
import com.example.stylo.data.model.RoomNoteBuilder
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import java.util.*
@RunWith(RobolectricTestRunner::class)
class NotesMetaDataDatabaseTest {
private lateinit var notesMetaDataDao: NotesMetaDataDao
private lateinit var database: NotesMetaDataDatabase
@Before
fun setUp() {
val context = ApplicationProvider.getApplicationContext<Context>()
database = Room.inMemoryDatabaseBuilder(context, NotesMetaDataDatabase::class.java)
.allowMainThreadQueries() // for robolectric support
.build()
notesMetaDataDao = database.notesMetaDataDao()
}
@After
fun tearDown() {
database.close()
}
@Test
fun `test setting all fields insert then get`() {
//Given a unique entity
val currentTime = Calendar.getInstance().time
val note = RoomNoteBuilder()
.setTitle("My Awesome Note")
.setDateCreated(currentTime)
.setDateLastModified(currentTime)
.setFileName("/filepath")
.build()
//When inserted and retrieved
notesMetaDataDao.insert(note)
val notes = notesMetaDataDao.getAllNotes()
//Then expect to recover that same entity
assertEquals(1, notes.size)
val recoveredNote = notes.first()
assertEquals("My Awesome Note", recoveredNote.title)
assertEquals(currentTime, recoveredNote.dateCreated)
assertEquals(currentTime, recoveredNote.dateLastSaved)
assertEquals("/filepath", recoveredNote.filePath)
}
@Test
fun `test insert then update and get`() {
//Given one unique entry
val builder = RoomNoteBuilder()
.setTitle("Entry")
var note = builder.build()
//When inserted into database, retrieved, and then updated
notesMetaDataDao.insert(note)
builder
.setTitle("New Title")
.setUID(notesMetaDataDao.getAllNotes()[0].uid)
note = builder.build()
notesMetaDataDao.insert(note)
//Then we expect just one entry that's been updated
val notes = notesMetaDataDao.getAllNotes()
assertEquals(1, notes.size)
note = notes.first()
assertEquals("New Title", note.title)
}
@Test
fun `test insert and get multiple entries`() {
//Given 3 unique entries in DB
notesMetaDataDao.insert(RoomNoteBuilder().setTitle("1").build())
notesMetaDataDao.insert(RoomNoteBuilder().setTitle("2").build())
notesMetaDataDao.insert(RoomNoteBuilder().setTitle("3").build())
//Then we expect 3 unique entries back
val notes = notesMetaDataDao.getAllNotes()
assertEquals(3, notes.size)
notes.forEachIndexed { index, note ->
assertEquals(index+1, note.title.toInt())
}
}
@Test
fun `test insert then delete`() {
//Given 2 notes inside DB
notesMetaDataDao.insert(RoomNoteBuilder().setTitle("First Note").build())
notesMetaDataDao.insert(RoomNoteBuilder().setTitle("Second Note").build())
//When 2nd note has been deleted
var notes = notesMetaDataDao.getAllNotes()
val secondNote = notes.first { it.title == "Second Note" }
notesMetaDataDao.deleteNote(secondNote.uid)
//Then we should only expect one entry in the DB
notes = notesMetaDataDao.getAllNotes()
assertEquals(1, notes.size)
assertEquals("First Note", notes.first().title)
}
@Test
fun `test insert 2 folders`() {
//Given 2 folders inserted into DB
val folder = RoomFolderBuilder().build()
notesMetaDataDao.insert(folder)
notesMetaDataDao.insert(folder)
//Then expect 2 unique folders back
val folders = notesMetaDataDao.getAllFolders()
folders.forEachIndexed { index, roomFolder ->
assertEquals(index+1, roomFolder.uid)
}
}
@Test
fun `test delete 1 folder`() {
//Given 2 inserted folders
notesMetaDataDao.insert(RoomFolderBuilder().setName("One").build())
notesMetaDataDao.insert(RoomFolderBuilder().setName("Two").build())
//When deleting one
val noteToDelete = notesMetaDataDao.getAllFolders().first { it.name == "One" }
notesMetaDataDao.deleteFolder(noteToDelete.uid)
//Then expect to only have one entry left
val notes = notesMetaDataDao.getAllFolders()
assertEquals(1, notes.size)
assertEquals("Two", notes.first().name)
}
@Test
fun `test add note to folder`() {
//Given 1 note and 1 folder
notesMetaDataDao.insert(RoomNoteBuilder().setTitle("Cool Note").build())
val note = notesMetaDataDao.getAllNotes().first()
notesMetaDataDao.insert(RoomFolderBuilder().setName("All Folders").build())
val folder = notesMetaDataDao.getAllFolders().first()
//When that note belongs to that folder
notesMetaDataDao.insert(
BelongsToBuilder()
.setNote(note.uid)
.setFolder(folder.uid)
.build()
)
//Then we can retrieve our belongs to relationship between the note and folder
val belongsToRelationship = notesMetaDataDao.getAllBelongsTo()
assertEquals(1, belongsToRelationship.size)
val recoveredNoteID = belongsToRelationship.first().note
val recoveredFolderID = belongsToRelationship.first().folder
val recoveredNote = notesMetaDataDao.getAllNotes().first { it.uid == recoveredNoteID }
val recoveredFolder = notesMetaDataDao.getAllFolders().first { it.uid == recoveredFolderID }
assertEquals("Cool Note", recoveredNote.title)
assertEquals("All Folders", recoveredFolder.name)
}
@Test
fun `test one note belongs to many folders`() {
//Given 1 note and 5 folders
val currentTime = Calendar.getInstance().time
val note = RoomNoteBuilder().setTitle("My Note")
.setDateCreated(currentTime)
.setDateLastModified(currentTime)
.build()
val folders : MutableList<RoomFolder> = mutableListOf()
for (i in 1..5) {
folders.add(RoomFolderBuilder().setName(i.toString()).build())
}
notesMetaDataDao.insert(note)
folders.forEach {
notesMetaDataDao.insert(it)
}
//When that note belongs to each folder
val recoveredNote = notesMetaDataDao.getAllNotes().also {
assertEquals(1, it.size)
}.first()
val recoveredFolders = notesMetaDataDao.getAllFolders()
assertEquals(5, recoveredFolders.size)
recoveredFolders.forEach {
notesMetaDataDao.insert(
BelongsToBuilder()
.setNote(recoveredNote.uid)
.setFolder(it.uid)
.build()
)
}
//Then we expect to be able to recover a belongs to relation ship for each folder to this note
val belongsTo = notesMetaDataDao.getAllBelongsTo()
assertEquals(5, belongsTo.size)
belongsTo.forEach { relation ->
val belongsToNote = notesMetaDataDao.getAllNotes().first { it.uid == relation.note }
val belongsToFolder = notesMetaDataDao.getAllFolders().first { it.uid == relation.folder }
assertEquals("My Note", belongsToNote.title)
assertEquals(true, listOf(1, 2, 3, 4, 5).contains(belongsToFolder.name.toInt()))
}
}
}
| 2
|
Kotlin
|
0
| 0
|
59c96bbcbaf61dd2328a725c781d486384a8c305
| 8,017
|
Stylo
|
Apache License 2.0
|
app/src/main/kotlin/com/ch3d/android/utils/StringUtils.kt
|
Ch3D
| 66,939,085
| false
| null |
package com.ch3d.android.utils
import android.content.Context
import android.util.TypedValue
class StringUtils {
companion object {
fun dpToPx(context: Context, i: Float): Float {
val displayMetrics = context.resources.displayMetrics
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, i, displayMetrics)
}
val EMPTY_STRING = ""
val DASH = "-"
val SPACE = " "
val UNDERSCORE = "_"
val NEXT_STRING = "\n"
/**
* Safely checks whether two strings are equal or not
* @return true - if strings are equal, false - otherwise
*/
fun hasChanges(newValue: String, oldValue: String): Boolean {
if (StringUtils.isEmpty(newValue) && StringUtils.isEmpty(oldValue)) {
return false
} else if (StringUtils.isEmpty(newValue) && !StringUtils.isEmpty(oldValue)) {
return true
} else
return !StringUtils.isEmpty(newValue) && StringUtils.isEmpty(
oldValue) || newValue.trim { it <= ' ' } != oldValue.trim { it <= ' ' }
}
/**
* Returns true if the string is null or 0-length.
* @param str the string to be examined
* *
* @return true if str is null or zero length
*/
fun hasNoEmptyValue(vararg str: CharSequence) = str.all { seq -> !isEmpty(seq) }
fun isEmpty(str: CharSequence?) = str == null || str.length == 0
}
}
| 0
|
Kotlin
|
0
| 0
|
131b16addee5741115b1b206025832b2bbf006d1
| 1,529
|
AndroidUtils
|
Apache License 2.0
|
finance/src/main/java/com/scitrader/finance/pane/modifiers/legend/StudyLegend.kt
|
ABTSoftware
| 468,421,926
| false
|
{"Kotlin": 296559, "Java": 3061}
|
package com.scitrader.finance.pane.modifiers.legend
import android.content.Context
import android.util.AttributeSet
import com.scichart.charting.visuals.layout.LinearViewContainer
import com.scitrader.finance.study.StudyId
import com.scitrader.finance.study.tooltips.IStudyTooltip
class StudyLegend @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : LinearViewContainer(context, attrs, defStyleAttr) {
init {
orientation = VERTICAL
}
private val studyTooltips = HashMap<StudyId, IStudyTooltip>()
var showSeriesTooltips: Boolean = false
set(value) {
if(field == value) return
field = value
for (item in studyTooltips) {
item.value.showSeriesTooltips = value
}
}
fun onStudyChanged(studyId: StudyId) {
studyTooltips[studyId]?.update()
}
fun removeTooltip(studyId: StudyId) {
studyTooltips.remove(studyId)?.removeFrom(this)
}
fun addTooltip(studyTooltip: IStudyTooltip) {
studyTooltips[studyTooltip.studyId] = studyTooltip
studyTooltip.placeInto(this)
studyTooltip.update()
studyTooltip.showSeriesTooltips = showSeriesTooltips
}
fun tryUpdateTooltips(x: Float, y: Float) {
for (item in studyTooltips) {
item.value.update(x, y)
}
}
fun tryUpdateTooltips() {
for (item in studyTooltips) {
item.value.update()
}
}
}
| 3
|
Kotlin
|
0
| 2
|
00245ef7ee93ee79b1b5a1e8a6a77bce0f02777b
| 1,496
|
Finance.Android
|
Apache License 2.0
|
app/src/main/java/com/zql/travelassistant/fragment/SettingsViewModel.kt
|
zliu80
| 596,862,076
| false
| null |
package com.zql.travelassistant.fragment
import androidx.lifecycle.ViewModel
class SettingsViewModel : ViewModel() {
// TODO: Implement the ViewModel
}
| 0
|
Kotlin
|
0
| 0
|
f6d0a9b8507e5f3d566f3578cdba231ab74b1042
| 157
|
491finalproject
|
MIT License
|
domain/src/main/java/com/demo/domain/db/AlbumDao.kt
|
Mithrandir21
| 415,935,855
| false
| null |
package com.demo.domain.db
import androidx.room.*
import com.demo.domain.model.albums.Album
import io.reactivex.rxjava3.core.Completable
import io.reactivex.rxjava3.core.Flowable
@Dao
interface AlbumDao {
/**
* Returns a single [Album] with the given [id].
* Note: Returning a List to allow for continuous observations, even if no results are found.
*/
@Query("SELECT * FROM album WHERE album.id IS :id")
fun getAlbum(id: Int): Flowable<List<Album>>
/** Returns all the [Album]s in the database, ordered by their [Album.title] in ascending order. */
@Query("SELECT * FROM album ORDER BY title ASC")
fun observeAllAlbums(): Flowable<List<Album>>
/** Adds the [Album] to the database. */
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun addAlbumCompletable(vararg genericItem: Album): Completable
/** Deletes all [Album]s from the database. */
@Query("DELETE FROM Album")
fun clearAlbumsCompletable(): Completable
/**
* Deletes all [Album]s from the database.
*
* Note: Added non-reactive method for use in the non-reactive [clearExistingAndAdd] method.
*/
@Query("DELETE FROM Album")
fun clearAlbums()
/**
* Adds the [Album] to the database.
*
* Note: Added non-reactive method for use in the non-reactive [clearExistingAndAdd] method.
*/
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun addAlbum(vararg genericItem: Album)
/** Deletes all [Album]s from the database AND then inserts all items in the given list within a single [Transaction]. */
@Transaction
fun clearExistingAndAdd(genericItems: List<Album>) {
clearAlbums()
addAlbum(*genericItems.toTypedArray())
}
}
| 0
|
Kotlin
|
0
| 0
|
09eb085fd6428750ce2825b6a7e9403f216742c8
| 1,745
|
demo
|
Apache License 2.0
|
plugins/amazonq/codetransform/jetbrains-community/src/software/aws/toolkits/jetbrains/ui/feedback/CodeTransformFeedbackDialog.kt
|
aws
| 91,485,909
| false
|
{"Kotlin": 7507266, "TypeScript": 132101, "C#": 97693, "Vue": 47529, "Java": 19596, "JavaScript": 12450, "HTML": 5878, "Python": 2939, "Shell": 2920, "Dockerfile": 2209, "SCSS": 2045, "CSS": 1827, "PowerShell": 386, "Batchfile": 77}
|
// Copyright 2024 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.aws.toolkits.jetbrains.ui.feedback
import com.intellij.openapi.project.Project
import software.aws.toolkits.jetbrains.feedback.sendFeedbackWithExperimentsMetadata
import software.aws.toolkits.jetbrains.services.codemodernizer.state.CodeModernizerSessionState
import software.aws.toolkits.resources.message
class CodeTransformFeedbackDialog(project: Project) : FeedbackDialog(project) {
init {
super.init()
title = message("feedback.title.amazonq")
}
override val productName = "Amazon Q"
override val feedbackPrompt = message("feedback.comment.textbox.title.amazonq")
override val notificationTitle = message("aws.notification.title.amazonq")
override suspend fun sendFeedback() {
val sessionState = CodeModernizerSessionState.getInstance(project)
val jobId: String = sessionState.currentJobId?.id ?: "None"
sendFeedbackWithExperimentsMetadata(
sentiment,
"Amazon Q onboarding: $commentText",
mapOf(FEEDBACK_SOURCE to "Amazon Q onboarding", "JobId" to jobId)
)
}
}
| 519
|
Kotlin
|
220
| 757
|
a81caf64a293b59056cef3f8a6f1c977be46937e
| 1,213
|
aws-toolkit-jetbrains
|
Apache License 2.0
|
chat-android/src/main/java/com/ably/chat/ErrorCodes.kt
|
ably-labs
| 842,493,008
| false
|
{"Kotlin": 99368}
|
package com.ably.chat
/**
* Error codes for the Chat SDK.
*/
object ErrorCodes {
/**
* The messages feature failed to attach.
*/
const val MessagesAttachmentFailed = 102_001
/**
* The presence feature failed to attach.
*/
const val PresenceAttachmentFailed = 102_002
/**
* The reactions feature failed to attach.
*/
const val ReactionsAttachmentFailed = 102_003
/**
* The occupancy feature failed to attach.
*/
const val OccupancyAttachmentFailed = 102_004
/**
* The typing feature failed to attach.
*/
const val TypingAttachmentFailed = 102_005
// 102006 - 102049 reserved for future use for attachment errors
/**
* The messages feature failed to detach.
*/
const val MessagesDetachmentFailed = 102_050
/**
* The presence feature failed to detach.
*/
const val PresenceDetachmentFailed = 102_051
/**
* The reactions feature failed to detach.
*/
const val ReactionsDetachmentFailed = 102_052
/**
* The occupancy feature failed to detach.
*/
const val OccupancyDetachmentFailed = 102_053
/**
* The typing feature failed to detach.
*/
const val TypingDetachmentFailed = 102_054
// 102055 - 102099 reserved for future use for detachment errors
/**
* The room has experienced a discontinuity.
*/
const val RoomDiscontinuity = 102_100
// Unable to perform operation;
/**
* Cannot perform operation because the room is in a failed state.
*/
const val RoomInFailedState = 102_101
/**
* Cannot perform operation because the room is in a releasing state.
*/
const val RoomIsReleasing = 102_102
/**
* Cannot perform operation because the room is in a released state.
*/
const val RoomIsReleased = 102_103
/**
* Cannot perform operation because the previous operation failed.
*/
const val PreviousOperationFailed = 102_104
/**
* An unknown error has happened in the room lifecycle.
*/
const val RoomLifecycleError = 102_105
/**
* The request cannot be understood
*/
const val BadRequest = 40_000
}
/**
* Http Status Codes
*/
object HttpStatusCodes {
const val BadRequest = 400
const val Unauthorized = 401
const val InternalServerError = 500
const val NotImplemented = 501
const val ServiceUnavailable = 502
const val GatewayTimeout = 503
const val Timeout = 504
}
| 8
|
Kotlin
|
0
| 1
|
b0943ab719663f2d8cf55ce7b3e69eecee711587
| 2,530
|
ably-chat-kotlin
|
Apache License 2.0
|
GUI/src/main/kotlin/frameNavigation/FrameNavigation.kt
|
amosproj
| 705,002,381
| false
|
{"Kotlin": 174558, "Python": 2014, "Shell": 588}
|
package frameNavigation
import FrameNavigationInterface
import algorithms.AlignmentElement
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.toAwtImage
import androidx.compose.ui.graphics.toComposeImageBitmap
import models.AppState
import org.bytedeco.javacv.FFmpegFrameGrabber
import wrappers.Resettable2DFrameConverter
import java.awt.image.BufferedImage
import kotlin.math.roundToInt
/**
* A class that implements the [FrameNavigationInterface] interface.
* @param state [MutableState]<[AppState]> containing the global state.
*/
class FrameNavigation(state: MutableState<AppState>) : FrameNavigationInterface {
// create the grabbers
private val video1Grabber: FFmpegFrameGrabber = FFmpegFrameGrabber(state.value.video1Path)
private val video2Grabber: FFmpegFrameGrabber = FFmpegFrameGrabber(state.value.video2Path)
private val grabberDiff: FFmpegFrameGrabber = FFmpegFrameGrabber(state.value.outputPath)
// create the sequences
private var diffSequence: Array<AlignmentElement> = state.value.sequenceObj
private var video1Frames: MutableList<Int> = mutableListOf()
private var video2Frames: MutableList<Int> = mutableListOf()
// create the converter
private val converter = Resettable2DFrameConverter()
// create the bitmaps
var video1Bitmap: MutableState<ImageBitmap> = mutableStateOf(BufferedImage(1, 1, 1).toComposeImageBitmap())
var video2Bitmap: MutableState<ImageBitmap> = mutableStateOf(BufferedImage(1, 1, 1).toComposeImageBitmap())
var diffBitmap: MutableState<ImageBitmap> = mutableStateOf(BufferedImage(1, 1, 1).toComposeImageBitmap())
// state variables for the current frame index
var currentIndex: MutableState<Int> = mutableStateOf(0)
// holds the relative position of the current frame in the diff video
// 0.0 means the first frame, 1.0 means the last frame
var currentRelativePosition: MutableState<Double> = mutableStateOf(0.0)
init {
// start the grabbers
video1Grabber.start()
video2Grabber.start()
grabberDiff.start()
// generate the sequences for video 1 and video 2
// diffSequence is already generated
generateSequences()
// jump to the first frame
jumpToFrame(0)
}
/**
* Close the grabbers.
*/
fun close() {
video1Grabber.stop()
video2Grabber.stop()
grabberDiff.stop()
video1Grabber.close()
video2Grabber.close()
grabberDiff.close()
}
/**
* Generate the sequences for video 1 and video 2.
*/
private fun generateSequences() {
// init with -1 to account for deletions/insertions on the first frame
video1Frames.add(-1)
video2Frames.add(-1)
for (i in diffSequence) {
when (i) {
AlignmentElement.MATCH -> {
video1Frames.add(video1Frames.last() + 1)
video2Frames.add(video2Frames.last() + 1)
}
AlignmentElement.INSERTION -> {
video1Frames.add(video1Frames.last())
video2Frames.add(video2Frames.last() + 1)
}
AlignmentElement.DELETION -> {
video1Frames.add(video1Frames.last() + 1)
video2Frames.add(video2Frames.last())
}
AlignmentElement.PERFECT -> {
video1Frames.add(video1Frames.last() + 1)
video2Frames.add(video2Frames.last() + 1)
}
}
}
// remove the initial -1
video1Frames.removeAt(0)
video2Frames.removeAt(0)
}
/**
* Jump n frames in a specified direction.
* @param frames [Int] containing the number of frames to jump.
* @return [Unit]
*/
override fun jumpFrames(frames: Int) {
jumpToFrame(grabberDiff.frameNumber + frames)
}
/**
* Jump to a specified percentage of the diff video.
* @param percentage [Double] containing the percentage to jump to, between 0 and 1.
*/
override fun jumpToPercentage(percentage: Double) {
// check bounds
if (percentage < 0.0 || percentage > 1.0) {
throw Exception("Percentage must be between 0.0 and 1.0")
}
// calculate the index to jump to; round to the nearest whole integer
val diffFrame = ((diffSequence.size - 1).toDouble() * percentage).roundToInt()
// check if the frame is already displayed
if (diffFrame == currentIndex.value) {
return
}
// jump to the frame
jumpToFrame(diffFrame)
}
/**
* Jump to a concretely specified frame.
* @param index [Int] containing the index of the frame to jump to.
* @return [Unit]
*/
override fun jumpToFrame(index: Int) {
// check bounds
val boundedIndex = index.coerceIn(0, diffSequence.size - 1)
currentIndex.value = boundedIndex
currentRelativePosition.value = boundedIndex.toDouble() / (diffSequence.size - 1).toDouble()
// jump to the frame in each video by mapping the frame using the generated sequences
video1Grabber.setVideoFrameNumber(video1Frames[boundedIndex])
video2Grabber.setVideoFrameNumber(video2Frames[boundedIndex])
grabberDiff.setVideoFrameNumber(boundedIndex)
// update the bitmaps
video1Bitmap.value = getBitmap(video1Grabber)
video2Bitmap.value = getBitmap(video2Grabber)
diffBitmap.value = getBitmap(grabberDiff)
}
/**
* Get the bitmap of the current frame of the grabber.
* @param grabber [FFmpegFrameGrabber] containing the grabber to get the bitmap from.
* @return [ImageBitmap] containing the bitmap of the current frame.
*/
private fun getBitmap(grabber: FFmpegFrameGrabber): ImageBitmap {
// check bounds
if (grabber.frameNumber < 0 || grabber.frameNumber >= grabber.lengthInFrames) {
// return a blank image
val bufferedIm = BufferedImage(grabber.imageWidth, grabber.imageHeight, BufferedImage.TYPE_INT_RGB)
return bufferedIm.toComposeImageBitmap()
}
// grab the image
return converter.convert(grabber.grabImage()).toComposeImageBitmap()
}
/**
* Jump to the next diff.
* @param forward [Boolean] containing whether to jump forward or backward.
* @return [Unit]
*/
override fun jumpToNextDiff(forward: Boolean) {
// get the current frame
var index = currentIndex.value
// create a function that increments or decrements the index
val op: (Int) -> Int = if (forward) { x: Int -> x + 1 } else { x: Int -> x - 1 }
// ignore current frame by jumping once
index = op(index)
// jump until a diff is found or the end is reached
while (index >= 0 && index < diffSequence.size && diffSequence[index] == AlignmentElement.PERFECT) {
index = op(index)
}
// jump to the frame
jumpToFrame(index)
}
/**
* Get count of frames in diff
* @return [Int] containing the number of frames in the diff.
*/
override fun getSizeOfDiff(): Int {
return diffSequence.size
}
/**
* Get count of frames in video1
* @return [Int] containing the number of frames in the first video.
*/
fun getSizeOfVideo1(): Int {
return video1Frames.size
}
/**
* Get count of frames in video2
* @return [Int] containing the number of frames in the second video.
*/
fun getSizeOfVideo2(): Int {
return video2Frames.size
}
/**
* Get count of insertions
* @return [Int] containing the number of insertions.
*/
fun getInsertions(): Int {
return diffSequence.count { it == AlignmentElement.INSERTION }
}
/**
* Get count of deletions
* @return [Int] containing the number of deletions.
*/
fun getDeletions(): Int {
return diffSequence.count { it == AlignmentElement.DELETION }
}
/**
* Get count of frames with pixel differences
* @return [Int] containing the number of frames with pixel differences.
*/
fun getFramesWithPixelDifferences(): Int {
return diffSequence.count { it == AlignmentElement.MATCH }
}
/**
* Creates a collage of the 3 videos and saves it to a file.
* @param outputPath [String] containing the path to save the collage to.
* @param border [Int] containing the width of the border between the videos.
* @param titleHeight [Int] containing the height of the title.
* @param font [java.awt.Font] containing the font to use for the title.
* @return [Unit]
*/
fun createCollage(
outputPath: String,
border: Int = 20,
titleHeight: Int = 100,
font: java.awt.Font =
java.awt.Font(
"Arial",
java.awt.Font.BOLD,
100,
),
) {
val width = video1Grabber.imageWidth
var xOffset = 0
// create the collage
val collage = BufferedImage(width * 3 + border * 2, video1Grabber.imageHeight + titleHeight, BufferedImage.TYPE_INT_RGB)
val g = collage.createGraphics()
// fill the background with white
g.color = java.awt.Color.WHITE
g.fillRect(0, 0, collage.width, collage.height)
// draw the images
for (item in listOf(video1Bitmap, diffBitmap, video2Bitmap)) {
val img = item.value.toAwtImage()
g.drawImage(img, xOffset, titleHeight, null)
xOffset += width + border
}
// draw the titles
g.color = java.awt.Color.BLACK
g.font = font
xOffset = 0
for (item in listOf("Video 1", "Diff", "Video 2")) {
val metrics = g.fontMetrics
val x = (width - metrics.stringWidth(item)) / 2
g.drawString(item, x + xOffset, titleHeight - 10)
xOffset += width + border
}
// save the collage
val file = java.io.File("$outputPath.png")
javax.imageio.ImageIO.write(collage, "png", file)
}
}
| 59
|
Kotlin
|
2
| 6
|
eac092621fd0e53eb12b948f8aef19f5c47df710
| 10,382
|
amos2023ws03-gui-frame-diff
|
MIT License
|
owntracks-android-2.5/project/app/src/androidTest/java/org/owntracks/android/data/waypoints/WaypointsMigrationFromObjectboxTest.kt
|
wir3z
| 737,346,188
| false
|
{"Kotlin": 928031, "Groovy": 381781, "Java": 12862, "Shell": 4540}
|
package org.owntracks.android.data.waypoints
import android.content.Context
import androidx.test.core.app.ApplicationProvider
import androidx.test.espresso.Espresso
import androidx.test.filters.SmallTest
import androidx.test.platform.app.InstrumentationRegistry
import kotlin.time.Duration.Companion.minutes
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import org.owntracks.android.testutils.idlingresources.EspressoTrackedDispatcher
import org.owntracks.android.testutils.use
@SmallTest
@RunWith(Parameterized::class)
class WaypointsMigrationFromObjectboxTest(private val parameter: Parameter) {
@Before
fun clearLocalPackageData() {
InstrumentationRegistry.getInstrumentation().targetContext.deleteDatabase("waypoints")
}
@Test
fun migratingAnObjectboxProducesCorrectNumberOfWaypoints() {
val context = ApplicationProvider.getApplicationContext<Context>()
val dataBytes =
this.javaClass.getResource("/objectbox-lmdbs/${parameter.dbName}/data.mdb")!!.readBytes()
context.filesDir.resolve("objectbox/objectbox/").run {
mkdirs()
resolve("data.mdb").run { outputStream().use { it.write(dataBytes) } }
}
val dispatcher = EspressoTrackedDispatcher(Dispatchers.IO)
dispatcher.idlingResource.use(2.minutes) {
val roomWaypointsRepo =
RoomWaypointsRepo(context, dispatcher, CoroutineScope(SupervisorJob()))
roomWaypointsRepo.migrateFromLegacyStorage()
Espresso.onIdle()
assertEquals(parameter.expectedCount, roomWaypointsRepo.all.size)
}
}
data class Parameter(val dbName: String, val expectedCount: Int)
companion object {
@JvmStatic
@Parameterized.Parameters(name = "(dbname={1},expected={2})")
fun data(): Iterable<Parameter> {
return arrayListOf(
Parameter("single-waypoint", 1),
Parameter("10-waypoints", 10),
Parameter("5000-waypoints", 5000),
Parameter("empty", 0),
Parameter("3-created-by-real-device", 3))
}
}
}
| 0
|
Kotlin
|
3
| 5
|
c8a9c15dfd402e126ab7a2a5316b316c80142cfb
| 2,223
|
hubitat
|
Apache License 2.0
|
src/main/kotlin/no/nav/syfo/infrastructure/kafka/AktivitetskravVarselProducer.kt
|
navikt
| 554,767,872
| false
|
{"Kotlin": 508056, "Dockerfile": 226}
|
package no.nav.syfo.infrastructure.kafka
import no.nav.syfo.infrastructure.kafka.domain.KafkaAktivitetskravVarsel
import org.apache.kafka.clients.producer.KafkaProducer
import org.apache.kafka.clients.producer.ProducerRecord
import org.slf4j.LoggerFactory
import java.util.*
class AktivitetskravVarselProducer(private val kafkaProducer: KafkaProducer<String, KafkaAktivitetskravVarsel>) {
fun sendAktivitetskravVarsel(
varsel: KafkaAktivitetskravVarsel,
) {
val key = UUID.nameUUIDFromBytes(varsel.personIdent.toByteArray()).toString()
try {
kafkaProducer.send(
ProducerRecord(
AKTIVITETSKRAV_VARSEL_TOPIC,
key,
varsel,
)
).get()
log.info(
"Varsel with uuid: {} published",
varsel.varselUuid
)
} catch (e: Exception) {
log.error(
"Exception was thrown when attempting to send KafkaAktivitetskravVarsel with id {}: ${e.message}",
key
)
throw e
}
}
companion object {
const val AKTIVITETSKRAV_VARSEL_TOPIC = "teamsykefravr.aktivitetskrav-varsel"
private val log = LoggerFactory.getLogger(AktivitetskravVarselProducer::class.java)
}
}
| 3
|
Kotlin
|
1
| 0
|
55c4a23f24c6776d947cafc6788d23f919c84de5
| 1,352
|
isaktivitetskrav
|
MIT License
|
stytch/src/main/kotlin/com/stytch/java/consumer/api/m2mclients/M2MClients.kt
|
stytchauth
| 665,684,154
| false
|
{"Kotlin": 1170620}
|
package com.stytch.java.consumer.api.m2mclients
// !!!
// WARNING: This file is autogenerated
// Only modify code within MANUAL() sections
// or your changes may be overwritten later!
// !!!
import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.Moshi
import com.squareup.moshi.Types
import com.stytch.java.common.InstantAdapter
import com.stytch.java.common.StytchResult
import com.stytch.java.consumer.api.m2mclientssecrets.Secrets
import com.stytch.java.consumer.api.m2mclientssecrets.SecretsImpl
import com.stytch.java.consumer.models.m2mclients.CreateRequest
import com.stytch.java.consumer.models.m2mclients.CreateResponse
import com.stytch.java.consumer.models.m2mclients.DeleteRequest
import com.stytch.java.consumer.models.m2mclients.DeleteResponse
import com.stytch.java.consumer.models.m2mclients.GetRequest
import com.stytch.java.consumer.models.m2mclients.GetResponse
import com.stytch.java.consumer.models.m2mclients.SearchRequest
import com.stytch.java.consumer.models.m2mclients.SearchResponse
import com.stytch.java.consumer.models.m2mclients.UpdateRequest
import com.stytch.java.consumer.models.m2mclients.UpdateResponse
import com.stytch.java.http.HttpClient
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.future.asCompletableFuture
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.concurrent.CompletableFuture
public interface Clients {
public val secrets: Secrets
/**
* Gets information about an existing M2M Client.
*/
public suspend fun get(data: GetRequest): StytchResult<GetResponse>
/**
* Gets information about an existing M2M Client.
*/
public fun get(data: GetRequest, callback: (StytchResult<GetResponse>) -> Unit)
/**
* Gets information about an existing M2M Client.
*/
public fun getCompletable(data: GetRequest): CompletableFuture<StytchResult<GetResponse>>
/**
* Search for M2M Clients within your Stytch Project. Submit an empty `query` in the request to return all M2M Clients.
*
* The following search filters are supported today:
* - `client_id`: Pass in a list of client IDs to get many clients in a single request
* - `client_name`: Search for clients by exact match on client name
* - `scopes`: Search for clients assigned a specific scope
*/
public suspend fun search(data: SearchRequest): StytchResult<SearchResponse>
/**
* Search for M2M Clients within your Stytch Project. Submit an empty `query` in the request to return all M2M Clients.
*
* The following search filters are supported today:
* - `client_id`: Pass in a list of client IDs to get many clients in a single request
* - `client_name`: Search for clients by exact match on client name
* - `scopes`: Search for clients assigned a specific scope
*/
public fun search(data: SearchRequest, callback: (StytchResult<SearchResponse>) -> Unit)
/**
* Search for M2M Clients within your Stytch Project. Submit an empty `query` in the request to return all M2M Clients.
*
* The following search filters are supported today:
* - `client_id`: Pass in a list of client IDs to get many clients in a single request
* - `client_name`: Search for clients by exact match on client name
* - `scopes`: Search for clients assigned a specific scope
*/
public fun searchCompletable(data: SearchRequest): CompletableFuture<StytchResult<SearchResponse>>
/**
* Updates an existing M2M Client. You can use this endpoint to activate or deactivate a M2M Client by changing its
* `status`. A deactivated M2M Client will not be allowed to perform future token exchange flows until it is reactivated.
*
* **Important:** Deactivating a M2M Client will not invalidate any existing JWTs issued to the client, only prevent it
* from receiving new ones.
* To protect more-sensitive routes, pass a lower `max_token_age` value
* when[authenticating the token](https://stytch.com/docs/b2b/api/authenticate-m2m-token)[authenticating the token](https://stytch.com/docs/api/authenticate-m2m-token).
*/
public suspend fun update(data: UpdateRequest): StytchResult<UpdateResponse>
/**
* Updates an existing M2M Client. You can use this endpoint to activate or deactivate a M2M Client by changing its
* `status`. A deactivated M2M Client will not be allowed to perform future token exchange flows until it is reactivated.
*
* **Important:** Deactivating a M2M Client will not invalidate any existing JWTs issued to the client, only prevent it
* from receiving new ones.
* To protect more-sensitive routes, pass a lower `max_token_age` value
* when[authenticating the token](https://stytch.com/docs/b2b/api/authenticate-m2m-token)[authenticating the token](https://stytch.com/docs/api/authenticate-m2m-token).
*/
public fun update(data: UpdateRequest, callback: (StytchResult<UpdateResponse>) -> Unit)
/**
* Updates an existing M2M Client. You can use this endpoint to activate or deactivate a M2M Client by changing its
* `status`. A deactivated M2M Client will not be allowed to perform future token exchange flows until it is reactivated.
*
* **Important:** Deactivating a M2M Client will not invalidate any existing JWTs issued to the client, only prevent it
* from receiving new ones.
* To protect more-sensitive routes, pass a lower `max_token_age` value
* when[authenticating the token](https://stytch.com/docs/b2b/api/authenticate-m2m-token)[authenticating the token](https://stytch.com/docs/api/authenticate-m2m-token).
*/
public fun updateCompletable(data: UpdateRequest): CompletableFuture<StytchResult<UpdateResponse>>
/**
* Deletes the M2M Client.
*
* **Important:** Deleting a M2M Client will not invalidate any existing JWTs issued to the client, only prevent it from
* receiving new ones.
* To protect more-sensitive routes, pass a lower `max_token_age` value
* when[authenticating the token](https://stytch.com/docs/b2b/api/authenticate-m2m-token)[authenticating the token](https://stytch.com/docs/api/authenticate-m2m-token).
*/
public suspend fun delete(data: DeleteRequest): StytchResult<DeleteResponse>
/**
* Deletes the M2M Client.
*
* **Important:** Deleting a M2M Client will not invalidate any existing JWTs issued to the client, only prevent it from
* receiving new ones.
* To protect more-sensitive routes, pass a lower `max_token_age` value
* when[authenticating the token](https://stytch.com/docs/b2b/api/authenticate-m2m-token)[authenticating the token](https://stytch.com/docs/api/authenticate-m2m-token).
*/
public fun delete(data: DeleteRequest, callback: (StytchResult<DeleteResponse>) -> Unit)
/**
* Deletes the M2M Client.
*
* **Important:** Deleting a M2M Client will not invalidate any existing JWTs issued to the client, only prevent it from
* receiving new ones.
* To protect more-sensitive routes, pass a lower `max_token_age` value
* when[authenticating the token](https://stytch.com/docs/b2b/api/authenticate-m2m-token)[authenticating the token](https://stytch.com/docs/api/authenticate-m2m-token).
*/
public fun deleteCompletable(data: DeleteRequest): CompletableFuture<StytchResult<DeleteResponse>>
/**
* Creates a new M2M Client. On initial client creation, you may pass in a custom `client_id` or `client_secret` to import
* an existing M2M client. If you do not pass in a custom `client_id` or `client_secret`, one will be generated
* automatically. The `client_id` must be unique among all clients in your project.
*
* **Important:** This is the only time you will be able to view the generated `client_secret` in the API response. Stytch
* stores a hash of the `client_secret` and cannot recover the value if lost. Be sure to persist the `client_secret` in a
* secure location. If the `client_secret` is lost, you will need to trigger a secret rotation flow to receive another one.
*/
public suspend fun create(data: CreateRequest): StytchResult<CreateResponse>
/**
* Creates a new M2M Client. On initial client creation, you may pass in a custom `client_id` or `client_secret` to import
* an existing M2M client. If you do not pass in a custom `client_id` or `client_secret`, one will be generated
* automatically. The `client_id` must be unique among all clients in your project.
*
* **Important:** This is the only time you will be able to view the generated `client_secret` in the API response. Stytch
* stores a hash of the `client_secret` and cannot recover the value if lost. Be sure to persist the `client_secret` in a
* secure location. If the `client_secret` is lost, you will need to trigger a secret rotation flow to receive another one.
*/
public fun create(data: CreateRequest, callback: (StytchResult<CreateResponse>) -> Unit)
/**
* Creates a new M2M Client. On initial client creation, you may pass in a custom `client_id` or `client_secret` to import
* an existing M2M client. If you do not pass in a custom `client_id` or `client_secret`, one will be generated
* automatically. The `client_id` must be unique among all clients in your project.
*
* **Important:** This is the only time you will be able to view the generated `client_secret` in the API response. Stytch
* stores a hash of the `client_secret` and cannot recover the value if lost. Be sure to persist the `client_secret` in a
* secure location. If the `client_secret` is lost, you will need to trigger a secret rotation flow to receive another one.
*/
public fun createCompletable(data: CreateRequest): CompletableFuture<StytchResult<CreateResponse>>
}
internal class ClientsImpl(
private val httpClient: HttpClient,
private val coroutineScope: CoroutineScope,
) : Clients {
private val moshi = Moshi.Builder().add(InstantAdapter()).build()
override val secrets: Secrets = SecretsImpl(httpClient, coroutineScope)
override suspend fun get(data: GetRequest): StytchResult<GetResponse> = withContext(Dispatchers.IO) {
val asJson = moshi.adapter(GetRequest::class.java).toJson(data)
val type = Types.newParameterizedType(Map::class.java, String::class.java, Any::class.java)
val adapter: JsonAdapter<Map<String, Any>> = moshi.adapter(type)
val asMap = adapter.fromJson(asJson) ?: emptyMap()
httpClient.get("/v1/m2m/clients/${data.clientId}", asMap)
}
override fun get(data: GetRequest, callback: (StytchResult<GetResponse>) -> Unit) {
coroutineScope.launch {
callback(get(data))
}
}
override fun getCompletable(data: GetRequest): CompletableFuture<StytchResult<GetResponse>> =
coroutineScope.async {
get(data)
}.asCompletableFuture()
override suspend fun search(data: SearchRequest): StytchResult<SearchResponse> = withContext(Dispatchers.IO) {
val asJson = moshi.adapter(SearchRequest::class.java).toJson(data)
httpClient.post("/v1/m2m/clients/search", asJson)
}
override fun search(data: SearchRequest, callback: (StytchResult<SearchResponse>) -> Unit) {
coroutineScope.launch {
callback(search(data))
}
}
override fun searchCompletable(data: SearchRequest): CompletableFuture<StytchResult<SearchResponse>> =
coroutineScope.async {
search(data)
}.asCompletableFuture()
override suspend fun update(data: UpdateRequest): StytchResult<UpdateResponse> = withContext(Dispatchers.IO) {
val asJson = moshi.adapter(UpdateRequest::class.java).toJson(data)
httpClient.put("/v1/m2m/clients/${data.clientId}", asJson)
}
override fun update(data: UpdateRequest, callback: (StytchResult<UpdateResponse>) -> Unit) {
coroutineScope.launch {
callback(update(data))
}
}
override fun updateCompletable(data: UpdateRequest): CompletableFuture<StytchResult<UpdateResponse>> =
coroutineScope.async {
update(data)
}.asCompletableFuture()
override suspend fun delete(data: DeleteRequest): StytchResult<DeleteResponse> = withContext(Dispatchers.IO) {
httpClient.delete("/v1/m2m/clients/${data.clientId}")
}
override fun delete(data: DeleteRequest, callback: (StytchResult<DeleteResponse>) -> Unit) {
coroutineScope.launch {
callback(delete(data))
}
}
override fun deleteCompletable(data: DeleteRequest): CompletableFuture<StytchResult<DeleteResponse>> =
coroutineScope.async {
delete(data)
}.asCompletableFuture()
override suspend fun create(data: CreateRequest): StytchResult<CreateResponse> = withContext(Dispatchers.IO) {
val asJson = moshi.adapter(CreateRequest::class.java).toJson(data)
httpClient.post("/v1/m2m/clients", asJson)
}
override fun create(data: CreateRequest, callback: (StytchResult<CreateResponse>) -> Unit) {
coroutineScope.launch {
callback(create(data))
}
}
override fun createCompletable(data: CreateRequest): CompletableFuture<StytchResult<CreateResponse>> =
coroutineScope.async {
create(data)
}.asCompletableFuture()
}
| 1
|
Kotlin
|
3
| 8
|
2913009c79852c9f7bccea41e24b2a3bcc2295c3
| 13,574
|
stytch-java
|
MIT License
|
plugins/kotlin/gradle/gradle-java/tests/test/org/jetbrains/kotlin/idea/codeInsight/gradle/CommonizerImportAndCheckHighlightingTest.kt
|
ingokegel
| 72,937,917
| false
| null |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.codeInsight.gradle
import com.intellij.lang.annotation.HighlightSeverity
import com.intellij.openapi.externalSystem.model.project.LibraryLevel
import com.intellij.openapi.project.rootManager
import com.intellij.openapi.roots.DependencyScope.COMPILE
import com.intellij.openapi.roots.DependencyScope.PROVIDED
import com.intellij.openapi.roots.LibraryOrderEntry
import com.intellij.openapi.roots.OrderRootType
import com.intellij.openapi.util.SystemInfo
import org.jetbrains.kotlin.tooling.core.KotlinToolingVersion
import org.junit.Assume
import org.junit.Test
import java.io.PrintStream
import java.util.*
class CommonizerImportAndCheckHighlightingTest : MultiplePluginVersionGradleImportingTestCase() {
override fun testDataDirName(): String = "multiplatform/commonizerImportAndCheckHighlighting"
override fun printOutput(stream: PrintStream, text: String) = stream.println(text)
override fun setUp() {
val testedVersions = setOf(KotlinGradlePluginVersions.lastStable, KotlinGradlePluginVersions.latest)
Assume.assumeTrue(
"CommonizerImportAndCheckHighlightingTest only runs against $testedVersions",
kotlinPluginVersion in testedVersions,
)
super.setUp()
}
@Test
fun testWithPosix() {
configureByFiles()
importProject(false)
val highlightingCheck = createHighlightingCheck()
checkProjectStructure(false, false, false) {
val scope = if (isKgpDependencyResolutionEnabled()) COMPILE else PROVIDED
module("project.p1.nativeMain") {
highlightingCheck(module)
libraryDependencyByUrl(Regex(""".*withPosix.*"""), scope)
libraryDependencyByUrl(Regex(""".*posix.*"""), scope)
}
module("project.p1.appleAndLinuxMain") {
if (SystemInfo.isMac || SystemInfo.isLinux) {
highlightingCheck(module)
libraryDependencyByUrl(Regex(""".*withPosix.*"""), scope)
libraryDependencyByUrl(Regex(""".*posix.*"""), scope)
}
}
module("project.p1.linuxMain") {
if (SystemInfo.isMac || SystemInfo.isLinux) {
highlightingCheck(module)
libraryDependencyByUrl(Regex(""".*withPosix.*"""), scope)
libraryDependencyByUrl(Regex(""".*posix.*"""), scope)
}
}
module("project.p1.appleMain") {
if (SystemInfo.isMac) {
highlightingCheck(module)
libraryDependencyByUrl(Regex(""".*withPosix.*"""), scope)
libraryDependencyByUrl(Regex(""".*posix.*"""), scope)
}
}
module("project.p1.iosMain") {
if (SystemInfo.isMac) {
highlightingCheck(module)
libraryDependencyByUrl(Regex(""".*withPosix.*"""), scope)
libraryDependencyByUrl(Regex(""".*posix.*"""), scope)
}
}
module("project.p1.linuxArm64Main") {
if (SystemInfo.isMac || SystemInfo.isLinux) {
highlightingCheck(module)
libraryDependencyByUrl(Regex(""".*withPosix.*"""), scope)
if (kotlinPluginVersion < KotlinToolingVersion("1.5.30-dev")) {
libraryDependencyByUrl(Regex(""".*/\(linux_arm64, linux_x64\)/.*posix.*"""), scope)
}
libraryDependencyByUrl(Regex(""".*/linux_arm64/.*posix.*"""), scope)
}
}
module("project.p1.linuxX64Main") {
if (SystemInfo.isMac || SystemInfo.isLinux) {
highlightingCheck(module)
libraryDependencyByUrl(Regex(""".*withPosix.*"""), scope)
if (kotlinPluginVersion < KotlinToolingVersion("1.5.30-dev")) {
libraryDependencyByUrl(Regex(""".*/\(linux_arm64, linux_x64\)/.*posix.*"""), scope)
}
libraryDependencyByUrl(Regex(""".*/linux_x64/.*posix.*"""), scope)
}
}
module("project.p1.macosMain") {
if (SystemInfo.isMac) {
highlightingCheck(module)
libraryDependencyByUrl(Regex(""".*withPosix.*"""), scope)
if (kotlinPluginVersion < KotlinToolingVersion("1.5.30-dev")) {
libraryDependencyByUrl(Regex(""".*/\(.*macos_x64.*\)/.*posix.*"""), scope)
}
libraryDependencyByUrl(Regex(""".*/macos_x64/.*posix.*"""), scope)
}
}
module("project.p1.windowsMain") {
if (SystemInfo.isWindows) {
highlightingCheck(module)
libraryDependencyByUrl(Regex(""".*withPosix.*"""), scope)
libraryDependencyByUrl(Regex(""".*posix.*"""), scope)
}
}
}
}
@Test
fun testSingleNativeTarget() {
configureByFiles()
importProject()
val highlightingCheck = createHighlightingCheck()
checkProjectStructure(false, false, false) {
val scope = if (isKgpDependencyResolutionEnabled()) COMPILE else PROVIDED
module("project.p1.nativeMain") {
highlightingCheck(module)
libraryDependency(Regex("""Kotlin/Native.*posix.*"""), scope)
}
module("project.p1.commonMain") {
highlightingCheck(module)
libraryDependency(Regex("""Kotlin/Native.*posix.*"""), scope)
}
}
}
@Test
fun testSingleSupportedNativeTargetDependencyPropagation() {
configureByFiles()
importProject()
val highlightingCheck = createHighlightingCheck(severityLevel = HighlightSeverity.ERROR)
checkProjectStructure(false, false, false) {
module("project.p1.commonMain") {
highlightingCheck(module)
}
val scope = if (isKgpDependencyResolutionEnabled()) COMPILE else PROVIDED
module("project.p1.nativeMainParent") {
highlightingCheck(module)
libraryDependencyByUrl(Regex(""".*posix.*"""), scope)
}
module("project.p1.nativeMain") {
highlightingCheck(module)
libraryDependencyByUrl(Regex(""".*posix.*"""), scope)
}
module("project.p1.nativePlatformMain") {
highlightingCheck(module)
val posixDependencies = module.rootManager.orderEntries.filterIsInstance<LibraryOrderEntry>().filter { entry ->
entry.library?.getUrls(OrderRootType.CLASSES)?.any { it.matches(Regex(""".*posix.*""")) } ?: false
}
if (posixDependencies.isEmpty()) {
report("Missing dependency on posix")
}
if (posixDependencies.size > 2) {
// Gradle plugin detail whether it decides to use commonized expect/actual, or just the original klib
report("Expected one or two dependencies on posix")
}
}
}
}
@Test
fun testLibraryNamesAndLevel() {
configureByFiles()
importProject(true)
checkProjectStructure(false, false, false) {
module("project.p1.nativeMain") {
/**
* Assert that a commonized Library, coming from the native distribution
* has a proper libraryName and is considered 'project level'
*/
run {
val posixLibraryNameRegex = nativeDistLibraryDependency("posix", libraryPlatform = null)
val posixEntriesMatchingNamingScheme = module.rootManager.orderEntries
.filterIsInstance<LibraryOrderEntry>()
.filter { it.libraryName.orEmpty().matches(posixLibraryNameRegex) }
assertEquals(
"Expected exactly one library matching the posix naming schema",
1, posixEntriesMatchingNamingScheme.size
)
val posix = posixEntriesMatchingNamingScheme.single()
assertEquals(
"Expected posix being 'PROJECT' level",
LibraryLevel.PROJECT.name.lowercase(Locale.getDefault()),
posix.libraryLevel.lowercase(Locale.getDefault()),
)
}
/**
* Assert that a commonized library, coming from a project's c-interop
* has a proper libraryName and is *not* considered 'project level'
*/
run {
val withPosixLibraryNameRegex = Regex(
"""(Gradle: )?project:p1-cinterop-withPosix.*\(linux_arm64, linux_x64, macos_x64, mingw_x64\).*"""
)
val libraryOrderEntries = module.rootManager.orderEntries
.filterIsInstance<LibraryOrderEntry>()
val withPosixEntriesMatchingNamingScheme = libraryOrderEntries
.filter { it.libraryName.orEmpty().matches(withPosixLibraryNameRegex) }
assertEquals(
"Expected exactly one library matching 'withPosix' naming schema\n" +
"Libraries: ${libraryOrderEntries.map { it.libraryName }}",
1, withPosixEntriesMatchingNamingScheme.size
)
val withPosix = withPosixEntriesMatchingNamingScheme.single()
if (!isKgpDependencyResolutionEnabled()) { // FIXME: KTIJ-24560
assertEquals(
"Expected 'withPosix' (c-interop) to be 'module level'",
LibraryLevel.MODULE.name.lowercase(Locale.getDefault()),
withPosix.libraryLevel.lowercase(Locale.getDefault())
)
}
}
}
module("project.p1.linuxX64Main") {
/**
* Assert that a library coming from the native distribution has the correct libraryName
* and is considered 'project level' for a leaf source set
*/
run {
val posixLibraryNameRegex = nativeDistLibraryDependency("posix", null)
val posixEntriesMatchingNamingScheme = module.rootManager.orderEntries
.filterIsInstance<LibraryOrderEntry>()
.filter { it.libraryName.orEmpty().matches(posixLibraryNameRegex) }
assertTrue(
"Expected one or two posix order entries for posix on a leaf source set",
posixEntriesMatchingNamingScheme.isNotEmpty() && posixEntriesMatchingNamingScheme.size <= 2
)
posixEntriesMatchingNamingScheme.forEach { posix ->
assertEquals(
"Expected posix being 'PROJECT' level",
LibraryLevel.PROJECT.name.lowercase(Locale.getDefault()),
posix.libraryLevel.lowercase(Locale.getDefault()),
)
}
}
/**
* Assert that a c-interop library has the correct libraryName and scope on a leaf source set.
*/
run {
val withPosixLibraryNameRegex = Regex(
"""(Gradle: )?project:p1-cinterop-withPosix( \| |:)linux_x64"""
)
val withPosixEntriesMatchingNamingScheme = module.rootManager.orderEntries
.filterIsInstance<LibraryOrderEntry>()
.filter { it.libraryName.orEmpty().matches(withPosixLibraryNameRegex) }
assertEquals(
"Expected exactly one library matching 'withPosixLibraryNameRegex'",
1, withPosixEntriesMatchingNamingScheme.size
)
val withPosix = withPosixEntriesMatchingNamingScheme.single()
if (!isKgpDependencyResolutionEnabled()) { // FIXME: KTIJ-24560
assertEquals(
"Expected 'withPosix' (c-interop) to be 'module level'",
LibraryLevel.MODULE.name.lowercase(Locale.getDefault()),
withPosix.libraryLevel.lowercase(Locale.getDefault())
)
}
}
}
}
}
}
| 236
| null |
4946
| 2
|
b07eabd319ad5b591373d63c8f502761c2b2dfe8
| 13,233
|
intellij-community
|
Apache License 2.0
|
src/main/kotlin/br/com/jiratorio/parser/EstimateIssueParser.kt
|
andrelugomes
| 230,294,644
| false
| null |
package br.com.jiratorio.parser
import br.com.jiratorio.aspect.annotation.ExecutionTime
import br.com.jiratorio.domain.FluxColumn
import br.com.jiratorio.domain.entity.Board
import br.com.jiratorio.domain.estimate.EstimateIssue
import br.com.jiratorio.domain.impediment.calculator.ImpedimentCalculatorResult
import br.com.jiratorio.extension.extractValue
import br.com.jiratorio.extension.extractValueNotNull
import br.com.jiratorio.extension.fromJiraToLocalDateTime
import br.com.jiratorio.extension.log
import br.com.jiratorio.extension.parallelStream
import br.com.jiratorio.extension.time.daysDiff
import br.com.jiratorio.service.ChangelogService
import br.com.jiratorio.service.HolidayService
import com.fasterxml.jackson.databind.JsonNode
import org.springframework.stereotype.Component
import java.time.LocalDate
import java.time.LocalDateTime
import kotlin.streams.toList
@Component
class EstimateIssueParser(
private val holidayService: HolidayService,
private val changelogService: ChangelogService,
private val changelogParser: ChangelogParser
) {
@ExecutionTime
fun parseEstimate(root: JsonNode, board: Board): List<EstimateIssue> {
val holidays = holidayService.findDaysByBoard(board.id)
val fluxColumn = FluxColumn(board)
val startColumns = fluxColumn.startColumns
return root.path("issues")
.parallelStream()
.map { jsonNodeToEstimateIssue(it, board, startColumns, holidays) }
.toList()
.filterNotNull()
}
private fun jsonNodeToEstimateIssue(
jsonNode: JsonNode,
board: Board,
startColumns: Set<String>,
holidays: List<LocalDate>
): EstimateIssue? =
try {
parseIssue(jsonNode, board, startColumns, holidays)
} catch (e: Exception) {
log.error(
"Method=jsonNodeToIssue, info=Error parsing estimate Issue, issue={}, err={}",
jsonNode.path("key").extractValue(), e.message
)
throw e
}
private fun parseIssue(
issue: JsonNode,
board: Board,
startColumns: Set<String>,
holidays: List<LocalDate>
): EstimateIssue? {
val fields = issue.path("fields")
val created = fields.path("created")
.extractValueNotNull().fromJiraToLocalDateTime()
val changelogItems = changelogParser.extractChangelogItems(issue)
val changelog = changelogService.parseChangelog(changelogItems, created, holidays, board.ignoreWeekend)
if (changelog.isNotEmpty()) {
val changelogItem = changelog.last()
changelogItem.leadTime = changelogItem.created.daysDiff(
LocalDateTime.now(),
holidays,
board.ignoreWeekend
)
changelogItem.endDate = LocalDateTime.now()
}
var startDate: LocalDateTime? = null
for (cl in changelog) {
if (startDate == null && startColumns.contains(cl.to?.toUpperCase())) {
startDate = cl.created
}
}
if ("BACKLOG" == board.startColumn) {
startDate = fields.get("created")
.extractValueNotNull().fromJiraToLocalDateTime()
}
if (startDate == null) {
return null
}
val priority: String? =
if (fields.hasNonNull("priority")) {
fields.path("priority").extractValue()
} else {
null
}
val leadTime = startDate.daysDiff(LocalDateTime.now(), holidays, board.ignoreWeekend)
val impedimentCalculatorResult = board.impedimentType?.calcImpediment(
board.impedimentColumns,
changelogItems,
changelog,
LocalDateTime.now(),
holidays,
board.ignoreWeekend
) ?: ImpedimentCalculatorResult()
val author: String? =
if (fields.hasNonNull("creator")) {
fields.path("creator").path("displayName").extractValue()
} else {
null
}
return EstimateIssue(
creator = author,
key = issue.path("key").extractValueNotNull(),
issueType = fields.path("issuetype").extractValue(),
startDate = startDate,
leadTime = leadTime,
system = fields.path(board.systemCF).extractValue(),
epic = fields.path(board.epicCF).extractValue(),
estimate = fields.path(board.estimateCF).extractValue(),
project = fields.path(board.projectCF).extractValue(),
summary = fields.path("summary").extractValueNotNull(),
changelog = changelog,
priority = priority,
impedimentTime = impedimentCalculatorResult.timeInImpediment,
impedimentHistory = impedimentCalculatorResult.impedimentHistory
)
}
}
| 0
| null |
0
| 1
|
168de10e5e53f31734937816811ac9dae6940202
| 4,968
|
jirareport
|
MIT License
|
korge/src/commonMain/kotlin/com/soywiz/korge/ui/UIScrollBar.kt
|
RezMike
| 245,256,664
| true
|
{"Kotlin": 1902450, "Java": 182026, "Shell": 1955, "Batchfile": 1618}
|
package com.soywiz.korge.ui
import com.soywiz.kmem.*
import com.soywiz.korge.input.*
import com.soywiz.korge.ui.UIScrollBar.*
import com.soywiz.korge.view.*
import com.soywiz.korio.async.*
import com.soywiz.korma.geom.*
import kotlin.math.*
inline fun Container.uiScrollBar(
width: Number,
height: Number,
current: Number = 0.0,
pageSize: Number = 1.0,
totalSize: Number = 10.0,
buttonSize: Number = 32.0,
stepSize: Double = pageSize.toDouble() / 10.0,
direction: Direction = if (width.toDouble() > height.toDouble()) Direction.Horizontal else Direction.Vertical,
skin: ScrollBarSkin = if (direction == Direction.Horizontal) defaultHorScrollBarSkin else defaultVerScrollBarSkin,
block: @ViewsDslMarker UIScrollBar.() -> Unit = {}
): UIScrollBar = UIScrollBar(
width.toDouble(),
height.toDouble(),
current.toDouble(),
pageSize.toDouble(),
totalSize.toDouble(),
buttonSize.toDouble(),
stepSize,
direction,
skin
).addTo(this).apply(block)
open class UIScrollBar(
width: Double,
height: Double,
current: Double,
pageSize: Double,
totalSize: Double,
buttonSize: Double = 32.0,
var stepSize: Double = pageSize / 10.0,
direction: Direction = if (width > height) Direction.Horizontal else Direction.Vertical,
skin: ScrollBarSkin = if (direction == Direction.Horizontal) DefaultHorScrollBarSkin else DefaultVerScrollBarSkin
) : UIView() {
enum class Direction { Vertical, Horizontal }
override var width by uiObservable(width) { reshape() }
override var height by uiObservable(height) { reshape() }
var buttonSize by uiObservable(buttonSize) { reshape() }
var direction by uiObservable(direction) { reshape() }
var current by uiObservable(current) { updatePosition() }
var pageSize by uiObservable(pageSize) { updatePosition() }
var totalSize by uiObservable(totalSize) { updatePosition() }
var buttonVisible by uiObservable(true) {
upButton.visible = it
downButton.visible = it
reshape()
}
val isHorizontal get() = direction == Direction.Horizontal
val isVertical get() = direction == Direction.Vertical
val buttonWidth get() = if (!buttonVisible) 0.0 else if (isHorizontal) buttonSize else width
val buttonHeight get() = if (!buttonVisible) 0.0 else if (isHorizontal) height else buttonSize
val trackWidth get() = if (isHorizontal) width - buttonWidth * 2 else width
val trackHeight get() = if (isHorizontal) height else height - buttonHeight * 2
val onChange = Signal<UIScrollBar>()
override var ratio: Double
get() = (current / (totalSize - pageSize)).clamp01()
set(value) {
current = value.clamp01() * (totalSize - pageSize)
}
protected val background = solidRect(100, 100, skin.backColor)
protected val upButton = iconButton(16, 16, skin.upSkin, skin.upIcon)
protected val downButton = iconButton(16, 16, skin.downSkin, skin.downIcon)
protected val thumb = uiButton(16, 16, skin.thumbSkin)
protected val views get() = stage?.views
init {
reshape()
upButton.onDown {
changeCurrent(-stepSize)
reshape()
}
downButton.onDown {
changeCurrent(+stepSize)
reshape()
}
background.onClick {
val pos = if (isHorizontal) thumb.localMouseX(views!!) else thumb.localMouseY(views!!)
changeCurrent(pos.sign * 0.8 * this.pageSize)
}
val tempP = Point()
var initRatio = 0.0
var startRatio = 0.0
thumb.onMouseDrag {
val lmouse = background.localMouseXY(views, tempP)
val curPosition = if (isHorizontal) lmouse.x else lmouse.y
val size = if (isHorizontal) background.width - thumb.width else background.height - thumb.height
val curRatio = curPosition / size
if (it.start) {
initRatio = ratio
startRatio = curRatio
}
ratio = initRatio + (curRatio - startRatio)
reshape()
}
}
protected fun changeCurrent(value: Double) {
current = (current + value).clamp(0.0, totalSize - pageSize)
}
protected fun reshape() {
if (isHorizontal) {
background.position(buttonWidth, 0).size(trackWidth, trackHeight)
upButton.position(0, 0).size(buttonWidth, buttonHeight)
downButton.position(width - buttonWidth, 0).size(buttonWidth, buttonHeight)
} else {
background.position(0, buttonHeight).size(trackWidth, trackHeight)
upButton.position(0, 0).size(buttonWidth, buttonHeight)
downButton.position(0, height - buttonHeight).size(buttonWidth, buttonHeight)
}
updatePosition()
}
protected fun updatePosition() {
if (isHorizontal) {
val thumbWidth = (trackWidth * (pageSize / totalSize)).clamp(4.0, trackWidth)
thumb.position(buttonWidth + (trackWidth - thumbWidth) * ratio, 0).size(thumbWidth, trackHeight)
} else {
val thumbHeight = (trackHeight * (pageSize / totalSize)).clamp(4.0, trackHeight)
thumb.position(0, buttonHeight + (trackHeight - thumbHeight) * ratio).size(trackWidth, thumbHeight)
}
onChange(this)
}
}
| 0
|
Kotlin
|
0
| 0
|
7516f754ecdb4ea8dce3c7b1a14ee2b07e28f984
| 5,377
|
korge
|
Apache License 2.0
|
compiler/fir/analysis-tests/testData/resolve/references/leakedImplicitType.kt
|
JetBrains
| 3,432,266
| false
| null |
// ISSUE: KT-46072
// Case 1
class Foo {
fun bar() {}
fun f() = <!UNRESOLVED_REFERENCE!>Unresolved<!>()::bar // Type of Unresolved()::bar is implicit
}
// Case 2
interface IA
interface IB : IA
fun IA.extFun(x: IB) {}
fun IB.extFun(x: IA) {}
fun testWithExpectedType() {
val extFun_AA_B: IA.(IA) -> Unit = IB::<!UNRESOLVED_REFERENCE!>extFun<!> // extFun is unresolved, type of IB::extFun is implicit
}
| 181
| null |
5748
| 49,172
|
33eb9cef3d146062c103f9853d772f0a1da0450e
| 417
|
kotlin
|
Apache License 2.0
|
src/main/kotlin/day4/solver.kt
|
derekaspaulding
| 317,756,568
| false
| null |
package day4
import java.io.File
fun getPassports(batch: String, shouldValidate: Boolean = false): List<Passport> = batch
.split("\n\n")
.map { Passport(it, shouldValidate) }
fun solveFirstProblem(batch: String): Int = getPassports(batch).count { it.isValid() }
fun solveSecondProblem(batch: String): Int = getPassports(batch, true).count { it.isValid() }
fun main() {
val batchInput = File("src/main/resources/day4/input.txt").readText(Charsets.UTF_8)
println("Passports With All Fields: ${solveFirstProblem(batchInput)}")
println("Passports With All Valid Fields: ${solveSecondProblem(batchInput)}")
}
| 0
|
Kotlin
|
0
| 0
|
0e26fdbb3415fac413ea833bc7579c09561b49e5
| 630
|
advent-of-code-2020
|
MIT License
|
wgpu4k/src/nativeMain/kotlin/io.ygdrasil.wgpu/RenderPassEncoder.native.kt
|
wgpu4k
| 773,068,055
| false
|
{"Kotlin": 1190676, "HTML": 1638, "Dockerfile": 1039, "Shell": 308}
|
@file:OptIn(ExperimentalForeignApi::class)
package io.ygdrasil.wgpu
import io.ygdrasil.wgpu.internal.toPointerArray
import kotlinx.cinterop.ExperimentalForeignApi
import kotlinx.cinterop.memScoped
import webgpu.*
actual class RenderPassEncoder(internal val handler: WGPURenderPassEncoder) {
actual fun end() {
wgpuRenderPassEncoderEnd(handler)
close()
}
actual fun setPipeline(renderPipeline: RenderPipeline) {
wgpuRenderPassEncoderSetPipeline(handler, renderPipeline.handler)
}
actual fun draw(
vertexCount: GPUSize32,
instanceCount: GPUSize32,
firstVertex: GPUSize32,
firstInstance: GPUSize32
) {
wgpuRenderPassEncoderDraw(
handler,
vertexCount.toUInt(),
instanceCount.toUInt(),
firstVertex.toUInt(),
firstInstance.toUInt()
)
}
actual fun setBindGroup(index: Int, bindGroup: BindGroup) {
wgpuRenderPassEncoderSetBindGroup(
handler,
index.toUInt(),
bindGroup.handler,
0uL,
null
)
}
actual fun setVertexBuffer(slot: Int, buffer: Buffer) {
wgpuRenderPassEncoderSetVertexBuffer(
handler,
slot.toUInt(),
buffer.handler,
0uL,
buffer.size.toULong()
)
}
actual fun setIndexBuffer(buffer: Buffer, indexFormat: IndexFormat, offset: GPUSize64, size: GPUSize64) {
wgpuRenderPassEncoderSetIndexBuffer(
handler,
buffer.handler,
indexFormat.value.toUInt(),
offset.toULong(),
size.toULong()
)
}
actual fun executeBundles(bundles: List<RenderBundle>) = memScoped {
wgpuRenderPassEncoderExecuteBundles(
handler,
bundles.size.toULong(),
bundles.map { it.handler }.toPointerArray(this)
)
}
private fun close() {
wgpuRenderPassEncoderRelease(handler)
}
}
| 7
|
Kotlin
|
6
| 41
|
822c304afaa72411ae42e86f20c7b5c62b5f9815
| 2,035
|
wgpu4k
|
MIT License
|
app/src/main/java/com/thecode/infotify/presentation/splash/SplashViewModel.kt
|
Ethiel97
| 373,656,092
| true
|
{"Kotlin": 103599}
|
package com.thecode.infotify.presentation.splash
import androidx.lifecycle.ViewModel
import com.thecode.infotify.core.usecases.IsOnboardingCompleted
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
@HiltViewModel
class SplashViewModel @Inject constructor(
private val isOnboardingCompleted: IsOnboardingCompleted
) : ViewModel() {
fun isOnboardingCompleted(): Boolean {
return isOnboardingCompleted.invoke()
}
}
| 0
| null |
0
| 0
|
bd6cfdd0f64a919cfb302e6b536c09b093e0dee6
| 464
|
Infotify
|
Apache License 2.0
|
component-toolkit/src/commonMain/kotlin/com/macaosoftware/component/core/deeplink/DeepLinkManager.kt
|
pablichjenkov
| 135,388,611
| false
| null |
package com.macaosoftware.component.core.deeplink
import com.macaosoftware.component.core.Component
import com.macaosoftware.component.core.ComponentLifecycleState
interface DeepLinkManager {
fun navigateToDeepLink(
component: Component,
deepLinkMsg: DeepLinkMsg
)
}
class DefaultDeepLinkManager: DeepLinkManager {
override fun navigateToDeepLink(
component: Component,
deepLinkMsg: DeepLinkMsg
) {
println("${component.instanceId()}::navigateToDeepLink(), path = ${deepLinkMsg.path.joinToString("/")}")
if (component.lifecycleState != ComponentLifecycleState.Active) {
println("${component.instanceId()}::navigateToDeepLink(), Waiting to be Started")
component.deepLinkNavigationAwaitsStartedState = true
component.awaitingDeepLinkMsg = deepLinkMsg
return
}
val deepLinkPathSegment = deepLinkMsg.path[0]
val match = component.deepLinkPathSegment == deepLinkPathSegment
if (match) {
if (deepLinkMsg.path.size == 1) {
deepLinkMsg.resultListener.invoke(DeepLinkResult.Success(component))
return
}
val nextDeepLinkPathSegment = deepLinkMsg.path[1]
val nextComponent = component.getChildForNextUriFragment(nextDeepLinkPathSegment)
if (nextComponent == null) {
deepLinkMsg.resultListener.invoke(
DeepLinkResult.Error(
"Component: ${component.instanceId()} does not have any child that handle path segment = $nextDeepLinkPathSegment"
)
)
return
}
nextComponent.startedFromDeepLink = true
if (deepLinkMsg.path.size > 2) {
val nextDeepLinkMsg = deepLinkMsg.copy(
path = deepLinkMsg.path.subList(1, deepLinkMsg.path.size)
)
component.onDeepLinkNavigateTo(nextComponent)
navigateToDeepLink(nextComponent, nextDeepLinkMsg)
} else {
component.onDeepLinkNavigateTo(nextComponent)
deepLinkMsg.resultListener.invoke(DeepLinkResult.Success(nextComponent))
}
} else {
deepLinkMsg.resultListener.invoke(
DeepLinkResult.Error(
"Component: ${component.instanceId()} does not handle DeepLinkPathSegment = $deepLinkPathSegment."
)
)
}
}
}
| 0
| null |
5
| 95
|
198b61ee7bb8b777868b64066f9004e070e63856
| 2,548
|
macao-sdk
|
The Unlicense
|
src/main/kotlin/org/cryptobiotic/mixnet/cli/RunMixnetTally.kt
|
JohnLCaron
| 762,789,706
| false
|
{"Kotlin": 169695, "Shell": 12082}
|
package org.cryptobiotic.mixnet.cli
import com.github.michaelbull.result.Err
import com.github.michaelbull.result.unwrap
import io.github.oshai.kotlinlogging.KotlinLogging
import kotlinx.cli.ArgParser
import kotlinx.cli.ArgType
import kotlinx.cli.required
import org.cryptobiotic.eg.core.*
import org.cryptobiotic.eg.election.*
import org.cryptobiotic.eg.publish.makeConsumer
import org.cryptobiotic.eg.publish.makePublisher
import org.cryptobiotic.eg.tally.AccumulateTally
import org.cryptobiotic.maths.VectorCiphertext
import org.cryptobiotic.mixnet.cli.RunMixnet.Companion.shuffledFilename
import org.cryptobiotic.util.ErrorMessages
import org.cryptobiotic.mixnet.writer.BallotReader
import org.cryptobiotic.mixnet.writer.MixnetConfig
import org.cryptobiotic.mixnet.writer.readMixnetConfigFromFile
// DO NOT USE
class RunMixnetTally {
companion object {
val logger = KotlinLogging.logger("RunMixnetTally")
@JvmStatic
fun main(args: Array<String>) {
val parser = ArgParser("RunMixnetTally")
val egkMixnetDir by parser.option(
ArgType.String,
shortName = "publicDir",
description = "egk mixnet public directory"
).required()
val mixDir by parser.option(
ArgType.String,
shortName = "mix",
description = "Mix directory"
).required()
parser.parse(args)
val info = buildString {
appendLine("starting MixnetTally")
appendLine(" egkMixnetDir= $egkMixnetDir")
append(" mixDir= $mixDir")
}
logger.info { info }
val configFilename = "$mixDir/${RunMixnet.configFilename}"
val resultConfig = readMixnetConfigFromFile(configFilename)
if (resultConfig is Err) {
RunMixnet.logger.error { "Error reading MixnetConfig from $configFilename err = $resultConfig" }
return
}
val config = resultConfig.unwrap()
val valid = runAccumulateBallots(egkMixnetDir, mixDir, config)
logger.info { "valid = $valid" }
}
fun runAccumulateBallots(
egkMixnetDir: String,
mixDir: String,
config: MixnetConfig
) {
val consumerIn = makeConsumer(egkMixnetDir)
val initResult = consumerIn.readElectionInitialized()
if (initResult is Err) {
logger.error { "readElectionInitialized error ${initResult.error}" }
return
}
val electionInit = initResult.unwrap()
val manifest = consumerIn.makeManifest(electionInit.config.manifestBytes)
val group = consumerIn.group
val reader = BallotReader(group, config.width)
val shuffled = reader.readFromFile("$mixDir/$shuffledFilename")
val accumulator = AccumulateTally(
group,
manifest,
config.mix_name,
electionInit.extendedBaseHash,
electionInit.jointPublicKey,
countNumberOfBallots = true,
)
val errs = ErrorMessages("RunAccumulateTally on Shuffled Ballots")
var nrows = 0
shuffled.forEach {
val ballotId = it.elems[0].hashCode().toString()
val eballot: EncryptedBallotIF = rehydrate(manifest, ballotId, electionInit.extendedBaseHash, 0, it)
if (!accumulator.addCastBallot(eballot, errs)) {
println(" got error $errs")
}
nrows++
}
val tally: EncryptedTally = accumulator.build()
val publisher = makePublisher(mixDir, false)
publisher.writeTallyResult(
TallyResult(
electionInit, tally, listOf("$mixDir/$shuffledFilename"),
mapOf(
Pair("CreatedBy", "RunMixnetTally"),
Pair("CreatedOn", getSystemDate()),
Pair("CreatedFrom", "$mixDir/$shuffledFilename")
)
), false
)
logger.info { "nrows=$nrows, width= ${config.width} per row" }
}
}
}
| 0
|
Kotlin
|
0
| 0
|
7f96f8ee4acb2e5a11c8a83acba0b082627cead0
| 4,353
|
egk-ec-mixnet
|
MIT License
|
app/src/main/java/com/prmto/mova_movieapp/feature_person_detail/presentation/adapter/PersonCastMovieAdapter.kt
|
tolgaprm
| 541,709,201
| false
|
{"Kotlin": 522687}
|
package com.prmto.mova_movieapp.feature_person_detail.presentation.adapter
import com.prmto.mova_movieapp.feature_person_detail.domain.model.CastForPerson
class PersonCastMovieAdapter() : PersonMovieBaseAdapter<CastForPerson>() {
override fun onBindViewHolder(holder: PersonMovieViewHolder, position: Int) {
val castForPerson = getItem(position)
holder.bindCast(cast = castForPerson)
holder.itemView.setOnClickListener {
super.clickListener(castForPerson)
}
}
}
| 1
|
Kotlin
|
3
| 56
|
1936fb736958a2e47e691ae7d694ba56e77e44f5
| 517
|
Mova-MovieApp
|
Apache License 2.0
|
app/src/main/java/com/example/stylish/data/remote/dto/detail/Catwalk.kt
|
world2222
| 713,460,580
| false
|
{"Kotlin": 161972}
|
package com.example.stylish.data.remote.dto.detail
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class Catwalk(
@SerialName("url")
val url: String? = null,
@SerialName("colourWayId")
val colourWayId: Int? = null,
@SerialName("colourCode")
val colourCode: String? = null
)
| 0
|
Kotlin
|
0
| 0
|
a73253f5852ec397a5c5b50f446cf4be60bdab4a
| 353
|
Stylish
|
Apache License 2.0
|
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/ecs/CfnTaskSetAwsVpcConfigurationPropertyDsl.kt
|
cloudshiftinc
| 667,063,030
| false
|
{"Kotlin": 70198112}
|
@file:Suppress(
"RedundantVisibilityModifier",
"RedundantUnitReturnType",
"RemoveRedundantQualifierName",
"unused",
"UnusedImport",
"ClassName",
"REDUNDANT_PROJECTION",
"DEPRECATION"
)
package cloudshift.awscdk.dsl.services.ecs
import cloudshift.awscdk.common.CdkDslMarker
import kotlin.String
import kotlin.collections.Collection
import kotlin.collections.MutableList
import software.amazon.awscdk.services.ecs.CfnService
/**
* An object representing the networking details for a task or service.
*
* 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.ecs.*;
* AwsVpcConfigurationProperty awsVpcConfigurationProperty = AwsVpcConfigurationProperty.builder()
* .assignPublicIp("assignPublicIp")
* .securityGroups(List.of("securityGroups"))
* .subnets(List.of("subnets"))
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-service-awsvpcconfiguration.html)
*/
@CdkDslMarker
public class CfnServiceAwsVpcConfigurationPropertyDsl {
private val cdkBuilder: CfnService.AwsVpcConfigurationProperty.Builder =
CfnService.AwsVpcConfigurationProperty.builder()
private val _securityGroups: MutableList<String> = mutableListOf()
private val _subnets: MutableList<String> = mutableListOf()
/**
* @param assignPublicIp Whether the task's elastic network interface receives a public IP
* address. The default value is `DISABLED` .
*/
public fun assignPublicIp(assignPublicIp: String) {
cdkBuilder.assignPublicIp(assignPublicIp)
}
/**
* @param securityGroups The IDs of the security groups associated with the task or service. If
* you don't specify a security group, the default security group for the VPC is used. There's
* a limit of 5 security groups that can be specified per `AwsVpcConfiguration` .
*
* All specified security groups must be from the same VPC.
*/
public fun securityGroups(vararg securityGroups: String) {
_securityGroups.addAll(listOf(*securityGroups))
}
/**
* @param securityGroups The IDs of the security groups associated with the task or service. If
* you don't specify a security group, the default security group for the VPC is used. There's
* a limit of 5 security groups that can be specified per `AwsVpcConfiguration` .
*
* All specified security groups must be from the same VPC.
*/
public fun securityGroups(securityGroups: Collection<String>) {
_securityGroups.addAll(securityGroups)
}
/**
* @param subnets The IDs of the subnets associated with the task or service. There's a limit of
* 16 subnets that can be specified per `AwsVpcConfiguration` .
*
* All specified subnets must be from the same VPC.
*/
public fun subnets(vararg subnets: String) {
_subnets.addAll(listOf(*subnets))
}
/**
* @param subnets The IDs of the subnets associated with the task or service. There's a limit of
* 16 subnets that can be specified per `AwsVpcConfiguration` .
*
* All specified subnets must be from the same VPC.
*/
public fun subnets(subnets: Collection<String>) {
_subnets.addAll(subnets)
}
public fun build(): CfnService.AwsVpcConfigurationProperty {
if (_securityGroups.isNotEmpty()) cdkBuilder.securityGroups(_securityGroups)
if (_subnets.isNotEmpty()) cdkBuilder.subnets(_subnets)
return cdkBuilder.build()
}
}
| 3
|
Kotlin
|
0
| 3
|
c59c6292cf08f0fc3280d61e7f8cff813a608a62
| 3,670
|
awscdk-dsl-kotlin
|
Apache License 2.0
|
klio/src/commonMain/kotlin/org/kodein/memory/io/IOException.kt
|
kosi-libs
| 181,659,560
| false
|
{"C": 2929780, "Kotlin": 313185, "JavaScript": 359}
|
package org.kodein.memory.io
public expect open class IOException(msg: String): Exception
| 0
|
C
|
0
| 7
|
bab7f6ff28ca5cf9031a3d312f56d67fe3151d3c
| 92
|
Klio
|
MIT License
|
app/src/main/java/com/example/androiddevchallenge/HomeScreen.kt
|
robertdegroot
| 355,230,750
| false
| null |
package com.example.androiddevchallenge
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.material.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.navigation.NavController
import com.example.androiddevchallenge.data.Dog
import com.example.androiddevchallenge.data.DogData
@Composable
fun HomeScreen(navController: NavController?) {
Column(modifier = Modifier.fillMaxSize()) {
TopAppBar(
title = { Text("Dog adoption list") },
)
Surface(color = MaterialTheme.colors.background) {
DogList(DogData().getAllDogs(), navController)
}
}
}
@Composable
fun DogList(dogs: List<Dog>, navController: NavController?) {
LazyColumn {
items(dogs) {
DogCard(it, navController)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
74d2a8b964b7d628521dddb73bd6d3ea718586a6
| 1,127
|
DogAdoptionJetpackCompose
|
Apache License 2.0
|
matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/ExportEncryptionTest.kt
|
matrix-org
| 287,466,066
| false
| null |
/*
* Copyright 2018 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 org.matrix.android.sdk.internal.crypto
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Assert.fail
import org.junit.FixMethodOrder
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.MethodSorters
/**
* Unit tests ExportEncryptionTest.
*/
@RunWith(AndroidJUnit4::class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
class ExportEncryptionTest {
@Test
fun checkExportError1() {
val password = "<PASSWORD>"
val input = "-----"
var failed = false
try {
MXMegolmExportEncryption.decryptMegolmKeyFile(input.toByteArray(charset("UTF-8")), password)
} catch (e: Exception) {
failed = true
}
assertTrue(failed)
}
@Test
fun checkExportError2() {
val password = "<PASSWORD>"
val input = "-----BEGIN MEGOLM SESSION DATA-----\n" + "-----"
var failed = false
try {
MXMegolmExportEncryption.decryptMegolmKeyFile(input.toByteArray(charset("UTF-8")), password)
} catch (e: Exception) {
failed = true
}
assertTrue(failed)
}
@Test
fun checkExportError3() {
val password = "<PASSWORD>"
val input = "-----BEGIN MEGOLM SESSION DATA-----\n" +
" <KEY>" +
" cissyYBxjsfsAn\n" +
" -----END MEGOLM SESSION DATA-----"
var failed = false
try {
MXMegolmExportEncryption.decryptMegolmKeyFile(input.toByteArray(charset("UTF-8")), password)
} catch (e: Exception) {
failed = true
}
assertTrue(failed)
}
@Test
fun checkExportDecrypt1() {
val password = "<PASSWORD>"
val input = "-----BEGIN MEGOLM SESSION DATA-----\nAXNhbHRzYWx0c2FsdHNhbHSIiIiIiIiIiIiIiIiIiIiIAAAACmIRUW2OjZ3L2l6j9h0lHlV3M2dx\n" + "cissyYBxjsfsAndErh065A8=\n-----END MEGOLM SESSION DATA-----"
val expectedString = "plain"
var decodedString: String? = null
try {
decodedString = MXMegolmExportEncryption.decryptMegolmKeyFile(input.toByteArray(charset("UTF-8")), password)
} catch (e: Exception) {
fail("## checkExportDecrypt1() failed : " + e.message)
}
assertEquals("## checkExportDecrypt1() : expectedString $expectedString -- decodedString $decodedString",
expectedString,
decodedString)
}
@Test
fun checkExportDecrypt2() {
val password = "<PASSWORD>"
val input = "-----BEGIN MEGOLM SESSION DATA-----\nAW1vcmVzYWx0bW9yZXNhbHT//////////wAAAAAAAAAAAAAD6KyBpe1Niv5M5NPm4ZATsJo5nghk\n" + "KYu63a0YQ5DRhUWEKk7CcMkrKnAUiZny\n-----END MEGOLM SESSION DATA-----"
val expectedString = "Hello, World"
var decodedString: String? = null
try {
decodedString = MXMegolmExportEncryption.decryptMegolmKeyFile(input.toByteArray(charset("UTF-8")), password)
} catch (e: Exception) {
fail("## checkExportDecrypt2() failed : " + e.message)
}
assertEquals("## checkExportDecrypt2() : expectedString $expectedString -- decodedString $decodedString",
expectedString,
decodedString)
}
@Test
fun checkExportDecrypt3() {
val password = "<PASSWORD>"
val input = "-----BEGIN MEGOLM SESSION DATA-----\nAXllc3NhbHR5Z29vZG5lc3P//////////wAAAAAAAAAAAAAD6OIW+Je7gwvjd4kYrb+49gKCfExw\n" + "MgJBMD4mrhLkmgAngwR1pHjbWXaoGybtiAYr0moQ93GrBQsCzPbvl82rZhaXO3iH5uHo/RCEpOqp\nPgg29363BGR+/Ripq/VCLKGNbw==\n-----END MEGOLM SESSION DATA-----"
val expectedString = "alphanumericallyalphanumericallyalphanumericallyalphanumerically"
var decodedString: String? = null
try {
decodedString = MXMegolmExportEncryption.decryptMegolmKeyFile(input.toByteArray(charset("UTF-8")), password)
} catch (e: Exception) {
fail("## checkExportDecrypt3() failed : " + e.message)
}
assertEquals("## checkExportDecrypt3() : expectedString $expectedString -- decodedString $decodedString",
expectedString,
decodedString)
}
@Test
fun checkExportEncrypt1() {
val password = "<PASSWORD>"
val expectedString = "plain"
var decodedString: String? = null
try {
decodedString = MXMegolmExportEncryption
.decryptMegolmKeyFile(MXMegolmExportEncryption.encryptMegolmKeyFile(expectedString, password, 1000), password)
} catch (e: Exception) {
fail("## checkExportEncrypt1() failed : " + e.message)
}
assertEquals("## checkExportEncrypt1() : expectedString $expectedString -- decodedString $decodedString",
expectedString,
decodedString)
}
@Test
fun checkExportEncrypt2() {
val password = "<PASSWORD>"
val expectedString = "Hello, World"
var decodedString: String? = null
try {
decodedString = MXMegolmExportEncryption
.decryptMegolmKeyFile(MXMegolmExportEncryption.encryptMegolmKeyFile(expectedString, password, 1000), password)
} catch (e: Exception) {
fail("## checkExportEncrypt2() failed : " + e.message)
}
assertEquals("## checkExportEncrypt2() : expectedString $expectedString -- decodedString $decodedString",
expectedString,
decodedString)
}
@Test
fun checkExportEncrypt3() {
val password = "<PASSWORD>"
val expectedString = "alphanumericallyalphanumericallyalphanumericallyalphanumerically"
var decodedString: String? = null
try {
decodedString = MXMegolmExportEncryption
.decryptMegolmKeyFile(MXMegolmExportEncryption.encryptMegolmKeyFile(expectedString, password, 1000), password)
} catch (e: Exception) {
fail("## checkExportEncrypt3() failed : " + e.message)
}
assertEquals("## checkExportEncrypt3() : expectedString $expectedString -- decodedString $decodedString",
expectedString,
decodedString)
}
@Test
fun checkExportEncrypt4() {
val password = "<PASSWORD>" + "<PASSWORD>"
val expectedString = "alphanumericallyalphanumericallyalphanumericallyalphanumerically"
var decodedString: String? = null
try {
decodedString = MXMegolmExportEncryption
.decryptMegolmKeyFile(MXMegolmExportEncryption.encryptMegolmKeyFile(expectedString, password, 1000), password)
} catch (e: Exception) {
fail("## checkExportEncrypt4() failed : " + e.message)
}
assertEquals("## checkExportEncrypt4() : expectedString $expectedString -- decodedString $decodedString",
expectedString,
decodedString)
}
}
| 75
| null |
6
| 97
|
55cc7362de34a840c67b4bbb3a14267bc8fd3b9c
| 7,608
|
matrix-android-sdk2
|
Apache License 2.0
|
app/src/main/java/com/tikou/androidstudylib/dagger2/DaggerActivity.kt
|
Tiannuo
| 502,867,476
| false
| null |
package com.tikou.androidstudylib.dagger2
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import com.orhanobut.logger.Logger
import com.tikou.androidstudylib.MyApp
import com.tikou.androidstudylib.R
import com.tikou.androidstudylib.di.Presenter
import javax.inject.Inject
class DaggerActivity : AppCompatActivity() {
@Inject
lateinit var httpDataObject1: HttpDataObject
@Inject
lateinit var httpDataObject2: HttpDataObject
@Inject
lateinit var presenter1: Presenter
@Inject
lateinit var presenter2: Presenter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_dagger)
// dagger注入方式一
//DaggerDaggerComponent.create().injectActivity(this)
//全局单例注入
(application as MyApp).getDaggerSingleComponent().injectActivity(this)
Logger.i("DaggerActivityCode" + httpDataObject1.hashCode())
Logger.i("DaggerActivityCode" + httpDataObject2.hashCode())
findViewById<View>(android.R.id.content).postDelayed(Runnable {
val intent = Intent(this@DaggerActivity, DaggerActivity2::class.java)
startActivity(intent)
}, 2000)
}
override fun onPause() {
super.onPause()
httpDataObject1.str = "onPause"
Logger.i("DaggerActivityCode" + httpDataObject2.str)
Logger.i("DaggerActivityCode" + httpDataObject2.str)
Logger.i("DaggerActivityCode" + presenter1.hashCode())
Logger.i("DaggerActivityCode" + presenter2.hashCode())
Logger.i("DaggerActivityCode onPause")
}
}
| 0
|
Kotlin
|
0
| 0
|
23e5a46bb5cd2be618ecf1b5fff52b81ebf38888
| 1,701
|
AndroidArchitect
|
Apache License 2.0
|
app/src/main/java/org/szymonbultrowicz/olympusphototransfer/app/MyAppGlideModule.kt
|
szymonbultrowicz
| 219,493,861
| false
| null |
package com.android.myapplication.movies.util
import android.content.Context
import com.bumptech.glide.GlideBuilder
import com.bumptech.glide.annotation.GlideModule
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.module.AppGlideModule
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.signature.ObjectKey
@GlideModule
class MyAppGlideModule : AppGlideModule(){
override fun applyOptions(context: Context, builder: GlideBuilder) {
super.applyOptions(context, builder)
builder.apply { RequestOptions().diskCacheStrategy(DiskCacheStrategy.ALL).signature(
ObjectKey(System.currentTimeMillis().toShort())
) }
}
}
| 0
| null |
0
| 2
|
9c3591336176ef440b3ca338a9b5f545e2760210
| 713
|
android-olympus-photo-transfer
|
Apache License 2.0
|
plugins/git4idea/tests/git4idea/update/GitForcePushedBranchUpdateBaseTest.kt
|
JetBrains
| 2,489,216
| false
| null |
// Copyright 2000-2024 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package git4idea.update
import com.intellij.testFramework.runInEdtAndWait
import com.intellij.testFramework.utils.coroutines.waitCoroutinesBlocking
import com.intellij.vcs.log.VcsCommitMetadata
import git4idea.actions.branch.GitForcePushedBranchUpdateExecutor
import git4idea.history.GitLogUtil
import git4idea.repo.GitRepository
import git4idea.test.GitPlatformTest
import git4idea.test.cd
import git4idea.test.file
import junit.framework.TestCase
abstract class GitForcePushedBranchUpdateBaseTest : GitPlatformTest() {
internal fun GitForcePushedBranchUpdateExecutor.waitForUpdate() {
runInEdtAndWait { waitCoroutinesBlocking(coroutineScope) }
}
protected fun GitRepository.commitsFrom(vararg logCommandParams: String): List<VcsCommitMetadata> {
return GitLogUtil.collectMetadata(project, root, *logCommandParams).commits
}
protected fun GitRepository.cd(): GitRepository {
cd(this)
return this
}
protected fun GitRepository.assertExists(file: String) = cd().file(file).assertExists()
protected fun GitRepository.assertNotExists(file: String) = cd().file(file).assertNotExists()
protected fun assertNotificationByMessage(notificationContent: String) =
vcsNotifier.notifications.find { it.content == notificationContent }
?: TestCase.fail("Notification $notificationContent not found")
}
| 284
| null |
5162
| 16,707
|
def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0
| 1,459
|
intellij-community
|
Apache License 2.0
|
app/src/test/java/com/babylon/wallet/android/presentation/settings/editgateway/GatewaysViewModelTest.kt
|
radixdlt
| 513,047,280
| false
| null |
package com.babylon.wallet.android.presentation.settings.editgateway
import app.cash.turbine.test
import com.babylon.wallet.android.domain.SampleDataProvider
import com.babylon.wallet.android.domain.model.NetworkInfo
import com.babylon.wallet.android.domain.usecases.GetNetworkInfoUseCase
import com.babylon.wallet.android.presentation.TestDispatcherRule
import com.babylon.wallet.android.presentation.settings.preferences.gateways.GatewayAddFailure
import com.babylon.wallet.android.presentation.settings.preferences.gateways.SettingsEditGatewayEvent
import com.babylon.wallet.android.presentation.settings.preferences.gateways.GatewaysViewModel
import com.babylon.wallet.android.utils.isValidUrl
import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.every
import io.mockk.mockk
import io.mockk.mockkStatic
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.test.advanceUntilIdle
import kotlinx.coroutines.test.runTest
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import rdx.works.profile.data.model.apppreferences.Radix
import rdx.works.profile.domain.GetProfileUseCase
import rdx.works.profile.domain.gateway.AddGatewayUseCase
import rdx.works.profile.domain.gateway.ChangeGatewayIfNetworkExistUseCase
import rdx.works.profile.domain.gateway.DeleteGatewayUseCase
@OptIn(ExperimentalCoroutinesApi::class)
class GatewaysViewModelTest {
@get:Rule
val coroutineRule = TestDispatcherRule()
private lateinit var vm: GatewaysViewModel
private val getProfileUseCase = mockk<GetProfileUseCase>()
private val changeGatewayIfNetworkExistUseCase = mockk<ChangeGatewayIfNetworkExistUseCase>()
private val addGatewayUseCase = mockk<AddGatewayUseCase>()
private val deleteGatewayUseCase = mockk<DeleteGatewayUseCase>()
private val getNetworkInfoUseCase = mockk<GetNetworkInfoUseCase>()
private val profile = SampleDataProvider().sampleProfile()
@Before
fun setUp() = runTest {
vm = GatewaysViewModel(
getProfileUseCase = getProfileUseCase,
changeGatewayIfNetworkExistUseCase = changeGatewayIfNetworkExistUseCase,
addGatewayUseCase = addGatewayUseCase,
deleteGatewayUseCase = deleteGatewayUseCase,
getNetworkInfoUseCase = getNetworkInfoUseCase
)
every { getProfileUseCase() } returns flowOf(profile)
coEvery { changeGatewayIfNetworkExistUseCase(any()) } returns true
coEvery { addGatewayUseCase(any()) } returns Unit
coEvery { getNetworkInfoUseCase(any()) } returns Result.success(
NetworkInfo(Radix.Network.nebunet, 0L)
)
mockkStatic("com.babylon.wallet.android.utils.StringExtensionsKt")
every { any<String>().isValidUrl() } returns true
}
@Test
fun `init loads profile and url`() = runTest {
assert(vm.state.value.currentGateway != null)
}
@Test
fun `url change updates it's value and valid state`() = runTest {
val sampleUrl = "https://test.com"
vm.onNewUrlChanged(sampleUrl)
assert(vm.state.value.newUrl == sampleUrl)
assert(vm.state.value.newUrlValid)
}
@Test
fun `adding network triggers network save`() = runTest {
val sampleUrl = Radix.Gateway.nebunet.url
vm.onNewUrlChanged(sampleUrl)
vm.onAddGateway()
advanceUntilIdle()
coVerify(exactly = 1) { addGatewayUseCase(any()) }
vm.oneOffEvent.test {
val item = expectMostRecentItem()
assert(item is SettingsEditGatewayEvent.GatewayAdded)
}
}
@Test
fun `network switch calls for create account`() = runTest {
val sampleUrl = Radix.Gateway.kisharnet.url
val gateway = Radix.Gateway(sampleUrl, Radix.Network.kisharnet)
vm.onNewUrlChanged(sampleUrl)
coEvery { changeGatewayIfNetworkExistUseCase(gateway) } returns false
vm.onGatewayClick(Radix.Gateway(sampleUrl, Radix.Network.kisharnet))
advanceUntilIdle()
vm.oneOffEvent.test {
val item = expectMostRecentItem()
assert(item is SettingsEditGatewayEvent.CreateProfileOnNetwork)
}
}
@Test
fun `network switch calls changes gateway when there are accounts present`() = runTest {
val sampleUrl = Radix.Gateway.kisharnet.url
val gateway = Radix.Gateway(sampleUrl, Radix.Network.kisharnet)
vm.onNewUrlChanged(sampleUrl)
coEvery { changeGatewayIfNetworkExistUseCase(gateway) } returns true
vm.onGatewayClick(Radix.Gateway(sampleUrl, Radix.Network.kisharnet))
advanceUntilIdle()
coVerify(exactly = 1) { changeGatewayIfNetworkExistUseCase(gateway) }
}
@Test
fun `trying to switch to current network is no op`() = runTest {
val sampleUrl = Radix.Gateway.default.url
val gateway = Radix.Gateway.default
vm.onNewUrlChanged(sampleUrl)
vm.onGatewayClick(gateway)
advanceUntilIdle()
coVerify(exactly = 0) { changeGatewayIfNetworkExistUseCase(gateway) }
assert(vm.state.value.gatewayAddFailure == GatewayAddFailure.AlreadyExist)
}
@Test
fun `network info error triggers ui error`() = runTest {
coEvery { getNetworkInfoUseCase(any()) } returns Result.failure(
Throwable()
)
val sampleUrl = Radix.Gateway.nebunet.url
vm.onNewUrlChanged(sampleUrl)
vm.onAddGateway()
advanceUntilIdle()
assert(vm.state.value.gatewayAddFailure == GatewayAddFailure.ErrorWhileAdding)
}
}
| 8
| null |
11
| 6
|
aad2bc0b39f8871eca0b3e1f2b822c010cd016a6
| 5,614
|
babylon-wallet-android
|
Apache License 2.0
|
app/src/main/java/app/epf/ratp_eb_pf/PreferencesActivity.kt
|
pierrefrncs
| 255,360,624
| false
| null |
package app.epf.ratp_eb_pf
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDelegate
import androidx.preference.PreferenceManager
const val KEY_THEME = "prefs.theme"
const val THEME_LIGHT = 0
const val THEME_DARK = 1
const val THEME_SYSTEM = 2
const val THEME_BATTERY = 3
// Activity contenant le fragment des préférences
class PreferencesActivity : AppCompatActivity(),
SharedPreferences.OnSharedPreferenceChangeListener {
private lateinit var prefs: SharedPreferences
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_preferences)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportFragmentManager
.beginTransaction()
.replace(R.id.container_layout, PreferencesFragment())
.commit()
PreferenceManager.getDefaultSharedPreferences(this)
.registerOnSharedPreferenceChangeListener(this)
prefs = PreferenceManager.getDefaultSharedPreferences(this)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
android.R.id.home -> {
finish()
true
}
else -> super.onOptionsItemSelected(item)
}
}
// En cas de changement d'un paramètre
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences?, key: String?) {
// Set le thème de l'application
when (sharedPreferences?.getString("theme_display", "themeSystem")) {
"themeLight" -> setTheme(AppCompatDelegate.MODE_NIGHT_NO, THEME_LIGHT)
"themeDark" -> setTheme(AppCompatDelegate.MODE_NIGHT_YES, THEME_DARK)
"themeSystem" -> setTheme(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM, THEME_SYSTEM)
}
restartPage()
}
private fun setTheme(themeMode: Int, prefsMode: Int) {
AppCompatDelegate.setDefaultNightMode(themeMode)
saveTheme(prefsMode)
}
private fun saveTheme(theme: Int) = prefs.edit().putInt(KEY_THEME, theme).apply()
// Reload la page en cas de changement de thème
private fun restartPage() {
val k = Intent(this, PreferencesActivity::class.java)
k.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
startActivity(k)
overridePendingTransition(0, 0)
finish()
overridePendingTransition(0, 0)
}
}
| 0
|
Kotlin
|
0
| 0
|
8e17c15d5cba1194247e0adc7a35b694fe14435c
| 2,609
|
Metro-Finder
|
MIT License
|
master_detail/app/src/main/java/com/tjclawson/master_detail/MainActivity.kt
|
tjclawson
| 257,737,751
| false
| null |
package com.tjclawson.master_detail
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.lifecycle.ViewModelProvider
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
private lateinit var viewModel: SharedViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
viewModel = ViewModelProvider(this).get(SharedViewModel::class.java)
if (frame_item_detail != null) viewModel.twoPane = true
initUI()
}
private fun initUI() {
if (viewModel.twoPane) {
supportFragmentManager
.beginTransaction()
.replace(R.id.frame_item_list, ListFragment())
.replace(R.id.frame_item_detail, DetailFragment())
.commit()
} else {
supportFragmentManager
.beginTransaction()
.replace(R.id.list_container, ListFragment())
.commit()
}
}
}
| 0
|
Kotlin
|
0
| 0
|
65975854b6ce1ad279293aeab531949d687ccdde
| 1,128
|
rv_java
|
MIT License
|
src/main/kotlin/es/jtp/graphql/server/dsl/builders/UnionTypeBuilder.kt
|
juliotpaez
| 215,011,592
| false
| null |
package es.jtp.graphql.server.dsl.builders
import es.jtp.graphql.server.dsl.exceptions.*
import es.jtp.graphql.server.dsl.interfaces.*
import graphql.schema.*
import kotlin.reflect.*
import kotlin.reflect.full.*
/**
* Builder for a GraphQL union type.
*/
@Suppress("UNCHECKED_CAST")
class UnionTypeBuilder<T : Any>(val type: KClass<T>) : IGraphQLBuilder, IGraphQLWithDescription {
override var description: String? = null
internal val types = mutableSetOf<KClass<*>>()
// METHODS ----------------------------------------------------------------
// TODO include directives
/**
* Sets a Union of two types.
*/
inline fun <reified T1 : T, reified T2 : T> ofTwo() {
of(T1::class, T2::class)
}
/**
* Sets a Union of three types.
*/
inline fun <reified T1 : T, reified T2 : T, reified T3 : T> ofThree() {
of(T1::class, T2::class, T3::class)
}
/**
* Sets a Union of four types.
*/
inline fun <reified T1 : T, reified T2 : T, reified T3 : T, reified T4 : T> ofFour() {
of(T1::class, T2::class, T3::class, T4::class)
}
/**
* Sets the types of the union.
*/
fun of(vararg unionTypes: KClass<*>) {
types.clear()
unionTypes.forEach {
if (!it.isSubclassOf(type)) {
throw GraphQLBuilderException("The type $it is not a subclass of $type")
}
types.add(it)
}
}
/**
* Builds a [GraphQLUnionType].
*/
override fun build(context: GraphQLBuilderContext): GraphQLUnionType {
val definition = GraphQLUnionType.newUnionType()
// Name
definition.name(type.simpleName)
// Description
if (this.description != null) {
definition.description(description)
}
// Member types
for (type in types) {
definition.possibleType(GraphQLTypeReference.typeRef(type.simpleName))
}
// Resolver
val result = definition.build()
context.codeRegistry.typeResolver(result) { env ->
val obj: Any = env.getObject()
val clazz = obj::class
if (clazz in types) {
return@typeResolver env.schema.getObjectType(clazz.simpleName!!)
}
null
}
return result
}
override fun toString(): String {
return "Union(name=${type.simpleName}, description=$description, types=[${types.joinToString(
" | ") { it.simpleName!! }}])"
}
}
| 0
|
Kotlin
|
0
| 0
|
119f266d08e3ef149b2a9c456e2550dcdfc3b6db
| 2,554
|
graphql-kotlin
|
MIT License
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.