repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 55
values | size
stringlengths 2
6
| content
stringlengths 55
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
979
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
jwren/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ImplementAbstractMemberIntention.kt | 3 | 12928 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.codeInsight.CodeInsightBundle
import com.intellij.codeInsight.FileModificationService
import com.intellij.codeInsight.generation.OverrideImplementUtil
import com.intellij.codeInsight.intention.impl.BaseIntentionAction
import com.intellij.ide.util.PsiClassListCellRenderer
import com.intellij.ide.util.PsiClassRenderingInfo
import com.intellij.ide.util.PsiElementListCellRenderer
import com.intellij.java.JavaBundle
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.fileEditor.OpenFileDescriptor
import com.intellij.openapi.ui.popup.IPopupChooserBuilder
import com.intellij.openapi.ui.popup.PopupChooserBuilder
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.ui.components.JBList
import com.intellij.util.IncorrectOperationException
import org.jetbrains.kotlin.asJava.classes.KtLightClass
import org.jetbrains.kotlin.asJava.toLightMethods
import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.ClassKind
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.caches.resolve.util.getJavaClassDescriptor
import org.jetbrains.kotlin.idea.core.overrideImplement.BodyType
import org.jetbrains.kotlin.idea.core.overrideImplement.GenerateMembersHandler
import org.jetbrains.kotlin.idea.core.overrideImplement.OverrideMemberChooserObject
import org.jetbrains.kotlin.idea.core.util.runSynchronouslyWithProgress
import org.jetbrains.kotlin.idea.refactoring.isAbstract
import org.jetbrains.kotlin.idea.search.declarationsSearch.HierarchySearchRequest
import org.jetbrains.kotlin.idea.search.declarationsSearch.searchInheritors
import org.jetbrains.kotlin.idea.util.application.executeCommand
import org.jetbrains.kotlin.idea.util.application.isUnitTestMode
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.idea.util.application.runWriteAction
import org.jetbrains.kotlin.idea.util.getTypeSubstitution
import org.jetbrains.kotlin.idea.util.substitute
import org.jetbrains.kotlin.load.java.descriptors.JavaClassDescriptor
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import org.jetbrains.kotlin.util.findCallableMemberBySignature
import javax.swing.ListSelectionModel
abstract class ImplementAbstractMemberIntentionBase : SelfTargetingRangeIntention<KtNamedDeclaration>(
KtNamedDeclaration::class.java,
KotlinBundle.lazyMessage("implement.abstract.member")
) {
companion object {
private val LOG = Logger.getInstance("#${ImplementAbstractMemberIntentionBase::class.java.canonicalName}")
}
protected fun findExistingImplementation(
subClass: ClassDescriptor,
superMember: CallableMemberDescriptor
): CallableMemberDescriptor? {
val superClass = superMember.containingDeclaration as? ClassDescriptor ?: return null
val substitution = getTypeSubstitution(superClass.defaultType, subClass.defaultType).orEmpty()
val signatureInSubClass = superMember.substitute(substitution) as? CallableMemberDescriptor ?: return null
val subMember = subClass.findCallableMemberBySignature(signatureInSubClass)
return if (subMember?.kind?.isReal == true) subMember else null
}
protected abstract fun acceptSubClass(subClassDescriptor: ClassDescriptor, memberDescriptor: CallableMemberDescriptor): Boolean
private fun findClassesToProcess(member: KtNamedDeclaration): Sequence<PsiElement> {
val baseClass = member.containingClassOrObject as? KtClass ?: return emptySequence()
val memberDescriptor = member.resolveToDescriptorIfAny() as? CallableMemberDescriptor ?: return emptySequence()
fun acceptSubClass(subClass: PsiElement): Boolean {
if (!BaseIntentionAction.canModify(subClass)) return false
val classDescriptor = when (subClass) {
is KtLightClass -> subClass.kotlinOrigin?.resolveToDescriptorIfAny()
is KtEnumEntry -> subClass.resolveToDescriptorIfAny()
is PsiClass -> subClass.getJavaClassDescriptor()
else -> null
} ?: return false
return acceptSubClass(classDescriptor, memberDescriptor)
}
if (baseClass.isEnum()) {
return baseClass.declarations
.asSequence()
.filterIsInstance<KtEnumEntry>()
.filter(::acceptSubClass)
}
return HierarchySearchRequest(baseClass, baseClass.useScope, false)
.searchInheritors()
.asSequence()
.filter(::acceptSubClass)
}
protected abstract fun computeText(element: KtNamedDeclaration): (() -> String)?
override fun applicabilityRange(element: KtNamedDeclaration): TextRange? {
if (!element.isAbstract()) return null
setTextGetter(computeText(element) ?: return null)
if (!findClassesToProcess(element).any()) return null
return element.nameIdentifier?.textRange
}
protected abstract val preferConstructorParameters: Boolean
private fun implementInKotlinClass(editor: Editor?, member: KtNamedDeclaration, targetClass: KtClassOrObject) {
val subClassDescriptor = targetClass.resolveToDescriptorIfAny() ?: return
val superMemberDescriptor = member.resolveToDescriptorIfAny() as? CallableMemberDescriptor ?: return
val superClassDescriptor = superMemberDescriptor.containingDeclaration as? ClassDescriptor ?: return
val substitution = getTypeSubstitution(superClassDescriptor.defaultType, subClassDescriptor.defaultType).orEmpty()
val descriptorToImplement = superMemberDescriptor.substitute(substitution) as CallableMemberDescriptor
val chooserObject = OverrideMemberChooserObject.create(
member.project,
descriptorToImplement,
descriptorToImplement,
BodyType.FROM_TEMPLATE,
preferConstructorParameters
)
GenerateMembersHandler.generateMembers(editor, targetClass, listOf(chooserObject), false)
}
private fun implementInJavaClass(member: KtNamedDeclaration, targetClass: PsiClass) {
member.toLightMethods().forEach { OverrideImplementUtil.overrideOrImplement(targetClass, it) }
}
private fun implementInClass(member: KtNamedDeclaration, targetClasses: List<PsiElement>) {
val project = member.project
project.executeCommand<Unit>(JavaBundle.message("intention.implement.abstract.method.command.name")) {
if (!FileModificationService.getInstance().preparePsiElementsForWrite(targetClasses)) return@executeCommand
runWriteAction<Unit> {
for (targetClass in targetClasses) {
try {
val descriptor = OpenFileDescriptor(project, targetClass.containingFile.virtualFile)
val targetEditor = FileEditorManager.getInstance(project).openTextEditor(descriptor, true)!!
when (targetClass) {
is KtLightClass -> targetClass.kotlinOrigin?.let { implementInKotlinClass(targetEditor, member, it) }
is KtEnumEntry -> implementInKotlinClass(targetEditor, member, targetClass)
is PsiClass -> implementInJavaClass(member, targetClass)
}
} catch (e: IncorrectOperationException) {
LOG.error(e)
}
}
}
}
}
private class ClassRenderer : PsiElementListCellRenderer<PsiElement>() {
private val psiClassRenderer = PsiClassListCellRenderer()
override fun getComparator(): Comparator<PsiElement> {
val baseComparator = psiClassRenderer.comparator
return Comparator { o1, o2 ->
when {
o1 is KtEnumEntry && o2 is KtEnumEntry -> o1.name!!.compareTo(o2.name!!)
o1 is KtEnumEntry -> -1
o2 is KtEnumEntry -> 1
o1 is PsiClass && o2 is PsiClass -> baseComparator.compare(o1, o2)
else -> 0
}
}
}
override fun getElementText(element: PsiElement?): String? {
return when (element) {
is KtEnumEntry -> element.name
is PsiClass -> psiClassRenderer.getElementText(element)
else -> null
}
}
override fun getContainerText(element: PsiElement?, name: String?): String? {
return when (element) {
is KtEnumEntry -> element.containingClassOrObject?.fqName?.asString()
is PsiClass -> PsiClassRenderingInfo.getContainerTextStatic(element)
else -> null
}
}
}
override fun startInWriteAction(): Boolean = false
override fun checkFile(file: PsiFile): Boolean {
return true
}
override fun preparePsiElementForWriteIfNeeded(target: KtNamedDeclaration): Boolean {
return true
}
override fun applyTo(element: KtNamedDeclaration, editor: Editor?) {
if (editor == null) throw IllegalArgumentException("This intention requires an editor")
val project = element.project
val classesToProcess = project.runSynchronouslyWithProgress(
JavaBundle.message("intention.implement.abstract.method.searching.for.descendants.progress"),
true
) { runReadAction { findClassesToProcess(element).toList() } } ?: return
if (classesToProcess.isEmpty()) return
classesToProcess.singleOrNull()?.let { return implementInClass(element, listOf(it)) }
val renderer = ClassRenderer()
val sortedClasses = classesToProcess.sortedWith(renderer.comparator)
if (isUnitTestMode()) return implementInClass(element, sortedClasses)
val list = JBList(sortedClasses).apply {
selectionMode = ListSelectionModel.MULTIPLE_INTERVAL_SELECTION
cellRenderer = renderer
}
val builder = PopupChooserBuilder<PsiElement>(list)
renderer.installSpeedSearch(builder as IPopupChooserBuilder<*>)
builder
.setTitle(CodeInsightBundle.message("intention.implement.abstract.method.class.chooser.title"))
.setItemChoosenCallback {
val index = list.selectedIndex
if (index < 0) return@setItemChoosenCallback
@Suppress("UNCHECKED_CAST")
implementInClass(element, list.selectedValues.toList() as List<KtClassOrObject>)
}
.createPopup()
.showInBestPositionFor(editor)
}
}
class ImplementAbstractMemberIntention : ImplementAbstractMemberIntentionBase() {
override fun computeText(element: KtNamedDeclaration): (() -> String)? = when (element) {
is KtProperty -> KotlinBundle.lazyMessage("implement.abstract.property")
is KtNamedFunction -> KotlinBundle.lazyMessage("implement.abstract.function")
else -> null
}
override fun acceptSubClass(subClassDescriptor: ClassDescriptor, memberDescriptor: CallableMemberDescriptor): Boolean {
return subClassDescriptor.kind != ClassKind.INTERFACE && findExistingImplementation(subClassDescriptor, memberDescriptor) == null
}
override val preferConstructorParameters: Boolean
get() = false
}
class ImplementAbstractMemberAsConstructorParameterIntention : ImplementAbstractMemberIntentionBase() {
override fun computeText(element: KtNamedDeclaration): (() -> String)? {
if (element !is KtProperty) return null
return KotlinBundle.lazyMessage("implement.as.constructor.parameter")
}
override fun acceptSubClass(subClassDescriptor: ClassDescriptor, memberDescriptor: CallableMemberDescriptor): Boolean {
val kind = subClassDescriptor.kind
return (kind == ClassKind.CLASS || kind == ClassKind.ENUM_CLASS)
&& subClassDescriptor !is JavaClassDescriptor
&& findExistingImplementation(subClassDescriptor, memberDescriptor) == null
}
override val preferConstructorParameters: Boolean
get() = true
override fun applicabilityRange(element: KtNamedDeclaration): TextRange? {
if (element !is KtProperty) return null
return super.applicabilityRange(element)
}
} | apache-2.0 | 770cbadc4a1079e17a0f12804ac68f56 | 46.885185 | 137 | 0.715347 | 5.763709 | false | false | false | false |
jwren/intellij-community | java/java-impl/src/com/intellij/codeInsight/hints/ImplicitTypeInlayProvider.kt | 1 | 3023 | // Copyright 2000-2020 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.codeInsight.hints
import com.intellij.codeInsight.hints.presentation.MenuOnClickPresentation
import com.intellij.java.JavaBundle
import com.intellij.openapi.editor.Editor
import com.intellij.psi.*
import javax.swing.JComponent
import javax.swing.JPanel
class ImplicitTypeInlayProvider : InlayHintsProvider<NoSettings> {
override fun getCollectorFor(file: PsiFile, editor: Editor, settings: NoSettings, sink: InlayHintsSink): InlayHintsCollector? {
val project = file.project
return object: FactoryInlayHintsCollector(editor) {
override fun collect(element: PsiElement, editor: Editor, sink: InlayHintsSink): Boolean {
if (element is PsiLocalVariable) {
val initializer = element.initializer ?: return true
val identifier = element.identifyingElement ?: return true
if (initializer is PsiLiteral ||
initializer is PsiPolyadicExpression ||
initializer is PsiNewExpression ||
initializer is PsiTypeCastExpression) {
return true
}
if (!element.typeElement.isInferredType) return true
val type = element.type
if (type == PsiPrimitiveType.NULL) return true
val presentation = JavaTypeHintsPresentationFactory.presentationWithColon(type, factory)
val withMenu = MenuOnClickPresentation(presentation, project) {
val provider = this@ImplicitTypeInlayProvider
listOf(InlayProviderDisablingAction(provider.name, file.language, project, provider.key))
}
val shifted = factory.inset(withMenu, left = 3)
sink.addInlineElement(identifier.textRange.endOffset, true, shifted, false)
}
return true
}
}
}
override fun createSettings(): NoSettings = NoSettings()
override val name: String
get() = JavaBundle.message("settings.inlay.java.implicit.types")
override val group: InlayGroup
get() = InlayGroup.TYPES_GROUP
override val key: SettingsKey<NoSettings>
get() = SettingsKey("java.implicit.types")
override val previewText: String
get() = "class HintsDemo {\n" +
"\n" +
" public static void main(String[] args) {\n" +
" var list = getList(); // List<String> is inferred\n" +
" }\n" +
"\n" +
" private static List<String> getList() {\n" +
" return Arrays.asList(\"hello\", \"world\");\n" +
" }\n" +
"}"
override fun createConfigurable(settings: NoSettings): ImmediateConfigurable {
return object : ImmediateConfigurable {
override fun createComponent(listener: ChangeListener): JComponent {
return JPanel()
}
}
}
override val description: String
get() = JavaBundle.message("settings.inlay.java.implicit.types.description")
}
| apache-2.0 | 05e45b76920040545402d4430174a687 | 41.577465 | 140 | 0.666556 | 4.907468 | false | false | false | false |
smmribeiro/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/management/modules/ModulesTreeItemRenderer.kt | 3 | 1770 | package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.modules
import com.intellij.icons.AllIcons
import com.intellij.ui.ColoredTreeCellRenderer
import com.intellij.ui.SimpleTextAttributes
import com.intellij.ui.speedSearch.SpeedSearchUtil
import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.TargetModules
import com.jetbrains.packagesearch.intellij.plugin.ui.util.scaled
import javax.swing.JTree
import javax.swing.tree.DefaultMutableTreeNode
class ModulesTreeItemRenderer : ColoredTreeCellRenderer() {
override fun customizeCellRenderer(
tree: JTree,
value: Any?,
selected: Boolean,
expanded: Boolean,
leaf: Boolean,
row: Int,
hasFocus: Boolean
) {
if (value !is DefaultMutableTreeNode) return
clear()
@Suppress("MagicNumber") // Swing dimension constants
iconTextGap = 4.scaled()
when (val nodeTarget = value.userObject as TargetModules) {
TargetModules.None, is TargetModules.All -> {
icon = AllIcons.Nodes.ModuleGroup
append(
PackageSearchBundle.message("packagesearch.ui.toolwindow.allModules"),
SimpleTextAttributes.REGULAR_ATTRIBUTES
)
}
is TargetModules.One -> {
val projectModule = nodeTarget.module.projectModule
icon = projectModule.moduleType.icon ?: AllIcons.Nodes.Module
append(projectModule.name, SimpleTextAttributes.REGULAR_ATTRIBUTES)
}
}
SpeedSearchUtil.applySpeedSearchHighlighting(tree, this, true, selected)
}
}
| apache-2.0 | 3f560601914ccc21770f81db72b208b9 | 35.875 | 91 | 0.684181 | 5.267857 | false | false | false | false |
LouisCAD/Splitties | modules/resources/src/androidMain/kotlin/splitties/resources/DrawableResources.kt | 1 | 2640 | /*
* Copyright 2019 Louis Cognault Ayeva Derman. Use of this source code is governed by the Apache 2.0 license.
*/
@file:Suppress("NOTHING_TO_INLINE")
package splitties.resources
import android.content.Context
import android.graphics.drawable.Drawable
import android.os.Build.VERSION.SDK_INT
import android.util.TypedValue
import android.view.View
import androidx.annotation.AttrRes
import androidx.annotation.DrawableRes
import androidx.fragment.app.Fragment
import splitties.init.appCtx
private val tmpValue by lazy { TypedValue() }
/**
* @see [androidx.core.content.ContextCompat.getDrawable]
*/
fun Context.drawable(@DrawableRes drawableResId: Int): Drawable? {
@Suppress("CascadeIf")
return if (SDK_INT >= 21) getDrawable(drawableResId)
else if (SDK_INT >= 16) {
@Suppress("DEPRECATION")
resources.getDrawable(drawableResId)
} else {
// Prior to API 16, Resources.getDrawable() would not correctly
// retrieve the final configuration density when the resource ID
// is a reference another Drawable resource. As a workaround, try
// to resolve the drawable reference manually.
val resolvedId = synchronized(tmpValue) {
resources.getValue(drawableResId, tmpValue, true)
tmpValue.resourceId
}
@Suppress("DEPRECATION")
resources.getDrawable(resolvedId)
}
}
inline fun Fragment.drawable(@DrawableRes drawableResId: Int) = context!!.drawable(drawableResId)
inline fun View.drawable(@DrawableRes drawableResId: Int) = context.drawable(drawableResId)
/**
* Use this method for non configuration dependent resources when you don't have a [Context]
* or when you're calling it from an Activity or a Fragment member (as the Context is not
* initialized yet).
*
* For theme dependent resources, the application theme will be implicitly used.
*/
inline fun appDrawable(@DrawableRes drawableResId: Int) = appCtx.drawable(drawableResId)
// Styled resources below
fun Context.styledDrawable(@AttrRes attr: Int): Drawable? = drawable(resolveThemeAttribute(attr))
inline fun Fragment.styledDrawable(@AttrRes attr: Int) = context!!.styledDrawable(attr)
inline fun View.styledDrawable(@AttrRes attr: Int) = context.styledDrawable(attr)
/**
* Use this method for non configuration dependent resources when you don't have a [Context]
* or when you're calling it from an Activity or a Fragment member (as the Context is not
* initialized yet).
*
* For theme dependent resources, the application theme will be implicitly used.
*/
inline fun appStyledDrawable(@AttrRes attr: Int) = appCtx.styledDrawable(attr)
| apache-2.0 | 68eb5e6f426692f76d4f6edb72cf9b38 | 37.26087 | 109 | 0.745455 | 4.378109 | false | false | false | false |
smmribeiro/intellij-community | plugins/git4idea/src/git4idea/repo/GitConfigHelper.kt | 13 | 836 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package git4idea.repo
import com.intellij.openapi.diagnostic.Logger
import org.ini4j.Ini
import java.io.File
import java.io.IOException
@Throws(IOException::class)
internal fun loadIniFile(file: File): Ini {
val ini = Ini()
ini.config.isMultiOption = true // duplicate keys (e.g. url in [remote])
ini.config.isTree = false // don't need tree structure: it corrupts url in section name (e.g. [url "http://github.com/"]
ini.config.isLowerCaseOption = true
ini.config.isEmptyOption = true
try {
ini.load(file)
return ini
}
catch (e: IOException) {
Logger.getInstance(GitConfig::class.java).warn("Couldn't load config file at ${file.path}", e)
throw e
}
} | apache-2.0 | ef224232b30d63181848caf2293683b5 | 33.875 | 140 | 0.714115 | 3.412245 | false | true | false | false |
smmribeiro/intellij-community | platform/vcs-impl/src/com/intellij/codeInsight/completion/ml/VcsFeatureProvider.kt | 9 | 2123 | // 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.codeInsight.completion.ml
import com.intellij.codeInsight.completion.CompletionLocation
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.openapi.vcs.changes.Change
import com.intellij.openapi.vcs.changes.ChangeListManager
import com.intellij.openapi.vcs.impl.LineStatusTrackerManager
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiNameIdentifierOwner
class VcsFeatureProvider : ElementFeatureProvider {
override fun getName(): String = "vcs"
override fun calculateFeatures(element: LookupElement,
location: CompletionLocation,
contextFeatures: ContextFeatures): Map<String, MLFeatureValue> {
val features = mutableMapOf<String, MLFeatureValue>()
val project = location.project
val psi = element.psiElement
val psiFile = psi?.containingFile
psiFile?.viewProvider?.virtualFile?.let { file ->
val changeListManager = ChangeListManager.getInstance(project)
changeListManager.getChange(file)?.let { change ->
features["file_state"] = MLFeatureValue.categorical(change.type) // NON-NLS
if (change.type == Change.Type.MODIFICATION && psi is PsiNameIdentifierOwner) {
val document = PsiDocumentManager.getInstance(project).getCachedDocument(psiFile)
val range = psi.textRange
if (document != null && range != null && range.endOffset <= document.textLength) {
val lineStatusTracker = LineStatusTrackerManager.getInstance(project).getLineStatusTracker(document)
if (lineStatusTracker != null && lineStatusTracker.isValid()) {
if (lineStatusTracker.isRangeModified(document.getLineNumber(range.startOffset), document.getLineNumber(range.endOffset))) {
features["declaration_is_changed"] = MLFeatureValue.binary(true) // NON-NLS
}
}
}
}
}
}
return features
}
} | apache-2.0 | e55d6ad8b572b92080416c650d994666 | 48.395349 | 140 | 0.709374 | 5.152913 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/jvm-debugger/test/test/org/jetbrains/kotlin/idea/debugger/test/util/LogPropagator.kt | 2 | 1297 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.debugger.test.util
import org.apache.log4j.AppenderSkeleton
import org.apache.log4j.Level
import org.apache.log4j.Logger
import org.apache.log4j.spi.LoggingEvent
import org.jetbrains.kotlin.idea.debugger.evaluate.KotlinDebuggerCaches
internal class LogPropagator(val systemLogger: (String) -> Unit) {
private var oldLogLevel: Level? = null
private val logger = Logger.getLogger(KotlinDebuggerCaches::class.java)
private var appender: AppenderSkeleton? = null
fun attach() {
oldLogLevel = logger.level
logger.level = Level.DEBUG
appender = object : AppenderSkeleton() {
override fun append(event: LoggingEvent?) {
val message = event?.renderedMessage
if (message != null) {
systemLogger(message)
}
}
override fun close() {}
override fun requiresLayout() = false
}
logger.addAppender(appender)
}
fun detach() {
logger.removeAppender(appender)
appender = null
logger.level = oldLogLevel
}
} | apache-2.0 | 566508f0abdbe25afa3fec75041eb421 | 30.658537 | 158 | 0.657672 | 4.39661 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/joinLines/removeTrailingComma/keepLineBreak.kt | 14 | 585 | class AdditionalData {
public val timeRange: String = "str"
}
fun curveSet(
log: String, timeRange: String,
graphVarId: String, xVariable: String,
unitSettings: String, rightColor: String
): String {
TODO()
}
fun main() {
var log: String = "str"
var xVariable = "str"
var unitSettings = "str"
var rightColor = "str"
var additionalData = AdditionalData()
var variableToUseAsAltitude = AdditionalData()
var a = curveSet(log, additionalData.timeRange, variableToUseAsAltitude.timeRange, xVariable, unitSettings,<caret> rightColor
)
} | apache-2.0 | 9f7a35b7811d9d24b4c13e569a986b08 | 24.478261 | 129 | 0.690598 | 3.75 | false | false | false | false |
gregcockroft/AndroidMath | mathdisplaylib/src/main/java/com/agog/mathdisplay/parse/MTMathList.kt | 1 | 3755 | package com.agog.mathdisplay.parse
class MTMathList {
var atoms = mutableListOf<MTMathAtom>()
constructor(vararg alist: MTMathAtom) {
for (atom in alist) {
atoms.add(atom)
}
}
constructor(alist: MutableList<MTMathAtom>) {
atoms.addAll(alist)
}
private fun isAtomAllowed(atom: MTMathAtom): Boolean {
return atom.type != MTMathAtomType.KMTMathAtomBoundary
}
fun addAtom(atom: MTMathAtom) {
if (!isAtomAllowed(atom)) {
val s = MTMathAtom.typeToText(atom.type)
throw MathDisplayException("Cannot add atom of type $s in a mathlist ")
}
atoms.add(atom)
}
fun insertAtom(atom: MTMathAtom, index: Int) {
if (!isAtomAllowed(atom)) {
val s = MTMathAtom.typeToText(atom.type)
throw MathDisplayException("Cannot add atom of type $s in a mathlist ")
}
atoms.add(index, atom)
}
fun append(list: MTMathList) {
atoms.addAll(list.atoms)
}
override fun toString(): String {
val str = StringBuilder()
for (atom in this.atoms) {
str.append(atom.toString())
}
return str.toString()
}
fun description(): String {
return (this.toString())
}
fun finalized(): MTMathList {
val newList = MTMathList()
val zeroRange = NSRange(0, 0)
var prevNode: MTMathAtom? = null
for (atom in this.atoms) {
val newNode = atom.finalized()
var skip = false // Skip adding this node it has been fused
// Each character is given a separate index.
if (zeroRange.equal(atom.indexRange)) {
val index: Int = if (prevNode == null) {
0
} else {
prevNode.indexRange.location + prevNode.indexRange.length
}
newNode.indexRange = NSRange(index, 1)
}
when (newNode.type) {
MTMathAtomType.KMTMathAtomBinaryOperator -> {
if (MTMathAtom.isNotBinaryOperator(prevNode)) {
newNode.type = MTMathAtomType.KMTMathAtomUnaryOperator
}
}
MTMathAtomType.KMTMathAtomRelation, MTMathAtomType.KMTMathAtomPunctuation, MTMathAtomType.KMTMathAtomClose -> {
if (prevNode != null && prevNode.type == MTMathAtomType.KMTMathAtomBinaryOperator) {
prevNode.type = MTMathAtomType.KMTMathAtomUnaryOperator
}
}
MTMathAtomType.KMTMathAtomNumber -> {
// combine numbers together
if (prevNode != null && prevNode.type == MTMathAtomType.KMTMathAtomNumber && prevNode.subScript == null && prevNode.superScript == null) {
prevNode.fuse(newNode)
// skip the current node, we are done here.
skip = true
}
}
else -> {
// Do nothing
}
}
if (!skip) {
newList.addAtom(newNode)
prevNode = newNode
}
}
if (prevNode != null && prevNode.type == MTMathAtomType.KMTMathAtomBinaryOperator) {
// it isn't a binary since there is noting after it. Make it a unary
prevNode.type = MTMathAtomType.KMTMathAtomUnaryOperator
}
return newList
}
fun copyDeep(): MTMathList {
val newList = MTMathList()
for (atom in this.atoms) {
newList.addAtom(atom.copyDeep())
}
return newList
}
}
| mit | 3f01f41e318825e3cab14a34e7194294 | 31.37069 | 158 | 0.534487 | 4.464923 | false | false | false | false |
shivamsriva31093/MovieFinder | app/src/main/java/task/application/com/colette/messaging/notifications/Empty.kt | 1 | 1241 | package task.application.com.colette.messaging.notifications
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import com.androidtmdbwrapper.model.mediadetails.MediaBasic
import task.application.com.colette.R
import task.application.com.colette.messaging.PushNotificationChannel
import task.application.com.colette.messaging.PushNotificationItem
import task.application.com.colette.ui.splash.SplashActivity
/**
* Created by sHIVAM on 3/25/2018.
*/
internal class Empty(val context: Context) : PushNotificationItem {
override fun channel(): PushNotificationChannel = PushNotificationChannel.Empty()
override fun title(): String = "Colette"
override fun message(): String = "Hello from the other side!"
override fun smallIcon(): Int = R.drawable.imdb_icon
override fun data(): MediaBasic = MediaBasic()
override fun pendingIntent(): PendingIntent {
val intent = Intent(context, SplashActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP
val reqId = System.currentTimeMillis().toInt()
return PendingIntent.getActivity(context, reqId, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}
} | apache-2.0 | a7229f9624b875acb699e349aa895f00 | 36.636364 | 99 | 0.771152 | 4.294118 | false | false | false | false |
NlRVANA/Unity | app/src/main/java/com/zwq65/unity/ui/presenter/AlbumPresenter.kt | 1 | 2015 | /*
* Copyright [2017] [NIRVANA PRIVATE 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.zwq65.unity.ui.presenter
import com.zwq65.unity.data.DataManager
import com.zwq65.unity.data.network.retrofit.response.enity.Image
import com.zwq65.unity.ui._base.BasePresenter
import com.zwq65.unity.ui.contract.AlbumContract
import javax.inject.Inject
/**
* ================================================
*
* Created by NIRVANA on 2017/07/20
* Contact with <[email protected]>
* ================================================
*/
class AlbumPresenter<V : AlbumContract.View<Image>> @Inject
internal constructor(dataManager: DataManager) : BasePresenter<V>(dataManager), AlbumContract.Presenter<V> {
private var page: Int = 0
override fun init() {
page = 1
loadImages(true)
}
override fun loadImages(isRefresh: Boolean?) {
dataManager.get20Images(page)
.apiSubscribe({
it?.let {
if (it.data?.isNotEmpty()!!) {
page++
if (isRefresh!!) {
mvpView?.refreshData(it.data!!)
} else {
mvpView?.loadData(it.data!!)
}
} else {
mvpView?.noMoreData()
}
}
})
}
}
| apache-2.0 | 051c6c95bbbfb79c29d28c8fbb1707ea | 33.152542 | 108 | 0.547395 | 4.69697 | false | false | false | false |
MartinStyk/AndroidApkAnalyzer | app/src/main/java/sk/styk/martin/apkanalyzer/manager/appanalysis/DexManager.kt | 1 | 1880 | package sk.styk.martin.apkanalyzer.manager.appanalysis
import android.content.pm.PackageInfo
import dalvik.system.DexFile
import sk.styk.martin.apkanalyzer.model.detail.ClassPathData
import sk.styk.martin.apkanalyzer.util.TAG_APP_ANALYSIS
import timber.log.Timber
import java.io.IOException
import java.util.*
import javax.inject.Inject
@Suppress("DEPRECATION")
class DexManager @Inject constructor(){
fun get(packageInfo: PackageInfo): ClassPathData {
val packageClasses = ArrayList<String>()
val otherClasses = ArrayList<String>()
var innerClasses = 0
if (packageInfo.applicationInfo != null) {
var dexFile: DexFile? = null
try {
dexFile = DexFile(packageInfo.applicationInfo.sourceDir)
val iterator = dexFile.entries()
while (iterator.hasMoreElements()) {
val className = iterator.nextElement()
if (className != null && className.startsWith(packageInfo.applicationInfo.packageName))
packageClasses.add(className)
else
otherClasses.add(className)
if (className != null && className.contains("$")) {
innerClasses++
}
}
} catch (e: IOException) {
Timber.tag(TAG_APP_ANALYSIS).w(e, "Can not read dex info")
} finally {
try {
dexFile?.close()
} catch (e: IOException) {
Timber.tag(TAG_APP_ANALYSIS).w(e, "Can not close dex file")
}
}
}
return ClassPathData(
packageClasses = packageClasses,
otherClasses = otherClasses,
numberOfInnerClasses = innerClasses
)
}
}
| gpl-3.0 | 775bc0675cab8ac1b0224691f62f7579 | 33.181818 | 107 | 0.563298 | 5.081081 | false | false | false | false |
prof18/RSS-Parser | rssparser/src/main/java/com/prof/rssparser/caching/CachedFeed.kt | 1 | 654 | package com.prof.rssparser.caching
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = CacheConstants.CACHED_FEEDS_TABLE_NAME)
internal class CachedFeed(
@PrimaryKey
@ColumnInfo(name = "url_hash")
var urlHash: Int,
@ColumnInfo(name = "byte_data", typeAffinity = ColumnInfo.BLOB)
var byteArray: ByteArray,
@ColumnInfo(name = "cached_date")
var cachedDate: Long,
@ColumnInfo(name = "library_version")
var libraryVersion: Int,
@ColumnInfo(name = "charset", defaultValue = "UTF-8")
var charset: String
)
| apache-2.0 | 467002734089cf63c0d0d9d1ee15781e | 26.25 | 71 | 0.668196 | 4.0875 | false | false | false | false |
Waboodoo/HTTP-Shortcuts | HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/extensions/ViewExtensions.kt | 1 | 1498 | package ch.rmy.android.http_shortcuts.extensions
import android.net.Uri
import android.text.Spanned
import android.text.style.ImageSpan
import android.widget.ImageView
import android.widget.TextView
import androidx.core.text.getSpans
import ch.rmy.android.framework.extensions.runIf
import ch.rmy.android.http_shortcuts.R
import com.squareup.picasso.MemoryPolicy
import com.squareup.picasso.NetworkPolicy
import com.squareup.picasso.Picasso
fun ImageView.loadImage(uri: Uri, preventMemoryCache: Boolean = false) {
Picasso.get()
.load(uri)
.noFade()
.placeholder(R.drawable.image_placeholder)
.networkPolicy(NetworkPolicy.NO_CACHE)
.runIf(preventMemoryCache) {
memoryPolicy(MemoryPolicy.NO_CACHE)
}
.error(R.drawable.bitsies_cancel)
.into(this)
}
fun TextView.reloadImageSpans() {
text = (text as? Spanned)
?.apply {
getSpans<ImageSpan>()
.map { it.drawable }
.forEach { drawable ->
if (drawable.intrinsicWidth > width && drawable.intrinsicWidth > 0) {
val aspectRatio = drawable.intrinsicWidth / drawable.intrinsicHeight.toDouble()
val newImageWidth = width
val newImageHeight = (newImageWidth / aspectRatio).toInt()
drawable.setBounds(0, 0, newImageWidth, newImageHeight)
}
}
}
?: return
}
| mit | 93f0745a5ea3f7dc5877b89700e55138 | 33.837209 | 103 | 0.633511 | 4.52568 | false | false | false | false |
MediaArea/MediaInfo | Source/GUI/Android/app/src/main/java/net/mediaarea/mediainfo/Core.kt | 1 | 2422 | /* Copyright (c) MediaArea.net SARL. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license that can
* be found in the License.html file in the root of the source tree.
*/
package net.mediaarea.mediainfo
object Core {
data class ReportView(val name: String, val desc: String, val mime: String, val exportable: Boolean) {
override fun toString(): String {
return desc
}
}
val ARG_REPORT_ID = "id"
val mi: MediaInfo = MediaInfo()
val views: MutableList<ReportView> = mutableListOf()
val version: String = mi.Option("Info_Version").replace("MediaInfoLib - v", "")
var language: String = ""
init {
// populate views list
val viewsCsv: String = mi.Option("Info_OutputFormats_CSV")
viewsCsv.split("\n").forEach {
val view: List<String> = it.split(",")
if (view.size > 2)
views.add(ReportView(view[0], view[1], view[2], true))
}
}
fun setLocale(locale: String) {
language = locale
}
fun createReport(fd: Int, name: String): ByteArray {
mi.Option("Language", "")
mi.Option("Inform", "MIXML")
mi.Option("Input_Compressed", "")
mi.Option("Inform_Compress", "zlib+base64")
mi.Open(fd, name)
val report: String = mi.Inform()
mi.Close()
return report.toByteArray()
}
fun convertReport(report: ByteArray, format: String, export: Boolean = false) : String {
mi.Option("Inform", format)
mi.Option("Inform_Compress", "")
mi.Option("Input_Compressed", "zlib+base64")
if (format == "Text" && !export) {
if (language.isNotEmpty()) {
mi.Option("Language", language.replace(" Config_Text_ColumnSize;40", " Config_Text_ColumnSize;25"))
}
else {
mi.Option("Language", " Config_Text_ColumnSize;25")
}
}
else {
if (language.isNotEmpty()) {
mi.Option("Language", language)
}
else {
mi.Option("Language", "")
}
}
mi.Open_Buffer_Init(report.size.toLong(), 0L)
mi.Open_Buffer_Continue(report, report.size.toLong())
mi.Open_Buffer_Finalize()
val output: String = mi.Inform()
mi.Close()
return output
}
}
| bsd-2-clause | 541ed39620aa92d0ecce29b2016dda4d | 29.658228 | 117 | 0.555739 | 4.009934 | false | false | false | false |
vivchar/RendererRecyclerViewAdapter | example/src/main/java/com/github/vivchar/example/widgets/MyItemDecoration.kt | 1 | 1739 | package com.github.vivchar.example.widgets
import android.graphics.Rect
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ItemDecoration
import com.github.vivchar.example.pages.github.items.CategoryModel
import com.github.vivchar.example.pages.github.items.RecyclerViewModel
import com.github.vivchar.rendererrecyclerviewadapter.RendererRecyclerViewAdapter
import com.github.vivchar.rendererrecyclerviewadapter.ViewModel
/**
* Created by Vivchar Vitaly on 7/24/17.
*/
class MyItemDecoration: ItemDecoration() {
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
val layoutManager = parent.layoutManager
val itemPosition = parent.getChildAdapterPosition(view)
if (itemPosition != RecyclerView.NO_POSITION) {
if (layoutManager is GridLayoutManager) {
val adapter = parent.adapter as RendererRecyclerViewAdapter?
when (adapter!!.getItem<ViewModel>(itemPosition)) {
is RecyclerViewModel -> {
outRect.left = (-10f).dpToPixels()
outRect.right = (-10f).dpToPixels()
outRect.top = (5f).dpToPixels()
outRect.bottom = (5f).dpToPixels()
}
is CategoryModel -> {
outRect.left = (5f).dpToPixels()
outRect.right = (5f).dpToPixels()
outRect.top = (10f).dpToPixels()
outRect.bottom = (2f).dpToPixels()
}
else -> {
outRect.left = (5f).dpToPixels()
outRect.right = (5f).dpToPixels()
outRect.top = (5f).dpToPixels()
outRect.bottom = (5f).dpToPixels()
}
}
} else {
throw UnsupportedClassVersionError("Unsupported LayoutManager")
}
}
}
} | apache-2.0 | f52b23cf9d656febc3f9d758eb34b171 | 34.510204 | 106 | 0.726855 | 3.75594 | false | false | false | false |
h0tk3y/better-parse | buildSrc/src/main/kotlin/AndCodegen.kt | 1 | 1995 | import java.io.File
fun andCodegen(maxN: Int, outputFile: String) {
fun genericsStr(i: Int) = (1..i).joinToString(prefix = "<", postfix = ">") { "T$it" }
val resultCode = buildString {
appendLine("@file:Suppress(")
appendLine(" \"NO_EXPLICIT_RETURN_TYPE_IN_API_MODE\", // fixme: bug in Kotlin 1.4.21, fixed in 1.4.30")
appendLine(" \"MoveLambdaOutsideParentheses\", ")
appendLine(" \"PackageDirectoryMismatch\"")
appendLine(")")
appendLine()
appendLine("package com.github.h0tk3y.betterParse.combinators")
appendLine("import com.github.h0tk3y.betterParse.utils.*")
appendLine("import com.github.h0tk3y.betterParse.parser.*")
appendLine("import kotlin.jvm.JvmName")
appendLine()
for (i in 2 until maxN) {
val generics = genericsStr(i)
val reifiedNext = (1..i + 1).joinToString { "reified T$it" }
val casts = (1..i + 1).joinToString { "it[${it - 1}] as T$it" }
appendLine(
"""
@JvmName("and$i") public inline infix fun <$reifiedNext>
AndCombinator<Tuple$i$generics>.and(p${i + 1}: Parser<T${i + 1}>)
// : AndCombinator<Tuple${i + 1}${genericsStr(i + 1)}> =
= AndCombinator(consumersImpl + p${i + 1}, {
Tuple${i + 1}($casts)
})
""".trimIndent() + "\n"
)
appendLine(
"""
@JvmName("and$i${"Operator"}") public inline operator fun <$reifiedNext>
AndCombinator<Tuple$i$generics>.times(p${i + 1}: Parser<T${i + 1}>)
// : AndCombinator<Tuple${i + 1}${genericsStr(i + 1)}> =
= this and p${i + 1}
""".trimIndent() + "\n\n"
)
}
}
File(outputFile).apply {
parentFile.mkdirs()
writeText(resultCode)
}
} | apache-2.0 | d419e5cfd3d71a703ed31e374041f0f9 | 37.384615 | 114 | 0.503759 | 4.104938 | false | false | false | false |
mapzen/eraser-map | app/src/test/kotlin/com/mapzen/erasermap/model/TestRouter.kt | 1 | 1589 | package com.mapzen.erasermap.model
import android.content.Context
import com.mapzen.android.routing.MapzenRouter
import com.mapzen.valhalla.RouteCallback
import java.util.ArrayList
class TestRouter(context: Context) : MapzenRouter(context) {
var locations: ArrayList<DoubleArray> = ArrayList()
var isFetching: Boolean = false
var units: MapzenRouter.DistanceUnits = MapzenRouter.DistanceUnits.MILES
var bearing: Int = 0
var name: String? = null
override fun clearLocations(): MapzenRouter {
locations.clear()
return this
}
override fun fetch() {
isFetching = true
}
override fun setBiking(): MapzenRouter {
return this
}
override fun setCallback(callback: RouteCallback): MapzenRouter {
return this
}
override fun setDriving(): MapzenRouter {
return this
}
override fun setLocation(point: DoubleArray): MapzenRouter {
locations.add(point)
return this
}
override fun setLocation(point: DoubleArray, heading: Int): MapzenRouter {
locations.add(point)
bearing = heading
return this
}
override fun setLocation(point: DoubleArray, name: String?, street: String?, city: String?,
state: String?): MapzenRouter {
this.name = name
locations.add(point)
return this
}
override fun setWalking(): MapzenRouter {
return this
}
override fun setDistanceUnits(units: MapzenRouter.DistanceUnits): MapzenRouter {
this.units = units
return this
}
}
| gpl-3.0 | 46614ceed4d5ce5b9da8f3b7388941f4 | 24.629032 | 95 | 0.662052 | 4.488701 | false | false | false | false |
seventhroot/elysium | bukkit/rpk-characters-bukkit/src/main/kotlin/com/rpkit/characters/bukkit/database/table/RPKCharacterTable.kt | 1 | 23230 | /*
* Copyright 2016 Ross 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.characters.bukkit.database.table
import com.rpkit.characters.bukkit.RPKCharactersBukkit
import com.rpkit.characters.bukkit.character.RPKCharacter
import com.rpkit.characters.bukkit.character.RPKCharacterImpl
import com.rpkit.characters.bukkit.database.jooq.rpkit.Tables.PLAYER_CHARACTER
import com.rpkit.characters.bukkit.database.jooq.rpkit.Tables.RPKIT_CHARACTER
import com.rpkit.characters.bukkit.gender.RPKGenderProvider
import com.rpkit.characters.bukkit.race.RPKRaceProvider
import com.rpkit.core.bukkit.util.itemStackArrayFromByteArray
import com.rpkit.core.bukkit.util.itemStackFromByteArray
import com.rpkit.core.bukkit.util.toByteArray
import com.rpkit.core.database.Database
import com.rpkit.core.database.Table
import com.rpkit.players.bukkit.player.RPKPlayer
import com.rpkit.players.bukkit.player.RPKPlayerProvider
import com.rpkit.players.bukkit.profile.RPKMinecraftProfile
import com.rpkit.players.bukkit.profile.RPKMinecraftProfileProvider
import com.rpkit.players.bukkit.profile.RPKProfile
import com.rpkit.players.bukkit.profile.RPKProfileProvider
import org.bukkit.Location
import org.ehcache.config.builders.CacheConfigurationBuilder
import org.ehcache.config.builders.ResourcePoolsBuilder
import org.jooq.impl.DSL.constraint
import org.jooq.impl.SQLDataType
/**
* Represents the character table.
*/
class RPKCharacterTable(database: Database, private val plugin: RPKCharactersBukkit): Table<RPKCharacter>(database, RPKCharacter::class) {
private val cache = if (plugin.config.getBoolean("caching.rpkit_character.id.enabled")) {
database.cacheManager.createCache("rpk-characters-bukkit.rpkit_character.id",
CacheConfigurationBuilder.newCacheConfigurationBuilder(Int::class.javaObjectType, RPKCharacter::class.java,
ResourcePoolsBuilder.heap(plugin.config.getLong("caching.rpkit_character.id.size"))).build())
} else {
null
}
override fun create() {
database.create.createTableIfNotExists(RPKIT_CHARACTER)
.column(RPKIT_CHARACTER.ID, SQLDataType.INTEGER.identity(true))
.column(RPKIT_CHARACTER.PLAYER_ID, SQLDataType.INTEGER)
.column(RPKIT_CHARACTER.PROFILE_ID, SQLDataType.INTEGER)
.column(RPKIT_CHARACTER.MINECRAFT_PROFILE_ID, SQLDataType.INTEGER)
.column(RPKIT_CHARACTER.NAME, SQLDataType.VARCHAR(256))
.column(RPKIT_CHARACTER.GENDER_ID, SQLDataType.INTEGER)
.column(RPKIT_CHARACTER.AGE, SQLDataType.INTEGER)
.column(RPKIT_CHARACTER.RACE_ID, SQLDataType.INTEGER)
.column(RPKIT_CHARACTER.DESCRIPTION, SQLDataType.VARCHAR(1024))
.column(RPKIT_CHARACTER.DEAD, SQLDataType.TINYINT.length(1))
.column(RPKIT_CHARACTER.WORLD, SQLDataType.VARCHAR(256))
.column(RPKIT_CHARACTER.X, SQLDataType.DOUBLE)
.column(RPKIT_CHARACTER.Y, SQLDataType.DOUBLE)
.column(RPKIT_CHARACTER.Z, SQLDataType.DOUBLE)
.column(RPKIT_CHARACTER.YAW, SQLDataType.DOUBLE)
.column(RPKIT_CHARACTER.PITCH, SQLDataType.DOUBLE)
.column(RPKIT_CHARACTER.INVENTORY_CONTENTS, SQLDataType.BLOB)
.column(RPKIT_CHARACTER.HELMET, SQLDataType.BLOB)
.column(RPKIT_CHARACTER.CHESTPLATE, SQLDataType.BLOB)
.column(RPKIT_CHARACTER.LEGGINGS, SQLDataType.BLOB)
.column(RPKIT_CHARACTER.BOOTS, SQLDataType.BLOB)
.column(RPKIT_CHARACTER.HEALTH, SQLDataType.DOUBLE)
.column(RPKIT_CHARACTER.MAX_HEALTH, SQLDataType.DOUBLE)
.column(RPKIT_CHARACTER.MANA, SQLDataType.INTEGER)
.column(RPKIT_CHARACTER.MAX_MANA, SQLDataType.INTEGER)
.column(RPKIT_CHARACTER.FOOD_LEVEL, SQLDataType.INTEGER)
.column(RPKIT_CHARACTER.THIRST_LEVEL, SQLDataType.INTEGER)
.column(RPKIT_CHARACTER.PLAYER_HIDDEN, SQLDataType.TINYINT.length(1))
.column(RPKIT_CHARACTER.PROFILE_HIDDEN, SQLDataType.TINYINT.length(1))
.column(RPKIT_CHARACTER.NAME_HIDDEN, SQLDataType.TINYINT.length(1))
.column(RPKIT_CHARACTER.GENDER_HIDDEN, SQLDataType.TINYINT.length(1))
.column(RPKIT_CHARACTER.AGE_HIDDEN, SQLDataType.TINYINT.length(1))
.column(RPKIT_CHARACTER.RACE_HIDDEN, SQLDataType.TINYINT.length(1))
.column(RPKIT_CHARACTER.DESCRIPTION_HIDDEN, SQLDataType.TINYINT.length(1))
.constraints(
constraint("pk_rpkit_character").primaryKey(RPKIT_CHARACTER.ID)
)
.execute()
database.create
.createTableIfNotExists(PLAYER_CHARACTER)
.column(PLAYER_CHARACTER.PLAYER_ID, SQLDataType.INTEGER)
.column(PLAYER_CHARACTER.CHARACTER_ID, SQLDataType.INTEGER)
.constraints(
constraint("uk_player_character").unique(PLAYER_CHARACTER.PLAYER_ID)
)
.execute()
}
override fun applyMigrations() {
if (database.getTableVersion(this) == null) {
database.setTableVersion(this, "1.3.0")
}
if (database.getTableVersion(this) == "0.1.0") {
database.setTableVersion(this, "0.1.1")
}
if (database.getTableVersion(this) == "0.1.1") {
database.setTableVersion(this, "0.1.2")
}
if (database.getTableVersion(this) == "0.1.2") {
database.create.alterTable(RPKIT_CHARACTER)
.addColumn(RPKIT_CHARACTER.PLAYER_HIDDEN, SQLDataType.TINYINT.length(1))
.execute()
database.create.alterTable(RPKIT_CHARACTER)
.addColumn(RPKIT_CHARACTER.NAME_HIDDEN, SQLDataType.TINYINT.length(1))
.execute()
database.create.alterTable(RPKIT_CHARACTER)
.addColumn(RPKIT_CHARACTER.GENDER_HIDDEN, SQLDataType.TINYINT.length(1))
.execute()
database.create.alterTable(RPKIT_CHARACTER)
.addColumn(RPKIT_CHARACTER.AGE_HIDDEN, SQLDataType.TINYINT.length(1))
.execute()
database.create.alterTable(RPKIT_CHARACTER)
.addColumn(RPKIT_CHARACTER.RACE_HIDDEN, SQLDataType.TINYINT.length(1))
.execute()
database.create.alterTable(RPKIT_CHARACTER)
.addColumn(RPKIT_CHARACTER.DESCRIPTION_HIDDEN, SQLDataType.TINYINT.length(1))
.execute()
database.setTableVersion(this, "0.4.0")
}
if (database.getTableVersion(this) == "0.4.0") {
database.create.alterTable(RPKIT_CHARACTER)
.addColumn(RPKIT_CHARACTER.PROFILE_ID, SQLDataType.INTEGER)
.execute()
database.create.alterTable(RPKIT_CHARACTER)
.addColumn(RPKIT_CHARACTER.MINECRAFT_PROFILE_ID, SQLDataType.INTEGER)
.execute()
database.create.alterTable(RPKIT_CHARACTER)
.addColumn(RPKIT_CHARACTER.PROFILE_HIDDEN, SQLDataType.TINYINT.length(1))
.execute()
database.setTableVersion(this, "1.3.0")
}
}
override fun insert(entity: RPKCharacter): Int {
database.create
.insertInto(
RPKIT_CHARACTER,
RPKIT_CHARACTER.PLAYER_ID,
RPKIT_CHARACTER.PROFILE_ID,
RPKIT_CHARACTER.MINECRAFT_PROFILE_ID,
RPKIT_CHARACTER.NAME,
RPKIT_CHARACTER.GENDER_ID,
RPKIT_CHARACTER.AGE,
RPKIT_CHARACTER.RACE_ID,
RPKIT_CHARACTER.DESCRIPTION,
RPKIT_CHARACTER.DEAD,
RPKIT_CHARACTER.WORLD,
RPKIT_CHARACTER.X,
RPKIT_CHARACTER.Y,
RPKIT_CHARACTER.Z,
RPKIT_CHARACTER.YAW,
RPKIT_CHARACTER.PITCH,
RPKIT_CHARACTER.INVENTORY_CONTENTS,
RPKIT_CHARACTER.HELMET,
RPKIT_CHARACTER.CHESTPLATE,
RPKIT_CHARACTER.LEGGINGS,
RPKIT_CHARACTER.BOOTS,
RPKIT_CHARACTER.HEALTH,
RPKIT_CHARACTER.MAX_HEALTH,
RPKIT_CHARACTER.MANA,
RPKIT_CHARACTER.MAX_MANA,
RPKIT_CHARACTER.FOOD_LEVEL,
RPKIT_CHARACTER.THIRST_LEVEL,
RPKIT_CHARACTER.PLAYER_HIDDEN,
RPKIT_CHARACTER.PROFILE_HIDDEN,
RPKIT_CHARACTER.NAME_HIDDEN,
RPKIT_CHARACTER.GENDER_HIDDEN,
RPKIT_CHARACTER.AGE_HIDDEN,
RPKIT_CHARACTER.RACE_HIDDEN,
RPKIT_CHARACTER.DESCRIPTION_HIDDEN
)
.values(
entity.player?.id,
entity.profile?.id,
entity.minecraftProfile?.id,
entity.name,
entity.gender?.id,
entity.age,
entity.race?.id,
entity.description,
entity.isDead,
entity.location.world?.name,
entity.location.x,
entity.location.y,
entity.location.z,
entity.location.yaw,
entity.location.pitch,
entity.inventoryContents.toByteArray(),
entity.helmet?.toByteArray(),
entity.chestplate?.toByteArray(),
entity.leggings?.toByteArray(),
entity.boots?.toByteArray(),
entity.health,
entity.maxHealth,
entity.mana,
entity.maxMana,
entity.foodLevel,
entity.thirstLevel,
entity.isPlayerHidden,
entity.isProfileHidden,
entity.isNameHidden,
entity.isGenderHidden,
entity.isAgeHidden,
entity.isRaceHidden,
entity.isDescriptionHidden
)
.execute()
val id = database.create.lastID().toInt()
entity.id = id
cache?.put(id, entity)
return id
}
override fun update(entity: RPKCharacter) {
database.create
.update(RPKIT_CHARACTER)
.set(RPKIT_CHARACTER.PLAYER_ID, entity.player?.id)
.set(RPKIT_CHARACTER.PROFILE_ID, entity.profile?.id)
.set(RPKIT_CHARACTER.MINECRAFT_PROFILE_ID, entity.minecraftProfile?.id)
.set(RPKIT_CHARACTER.NAME, entity.name)
.set(RPKIT_CHARACTER.GENDER_ID, entity.gender?.id)
.set(RPKIT_CHARACTER.AGE, entity.age)
.set(RPKIT_CHARACTER.RACE_ID, entity.race?.id)
.set(RPKIT_CHARACTER.DESCRIPTION, entity.description)
.set(RPKIT_CHARACTER.DEAD, if (entity.isDead) 1.toByte() else 0.toByte())
.set(RPKIT_CHARACTER.WORLD, entity.location.world?.name)
.set(RPKIT_CHARACTER.X, entity.location.x)
.set(RPKIT_CHARACTER.Y, entity.location.y)
.set(RPKIT_CHARACTER.Z, entity.location.z)
.set(RPKIT_CHARACTER.YAW, entity.location.yaw.toDouble())
.set(RPKIT_CHARACTER.PITCH, entity.location.pitch.toDouble())
.set(RPKIT_CHARACTER.INVENTORY_CONTENTS, entity.inventoryContents.toByteArray())
.set(RPKIT_CHARACTER.HELMET, entity.helmet?.toByteArray())
.set(RPKIT_CHARACTER.CHESTPLATE, entity.chestplate?.toByteArray())
.set(RPKIT_CHARACTER.LEGGINGS, entity.leggings?.toByteArray())
.set(RPKIT_CHARACTER.BOOTS, entity.boots?.toByteArray())
.set(RPKIT_CHARACTER.HEALTH, entity.health)
.set(RPKIT_CHARACTER.MAX_HEALTH, entity.maxHealth)
.set(RPKIT_CHARACTER.MANA, entity.mana)
.set(RPKIT_CHARACTER.MAX_MANA, entity.maxMana)
.set(RPKIT_CHARACTER.FOOD_LEVEL, entity.foodLevel)
.set(RPKIT_CHARACTER.THIRST_LEVEL, entity.thirstLevel)
.set(RPKIT_CHARACTER.PLAYER_HIDDEN, if (entity.isPlayerHidden) 1.toByte() else 0.toByte())
.set(RPKIT_CHARACTER.PROFILE_HIDDEN, if (entity.isProfileHidden) 1.toByte() else 0.toByte())
.set(RPKIT_CHARACTER.NAME_HIDDEN, if (entity.isNameHidden) 1.toByte() else 0.toByte())
.set(RPKIT_CHARACTER.GENDER_HIDDEN, if (entity.isGenderHidden) 1.toByte() else 0.toByte())
.set(RPKIT_CHARACTER.AGE_HIDDEN, if (entity.isAgeHidden) 1.toByte() else 0.toByte())
.set(RPKIT_CHARACTER.RACE_HIDDEN, if (entity.isRaceHidden) 1.toByte() else 0.toByte())
.set(RPKIT_CHARACTER.DESCRIPTION_HIDDEN, if (entity.isDescriptionHidden) 1.toByte() else 0.toByte())
.where(RPKIT_CHARACTER.ID.eq(entity.id))
.execute()
cache?.put(entity.id, entity)
}
override fun get(id: Int): RPKCharacter? {
if (cache?.containsKey(id) == true) {
return cache.get(id)
} else {
val result = database.create
.select(
RPKIT_CHARACTER.ID,
RPKIT_CHARACTER.PLAYER_ID,
RPKIT_CHARACTER.PROFILE_ID,
RPKIT_CHARACTER.MINECRAFT_PROFILE_ID,
RPKIT_CHARACTER.NAME,
RPKIT_CHARACTER.GENDER_ID,
RPKIT_CHARACTER.AGE,
RPKIT_CHARACTER.RACE_ID,
RPKIT_CHARACTER.DESCRIPTION,
RPKIT_CHARACTER.DEAD,
RPKIT_CHARACTER.WORLD,
RPKIT_CHARACTER.X,
RPKIT_CHARACTER.Y,
RPKIT_CHARACTER.Z,
RPKIT_CHARACTER.YAW,
RPKIT_CHARACTER.PITCH,
RPKIT_CHARACTER.INVENTORY_CONTENTS,
RPKIT_CHARACTER.HELMET,
RPKIT_CHARACTER.CHESTPLATE,
RPKIT_CHARACTER.LEGGINGS,
RPKIT_CHARACTER.BOOTS,
RPKIT_CHARACTER.HEALTH,
RPKIT_CHARACTER.MAX_HEALTH,
RPKIT_CHARACTER.MANA,
RPKIT_CHARACTER.MAX_MANA,
RPKIT_CHARACTER.FOOD_LEVEL,
RPKIT_CHARACTER.THIRST_LEVEL,
RPKIT_CHARACTER.PLAYER_HIDDEN,
RPKIT_CHARACTER.PROFILE_HIDDEN,
RPKIT_CHARACTER.NAME_HIDDEN,
RPKIT_CHARACTER.GENDER_HIDDEN,
RPKIT_CHARACTER.AGE_HIDDEN,
RPKIT_CHARACTER.RACE_HIDDEN,
RPKIT_CHARACTER.DESCRIPTION_HIDDEN
)
.from(RPKIT_CHARACTER)
.where(RPKIT_CHARACTER.ID.eq(id))
.fetchOne() ?: return null
val playerProvider = plugin.core.serviceManager.getServiceProvider(RPKPlayerProvider::class)
val profileProvider = plugin.core.serviceManager.getServiceProvider(RPKProfileProvider::class)
val minecraftProfileProvider = plugin.core.serviceManager.getServiceProvider(RPKMinecraftProfileProvider::class)
val genderProvider = plugin.core.serviceManager.getServiceProvider(RPKGenderProvider::class)
val raceProvider = plugin.core.serviceManager.getServiceProvider(RPKRaceProvider::class)
val playerId = result.get(RPKIT_CHARACTER.PLAYER_ID)
val player = if (playerId == null) null else playerProvider.getPlayer(playerId)
val profileId = result.get(RPKIT_CHARACTER.PROFILE_ID)
val profile = if (profileId == null) null else profileProvider.getProfile(profileId)
val minecraftProfileId = result.get(RPKIT_CHARACTER.MINECRAFT_PROFILE_ID)
val minecraftProfile = if (minecraftProfileId == null) null else minecraftProfileProvider.getMinecraftProfile(minecraftProfileId)
val genderId = result.get(RPKIT_CHARACTER.GENDER_ID)
val gender = if (genderId == null) null else genderProvider.getGender(genderId)
val raceId = result.get(RPKIT_CHARACTER.RACE_ID)
val race = if (raceId == null) null else raceProvider.getRace(raceId)
val helmetBytes = result.get(RPKIT_CHARACTER.HELMET)
val helmet = if (helmetBytes == null) null else itemStackFromByteArray(helmetBytes)
val chestplateBytes = result.get(RPKIT_CHARACTER.CHESTPLATE)
val chestplate = if (chestplateBytes == null) null else itemStackFromByteArray(chestplateBytes)
val leggingsBytes = result.get(RPKIT_CHARACTER.LEGGINGS)
val leggings = if (leggingsBytes == null) null else itemStackFromByteArray(leggingsBytes)
val bootsBytes = result.get(RPKIT_CHARACTER.BOOTS)
val boots = if (bootsBytes == null) null else itemStackFromByteArray(bootsBytes)
val character = RPKCharacterImpl(
plugin = plugin,
id = result.get(RPKIT_CHARACTER.ID),
player = player,
profile = profile,
minecraftProfile = minecraftProfile,
name = result.get(RPKIT_CHARACTER.NAME),
gender = gender,
age = result.get(RPKIT_CHARACTER.AGE),
race = race,
description = result.get(RPKIT_CHARACTER.DESCRIPTION),
dead = result.get(RPKIT_CHARACTER.DEAD) == 1.toByte(),
location = Location(
plugin.server.getWorld(result.get(RPKIT_CHARACTER.WORLD)),
result.get(RPKIT_CHARACTER.X),
result.get(RPKIT_CHARACTER.Y),
result.get(RPKIT_CHARACTER.Z),
result.get(RPKIT_CHARACTER.YAW).toFloat(),
result.get(RPKIT_CHARACTER.PITCH).toFloat()
),
inventoryContents = itemStackArrayFromByteArray(result.get(RPKIT_CHARACTER.INVENTORY_CONTENTS)),
helmet = helmet,
chestplate = chestplate,
leggings = leggings,
boots = boots,
health = result.get(RPKIT_CHARACTER.HEALTH),
maxHealth = result.get(RPKIT_CHARACTER.MAX_HEALTH),
mana = result.get(RPKIT_CHARACTER.MANA),
maxMana = result.get(RPKIT_CHARACTER.MAX_MANA),
foodLevel = result.get(RPKIT_CHARACTER.FOOD_LEVEL),
thirstLevel = result.get(RPKIT_CHARACTER.THIRST_LEVEL),
isPlayerHidden = result.get(RPKIT_CHARACTER.PLAYER_HIDDEN) == 1.toByte(),
isProfileHidden = result.get(RPKIT_CHARACTER.PROFILE_HIDDEN) == 1.toByte(),
isNameHidden = result.get(RPKIT_CHARACTER.NAME_HIDDEN) == 1.toByte(),
isGenderHidden = result.get(RPKIT_CHARACTER.GENDER_HIDDEN) == 1.toByte(),
isAgeHidden = result.get(RPKIT_CHARACTER.AGE_HIDDEN) == 1.toByte(),
isRaceHidden = result.get(RPKIT_CHARACTER.RACE_HIDDEN) == 1.toByte(),
isDescriptionHidden = result.get(RPKIT_CHARACTER.DESCRIPTION_HIDDEN) == 1.toByte()
)
cache?.put(id, character)
return character
}
}
fun getActive(player: RPKPlayer): RPKCharacter? {
val result = database.create
.select(PLAYER_CHARACTER.CHARACTER_ID)
.from(PLAYER_CHARACTER)
.where(PLAYER_CHARACTER.PLAYER_ID.eq(player.id))
.fetchOne() ?: return null
return get(result.get(PLAYER_CHARACTER.CHARACTER_ID))
}
fun get(player: RPKPlayer): List<RPKCharacter> {
val results = database.create
.select(RPKIT_CHARACTER.ID)
.from(RPKIT_CHARACTER)
.where(RPKIT_CHARACTER.PLAYER_ID.eq(player.id))
.fetch()
return results.map { result -> get(result.get(RPKIT_CHARACTER.ID)) }
.filterNotNull()
}
fun get(minecraftProfile: RPKMinecraftProfile): RPKCharacter? {
val result = database.create
.select(RPKIT_CHARACTER.ID)
.from(RPKIT_CHARACTER)
.where(RPKIT_CHARACTER.MINECRAFT_PROFILE_ID.eq(minecraftProfile.id))
.fetchOne() ?: return null
return get(result.get(RPKIT_CHARACTER.ID))
}
fun get(profile: RPKProfile): List<RPKCharacter> {
val results = database.create
.select(RPKIT_CHARACTER.ID)
.from(RPKIT_CHARACTER)
.where(RPKIT_CHARACTER.PROFILE_ID.eq(profile.id))
.fetch()
return results.map { result -> get(result.get(RPKIT_CHARACTER.ID)) }
.filterNotNull()
}
fun get(name: String): List<RPKCharacter> {
val results = database.create
.select(RPKIT_CHARACTER.ID)
.from(RPKIT_CHARACTER)
.where(RPKIT_CHARACTER.NAME.likeIgnoreCase("%$name%"))
.fetch()
return results.map { result -> get(result.get(RPKIT_CHARACTER.ID)) }
.filterNotNull()
}
override fun delete(entity: RPKCharacter) {
database.create
.deleteFrom(RPKIT_CHARACTER)
.where(RPKIT_CHARACTER.ID.eq(entity.id))
.execute()
cache?.remove(entity.id)
}
}
| apache-2.0 | 043600c6b0bfe4908c17307433370efc | 51.795455 | 141 | 0.572234 | 4.824507 | false | false | false | false |
google/intellij-gn-plugin | src/main/java/com/google/idea/gn/psi/builtin/Import.kt | 1 | 1379 | // Copyright (c) 2020 Google LLC All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package com.google.idea.gn.psi.builtin
import com.google.idea.gn.GnLabel
import com.google.idea.gn.GnLanguage
import com.google.idea.gn.completion.CompletionIdentifier
import com.google.idea.gn.psi.*
import com.google.idea.gn.psi.Function
import com.google.idea.gn.psi.scope.Scope
class Import : Function {
override fun execute(call: GnCall, targetScope: Scope): GnValue? {
val name = GnPsiUtil.evaluateFirstToString(call.exprList, targetScope) ?: return null
val label: GnLabel = GnLabel.parse(name) ?: return null
val file = GnPsiUtil.findPsiFile(call.containingFile, label)
if (file == null || GnLanguage != file.language) {
return null
}
file.accept(Visitor(targetScope))
return null
}
override val identifierType: CompletionIdentifier.IdentifierType
get() = CompletionIdentifier.IdentifierType.FUNCTION
override val isBuiltin: Boolean
get() = true
override val identifierName: String
get() = NAME
override val autoSuggestOnInsertion: Boolean
get() = true
override val postInsertType: CompletionIdentifier.PostInsertType?
get() = CompletionIdentifier.PostInsertType.CALL_WITH_STRING
companion object {
const val NAME = "import"
}
}
| bsd-3-clause | c5a8a751b2741b0831824e08e9ce41f7 | 30.340909 | 89 | 0.744017 | 4.055882 | false | false | false | false |
hazuki0x0/YuzuBrowser | module/ui/src/main/java/jp/hazuki/yuzubrowser/ui/widget/breadcrumbs/BreadcrumbItemDecoration.kt | 1 | 2315 | /*
* Copyright (C) 2017-2019 Hazuki
*
* 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 jp.hazuki.yuzubrowser.ui.widget.breadcrumbs
import android.content.Context
import android.graphics.Canvas
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import jp.hazuki.yuzubrowser.core.utility.extensions.convertDpToPx
import jp.hazuki.yuzubrowser.ui.R
class BreadcrumbItemDecoration(context: Context, color: Int) : RecyclerView.ItemDecoration() {
private val icon: Drawable = context.getDrawable(R.drawable.ic_chevron_right_white_24dp)!!
private val leftPadding = context.convertDpToPx(8)
init {
icon.setTint(color)
}
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
super.getItemOffsets(outRect, view, parent, state)
val pos = parent.getChildAdapterPosition(view)
outRect.left = if (pos != 0) {
icon.intrinsicWidth
} else {
leftPadding
}
}
override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
val padding = (parent.height - icon.intrinsicHeight) / 2
val arrowTop = parent.paddingTop + padding
val arrowBottom = arrowTop + icon.intrinsicHeight
val childCount = parent.childCount
for (i in 0 until childCount - 1) {
val child = parent.getChildAt(i)
val params = child.layoutParams as RecyclerView.LayoutParams
val arrowLeft = child.right + params.rightMargin
val arrowRight = arrowLeft + icon.intrinsicWidth
icon.setBounds(arrowLeft, arrowTop, arrowRight, arrowBottom)
icon.draw(c)
}
}
} | apache-2.0 | 39a2f4cc602cc17df104f625f6771739 | 34.090909 | 109 | 0.702808 | 4.417939 | false | false | false | false |
orgzly/orgzly-android | app/src/main/java/com/orgzly/android/ui/util/SystemActions.kt | 1 | 726 | @file:JvmName("SystemActions")
package com.orgzly.android.ui.util
import android.app.Activity
import android.content.ClipData
import android.content.Context
import android.content.Intent
fun Context.copyPlainTextToClipboard(label: CharSequence, text: CharSequence) {
getClipboardManager().let { clipboardManager ->
val clip = ClipData.newPlainText(label, text)
clipboardManager.setPrimaryClip(clip)
}
}
fun Activity.sharePlainText(text: CharSequence) {
val sendIntent = Intent().apply {
action = Intent.ACTION_SEND
putExtra(Intent.EXTRA_TEXT, text)
type = "text/plain"
}
val shareIntent = Intent.createChooser(sendIntent, null)
startActivity(shareIntent)
}
| gpl-3.0 | 1cfae1c411fc1650d0dfdf3e86f07d34 | 26.923077 | 79 | 0.731405 | 4.321429 | false | false | false | false |
SveTob/rabbit-puppy | src/main/java/com/meltwater/puppy/Main.kt | 1 | 3137 | package com.meltwater.puppy
import com.beust.jcommander.JCommander
import com.beust.jcommander.Parameter
import com.beust.jcommander.ParameterException
import com.meltwater.puppy.config.BindingData
import com.meltwater.puppy.config.ExchangeData
import com.meltwater.puppy.config.PermissionsData
import com.meltwater.puppy.config.QueueData
import com.meltwater.puppy.config.RabbitConfig
import com.meltwater.puppy.config.UserData
import com.meltwater.puppy.config.VHostData
import com.meltwater.puppy.config.reader.RabbitConfigException
import com.meltwater.puppy.config.reader.RabbitConfigReader
import com.meltwater.puppy.rest.RabbitRestClient
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.io.File
import java.io.IOException
import java.util.HashMap
class RabbitPuppyException(s: String, val errors: List<Throwable>) : Exception(s)
private val log = LoggerFactory.getLogger("Main")
private val rabbitConfigReader = RabbitConfigReader()
private class Arguments {
@Parameter(names = arrayOf("-h", "--help"), description = "Print help and exit", help = true)
public var help: Boolean = false
@Parameter(names = arrayOf("-c", "--config"), description = "YAML config file path", required = true)
public var configPath: String? = null
@Parameter(names = arrayOf("-b", "--broker"), description = "HTTP URL to broker", required = true)
public var broker: String? = null
@Parameter(names = arrayOf("-u", "--user"), description = "Username", required = true)
public var user: String? = null
@Parameter(names = arrayOf("-p", "--pass"), description = "Password", required = true)
public var pass: String? = null
@Parameter(names = arrayOf("-w", "--wait"), description = "Seconds to wait for broker to become available")
public var wait = 0
}
private fun parseArguments(programName: String, argv: Array<String>): Arguments {
val arguments = Arguments()
val jc = JCommander()
jc.addObject(arguments)
jc.setProgramName(programName)
try {
jc.parse(*argv)
if (arguments.help) {
jc.usage()
System.exit(1)
}
} catch (e: ParameterException) {
log.error(e.message)
jc.usage()
System.exit(1)
}
return arguments
}
fun main(argv: Array<String>) {
if (!run(argv)) {
System.exit(1)
}
}
public fun run(argv: Array<String>): Boolean {
val arguments = parseArguments("rabbit-puppy", argv)
log.info("Reading configuration from " + arguments.configPath!!)
try {
val rabbitConfig = rabbitConfigReader.read(File(arguments.configPath))
val rabbitPuppy = RabbitPuppy(arguments.broker!!, arguments.user!!, arguments.pass!!)
if (arguments.wait > 0) {
rabbitPuppy.waitForBroker(arguments.wait)
}
rabbitPuppy.apply(rabbitConfig)
return true
} catch (e: RabbitConfigException) {
log.error("Failed to read configuration, exiting")
return false
} catch (e: RabbitPuppyException) {
log.error("Encountered ${e.errors.size} errors, exiting")
return false
}
}
| mit | 969374a93f9a2ca15f65c6651d6423ce | 32.021053 | 111 | 0.694613 | 3.839657 | false | true | false | false |
foresterre/mal | kotlin/src/mal/step3_env.kt | 18 | 2760 | package mal
fun read(input: String?): MalType = read_str(input)
fun eval(ast: MalType, env: Env): MalType =
if (ast is MalList && ast.count() > 0) {
val first = ast.first()
if (first is MalSymbol && first.value == "def!") {
env.set(ast.nth(1) as MalSymbol, eval(ast.nth(2), env))
} else if (first is MalSymbol && first.value == "let*") {
val child = Env(env)
val bindings = ast.nth(1)
if (bindings !is ISeq) throw MalException("expected sequence as the first parameter to let*")
val it = bindings.seq().iterator()
while (it.hasNext()) {
val key = it.next()
if (!it.hasNext()) throw MalException("odd number of binding elements in let*")
val value = eval(it.next(), child)
child.set(key as MalSymbol, value)
}
eval(ast.nth(2), child)
} else {
val evaluated = eval_ast(ast, env) as ISeq
if (evaluated.first() !is MalFunction) throw MalException("cannot execute non-function")
(evaluated.first() as MalFunction).apply(evaluated.rest())
}
} else eval_ast(ast, env)
fun eval_ast(ast: MalType, env: Env): MalType =
when (ast) {
is MalSymbol -> env.get(ast)
is MalList -> ast.elements.fold(MalList(), { a, b -> a.conj_BANG(eval(b, env)); a })
is MalVector -> ast.elements.fold(MalVector(), { a, b -> a.conj_BANG(eval(b, env)); a })
is MalHashMap -> ast.elements.entries.fold(MalHashMap(), { a, b -> a.assoc_BANG(b.key, eval(b.value, env)); a })
else -> ast
}
fun print(result: MalType) = pr_str(result, print_readably = true)
fun main(args: Array<String>) {
val env = Env()
env.set(MalSymbol("+"), MalFunction({ a: ISeq -> a.seq().reduce({ x, y -> x as MalInteger + y as MalInteger }) }))
env.set(MalSymbol("-"), MalFunction({ a: ISeq -> a.seq().reduce({ x, y -> x as MalInteger - y as MalInteger }) }))
env.set(MalSymbol("*"), MalFunction({ a: ISeq -> a.seq().reduce({ x, y -> x as MalInteger * y as MalInteger }) }))
env.set(MalSymbol("/"), MalFunction({ a: ISeq -> a.seq().reduce({ x, y -> x as MalInteger / y as MalInteger }) }))
while (true) {
val input = readline("user> ")
try {
println(print(eval(read(input), env)))
} catch (e: EofException) {
break
} catch (e: MalContinue) {
} catch (e: MalException) {
println("Error: " + e.message)
} catch (t: Throwable) {
println("Uncaught " + t + ": " + t.message)
}
}
}
| mpl-2.0 | 2f74e294a122e2df5aebf9d5632f7550 | 44.245902 | 124 | 0.524275 | 3.801653 | false | false | false | false |
fluidsonic/jetpack-kotlin | Sources/GeoCoordinate.kt | 1 | 1231 | package com.github.fluidsonic.jetpack
public data class GeoCoordinate(
public val latitude: Double,
public val longitude: Double
) {
/**
* Computes the distance between two geo coordinates in meters.
* @param coordinate the other coordinate
* *
* @return the distance between this and the other geo coordinates in meters.
*/
public fun distanceTo(coordinate: GeoCoordinate): Double {
val sinHalfLatitudeDistance = Math.sin(Math.toRadians(coordinate.latitude - latitude) * 0.5)
val sinHalfLongitudeDistance = Math.sin(Math.toRadians(coordinate.longitude - longitude) * 0.5)
val a = sinHalfLatitudeDistance * sinHalfLatitudeDistance + Math.cos(Math.toRadians(latitude)) * Math.cos(Math.toRadians(coordinate.latitude)) * sinHalfLongitudeDistance * sinHalfLongitudeDistance
val b = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
return EARTH_RADIUS * b
}
public val isInNorthernHemisphere: Boolean
get() = latitude > 0.0
public val isInSouthernHemisphere: Boolean
get() = latitude < 0.0
public val isOnEquator: Boolean
get() = latitude == 0.0
public override fun toString()
= "$latitude,$longitude"
public companion object {
private val EARTH_RADIUS = 6378137.0 // in meters
}
}
| mit | 9a8e6cdcec4a630ba52e2c67e10480c2 | 26.355556 | 198 | 0.738424 | 3.620588 | false | false | false | false |
premnirmal/StockTicker | app/src/main/kotlin/com/github/premnirmal/ticker/repo/migrations/Migrations.kt | 1 | 4381 | package com.github.premnirmal.ticker.repo.migrations
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
/**
* Migration from version 1 of the database to version 2:
* Delete field 'description' in table QuoteRow.
* Add fields 'is_post_market,annual_dividend_rate,annual_dividend_yield' in table QuoteRow.
* Add table PropertiesRow.
*/
val MIGRATION_1_2 = object : Migration(1, 2) {
override fun migrate(database: SupportSQLiteDatabase) {
val TABLE_NAME = "QuoteRow"
val TABLE_NAME_TEMP = "new_QuoteRow"
// Create new QuoteRow table that will replace the table QuoteRow version 1.
database.execSQL(
"""
CREATE TABLE `${TABLE_NAME_TEMP}` (
symbol TEXT NOT NULL,
name TEXT NOT NULL,
last_trade_price REAL NOT NULL,
change_percent REAL NOT NULL,
change REAL NOT NULL,
exchange TEXT NOT NULL,
currency TEXT NOT NULL,
is_post_market INTEGER NOT NULL,
annual_dividend_rate REAL NOT NULL,
annual_dividend_yield REAL NOT NULL,
PRIMARY KEY(symbol)
)
""".trimIndent()
)
// Copy value from table QuoteRow version 1 to table QuoteRow version 2.
// Use default values is_post_market=0, annual_dividend_rate=0, annual_dividend_yield=0.
database.execSQL(
"""
INSERT INTO `${TABLE_NAME_TEMP}` (symbol, name, last_trade_price, change_percent, change, exchange, currency, is_post_market, annual_dividend_rate, annual_dividend_yield)
SELECT symbol, name, last_trade_price, change_percent, change, exchange, currency, 0, 0, 0 FROM `${TABLE_NAME}`
""".trimIndent()
)
// Remove table QuoteRow version 1.
database.execSQL("DROP TABLE `${TABLE_NAME}`")
// Rename table QuoteRow version 2 to be the new table QuoteRow.
database.execSQL("ALTER TABLE `${TABLE_NAME_TEMP}` RENAME TO `${TABLE_NAME}`")
// Add the new table PropertiesRow.
database.execSQL(
"CREATE TABLE IF NOT EXISTS `PropertiesRow` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `properties_quote_symbol` TEXT NOT NULL, `notes` TEXT NOT NULL, `alert_above` REAL NOT NULL, `alert_below` REAL NOT NULL)"
)
}
}
val MIGRATION_2_3 = object : Migration(2, 3) {
override fun migrate(database: SupportSQLiteDatabase) {
val tableName = "QuoteRow"
database.execSQL("ALTER TABLE `$tableName` ADD COLUMN `dayHigh` REAL;")
database.execSQL("ALTER TABLE `$tableName` ADD COLUMN `dayLow` REAL;")
database.execSQL("ALTER TABLE `$tableName` ADD COLUMN `previousClose` REAL NOT NULL DEFAULT 0.0;")
database.execSQL("ALTER TABLE `$tableName` ADD COLUMN `open` REAL;")
database.execSQL("ALTER TABLE `$tableName` ADD COLUMN `regularMarketVolume` REAL;")
database.execSQL("ALTER TABLE `$tableName` ADD COLUMN `peRatio` REAL;")
database.execSQL("ALTER TABLE `$tableName` ADD COLUMN `fiftyTwoWeekLowChange` REAL;")
database.execSQL("ALTER TABLE `$tableName` ADD COLUMN `fiftyTwoWeekLowChangePercent` REAL;")
database.execSQL("ALTER TABLE `$tableName` ADD COLUMN `fiftyTwoWeekHighChange` REAL;")
database.execSQL("ALTER TABLE `$tableName` ADD COLUMN `fiftyTwoWeekHighChangePercent` REAL;")
database.execSQL("ALTER TABLE `$tableName` ADD COLUMN `fiftyTwoWeekLow` REAL;")
database.execSQL("ALTER TABLE `$tableName` ADD COLUMN `fiftyTwoWeekHigh` REAL;")
database.execSQL("ALTER TABLE `$tableName` ADD COLUMN `dividendDate` REAL;")
database.execSQL("ALTER TABLE `$tableName` ADD COLUMN `earningsDate` REAL;")
database.execSQL("ALTER TABLE `$tableName` ADD COLUMN `marketCap` REAL;")
}
}
val MIGRATION_3_4 = object : Migration(3, 4) {
override fun migrate(database: SupportSQLiteDatabase) {
val tableName = "QuoteRow"
database.execSQL("ALTER TABLE `$tableName` ADD COLUMN `isTradeable` INTEGER;")
}
}
val MIGRATION_4_5 = object : Migration(4, 5) {
override fun migrate(database: SupportSQLiteDatabase) {
val tableName = "QuoteRow"
database.execSQL("ALTER TABLE `$tableName` ADD COLUMN `isTriggerable` INTEGER;")
}
}
val MIGRATION_5_6 = object : Migration(5, 6) {
override fun migrate(database: SupportSQLiteDatabase) {
val tableName = "QuoteRow"
database.execSQL("ALTER TABLE `$tableName` ADD COLUMN `marketState` TEXT;")
}
} | gpl-3.0 | e66e7f26c7a2dab800a76f8bf72dcdeb | 43.714286 | 215 | 0.687743 | 4.176358 | false | false | false | false |
NLPIE/BioMedICUS | nlpengine/src/main/kotlin/edu/umn/nlpengine/DistinctLabelIndex.kt | 1 | 17614 | /*
* Copyright (c) 2018 Regents of the University of Minnesota.
*
* 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 edu.umn.nlpengine
import java.util.*
import java.util.Collections.emptyList
import java.util.Collections.unmodifiableCollection
import kotlin.collections.AbstractList
inline fun <reified T: Label> DistinctLabelIndex(vararg labels: T): DistinctLabelIndex<T> {
return DistinctLabelIndex(T::class.java, *labels)
}
inline fun <reified T: Label> DistinctLabelIndex(
comparator: Comparator<T>,
vararg labels: T
) : DistinctLabelIndex<T> {
return DistinctLabelIndex(T::class.java, comparator, *labels)
}
inline fun <reified T: Label> DistinctLabelIndex(
labels: Iterable<T>
) : DistinctLabelIndex<T> {
return DistinctLabelIndex(T::class.java, labels)
}
inline fun <reified T: Label> DistinctLabelIndex(
comparator: Comparator<T>,
labels: Iterable<T>
) : DistinctLabelIndex<T> {
return DistinctLabelIndex(T::class.java, comparator, labels)
}
/**
* A label index where the labels are distinct i.e. non-overlapping.
*/
class DistinctLabelIndex<T : Label> internal constructor(
override val labelClass: Class<T>,
private val values: List<T>
) : LabelIndex<T>, Collection<T> by unmodifiableCollection(values) {
constructor(
labelClass: Class<T>,
vararg labels: T
) : this(labelClass, labels.sortedWith(Comparator { o1, o2 ->
o1.compareStart(o2)
}))
constructor(
labelClass: Class<T>,
comparator: Comparator<T>,
vararg labels: T
) : this(labelClass, labels.sortedWith(comparator))
constructor(
labelClass: Class<T>,
labels: Iterable<T>
) : this(labelClass, labels.sortedWith(Comparator { o1, o2 ->
o1.compareStart(o2)
}))
constructor(
labelClass: Class<T>,
comparator: Comparator<T>, labels: Iterable<T>
) : this(labelClass, labels.sortedWith(comparator))
override fun containing(startIndex: Int, endIndex: Int): LabelIndex<T> {
val index = containingIndex(startIndex, endIndex)
return AscendingView(left = index, right = index)
}
override fun inside(startIndex: Int, endIndex: Int): LabelIndex<T> =
AscendingView(minTextIndex = startIndex, maxTextIndex = endIndex)
override fun beginsInside(startIndex: Int, endIndex: Int): LabelIndex<T> =
AscendingView(
minTextIndex = startIndex,
right = lowerStart(endIndex)
)
override fun ascendingStartIndex() = this
override fun descendingStartIndex(): LabelIndex<T> = DescendingView()
override fun ascendingEndIndex() = this
override fun descendingEndIndex() = this
override fun toTheLeftOf(index: Int): LabelIndex<T> = AscendingView(maxTextIndex = index)
override fun toTheRightOf(index: Int): LabelIndex<T> = AscendingView(minTextIndex = index)
override fun first() = values.firstOrNull()
override fun last() = values.lastOrNull()
override fun atLocation(textRange: TextRange) = internalAtLocation(textRange)
override fun contains(element: @UnsafeVariance T) = internalIndexOf(element) != -1
override fun containsSpan(textRange: TextRange) = internalContainsLocation(textRange)
override fun asList() = object : List<T> by Collections.unmodifiableList(values) {
override fun indexOf(element: @UnsafeVariance T) = internalIndexOf(element)
override fun lastIndexOf(element: @UnsafeVariance T) = internalIndexOf(element)
override fun contains(element: @UnsafeVariance T) = internalIndexOf(element) != -1
override fun equals(other: Any?): Boolean {
return values == other as? List<*>
}
override fun hashCode(): Int {
return values.hashCode()
}
override fun toString(): String {
return values.toString()
}
}
internal fun containingIndex(
startIndex: Int,
endIndex: Int,
fromIndex: Int = 0,
toIndex: Int = size
): Int {
if (values.isEmpty()) {
return -1
}
var index = values.binarySearchBy(startIndex, fromIndex, toIndex) { it.startIndex }
if (index < 0) {
index = -1 * (index + 1) - 1
}
return if (index >= 0 && index < values.size && values[index].startIndex <= startIndex && values[index].endIndex >= endIndex) {
index
} else -1
}
internal fun internalAtLocation(
textRange: TextRange,
fromIndex: Int = 0,
toIndex: Int = values.size
): Collection<T> {
val index = values.binarySearch(textRange, Comparator { o1, o2 ->
o1.compareStart(o2)
}, fromIndex, toIndex)
return if (index >= 0 && values[index].endIndex == textRange.endIndex) {
listOf(values[index])
} else emptyList()
}
internal fun internalIndexOf(
element: @UnsafeVariance T,
fromIndex: Int = 0,
toIndex: Int = size
): Int {
val index = values.binarySearch(element, Comparator { o1, o2 ->
o1.compareStart(o2)
}, fromIndex, toIndex)
return if (index < 0 || values[index] != element) -1 else index
}
internal fun internalContainsLocation(
textRange: TextRange,
fromIndex: Int = 0,
toIndex: Int = size
): Boolean {
val index = values.binarySearch(textRange, Comparator { o1, o2 ->
o1.compareStart(o2)
}, fromIndex, toIndex)
return index >= 0 && values[index].endIndex == textRange.endIndex
}
/**
* Index of earliest label with a location after than the text index [index] or -1 if there is
* no such index
*/
internal fun higherIndex(
index: Int,
fromIndex: Int = 0,
toIndex: Int = size
): Int {
var i = values.binarySearchBy(index, fromIndex, toIndex) { it.startIndex }
if (i < 0) {
i = -1 * (i + 1)
if (i == toIndex) {
return -1
}
}
return i
}
/**
* Index of the last label with a location before than the text index [index] or -1 if there is
* no such index
*/
internal fun lowerIndex(
index: Int,
fromIndex: Int = 0,
toIndex: Int = size
): Int {
var i = values.binarySearchBy(index, fromIndex, toIndex) { it.endIndex }
if (i < 0) {
i = -1 * (i + 1)
if (i <= fromIndex) {
return -1
}
i--
}
return i
}
/**
* Returns the index of a label that starts before the index or -1 if there is no such index.
*/
internal fun lowerStart(
index: Int,
fromIndex: Int = 0,
toIndex: Int = size
) : Int {
var i = values.binarySearchBy(index - 1, fromIndex, toIndex) { it.startIndex }
if (i < 0) {
i = -1 * (i + 1)
if (i <= fromIndex) {
return -1
}
i--
}
return i
}
internal abstract inner class View(
left: Int,
right: Int
) : LabelIndex<T> {
override val labelClass get() = [email protected]
final override val size: Int
val left: Int
val right: Int
init {
if (left == -1 || right == -1 || right < left) {
this.left = 0
this.right = -1
} else {
this.left = left
this.right = right
}
size = this.right - this.left + 1
}
abstract val firstIndex: Int
abstract val lastIndex: Int
abstract fun updateEnds(newLeft: Int, newRight: Int): LabelIndex<T>
override fun isEmpty() = size == 0
override fun atLocation(textRange: TextRange) = internalAtLocation(textRange, left, right + 1)
override fun contains(element: @UnsafeVariance T) =
internalIndexOf(element, left, right + 1) != -1
override fun containsAll(elements: Collection<@UnsafeVariance T>) =
elements.all { contains(it) }
override fun containsSpan(textRange: TextRange) =
internalContainsLocation(textRange, left, right + 1)
override fun toTheLeftOf(index: Int) = updateBounds(maxTextIndex = index)
override fun toTheRightOf(index: Int) = updateBounds(minTextIndex = index)
override fun inside(startIndex: Int, endIndex: Int) = updateBounds(
minTextIndex = startIndex,
maxTextIndex = endIndex
)
override fun beginsInside(startIndex: Int, endIndex: Int): LabelIndex<T> {
return updateEnds(higherIndex(startIndex, left, right + 1), lowerStart(endIndex, left, right + 1))
}
override fun first(): T? {
if (firstIndex in 0 until values.size && firstIndex <= right && firstIndex >= left) {
return values[firstIndex]
}
return null
}
override fun last(): T? {
if (lastIndex in 0 until values.size && lastIndex >= left && lastIndex <= right) {
return values[lastIndex]
}
return null
}
override fun containing(startIndex: Int, endIndex: Int): LabelIndex<T> {
val index = containingIndex(startIndex, endIndex, left, right + 1)
return if (index != -1) updateEnds(index, index) else updateEnds(0, -1)
}
internal fun inBounds(index: Int) = index in left..right
internal fun updateBounds(
minTextIndex: Int? = null,
maxTextIndex: Int? = null
): LabelIndex<T> {
val newLeft = if (minTextIndex != null) {
higherIndex(minTextIndex, left, right + 1)
} else left
val newRight = if (maxTextIndex != null) {
lowerIndex(maxTextIndex, left, right + 1)
} else right
if (newLeft == -1) {
return updateEnds(0, -1)
}
return updateEnds(maxOf(left, newLeft), minOf(right, newRight))
}
}
internal inner class AscendingView(
minTextIndex: Int = 0,
maxTextIndex: Int = Int.MAX_VALUE,
left: Int = higherIndex(minTextIndex),
right: Int = lowerIndex(maxTextIndex)
) : View(left, right) {
override val firstIndex = this.left
override val lastIndex = this.right
override fun updateEnds(newLeft: Int, newRight: Int): LabelIndex<T> {
if (newLeft == -1) {
return AscendingView(0, -1)
}
return AscendingView(left = newLeft, right = newRight)
}
override fun descendingEndIndex() = this
override fun descendingStartIndex() = DescendingView(left = left, right = right)
override fun ascendingStartIndex() = this
override fun ascendingEndIndex() = this
override fun iterator() = AscendingListIterator(0)
override fun asList(): List<T> = object: AbstractList<T>() {
override val size = [email protected]
override fun isEmpty() = size == 0
override fun contains(element: @UnsafeVariance T) =
internalIndexOf(element, left, right + 1) != -1
override fun containsAll(elements: Collection<@UnsafeVariance T>) =
elements.all { contains(it) }
override fun lastIndexOf(element: @UnsafeVariance T) = indexOf(element)
override fun iterator(): Iterator<T> = listIterator()
override fun listIterator() = listIterator(0)
override fun listIterator(index: Int) = AscendingListIterator(index)
override fun get(index: Int): T {
if (index !in 0 until size) {
throw IndexOutOfBoundsException("$index is not in bounds 0:$size")
}
return values[firstIndex + index]
}
override fun indexOf(element: @UnsafeVariance T): Int {
val index = internalIndexOf(element, left, right + 1)
if (index == -1) return -1
return index - left
}
override fun subList(fromIndex: Int, toIndex: Int): List<T> {
if (fromIndex !in 0..size || toIndex !in 0..size || toIndex < fromIndex) {
throw IllegalArgumentException("Invalid range: from=$fromIndex to=$toIndex")
}
return AscendingView(left = left + fromIndex, right = left + toIndex - 1).asList()
}
}
internal inner class AscendingListIterator(index: Int) : ListIterator<T> {
var index: Int = left + index
val localIndex get() = index - left
override fun hasNext() = index <= right
override fun hasPrevious() = index > left
override fun nextIndex() = localIndex
override fun previousIndex() = localIndex - 1
override fun next(): T {
if (!hasNext()) {
throw NoSuchElementException()
}
return values[index++]
}
override fun previous(): T {
if (!hasPrevious()) {
throw NoSuchElementException()
}
return values[--index]
}
}
}
internal inner class DescendingView(
minTextIndex: Int = 0,
maxTextIndex: Int = Int.MAX_VALUE,
left: Int = higherIndex(minTextIndex),
right: Int = lowerIndex(maxTextIndex)
) : View(left, right) {
override val firstIndex = right
override val lastIndex = left
override fun ascendingStartIndex() = AscendingView(left = left, right = right)
override fun descendingStartIndex() = this
override fun ascendingEndIndex() = this
override fun descendingEndIndex() = this
override fun updateEnds(newLeft: Int, newRight: Int): View {
if (newLeft == -1) {
return DescendingView(0, -1)
}
return DescendingView(left = newLeft, right = newRight)
}
override fun iterator() = DescendingListIterator(0)
override fun asList(): List<T> = object: List<T> {
override val size = [email protected]
override fun isEmpty() = size == 0
override fun contains(element: @UnsafeVariance T) =
internalIndexOf(element, left, right + 1) != -1
override fun containsAll(elements: Collection<@UnsafeVariance T>) =
elements.all { contains(it) }
override fun lastIndexOf(element: @UnsafeVariance T) = indexOf(element)
override fun iterator() = listIterator()
override fun listIterator() = listIterator(0)
override fun listIterator(index: Int) = DescendingListIterator(index)
override fun get(index: Int): T {
if (index !in 0 until size) {
throw IndexOutOfBoundsException("$index is not in bounds")
}
return values[right - index]
}
override fun indexOf(element: @UnsafeVariance T): Int {
val index = internalIndexOf(element, left, right + 1)
if (index == -1) return -1
return right - index
}
override fun subList(fromIndex: Int, toIndex: Int): List<T> {
if (fromIndex !in 0..size || toIndex !in 0..size || toIndex < fromIndex) {
throw IllegalArgumentException("Invalid range: from=$fromIndex to=$toIndex")
}
return DescendingView(left = right - toIndex + 1, right = right - fromIndex)
.asList()
}
}
internal inner class DescendingListIterator(index: Int) : ListIterator<T> {
var index: Int = right - index
val localIndex get() = right - index
override fun hasNext() = index >= left
override fun hasPrevious() = index < right
override fun nextIndex() = localIndex
override fun previousIndex() = localIndex - 1
override fun next(): T {
if (!hasNext()) {
throw NoSuchElementException()
}
return values[index--]
}
override fun previous(): T {
if (!hasPrevious()) {
throw NoSuchElementException()
}
return values[++index]
}
}
}
}
| apache-2.0 | c94dc88b9368072292fcf18a313c99d8 | 30.62298 | 135 | 0.567503 | 4.668434 | false | false | false | false |
nickthecoder/tickle | tickle-core/src/main/kotlin/uk/co/nickthecoder/tickle/action/animation/Scale.kt | 1 | 1643 | /*
Tickle
Copyright (C) 2017 Nick Robinson
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.nickthecoder.tickle.action.animation
import org.joml.Vector2d
import uk.co.nickthecoder.tickle.Actor
class Scale(
val actor: Actor,
seconds: Double,
val finalScale: Vector2d,
ease: Ease = LinearEase.instance)
: AnimationAction(seconds, ease) {
constructor(actor: Actor, seconds: Double, finalScale: Vector2d) : this(actor, seconds, finalScale, LinearEase.instance)
constructor(actor: Actor, seconds: Double, finalScale: Double, ease: Ease = LinearEase.instance)
: this(actor, seconds = seconds, finalScale = Vector2d(finalScale, finalScale), ease = ease)
constructor(actor: Actor, seconds: Double, finalScale: Double) : this(actor, seconds, finalScale, LinearEase.instance)
private var initialScale = Vector2d()
override fun storeInitialValue() {
initialScale.set(actor.scale)
}
override fun update(t: Double) {
lerp(initialScale, finalScale, t, actor.scale)
}
}
| gpl-3.0 | f3e91b78ccdfe09fc0300d7085bdbef0 | 32.530612 | 124 | 0.732806 | 4.087065 | false | false | false | false |
square/kotlinpoet | interop/kotlinx-metadata/src/main/kotlin/com/squareup/kotlinpoet/metadata/specs/MethodData.kt | 1 | 3423 | /*
* Copyright (C) 2021 Square, 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.kotlinpoet.metadata.specs
import com.squareup.kotlinpoet.AnnotationSpec
import com.squareup.kotlinpoet.AnnotationSpec.UseSiteTarget
import com.squareup.kotlinpoet.TypeName
import com.squareup.kotlinpoet.metadata.KotlinPoetMetadataPreview
import com.squareup.kotlinpoet.metadata.classinspectors.ClassInspectorUtil
/**
* Represents relevant information on a method used for [ClassInspector]. Should only be
* associated with methods of a [ClassData] or [PropertyData].
*
* @param annotations declared annotations on this method.
* @property parameterAnnotations a mapping of parameter indices to annotations on them.
* @property isSynthetic indicates if this method is synthetic or not.
* @property jvmModifiers set of [JvmMethodModifiers][JvmMethodModifier] on this method.
* @property isOverride indicates if this method overrides one in a supertype.
* @property exceptions list of exceptions thrown by this method.
*/
@KotlinPoetMetadataPreview
public data class MethodData(
private val annotations: List<AnnotationSpec>,
val parameterAnnotations: Map<Int, Collection<AnnotationSpec>>,
val isSynthetic: Boolean,
val jvmModifiers: Set<JvmMethodModifier>,
val isOverride: Boolean,
val exceptions: List<TypeName>,
) {
/**
* A collection of all annotations on this method, including any derived from [jvmModifiers],
* [isSynthetic], and [exceptions].
*
* @param useSiteTarget an optional [UseSiteTarget] that all annotations on this method should
* use.
* @param containsReifiedTypeParameter an optional boolean indicating if any type parameters on
* this function are `reified`, which are implicitly synthetic.
*/
public fun allAnnotations(
useSiteTarget: UseSiteTarget? = null,
containsReifiedTypeParameter: Boolean = false,
): Collection<AnnotationSpec> {
return ClassInspectorUtil.createAnnotations(
useSiteTarget,
) {
addAll(annotations)
if (isSynthetic && !containsReifiedTypeParameter) {
add(ClassInspectorUtil.JVM_SYNTHETIC_SPEC)
}
addAll(jvmModifiers.mapNotNull(JvmMethodModifier::annotationSpec))
exceptions.takeIf { it.isNotEmpty() }
?.let {
add(ClassInspectorUtil.createThrowsSpec(it, useSiteTarget))
}
}
}
public companion object {
public val SYNTHETIC: MethodData = MethodData(
annotations = emptyList(),
parameterAnnotations = emptyMap(),
isSynthetic = true,
jvmModifiers = emptySet(),
isOverride = false,
exceptions = emptyList(),
)
public val EMPTY: MethodData = MethodData(
annotations = emptyList(),
parameterAnnotations = emptyMap(),
isSynthetic = false,
jvmModifiers = emptySet(),
isOverride = false,
exceptions = emptyList(),
)
}
}
| apache-2.0 | 00e76f136282a08b89ccbcc7f8ece095 | 36.615385 | 97 | 0.732398 | 4.821127 | false | false | false | false |
oakkub/pin-edittext | pin-edittext/src/main/java/com/oakkub/android/PinEditText.kt | 1 | 7154 | package com.oakkub.android
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.support.v4.content.ContextCompat
import android.support.v7.widget.AppCompatEditText
import android.util.AttributeSet
import android.view.ActionMode
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.TextView
/**
* Created by oakkub on 8/24/2017 AD.
*/
class PinEditText : AppCompatEditText {
private lateinit var pinPainter: PinPainter
private var onClickListener: View.OnClickListener? = null
private var onEditorActionListener: TextView.OnEditorActionListener? = null
constructor(context: Context) : super(context) {
init(null, 0)
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
init(attrs, 0)
}
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
init(attrs, defStyleAttr)
}
override fun onFocusChanged(focused: Boolean, direction: Int, previouslyFocusedRect: Rect?) {
super.onFocusChanged(focused, direction, previouslyFocusedRect)
if (focused) {
setSelection(text.length)
}
}
override fun setOnClickListener(onClickListener: View.OnClickListener?) {
this.onClickListener = onClickListener
}
override fun setOnEditorActionListener(onEditorActionListener: TextView.OnEditorActionListener) {
this.onEditorActionListener = onEditorActionListener
}
/** This is a replacement method for the base TextView class' method of the same name. This
* method is used in hidden class android.widget.Editor to determine whether the PASTE/REPLACE popup
* appears when triggered from the text insertion handle. Returning false forces this window
* to never appear.
* This function is privately use by the EditText so we have to create a function with the same name
* @return false
*/
fun canPaste(): Boolean = false
/** This is a replacement method for the base TextView class' method of the same name. This method
* is used in hidden class android.widget.Editor to determine whether the PASTE/REPLACE popup
* appears when triggered from the text insertion handle. Returning false forces this window
* to never appear.
* @return false
*/
override fun isSuggestionsEnabled(): Boolean = false
@SuppressLint("DrawAllocation")
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
val (newWidthMeasureSpec, newHeightMeasureSpec) = pinPainter.getCalculatedMeasureSpecSize()
setMeasuredDimension(newWidthMeasureSpec, newHeightMeasureSpec)
}
override fun onDraw(canvas: Canvas) {
pinPainter.draw(canvas)
}
private fun init(attrs: AttributeSet?, defStyleAttr: Int) {
isCursorVisible = false
isLongClickable = false
customSelectionActionModeCallback = ActionModeCallbackInterceptor()
maxLines = DEFAULT_PIN_MAX_LINES
setBackgroundColor(Color.TRANSPARENT)
initClickListener()
initOnEditorActionListener()
var normalStateDrawable: Drawable? = ContextCompat.getDrawable(context, R.drawable.pin_default_normal_state)
var highlightStateDrawable: Drawable? = ContextCompat.getDrawable(context, R.drawable.pin_default_highlight_state)
var pinWidth = context.dpToPx(DEFAULT_PIN_WIDTH)
var pinHeight = context.dpToPx(DEFAULT_PIN_HEIGHT)
var pinTotal = DEFAULT_PIN_TOTAL
var pinSpace = context.dpToPx(DEFAULT_PIN_SPACE)
if (attrs != null) {
val typedArray = context.obtainStyledAttributes(attrs, R.styleable.PinEditText, defStyleAttr, 0)
try {
pinTotal = getTextViewMaxLength(attrs, pinTotal)
pinWidth = typedArray.getDimension(R.styleable.PinEditText_pinWidth, pinWidth)
pinHeight = typedArray.getDimension(R.styleable.PinEditText_pinHeight, pinHeight)
pinSpace = typedArray.getDimension(R.styleable.PinEditText_pinSpace, pinSpace)
typedArray.getDrawable(R.styleable.PinEditText_pinNormalStateDrawable)?.let {
normalStateDrawable = it
}
typedArray.getDrawable(R.styleable.PinEditText_pinHighlightStateDrawable)?.let {
highlightStateDrawable = it
}
} finally {
typedArray.recycle()
}
}
require(normalStateDrawable != null) {
"normalStateDrawable must not be null"
}
require(highlightStateDrawable != null) {
"highlightStateDrawable must not be null"
}
pinPainter = PinPainter(
normalStateDrawable!!,
highlightStateDrawable!!,
this,
pinWidth,
pinHeight,
pinTotal,
pinSpace)
}
private fun initClickListener() {
super.setOnClickListener { view ->
// Force the cursor to the end every time we click at this EditText
setSelection(text.length)
onClickListener?.onClick(view)
}
}
private fun initOnEditorActionListener() {
super.setOnEditorActionListener { view, actionId, event ->
// For some reasons the soft keyboard does not response when tap :(
// But after set OnEditorActionListener it works :)
onEditorActionListener?.onEditorAction(view, actionId, event) ?: false
}
}
private fun getTextViewMaxLength(attrs: AttributeSet, defaultMaxLength: Int): Int {
return attrs.getAttributeIntValue(XML_NAMESPACE_ANDROID, "maxLength", defaultMaxLength)
}
private fun Context.dpToPx(dp: Int) = dp * resources.displayMetrics.density
/**
* Prevents the action bar (top horizontal bar with cut, copy, paste, etc.) from appearing
* by intercepting the callback that would cause it to be created, and returning false.
*/
private class ActionModeCallbackInterceptor : ActionMode.Callback {
override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean = false
override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean = false
override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean = false
override fun onDestroyActionMode(mode: ActionMode) {}
}
companion object {
/**
* android: namespace
*/
private const val XML_NAMESPACE_ANDROID = "http://schemas.android.com/apk/res/android"
private const val DEFAULT_PIN_WIDTH = 24
private const val DEFAULT_PIN_HEIGHT = 24
private const val DEFAULT_PIN_TOTAL = 4
private const val DEFAULT_PIN_SPACE = 16
private const val DEFAULT_PIN_MAX_LINES = 1
}
}
| apache-2.0 | cb29b99cf641e1b40a37138bd3117cb2 | 36.652632 | 122 | 0.681996 | 5.038028 | false | false | false | false |
sakuna63/requery | requery-android/example-kotlin/src/main/kotlin/io/requery/android/example/app/PeopleActivity.kt | 1 | 4636 | package io.requery.android.example.app
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.RecyclerView.ViewHolder
import android.view.*
import android.widget.ImageView
import android.widget.TextView
import io.requery.Persistable
import io.requery.android.QueryRecyclerAdapter
import io.requery.android.example.app.model.Models
import io.requery.android.example.app.model.Person
import io.requery.android.example.app.model.PersonEntity
import io.requery.kotlin.lower
import io.requery.query.Result
import io.requery.sql.KotlinEntityDataStore
import rx.Observable
import rx.schedulers.Schedulers
import java.util.*
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
/**
* Activity displaying a list of random people. You can tap on a person to edit their record.
* Shows how to use a query with a [RecyclerView] and [QueryRecyclerAdapter] and RxJava
*/
class PeopleActivity : AppCompatActivity() {
private lateinit var data: KotlinEntityDataStore<Persistable>
private lateinit var executor: ExecutorService
private lateinit var adapter: PersonAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
supportActionBar?.title = "People"
setContentView(R.layout.activity_people)
val recyclerView = findViewById(R.id.recyclerView) as RecyclerView
data = (application as PeopleApplication).data
executor = Executors.newSingleThreadExecutor()
adapter = PersonAdapter()
adapter.setExecutor(executor)
recyclerView.adapter = adapter
recyclerView.layoutManager = LinearLayoutManager(this)
data.count(Person::class).get().toSingle().subscribe { integer ->
if (integer === 0) {
Observable.fromCallable(CreatePeople(data))
.flatMap { o -> o }
.observeOn(Schedulers.computation())
.subscribe({ adapter.queryAsync() })
}
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_plus -> {
val intent = Intent(this, PersonEditActivity::class.java)
startActivity(intent)
return true
}
}
return false
}
override fun onResume() {
adapter.queryAsync()
super.onResume()
}
override fun onDestroy() {
executor.shutdown()
adapter.close()
super.onDestroy()
}
internal inner class PersonHolder(itemView: View) : ViewHolder(itemView) {
var image : ImageView? = null
var name : TextView? = null
}
private inner class PersonAdapter internal constructor() :
QueryRecyclerAdapter<Person, PersonHolder>(Models.DEFAULT, Person::class.java),
View.OnClickListener {
private val random = Random()
private val colors = intArrayOf(Color.RED, Color.BLUE, Color.GREEN, Color.MAGENTA)
override fun performQuery(): Result<Person> {
return ( data select(Person::class) orderBy Person::name.lower() ).get()
}
override fun onBindViewHolder(item: Person, holder: PersonHolder, position: Int) {
holder.name!!.text = item.name
holder.image!!.setBackgroundColor(colors[random.nextInt(colors.size)])
holder.itemView.tag = item
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PersonHolder {
val inflater = LayoutInflater.from(parent.context)
val view = inflater.inflate(R.layout.person_item, null)
val holder = PersonHolder(view)
holder.name = view.findViewById(R.id.name) as TextView
holder.image = view.findViewById(R.id.picture) as ImageView
view.setOnClickListener(this)
return holder
}
override fun onClick(v: View) {
val person = v.tag as PersonEntity?
if (person != null) {
val intent = Intent(this@PeopleActivity, PersonEditActivity::class.java)
intent.putExtra(PersonEditActivity.Companion.EXTRA_PERSON_ID, person.id)
startActivity(intent)
}
}
}
}
| apache-2.0 | 65a9e5babff2c52758692cdefc3f03b5 | 35.503937 | 93 | 0.666954 | 4.759754 | false | false | false | false |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/tables/SpicyStacktraces.kt | 1 | 756 | package net.perfectdreams.loritta.morenitta.tables
import org.jetbrains.exposed.dao.id.LongIdTable
object SpicyStacktraces : LongIdTable() {
val message = text("message").index()
val spicyHash = text("spicy_hash").nullable().index()
val file = text("file")
val line = integer("line")
val column = integer("column")
val userAgent = text("user_agent").nullable()
val url = text("url")
val spicyPath = text("spicy_path").nullable()
val localeId = text("locale_id")
val isLocaleInitialized = bool("is_locale_initialized")
val userId = long("user").nullable().index()
val currentRoute = text("current_route").nullable()
val stack = text("stack").nullable()
val receivedAt = long("received_at").index()
} | agpl-3.0 | 858ce452da19799bc37b6c4555181ea6 | 36.85 | 59 | 0.675926 | 3.857143 | false | false | false | false |
DVT/showcase-android | app/src/main/kotlin/za/co/dvt/android/showcase/ui/MainNavigationActivity.kt | 1 | 2688 | package za.co.dvt.android.showcase.ui
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.PersistableBundle
import android.support.design.widget.BottomNavigationView
import android.support.v4.app.Fragment
import android.support.v7.app.AppCompatActivity
import android.view.MenuItem
import android.widget.FrameLayout
import za.co.dvt.android.showcase.R
import za.co.dvt.android.showcase.ui.about.AboutFragment
import za.co.dvt.android.showcase.ui.contact.ContactUsFragment
import za.co.dvt.android.showcase.ui.listapps.ListAppsFragment
class MainNavigationActivity : AppCompatActivity() {
private var frameLayout: FrameLayout? = null
private val onNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item: MenuItem ->
when (item.itemId) {
R.id.navigation_home -> {
showScreen(ListAppsFragment.newInstance())
true
}
R.id.navigation_about -> {
showScreen(AboutFragment.newInstance())
true
}
R.id.navigation_contact -> {
showScreen(ContactUsFragment.newInstance())
true
}
else -> false
}
}
private var selectedItem: Int = 0
private lateinit var navigationView: BottomNavigationView
private val SELECTED_FRAGMENT_BUNDLE = "selected_fragment"
override fun onSaveInstanceState(outState: Bundle?, outPersistentState: PersistableBundle?) {
super.onSaveInstanceState(outState, outPersistentState)
selectedItem = navigationView.selectedItemId
outState?.putInt(SELECTED_FRAGMENT_BUNDLE, selectedItem)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main_navigation)
frameLayout = findViewById(R.id.fragment_content)
navigationView = findViewById<BottomNavigationView>(R.id.navigation)
navigationView.setOnNavigationItemSelectedListener(onNavigationItemSelectedListener)
selectedItem = savedInstanceState?.getInt(SELECTED_FRAGMENT_BUNDLE) ?: R.id.navigation_home
navigationView.selectedItemId = selectedItem
}
fun showScreen(fragment: Fragment) {
val fragmentTransaction = supportFragmentManager.beginTransaction()
fragmentTransaction.replace(R.id.fragment_content, fragment)
fragmentTransaction.commit()
}
companion object {
fun createIntent(context: Context): Intent {
return Intent(context, MainNavigationActivity::class.java)
}
}
}
| apache-2.0 | f4a1de16a1de770d0a328b48eabee550 | 33.461538 | 124 | 0.710938 | 5.179191 | false | false | false | false |
ericberman/MyFlightbookAndroid | app/src/main/java/model/GPX.kt | 1 | 6172 | /*
MyFlightbook for Android - provides native access to MyFlightbook
pilot's logbook
Copyright (C) 2017-2022 MyFlightbook, LLC
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package model
import android.content.Context
import android.net.Uri
import org.xmlpull.v1.XmlPullParser
import org.xmlpull.v1.XmlPullParserException
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.*
/**
* Created by ericberman on 11/30/17.
*
* Concrete telemetry class that can read/write GPX
*/
class GPX internal constructor(uri: Uri?, c: Context?) : Telemetry(uri, c) {
private fun readTrkPoint(parser: XmlPullParser): LocSample {
val szLat = parser.getAttributeValue(null, "lat")
val szLon = parser.getAttributeValue(null, "lon")
return LocSample(szLat.toDouble(), szLon.toDouble(), 0, 0.0, 1.0, "")
}
private fun readMetaName(parser: XmlPullParser) {
val szTail = parser.getAttributeValue(null, TELEMETRY_METADATA_TAIL)
if (szTail != null && metaData != null) metaData!![TELEMETRY_METADATA_TAIL] = szTail
}
@Throws(IOException::class, XmlPullParserException::class)
private fun readEle(sample: LocSample?, parser: XmlPullParser) {
if (sample == null) return
sample.altitude = (readText(parser).toDouble() * MFBConstants.METERS_TO_FEET).toInt()
}
@Throws(IOException::class, XmlPullParserException::class)
private fun readTime(sample: LocSample?, parser: XmlPullParser) {
if (sample == null) return
sample.timeStamp = parseUTCDate(readText(parser))
}
@Throws(IOException::class, XmlPullParserException::class)
private fun readSpeed(sample: LocSample?, parser: XmlPullParser) {
if (sample == null) return
sample.speed = readText(parser).toDouble() * MFBConstants.MPS_TO_KNOTS
}
@Throws(IOException::class, XmlPullParserException::class)
private fun readBadElfSpeed(sample: LocSample?, parser: XmlPullParser) {
if (sample == null) return
sample.speed = readText(parser).toDouble() * MFBConstants.MPS_TO_KNOTS
}
public override fun readFeed(parser: XmlPullParser?): Array<LocSample> {
if (parser == null)
return arrayOf()
val lst = ArrayList<LocSample>()
var sample: LocSample? = null
try {
while (parser.next() != XmlPullParser.END_DOCUMENT) {
try {
val eventType = parser.eventType
if (eventType == XmlPullParser.START_TAG) {
when (parser.name) {
"trkpt" -> sample = readTrkPoint(parser)
"ele" -> readEle(sample, parser)
"time" -> readTime(sample, parser)
"speed" -> readSpeed(sample, parser)
"badelf:speed" -> readBadElfSpeed(sample, parser)
"name" -> readMetaName(parser)
}
} else if (eventType == XmlPullParser.END_TAG) {
if (parser.name == "trkpt") {
lst.add(sample!!)
sample = null
}
}
} catch (e: XmlPullParserException) {
e.printStackTrace()
}
}
} catch (e: XmlPullParserException) {
e.printStackTrace()
} catch (e: IOException) {
e.printStackTrace()
}
return lst.toTypedArray()
}
companion object {
fun getFlightDataStringAsGPX(rgloc: Array<LatLong>): String {
val sdf = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.getDefault())
sdf.timeZone = TimeZone.getTimeZone("UTC")
val sb = StringBuilder()
// Hack - this is brute force writing, not proper generation of XML. But it works...
// We are also assuming valid timestamps (i.e., we're using gx:Track)
sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n")
sb.append("<gpx creator=\"http://myflightbook.com\" version=\"1.1\" xmlns=\"http://www.topografix.com/GPX/1/1\">\n")
sb.append("<trk>\r\n<name />\r\n<trkseg>\r\n")
val fIsLocSample = rgloc.isNotEmpty() && rgloc[0] is LocSample
for (ll in rgloc) {
sb.append(
String.format(
Locale.US,
"<trkpt lat=\"%.8f\" lon=\"%.8f\">\r\n",
ll.latitude,
ll.longitude
)
)
if (fIsLocSample) {
val ls = ll as LocSample
sb.append(
String.format(
Locale.US,
"<ele>%.8f</ele>\r\n",
ls.altitude / MFBConstants.METERS_TO_FEET
)
)
sb.append(
String.format(
Locale.US,
"<time>%s</time>\r\n",
sdf.format(ls.timeStamp)
)
)
sb.append(String.format(Locale.US, "<speed>%.8f</speed>\r\n", ls.speed))
}
sb.append("</trkpt>\r\n")
}
sb.append("</trkseg></trk></gpx>")
return sb.toString()
}
}
} | gpl-3.0 | 5f2289bca1dca3152abd0ced0773b969 | 40.153333 | 128 | 0.545042 | 4.495266 | false | false | false | false |
vincentvalenlee/XCRM | src/main/kotlin/org/rocfish/dao/OptionTargetFactory.kt | 1 | 566 | package org.rocfish.dao
import kotlin.reflect.KClass
/**
* 获取选项目标的工厂
*/
interface OptionTargetFactory {
companion object {
const val SORT_FIELD_OPTION = "SORT"
const val LIMT_FILED_OPTION = "LIMIT"
const val SKIP_FILED_OPTION = "SKIP"
const val BOOKMARK_CONDITION = "MARKCONDITIONS" //书签排序条件,指定field
const val FIX_FIELD_OPTION = "SELECT_FIELDS" //指定查询的字段列表
}
/**
* 获取选项目标
*/
fun <T> getTarget(clazz: KClass<*>):OptionTarget<T>
} | apache-2.0 | d1b2bea9afebb03dd2c9770cfaf13acc | 21.772727 | 72 | 0.634 | 3.424658 | false | false | false | false |
Nagarajj/orca | orca-queue/src/test/kotlin/com/netflix/spinnaker/orca/q/SpringIntegrationTest.kt | 1 | 13792 | /*
* Copyright 2017 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.spinnaker.orca.q
import com.natpryce.hamkrest.allElements
import com.natpryce.hamkrest.equalTo
import com.natpryce.hamkrest.should.shouldMatch
import com.netflix.appinfo.InstanceInfo.InstanceStatus.*
import com.netflix.discovery.StatusChangeEvent
import com.netflix.spectator.api.Counter
import com.netflix.spectator.api.Id
import com.netflix.spectator.api.Registry
import com.netflix.spinnaker.config.QueueConfiguration
import com.netflix.spinnaker.kork.eureka.RemoteStatusChangedEvent
import com.netflix.spinnaker.orca.ExecutionStatus.*
import com.netflix.spinnaker.orca.TaskResult
import com.netflix.spinnaker.orca.batch.exceptions.DefaultExceptionHandler
import com.netflix.spinnaker.orca.pipeline.RestrictExecutionDuringTimeWindow
import com.netflix.spinnaker.orca.pipeline.StageDefinitionBuilder
import com.netflix.spinnaker.orca.pipeline.TaskNode.Builder
import com.netflix.spinnaker.orca.pipeline.model.Execution
import com.netflix.spinnaker.orca.pipeline.model.Stage
import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository
import com.netflix.spinnaker.orca.pipeline.persistence.jedis.JedisExecutionRepository
import com.netflix.spinnaker.orca.pipeline.util.ContextParameterProcessor
import com.netflix.spinnaker.orca.pipeline.util.StageNavigator
import com.netflix.spinnaker.orca.test.redis.EmbeddedRedisConfiguration
import com.netflix.spinnaker.spek.shouldEqual
import com.nhaarman.mockito_kotlin.*
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.springframework.beans.factory.DisposableBean
import org.springframework.beans.factory.InitializingBean
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfiguration
import org.springframework.context.ConfigurableApplicationContext
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.Import
import org.springframework.test.context.ContextConfiguration
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner
import java.lang.Thread.sleep
import java.time.Duration
import java.time.ZonedDateTime.now
import java.util.concurrent.atomic.AtomicBoolean
@RunWith(SpringJUnit4ClassRunner::class)
@ContextConfiguration(classes = arrayOf(TestConfig::class))
class SpringIntegrationTest {
@Autowired lateinit var queue: Queue
@Autowired lateinit var runner: QueueExecutionRunner
@Autowired lateinit var repository: ExecutionRepository
@Autowired lateinit var dummyTask: DummyTask
@Autowired lateinit var context: ConfigurableApplicationContext
@Before fun discoveryUp() {
context.publishEvent(RemoteStatusChangedEvent(StatusChangeEvent(STARTING, UP)))
}
@After fun discoveryDown() {
context.publishEvent(RemoteStatusChangedEvent(StatusChangeEvent(UP, OUT_OF_SERVICE)))
}
@After fun resetMocks() = reset(dummyTask)
@Test fun `can run a simple pipeline`() {
val pipeline = pipeline {
application = "spinnaker"
stage {
refId = "1"
type = "dummy"
}
}
repository.store(pipeline)
whenever(dummyTask.timeout) doReturn 2000L
whenever(dummyTask.execute(any())) doReturn TaskResult.SUCCEEDED
context.runToCompletion(pipeline, runner::start)
repository.retrievePipeline(pipeline.id).status shouldEqual SUCCEEDED
}
@Test fun `can run a fork join pipeline`() {
val pipeline = pipeline {
application = "spinnaker"
stage {
refId = "1"
type = "dummy"
}
stage {
refId = "2a"
requisiteStageRefIds = setOf("1")
type = "dummy"
}
stage {
refId = "2b"
requisiteStageRefIds = setOf("1")
type = "dummy"
}
stage {
refId = "3"
requisiteStageRefIds = setOf("2a", "2b")
type = "dummy"
}
}
repository.store(pipeline)
whenever(dummyTask.timeout) doReturn 2000L
whenever(dummyTask.execute(any())) doReturn TaskResult.SUCCEEDED
context.runToCompletion(pipeline, runner::start)
repository.retrievePipeline(pipeline.id).apply {
status shouldEqual SUCCEEDED
stageByRef("1").status shouldEqual SUCCEEDED
stageByRef("2a").status shouldEqual SUCCEEDED
stageByRef("2b").status shouldEqual SUCCEEDED
stageByRef("3").status shouldEqual SUCCEEDED
}
}
@Test fun `can run a pipeline that ends in a branch`() {
val pipeline = pipeline {
application = "spinnaker"
stage {
refId = "1"
type = "dummy"
}
stage {
refId = "2a"
requisiteStageRefIds = setOf("1")
type = "dummy"
}
stage {
refId = "2b1"
requisiteStageRefIds = setOf("1")
type = "dummy"
}
stage {
refId = "2b2"
requisiteStageRefIds = setOf("2b1")
type = "dummy"
}
}
repository.store(pipeline)
whenever(dummyTask.timeout) doReturn 2000L
whenever(dummyTask.execute(any())) doReturn TaskResult.SUCCEEDED
context.runToCompletion(pipeline, runner::start)
repository.retrievePipeline(pipeline.id).apply {
status shouldEqual SUCCEEDED
stageByRef("1").status shouldEqual SUCCEEDED
stageByRef("2a").status shouldEqual SUCCEEDED
stageByRef("2b1").status shouldEqual SUCCEEDED
stageByRef("2b2").status shouldEqual SUCCEEDED
}
}
@Test fun `can skip stages`() {
val pipeline = pipeline {
application = "spinnaker"
stage {
refId = "1"
type = "dummy"
context["stageEnabled"] = mapOf(
"type" to "expression",
"expression" to "false"
)
}
}
repository.store(pipeline)
context.runToCompletion(pipeline, runner::start)
repository.retrievePipeline(pipeline.id).status shouldEqual SUCCEEDED
verify(dummyTask, never()).execute(any())
}
@Test fun `pipeline fails if a task fails`() {
val pipeline = pipeline {
application = "spinnaker"
stage {
refId = "1"
type = "dummy"
}
}
repository.store(pipeline)
whenever(dummyTask.execute(any())) doReturn TaskResult(TERMINAL)
context.runToCompletion(pipeline, runner::start)
repository.retrievePipeline(pipeline.id).status shouldEqual TERMINAL
}
@Test fun `parallel stages that fail cancel other branches`() {
val pipeline = pipeline {
application = "spinnaker"
stage {
refId = "1"
type = "dummy"
}
stage {
refId = "2a1"
type = "dummy"
requisiteStageRefIds = listOf("1")
}
stage {
refId = "2a2"
type = "dummy"
requisiteStageRefIds = listOf("2a1")
}
stage {
refId = "2b"
type = "dummy"
requisiteStageRefIds = listOf("1")
}
stage {
refId = "3"
type = "dummy"
requisiteStageRefIds = listOf("2a2", "2b")
}
}
repository.store(pipeline)
whenever(dummyTask.execute(argThat { getRefId() == "2a1" })) doReturn TaskResult(TERMINAL)
whenever(dummyTask.execute(argThat { getRefId() != "2a1" })) doReturn TaskResult.SUCCEEDED
context.runToCompletion(pipeline, runner::start)
repository.retrievePipeline(pipeline.id).apply {
status shouldEqual TERMINAL
stageByRef("1").status shouldEqual SUCCEEDED
stageByRef("2a1").status shouldEqual TERMINAL
stageByRef("2a2").status shouldEqual NOT_STARTED
stageByRef("2b").status shouldEqual SUCCEEDED
stageByRef("3").status shouldEqual NOT_STARTED
}
}
@Test fun `stages set to allow failure will proceed in spite of errors`() {
val pipeline = pipeline {
application = "spinnaker"
stage {
refId = "1"
type = "dummy"
}
stage {
refId = "2a1"
type = "dummy"
requisiteStageRefIds = listOf("1")
context["continuePipeline"] = true
}
stage {
refId = "2a2"
type = "dummy"
requisiteStageRefIds = listOf("2a1")
}
stage {
refId = "2b"
type = "dummy"
requisiteStageRefIds = listOf("1")
}
stage {
refId = "3"
type = "dummy"
requisiteStageRefIds = listOf("2a2", "2b")
}
}
repository.store(pipeline)
whenever(dummyTask.timeout) doReturn 2000L
whenever(dummyTask.execute(argThat { getRefId() == "2a1" })) doReturn TaskResult(TERMINAL)
whenever(dummyTask.execute(argThat { getRefId() != "2a1" })) doReturn TaskResult.SUCCEEDED
context.runToCompletion(pipeline, runner::start)
repository.retrievePipeline(pipeline.id).apply {
status shouldEqual SUCCEEDED
stageByRef("1").status shouldEqual SUCCEEDED
stageByRef("2a1").status shouldEqual FAILED_CONTINUE
stageByRef("2a2").status shouldEqual SUCCEEDED
stageByRef("2b").status shouldEqual SUCCEEDED
stageByRef("3").status shouldEqual SUCCEEDED
}
}
@Test fun `stages set to allow failure but fail the pipeline will run to completion but then mark the pipeline failed`() {
val pipeline = pipeline {
application = "spinnaker"
stage {
refId = "1"
type = "dummy"
}
stage {
refId = "2a1"
type = "dummy"
requisiteStageRefIds = listOf("1")
context["continuePipeline"] = false
context["failPipeline"] = false
context["completeOtherBranchesThenFail"] = true
}
stage {
refId = "2a2"
type = "dummy"
requisiteStageRefIds = listOf("2a1")
}
stage {
refId = "2b"
type = "dummy"
requisiteStageRefIds = listOf("1")
}
stage {
refId = "3"
type = "dummy"
requisiteStageRefIds = listOf("2a2", "2b")
}
}
repository.store(pipeline)
whenever(dummyTask.timeout) doReturn 2000L
whenever(dummyTask.execute(argThat { getRefId() == "2a1" })) doReturn TaskResult(TERMINAL)
whenever(dummyTask.execute(argThat { getRefId() != "2a1" })) doReturn TaskResult.SUCCEEDED
context.runToCompletion(pipeline, runner::start)
repository.retrievePipeline(pipeline.id).apply {
status shouldEqual TERMINAL
stageByRef("1").status shouldEqual SUCCEEDED
stageByRef("2a1").status shouldEqual STOPPED
stageByRef("2a2").status shouldEqual NOT_STARTED
stageByRef("2b").status shouldEqual SUCCEEDED
stageByRef("3").status shouldEqual NOT_STARTED
}
}
@Test fun `can run a stage with an execution window`() {
val pipeline = pipeline {
application = "spinnaker"
stage {
refId = "1"
type = "dummy"
context = mapOf(
"restrictExecutionDuringTimeWindow" to true,
"restrictedExecutionWindow" to mapOf(
"days" to (1..7).toList(),
"whitelist" to listOf(mapOf(
"startHour" to now().hour,
"startMin" to 0,
"endHour" to now().hour + 1,
"endMin" to 0
))
)
)
}
}
repository.store(pipeline)
whenever(dummyTask.timeout) doReturn 2000L
whenever(dummyTask.execute(any())) doReturn TaskResult.SUCCEEDED
context.runToCompletion(pipeline, runner::start)
repository.retrievePipeline(pipeline.id).apply {
status shouldEqual SUCCEEDED
stages.size shouldEqual 2
stages.first().type shouldEqual RestrictExecutionDuringTimeWindow.TYPE
stages.map { it.status } shouldMatch allElements(equalTo(SUCCEEDED))
}
}
}
@Configuration
@Import(
PropertyPlaceholderAutoConfiguration::class,
QueueConfiguration::class,
EmbeddedRedisConfiguration::class,
JedisExecutionRepository::class,
StageNavigator::class,
RestrictExecutionDuringTimeWindow::class
)
open class TestConfig {
@Bean open fun registry(): Registry = mock {
on { createId(any<String>()) }.doReturn(mock<Id>())
on { counter(any<Id>()) }.doReturn(mock<Counter>())
}
@Bean open fun dummyTask(): DummyTask = mock {
on { timeout } doReturn Duration.ofMinutes(2).toMillis()
}
@Bean open fun dummyStage(): StageDefinitionBuilder = object : StageDefinitionBuilder {
override fun <T : Execution<T>> taskGraph(stage: Stage<T>, builder: Builder) {
builder.withTask("dummy", DummyTask::class.java)
}
override fun getType() = "dummy"
}
@Bean open fun stupidPretendScheduler(queueProcessor: QueueProcessor): Any =
object : InitializingBean, DisposableBean {
private val running = AtomicBoolean(false)
override fun afterPropertiesSet() {
running.set(true)
Thread(Runnable {
while (running.get()) {
queueProcessor.pollOnce()
sleep(10)
}
}).start()
}
override fun destroy() {
running.set(false)
}
}
@Bean open fun currentInstanceId() = "localhost"
@Bean open fun contextParameterProcessor() = ContextParameterProcessor()
@Bean open fun defaultExceptionHandler() = DefaultExceptionHandler()
}
| apache-2.0 | 507c383f04ede38bcb75c21d7c3e216c | 29.923767 | 124 | 0.673869 | 4.447598 | false | true | false | false |
gotev/recycler-adapter | app/demo/src/main/java/net/gotev/recycleradapterdemo/adapteritems/SyncItem.kt | 1 | 694 | package net.gotev.recycleradapterdemo.adapteritems
import net.gotev.recycleradapter.AdapterItem
class SyncItem(val id: Int, private val suffix: String) : TitleSubtitleItem("item $id $suffix", suffix) {
override fun diffingId() = javaClass.name + id
override fun compareTo(other: AdapterItem<*>): Int {
if (other.javaClass != javaClass)
return -1
val item = other as SyncItem
if (id == item.id)
return 0
return if (id > item.id) 1 else -1
}
override fun hasToBeReplacedBy(newItem: AdapterItem<*>): Boolean {
if (newItem !is SyncItem)
return true
return suffix != newItem.suffix
}
}
| apache-2.0 | 43796759facd574eb14bbec6cbb6e2fd | 24.703704 | 105 | 0.631124 | 4.3375 | false | false | false | false |
ruuvi/Android_RuuvitagScanner | app/src/main/java/com/ruuvi/station/util/extensions/String.kt | 1 | 533 | package com.ruuvi.station.util.extensions
import java.util.Locale
private const val HEX_CHARS = "0123456789ABCDEF"
fun String.hexStringToByteArray(): ByteArray {
val input = this.toUpperCase(Locale.getDefault())
val result = ByteArray(length / 2)
for (i in 0 until length step 2) {
val firstIndex = HEX_CHARS.indexOf(input[i])
val secondIndex = HEX_CHARS.indexOf(input[i + 1])
val octet = firstIndex.shl(4).or(secondIndex)
result[i.shr(1)] = octet.toByte()
}
return result
} | mit | d0d34edb80a9aa1e8742a088f0578b3c | 24.428571 | 57 | 0.673546 | 3.780142 | false | false | false | false |
HughG/partial-order | partial-order-app/src/main/kotlin/org/tameter/partialorder/dag/kpouchdb/NodeDoc.kt | 1 | 1158 | package org.tameter.partialorder.dag.kpouchdb
import org.tameter.kpouchdb.PouchDoc
import org.tameter.kpouchdb.toStringForExternal
/**
* Copyright (c) 2016 Hugh Greene ([email protected]).
*/
external interface NodeDoc : PouchDoc {
// TODO 2017-08-10 HughG: Need to document what these mean!
val source: String
val sourceId: String
val sourceDescription: String
val index: Long
val description: String
}
fun NodeDoc.toStringForExternal(): String {
return "${this.unsafeCast<PouchDoc>().toStringForExternal()}, description: ${description}"
}
fun NodeDoc(source: String, sourceId: String, sourceDescription: String, index: Long, description: String): NodeDoc {
val id = "${source}/${index}"
return PouchDoc<NodeDoc>(id, "N").apply {
this.asDynamic().source = source
this.asDynamic().sourceId = sourceId
this.asDynamic().sourceDescription = sourceDescription
this.asDynamic().index = index
this.asDynamic().description = description
}
}
fun NodeDoc(doc: NodeDoc): NodeDoc {
return NodeDoc(doc.source, doc.sourceId, doc.sourceDescription, doc.index, doc.description)
}
| mit | 03e02a82fcb7c14cef39294e1da4fae1 | 32.085714 | 117 | 0.711572 | 3.89899 | false | false | false | false |
tom-kita/kktAPK | app/src/main/kotlin/com/bl_lia/kirakiratter/presentation/fragment/NotificationFragment.kt | 3 | 7263 | package com.bl_lia.kirakiratter.presentation.fragment
import android.content.Intent
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v4.app.ActivityOptionsCompat
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.bl_lia.kirakiratter.App
import com.bl_lia.kirakiratter.R
import com.bl_lia.kirakiratter.domain.entity.Notification
import com.bl_lia.kirakiratter.domain.entity.Status
import com.bl_lia.kirakiratter.domain.extension.preparedErrorMessage
import com.bl_lia.kirakiratter.domain.value_object.Translation
import com.bl_lia.kirakiratter.presentation.activity.AccountActivity
import com.bl_lia.kirakiratter.presentation.activity.KatsuActivity
import com.bl_lia.kirakiratter.presentation.adapter.notification.NotificationAdapter
import com.bl_lia.kirakiratter.presentation.internal.di.component.DaggerNotificationComponent
import com.bl_lia.kirakiratter.presentation.internal.di.component.NotificationComponent
import com.bl_lia.kirakiratter.presentation.internal.di.module.FragmentModule
import com.bl_lia.kirakiratter.presentation.presenter.NotificationPresenter
import com.bl_lia.kirakiratter.presentation.scroll_listener.NotificationScrollListener
import com.trello.rxlifecycle2.components.support.RxFragment
import kotlinx.android.synthetic.main.fragment_notification.*
import javax.inject.Inject
class NotificationFragment : RxFragment(), ScrollableFragment {
companion object {
fun newInstance(): NotificationFragment = NotificationFragment()
}
@Inject
lateinit var presenter: NotificationPresenter
private var moreLoading: Boolean = false
private var layoutManager: RecyclerView.LayoutManager? = null
private val component: NotificationComponent by lazy {
DaggerNotificationComponent.builder()
.applicationComponent((activity.application as App).component)
.fragmentModule(FragmentModule(this))
.build()
}
private val adapter: NotificationAdapter by lazy {
NotificationAdapter()
}
private val scrollListener: NotificationScrollListener by lazy {
object: NotificationScrollListener(layoutManager as LinearLayoutManager) {
override fun onLoadMore() {
adapter.maxId?.let { maxId ->
if (moreLoading) return@let
moreLoading = true
presenter.fetchMoreNotification(maxId)
?.doAfterTerminate {
moreLoading = false
}
?.subscribe { list, error ->
if (error != null) {
showError(error)
return@subscribe
}
adapter.add(list)
}
}
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
component.inject(this)
}
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? =
inflater?.inflate(R.layout.fragment_notification, container, false)
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
if (list_notification.layoutManager == null) {
layoutManager = LinearLayoutManager(activity)
list_notification.layoutManager = layoutManager
}
list_notification.adapter = adapter
list_notification.addOnScrollListener(scrollListener)
layout_swipe_refresh?.setOnRefreshListener {
fetch()
}
adapter.onClickAccount.subscribe { pair ->
val account = pair.first
val imageView = pair.second
val intent = Intent(activity, AccountActivity::class.java).apply {
putExtra(AccountActivity.INTENT_PARAM_ACCOUNT, account)
}
val options = ActivityOptionsCompat.makeSceneTransitionAnimation(activity, imageView, "avatar")
startActivity(intent, options.toBundle())
}
adapter.onClickReply.subscribe { status ->
val target = status.reblog ?: status
val intent = Intent(activity, KatsuActivity::class.java).apply {
putExtra(KatsuActivity.INTENT_PARAM_REPLY_ACCOUNT_NAME, target.account?.userName)
putExtra(KatsuActivity.INTENT_PARAM_REPLY_STATUS_ID, target.id)
}
startActivity(intent)
}
adapter.onClickReblog.subscribe { notification ->
val target = notification.status?.reblog ?: notification.status
target?.let { target ->
presenter.reblog(target)
.compose(bindToLifecycle())
.subscribe { status, error ->
if (error != null) {
showError(error)
return@subscribe
}
adapter.update(notification.copy(status = status))
}
}
}
adapter.onClickFavourite.subscribe { notification ->
notification.status?.let { status ->
presenter.favourite(status)
.compose(bindToLifecycle())
.subscribe { status, error ->
if (error != null) {
showError(error)
return@subscribe
}
adapter.update(notification.copy(status = status))
}
}
}
adapter.onClickTranslate.subscribe { notification ->
presenter.translate(notification)
}
fetch()
}
override fun scrollToTop() {
list_notification?.smoothScrollToPosition(0)
}
fun tranlateText(notification: Notification, status: Status, translations: List<Translation>, error: Throwable?) {
if (error != null) {
showError(error)
return
}
adapter.addTranslatedText(notification.copy(status = status), translations.first().translatedText)
}
private fun fetch() {
layout_swipe_refresh?.isRefreshing = true
presenter.fetchNotification()
.doAfterTerminate {
layout_swipe_refresh?.isRefreshing = false
}
.compose(bindToLifecycle())
.subscribe { list, error ->
if (error != null) {
showError(error)
return@subscribe
}
adapter.reset(list)
}
}
private fun showError(error: Throwable) {
Snackbar.make(layout_content, error.preparedErrorMessage(activity), Snackbar.LENGTH_LONG).show()
}
} | mit | 57fde2661ff1adc7aa5c9aae5aaed31f | 37.638298 | 118 | 0.606361 | 5.608494 | false | false | false | false |
lispyclouds/bob | src/main/kotlin/bob/util/Tools.kt | 1 | 3996 | /*
* This file is part of Bob.
*
* Bob is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Bob is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Bob. If not, see <http://www.gnu.org/licenses/>.
*/
package bob.util
import bob.core.GenericResponse
import bob.core.asJsonString
import com.google.gson.Gson
import org.jetbrains.ktor.application.ApplicationCall
import org.jetbrains.ktor.http.ContentType
import org.jetbrains.ktor.http.HttpStatusCode
import org.jetbrains.ktor.request.receive
import org.jetbrains.ktor.response.respondText
fun generateID() = java.util.UUID.randomUUID().toString()
fun <T> jsonStringOf(obj: T): String = Gson().toJson(obj)
suspend fun respondWith(call: ApplicationCall, message: String,
status: HttpStatusCode = HttpStatusCode.OK) {
call.response.status(status)
call.respondText(
GenericResponse(message).asJsonString(),
ContentType.Application.Json
)
}
suspend fun respondWith404(call: ApplicationCall) {
call.response.status(HttpStatusCode.NotFound)
call.respondText(
GenericResponse("Sorry, Not found!").asJsonString(),
ContentType.Application.Json
)
}
suspend fun respondWithError(call: ApplicationCall) {
call.response.status(HttpStatusCode.InternalServerError)
call.respondText(
GenericResponse("Internal Error happened!").asJsonString(),
ContentType.Application.Json
)
}
suspend fun respondWithBadRequest(call: ApplicationCall) {
call.response.status(HttpStatusCode.BadRequest)
call.respondText(
GenericResponse("Bad request: Please check the params supplied")
.asJsonString(),
ContentType.Application.Json
)
}
suspend fun <T> respondIfExists(call: ApplicationCall,
getUsing: (String) -> T?,
serializeUsing: ((T) -> String)?,
param: String = "id") {
val id = call.parameters[param]
when (id) {
null -> respondWithBadRequest(call)
else -> {
val entity = getUsing(id)
when (entity) {
null -> respondWith404(call)
else -> {
call.response.status(HttpStatusCode.OK)
if (serializeUsing != null) {
call.respondText(
serializeUsing(entity),
ContentType.Application.Json
)
} else {
respondWith(call, "Ok")
}
}
}
}
}
}
suspend fun deleteEntity(call: ApplicationCall, using: (String) -> Int,
param: String = "id") {
val id = call.parameters[param]
when (id) {
null -> respondWithBadRequest(call)
else -> {
using(id)
respondWith(call, "Ok")
}
}
}
suspend fun <T> doIfParamsValid(call: ApplicationCall, param: String = "id",
deserializeUsing: (String) -> T?,
toDo: suspend (String, T) -> Unit) {
val id = call.parameters[param]
val options = call.receive<String>()
when {
id == null || options.isEmpty() -> respondWithBadRequest(call)
else -> {
val entity = deserializeUsing(options)
when (entity) {
null -> respondWithBadRequest(call)
else -> toDo(id, entity)
}
}
}
}
| gpl-3.0 | a3f5a8fc98971470b974ea35f13709b3 | 30.464567 | 76 | 0.597347 | 4.701176 | false | false | false | false |
robinverduijn/gradle | buildSrc/subprojects/binary-compatibility/src/main/kotlin/org/gradle/binarycompatibility/metadata/HasKotlinFlagsMetadataQuery.kt | 1 | 11707 | /*
* Copyright 2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.binarycompatibility.metadata
import kotlinx.metadata.ClassName
import kotlinx.metadata.Flag
import kotlinx.metadata.Flags
import kotlinx.metadata.KmClassExtensionVisitor
import kotlinx.metadata.KmClassVisitor
import kotlinx.metadata.KmConstructorExtensionVisitor
import kotlinx.metadata.KmConstructorVisitor
import kotlinx.metadata.KmExtensionType
import kotlinx.metadata.KmFunctionExtensionVisitor
import kotlinx.metadata.KmFunctionVisitor
import kotlinx.metadata.KmPackageExtensionVisitor
import kotlinx.metadata.KmPackageVisitor
import kotlinx.metadata.KmPropertyExtensionVisitor
import kotlinx.metadata.KmPropertyVisitor
import kotlinx.metadata.jvm.JvmClassExtensionVisitor
import kotlinx.metadata.jvm.JvmConstructorExtensionVisitor
import kotlinx.metadata.jvm.JvmFieldSignature
import kotlinx.metadata.jvm.JvmFunctionExtensionVisitor
import kotlinx.metadata.jvm.JvmMethodSignature
import kotlinx.metadata.jvm.JvmPackageExtensionVisitor
import kotlinx.metadata.jvm.JvmPropertyExtensionVisitor
import kotlinx.metadata.jvm.KotlinClassMetadata
internal
fun KotlinClassMetadata.hasKotlinFlag(memberType: MemberType, jvmSignature: String, flag: Flag): Boolean =
hasKotlinFlags(memberType, jvmSignature) { flags ->
flag(flags)
}
private
fun KotlinClassMetadata.hasKotlinFlags(memberType: MemberType, jvmSignature: String, predicate: (Flags) -> Boolean): Boolean =
when (this) {
is KotlinClassMetadata.Class -> classVisitorFor(memberType, jvmSignature, predicate).apply(::accept).isSatisfied
is KotlinClassMetadata.FileFacade -> packageVisitorFor(memberType, jvmSignature, predicate).apply(::accept).isSatisfied
is KotlinClassMetadata.MultiFileClassPart -> packageVisitorFor(memberType, jvmSignature, predicate).apply(::accept).isSatisfied
is KotlinClassMetadata.MultiFileClassFacade -> false
is KotlinClassMetadata.SyntheticClass -> false
is KotlinClassMetadata.Unknown -> false
else -> throw IllegalStateException("Unsupported Kotlin metadata type '${this::class}'")
}
private
typealias FlagsPredicate = (Flags) -> Boolean
private
interface CanBeSatisfied {
var isSatisfied: Boolean
}
private
abstract class SatisfiableClassVisitor : KmClassVisitor(), CanBeSatisfied
private
abstract class SatisfiablePackageVisitor : KmPackageVisitor(), CanBeSatisfied
@Suppress("unchecked_cast")
private
fun classVisitorFor(memberType: MemberType, jvmSignature: String, predicate: FlagsPredicate): SatisfiableClassVisitor =
when (memberType) {
MemberType.TYPE -> TypeFlagsKmClassVisitor(jvmSignature, predicate)
MemberType.FIELD -> FieldFlagsKmClassVisitor(jvmSignature, predicate)
MemberType.CONSTRUCTOR -> ConstructorFlagsKmClassVisitor(jvmSignature, predicate)
MemberType.METHOD -> MethodFlagsKmClassVisitor(jvmSignature, predicate)
}
@Suppress("unchecked_cast")
private
fun packageVisitorFor(memberType: MemberType, jvmSignature: String, predicate: FlagsPredicate): SatisfiablePackageVisitor =
when (memberType) {
MemberType.FIELD -> FieldFlagsKmPackageVisitor(jvmSignature, predicate)
MemberType.METHOD -> MethodFlagsKmPackageVisitor(jvmSignature, predicate)
else -> NoopFlagsKmPackageVisitor
}
private
class TypeFlagsKmClassVisitor(
private val jvmSignature: String,
private val predicate: FlagsPredicate
) : SatisfiableClassVisitor() {
override var isSatisfied = false
private
var isDoneVisiting = false
override fun visit(flags: Flags, name: ClassName) {
if (!isDoneVisiting && jvmSignature == name.replace("/", ".")) {
isSatisfied = predicate(flags)
isDoneVisiting = true
}
}
}
private
class FieldFlagsKmClassVisitor(
private val jvmSignature: String,
private val predicate: FlagsPredicate
) : SatisfiableClassVisitor() {
override var isSatisfied = false
private
var isDoneVisiting = false
private
val onMatch = { satisfaction: Boolean ->
isSatisfied = satisfaction
isDoneVisiting = true
}
override fun visitProperty(flags: Flags, name: String, getterFlags: Flags, setterFlags: Flags): KmPropertyVisitor? =
if (isDoneVisiting) null
else MemberFlagsKmPropertyExtensionVisitor(jvmSignature, predicate, flags, getterFlags, setterFlags, onMatch)
override fun visitExtensions(type: KmExtensionType): KmClassExtensionVisitor? =
if (isDoneVisiting) null
else object : JvmClassExtensionVisitor() {
override fun visitLocalDelegatedProperty(flags: Flags, name: String, getterFlags: Flags, setterFlags: Flags): KmPropertyVisitor? =
MemberFlagsKmPropertyExtensionVisitor(jvmSignature, predicate, flags, getterFlags, setterFlags, onMatch)
}
}
private
class ConstructorFlagsKmClassVisitor(
private val jvmSignature: String,
private val predicate: FlagsPredicate
) : SatisfiableClassVisitor() {
override var isSatisfied = false
private
var isDoneVisiting = false
override fun visitConstructor(flags: Flags): KmConstructorVisitor? =
if (isDoneVisiting) null
else object : KmConstructorVisitor() {
override fun visitExtensions(type: KmExtensionType): KmConstructorExtensionVisitor =
object : JvmConstructorExtensionVisitor() {
override fun visit(signature: JvmMethodSignature?) {
if (jvmSignature == signature?.asString()) {
isSatisfied = predicate(flags)
isDoneVisiting = true
}
}
}
}
}
private
class MethodFlagsKmClassVisitor(
private val jvmSignature: String,
private val predicate: FlagsPredicate
) : SatisfiableClassVisitor() {
override var isSatisfied = false
private
var isDoneVisiting = false
private
val onMatch = { satisfaction: Boolean ->
isSatisfied = satisfaction
isDoneVisiting = true
}
override fun visitFunction(flags: Flags, name: String): KmFunctionVisitor? =
if (isDoneVisiting) null
else MethodFlagsKmFunctionVisitor(jvmSignature, predicate, flags, onMatch)
override fun visitProperty(flags: Flags, name: String, getterFlags: Flags, setterFlags: Flags): KmPropertyVisitor? =
if (isDoneVisiting) null
else MemberFlagsKmPropertyExtensionVisitor(jvmSignature, predicate, flags, getterFlags, setterFlags, onMatch)
override fun visitExtensions(type: KmExtensionType): KmClassExtensionVisitor? =
if (isDoneVisiting) null
else object : JvmClassExtensionVisitor() {
override fun visitLocalDelegatedProperty(flags: Flags, name: String, getterFlags: Flags, setterFlags: Flags): KmPropertyVisitor =
MemberFlagsKmPropertyExtensionVisitor(jvmSignature, predicate, flags, getterFlags, setterFlags, onMatch)
}
}
private
class FieldFlagsKmPackageVisitor(
private val jvmSignature: String,
private val predicate: FlagsPredicate
) : SatisfiablePackageVisitor() {
override var isSatisfied = false
private
var isDoneVisiting = false
private
val onMatch = { satisfaction: Boolean ->
isSatisfied = satisfaction
isDoneVisiting = true
}
override fun visitProperty(flags: Flags, name: String, getterFlags: Flags, setterFlags: Flags): KmPropertyVisitor? =
if (isDoneVisiting) null
else MemberFlagsKmPropertyExtensionVisitor(jvmSignature, predicate, flags, getterFlags, setterFlags, onMatch)
override fun visitExtensions(type: KmExtensionType): KmPackageExtensionVisitor? =
if (isDoneVisiting) null
else object : JvmPackageExtensionVisitor() {
override fun visitLocalDelegatedProperty(flags: Flags, name: String, getterFlags: Flags, setterFlags: Flags): KmPropertyVisitor =
MemberFlagsKmPropertyExtensionVisitor(jvmSignature, predicate, flags, getterFlags, setterFlags, onMatch)
}
}
private
class MethodFlagsKmPackageVisitor(
private val jvmSignature: String,
private val predicate: FlagsPredicate
) : SatisfiablePackageVisitor() {
override var isSatisfied = false
private
var isDoneVisiting = false
private
val onMatch = { satisfaction: Boolean ->
isSatisfied = satisfaction
isDoneVisiting = true
}
override fun visitFunction(flags: Flags, name: String): KmFunctionVisitor? =
if (isDoneVisiting) null
else MethodFlagsKmFunctionVisitor(jvmSignature, predicate, flags, onMatch)
override fun visitProperty(flags: Flags, name: String, getterFlags: Flags, setterFlags: Flags): KmPropertyVisitor? =
if (isDoneVisiting) null
else MemberFlagsKmPropertyExtensionVisitor(jvmSignature, predicate, flags, getterFlags, setterFlags, onMatch)
override fun visitExtensions(type: KmExtensionType): KmPackageExtensionVisitor? =
if (isDoneVisiting) null
else object : JvmPackageExtensionVisitor() {
override fun visitLocalDelegatedProperty(flags: Flags, name: String, getterFlags: Flags, setterFlags: Flags): KmPropertyVisitor =
MemberFlagsKmPropertyExtensionVisitor(jvmSignature, predicate, flags, getterFlags, setterFlags, onMatch)
}
}
private
object NoopFlagsKmPackageVisitor : SatisfiablePackageVisitor() {
override var isSatisfied = false
}
private
class MemberFlagsKmPropertyExtensionVisitor(
private val jvmSignature: String,
private val predicate: FlagsPredicate,
private val fieldFlags: Flags,
private val getterFlags: Flags,
private val setterFlags: Flags,
private val onMatch: (Boolean) -> Unit
) : KmPropertyVisitor() {
private
val kmPropertyExtensionVisitor = object : JvmPropertyExtensionVisitor() {
override fun visit(fieldSignature: JvmFieldSignature?, getterSignature: JvmMethodSignature?, setterSignature: JvmMethodSignature?) {
when (jvmSignature) {
fieldSignature?.asString() -> onMatch(predicate(fieldFlags))
getterSignature?.asString() -> onMatch(predicate(getterFlags))
setterSignature?.asString() -> onMatch(predicate(setterFlags))
}
}
}
override fun visitExtensions(type: KmExtensionType): KmPropertyExtensionVisitor =
kmPropertyExtensionVisitor
}
private
class MethodFlagsKmFunctionVisitor(
private val jvmSignature: String,
private val predicate: FlagsPredicate,
private val functionFlags: Flags,
private val onMatch: (Boolean) -> Unit
) : KmFunctionVisitor() {
private
val kmFunctionExtensionVisitor = object : JvmFunctionExtensionVisitor() {
override fun visit(signature: JvmMethodSignature?) {
if (jvmSignature == signature?.asString()) {
onMatch(predicate(functionFlags))
}
}
}
override fun visitExtensions(type: KmExtensionType): KmFunctionExtensionVisitor? =
kmFunctionExtensionVisitor
}
| apache-2.0 | 9afca2a179fb655b3151fb039cca22ab | 34.692073 | 142 | 0.732211 | 4.790098 | false | false | false | false |
ReactiveCircus/FlowBinding | flowbinding-android/src/main/java/reactivecircus/flowbinding/android/widget/TextViewAfterTextChangeEventFlow.kt | 1 | 1916 | @file:Suppress("MatchingDeclarationName")
package reactivecircus.flowbinding.android.widget
import android.text.Editable
import android.text.TextWatcher
import android.widget.TextView
import androidx.annotation.CheckResult
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.conflate
import reactivecircus.flowbinding.common.InitialValueFlow
import reactivecircus.flowbinding.common.asInitialValueFlow
import reactivecircus.flowbinding.common.checkMainThread
/**
* Create a [InitialValueFlow] of after text change events on the [TextView] instance.
*
* Note: Created flow keeps a strong reference to the [TextView] instance
* until the coroutine that launched the flow collector is cancelled.
*
* Example of usage:
*
* ```
* textView.afterTextChanges()
* .onEach { event ->
* // handle text view after text change event
* }
* .launchIn(uiScope)
* ```
*/
@CheckResult
@OptIn(ExperimentalCoroutinesApi::class)
public fun TextView.afterTextChanges(): InitialValueFlow<AfterTextChangeEvent> = callbackFlow {
checkMainThread()
val listener = object : TextWatcher {
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) = Unit
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) = Unit
override fun afterTextChanged(s: Editable) {
trySend(AfterTextChangeEvent(view = this@afterTextChanges, editable = s))
}
}
addTextChangedListener(listener)
awaitClose { removeTextChangedListener(listener) }
}
.conflate()
.asInitialValueFlow {
AfterTextChangeEvent(view = this@afterTextChanges, editable = editableText)
}
public data class AfterTextChangeEvent(
public val view: TextView,
public val editable: Editable?
)
| apache-2.0 | 56247297987e7b16ad4401543e73989e | 32.034483 | 98 | 0.752088 | 4.742574 | false | false | false | false |
consp1racy/android-commons | commons/src/main/java/com/squareup/picasso/ExifContentStreamRequestHandler.kt | 1 | 1318 | package com.squareup.picasso
import android.content.ContentResolver
import android.content.Context
import net.xpece.android.media.exif.ExifUtils
import java.io.FileNotFoundException
import java.io.IOException
import java.io.InputStream
/**
* Requires com.android.support:exifinterface:25.1.0+.
*
* *Warning!* Android PNG reader doesn't support reset stream. Open a new stream before reading the image.
*
* @author Eugen on 17. 5. 2016.
*/
open class ExifContentStreamRequestHandler(val context: Context) : RequestHandler() {
override fun canHandleRequest(data: Request): Boolean {
return ContentResolver.SCHEME_CONTENT == data.uri.scheme
}
@Throws(IOException::class)
override fun load(request: Request, networkPolicy: Int): Result {
val inputStream = getInputStream(request).buffered()
val orientation = ExifUtils.getOrientation(inputStream)
val rotation = ExifUtils.getRotationFromOrientation(orientation)
// Package private, do not move.
return Result(null, inputStream, Picasso.LoadedFrom.DISK, rotation)
}
@Throws(FileNotFoundException::class)
open fun getInputStream(request: Request): InputStream {
val contentResolver = context.contentResolver
return contentResolver.openInputStream(request.uri)
}
}
| apache-2.0 | ff4d4cf49769ebd7548b75bd04e74eb2 | 31.95 | 106 | 0.740516 | 4.560554 | false | false | false | false |
Deletescape-Media/Lawnchair | SystemUIShared/src/com/android/systemui/unfold/progress/PhysicsBasedUnfoldTransitionProgressProvider.kt | 1 | 7392 | /*
* Copyright (C) 2021 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.systemui.unfold.progress
import android.util.Log
import android.util.MathUtils.saturate
import androidx.dynamicanimation.animation.DynamicAnimation
import androidx.dynamicanimation.animation.FloatPropertyCompat
import androidx.dynamicanimation.animation.SpringAnimation
import androidx.dynamicanimation.animation.SpringForce
import com.android.systemui.unfold.UnfoldTransitionProgressProvider
import com.android.systemui.unfold.UnfoldTransitionProgressProvider.TransitionProgressListener
import com.android.systemui.unfold.updates.FOLD_UPDATE_ABORTED
import com.android.systemui.unfold.updates.FOLD_UPDATE_FINISH_CLOSED
import com.android.systemui.unfold.updates.FOLD_UPDATE_START_CLOSING
import com.android.systemui.unfold.updates.FOLD_UPDATE_FINISH_FULL_OPEN
import com.android.systemui.unfold.updates.FOLD_UPDATE_UNFOLDED_SCREEN_AVAILABLE
import com.android.systemui.unfold.updates.FoldStateProvider
import com.android.systemui.unfold.updates.FoldStateProvider.FoldUpdate
import com.android.systemui.unfold.updates.FoldStateProvider.FoldUpdatesListener
/**
* Maps fold updates to unfold transition progress using DynamicAnimation.
*
* TODO(b/193793338) Current limitations:
* - doesn't handle postures
*/
internal class PhysicsBasedUnfoldTransitionProgressProvider(
private val foldStateProvider: FoldStateProvider
) :
UnfoldTransitionProgressProvider,
FoldUpdatesListener,
DynamicAnimation.OnAnimationEndListener {
private val springAnimation = SpringAnimation(this, AnimationProgressProperty)
.apply {
addEndListener(this@PhysicsBasedUnfoldTransitionProgressProvider)
}
private var isTransitionRunning = false
private var isAnimatedCancelRunning = false
private var transitionProgress: Float = 0.0f
set(value) {
if (isTransitionRunning) {
listeners.forEach { it.onTransitionProgress(value) }
}
field = value
}
private val listeners: MutableList<TransitionProgressListener> = mutableListOf()
init {
foldStateProvider.addCallback(this)
foldStateProvider.start()
}
override fun destroy() {
foldStateProvider.stop()
}
override fun onHingeAngleUpdate(angle: Float) {
if (!isTransitionRunning || isAnimatedCancelRunning) return
val progress = saturate(angle / FINAL_HINGE_ANGLE_POSITION)
springAnimation.animateToFinalPosition(progress)
}
override fun onFoldUpdate(@FoldUpdate update: Int) {
when (update) {
FOLD_UPDATE_UNFOLDED_SCREEN_AVAILABLE -> {
startTransition(startValue = 0f)
// Stop the animation if the device has already opened by the time when
// the display is available as we won't receive the full open event anymore
if (foldStateProvider.isFullyOpened) {
cancelTransition(endValue = 1f, animate = true)
}
}
FOLD_UPDATE_FINISH_FULL_OPEN, FOLD_UPDATE_ABORTED -> {
// Do not cancel if we haven't started the transition yet.
// This could happen when we fully unfolded the device before the screen
// became available. In this case we start and immediately cancel the animation
// in FOLD_UPDATE_UNFOLDED_SCREEN_AVAILABLE event handler, so we don't need to
// cancel it here.
if (isTransitionRunning) {
cancelTransition(endValue = 1f, animate = true)
}
}
FOLD_UPDATE_FINISH_CLOSED -> {
cancelTransition(endValue = 0f, animate = false)
}
FOLD_UPDATE_START_CLOSING -> {
// The transition might be already running as the device might start closing several
// times before reaching an end state.
if (!isTransitionRunning) {
startTransition(startValue = 1f)
}
}
}
if (DEBUG) {
Log.d(TAG, "onFoldUpdate = $update")
}
}
private fun cancelTransition(endValue: Float, animate: Boolean) {
if (isTransitionRunning && animate) {
isAnimatedCancelRunning = true
springAnimation.animateToFinalPosition(endValue)
} else {
transitionProgress = endValue
isAnimatedCancelRunning = false
isTransitionRunning = false
springAnimation.cancel()
listeners.forEach {
it.onTransitionFinished()
}
if (DEBUG) {
Log.d(TAG, "onTransitionFinished")
}
}
}
override fun onAnimationEnd(
animation: DynamicAnimation<out DynamicAnimation<*>>,
canceled: Boolean,
value: Float,
velocity: Float
) {
if (isAnimatedCancelRunning) {
cancelTransition(value, animate = false)
}
}
private fun onStartTransition() {
listeners.forEach {
it.onTransitionStarted()
}
isTransitionRunning = true
if (DEBUG) {
Log.d(TAG, "onTransitionStarted")
}
}
private fun startTransition(startValue: Float) {
if (!isTransitionRunning) onStartTransition()
springAnimation.apply {
spring = SpringForce().apply {
finalPosition = startValue
dampingRatio = SpringForce.DAMPING_RATIO_NO_BOUNCY
stiffness = SPRING_STIFFNESS
}
minimumVisibleChange = MINIMAL_VISIBLE_CHANGE
setStartValue(startValue)
setMinValue(0f)
setMaxValue(1f)
}
springAnimation.start()
}
override fun addCallback(listener: TransitionProgressListener) {
listeners.add(listener)
}
override fun removeCallback(listener: TransitionProgressListener) {
listeners.remove(listener)
}
private object AnimationProgressProperty :
FloatPropertyCompat<PhysicsBasedUnfoldTransitionProgressProvider>("animation_progress") {
override fun setValue(
provider: PhysicsBasedUnfoldTransitionProgressProvider,
value: Float
) {
provider.transitionProgress = value
}
override fun getValue(provider: PhysicsBasedUnfoldTransitionProgressProvider): Float =
provider.transitionProgress
}
}
private const val TAG = "PhysicsBasedUnfoldTransitionProgressProvider"
private const val DEBUG = true
private const val SPRING_STIFFNESS = 200.0f
private const val MINIMAL_VISIBLE_CHANGE = 0.001f
private const val FINAL_HINGE_ANGLE_POSITION = 165f
| gpl-3.0 | b8094e1e3856cf6df5e2fc38f1ab992d | 34.710145 | 100 | 0.663826 | 4.809369 | false | false | false | false |
fython/PackageTracker | mobile/src/main/kotlin/info/papdt/express/helper/support/MaterialColorGenerator.kt | 1 | 5990 | package info.papdt.express.helper.support
import android.content.Context
import info.papdt.express.helper.model.MaterialPalette
import kotlin.random.Random
object MaterialColorGenerator {
lateinit var Red: MaterialPalette
lateinit var Pink: MaterialPalette
lateinit var Purple: MaterialPalette
lateinit var DeepPurple: MaterialPalette
lateinit var Indigo: MaterialPalette
lateinit var Blue: MaterialPalette
lateinit var LightBlue: MaterialPalette
lateinit var Cyan: MaterialPalette
lateinit var Teal: MaterialPalette
lateinit var Green: MaterialPalette
lateinit var LightGreen: MaterialPalette
lateinit var Lime: MaterialPalette
lateinit var Yellow: MaterialPalette
lateinit var Amber: MaterialPalette
lateinit var Orange: MaterialPalette
lateinit var DeepOrange: MaterialPalette
lateinit var Brown: MaterialPalette
lateinit var BlueGrey: MaterialPalette
val AllPalettes: List<MaterialPalette> by lazy {
listOf(Red, Pink, Purple, DeepPurple, Indigo, Blue, LightBlue,
Cyan, Teal, Green, LightGreen, Lime, Amber, Orange,
DeepOrange, Brown, BlueGrey)
}
private val random: Random = Random(System.currentTimeMillis())
private val RedProducer = PaletteProducer("red",
"50", "100", "200", "300", "400", "500",
"600", "700", "800", "900", "A100", "A200", "A400", "A700")
private val PinkProducer = PaletteProducer("pink",
"50", "100", "200", "300", "400", "500",
"600", "700", "800", "900", "A100", "A200", "A400", "A700")
private val PurpleProducer = PaletteProducer("purple",
"50", "100", "200", "300", "400", "500",
"600", "700", "800", "900", "A100", "A200", "A400", "A700")
private val DeepPurpleProducer = PaletteProducer("deep_purple",
"50", "100", "200", "300", "400", "500",
"600", "700", "800", "900", "A100", "A200", "A400", "A700")
private val IndigoProducer = PaletteProducer("indigo",
"50", "100", "200", "300", "400", "500",
"600", "700", "800", "900", "A100", "A200", "A400", "A700")
private val BlueProducer = PaletteProducer("blue",
"50", "100", "200", "300", "400", "500",
"600", "700", "800", "900", "A100", "A200", "A400", "A700")
private val LightBlueProducer = PaletteProducer("light_blue",
"50", "100", "200", "300", "400", "500",
"600", "700", "800", "900", "A100", "A200", "A400", "A700")
private val CyanProducer = PaletteProducer("cyan",
"50", "100", "200", "300", "400", "500",
"600", "700", "800", "900", "A100", "A200", "A400", "A700")
private val TealProducer = PaletteProducer("teal",
"50", "100", "200", "300", "400", "500",
"600", "700", "800", "900", "A100", "A200", "A400", "A700")
private val GreenProducer = PaletteProducer("green",
"50", "100", "200", "300", "400", "500",
"600", "700", "800", "900", "A100", "A200", "A400", "A700")
private val LightGreenProducer = PaletteProducer("light_green",
"50", "100", "200", "300", "400", "500",
"600", "700", "800", "900", "A100", "A200", "A400", "A700")
private val LimeProducer = PaletteProducer("lime",
"50", "100", "200", "300", "400", "500",
"600", "700", "800", "900", "A100", "A200", "A400", "A700")
private val YellowProducer = PaletteProducer("yellow",
"50", "100", "200", "300", "400", "500",
"600", "700", "800", "900", "A100", "A200", "A400", "A700")
private val AmberProducer = PaletteProducer("amber",
"50", "100", "200", "300", "400", "500",
"600", "700", "800", "900", "A100", "A200", "A400", "A700")
private val OrangeProducer = PaletteProducer("orange",
"50", "100", "200", "300", "400", "500",
"600", "700", "800", "900", "A100", "A200", "A400", "A700")
private val DeepOrangeProducer = PaletteProducer("deep_orange",
"50", "100", "200", "300", "400", "500",
"600", "700", "800", "900", "A100", "A200", "A400", "A700")
private val BrownProducer = PaletteProducer("brown",
"50", "100", "200", "300", "400", "500",
"600", "700", "800", "900")
private val BlueGreyProducer = PaletteProducer("blue_grey",
"50", "100", "200", "300", "400", "500",
"600", "700", "800", "900")
fun init(context: Context) {
Red = RedProducer.make(context)
Pink = PinkProducer.make(context)
Purple = PurpleProducer.make(context)
DeepPurple = DeepPurpleProducer.make(context)
Indigo = IndigoProducer.make(context)
Blue = BlueProducer.make(context)
LightBlue = LightBlueProducer.make(context)
Cyan = CyanProducer.make(context)
Teal = TealProducer.make(context)
Green = GreenProducer.make(context)
LightGreen = LightGreenProducer.make(context)
Lime = LimeProducer.make(context)
Yellow = YellowProducer.make(context)
Amber = AmberProducer.make(context)
Orange = OrangeProducer.make(context)
DeepOrange = DeepOrangeProducer.make(context)
Brown = BrownProducer.make(context)
BlueGrey = BlueGreyProducer.make(context)
}
fun getPalette(key: Any): MaterialPalette {
return AllPalettes[Math.abs(key.hashCode()) % AllPalettes.size]
}
private class PaletteProducer(
val colorName: String,
vararg val colorKeys: String
) {
fun make(context: Context): MaterialPalette {
val res = context.resources
val ids = colorKeys.map {
it to res.getIdentifier("${colorName}_$it",
"color", context.packageName)
}.toTypedArray()
return MaterialPalette.makeFromResources(context, colorName, *ids)
}
}
} | gpl-3.0 | ec26a8d40a9bd430c67ab9caadbb9426 | 44.386364 | 78 | 0.577963 | 3.774417 | false | false | false | false |
spinnaker/gate | gate-plugins/src/main/kotlin/com/netflix/spinnaker/gate/plugins/deck/DeckPluginService.kt | 1 | 3532 | /*
* 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.spinnaker.gate.plugins.deck
import com.netflix.spectator.api.Registry
import java.io.File
import org.slf4j.LoggerFactory
/**
* Provides Deck with means of discovering what plugins it needs to download and a standard interface for
* retrieving plugin assets.
*/
open class DeckPluginService(
private val pluginCache: DeckPluginCache,
private val registry: Registry
) {
private val log by lazy { LoggerFactory.getLogger(javaClass) }
private val assetHitsId = registry.createId("plugins.deckAssets.hits")
private val assetMissesId = registry.createId("plugins.deckAssets.misses")
/**
* Returns a list of all plugin versions that Deck should know how to load.
*
* Deck will be responsible for taking this manifest and requesting the `index.js` file inside of a plugin version
* and dynamically resolving any needed assets as it goes along.
*/
fun getPluginsManifests(): List<DeckPluginVersion> {
if (!pluginCache.isCachePopulated()) {
throw CacheNotReadyException()
}
return pluginCache.getCache().map { it.plugin }
}
/**
* Get an individual plugin's asset by version.
*
* If the plugin does not exist on the filesystem, it will be downloaded and cached to a standard location so that
* subsequent asset requests for the plugin version will be faster.
*/
fun getPluginAsset(pluginId: String, pluginVersion: String, assetPath: String): PluginAsset? {
if (!pluginCache.isCachePopulated()) {
throw CacheNotReadyException()
}
val sanitizedAssetPath = if (assetPath.startsWith("/")) assetPath.substring(1) else assetPath
val localAsset = pluginCache.getOrDownload(pluginId, pluginVersion)?.let {
path ->
path.resolve(sanitizedAssetPath).toFile()
}
if (localAsset == null || !localAsset.exists()) {
log.error("Unable to find requested plugin asset '$assetPath' for '$pluginId@$pluginVersion'")
registry.counter(assetMissesId).increment()
return null
}
registry.counter(assetHitsId).increment()
return PluginAsset.from(localAsset)
}
data class PluginAsset(val contentType: String, val content: String) {
companion object {
private val log by lazy { LoggerFactory.getLogger(PluginAsset::class.java) }
fun from(file: File): PluginAsset {
return PluginAsset(
contentType = when {
file.toString().endsWith(".js") -> {
"application/javascript"
}
file.toString().endsWith(".css") -> {
"text/css"
}
file.toString().endsWith(".html") -> {
"text/html"
}
else -> {
log.warn("Unhandled file extension to content-type mapping for file `{}`, falling back to text/plain", file.toString())
"text/plain"
}
},
content = file.readText()
)
}
}
}
}
| apache-2.0 | 2dc7511887d73626c2f905ddedf8bf44 | 33.291262 | 133 | 0.674122 | 4.453972 | false | false | false | false |
wordpress-mobile/WordPress-FluxC-Android | example/src/test/java/org/wordpress/android/fluxc/wc/stats/WCVisitorStatsSqlUtilsTest.kt | 2 | 44197 | package org.wordpress.android.fluxc.wc.stats
import com.yarolegovich.wellsql.WellSql
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import org.wordpress.android.fluxc.SingleStoreWellSqlConfigForTests
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.model.WCNewVisitorStatsModel
import org.wordpress.android.fluxc.model.WCVisitorStatsModel
import org.wordpress.android.fluxc.network.rest.wpcom.wc.orderstats.OrderStatsRestClient.OrderStatsApiUnit
import org.wordpress.android.fluxc.persistence.WCVisitorStatsSqlUtils
import org.wordpress.android.fluxc.persistence.WellSqlConfig
import org.wordpress.android.fluxc.store.WCStatsStore.StatsGranularity
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertNull
@Config(manifest = Config.NONE)
@RunWith(RobolectricTestRunner::class)
class WCVisitorStatsSqlUtilsTest {
@Before
fun setUp() {
val appContext = RuntimeEnvironment.application.applicationContext
val config = SingleStoreWellSqlConfigForTests(
appContext,
listOf(WCVisitorStatsModel::class.java, WCNewVisitorStatsModel::class.java),
WellSqlConfig.ADDON_WOOCOMMERCE)
WellSql.init(config)
config.reset()
}
@Test
@Suppress("LongMethod")
fun testSimpleInsertionAndRetrievalOfVisitorStats() {
// insert a visitor stats entry and verify that it is stored correctly
val visitorStatsModel = WCStatsTestUtils.generateSampleVisitorStatsModel()
WCVisitorStatsSqlUtils.insertOrUpdateVisitorStats(visitorStatsModel)
with(WellSql.select(WCVisitorStatsModel::class.java).asModel) {
assertEquals(1, size)
assertEquals(visitorStatsModel.unit, first().unit)
assertEquals(visitorStatsModel.startDate, first().startDate)
assertEquals(visitorStatsModel.endDate, first().endDate)
}
// Create a second visitor stats entry for this site with same quantity but with different unit
val visitorStatsModel2 = WCStatsTestUtils.generateSampleVisitorStatsModel(
unit = OrderStatsApiUnit.MONTH.toString(), quantity = "12", data = "fake-data"
)
WCVisitorStatsSqlUtils.insertOrUpdateVisitorStats(visitorStatsModel2)
with(WellSql.select(WCVisitorStatsModel::class.java).asModel) {
assertEquals(2, size)
assertEquals(visitorStatsModel.unit, first().unit)
assertEquals(visitorStatsModel.startDate, first().startDate)
assertEquals(visitorStatsModel.endDate, first().endDate)
assertEquals(visitorStatsModel2.unit, get(1).unit)
assertEquals(visitorStatsModel2.startDate, get(1).startDate)
assertEquals(visitorStatsModel2.endDate, get(1).endDate)
}
// Create a third stats entry for this site with same interval but different start & end date
// i.e. custom stats
val visitorStatsModel3 =
WCStatsTestUtils.generateSampleVisitorStatsModel(
data = "fake-data2", startDate = "2019-07-07", endDate = "2019-07-13"
)
WCVisitorStatsSqlUtils.insertOrUpdateVisitorStats(visitorStatsModel3)
with(WellSql.select(WCVisitorStatsModel::class.java).asModel) {
assertEquals(3, size)
assertEquals(visitorStatsModel.unit, first().unit)
assertEquals(visitorStatsModel.startDate, first().startDate)
assertEquals(visitorStatsModel.endDate, first().endDate)
assertEquals(visitorStatsModel2.unit, get(1).unit)
assertEquals(visitorStatsModel2.startDate, get(1).startDate)
assertEquals(visitorStatsModel2.endDate, get(1).endDate)
assertEquals(visitorStatsModel3.unit, get(2).unit)
assertEquals(visitorStatsModel3.startDate, get(2).startDate)
assertEquals(visitorStatsModel3.endDate, get(2).endDate)
}
// Overwrite an existing entry and verify that update is happening correctly
val visitorStatsModel4 = WCStatsTestUtils.generateSampleVisitorStatsModel()
WCVisitorStatsSqlUtils.insertOrUpdateVisitorStats(visitorStatsModel4)
with(WellSql.select(WCVisitorStatsModel::class.java).asModel) {
assertEquals(3, size)
assertEquals(visitorStatsModel.unit, first().unit)
assertEquals(visitorStatsModel.startDate, first().startDate)
assertEquals(visitorStatsModel.endDate, first().endDate)
assertEquals(visitorStatsModel2.unit, get(1).unit)
assertEquals(visitorStatsModel2.startDate, get(1).startDate)
assertEquals(visitorStatsModel2.endDate, get(1).endDate)
assertEquals(visitorStatsModel3.unit, get(2).unit)
assertEquals(visitorStatsModel3.startDate, get(2).startDate)
assertEquals(visitorStatsModel3.endDate, get(2).endDate)
}
// Add another "day" entry, but for another site
val visitorStatsModel5 = WCStatsTestUtils.generateSampleVisitorStatsModel(localSiteId = 8)
WCVisitorStatsSqlUtils.insertOrUpdateVisitorStats(visitorStatsModel5)
with(WellSql.select(WCVisitorStatsModel::class.java).asModel) {
assertEquals(4, size)
assertEquals(visitorStatsModel.unit, first().unit)
assertEquals(visitorStatsModel.startDate, first().startDate)
assertEquals(visitorStatsModel.endDate, first().endDate)
assertEquals(visitorStatsModel2.unit, get(1).unit)
assertEquals(visitorStatsModel2.startDate, get(1).startDate)
assertEquals(visitorStatsModel2.endDate, get(1).endDate)
assertEquals(visitorStatsModel3.unit, get(2).unit)
assertEquals(visitorStatsModel3.startDate, get(2).startDate)
assertEquals(visitorStatsModel3.endDate, get(2).endDate)
assertEquals(visitorStatsModel5.unit, get(3).unit)
assertEquals(visitorStatsModel5.localSiteId, get(3).localSiteId)
assertEquals(visitorStatsModel5.startDate, get(3).startDate)
assertEquals(visitorStatsModel5.endDate, get(3).endDate)
}
}
@Test
fun testGetRawVisitorStatsForSiteAndUnit() {
val dayOrderStatsModel = WCStatsTestUtils.generateSampleVisitorStatsModel()
val site = SiteModel().apply { id = dayOrderStatsModel.localSiteId }
val monthOrderStatsModel = WCStatsTestUtils.generateSampleVisitorStatsModel(
unit = "month", fields = "fake-data", data = "fake-data"
)
WCVisitorStatsSqlUtils.insertOrUpdateVisitorStats(dayOrderStatsModel)
WCVisitorStatsSqlUtils.insertOrUpdateVisitorStats(monthOrderStatsModel)
val site2 = SiteModel().apply { id = 8 }
val altSiteOrderStatsModel = WCStatsTestUtils.generateSampleVisitorStatsModel(localSiteId = site2.id)
WCVisitorStatsSqlUtils.insertOrUpdateVisitorStats(altSiteOrderStatsModel)
val dayOrderStats = WCVisitorStatsSqlUtils.getRawVisitorStatsForSiteUnitQuantityAndDate(
site, OrderStatsApiUnit.DAY
)
assertNotNull(dayOrderStats)
with(dayOrderStats) {
assertEquals("day", unit)
assertEquals(false, isCustomField)
}
val dayOrderCustomStatsModel = WCStatsTestUtils.generateSampleVisitorStatsModel(startDate = "2019-01-15",
endDate = "2019-02-13")
WCVisitorStatsSqlUtils.insertOrUpdateVisitorStats(dayOrderCustomStatsModel)
val dayOrderCustomStats = WCVisitorStatsSqlUtils.getRawVisitorStatsForSiteUnitQuantityAndDate(
site, OrderStatsApiUnit.DAY, dayOrderCustomStatsModel.quantity,
dayOrderCustomStatsModel.date, dayOrderCustomStatsModel.isCustomField
)
assertNotNull(dayOrderCustomStats)
with(dayOrderCustomStats) {
assertEquals("day", unit)
assertEquals(true, isCustomField)
}
assertNotNull(dayOrderStats)
val altSiteDayOrderStats = WCVisitorStatsSqlUtils.getRawVisitorStatsForSiteUnitQuantityAndDate(
site2, OrderStatsApiUnit.DAY
)
assertNotNull(altSiteDayOrderStats)
val monthOrderStatus = WCVisitorStatsSqlUtils.getRawVisitorStatsForSiteUnitQuantityAndDate(
site, OrderStatsApiUnit.MONTH
)
assertNotNull(monthOrderStatus)
with(monthOrderStatus) {
assertEquals("month", unit)
assertEquals(false, isCustomField)
}
val nonExistentSite = WCVisitorStatsSqlUtils.getRawVisitorStatsForSiteUnitQuantityAndDate(
SiteModel().apply { id = 88 }, OrderStatsApiUnit.DAY
)
assertNull(nonExistentSite)
val missingData = WCVisitorStatsSqlUtils.getRawVisitorStatsForSiteUnitQuantityAndDate(
site, OrderStatsApiUnit.YEAR
)
assertNull(missingData)
}
@Test
@Suppress("LongMethod")
fun testSimpleInsertionAndRetrievalOfCustomVisitorStats() {
// Test Scenario - 1: Generate default stats with granularity - DAYS, quantity - 30, date - current date
// and isCustomField - false
// The total size of the local db table = 1
val defaultDayVisitorStatsModel = WCStatsTestUtils.generateSampleVisitorStatsModel()
WCVisitorStatsSqlUtils.insertOrUpdateVisitorStats(defaultDayVisitorStatsModel)
val site = SiteModel().apply { id = defaultDayVisitorStatsModel.localSiteId }
val defaultDayVisitorStats = WCVisitorStatsSqlUtils.getRawVisitorStatsForSiteUnitQuantityAndDate(
site, OrderStatsApiUnit.DAY
)
assertEquals(defaultDayVisitorStatsModel.unit, defaultDayVisitorStats?.unit)
assertEquals(defaultDayVisitorStatsModel.quantity, defaultDayVisitorStats?.quantity)
assertEquals(defaultDayVisitorStatsModel.date, defaultDayVisitorStats?.date)
assertEquals(defaultDayVisitorStatsModel.isCustomField, defaultDayVisitorStats?.isCustomField)
with(WellSql.select(WCVisitorStatsModel::class.java).asModel) {
assertEquals(1, size)
}
// Test Scenario - 2: Generate custom stats for same site with granularity - DAYS, quantity - 1,
// date - 2019-01-01 and isCustomField - true
// The total size of the local db table = 2
val customDayVisitorStatsModel = WCStatsTestUtils.generateSampleVisitorStatsModel(
quantity = "1", endDate = "2019-01-01", startDate = "2018-12-31"
)
WCVisitorStatsSqlUtils.insertOrUpdateVisitorStats(customDayVisitorStatsModel)
val customDayVisitorStats = WCVisitorStatsSqlUtils.getRawVisitorStatsForSiteUnitQuantityAndDate(
site, OrderStatsApiUnit.DAY, customDayVisitorStatsModel.quantity,
customDayVisitorStatsModel.date, customDayVisitorStatsModel.isCustomField
)
assertEquals(customDayVisitorStatsModel.unit, customDayVisitorStats?.unit)
assertEquals(customDayVisitorStatsModel.quantity, customDayVisitorStats?.quantity)
assertEquals(customDayVisitorStatsModel.endDate, customDayVisitorStats?.endDate)
assertEquals(customDayVisitorStatsModel.startDate, customDayVisitorStats?.startDate)
assertEquals(customDayVisitorStatsModel.date, customDayVisitorStats?.date)
assertEquals(customDayVisitorStatsModel.isCustomField, customDayVisitorStats?.isCustomField)
with(WellSql.select(WCVisitorStatsModel::class.java).asModel) {
assertEquals(2, size)
}
// Test Scenario - 3: Overwrite an existing default stats for same site, same unit, same quantity and same date,
// The total size of the local db table = 2 (since no new data is inserted)
val defaultDayVisitorStatsModel2 = WCStatsTestUtils.generateSampleVisitorStatsModel()
WCVisitorStatsSqlUtils.insertOrUpdateVisitorStats(defaultDayVisitorStatsModel2)
val defaultDayVisitorStats2 = WCVisitorStatsSqlUtils.getRawVisitorStatsForSiteUnitQuantityAndDate(
site, OrderStatsApiUnit.DAY
)
assertEquals(defaultDayVisitorStatsModel2.unit, defaultDayVisitorStats2?.unit)
assertEquals(defaultDayVisitorStatsModel2.quantity, defaultDayVisitorStats2?.quantity)
assertEquals(defaultDayVisitorStatsModel2.date, defaultDayVisitorStats2?.date)
assertEquals(defaultDayVisitorStatsModel2.isCustomField, defaultDayVisitorStats2?.isCustomField)
assertEquals("", defaultDayVisitorStats2?.startDate)
with(WellSql.select(WCVisitorStatsModel::class.java).asModel) {
assertEquals(2, size)
}
// Test Scenario - 4: Overwrite an existing custom stats for same site, same unit, same quantity and same date,
// The total size of the local db table = 2 (since no new data is inserted)
val customDayVisitorStatsModel2 = WCStatsTestUtils.generateSampleVisitorStatsModel(
quantity = "1", endDate = "2019-01-01", startDate = "2018-12-31"
)
WCVisitorStatsSqlUtils.insertOrUpdateVisitorStats(customDayVisitorStatsModel2)
val customDayVisitorStats2 = WCVisitorStatsSqlUtils.getRawVisitorStatsForSiteUnitQuantityAndDate(
site, OrderStatsApiUnit.DAY, customDayVisitorStatsModel2.quantity,
customDayVisitorStatsModel2.endDate, customDayVisitorStatsModel2.isCustomField
)
assertEquals(customDayVisitorStatsModel2.unit, customDayVisitorStats2?.unit)
assertEquals(customDayVisitorStatsModel2.quantity, customDayVisitorStats2?.quantity)
assertEquals(customDayVisitorStatsModel2.endDate, customDayVisitorStats2?.endDate)
assertEquals(customDayVisitorStatsModel2.startDate, customDayVisitorStats2?.startDate)
assertEquals(customDayVisitorStatsModel2.date, customDayVisitorStats2?.date)
assertEquals(customDayVisitorStatsModel2.isCustomField, customDayVisitorStats2?.isCustomField)
with(WellSql.select(WCVisitorStatsModel::class.java).asModel) {
assertEquals(2, size)
}
// Test Scenario - 5: Overwrite an existing custom stats for same site, unit, quantity but different date,
// The total size of the local db table = 2 (since no old data was purged and new data was inserted)
val customDayVisitorStatsModel3 = WCStatsTestUtils.generateSampleVisitorStatsModel(
quantity = "1", endDate = "2018-12-31", startDate = "2018-12-31"
)
WCVisitorStatsSqlUtils.insertOrUpdateVisitorStats(customDayVisitorStatsModel3)
val customDayVisitorStats3 = WCVisitorStatsSqlUtils.getRawVisitorStatsForSiteUnitQuantityAndDate(
site, OrderStatsApiUnit.DAY, customDayVisitorStatsModel3.quantity,
customDayVisitorStatsModel3.endDate, customDayVisitorStatsModel3.isCustomField
)
assertEquals(customDayVisitorStatsModel3.unit, customDayVisitorStats3?.unit)
assertEquals(customDayVisitorStatsModel3.quantity, customDayVisitorStats3?.quantity)
assertEquals(customDayVisitorStatsModel3.endDate, customDayVisitorStats3?.endDate)
assertEquals(customDayVisitorStatsModel3.startDate, customDayVisitorStats3?.startDate)
assertEquals(customDayVisitorStatsModel3.date, customDayVisitorStats3?.date)
assertEquals(customDayVisitorStatsModel3.isCustomField, customDayVisitorStats3?.isCustomField)
/* expected size of local cache would still be 2 because there can only be one
* custom stats row stored in local cache at any point of time. Before storing incoming data,
* the existing data will be purged */
with(WellSql.select(WCVisitorStatsModel::class.java).asModel) {
assertEquals(2, size)
}
// Test Scenario - 6: Generate default stats for same site with different unit,
// The total size of the local db table = 3 (since stats with DAYS granularity would be stored already)
val defaultWeekVisitorStatsModel = WCStatsTestUtils.generateSampleVisitorStatsModel(
unit = OrderStatsApiUnit.WEEK.toString(), quantity = "17"
)
WCVisitorStatsSqlUtils.insertOrUpdateVisitorStats(defaultWeekVisitorStatsModel)
val defaultWeekVisitorStats = WCVisitorStatsSqlUtils.getRawVisitorStatsForSiteUnitQuantityAndDate(
site, OrderStatsApiUnit.WEEK
)
assertEquals(defaultWeekVisitorStatsModel.unit, defaultWeekVisitorStats?.unit)
assertEquals(defaultWeekVisitorStatsModel.quantity, defaultWeekVisitorStats?.quantity)
assertEquals(defaultWeekVisitorStatsModel.endDate, defaultWeekVisitorStats?.endDate)
assertEquals(defaultWeekVisitorStatsModel.date, defaultWeekVisitorStats?.date)
assertEquals(defaultWeekVisitorStatsModel.isCustomField, defaultWeekVisitorStats?.isCustomField)
assertEquals("", defaultWeekVisitorStats?.startDate)
with(WellSql.select(WCVisitorStatsModel::class.java).asModel) {
assertEquals(3, size)
}
// Test Scenario - 7: Generate custom stats for same site with different unit:
// The total size of the local db table = 3 (since stats with DAYS granularity would be stored already)
val customWeekVisitorStatsModel = WCStatsTestUtils.generateSampleVisitorStatsModel(
unit = OrderStatsApiUnit.WEEK.toString(), quantity = "2",
endDate = "2019-01-28", startDate = "2019-01-25"
)
WCVisitorStatsSqlUtils.insertOrUpdateVisitorStats(customWeekVisitorStatsModel)
val customWeekVisitorStats = WCVisitorStatsSqlUtils.getRawVisitorStatsForSiteUnitQuantityAndDate(
site, OrderStatsApiUnit.WEEK, customWeekVisitorStatsModel.quantity,
customWeekVisitorStatsModel.date, customWeekVisitorStatsModel.isCustomField
)
assertEquals(customWeekVisitorStatsModel.unit, customWeekVisitorStats?.unit)
assertEquals(customWeekVisitorStatsModel.quantity, customWeekVisitorStats?.quantity)
assertEquals(customWeekVisitorStatsModel.endDate, customWeekVisitorStats?.endDate)
assertEquals(customWeekVisitorStatsModel.startDate, customWeekVisitorStats?.startDate)
assertEquals(customWeekVisitorStatsModel.date, customWeekVisitorStats?.date)
assertEquals(customWeekVisitorStatsModel.isCustomField, customWeekVisitorStats?.isCustomField)
with(WellSql.select(WCVisitorStatsModel::class.java).asModel) {
assertEquals(3, size)
}
// Test Scenario - 8: Generate default stats for different site with different unit:
// The total size of the local db table = 5 (since stats with DAYS and WEEKS data would be stored already)
val site2 = SiteModel().apply { id = 8 }
val defaultMonthVisitorStatsModel = WCStatsTestUtils.generateSampleVisitorStatsModel(
localSiteId = site2.id, unit = OrderStatsApiUnit.MONTH.toString(), quantity = "12"
)
WCVisitorStatsSqlUtils.insertOrUpdateVisitorStats(defaultMonthVisitorStatsModel)
val defaultMonthVisitorStats = WCVisitorStatsSqlUtils.getRawVisitorStatsForSiteUnitQuantityAndDate(
site2, OrderStatsApiUnit.MONTH
)
assertEquals(defaultMonthVisitorStatsModel.unit, defaultMonthVisitorStats?.unit)
assertEquals(defaultMonthVisitorStatsModel.quantity, defaultMonthVisitorStats?.quantity)
assertEquals(defaultMonthVisitorStatsModel.date, defaultMonthVisitorStats?.date)
assertEquals(defaultMonthVisitorStatsModel.isCustomField, defaultMonthVisitorStats?.isCustomField)
assertEquals("", defaultMonthVisitorStats?.startDate)
with(WellSql.select(WCVisitorStatsModel::class.java).asModel) {
assertEquals(4, size)
}
// Test Scenario - 9: Generate custom stats for different site with different unit and different date
// The total size of the local db table = 5 (since 3 default stats for another site would be stored already
// and 1 stats for site 8 would be stored). No purging of data would take place
val customMonthVisitorStatsModel = WCStatsTestUtils.generateSampleVisitorStatsModel(
localSiteId = site2.id, unit = OrderStatsApiUnit.MONTH.toString(), quantity = "2",
endDate = "2019-01-28", startDate = "2018-12-31"
)
WCVisitorStatsSqlUtils.insertOrUpdateVisitorStats(customMonthVisitorStatsModel)
val customMonthVisitorStats = WCVisitorStatsSqlUtils.getRawVisitorStatsForSiteUnitQuantityAndDate(
site2, OrderStatsApiUnit.MONTH, customMonthVisitorStatsModel.quantity,
customMonthVisitorStatsModel.date, customMonthVisitorStatsModel.isCustomField
)
assertEquals(customMonthVisitorStatsModel.unit, customMonthVisitorStats?.unit)
assertEquals(customMonthVisitorStatsModel.quantity, customMonthVisitorStats?.quantity)
assertEquals(customMonthVisitorStatsModel.endDate, customMonthVisitorStats?.endDate)
assertEquals(customMonthVisitorStatsModel.startDate, customMonthVisitorStats?.startDate)
assertEquals(customMonthVisitorStatsModel.date, customMonthVisitorStats?.date)
assertEquals(customMonthVisitorStatsModel.isCustomField, customMonthVisitorStats?.isCustomField)
with(WellSql.select(WCVisitorStatsModel::class.java).asModel) {
assertEquals(5, size)
}
// Test Scenario - 10: Check for missing stats data. Query should return null
val missingData = WCVisitorStatsSqlUtils.getRawVisitorStatsForSiteUnitQuantityAndDate(
site2, OrderStatsApiUnit.YEAR, "1", "2019-01-01"
)
assertNull(missingData)
// Test Scenario - 11: Fetch data with only site(8) and granularity (MONTHS)
val defaultVisitorStats = WCVisitorStatsSqlUtils.getRawVisitorStatsForSiteUnitQuantityAndDate(
site2, OrderStatsApiUnit.MONTH
)
assertNotNull(defaultVisitorStats)
assertEquals(OrderStatsApiUnit.MONTH.toString(), defaultVisitorStats.unit)
}
@Test
@Suppress("LongMethod")
fun testSimpleInsertionAndRetrievalOfNewVisitorStats() {
// insert a visitor stats entry and verify that it is stored correctly
val visitorStatsModel = WCStatsTestUtils.generateSampleNewVisitorStatsModel()
WCVisitorStatsSqlUtils.insertOrUpdateNewVisitorStats(visitorStatsModel)
with(WellSql.select(WCNewVisitorStatsModel::class.java).asModel) {
assertEquals(1, size)
assertEquals(visitorStatsModel.granularity, first().granularity)
assertEquals(visitorStatsModel.startDate, first().startDate)
assertEquals(visitorStatsModel.endDate, first().endDate)
}
// Create a second visitor stats entry for this site with same quantity but with different unit
val visitorStatsModel2 = WCStatsTestUtils.generateSampleNewVisitorStatsModel(
granularity = StatsGranularity.MONTHS.toString(), quantity = "12", data = "fake-data"
)
WCVisitorStatsSqlUtils.insertOrUpdateNewVisitorStats(visitorStatsModel2)
with(WellSql.select(WCNewVisitorStatsModel::class.java).asModel) {
assertEquals(2, size)
assertEquals(visitorStatsModel.granularity, first().granularity)
assertEquals(visitorStatsModel.startDate, first().startDate)
assertEquals(visitorStatsModel.endDate, first().endDate)
assertEquals(visitorStatsModel2.granularity, get(1).granularity)
assertEquals(visitorStatsModel2.startDate, get(1).startDate)
assertEquals(visitorStatsModel2.endDate, get(1).endDate)
}
// Create a third stats entry for this site with same interval but different start & end date
// i.e. custom stats
val visitorStatsModel3 =
WCStatsTestUtils.generateSampleNewVisitorStatsModel(
data = "fake-data2", startDate = "2019-07-07", endDate = "2019-07-13"
)
WCVisitorStatsSqlUtils.insertOrUpdateNewVisitorStats(visitorStatsModel3)
with(WellSql.select(WCNewVisitorStatsModel::class.java).asModel) {
assertEquals(3, size)
assertEquals(visitorStatsModel.granularity, first().granularity)
assertEquals(visitorStatsModel.startDate, first().startDate)
assertEquals(visitorStatsModel.endDate, first().endDate)
assertEquals(visitorStatsModel2.granularity, get(1).granularity)
assertEquals(visitorStatsModel2.startDate, get(1).startDate)
assertEquals(visitorStatsModel2.endDate, get(1).endDate)
assertEquals(visitorStatsModel3.granularity, get(2).granularity)
assertEquals(visitorStatsModel3.startDate, get(2).startDate)
assertEquals(visitorStatsModel3.endDate, get(2).endDate)
}
// Overwrite an existing entry and verify that update is happening correctly
val visitorStatsModel4 = WCStatsTestUtils.generateSampleNewVisitorStatsModel()
WCVisitorStatsSqlUtils.insertOrUpdateNewVisitorStats(visitorStatsModel4)
with(WellSql.select(WCNewVisitorStatsModel::class.java).asModel) {
assertEquals(3, size)
assertEquals(visitorStatsModel.granularity, first().granularity)
assertEquals(visitorStatsModel.startDate, first().startDate)
assertEquals(visitorStatsModel.endDate, first().endDate)
assertEquals(visitorStatsModel2.granularity, get(1).granularity)
assertEquals(visitorStatsModel2.startDate, get(1).startDate)
assertEquals(visitorStatsModel2.endDate, get(1).endDate)
assertEquals(visitorStatsModel3.granularity, get(2).granularity)
assertEquals(visitorStatsModel3.startDate, get(2).startDate)
assertEquals(visitorStatsModel3.endDate, get(2).endDate)
}
// Add another "day" entry, but for another site
val visitorStatsModel5 = WCStatsTestUtils.generateSampleNewVisitorStatsModel(localSiteId = 8)
WCVisitorStatsSqlUtils.insertOrUpdateNewVisitorStats(visitorStatsModel5)
with(WellSql.select(WCNewVisitorStatsModel::class.java).asModel) {
assertEquals(4, size)
assertEquals(visitorStatsModel.granularity, first().granularity)
assertEquals(visitorStatsModel.startDate, first().startDate)
assertEquals(visitorStatsModel.endDate, first().endDate)
assertEquals(visitorStatsModel2.granularity, get(1).granularity)
assertEquals(visitorStatsModel2.startDate, get(1).startDate)
assertEquals(visitorStatsModel2.endDate, get(1).endDate)
assertEquals(visitorStatsModel3.granularity, get(2).granularity)
assertEquals(visitorStatsModel3.startDate, get(2).startDate)
assertEquals(visitorStatsModel3.endDate, get(2).endDate)
assertEquals(visitorStatsModel5.granularity, get(3).granularity)
assertEquals(visitorStatsModel5.localSiteId, get(3).localSiteId)
assertEquals(visitorStatsModel5.startDate, get(3).startDate)
assertEquals(visitorStatsModel5.endDate, get(3).endDate)
}
}
@Test
fun testGetNewRawVisitorStatsForSiteAndGranularity() {
val dayOrderStatsModel = WCStatsTestUtils.generateSampleNewVisitorStatsModel()
val site = SiteModel().apply { id = dayOrderStatsModel.localSiteId }
val monthOrderStatsModel = WCStatsTestUtils.generateSampleNewVisitorStatsModel(
granularity = StatsGranularity.MONTHS.toString(), fields = "fake-data", data = "fake-data"
)
WCVisitorStatsSqlUtils.insertOrUpdateNewVisitorStats(dayOrderStatsModel)
WCVisitorStatsSqlUtils.insertOrUpdateNewVisitorStats(monthOrderStatsModel)
val site2 = SiteModel().apply { id = 8 }
val altSiteOrderStatsModel = WCStatsTestUtils.generateSampleNewVisitorStatsModel(localSiteId = site2.id)
WCVisitorStatsSqlUtils.insertOrUpdateNewVisitorStats(altSiteOrderStatsModel)
val dayOrderStats = WCVisitorStatsSqlUtils.getNewRawVisitorStatsForSiteGranularityQuantityAndDate(
site, StatsGranularity.DAYS
)
assertNotNull(dayOrderStats)
with(dayOrderStats) {
assertEquals(dayOrderStatsModel.granularity, granularity)
assertEquals(false, isCustomField)
}
val dayOrderCustomStatsModel = WCStatsTestUtils.generateSampleNewVisitorStatsModel(startDate = "2019-01-15",
endDate = "2019-02-13")
WCVisitorStatsSqlUtils.insertOrUpdateNewVisitorStats(dayOrderCustomStatsModel)
val dayOrderCustomStats = WCVisitorStatsSqlUtils.getNewRawVisitorStatsForSiteGranularityQuantityAndDate(
site, StatsGranularity.DAYS, dayOrderCustomStatsModel.quantity,
dayOrderCustomStatsModel.date, dayOrderCustomStatsModel.isCustomField
)
assertNotNull(dayOrderCustomStats)
with(dayOrderCustomStats) {
assertEquals(dayOrderCustomStatsModel.granularity, granularity)
assertEquals(true, isCustomField)
}
assertNotNull(dayOrderStats)
val altSiteDayOrderStats = WCVisitorStatsSqlUtils.getNewRawVisitorStatsForSiteGranularityQuantityAndDate(
site2, StatsGranularity.DAYS
)
assertNotNull(altSiteDayOrderStats)
val monthOrderStatus = WCVisitorStatsSqlUtils.getNewRawVisitorStatsForSiteGranularityQuantityAndDate(
site, StatsGranularity.MONTHS
)
assertNotNull(monthOrderStatus)
with(monthOrderStatus) {
assertEquals(monthOrderStatsModel.granularity, granularity)
assertEquals(false, isCustomField)
}
val nonExistentSite = WCVisitorStatsSqlUtils.getNewRawVisitorStatsForSiteGranularityQuantityAndDate(
SiteModel().apply { id = 88 }, StatsGranularity.DAYS
)
assertNull(nonExistentSite)
val missingData = WCVisitorStatsSqlUtils.getNewRawVisitorStatsForSiteGranularityQuantityAndDate(
site, StatsGranularity.YEARS
)
assertNull(missingData)
}
@Test
@Suppress("LongMethod")
fun testSimpleInsertionAndRetrievalOfNewCustomVisitorStats() {
// Test Scenario - 1: Generate default stats with granularity - DAYS, quantity - 30, date - current date
// and isCustomField - false
// The total size of the local db table = 1
val defaultDayVisitorStatsModel = WCStatsTestUtils.generateSampleNewVisitorStatsModel()
WCVisitorStatsSqlUtils.insertOrUpdateNewVisitorStats(defaultDayVisitorStatsModel)
val site = SiteModel().apply { id = defaultDayVisitorStatsModel.localSiteId }
val defaultDayVisitorStats = WCVisitorStatsSqlUtils.getNewRawVisitorStatsForSiteGranularityQuantityAndDate(
site, StatsGranularity.DAYS
)
assertEquals(defaultDayVisitorStatsModel.granularity, defaultDayVisitorStats?.granularity)
assertEquals(defaultDayVisitorStatsModel.quantity, defaultDayVisitorStats?.quantity)
assertEquals(defaultDayVisitorStatsModel.date, defaultDayVisitorStats?.date)
assertEquals(defaultDayVisitorStatsModel.isCustomField, defaultDayVisitorStats?.isCustomField)
with(WellSql.select(WCNewVisitorStatsModel::class.java).asModel) {
assertEquals(1, size)
}
// Test Scenario - 2: Generate custom stats for same site with granularity - DAYS, quantity - 1,
// date - 2019-01-01 and isCustomField - true
// The total size of the local db table = 2
val customDayVisitorStatsModel = WCStatsTestUtils.generateSampleNewVisitorStatsModel(
quantity = "1", endDate = "2019-01-01", startDate = "2018-12-31"
)
WCVisitorStatsSqlUtils.insertOrUpdateNewVisitorStats(customDayVisitorStatsModel)
val customDayVisitorStats = WCVisitorStatsSqlUtils.getNewRawVisitorStatsForSiteGranularityQuantityAndDate(
site, StatsGranularity.DAYS, customDayVisitorStatsModel.quantity,
customDayVisitorStatsModel.date, customDayVisitorStatsModel.isCustomField
)
assertEquals(customDayVisitorStatsModel.granularity, customDayVisitorStats?.granularity)
assertEquals(customDayVisitorStatsModel.quantity, customDayVisitorStats?.quantity)
assertEquals(customDayVisitorStatsModel.endDate, customDayVisitorStats?.endDate)
assertEquals(customDayVisitorStatsModel.startDate, customDayVisitorStats?.startDate)
assertEquals(customDayVisitorStatsModel.date, customDayVisitorStats?.date)
assertEquals(customDayVisitorStatsModel.isCustomField, customDayVisitorStats?.isCustomField)
with(WellSql.select(WCNewVisitorStatsModel::class.java).asModel) {
assertEquals(2, size)
}
// Test Scenario - 3: Overwrite an existing default stats for same site, same unit, same quantity and same date,
// The total size of the local db table = 2 (since no new data is inserted)
val defaultDayVisitorStatsModel2 = WCStatsTestUtils.generateSampleNewVisitorStatsModel()
WCVisitorStatsSqlUtils.insertOrUpdateNewVisitorStats(defaultDayVisitorStatsModel2)
val defaultDayVisitorStats2 = WCVisitorStatsSqlUtils.getNewRawVisitorStatsForSiteGranularityQuantityAndDate(
site, StatsGranularity.DAYS
)
assertEquals(defaultDayVisitorStatsModel2.granularity, defaultDayVisitorStats2?.granularity)
assertEquals(defaultDayVisitorStatsModel2.quantity, defaultDayVisitorStats2?.quantity)
assertEquals(defaultDayVisitorStatsModel2.date, defaultDayVisitorStats2?.date)
assertEquals(defaultDayVisitorStatsModel2.isCustomField, defaultDayVisitorStats2?.isCustomField)
assertEquals("", defaultDayVisitorStats2?.startDate)
with(WellSql.select(WCNewVisitorStatsModel::class.java).asModel) {
assertEquals(2, size)
}
// Test Scenario - 4: Overwrite an existing custom stats for same site, same unit, same quantity and same date,
// The total size of the local db table = 2 (since no new data is inserted)
val customDayVisitorStatsModel2 = WCStatsTestUtils.generateSampleNewVisitorStatsModel(
quantity = "1", endDate = "2019-01-01", startDate = "2018-12-31"
)
WCVisitorStatsSqlUtils.insertOrUpdateNewVisitorStats(customDayVisitorStatsModel2)
val customDayVisitorStats2 = WCVisitorStatsSqlUtils.getNewRawVisitorStatsForSiteGranularityQuantityAndDate(
site, StatsGranularity.DAYS, customDayVisitorStatsModel2.quantity,
customDayVisitorStatsModel2.endDate, customDayVisitorStatsModel2.isCustomField
)
assertEquals(customDayVisitorStatsModel2.granularity, customDayVisitorStats2?.granularity)
assertEquals(customDayVisitorStatsModel2.quantity, customDayVisitorStats2?.quantity)
assertEquals(customDayVisitorStatsModel2.endDate, customDayVisitorStats2?.endDate)
assertEquals(customDayVisitorStatsModel2.startDate, customDayVisitorStats2?.startDate)
assertEquals(customDayVisitorStatsModel2.date, customDayVisitorStats2?.date)
assertEquals(customDayVisitorStatsModel2.isCustomField, customDayVisitorStats2?.isCustomField)
with(WellSql.select(WCNewVisitorStatsModel::class.java).asModel) {
assertEquals(2, size)
}
// Test Scenario - 5: Overwrite an existing custom stats for same site, unit, quantity but different date,
// The total size of the local db table = 2 (since no old data was purged and new data was inserted)
val customDayVisitorStatsModel3 = WCStatsTestUtils.generateSampleNewVisitorStatsModel(
quantity = "1", endDate = "2018-12-31", startDate = "2018-12-31"
)
WCVisitorStatsSqlUtils.insertOrUpdateNewVisitorStats(customDayVisitorStatsModel3)
val customDayVisitorStats3 = WCVisitorStatsSqlUtils.getNewRawVisitorStatsForSiteGranularityQuantityAndDate(
site, StatsGranularity.DAYS, customDayVisitorStatsModel3.quantity,
customDayVisitorStatsModel3.endDate, customDayVisitorStatsModel3.isCustomField
)
assertEquals(customDayVisitorStatsModel3.granularity, customDayVisitorStats3?.granularity)
assertEquals(customDayVisitorStatsModel3.quantity, customDayVisitorStats3?.quantity)
assertEquals(customDayVisitorStatsModel3.endDate, customDayVisitorStats3?.endDate)
assertEquals(customDayVisitorStatsModel3.startDate, customDayVisitorStats3?.startDate)
assertEquals(customDayVisitorStatsModel3.date, customDayVisitorStats3?.date)
assertEquals(customDayVisitorStatsModel3.isCustomField, customDayVisitorStats3?.isCustomField)
/* expected size of local cache would still be 2 because there can only be one
* custom stats row stored in local cache at any point of time. Before storing incoming data,
* the existing data will be purged */
with(WellSql.select(WCNewVisitorStatsModel::class.java).asModel) {
assertEquals(2, size)
}
// Test Scenario - 6: Generate default stats for same site with different unit,
// The total size of the local db table = 3 (since stats with DAYS granularity would be stored already)
val defaultWeekVisitorStatsModel = WCStatsTestUtils.generateSampleNewVisitorStatsModel(
granularity = StatsGranularity.WEEKS.toString(), quantity = "17"
)
WCVisitorStatsSqlUtils.insertOrUpdateNewVisitorStats(defaultWeekVisitorStatsModel)
val defaultWeekVisitorStats = WCVisitorStatsSqlUtils.getNewRawVisitorStatsForSiteGranularityQuantityAndDate(
site, StatsGranularity.WEEKS
)
assertEquals(defaultWeekVisitorStatsModel.granularity, defaultWeekVisitorStats?.granularity)
assertEquals(defaultWeekVisitorStatsModel.quantity, defaultWeekVisitorStats?.quantity)
assertEquals(defaultWeekVisitorStatsModel.endDate, defaultWeekVisitorStats?.endDate)
assertEquals(defaultWeekVisitorStatsModel.date, defaultWeekVisitorStats?.date)
assertEquals(defaultWeekVisitorStatsModel.isCustomField, defaultWeekVisitorStats?.isCustomField)
assertEquals("", defaultWeekVisitorStats?.startDate)
with(WellSql.select(WCNewVisitorStatsModel::class.java).asModel) {
assertEquals(3, size)
}
// Test Scenario - 7: Generate custom stats for same site with different unit:
// The total size of the local db table = 3 (since stats with DAYS granularity would be stored already)
val customWeekVisitorStatsModel = WCStatsTestUtils.generateSampleNewVisitorStatsModel(
granularity = StatsGranularity.WEEKS.toString(), quantity = "2",
endDate = "2019-01-28", startDate = "2019-01-25"
)
WCVisitorStatsSqlUtils.insertOrUpdateNewVisitorStats(customWeekVisitorStatsModel)
val customWeekVisitorStats = WCVisitorStatsSqlUtils.getNewRawVisitorStatsForSiteGranularityQuantityAndDate(
site, StatsGranularity.WEEKS, customWeekVisitorStatsModel.quantity,
customWeekVisitorStatsModel.date, customWeekVisitorStatsModel.isCustomField
)
assertEquals(customWeekVisitorStatsModel.granularity, customWeekVisitorStats?.granularity)
assertEquals(customWeekVisitorStatsModel.quantity, customWeekVisitorStats?.quantity)
assertEquals(customWeekVisitorStatsModel.endDate, customWeekVisitorStats?.endDate)
assertEquals(customWeekVisitorStatsModel.startDate, customWeekVisitorStats?.startDate)
assertEquals(customWeekVisitorStatsModel.date, customWeekVisitorStats?.date)
assertEquals(customWeekVisitorStatsModel.isCustomField, customWeekVisitorStats?.isCustomField)
with(WellSql.select(WCNewVisitorStatsModel::class.java).asModel) {
assertEquals(3, size)
}
// Test Scenario - 8: Generate default stats for different site with different unit:
// The total size of the local db table = 5 (since stats with DAYS and WEEKS data would be stored already)
val site2 = SiteModel().apply { id = 8 }
val defaultMonthVisitorStatsModel = WCStatsTestUtils.generateSampleNewVisitorStatsModel(
localSiteId = site2.id, granularity = StatsGranularity.MONTHS.toString(), quantity = "12"
)
WCVisitorStatsSqlUtils.insertOrUpdateNewVisitorStats(defaultMonthVisitorStatsModel)
val defaultMonthVisitorStats = WCVisitorStatsSqlUtils.getNewRawVisitorStatsForSiteGranularityQuantityAndDate(
site2, StatsGranularity.MONTHS
)
assertEquals(defaultMonthVisitorStatsModel.granularity, defaultMonthVisitorStats?.granularity)
assertEquals(defaultMonthVisitorStatsModel.quantity, defaultMonthVisitorStats?.quantity)
assertEquals(defaultMonthVisitorStatsModel.date, defaultMonthVisitorStats?.date)
assertEquals(defaultMonthVisitorStatsModel.isCustomField, defaultMonthVisitorStats?.isCustomField)
assertEquals("", defaultMonthVisitorStats?.startDate)
with(WellSql.select(WCNewVisitorStatsModel::class.java).asModel) {
assertEquals(4, size)
}
// Test Scenario - 9: Generate custom stats for different site with different unit and different date
// The total size of the local db table = 5 (since 3 default stats for another site would be stored already
// and 1 stats for site 8 would be stored). No purging of data would take place
val customMonthVisitorStatsModel = WCStatsTestUtils.generateSampleNewVisitorStatsModel(
localSiteId = site2.id, granularity = StatsGranularity.MONTHS.toString(), quantity = "2",
endDate = "2019-01-28", startDate = "2018-12-31"
)
WCVisitorStatsSqlUtils.insertOrUpdateNewVisitorStats(customMonthVisitorStatsModel)
val customMonthVisitorStats = WCVisitorStatsSqlUtils.getNewRawVisitorStatsForSiteGranularityQuantityAndDate(
site2, StatsGranularity.MONTHS, customMonthVisitorStatsModel.quantity,
customMonthVisitorStatsModel.date, customMonthVisitorStatsModel.isCustomField
)
assertEquals(customMonthVisitorStatsModel.granularity, customMonthVisitorStats?.granularity)
assertEquals(customMonthVisitorStatsModel.quantity, customMonthVisitorStats?.quantity)
assertEquals(customMonthVisitorStatsModel.endDate, customMonthVisitorStats?.endDate)
assertEquals(customMonthVisitorStatsModel.startDate, customMonthVisitorStats?.startDate)
assertEquals(customMonthVisitorStatsModel.date, customMonthVisitorStats?.date)
assertEquals(customMonthVisitorStatsModel.isCustomField, customMonthVisitorStats?.isCustomField)
with(WellSql.select(WCNewVisitorStatsModel::class.java).asModel) {
assertEquals(5, size)
}
// Test Scenario - 10: Check for missing stats data. Query should return null
val missingData = WCVisitorStatsSqlUtils.getNewRawVisitorStatsForSiteGranularityQuantityAndDate(
site2, StatsGranularity.YEARS, "1", "2019-01-01"
)
assertNull(missingData)
// Test Scenario - 11: Fetch data with only site(8) and granularity (MONTHS)
val defaultVisitorStats = WCVisitorStatsSqlUtils.getNewRawVisitorStatsForSiteGranularityQuantityAndDate(
site2, StatsGranularity.MONTHS
)
assertNotNull(defaultVisitorStats)
assertEquals(StatsGranularity.MONTHS.toString(), defaultVisitorStats.granularity)
}
}
| gpl-2.0 | 1e7a02bb35f8627384536040e0246349 | 55.445722 | 120 | 0.731905 | 4.801934 | false | true | false | false |
googlemaps/android-samples | ApiDemos/kotlin/app/src/gms/java/com/example/kotlindemos/RetainMapDemoActivity.kt | 1 | 1839 | // Copyright 2020 Google LLC
//
// 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.example.kotlindemos
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.MarkerOptions
import com.google.maps.android.ktx.addMarker
import com.google.maps.android.ktx.awaitMap
/**
* This shows how to retain a map across activity restarts (e.g., from screen rotations), which can
* be faster than relying on state serialization.
*/
class RetainMapDemoActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_basic_map_demo)
val mapFragment = supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragment
if (savedInstanceState == null) {
// First incarnation of this activity.
mapFragment.retainInstance = true
}
lifecycleScope.launchWhenCreated {
val map = mapFragment.awaitMap()
map.addMarker {
position(LatLng(0.0, 0.0))
title("Marker")
}
}
}
} | apache-2.0 | adbe7f18bc131f22d5a8befbbb26cd8b | 37.333333 | 99 | 0.756389 | 4.296729 | false | false | false | false |
Kiskae/Twitch-Archiver | twitch/src/main/kotlin/net/serverpeon/twitcharchiver/twitch/playlist/TwitchHlsPlaylist.kt | 1 | 6950 | package net.serverpeon.twitcharchiver.twitch.playlist
import com.google.common.base.Preconditions.checkState
import com.google.common.collect.ImmutableList
import com.google.common.collect.Lists
import com.google.common.io.Resources
import net.serverpeon.twitcharchiver.hls.*
import net.serverpeon.twitcharchiver.hls.OfficialTags.toDuration
import okhttp3.HttpUrl
import org.slf4j.LoggerFactory
import java.net.URI
import java.time.Duration
internal object TwitchHlsPlaylist {
private const val END_OFFSET_PARAM = "end_offset"
// Experimentally determined to be the maximum Twitch allows
// Any longer and it refuses to respond correctly.
private val TWITCH_MAXIMUM_SEGMENT_DURATION = Duration.ofSeconds(19)
private val log = LoggerFactory.getLogger(TwitchHlsPlaylist::class.java)
private val REDUCE_DISABLED = System.getProperty("twitch.dontreduce", "false").toBoolean()
private val HLS_ENCODING_PROPS = EncodingDescription(
ImmutableList.of("-bsf:a", "aac_adtstoasc"),
EncodingDescription.IOType.INPUT_CONCAT
)
init {
if (REDUCE_DISABLED) {
log.info("Playlist reduction disabled")
}
}
private val EXT_X_TWITCH_TOTAL_SECS: HlsTag<Duration> = HlsTag("EXT-X-TWITCH-TOTAL-SECS", appliesTo = HlsTag.AppliesTo.ENTIRE_PLAYLIST) {
it.toDuration()
}
val TWITCH_HLS_TAG_REPOSITORY: TagRepository = TagRepository.newRepository().apply {
register(EXT_X_TWITCH_TOTAL_SECS)
fun String.toResolution(): AttributeListParser.Resolution {
return if (this[0] == '"') {
this.substring(1, this.length - 1)
} else {
this
}.let { resolution ->
val pivot = resolution.indexOf('x')
checkState(pivot != -1 && (pivot < resolution.length - 1), "Malformed attribute list, invalid resolution format")
try {
val width = resolution.substring(0, pivot).toInt()
val height = resolution.substring(pivot + 1).toInt()
AttributeListParser.Resolution(width, height)
} catch (ex: NumberFormatException) {
throw IllegalStateException("Malformed attribute list, invalid resolution value", ex)
}
}
}
// Override for Twitch
register(HlsTag(
"EXT-X-STREAM-INF",
appliesTo = HlsTag.AppliesTo.NEXT_SEGMENT,
unique = true
) { rawData ->
val parser = AttributeListParser(rawData)
var bandwidth: Long? = null
var programId: Long? = null
var codecs: String? = null
var resolution: AttributeListParser.Resolution? = null
var audio: String? = null
var video: String? = null
while (parser.hasMoreAttributes()) {
when (parser.readAttributeName()) {
"BANDWIDTH" -> bandwidth = parser.readDecimalInt()
"PROGRAM-ID" -> programId = parser.readDecimalInt()
"CODECS" -> codecs = parser.readQuotedString()
// Twitch returns a quoted version of the resolution for some reason
"RESOLUTION" -> resolution = parser.readEnumeratedString().toResolution()
"AUDIO" -> audio = parser.readQuotedString()
"VIDEO" -> video = parser.readQuotedString()
}
}
OfficialTags.StreamInformation(
bandwidth!!,
programId,
codecs?.let { ImmutableList.copyOf(it.split(',')) } ?: ImmutableList.of(),
resolution,
audio,
video
)
}, override = true)
}
fun load(broadcastId: String, stream: HlsPlaylist.Variant): Playlist {
val actualPlaylist = HlsParser.parseSimplePlaylist(
stream.uri,
Resources.asCharSource(stream.uri.toURL(), Charsets.UTF_8),
TWITCH_HLS_TAG_REPOSITORY
)
val videos = reduceVideos(actualPlaylist, stream.uri)
return Playlist(
broadcastId,
ImmutableList.copyOf(videos),
actualPlaylist[EXT_X_TWITCH_TOTAL_SECS] ?: fallbackCalculateDuration(videos),
HLS_ENCODING_PROPS
)
}
private fun fallbackCalculateDuration(videos: List<Playlist.Video>): Duration {
if (videos.isEmpty()) {
return Duration.ZERO
} else {
return videos.map { it.length }.reduce { length1, length2 ->
length1 + length2
}
}
}
private fun reduceVideos(videos: List<HlsPlaylist.Segment>, source: URI): List<Playlist.Video> {
val ret: MutableList<Playlist.Video> = Lists.newArrayList()
val it = videos.iterator()
var lastVideo = it.next()
var startVideoUrl = HttpUrl.get(lastVideo.uri)
var length = lastVideo.info.duration
if (REDUCE_DISABLED || startVideoUrl.queryParameter(END_OFFSET_PARAM) == null) {
log.debug("Irreducible video: {}", source)
return videos.map {
val uri = HttpUrl.get(it.uri)
Playlist.Video(
uri,
it.info.duration,
muted = uri.encodedPath().endsWith("-muted.ts")
)
}
}
while (it.hasNext()) {
val nextVideo = it.next()
val nextUrl = HttpUrl.get(nextVideo.uri)
if (startVideoUrl.encodedPath() != nextUrl.encodedPath()
|| (length + nextVideo.info.duration) >= TWITCH_MAXIMUM_SEGMENT_DURATION) {
//We've gone past the previous video segment, finalize it
ret.add(constructVideo(startVideoUrl, HttpUrl.get(lastVideo.uri), length))
startVideoUrl = nextUrl
length = Duration.ZERO
}
length += nextVideo.info.duration
lastVideo = nextVideo
}
ret.add(constructVideo(startVideoUrl, HttpUrl.get(lastVideo.uri), length))
log.debug("reduce on {}: {} -> {}", source, videos.size, ret.size)
return ret
}
private fun constructVideo(start: HttpUrl, end: HttpUrl, length: Duration): Playlist.Video {
return start.newBuilder()
// Replace the end offset of the starting url with the ending url
.setQueryParameter(END_OFFSET_PARAM, end.queryParameter(END_OFFSET_PARAM))
.build()
.let { url ->
Playlist.Video(
url,
length,
muted = url.encodedPath().endsWith("-muted.ts")
)
}
}
}
| mit | 0a8a0b22b7f35ca127c4da2aa21492c5 | 38.044944 | 141 | 0.568921 | 4.849965 | false | false | false | false |
vshkl/Pik | app/src/main/java/by/vshkl/android/pik/util/DimensionUtils.kt | 1 | 1004 | package by.vshkl.android.pik.util
import android.content.res.Resources
import android.util.TypedValue
import com.drew.lang.Rational
import java.util.*
object DimensionUtils {
fun getReadableMpix(width: Int, height: Int): String
= String.format(Locale.getDefault(), "%.1f%s", width.toFloat() * height / 1000000, "MP")
fun getReadableFileSize(bytes: Int): String {
val unit = 1024.0
if (bytes < unit) return bytes.toString() + " B"
val exp = (Math.log(bytes.toDouble()) / Math.log(unit)).toInt()
val pre = "KMGTPE"[exp - 1]
return String.format(Locale.getDefault(), "%.1f %sB", bytes / Math.pow(unit, exp.toDouble()), pre)
}
fun getReadableExposure(exposure: Rational): String
= String.format(Locale.getDefault(), "1/%d", (exposure.denominator / exposure.numerator))
fun px2dp(px: Float): Float {
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, px, Resources.getSystem().displayMetrics)
}
} | apache-2.0 | 8315172de61ebeb4f9b2ede34550f028 | 36.222222 | 111 | 0.665339 | 3.788679 | false | false | false | false |
jtransc/jtransc | jtransc-core/src/com/jtransc/ast/feature/method/GotosFeature.kt | 1 | 8393 | /*
* Copyright 2016 Carlos Ballesteros Velasco
*
* 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.jtransc.ast.feature.method
import com.jtransc.ast.*
import com.jtransc.ast.optimize.optimize
import com.jtransc.graph.Relooper
import com.jtransc.graph.RelooperException
@Suppress("UNUSED_PARAMETER", "LoopToCallChain")
// @TODO: Use AstBuilder to make it more readable
class GotosFeature : AstMethodFeature() {
override fun remove(method: AstMethod, body: AstBody, settings: AstBuildSettings, types: AstTypes): AstBody {
if (settings.relooper) {
try {
return removeRelooper(body, settings, types) ?: removeMachineState(body, types)
} catch (t: Throwable) {
t.printStackTrace()
return removeMachineState(body, types)
}
} else {
return removeMachineState(body, types)
}
}
private fun removeRelooper(body: AstBody, settings: AstBuildSettings, types: AstTypes): AstBody? {
class BasicBlock(var index: Int) {
var node: Relooper.Node? = null
val stms = arrayListOf<AstStm>()
var next: BasicBlock? = null
var condExpr: AstExpr? = null
var ifNext: BasicBlock? = null
//val targets by lazy { (listOf(next, ifNext) + (switchNext?.values ?: listOf())).filterNotNull() }
override fun toString(): String = "BasicBlock($index)"
}
val entryStm = body.stm as? AstStm.STMS ?: return null
// Not relooping single statements
if (body.traps.isNotEmpty()) return null // Not relooping functions with traps by the moment
val stms = entryStm.stms
val bblist = arrayListOf<BasicBlock>()
val bbs = hashMapOf<AstLabel, BasicBlock>()
fun createBB(): BasicBlock {
val bb = BasicBlock(bblist.size)
bblist += bb
return bb
}
fun getBBForLabel(label: AstLabel): BasicBlock {
return bbs.getOrPut(label) { createBB() }
}
val entry = createBB()
var current = entry
for (stmBox in stms) {
val stm = stmBox.value
when (stm) {
is AstStm.STM_LABEL -> {
val prev = current
current = getBBForLabel(stm.label)
prev.next = current
}
is AstStm.GOTO -> {
val prev = current
current = createBB()
prev.next = getBBForLabel(stm.label)
}
is AstStm.IF_GOTO -> {
val prev = current
current = createBB()
prev.condExpr = stm.cond.value
prev.ifNext = getBBForLabel(stm.label)
prev.next = current
}
is AstStm.SWITCH_GOTO -> {
// Not handled switches yet!
return null
}
is AstStm.RETURN, is AstStm.THROW, is AstStm.RETHROW -> {
current.stms += stm
val prev = current
current = createBB()
prev.next = null
}
else -> {
current.stms += stm
}
}
}
val relooper = Relooper(types)
for (n in bblist) {
n.node = relooper.node(n.stms)
//println("NODE(${n.index}): ${n.stms}")
//if (n.next != null) println(" -> ${n.next}")
//if (n.ifNext != null) println(" -> ${n.ifNext} [${n.condExpr}]")
}
for (n in bblist) {
val next = n.next
val ifNext = n.ifNext
if (next != null) relooper.edge(n.node!!, next.node!!)
if (n.condExpr != null && ifNext != null) relooper.edge(n.node!!, ifNext.node!!, n.condExpr!!)
}
try {
val render = relooper.render(bblist[0].node!!)
val bodyGotos = if (settings.optimize) {
render?.optimize(body.flags)
} else {
render
}
return body.copy(
stm = bodyGotos ?: return null
)
} catch (e: RelooperException) {
//println("RelooperException: ${e.message}")
return null
}
//return AstBody(relooper.render(bblist[0].node!!) ?: return null, body.locals, body.traps)
}
fun removeMachineState(body: AstBody, types: AstTypes): AstBody {
// @TODO: this should create simple blocks and do analysis like that, instead of creating a gigantic switch
// @TODO: trying to generate whiles, ifs and so on to allow javascript be fast. See relooper paper.
var stm = body.stm
//val locals = body.locals.toCollection(arrayListOf<AstLocal>())
val traps = body.traps.toCollection(arrayListOf<AstTrap>())
//val gotostate = AstLocal(-1, "_gotostate", AstType.INT)
val gotostate = AstExpr.LOCAL(AstLocal(-1, "G", AstType.INT))
var hasLabels = false
var stateIndex = 0
val labelsToState = hashMapOf<AstLabel, Int>()
fun getStateFromLabel(label: AstLabel): Int {
if (label !in labelsToState) {
labelsToState[label] = ++stateIndex
}
return labelsToState[label]!!
}
fun strip(stm: AstStm): AstStm = when (stm) {
is AstStm.STMS -> {
// Without labels/gotos
if (!stm.stms.any { it.value is AstStm.STM_LABEL }) {
stm
}
// With labels/gotos
else {
hasLabels = true
val stms = stm.stms
var stateIndex2 = 0
var stateStms = arrayListOf<AstStm>()
val cases = arrayListOf<Pair<List<Int>, AstStm>>()
fun flush() {
cases.add(Pair(listOf(stateIndex2), stateStms.stm()))
stateIndex2 = -1
stateStms = arrayListOf<AstStm>()
}
fun simulateGotoLabel(index: Int) = listOf(
gotostate.setTo(index.lit),
AstStm.CONTINUE()
)
fun simulateGotoLabel(label: AstLabel) = simulateGotoLabel(getStateFromLabel(label))
for (ss in stms) {
val s = ss.value
when (s) {
is AstStm.STM_LABEL -> {
val nextIndex = getStateFromLabel(s.label)
val lastStm = stateStms.lastOrNull()
if ((lastStm !is AstStm.CONTINUE) && (lastStm !is AstStm.BREAK) && (lastStm !is AstStm.RETURN)) {
stateStms.addAll(simulateGotoLabel(s.label))
}
flush()
stateIndex2 = nextIndex
stateStms = arrayListOf<AstStm>()
}
is AstStm.IF_GOTO -> {
stateStms.add(AstStm.IF(
s.cond.value,
simulateGotoLabel(s.label).stm()
))
}
is AstStm.GOTO -> {
stateStms.addAll(simulateGotoLabel(s.label))
}
is AstStm.SWITCH_GOTO -> {
//throw NotImplementedError("Must implement switch goto ")
stateStms.add(AstStm.SWITCH(
s.subject.value,
simulateGotoLabel(s.default).stm(),
s.cases.map {
Pair(it.first, simulateGotoLabel(it.second).stm())
}
))
}
else -> {
stateStms.add(s)
}
}
}
flush()
fun extraReturn() = when (body.type.ret) {
is AstType.VOID -> AstStm.RETURN_VOID()
is AstType.BOOL -> AstStm.RETURN(false.lit)
is AstType.BYTE, is AstType.SHORT, is AstType.CHAR, is AstType.INT -> AstStm.RETURN(0.lit)
is AstType.LONG -> AstStm.RETURN(0L.lit)
is AstType.FLOAT -> AstStm.RETURN(0f.lit)
is AstType.DOUBLE -> AstStm.RETURN(0.0.lit)
else -> AstStm.RETURN(null.lit)
}
val plainWhile =
listOf(
AstStm.WHILE(true.lit,
AstStm.SWITCH(gotostate, AstStm.NOP("no default"), cases)
),
extraReturn()
).stm()
if (traps.isEmpty()) {
plainWhile
} else {
// Calculate ranges for try...catch
val checkTraps = traps.map { trap ->
val startState = getStateFromLabel(trap.start)
val endState = getStateFromLabel(trap.end)
val handlerState = getStateFromLabel(trap.handler)
AstStm.IF(
//(gotostate ge AstExpr.LITERAL(startState)) band (gotostate le AstExpr.LITERAL(endState)) band (AstExpr.CAUGHT_EXCEPTION() instanceof trap.exception),
(gotostate ge startState.lit) band (gotostate lt endState.lit) band (AstExpr.CAUGHT_EXCEPTION() instanceof trap.exception),
simulateGotoLabel(handlerState).stm()
)
}
listOf(
AstStm.WHILE(true.lit,
AstStm.TRY_CATCH(plainWhile, stms(
checkTraps.stms,
AstStm.RETHROW()
))
),
extraReturn()
).stm()
}
}
}
else -> stm
}
stm = strip(stm)
//if (hasLabels) locals.add(gotostate.local)
return body.copy(types = types, stm = stm, traps = traps)
}
}
| apache-2.0 | ba72e72fbdde300cd9f507663648a0c9 | 28.552817 | 159 | 0.634815 | 3.261951 | false | false | false | false |
googlecreativelab/digital-wellbeing-experiments-toolkit | geolocation/geofence/app/src/main/java/com/digitalwellbeingexperiments/toolkit/geofence/MainActivity.kt | 1 | 7500 | // Copyright 2019 Google LLC
//
// 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.digitalwellbeingexperiments.toolkit.geofence
import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.location.Geocoder
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Button
import androidx.core.content.ContextCompat
import androidx.navigation.Navigation
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.RecyclerView
import com.google.android.gms.location.LocationServices
import com.google.android.gms.maps.model.LatLng
import com.google.android.libraries.places.api.Places
import com.google.android.libraries.places.api.model.Place
import com.google.android.libraries.places.widget.Autocomplete
import com.google.android.libraries.places.widget.AutocompleteActivity
import com.google.android.libraries.places.widget.model.AutocompleteActivityMode
import com.google.android.material.snackbar.Snackbar
import java.io.IOException
private const val DEFAULT_RADIUS_METERS = 150f
private const val AUTOCOMPLETE_REQUEST_CODE = 10001
private const val PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 111
class MainActivity : AppCompatActivity() {
private lateinit var triggersAdapter: TriggersAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
triggersAdapter = TriggersAdapter()
Places.initialize(this, getString(R.string.google_maps_key))
findViewById<Button>(R.id.btn_add).setOnClickListener {
if (ContextCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_FINE_LOCATION
) != PackageManager.PERMISSION_GRANTED
) {
requestPermissions(
arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION
)
} else {
showPlaceSearch()
}
}
findViewById<RecyclerView>(R.id.recycler).apply {
layoutManager = androidx.recyclerview.widget.LinearLayoutManager(context)
addItemDecoration(DividerItemDecoration(this.context, DividerItemDecoration.VERTICAL))
adapter = triggersAdapter
}
}
override fun onResume() {
super.onResume()
triggersAdapter.refresh()
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
when (requestCode) {
PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION -> {
// If request is cancelled, the result arrays are empty.
if ((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
if (ContextCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_FINE_LOCATION
) == PackageManager.PERMISSION_GRANTED
) {
showPlaceSearch()
}
}
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
data?.let {
if (requestCode == AUTOCOMPLETE_REQUEST_CODE) {
when (resultCode) {
RESULT_OK -> {
val place = Autocomplete.getPlaceFromIntent(data)
place.latLng?.let {
val description = place.name ?: reverseGeocode(it)
Log.w(TAG(), "GOT $description")
GeofenceApplication.instance.triggerManager.add(Trigger(
latLng = it,
radius = DEFAULT_RADIUS_METERS,
placeName = description
),
successCallback = { isSuccess, errorMessage ->
if (isSuccess) {
triggersAdapter.refresh()
} else {
createSnackbar(
window.decorView.findViewById(android.R.id.content),
errorMessage
?: getString(R.string.error_unknown_trigger),
Snackbar.LENGTH_LONG
).show()
}
})
}
}
AutocompleteActivity.RESULT_ERROR -> {
val status = Autocomplete.getStatusFromIntent(data)
val message = status.statusMessage?: getString(R.string.error_unknown_trigger)
Log.w(TAG(), message)
createSnackbar(
window.decorView.findViewById(android.R.id.content),
message,
Snackbar.LENGTH_LONG
).show()
}
RESULT_CANCELED -> {
// The user canceled the operation.
Log.w(TAG(), "cancelled")
}
}
}
}
}
private fun showPlaceSearch() {
val fields: List<Place.Field> =
listOf(Place.Field.ID, Place.Field.NAME, Place.Field.LAT_LNG)
val intent = Autocomplete.IntentBuilder(
AutocompleteActivityMode.FULLSCREEN, fields
).build(this)
startActivityForResult(intent, AUTOCOMPLETE_REQUEST_CODE)
}
private fun reverseGeocode(latlng: LatLng): String {
fun fallback(fallback: String = "${latlng.latitude} ${latlng.longitude}"): String {
return fallback
}
try {
Geocoder(this).getFromLocation(latlng.latitude, latlng.longitude, 1)?.let { results ->
if (results.isNotEmpty()) {
results.first().let {
if (it.maxAddressLineIndex == -1) return fallback()
var address = ""
for (i in 0..it.maxAddressLineIndex) {
address += it.getAddressLine(i)
}
return address
}
} else {
return fallback()
}
}
} catch (e: IOException) {
return fallback()
}
return fallback()
}
}
| apache-2.0 | f097b2fc0e20bc1ad41743b4d7cdb577 | 39.76087 | 106 | 0.553067 | 5.613772 | false | false | false | false |
infinum/android_dbinspector | dbinspector/src/test/kotlin/com/infinum/dbinspector/data/sources/memory/connection/AndroidConnectionSourceTest.kt | 1 | 4139 | package com.infinum.dbinspector.data.sources.memory.connection
import android.database.sqlite.SQLiteDatabase
import com.infinum.dbinspector.shared.BaseTest
import io.mockk.every
import io.mockk.mockk
import io.mockk.mockkStatic
import io.mockk.unmockkStatic
import kotlin.collections.List
import kotlin.collections.isNotEmpty
import kotlin.collections.listOf
import kotlin.collections.set
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
import org.koin.core.module.Module
@DisplayName("AndroidConnectionSource tests")
internal class AndroidConnectionSourceTest : BaseTest() {
override fun modules(): List<Module> = listOf()
@Test
fun `New instance has empty but existing connection pool`() {
val source = AndroidConnectionSource()
assertTrue(source.connectionPool.isEmpty())
assertNotNull(source.connectionPool)
}
@Test
fun `Open connection adds new key to connection pool`() {
val given = "test.db"
mockkStatic(SQLiteDatabase::class)
every { SQLiteDatabase.openOrCreateDatabase(given, null) } returns mockk {
every { path } returns given
}
val source = AndroidConnectionSource()
test {
source.openConnection(given)
}
unmockkStatic(SQLiteDatabase::class)
assertTrue(source.connectionPool.isNotEmpty())
assertNotNull(source.connectionPool)
assertEquals(source.connectionPool.size, 1)
assertTrue(source.connectionPool.containsKey(given))
}
@Test
fun `Open connection reuses existing key from connection pool`() {
val given = "test.db"
val expected: SQLiteDatabase = mockk()
mockkStatic(SQLiteDatabase::class)
every { SQLiteDatabase.openOrCreateDatabase(given, null) } returns mockk {
every { path } returns given
}
val source = AndroidConnectionSource()
source.connectionPool[given] = expected
test {
source.openConnection(given)
}
unmockkStatic(SQLiteDatabase::class)
assertTrue(source.connectionPool.isNotEmpty())
assertNotNull(source.connectionPool)
assertEquals(source.connectionPool.size, 1)
assertTrue(source.connectionPool.containsKey(given))
assertEquals(expected, source.connectionPool[given])
}
@Test
fun `Close connection removes existing key from connection pool`() {
val given = "test.db"
val expected: SQLiteDatabase = mockk {
every { isOpen } returns true
every { close() } returns Unit
}
mockkStatic(SQLiteDatabase::class)
every { SQLiteDatabase.openOrCreateDatabase(given, null) } returns mockk {
every { path } returns given
every { isOpen } returns true
every { close() } returns Unit
}
val source = AndroidConnectionSource()
source.connectionPool[given] = expected
test {
source.closeConnection(given)
}
unmockkStatic(SQLiteDatabase::class)
assertTrue(source.connectionPool.isEmpty())
assertNotNull(source.connectionPool)
assertFalse(source.connectionPool.containsKey(given))
}
@Test
fun `Close connection does nothing for non-existing key in connection pool`() {
val given = "test.db"
mockkStatic(SQLiteDatabase::class)
every { SQLiteDatabase.openOrCreateDatabase(given, null) } returns mockk {
every { path } returns given
every { isOpen } returns true
every { close() } returns Unit
}
val source = AndroidConnectionSource()
test {
source.closeConnection(given)
}
unmockkStatic(SQLiteDatabase::class)
assertTrue(source.connectionPool.isEmpty())
assertNotNull(source.connectionPool)
assertFalse(source.connectionPool.containsKey(given))
}
}
| apache-2.0 | d1ccdbdf0b4a5604113f17e7731e0abb | 28.776978 | 83 | 0.671418 | 5.116193 | false | true | false | false |
pdvrieze/ProcessManager | buildSrc/src/main/kotlin/net/devrieze/gradle/multiplatform/MPConsumerPlugin.kt | 1 | 5017 | /*
* Copyright (c) 2019.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
package multiplatform.net.devrieze.gradle.multiplatform
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.artifacts.Configuration
import org.gradle.api.artifacts.ConfigurationContainer
import org.gradle.api.attributes.AttributeDisambiguationRule
import org.gradle.api.attributes.MultipleCandidatesDetails
import org.gradle.kotlin.dsl.closureOf
import org.gradle.kotlin.dsl.hasPlugin
import org.jetbrains.kotlin.gradle.plugin.KotlinPlatformAndroidPlugin
import org.jetbrains.kotlin.gradle.plugin.KotlinPlatformJsPlugin
import org.jetbrains.kotlin.gradle.plugin.KotlinPlatformType
import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinMultiplatformPlugin
import org.jetbrains.kotlin.gradle.targets.js.KotlinJsCompilerAttribute
import org.jetbrains.kotlin.gradle.targets.js.KotlinJsCompilerAttribute.Companion.jsCompilerAttribute
class MPConsumerPlugin: Plugin<Project> {
override fun apply(project: Project) {
with(project) {
logger.lifecycle("Multiplatform consumer plugin applied!")
if (pluginManager.hasPlugin("kotlin-multiplatform")) {
logger.warn("Applying multiplatform consumer plugin on a multiplatform project, this has no effect")
} else {
val platformType = when {
// Don't use classes for the android plugins as we don't want to pull in the android plugin into the
// classpath just to find that android is not needed.
plugins.hasPlugin(KotlinPlatformAndroidPlugin::class) or
plugins.hasPlugin("com.android.application") or
plugins.hasPlugin("com.android.feature") or
plugins.hasPlugin("com.android.test") or
plugins.hasPlugin("com.android.library") -> KotlinPlatformType.androidJvm
plugins.hasPlugin(KotlinPlatformJsPlugin::class) -> KotlinPlatformType.js
else -> KotlinPlatformType.jvm
}
configurations.configureEach {
if (! isCanBeConsumed) {
attributes {
if (!contains(KotlinPlatformType.attribute)) {
logger.info("Adding kotlin usage attribute $platformType to configuration: ${name}")
attribute(KotlinPlatformType.attribute, platformType)
} else {
logger.debug(
"Preserving kotlin usage attribute on configuration $name as ${
getAttribute(
KotlinPlatformType.attribute
)
} instead of $platformType"
)
}
if (platformType == KotlinPlatformType.js && !contains(KotlinJsCompilerAttribute.jsCompilerAttribute)) {
attribute(
KotlinJsCompilerAttribute.jsCompilerAttribute,
KotlinJsCompilerAttribute.legacy
)
}
}
}
}
logger.lifecycle("Registering the platform type attributes to the schema with the resolution rules")
KotlinPlatformType.setupAttributesMatchingStrategy(dependencies.attributesSchema)
dependencies.attributesSchema.attribute(jsCompilerAttribute) {
disambiguationRules.add(KotlinJsDisambiguationRule::class.java)
}
}
}
}
}
class KotlinJsDisambiguationRule : AttributeDisambiguationRule<KotlinJsCompilerAttribute> {
override fun execute(details: MultipleCandidatesDetails<KotlinJsCompilerAttribute?>) = with(details) {
if (consumerValue == null || consumerValue == KotlinJsCompilerAttribute.both) {
if (candidateValues == setOf(KotlinJsCompilerAttribute.legacy, KotlinJsCompilerAttribute.ir))
closestMatch(KotlinJsCompilerAttribute.legacy)
} else {
closestMatch(consumerValue!!)
}
}
}
| lgpl-3.0 | 2e1985485a08f7f46aff1f902cbfed47 | 49.17 | 132 | 0.622484 | 5.64342 | false | true | false | false |
songzhw/Hello-kotlin | AdvancedJ/src/main/kotlin/effective/StaticFactory01.kt | 1 | 894 | package effective
/*
一. 考虑用 静态工厂 替代 构造函数
如: String number = String.valueOf(1, 2)
List<Integer> list = Arrays.asList(1, 2, 4)
原因有:
1. 可读性好. 如: ArrayList.withSize(3)
2. 静态工厂内里的实现还可以用cache. 不见得像constructor一样每次都是new一个对象
3. 静态工厂可以返回子类, constructor不行 -- 即可以隐去细节, 有个别场景需要这样的灵活
4. 像Builder模式一样, 静态工厂可以避免过于冗长的constructor参数表. 但又不像builder一样要写一个Builder类.
静态工厂的缺点是: 与其它static方法不容易区分开来. 这点就比不上Builder
*/
// 1. Companion Factory Method: 请见 CompanionThree.kt
// 2. 顶层函数
fun foo(){
val list = List(4) { "$it"}
println("list = $list ") //=> list = [0, 1, 2, 3]
}
fun main(args: Array<String>) {
foo()
} | apache-2.0 | 14c0cf2e9989366fe761a53bc7b5ab59 | 21.407407 | 72 | 0.700331 | 2.10453 | false | false | false | false |
youkai-app/Youkai | app/src/main/kotlin/app/youkai/data/models/MediaRelationship.kt | 1 | 907 | package app.youkai.data.models
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.github.jasminb.jsonapi.Links
import com.github.jasminb.jsonapi.annotations.Relationship
import com.github.jasminb.jsonapi.annotations.RelationshipLinks
import com.github.jasminb.jsonapi.annotations.Type
@Type("mediaRelationships") @JsonIgnoreProperties(ignoreUnknown = true)
class MediaRelationship : BaseJsonModel(JsonType("mediaRelationships")) {
companion object FieldNames {
val ROLE = "role"
val SOURCE = "source"
val DESTINATION = "destination"
}
var role: String? = null
@Relationship("source")
var source: BaseMedia? = null
@RelationshipLinks("source")
var sourceLinks: Links? = null
@Relationship("destination")
var destination: BaseMedia? = null
@RelationshipLinks("destination")
var destinationLinks: Links? = null
} | gpl-3.0 | b040d2eb0bfc69e459982d8adaf00306 | 27.375 | 73 | 0.742007 | 4.580808 | false | false | false | false |
fossasia/open-event-android | app/src/main/java/org/fossasia/openevent/general/event/EventDetailsFragment.kt | 1 | 34408 | package org.fossasia.openevent.general.event
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.CalendarContract
import android.text.Editable
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.appcompat.app.AlertDialog
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.navigation.Navigation.findNavController
import androidx.navigation.fragment.FragmentNavigatorExtras
import androidx.navigation.fragment.navArgs
import androidx.recyclerview.widget.LinearLayoutManager
import com.squareup.picasso.Picasso
import kotlinx.android.synthetic.main.content_event.view.alreadyRegisteredLayout
import kotlinx.android.synthetic.main.content_event.view.eventDateDetailsFirst
import kotlinx.android.synthetic.main.content_event.view.eventDateDetailsSecond
import kotlinx.android.synthetic.main.content_event.view.eventDescription
import kotlinx.android.synthetic.main.content_event.view.eventImage
import kotlinx.android.synthetic.main.content_event.view.eventLocationLinearLayout
import kotlinx.android.synthetic.main.content_event.view.eventName
import kotlinx.android.synthetic.main.content_event.view.eventOrganiserDescription
import kotlinx.android.synthetic.main.content_event.view.eventTimingLinearLayout
import kotlinx.android.synthetic.main.content_event.view.feedbackBtn
import kotlinx.android.synthetic.main.content_event.view.feedbackProgress
import kotlinx.android.synthetic.main.content_event.view.feedbackRv
import kotlinx.android.synthetic.main.content_event.view.imageMap
import kotlinx.android.synthetic.main.content_event.view.nestedContentEventScroll
import kotlinx.android.synthetic.main.content_event.view.noFeedBackTv
import kotlinx.android.synthetic.main.content_event.view.priceRangeTextView
import kotlinx.android.synthetic.main.content_event.view.seeFeedbackTextView
import kotlinx.android.synthetic.main.content_event.view.seeMore
import kotlinx.android.synthetic.main.content_event.view.seeMoreOrganizer
import kotlinx.android.synthetic.main.content_event.view.sessionContainer
import kotlinx.android.synthetic.main.content_event.view.sessionsRv
import kotlinx.android.synthetic.main.content_event.view.shimmerSimilarEvents
import kotlinx.android.synthetic.main.content_event.view.similarEventsContainer
import kotlinx.android.synthetic.main.content_event.view.similarEventsRecycler
import kotlinx.android.synthetic.main.content_event.view.socialLinkContainer
import kotlinx.android.synthetic.main.content_event.view.socialLinksRecycler
import kotlinx.android.synthetic.main.content_event.view.speakerRv
import kotlinx.android.synthetic.main.content_event.view.speakersContainer
import kotlinx.android.synthetic.main.content_event.view.sponsorsRecyclerView
import kotlinx.android.synthetic.main.content_event.view.sponsorsSummaryContainer
import kotlinx.android.synthetic.main.content_event.view.ticketPriceLinearLayout
import kotlinx.android.synthetic.main.content_fetching_event_error.view.retry
import kotlinx.android.synthetic.main.dialog_feedback.view.feedback
import kotlinx.android.synthetic.main.dialog_feedback.view.feedbackTextInputLayout
import kotlinx.android.synthetic.main.dialog_feedback.view.feedbackrating
import kotlinx.android.synthetic.main.fragment_event.view.buttonTickets
import kotlinx.android.synthetic.main.fragment_event.view.container
import kotlinx.android.synthetic.main.fragment_event.view.eventErrorCard
import org.fossasia.openevent.general.R
import org.fossasia.openevent.general.common.EventClickListener
import org.fossasia.openevent.general.common.FavoriteFabClickListener
import org.fossasia.openevent.general.common.SessionClickListener
import org.fossasia.openevent.general.common.SpeakerClickListener
import org.fossasia.openevent.general.databinding.FragmentEventBinding
import org.fossasia.openevent.general.event.EventUtils.loadMapUrl
import org.fossasia.openevent.general.event.similarevent.SimilarEventsListAdapter
import org.fossasia.openevent.general.feedback.FeedbackRecyclerAdapter
import org.fossasia.openevent.general.feedback.LIMITED_FEEDBACK_NUMBER
import org.fossasia.openevent.general.sessions.SessionRecyclerAdapter
import org.fossasia.openevent.general.social.SocialLinksRecyclerAdapter
import org.fossasia.openevent.general.speakers.SpeakerRecyclerAdapter
import org.fossasia.openevent.general.sponsor.SponsorClickListener
import org.fossasia.openevent.general.sponsor.SponsorRecyclerAdapter
import org.fossasia.openevent.general.utils.EVENT_IDENTIFIER
import org.fossasia.openevent.general.utils.Utils
import org.fossasia.openevent.general.utils.Utils.progressDialog
import org.fossasia.openevent.general.utils.Utils.setToolbar
import org.fossasia.openevent.general.utils.Utils.show
import org.fossasia.openevent.general.utils.extensions.nonNull
import org.fossasia.openevent.general.utils.extensions.setSharedElementEnterTransition
import org.fossasia.openevent.general.utils.nullToEmpty
import org.fossasia.openevent.general.utils.stripHtml
import org.jetbrains.anko.design.longSnackbar
import org.jetbrains.anko.design.snackbar
import org.koin.androidx.viewmodel.ext.android.viewModel
import timber.log.Timber
const val EVENT_DETAIL_FRAGMENT = "eventDetailFragment"
class EventDetailsFragment : Fragment() {
private val eventViewModel by viewModel<EventDetailsViewModel>()
private val safeArgs: EventDetailsFragmentArgs by navArgs()
private val feedbackAdapter = FeedbackRecyclerAdapter(true)
private val speakersAdapter = SpeakerRecyclerAdapter()
private val sponsorsAdapter = SponsorRecyclerAdapter()
private val sessionsAdapter = SessionRecyclerAdapter()
private val socialLinkAdapter = SocialLinksRecyclerAdapter()
private val similarEventsAdapter = SimilarEventsListAdapter()
private var hasSimilarEvents: Boolean = false
private lateinit var rootView: View
private lateinit var binding: FragmentEventBinding
private val LINE_COUNT: Int = 3
private val LINE_COUNT_ORGANIZER: Int = 2
private var menuActionBar: Menu? = null
private var currentEvent: Event? = null
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
setSharedElementEnterTransition()
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_event, container, false)
val progressDialog = progressDialog(context, getString(R.string.loading_message))
rootView = binding.root
setToolbar(activity)
setHasOptionsMenu(true)
setupOrder()
setupEventOverview()
setupSocialLinks()
setupFeedback()
setupSessions()
setupSpeakers()
setupSponsors()
setupSimilarEvents()
rootView.buttonTickets.setOnClickListener {
val ticketUrl = currentEvent?.ticketUrl
if (!ticketUrl.isNullOrEmpty() &&
Uri.parse(ticketUrl).host != getString(R.string.FRONTEND_HOST)) {
Utils.openUrl(requireContext(), ticketUrl)
} else {
loadTicketFragment()
}
}
eventViewModel.popMessage
.nonNull()
.observe(viewLifecycleOwner, Observer {
rootView.snackbar(it)
showEventErrorScreen(it == getString(R.string.error_fetching_event_message))
})
eventViewModel.progress
.nonNull()
.observe(viewLifecycleOwner, Observer {
progressDialog.show(it)
})
rootView.retry.setOnClickListener {
currentEvent?.let { eventViewModel.loadEvent(it.id) }
}
return rootView
}
private fun setupOrder() {
if (eventViewModel.orders.value == null)
eventViewModel.loadOrders()
eventViewModel.orders
.nonNull()
.observe(viewLifecycleOwner, Observer {
it.forEach { order ->
if (order.event?.id == safeArgs.eventId) {
rootView.alreadyRegisteredLayout.isVisible = true
rootView.alreadyRegisteredLayout.setOnClickListener {
order.identifier?.let { identifier ->
EventDetailsFragmentDirections.actionEventDetailsToOrderDetail(
eventId = safeArgs.eventId,
orderId = order.id,
orderIdentifier = identifier
)
}?.let { navigation ->
findNavController(rootView).navigate(navigation)
}
}
return@forEach
}
}
})
}
private fun setupEventOverview() {
eventViewModel.event
.nonNull()
.observe(viewLifecycleOwner, Observer {
currentEvent = it
loadEvent(it)
if (eventViewModel.similarEvents.value == null) {
val eventTopicId = it.eventTopic?.id ?: 0
val eventLocation = it.searchableLocationName ?: it.locationName
eventViewModel.fetchSimilarEvents(it.id, eventTopicId, eventLocation)
}
if (eventViewModel.eventFeedback.value == null)
eventViewModel.fetchEventFeedback(it.id)
if (eventViewModel.eventSessions.value == null)
eventViewModel.fetchEventSessions(it.id)
if (eventViewModel.eventSpeakers.value == null)
eventViewModel.fetchEventSpeakers(it.id)
if (eventViewModel.eventSponsors.value == null)
eventViewModel.fetchEventSponsors(it.id)
if (eventViewModel.socialLinks.value == null)
eventViewModel.fetchSocialLink(it.id)
if (eventViewModel.priceRange.value == null)
eventViewModel.syncTickets(it)
// Update favorite icon and external event url menu option
activity?.invalidateOptionsMenu()
Timber.d("Fetched events of id ${it.id}")
showEventErrorScreen(false)
setHasOptionsMenu(true)
})
eventViewModel.priceRange
.nonNull()
.observe(viewLifecycleOwner, Observer {
rootView.ticketPriceLinearLayout.isVisible = true
rootView.priceRangeTextView.text = it
})
val eventIdentifier = arguments?.getString(EVENT_IDENTIFIER)
val event = eventViewModel.event.value
when {
event != null -> {
currentEvent = event
loadEvent(event)
}
!eventIdentifier.isNullOrEmpty() -> eventViewModel.loadEventByIdentifier(eventIdentifier)
else -> eventViewModel.loadEvent(safeArgs.eventId)
}
// Set toolbar title to event name
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
rootView.nestedContentEventScroll.setOnScrollChangeListener { _, _, scrollY, _, _ ->
if (scrollY > rootView.eventName.height + rootView.eventImage.height)
/*Toolbar title set to name of Event if scrolled more than
combined height of eventImage and eventName views*/
setToolbar(activity, eventViewModel.event.value?.name ?: "")
else
// Toolbar title set to an empty string
setToolbar(activity)
}
}
}
private fun setupSocialLinks() {
val socialLinkLinearLayoutManager = LinearLayoutManager(context)
socialLinkLinearLayoutManager.orientation = LinearLayoutManager.HORIZONTAL
rootView.socialLinksRecycler.layoutManager = socialLinkLinearLayoutManager
rootView.socialLinksRecycler.adapter = socialLinkAdapter
eventViewModel.socialLinks.observe(viewLifecycleOwner, Observer {
socialLinkAdapter.addAll(it)
rootView.socialLinkContainer.isVisible = it.isNotEmpty()
})
}
private fun setupFeedback() {
rootView.feedbackRv.layoutManager = LinearLayoutManager(context)
rootView.feedbackRv.adapter = feedbackAdapter
eventViewModel.feedbackProgress
.nonNull()
.observe(viewLifecycleOwner, Observer {
rootView.feedbackProgress.isVisible = it
rootView.feedbackBtn.isVisible = !it
})
eventViewModel.eventFeedback.observe(viewLifecycleOwner, Observer {
feedbackAdapter.addAll(it)
if (it.isEmpty()) {
rootView.feedbackRv.isVisible = false
rootView.noFeedBackTv.isVisible = true
rootView.seeFeedbackTextView.isVisible = false
} else {
rootView.feedbackRv.isVisible = true
rootView.noFeedBackTv.isVisible = false
rootView.seeFeedbackTextView.isVisible = it.size >= LIMITED_FEEDBACK_NUMBER
}
})
eventViewModel.submittedFeedback
.nonNull()
.observe(viewLifecycleOwner, Observer {
if (feedbackAdapter.itemCount < LIMITED_FEEDBACK_NUMBER)
feedbackAdapter.add(it)
else
rootView.seeFeedbackTextView.isVisible = true
rootView.feedbackRv.isVisible = true
rootView.noFeedBackTv.isVisible = false
})
rootView.feedbackBtn.setOnClickListener {
checkForAuthentication()
}
}
private fun setupSpeakers() {
val linearLayoutManager = LinearLayoutManager(context)
linearLayoutManager.orientation = LinearLayoutManager.HORIZONTAL
rootView.speakerRv.layoutManager = linearLayoutManager
rootView.speakerRv.adapter = speakersAdapter
eventViewModel.eventSpeakers.observe(viewLifecycleOwner, Observer {
speakersAdapter.addAll(it)
rootView.speakersContainer.isVisible = it.isNotEmpty()
})
val speakerClickListener: SpeakerClickListener = object : SpeakerClickListener {
override fun onClick(speakerId: Long) {
findNavController(rootView).navigate(EventDetailsFragmentDirections
.actionEventDetailsToSpeaker(speakerId))
}
}
speakersAdapter.apply {
onSpeakerClick = speakerClickListener
}
}
private fun setupSessions() {
val linearLayoutManagerSessions = LinearLayoutManager(context)
linearLayoutManagerSessions.orientation = LinearLayoutManager.HORIZONTAL
rootView.sessionsRv.layoutManager = linearLayoutManagerSessions
rootView.sessionsRv.adapter = sessionsAdapter
eventViewModel.eventSessions.observe(viewLifecycleOwner, Observer {
sessionsAdapter.addAll(it)
rootView.sessionContainer.isVisible = it.isNotEmpty()
})
val sessionClickListener: SessionClickListener = object : SessionClickListener {
override fun onClick(sessionId: Long) {
findNavController(rootView).navigate(EventDetailsFragmentDirections
.actionEventDetailsToSession(sessionId))
}
}
sessionsAdapter.apply {
onSessionClick = sessionClickListener
}
}
private fun setupSponsors() {
val sponsorLinearLayoutManager = LinearLayoutManager(context)
sponsorLinearLayoutManager.orientation = LinearLayoutManager.HORIZONTAL
rootView.sponsorsRecyclerView.layoutManager = sponsorLinearLayoutManager
rootView.sponsorsRecyclerView.adapter = sponsorsAdapter
eventViewModel.eventSponsors.observe(viewLifecycleOwner, Observer { sponsors ->
sponsorsAdapter.addAll(sponsors)
rootView.sponsorsSummaryContainer.isVisible = sponsors.isNotEmpty()
})
val sponsorClickListener: SponsorClickListener = object : SponsorClickListener {
override fun onClick() {
moveToSponsorSection()
}
}
sponsorsAdapter.apply {
onSponsorClick = sponsorClickListener
}
rootView.sponsorsSummaryContainer.setOnClickListener {
moveToSponsorSection()
}
}
private fun setupSimilarEvents() {
eventViewModel.similarEventsProgress
.nonNull()
.observe(viewLifecycleOwner, Observer {
rootView.shimmerSimilarEvents.isVisible = it
if (it) {
rootView.shimmerSimilarEvents.startShimmer()
rootView.similarEventsContainer.isVisible = true
} else {
rootView.shimmerSimilarEvents.stopShimmer()
if (!similarEventsAdapter.currentList.isNullOrEmpty()) {
hasSimilarEvents = true
}
rootView.similarEventsContainer.isVisible = hasSimilarEvents
}
})
val similarLinearLayoutManager = LinearLayoutManager(context)
similarLinearLayoutManager.orientation = LinearLayoutManager.HORIZONTAL
rootView.similarEventsRecycler.layoutManager = similarLinearLayoutManager
rootView.similarEventsRecycler.adapter = similarEventsAdapter
eventViewModel.similarEvents
.nonNull()
.observe(viewLifecycleOwner, Observer { similarEvents ->
similarEventsAdapter.submitList(similarEvents)
})
}
private fun loadEvent(event: Event) {
val startsAt = EventUtils.getEventDateTime(event.startsAt, event.timezone)
val endsAt = EventUtils.getEventDateTime(event.endsAt, event.timezone)
binding.event = event
binding.executePendingBindings()
// Set Cover Image
Picasso.get()
.load(event.originalImageUrl)
.placeholder(R.drawable.header)
.into(rootView.eventImage)
// Organizer Section
if (!event.ownerName.isNullOrEmpty()) {
val organizerDescriptionListener = View.OnClickListener {
rootView.eventOrganiserDescription.toggle()
rootView.seeMoreOrganizer.text = if (rootView.eventOrganiserDescription.isExpanded)
getString(R.string.see_less) else getString(R.string.see_more)
}
rootView.eventOrganiserDescription.post {
if (rootView.eventOrganiserDescription.lineCount > LINE_COUNT_ORGANIZER) {
rootView.seeMoreOrganizer.isVisible = true
// Set up toggle organizer description
rootView.seeMoreOrganizer.setOnClickListener(organizerDescriptionListener)
rootView.eventOrganiserDescription.setOnClickListener(organizerDescriptionListener)
}
}
}
// About event on-click
val aboutEventOnClickListener = View.OnClickListener {
currentEvent?.let {
findNavController(rootView).navigate(EventDetailsFragmentDirections
.actionEventDetailsToAboutEvent(it.id))
}
}
// Event Description Section
val description = event.description.nullToEmpty().stripHtml()
if (!description.isNullOrEmpty()) {
rootView.eventDescription.post {
if (rootView.eventDescription.lineCount > LINE_COUNT) {
rootView.seeMore.isVisible = true
// start about fragment
rootView.eventDescription.setOnClickListener(aboutEventOnClickListener)
rootView.seeMore.setOnClickListener(aboutEventOnClickListener)
}
}
}
// load location to map
val mapClickListener = View.OnClickListener { startMap(event) }
if (!event.locationName.isNullOrEmpty() && hasCoordinates(event)) {
rootView.imageMap.setOnClickListener(mapClickListener)
rootView.eventLocationLinearLayout.setOnClickListener(mapClickListener)
Picasso.get()
.load(eventViewModel.loadMap(event))
.placeholder(R.drawable.ic_map_black)
.error(R.drawable.ic_map_black)
.into(rootView.imageMap)
} else {
rootView.imageMap.isVisible = false
}
// Date and Time section
rootView.eventDateDetailsFirst.text = EventUtils.getFormattedEventDateTimeRange(startsAt, endsAt)
rootView.eventDateDetailsSecond.text = EventUtils.getFormattedEventDateTimeRangeSecond(startsAt, endsAt)
// Add event to Calendar
val dateClickListener = View.OnClickListener { startCalendar(event) }
rootView.eventTimingLinearLayout.setOnClickListener(dateClickListener)
}
private fun hasCoordinates(event: Event): Boolean {
return event.longitude != null && event.longitude != 0.00 && event.latitude != null && event.latitude != 0.00
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
eventViewModel.connection
.nonNull()
.observe(viewLifecycleOwner, Observer { isConnected ->
if (isConnected) {
val currentFeedback = eventViewModel.eventFeedback.value
if (currentFeedback == null) {
currentEvent?.let { eventViewModel.fetchEventFeedback(it.id) }
} else {
feedbackAdapter.addAll(currentFeedback)
if (currentFeedback.isEmpty()) {
rootView.feedbackRv.isVisible = false
rootView.noFeedBackTv.isVisible = true
} else {
rootView.feedbackRv.isVisible = true
rootView.noFeedBackTv.isVisible = false
}
}
val currentSpeakers = eventViewModel.eventSpeakers.value
if (currentSpeakers == null) {
currentEvent?.let { eventViewModel.fetchEventSpeakers(it.id) }
} else {
speakersAdapter.addAll(currentSpeakers)
rootView.speakersContainer.isVisible = currentSpeakers.isNotEmpty()
}
val currentSessions = eventViewModel.eventSessions.value
if (currentSessions == null) {
currentEvent?.let { eventViewModel.fetchEventSessions(it.id) }
} else {
sessionsAdapter.addAll(currentSessions)
rootView.sessionContainer.isVisible = currentSessions.isNotEmpty()
}
val currentSponsors = eventViewModel.eventSponsors.value
if (currentSponsors == null) {
currentEvent?.let { eventViewModel.fetchEventSponsors(it.id) }
} else {
sponsorsAdapter.addAll(currentSponsors)
rootView.sponsorsSummaryContainer.isVisible = currentSponsors.isNotEmpty()
}
val currentSocialLinks = eventViewModel.socialLinks.value
if (currentSocialLinks == null) {
currentEvent?.let { eventViewModel.fetchSocialLink(it.id) }
} else {
socialLinkAdapter.addAll(currentSocialLinks)
rootView.socialLinkContainer.isVisible = currentSocialLinks.isNotEmpty()
}
}
})
val eventClickListener: EventClickListener = object : EventClickListener {
override fun onClick(eventID: Long, imageView: ImageView) {
findNavController(rootView)
.navigate(EventDetailsFragmentDirections.actionSimilarEventsToEventDetails(eventID),
FragmentNavigatorExtras(imageView to "eventDetailImage"))
}
}
val redirectToLogin = object : RedirectToLogin {
override fun goBackToLogin() {
redirectToLogin()
}
}
val favFabClickListener: FavoriteFabClickListener = object : FavoriteFabClickListener {
override fun onClick(event: Event, itemPosition: Int) {
if (eventViewModel.isLoggedIn()) {
event.favorite = !event.favorite
eventViewModel.setFavorite(event, event.favorite)
similarEventsAdapter.notifyItemChanged(itemPosition)
} else {
EventUtils.showLoginToLikeDialog(requireContext(),
layoutInflater, redirectToLogin, event.originalImageUrl, event.name)
}
}
}
similarEventsAdapter.apply {
onEventClick = eventClickListener
onFavFabClick = favFabClickListener
}
rootView.seeFeedbackTextView.setOnClickListener {
currentEvent?.let {
findNavController(rootView).navigate(EventDetailsFragmentDirections.actionEventDetailsToFeedback(it.id))
}
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
android.R.id.home -> {
activity?.onBackPressed()
true
}
R.id.add_to_calendar -> {
// Add event to Calendar
currentEvent?.let { startCalendar(it) }
true
}
R.id.report_event -> {
currentEvent?.let { reportEvent(it) }
true
}
R.id.open_external_event_url -> {
currentEvent?.externalEventUrl?.let { Utils.openUrl(requireContext(), it) }
true
}
R.id.favorite_event -> {
currentEvent?.let {
if (eventViewModel.isLoggedIn()) {
it.favorite = !it.favorite
eventViewModel.setFavorite(it, it.favorite)
currentEvent = it
} else {
EventUtils.showLoginToLikeDialog(requireContext(), layoutInflater, object : RedirectToLogin {
override fun goBackToLogin() { redirectToLogin() } }, it.originalImageUrl, it.name)
}
}
true
}
R.id.call_for_speakers -> {
currentEvent?.let {
findNavController(rootView).navigate(EventDetailsFragmentDirections
.actionEventDetailsToSpeakersCall(it.identifier, it.id, it.timezone))
}
true
}
R.id.event_share -> {
currentEvent?.let { EventUtils.share(it, requireContext()) }
return true
}
R.id.code_of_conduct -> {
currentEvent?.let { event ->
findNavController(rootView)
.navigate(EventDetailsFragmentDirections.actionEventDetailsToConductCode(event.id))
}
return true
}
R.id.open_faqs -> {
currentEvent?.let {
findNavController(rootView).navigate(EventDetailsFragmentDirections
.actionEventDetailsToFaq(it.id))
}
return true
}
else -> super.onOptionsItemSelected(item)
}
}
private fun startCalendar(event: Event) {
val intent = Intent(Intent.ACTION_INSERT)
intent.type = "vnd.android.cursor.item/event"
intent.putExtra(CalendarContract.Events.TITLE, event.name)
intent.putExtra(CalendarContract.Events.DESCRIPTION, event.description?.stripHtml())
intent.putExtra(CalendarContract.Events.EVENT_LOCATION, event.locationName)
intent.putExtra(CalendarContract.Events.CALENDAR_TIME_ZONE, event.timezone)
intent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME,
EventUtils.getTimeInMilliSeconds(event.startsAt, event.timezone))
intent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME,
EventUtils.getTimeInMilliSeconds(event.endsAt, event.timezone))
startActivity(intent)
}
private fun reportEvent(event: Event) {
val email = "[email protected]"
val subject = "Report of ${event.name} (${event.identifier})"
val body = "Let us know what's wrong"
val emailIntent = Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:$email"))
emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject)
emailIntent.putExtra(Intent.EXTRA_TEXT, body)
startActivity(Intent.createChooser(emailIntent, "Chooser Title"))
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.event_details, menu)
menuActionBar = menu
}
override fun onPrepareOptionsMenu(menu: Menu) {
currentEvent?.let { currentEvent ->
if (currentEvent.externalEventUrl.isNullOrBlank())
menu.findItem(R.id.open_external_event_url).isVisible = false
if (currentEvent.codeOfConduct.isNullOrBlank())
menu.findItem(R.id.code_of_conduct).isVisible = false
setFavoriteIconFilled(currentEvent.favorite)
}
super.onPrepareOptionsMenu(menu)
}
override fun onDestroyView() {
super.onDestroyView()
Picasso.get().cancelRequest(rootView.eventImage)
speakersAdapter.onSpeakerClick = null
sponsorsAdapter.onSponsorClick = null
sessionsAdapter.onSessionClick = null
similarEventsAdapter.apply {
onEventClick = null
onFavFabClick = null
}
}
private fun loadTicketFragment() {
val currency = currentEvent?.paymentCurrency ?: "USD"
currentEvent?.let {
findNavController(rootView).navigate(EventDetailsFragmentDirections
.actionEventDetailsToTickets(it.id, currency))
}
}
private fun startMap(event: Event) {
// start map intent
val mapUrl = loadMapUrl(event)
val mapIntent = Intent(Intent.ACTION_VIEW, Uri.parse(mapUrl))
val packageManager = activity?.packageManager
if (packageManager != null && mapIntent.resolveActivity(packageManager) != null) {
startActivity(mapIntent)
}
}
private fun setFavoriteIconFilled(filled: Boolean) {
val id = when {
filled -> R.drawable.ic_baseline_favorite_white
else -> R.drawable.ic_baseline_favorite_border_white
}
menuActionBar?.findItem(R.id.favorite_event)?.icon = ContextCompat.getDrawable(requireContext(), id)
}
private fun showEventErrorScreen(show: Boolean) {
rootView.container.isVisible = !show
rootView.eventErrorCard.isVisible = show
val menuItemSize = menuActionBar?.size() ?: 0
for (i in 0 until menuItemSize) {
menuActionBar?.getItem(i)?.isVisible = !show
}
}
private fun checkForAuthentication() {
if (eventViewModel.isLoggedIn())
writeFeedback()
else {
rootView.nestedContentEventScroll.longSnackbar(getString(R.string.log_in_first))
redirectToLogin()
}
}
private fun redirectToLogin() {
findNavController(rootView).navigate(EventDetailsFragmentDirections
.actionEventDetailsToAuth(getString(R.string.log_in_first), EVENT_DETAIL_FRAGMENT))
}
private fun writeFeedback() {
val layout = layoutInflater.inflate(R.layout.dialog_feedback, null)
val alertDialog = AlertDialog.Builder(requireContext())
.setTitle(getString(R.string.submit_feedback))
.setView(layout)
.setPositiveButton(getString(R.string.submit)) { _, _ ->
currentEvent?.let {
eventViewModel.submitFeedback(layout.feedback.text.toString(),
layout.feedbackrating.rating,
it.id)
}
}
.setNegativeButton(getString(R.string.cancel)) { dialog, _ ->
dialog.cancel()
}
.show()
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).isEnabled = false
layout.feedback.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(p0: Editable?) {
if (layout.feedback.text.toString().isNotEmpty()) {
layout.feedbackTextInputLayout.error = null
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).isEnabled = true
layout.feedbackTextInputLayout.isErrorEnabled = false
} else {
layout.feedbackTextInputLayout.error = getString(R.string.cant_be_empty)
}
}
override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) { /*Implement here*/ }
override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) { /*Implement here*/ }
})
}
private fun moveToSponsorSection() {
currentEvent?.let {
findNavController(rootView).navigate(EventDetailsFragmentDirections
.actionEventDetailsToSponsor(it.id))
}
}
}
| apache-2.0 | 7d111b54a2f6bb5e0d8438a3e7af6338 | 42.887755 | 120 | 0.640897 | 5.361172 | false | false | false | false |
cfig/Nexus_boot_image_editor | bbootimg/src/main/kotlin/avb/blob/Footer.kt | 1 | 4139 | // Copyright 2021 [email protected]
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package avb.blob
import cfig.io.Struct3
import java.io.File
import java.io.FileInputStream
import java.io.InputStream
/*
https://github.com/cfig/Android_boot_image_editor/blob/master/doc/layout.md#32-avb-footer-vboot-20
+---------------------------------------+-------------------------+ --> partition_size - block_size
| Padding | block_size - 64 |
+---------------------------------------+-------------------------+ --> partition_size - 64
| AVB Footer | total 64 |
| | |
| - Footer Magic "AVBf" | 4 |
| - Footer Major Version | 4 |
| - Footer Minor Version | 4 |
| - Original image size | 8 |
| - VBMeta offset | 8 |
| - VBMeta size | 8 |
| - Padding | 28 |
+---------------------------------------+-------------------------+ --> partition_size
*/
data class Footer constructor(
var versionMajor: Int = FOOTER_VERSION_MAJOR,
var versionMinor: Int = FOOTER_VERSION_MINOR,
var originalImageSize: Long = 0,
var vbMetaOffset: Long = 0,
var vbMetaSize: Long = 0
) {
@Throws(IllegalArgumentException::class)
constructor(iS: InputStream) : this() {
val info = Struct3(FORMAT_STRING).unpack(iS)
assert(7 == info.size)
if (MAGIC != (info[0] as String)) {
throw IllegalArgumentException("stream doesn't look like valid AVB Footer")
}
versionMajor = (info[1] as UInt).toInt()
versionMinor = (info[2] as UInt).toInt()
originalImageSize = (info[3] as ULong).toLong()
vbMetaOffset = (info[4] as ULong).toLong()
vbMetaSize = (info[5] as ULong).toLong()
}
constructor(originalImageSize: Long, vbMetaOffset: Long, vbMetaSize: Long)
: this(FOOTER_VERSION_MAJOR, FOOTER_VERSION_MINOR, originalImageSize, vbMetaOffset, vbMetaSize)
@Throws(IllegalArgumentException::class)
constructor(image_file: String) : this() {
FileInputStream(image_file).use { fis ->
fis.skip(File(image_file).length() - SIZE)
val footer = Footer(fis)
this.versionMajor = footer.versionMajor
this.versionMinor = footer.versionMinor
this.originalImageSize = footer.originalImageSize
this.vbMetaOffset = footer.vbMetaOffset
this.vbMetaSize = footer.vbMetaSize
}
}
fun encode(): ByteArray {
return Struct3(FORMAT_STRING).pack(MAGIC, //4s
this.versionMajor, //L
this.versionMinor, //L
this.originalImageSize, //Q
this.vbMetaOffset, //Q
this.vbMetaSize, //Q
null) //${RESERVED}x
}
companion object {
private const val MAGIC = "AVBf"
const val SIZE = 64
private const val RESERVED = 28
private const val FOOTER_VERSION_MAJOR = 1
private const val FOOTER_VERSION_MINOR = 0
private const val FORMAT_STRING = "!4s2L3Q${RESERVED}x"
init {
assert(SIZE == Struct3(FORMAT_STRING).calcSize())
}
}
}
| apache-2.0 | 4d673e8366d771213469012df18d4443 | 40.808081 | 107 | 0.522348 | 4.469762 | false | false | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/util/LocaleCache.kt | 1 | 1377 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.util
import org.lanternpowered.api.locale.Locales
import java.util.Locale
import java.util.concurrent.ConcurrentHashMap
object LocaleCache {
private val cache: MutableMap<String, Locale> = ConcurrentHashMap()
/**
* Gets the [Locale] for the given name.
*
* @param name The name
* @return The locale
*/
operator fun get(name: String): Locale = this.cache.computeIfAbsent(name.toLowerCase(Locale.ENGLISH)) {
val parts = name.split("_".toRegex(), 3).toTypedArray()
when (parts.size) {
3 -> Locale(parts[0].toLowerCase(), parts[1].toUpperCase(), parts[2])
2 -> Locale(parts[0].toLowerCase(), parts[1].toUpperCase())
else -> Locale(parts[0])
}
}
init {
for (field in Locales::class.java.fields) {
val name: String = field.name
if (name.indexOf('_') < 0)
continue
this.cache[name.toLowerCase(Locale.ENGLISH)] = field.get(null) as Locale
}
}
}
| mit | aaa716609b05074993af3593738be425 | 30.295455 | 107 | 0.626725 | 4.002907 | false | false | false | false |
androidx/androidx-ci-action | AndroidXCI/lib/src/main/kotlin/dev/androidx/ci/testRunner/dto/TestRun.kt | 1 | 3167 | /*
* Copyright 2021 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 dev.androidx.ci.testRunner.dto
import com.google.cloud.datastore.Entity
import com.google.cloud.datastore.FullEntity
import com.google.cloud.datastore.IncompleteKey
import com.google.cloud.datastore.Key
import com.squareup.moshi.Moshi
import com.squareup.moshi.Types
import dev.androidx.ci.datastore.DatastoreApi
import dev.androidx.ci.generated.ftl.EnvironmentMatrix
import dev.androidx.ci.testRunner.vo.ApkInfo
import dev.androidx.ci.util.sha256
import dev.zacsweers.moshix.reflect.MetadataKotlinJsonAdapterFactory
private const val PROP_TEST_MATRIX_ID = "testMatrixId"
/**
* Object that gets pushed into Datastore for each unique test run.
* Uniqueness of a TestRun is computed from its parameters, see [createId].
*/
internal class TestRun(
val id: Id,
val testMatrixId: String
) {
inline class Id(val key: Key)
/**
* Unique key for each test run. This is used to de-dup TestMatrix requests such that we won't recreate a TestMatrix
* if we've already run the exact same test.
*/
companion object {
private val adapter by lazy {
val type = Types.newParameterizedType(
Map::class.java,
String::class.java,
Any::class.java
)
val moshi = Moshi.Builder()
.add(MetadataKotlinJsonAdapterFactory())
.build()
moshi.adapter<Map<String, Any>>(type)
}
/**
* Creates a unique ID for the given parameters
*/
fun createId(
datastoreApi: DatastoreApi,
environment: EnvironmentMatrix,
appApk: ApkInfo,
testApk: ApkInfo
): Id {
val json = adapter.toJson(
mapOf(
"e" to environment,
"app" to appApk.idHash,
"test" to testApk.idHash
)
)
val sha = sha256(json.toByteArray(Charsets.UTF_8))
return Id(datastoreApi.createKey(datastoreApi.testRunObjectKind, sha))
}
}
}
internal fun TestRun.toEntity(): FullEntity<IncompleteKey> = Entity.newBuilder()
.set(PROP_TEST_MATRIX_ID, testMatrixId)
.setKey(id.key)
.build()
internal fun Entity.toTestRun(): TestRun? {
if (this.isNull(PROP_TEST_MATRIX_ID)) {
return null
}
val key = this.key ?: return null
val testMatrixId = this.getString(PROP_TEST_MATRIX_ID)
return TestRun(
id = TestRun.Id(key),
testMatrixId = testMatrixId
)
}
| apache-2.0 | 2fa8f2bd22f43be01b0db3392c2058c9 | 31.989583 | 120 | 0.649826 | 4.156168 | false | true | false | false |
WindSekirun/RichUtilsKt | RichUtils/src/main/java/pyxis/uzuki/live/richutilskt/utils/RConstructorBuilder.kt | 1 | 1091 | package pyxis.uzuki.live.richutilskt.utils
import kotlin.reflect.KClass
/**
* Class for generate Instance of given Class object
*
* Usages:
* 1. Constructor hasn't any parameter
* val sampleClassObj = RConstructorBuilder(SampleClass::class.java).newInstance()
*
* 2. Constructor has at least one parameter
* val sampleClass2Obj = RConstructorBuilder(SampleClass2::class.java)
* .addParameter(String::class.java, "ABC")
* .addParameter(Int::class, 20)
* .newInstance()
*
*/
class RConstructorBuilder<T>(private val targetCls: Class<T>) {
private val mMap = LinkedHashMap<Class<*>, Any?>()
fun addParameter(cls: Class<*>, value: Any?): RConstructorBuilder<T> = this.apply { mMap[cls] = value }
fun addParameter(cls: KClass<*>, value: Any?): RConstructorBuilder<T> = this.apply { mMap[cls.java] = value }
fun newInstance(map: Map<Class<*>, Any?> = mMap): T {
val keyArray = map.keys.toTypedArray()
val objArray = map.values.toTypedArray()
return targetCls.getConstructor(*keyArray).newInstance(*objArray)
}
} | apache-2.0 | a6a9e0148f805da274181274f7bc51fa | 34.225806 | 113 | 0.683776 | 3.841549 | false | false | false | false |
RoverPlatform/rover-android | core/src/main/kotlin/io/rover/sdk/core/Rover.kt | 1 | 3367 | package io.rover.sdk.core
import android.content.Context
import io.rover.core.BuildConfig
import io.rover.sdk.core.container.Assembler
import io.rover.sdk.core.container.ContainerResolver
import io.rover.sdk.core.container.InjectionContainer
import io.rover.sdk.core.data.http.AndroidHttpsUrlConnectionNetworkClient
import io.rover.sdk.core.logging.AndroidLogger
import io.rover.sdk.core.logging.GlobalStaticLogHolder
import io.rover.sdk.core.logging.LogBuffer
import io.rover.sdk.core.logging.log
import java.net.HttpURLConnection
/**
* Entry point for the Rover SDK.
*
* The Rover SDK consists of several discrete modules, which each offer a major vertical
* (eg. Experiences and Location) of the Rover Platform. It's up to you to select which
* are appropriate to activate in your app.
*
* TODO: exhaustive usage information.
*
* Serves as a dependency injection container for the various components (modules) of the Rover SDK.
*/
class Rover(
assemblers: List<Assembler>
) : ContainerResolver by InjectionContainer(assemblers) {
init {
// global, which we "inject" using static scope
GlobalStaticLogHolder.globalLogEmitter =
LogBuffer(
// uses the resolver to discover when the EventQueueService is ready and can be used
// to submit the logs.
AndroidLogger()
)
initializeContainer()
}
companion object {
private var sharedInstanceBackingField: Rover? = null
// we have a global singleton of the Rover container.
@JvmStatic
@Deprecated("Please use shared instead.")
val sharedInstance: Rover
get() = sharedInstanceBackingField ?: throw RuntimeException("Rover shared instance accessed before calling initialize.\n\n" +
"Did you remember to call Rover.initialize() in your Application.onCreate()?")
@JvmStatic
val shared: Rover?
get() = sharedInstanceBackingField ?: log.w("Rover shared instance accessed before calling initialize.\n\n" +
"Did you remember to call Rover.initialize() in your Application.onCreate()?").let { null }
@JvmStatic
fun initialize(vararg assemblers: Assembler) {
val rover = Rover(assemblers.asList())
if (sharedInstanceBackingField != null) {
throw RuntimeException("Rover SDK is already initialized. This is most likely a bug.")
}
sharedInstanceBackingField = rover
log.i("Started Rover Android SDK v${BuildConfig.ROVER_SDK_VERSION}.")
}
/**
* Be sure to always call this after [Rover.initialize] in your Application's onCreate()!
*
* Rover internally uses the standard HTTP client included with Android, but to work
* effectively it needs HTTP caching enabled. Unfortunately, this can only be done at the
* global level, so we ask that you call this method -- [installSaneGlobalHttpCache] -- at
* application start time (unless you have already added your own cache to Android's
* [HttpURLConnection].
*/
@JvmStatic
fun installSaneGlobalHttpCache(applicationContext: Context) {
AndroidHttpsUrlConnectionNetworkClient.installSaneGlobalHttpCache(applicationContext)
}
}
}
| apache-2.0 | 33a21f5842d51d6e9a85312b4c3a7c36 | 41.0875 | 138 | 0.684586 | 4.7223 | false | false | false | false |
GeoffreyMetais/vlc-android | application/vlc-android/src/org/videolan/vlc/gui/helpers/NotificationHelper.kt | 1 | 9461 | /*****************************************************************************
* NotificationHelper.java
*
* Copyright © 2017 VLC authors and VideoLAN
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*/
package org.videolan.vlc.gui.helpers
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.os.Build
import android.support.v4.media.session.MediaSessionCompat
import android.support.v4.media.session.PlaybackStateCompat
import androidx.annotation.RequiresApi
import androidx.core.app.NotificationCompat
import androidx.media.session.MediaButtonReceiver
import org.videolan.libvlc.util.AndroidUtil
import org.videolan.resources.*
import org.videolan.tools.getContextWithLocale
import org.videolan.tools.getMediaDescription
import org.videolan.vlc.R
private const val MEDIALIBRRARY_CHANNEL_ID = "vlc_medialibrary"
private const val PLAYBACK_SERVICE_CHANNEL_ID = "vlc_playback"
const val MISC_CHANNEL_ID = "misc"
private const val RECOMMENDATION_CHANNEL_ID = "vlc_recommendations"
object NotificationHelper {
const val TAG = "VLC/NotificationHelper"
private val sb = StringBuilder()
const val VLC_DEBUG_CHANNEL = "vlc_debug"
private val notificationIntent = Intent()
fun createPlaybackNotification(ctx: Context, video: Boolean, title: String, artist: String,
album: String, cover: Bitmap?, playing: Boolean, pausable: Boolean,
sessionToken: MediaSessionCompat.Token?,
spi: PendingIntent?): Notification {
val piStop = MediaButtonReceiver.buildMediaButtonPendingIntent(ctx, PlaybackStateCompat.ACTION_STOP)
val builder = NotificationCompat.Builder(ctx, PLAYBACK_SERVICE_CHANNEL_ID)
sb.setLength(0)
sb.append(title).append(" - ").append(artist)
builder.setSmallIcon(if (video) R.drawable.ic_notif_video else R.drawable.ic_notif_audio)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setContentTitle(title)
.setContentText(getMediaDescription(artist, album))
.setLargeIcon(cover)
.setTicker(sb.toString())
.setAutoCancel(!playing)
.setOngoing(playing)
.setCategory(NotificationCompat.CATEGORY_TRANSPORT)
.setDeleteIntent(piStop)
.addAction(NotificationCompat.Action(
R.drawable.ic_widget_previous_w, ctx.getString(R.string.previous),
MediaButtonReceiver.buildMediaButtonPendingIntent(ctx,
PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS)))
spi?.let { builder.setContentIntent(it) }
if (pausable) {
if (playing) builder.addAction(NotificationCompat.Action(
R.drawable.ic_widget_pause_w, ctx.getString(R.string.pause),
MediaButtonReceiver.buildMediaButtonPendingIntent(ctx,
PlaybackStateCompat.ACTION_PLAY_PAUSE)))
else builder.addAction(NotificationCompat.Action(
R.drawable.ic_widget_play_w, ctx.getString(R.string.play),
MediaButtonReceiver.buildMediaButtonPendingIntent(ctx,
PlaybackStateCompat.ACTION_PLAY_PAUSE)))
}
builder.addAction(NotificationCompat.Action(
R.drawable.ic_widget_next_w, ctx.getString(R.string.next),
MediaButtonReceiver.buildMediaButtonPendingIntent(ctx,
PlaybackStateCompat.ACTION_SKIP_TO_NEXT)))
if (!pausable) builder.addAction(NotificationCompat.Action(
R.drawable.ic_widget_close_w, ctx.getString(R.string.stop), piStop))
if (AndroidDevices.showMediaStyle) {
val mediaStyle = androidx.media.app.NotificationCompat.MediaStyle()
.setShowActionsInCompactView(0, 1, 2)
.setShowCancelButton(true)
.setCancelButtonIntent(piStop)
sessionToken?.let { mediaStyle.setMediaSession(it) }
builder.setStyle(mediaStyle)
}
return builder.build()
}
fun createScanNotification(ctx: Context, progressText: String, paused: Boolean): Notification {
val intent = Intent(Intent.ACTION_VIEW).setClassName(ctx, START_ACTIVITY)
val scanCompatBuilder = NotificationCompat.Builder(ctx, MEDIALIBRRARY_CHANNEL_ID)
.setContentIntent(PendingIntent.getActivity(ctx, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT))
.setSmallIcon(R.drawable.ic_notif_scan)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setContentTitle(ctx.getString(R.string.ml_scanning))
.setAutoCancel(false)
.setCategory(NotificationCompat.CATEGORY_PROGRESS)
.setOngoing(true)
scanCompatBuilder.setContentText(progressText)
notificationIntent.action = if (paused) ACTION_RESUME_SCAN else ACTION_PAUSE_SCAN
val pi = PendingIntent.getBroadcast(ctx.applicationContext.getContextWithLocale(AppContextProvider.locale), 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT)
val playpause = if (paused)
NotificationCompat.Action(R.drawable.ic_play_notif, ctx.getString(R.string.resume), pi)
else
NotificationCompat.Action(R.drawable.ic_pause_notif, ctx.getString(R.string.pause), pi)
scanCompatBuilder.addAction(playpause)
return scanCompatBuilder.build()
}
@RequiresApi(api = Build.VERSION_CODES.O)
fun createNotificationChannels(appCtx: Context) {
if (!AndroidUtil.isOOrLater) return
val notificationManager = appCtx.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val channels = mutableListOf<NotificationChannel>()
// Playback channel
if (notificationManager.getNotificationChannel(PLAYBACK_SERVICE_CHANNEL_ID) == null ) {
val name: CharSequence = appCtx.getString(R.string.playback)
val description = appCtx.getString(R.string.playback_controls)
val channel = NotificationChannel(PLAYBACK_SERVICE_CHANNEL_ID, name, NotificationManager.IMPORTANCE_LOW)
channel.description = description
channel.lockscreenVisibility = Notification.VISIBILITY_PUBLIC
channels.add(channel)
}
// Scan channel
if (notificationManager.getNotificationChannel(MEDIALIBRRARY_CHANNEL_ID) == null ) {
val name = appCtx.getString(R.string.medialibrary_scan)
val description = appCtx.getString(R.string.Medialibrary_progress)
val channel = NotificationChannel(MEDIALIBRRARY_CHANNEL_ID, name, NotificationManager.IMPORTANCE_LOW)
channel.description = description
channel.lockscreenVisibility = Notification.VISIBILITY_PUBLIC
channels.add(channel)
}
// Misc channel
if (notificationManager.getNotificationChannel(MISC_CHANNEL_ID) == null ) {
val name = appCtx.getString(R.string.misc)
val channel = NotificationChannel(MISC_CHANNEL_ID, name, NotificationManager.IMPORTANCE_LOW)
channel.lockscreenVisibility = Notification.VISIBILITY_PUBLIC
channels.add(channel)
}
// Recommendations channel
if (AndroidDevices.isAndroidTv && notificationManager.getNotificationChannel(RECOMMENDATION_CHANNEL_ID) == null) {
val name = appCtx.getString(R.string.recommendations)
val description = appCtx.getString(R.string.recommendations_desc)
val channel = NotificationChannel(RECOMMENDATION_CHANNEL_ID, name, NotificationManager.IMPORTANCE_LOW)
channel.description = description
channel.lockscreenVisibility = Notification.VISIBILITY_PUBLIC
channels.add(channel)
}
if (channels.isNotEmpty()) notificationManager.createNotificationChannels(channels)
}
@RequiresApi(api = Build.VERSION_CODES.O)
fun createDebugServcieChannel(appCtx: Context) {
val notificationManager = appCtx.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
// Playback channel
val name = appCtx.getString(R.string.debug_logs)
val channel = NotificationChannel(VLC_DEBUG_CHANNEL, name, NotificationManager.IMPORTANCE_LOW)
channel.lockscreenVisibility = Notification.VISIBILITY_PUBLIC
notificationManager.createNotificationChannel(channel)
}
}
| gpl-2.0 | afb09bed2b73754e3936833cacb116d0 | 50.978022 | 173 | 0.684144 | 4.950288 | false | false | false | false |
GeoffreyMetais/vlc-android | application/vlc-android/src/org/videolan/vlc/providers/medialibrary/VideoGroupsProvider.kt | 1 | 1489 | package org.videolan.vlc.providers.medialibrary
import android.content.Context
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch
import org.videolan.medialibrary.interfaces.Medialibrary
import org.videolan.medialibrary.interfaces.media.VideoGroup
import org.videolan.medialibrary.media.MediaLibraryItem
import org.videolan.tools.Settings
import org.videolan.vlc.viewmodels.SortableModel
class VideoGroupsProvider(context: Context, model: SortableModel) : MedialibraryProvider<MediaLibraryItem>(context, model) {
override fun canSortByDuration() = true
override fun canSortByInsertionDate() = true
override fun canSortByLastModified() = true
override fun canSortByMediaNumber() = true
override fun getAll() : Array<VideoGroup> = medialibrary.getVideoGroups(sort, desc, getTotalCount(), 0)
override fun getTotalCount() = medialibrary.getVideoGroupsCount(model.filterQuery)
override fun getPage(loadSize: Int, startposition: Int) : Array<MediaLibraryItem> = if (model.filterQuery.isNullOrEmpty()) {
medialibrary.getVideoGroups(sort, desc, loadSize, startposition)
} else {
medialibrary.searchVideoGroups(model.filterQuery, sort, desc, loadSize, startposition)
}.extractSingles().also { if (Settings.showTvUi) completeHeaders(it, startposition) }
}
private fun Array<VideoGroup>.extractSingles() = map {
if (it.mediaCount() == 1) it.media(Medialibrary.SORT_DEFAULT, false, 1, 0)[0] else it
}.toTypedArray() | gpl-2.0 | a06f904f28f751b8b3ebb5faa1abb9d4 | 45.5625 | 128 | 0.783747 | 4.366569 | false | false | false | false |
didi/DoraemonKit | Android/dokit-gps-mock/src/main/java/com/didichuxing/doraemonkit/gps_mock/sysservicehook/StartActivityMethodHandler.kt | 1 | 756 | package com.didichuxing.doraemonkit.gps_mock.sysservicehook
import com.didichuxing.doraemonkit.gps_mock.gpsmock.MethodHandler
import java.lang.reflect.Method
/**
* ================================================
* 作 者:jint(金台)
* 版 本:1.0
* 创建日期:2021/6/15-17:21
* 描 述:
* 修订历史:
* ================================================
*/
class StartActivityMethodHandler : MethodHandler() {
override fun onInvoke(originObject: Any, method: Method, args: Array<Any>?): Any? {
//LogHelper.i(TAG, "===method===$method $args")
return if (args == null) {
method.invoke(originObject, null)
} else {
method.invoke(originObject, *args)
}
}
}
| apache-2.0 | cb9e6e976fb1169ecb741047ef6561c0 | 28.583333 | 87 | 0.53662 | 3.837838 | false | false | false | false |
tasks/tasks | app/src/main/java/org/tasks/jobs/NotificationService.kt | 1 | 1773 | package org.tasks.jobs
import android.content.Intent
import android.os.IBinder
import com.todoroo.andlib.utility.AndroidUtilities
import com.todoroo.astrid.alarms.AlarmService
import dagger.hilt.android.AndroidEntryPoint
import org.tasks.Notifier
import org.tasks.R
import org.tasks.data.Alarm.Companion.TYPE_SNOOZE
import org.tasks.data.AlarmDao
import org.tasks.injection.InjectingService
import org.tasks.preferences.Preferences
import javax.inject.Inject
@AndroidEntryPoint
class NotificationService : InjectingService() {
@Inject lateinit var preferences: Preferences
@Inject lateinit var notifier: Notifier
@Inject lateinit var notificationQueue: NotificationQueue
@Inject lateinit var alarmDao: AlarmDao
@Inject lateinit var alarmService: AlarmService
override fun onBind(intent: Intent): IBinder? = null
override val notificationId = -1
override val notificationBody = R.string.building_notifications
override suspend fun doWork() {
AndroidUtilities.assertNotMainThread()
if (!preferences.isCurrentlyQuietHours) {
val overdueJobs = notificationQueue.overdueJobs
if (!notificationQueue.remove(overdueJobs)) {
throw RuntimeException("Failed to remove jobs from queue")
}
notifier.triggerNotifications(overdueJobs.map { it.toNotification() })
overdueJobs
.filter { it.type == TYPE_SNOOZE }
.takeIf { it.isNotEmpty() }
?.map { it.id }
?.let { alarmDao.deleteByIds(it) }
overdueJobs
.map { it.taskId }
.let { alarmService.scheduleAlarms(it) }
}
}
override fun scheduleNext() = notificationQueue.scheduleNext()
} | gpl-3.0 | fee1e9608455e6edf91b0fda67e34bb7 | 34.48 | 82 | 0.695995 | 4.6781 | false | false | false | false |
wiltonlazary/kotlin-native | backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/lower/VarargLowering.kt | 1 | 12788 | /*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.backend.konan.lower
import org.jetbrains.kotlin.backend.common.DeclarationContainerLoweringPass
import org.jetbrains.kotlin.backend.common.descriptors.synthesizedString
import org.jetbrains.kotlin.backend.common.ir.ir2string
import org.jetbrains.kotlin.backend.common.lower.createIrBuilder
import org.jetbrains.kotlin.backend.common.lower.irBlock
import org.jetbrains.kotlin.backend.konan.KonanBackendContext
import org.jetbrains.kotlin.builtins.PrimitiveType
import org.jetbrains.kotlin.builtins.UnsignedType
import org.jetbrains.kotlin.ir.IrElement
import org.jetbrains.kotlin.ir.builders.*
import org.jetbrains.kotlin.ir.declarations.*
import org.jetbrains.kotlin.ir.expressions.*
import org.jetbrains.kotlin.ir.expressions.impl.IrConstImpl
import org.jetbrains.kotlin.ir.expressions.impl.IrVarargImpl
import org.jetbrains.kotlin.ir.symbols.IrClassSymbol
import org.jetbrains.kotlin.ir.symbols.IrSymbol
import org.jetbrains.kotlin.ir.types.*
import org.jetbrains.kotlin.ir.util.*
import org.jetbrains.kotlin.ir.visitors.IrElementTransformerVoid
import org.jetbrains.kotlin.ir.visitors.transformChildrenVoid
import org.jetbrains.kotlin.util.OperatorNameConventions
internal class VarargInjectionLowering constructor(val context: KonanBackendContext): DeclarationContainerLoweringPass {
override fun lower(irDeclarationContainer: IrDeclarationContainer) {
irDeclarationContainer.declarations.forEach{
when (it) {
is IrField -> lower(it.symbol, it.initializer)
is IrFunction -> lower(it.symbol, it.body)
is IrProperty -> {
it.backingField?.let { field ->
lower(field.symbol, field)
}
it.getter?.let { getter ->
lower(getter.symbol, getter)
}
it.setter?.let { setter ->
lower(setter.symbol, setter)
}
}
}
}
}
private fun lower(owner: IrSymbol, element: IrElement?) {
element?.transformChildrenVoid(object: IrElementTransformerVoid() {
val transformer = this
private fun replaceEmptyParameterWithEmptyArray(expression: IrFunctionAccessExpression) {
val callee = expression.symbol.owner
log { "call of: ${callee.fqNameForIrSerialization}" }
context.createIrBuilder(owner, expression.startOffset, expression.endOffset).apply {
callee.valueParameters.forEach {
log { "varargElementType: ${it.varargElementType} expr: ${ir2string(expression.getValueArgument(it.index))}" }
}
callee.valueParameters
.filter { it.varargElementType != null && expression.getValueArgument(it.index) == null }
.forEach {
expression.putValueArgument(
it.index,
IrVarargImpl(
startOffset = startOffset,
endOffset = endOffset,
type = it.type,
varargElementType = it.varargElementType!!
)
)
}
}
expression.transformChildrenVoid(this)
}
override fun visitFunctionAccess(expression: IrFunctionAccessExpression): IrExpression {
replaceEmptyParameterWithEmptyArray(expression)
return expression
}
override fun visitVararg(expression: IrVararg): IrExpression {
expression.transformChildrenVoid(transformer)
val hasSpreadElement = hasSpreadElement(expression)
val irBuilder = context.createIrBuilder(owner, expression.startOffset, expression.endOffset)
return irBuilder.irBlock(expression, null, expression.type) {
val type = expression.varargElementType
log { "$expression: array type:$type, is array of primitives ${!expression.type.isArray()}" }
val arrayHandle = arrayType(expression.type)
val vars = expression.elements.map {
it to irTemporaryVar(
(it as? IrSpreadElement)?.expression ?: it as IrExpression,
"elem".synthesizedString
)
}.toMap()
val arraySize = calculateArraySize(arrayHandle, hasSpreadElement, scope, expression, vars)
val array = arrayHandle.createArray(this, expression.varargElementType, arraySize)
val arrayTmpVariable = irTemporaryVar(array, "array".synthesizedString)
lateinit var indexTmpVariable: IrVariable
if (hasSpreadElement)
indexTmpVariable = irTemporaryVar(kIntZero, "index".synthesizedString)
expression.elements.forEachIndexed { i, element ->
irBuilder.at(element.startOffset, element.endOffset)
log { "element:$i> ${ir2string(element)}" }
val dst = vars[element]!!
if (element !is IrSpreadElement) {
+irCall(arrayHandle.setMethodSymbol.owner).apply {
dispatchReceiver = irGet(arrayTmpVariable)
putValueArgument(0, if (hasSpreadElement) irGet(indexTmpVariable) else irConstInt(i))
putValueArgument(1, irGet(dst))
}
if (hasSpreadElement)
+incrementVariable(indexTmpVariable, kIntOne)
} else {
val arraySizeVariable = irTemporary(irArraySize(arrayHandle, irGet(dst)), "length".synthesizedString)
+irCall(arrayHandle.copyIntoSymbol.owner).apply {
extensionReceiver = irGet(dst)
putValueArgument(0, irGet(arrayTmpVariable)) /* destination */
putValueArgument(1, irGet(indexTmpVariable)) /* destinationOffset */
putValueArgument(2, kIntZero) /* startIndex */
putValueArgument(3, irGet(arraySizeVariable)) /* endIndex */
}
+incrementVariable(indexTmpVariable, irGet(arraySizeVariable))
log { "element:$i:spread element> ${ir2string(element.expression)}" }
}
}
+irGet(arrayTmpVariable)
}
}
})
}
private val symbols = context.ir.symbols
private val intPlusInt = symbols.intPlusInt.owner
private fun arrayType(type: IrType): ArrayHandle {
val arrayClass = type.classifierOrFail
return arrayToHandle[arrayClass] ?: error(arrayClass.descriptor)
}
private fun IrBuilderWithScope.intPlus() = irCall(intPlusInt)
private fun IrBuilderWithScope.increment(expression: IrExpression, value: IrExpression): IrExpression {
return intPlus().apply {
dispatchReceiver = expression
putValueArgument(0, value)
}
}
private fun IrBuilderWithScope.incrementVariable(variable: IrVariable, value: IrExpression): IrExpression {
return irSetVar(variable.symbol, intPlus().apply {
dispatchReceiver = irGet(variable)
putValueArgument(0, value)
})
}
private fun calculateArraySize(arrayHandle: ArrayHandle, hasSpreadElement: Boolean, scope:Scope, expression: IrVararg, vars: Map<IrVarargElement, IrVariable>): IrExpression {
context.createIrBuilder(scope.scopeOwnerSymbol, expression.startOffset, expression.endOffset).run {
if (!hasSpreadElement)
return irConstInt(expression.elements.size)
val notSpreadElementCount = expression.elements.filter { it !is IrSpreadElement}.size
val initialValue = irConstInt(notSpreadElementCount) as IrExpression
return vars.filter{it.key is IrSpreadElement}.toList().fold( initial = initialValue) { result, it ->
val arraySize = irArraySize(arrayHandle, irGet(it.second))
increment(result, arraySize)
}
}
}
private fun IrBuilderWithScope.irArraySize(arrayHandle: ArrayHandle, expression: IrExpression): IrExpression {
val arraySize = irCall(arrayHandle.sizeGetterSymbol.owner).apply {
dispatchReceiver = expression
}
return arraySize
}
private fun hasSpreadElement(expression: IrVararg?) = expression?.elements?.any { it is IrSpreadElement }?:false
private fun log(msg:() -> String) {
context.log { "VARARG-INJECTOR: ${msg()}" }
}
abstract inner class ArrayHandle(val arraySymbol: IrClassSymbol) {
val setMethodSymbol = arraySymbol.functions.single { it.descriptor.name == OperatorNameConventions.SET }
val sizeGetterSymbol = arraySymbol.getPropertyGetter("size")!!
val copyIntoSymbol = symbols.copyInto[arraySymbol.descriptor]!!
protected val singleParameterConstructor =
arraySymbol.owner.constructors.find { it.valueParameters.size == 1 }!!
abstract fun createArray(builder: IrBuilderWithScope, elementType: IrType, size: IrExpression): IrExpression
}
inner class ReferenceArrayHandle : ArrayHandle(symbols.array) {
override fun createArray(builder: IrBuilderWithScope, elementType: IrType, size: IrExpression): IrExpression {
return builder.irCall(singleParameterConstructor).apply {
putTypeArgument(0, elementType)
putValueArgument(0, size)
}
}
}
inner class PrimitiveArrayHandle(primitiveType: PrimitiveType)
: ArrayHandle(symbols.primitiveArrays[primitiveType]!!) {
override fun createArray(builder: IrBuilderWithScope, elementType: IrType, size: IrExpression): IrExpression {
return builder.irCall(singleParameterConstructor).apply {
putValueArgument(0, size)
}
}
}
inner class UnsignedArrayHandle(
arraySymbol: IrClassSymbol,
private val wrappedArrayHandle: PrimitiveArrayHandle
) : ArrayHandle(arraySymbol) {
override fun createArray(builder: IrBuilderWithScope, elementType: IrType, size: IrExpression): IrExpression {
val wrappedArray = wrappedArrayHandle.createArray(builder, elementType, size)
return builder.irCall(singleParameterConstructor).apply {
putValueArgument(0, wrappedArray)
}
}
}
private val primitiveArrayHandles = PrimitiveType.values().associate { it to PrimitiveArrayHandle(it) }
private val unsignedArrayHandles = UnsignedType.values().mapNotNull { unsignedType ->
symbols.unsignedArrays[unsignedType]?.let {
val primitiveType = when (unsignedType) {
UnsignedType.UBYTE -> PrimitiveType.BYTE
UnsignedType.USHORT -> PrimitiveType.SHORT
UnsignedType.UINT -> PrimitiveType.INT
UnsignedType.ULONG -> PrimitiveType.LONG
}
UnsignedArrayHandle(it, primitiveArrayHandles[primitiveType]!!)
}
}
val arrayToHandle =
(primitiveArrayHandles.values + unsignedArrayHandles + ReferenceArrayHandle()).associateBy { it.arraySymbol }
}
private fun IrBuilderWithScope.irConstInt(value: Int): IrConst<Int> =
IrConstImpl.int(startOffset, endOffset, context.irBuiltIns.intType, value)
private val IrBuilderWithScope.kIntZero get() = irConstInt(0)
private val IrBuilderWithScope.kIntOne get() = irConstInt(1)
| apache-2.0 | 0e33f0d610c3440b64c8e0bf3f7487de | 47.80916 | 178 | 0.623006 | 5.386689 | false | false | false | false |
nemerosa/ontrack | ontrack-ui-support/src/main/java/net/nemerosa/ontrack/ui/resource/Pagination.kt | 1 | 2366 | package net.nemerosa.ontrack.ui.resource
import net.nemerosa.ontrack.model.support.Page
import java.net.URI
data class Pagination(
val offset: Int,
val limit: Int,
val total: Int,
val prev: URI? = null,
val next: URI? = null
) {
fun withPrev(uri: URI?) =
Pagination(
offset,
limit,
total,
uri,
next
)
fun withNext(uri: URI?) =
Pagination(
offset,
limit,
total,
prev,
uri
)
companion object {
@JvmField
val NONE: Pagination? = null
@JvmStatic
fun of(offset: Int, limit: Int, total: Int): Pagination {
return Pagination(
offset,
limit,
total,
null,
null
)
}
@JvmStatic
fun <T> paginate(
items: List<T>,
page: Page,
uriSupplier: (Int, Int) -> URI
): PaginatedList<T> {
val offset = page.offset
val limit = page.count
val total = items.size
val paginatedList = items.subList(offset, minOf(offset + limit, total))
val actualCount = paginatedList.size
var pagination = Pagination(offset, actualCount, total)
// Previous page
if (offset > 0) {
pagination = pagination.withPrev(
uriSupplier(
maxOf(0, offset - limit),
limit
)
)
}
// Next page
if (offset + limit < total) {
pagination = pagination.withNext(
uriSupplier(
offset + limit,
limit
)
)
}
// OK
return PaginatedList(
paginatedList,
pagination
)
}
}
}
data class PaginatedList<out T>(
val items: List<T>,
val pagination: Pagination
)
| mit | 9e22195e06051f6de2f024eefd8ef902 | 25 | 83 | 0.393491 | 5.646778 | false | false | false | false |
nemerosa/ontrack | ontrack-kdsl/src/main/java/net/nemerosa/ontrack/kdsl/connector/support/DefaultConnector.kt | 1 | 2183 | package net.nemerosa.ontrack.kdsl.connector.support
import net.nemerosa.ontrack.kdsl.connector.Connector
import net.nemerosa.ontrack.kdsl.connector.ConnectorResponse
import net.nemerosa.ontrack.kdsl.connector.ConnectorResponseBody
import org.springframework.boot.web.client.RestTemplateBuilder
import org.springframework.http.ResponseEntity
import org.springframework.web.client.RestTemplate
import org.springframework.web.client.getForEntity
import org.springframework.web.client.postForEntity
import java.nio.charset.Charset
class DefaultConnector(
override val url: String,
private val defaultHeaders: Map<String, String> = emptyMap(),
) : Connector {
override val token: String?
get() = defaultHeaders["X-Ontrack-Token"]
override fun get(path: String, headers: Map<String, String>): ConnectorResponse {
val response = restTemplate(headers).getForEntity<ByteArray>(path)
return RestTemplateConnectorResponse(response)
}
class RestTemplateConnectorResponse(
private val response: ResponseEntity<ByteArray>,
) : ConnectorResponse {
override val statusCode: Int
get() = response.statusCodeValue
override val body: ConnectorResponseBody = object : ConnectorResponseBody {
override fun asText(charset: Charset): String =
response.body?.toString(charset) ?: ""
}
}
override fun post(path: String, headers: Map<String, String>, body: Any?): ConnectorResponse {
val response = restTemplate(headers).postForEntity<ByteArray>(path, body)
return RestTemplateConnectorResponse(response)
}
override fun put(path: String, headers: Map<String, String>, body: Any?) {
restTemplate(headers).put(path, body)
}
private fun restTemplate(
headers: Map<String, String>,
): RestTemplate {
var builder = RestTemplateBuilder().rootUri(url)
defaultHeaders.forEach { (name, value) ->
builder = builder.defaultHeader(name, value)
}
headers.forEach { (name, value) ->
builder = builder.defaultHeader(name, value)
}
return builder.build()
}
} | mit | b3918b1adbf43c9d97125bfb7a1896b5 | 36.655172 | 98 | 0.704535 | 4.66453 | false | false | false | false |
cbeust/kobalt | modules/kobalt-plugin-api/src/main/kotlin/com/beust/kobalt/misc/Io.kt | 2 | 2335 | package com.beust.kobalt.misc
import java.io.File
import java.nio.file.*
class Io(val dryRun: Boolean = false) {
fun mkdirs(dir: String) {
kobaltLog("mkdirs $dir")
if (! dryRun) {
File(dir).mkdirs()
}
}
fun rm(path: String) {
kobaltLog("rm $path")
if (! dryRun) {
File(path).deleteRecursively()
}
}
fun moveFile(from: File, toDir: File) {
kobaltLog("mv $from $toDir")
if (! dryRun) {
require(from.exists(), { -> "$from should exist" })
require(from.isFile, { -> "$from should be a file" })
require(toDir.isDirectory, { -> "$toDir should be a file"})
val toFile = File(toDir, from.name)
Files.move(Paths.get(from.absolutePath), Paths.get(toFile.absolutePath), StandardCopyOption.ATOMIC_MOVE)
}
}
fun rename(from: File, to: File) {
kobaltLog("rename $from $to")
moveFile(from, to.parentFile)
if (from.name != to.name) {
File(to, from.name).renameTo(to)
}
}
fun copyDirectory(from: File, toDir: File) {
kobaltLog("cp -r $from $toDir")
if (! dryRun) {
KFiles.copyRecursively(from, toDir)
require(from.exists(), { -> "$from should exist" })
require(from.isDirectory, { -> kobaltLog(1, "$from should be a directory")})
require(toDir.isDirectory, { -> kobaltLog(1, "$toDir should be a file")})
}
}
fun rmDir(dir: File, keep: (File) -> Boolean = { t -> false }) = rmDir(dir, keep, " ")
private fun rmDir(dir: File, keep: (File) -> Boolean, indent : String) {
kobaltLog("rm -rf $dir")
require(dir.isDirectory, { -> kobaltLog(1, "$dir should be a directory")})
dir.listFiles({ p0 -> ! keep(p0!!) }).forEach {
if (it.isDirectory) {
rmDir(it, keep, indent + " ")
it.deleteRecursively()
}
else {
kobaltLog(indent + "rm $it")
if (! dryRun) it.delete()
}
}
}
fun mkdir(dir: File) {
kobaltLog("mkdir $dir")
if (! dryRun) {
dir.mkdirs()
}
}
private fun kobaltLog(s: String) {
kobaltLog(1, "[Io] $s")
}
}
| apache-2.0 | 38c80ccbb48018a5c1e5ffb461221e26 | 26.797619 | 116 | 0.509208 | 3.846787 | false | false | false | false |
nickbutcher/plaid | dribbble/src/main/java/io/plaidapp/dribbble/ui/shot/ShotActivity.kt | 1 | 8804 | /*
* Copyright 2018 Google LLC.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.plaidapp.dribbble.ui.shot
import android.animation.ValueAnimator
import android.app.Activity
import android.app.assist.AssistContent
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.util.TypedValue
import androidx.appcompat.app.AppCompatActivity
import androidx.browser.customtabs.CustomTabsIntent
import androidx.core.app.ShareCompat
import androidx.core.content.ContextCompat
import androidx.core.net.toUri
import androidx.lifecycle.Observer
import androidx.palette.graphics.Palette
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import io.plaidapp.core.ui.widget.ElasticDragDismissFrameLayout
import io.plaidapp.core.util.Activities
import io.plaidapp.core.util.AnimUtils.getFastOutSlowInInterpolator
import io.plaidapp.core.util.ColorUtils
import io.plaidapp.core.util.ViewUtils
import io.plaidapp.core.util.customtabs.CustomTabActivityHelper
import io.plaidapp.core.util.delegates.contentView
import io.plaidapp.core.util.event.EventObserver
import io.plaidapp.core.util.glide.getBitmap
import io.plaidapp.dribbble.R
import io.plaidapp.dribbble.dagger.inject
import io.plaidapp.dribbble.databinding.ActivityDribbbleShotBinding
import io.plaidapp.dribbble.domain.ShareShotInfo
import javax.inject.Inject
/**
* Activity displaying a single Dribbble shot.
*/
class ShotActivity : AppCompatActivity() {
@Inject
internal lateinit var viewModel: ShotViewModel
internal lateinit var chromeFader: ElasticDragDismissFrameLayout.SystemChromeFader
private val binding by contentView<ShotActivity, ActivityDribbbleShotBinding>(
R.layout.activity_dribbble_shot
)
private var largeAvatarSize: Int = 0
private val shotLoadListener = object : RequestListener<Drawable> {
override fun onResourceReady(
resource: Drawable,
model: Any,
target: Target<Drawable>,
dataSource: DataSource,
isFirstResource: Boolean
): Boolean {
val bitmap = resource.getBitmap() ?: return false
Palette.from(bitmap)
.clearFilters() /* by default palette ignore certain hues
(e.g. pure black/white) but we don't want this. */
.generate { palette -> applyFullImagePalette(palette) }
val twentyFourDip = TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
24f,
[email protected]
).toInt()
Palette.from(bitmap)
.maximumColorCount(3)
.clearFilters()
.setRegion(0, 0, bitmap.width - 1, twentyFourDip) /* - 1 to work around
https://code.google.com/p/android/issues/detail?id=191013 */
.generate { palette -> applyTopPalette(bitmap, palette) }
// TODO should keep the background if the image contains transparency?!
binding.shot.background = null
return false
}
override fun onLoadFailed(
e: GlideException?,
model: Any,
target: Target<Drawable>,
isFirstResource: Boolean
) = false
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val shotId = intent.getLongExtra(Activities.Dribbble.Shot.EXTRA_SHOT_ID, -1L)
if (shotId == -1L) {
finishAfterTransition()
}
inject(shotId)
largeAvatarSize = resources.getDimensionPixelSize(io.plaidapp.R.dimen.large_avatar_size)
binding.viewModel = viewModel.also { vm ->
vm.openLink.observe(this, EventObserver { openLink(it) })
vm.shareShot.observe(this, EventObserver { shareShot(it) })
vm.shotUiModel.observe(this, Observer {
binding.uiModel = it
})
}
binding.shotLoadListener = shotLoadListener
binding.apply {
bodyScroll.setOnScrollChangeListener { _, _, scrollY, _, _ ->
shot.offset = -scrollY
}
back.setOnClickListener { setResultAndFinish() }
}
chromeFader = object : ElasticDragDismissFrameLayout.SystemChromeFader(this) {
override fun onDragDismissed() {
setResultAndFinish()
}
}
}
override fun onResume() {
super.onResume()
binding.draggableFrame.addListener(chromeFader)
}
override fun onPause() {
binding.draggableFrame.removeListener(chromeFader)
super.onPause()
}
override fun onBackPressed() {
setResultAndFinish()
}
override fun onNavigateUp(): Boolean {
setResultAndFinish()
return true
}
override fun onProvideAssistContent(outContent: AssistContent) {
outContent.webUri = viewModel.getAssistWebUrl().toUri()
}
private fun openLink(url: String) {
CustomTabActivityHelper.openCustomTab(
this,
CustomTabsIntent.Builder()
.setToolbarColor(
ContextCompat.getColor(this@ShotActivity, io.plaidapp.R.color.dribbble)
)
.addDefaultShareMenuItem()
.build(),
url
)
}
private fun shareShot(shareInfo: ShareShotInfo) {
with(shareInfo) {
ShareCompat.IntentBuilder.from(this@ShotActivity)
.setText(shareText)
.setSubject(title)
.setStream(imageUri)
.setType(mimeType)
.startChooser()
}
}
internal fun applyFullImagePalette(palette: Palette?) {
// color the ripple on the image spacer (default is grey)
binding.shotSpacer.background = ViewUtils.createRipple(
palette, 0.25f, 0.5f,
ContextCompat.getColor(this@ShotActivity, io.plaidapp.R.color.mid_grey), true
)
// slightly more opaque ripple on the pinned image to compensate for the scrim
binding.shot.foreground = ViewUtils.createRipple(
palette, 0.3f, 0.6f,
ContextCompat.getColor(this@ShotActivity, io.plaidapp.R.color.mid_grey), true
)
}
internal fun applyTopPalette(bitmap: Bitmap, palette: Palette?) {
val lightness = ColorUtils.isDark(palette)
val isDark = if (lightness == ColorUtils.LIGHTNESS_UNKNOWN) {
ColorUtils.isDark(bitmap, bitmap.width / 2, 0)
} else {
lightness == ColorUtils.IS_DARK
}
if (!isDark) { // make back icon dark on light images
binding.back.setColorFilter(
ContextCompat.getColor(this@ShotActivity, io.plaidapp.R.color.dark_icon)
)
}
// color the status bar.
var statusBarColor = window.statusBarColor
ColorUtils.getMostPopulousSwatch(palette)?.let {
statusBarColor = ColorUtils.scrimify(it.rgb, isDark, SCRIM_ADJUSTMENT)
// set a light status bar
if (!isDark) {
ViewUtils.setLightStatusBar(binding.shot)
}
}
if (statusBarColor != window.statusBarColor) {
binding.shot.setScrimColor(statusBarColor)
ValueAnimator.ofArgb(window.statusBarColor, statusBarColor).apply {
addUpdateListener { animation ->
window.statusBarColor = animation.animatedValue as Int
}
duration = 1000L
interpolator = getFastOutSlowInInterpolator(this@ShotActivity)
}.start()
}
}
internal fun setResultAndFinish() {
val resultData = Intent().apply {
putExtra(Activities.Dribbble.Shot.RESULT_EXTRA_SHOT_ID, viewModel.getShotId())
}
setResult(Activity.RESULT_OK, resultData)
finishAfterTransition()
}
companion object {
private const val SCRIM_ADJUSTMENT = 0.075f
}
}
| apache-2.0 | 19143de8c27cb4290e5a03e702cf8790 | 34.075697 | 96 | 0.647774 | 4.764069 | false | false | false | false |
BOINC/boinc | android/BOINC/app/src/main/java/edu/berkeley/boinc/rpc/TimePreferencesClasses.kt | 4 | 2969 | /*
* This file is part of BOINC.
* http://boinc.berkeley.edu
* Copyright (C) 2020 University of California
*
* BOINC is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* BOINC is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with BOINC. If not, see <http://www.gnu.org/licenses/>.
*/
package edu.berkeley.boinc.rpc
import android.os.Parcel
import android.os.Parcelable
data class TimeSpan(var startHour: Double = 0.0, var endHour: Double = 0.0)
data class TimePreferences(
var startHour: Double = 0.0,
var endHour: Double = 0.0,
var weekPrefs: Array<TimeSpan?> = arrayOfNulls(7)
) : Parcelable {
private constructor(parcel: Parcel): this() {
val dArray = parcel.createDoubleArray()!!
startHour = dArray[0]
endHour = dArray[1]
var i = 2
while (i <= 14) {
val index = i / 2 - 1
if (dArray[i] != Double.NEGATIVE_INFINITY) {
weekPrefs[index]!!.startHour = dArray[i]
weekPrefs[index]!!.endHour = dArray[i + 1]
} else {
weekPrefs[index] = null
}
i += 2
}
}
override fun describeContents() = 0
override fun writeToParcel(dest: Parcel, flags: Int) {
val weekPrefValues = mutableListOf(startHour, endHour)
for (i in 0..6) {
weekPrefValues.add(weekPrefs[i]?.startHour ?: Double.NEGATIVE_INFINITY)
weekPrefValues.add(weekPrefs[i]?.endHour ?: Double.NEGATIVE_INFINITY)
}
dest.writeDoubleArray(weekPrefValues.toDoubleArray())
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
return other is TimePreferences && startHour == other.startHour &&
endHour == other.endHour && weekPrefs.contentEquals(other.weekPrefs)
}
override fun hashCode(): Int {
var result = startHour.hashCode()
result = 31 * result + endHour.hashCode()
result = 31 * result + weekPrefs.contentHashCode()
return result
}
object Fields {
const val START_HOUR = "startHour"
const val END_HOUR = "endHour"
}
companion object {
@JvmField
val CREATOR: Parcelable.Creator<TimePreferences> = object : Parcelable.Creator<TimePreferences> {
override fun createFromParcel(parcel: Parcel) = TimePreferences(parcel)
override fun newArray(size: Int) = arrayOfNulls<TimePreferences>(size)
}
}
}
| lgpl-3.0 | 49320eba6562716e900319dd4f65d0d1 | 33.126437 | 105 | 0.634894 | 4.290462 | false | false | false | false |
martin-nordberg/KatyDOM | Katydid-VDOM-JS/src/main/kotlin/i/katydid/vdom/elements/text/KatydidA.kt | 1 | 4098 | //
// (C) Copyright 2017-2019 Martin E. Nordberg III
// Apache 2.0 License
//
package i.katydid.vdom.elements.text
import i.katydid.vdom.builders.KatydidFlowContentBuilderImpl
import i.katydid.vdom.builders.KatydidPhrasingContentBuilderImpl
import i.katydid.vdom.elements.KatydidHtmlElementImpl
import o.katydid.vdom.builders.KatydidFlowContentBuilder
import o.katydid.vdom.builders.KatydidPhrasingContentBuilder
import o.katydid.vdom.types.EAnchorHtmlLinkType
import o.katydid.vdom.types.EDirection
//---------------------------------------------------------------------------------------------------------------------
/**
* Virtual node for an anchor <a> element.
*/
internal class KatydidA<Msg> : KatydidHtmlElementImpl<Msg> {
constructor(
phrasingContent: KatydidPhrasingContentBuilderImpl<Msg>,
selector: String?,
key: Any?,
accesskey: Char?,
contenteditable: Boolean?,
dir: EDirection?,
download: String?,
draggable: Boolean?,
hidden: Boolean?,
href: String?,
hreflang: String?,
lang: String?,
rel: Iterable<EAnchorHtmlLinkType>?,
rev: Iterable<EAnchorHtmlLinkType>?,
spellcheck: Boolean?,
style: String?,
tabindex: Int?,
target: String?,
title: String?,
translate: Boolean?,
type: String?,
defineContent: KatydidPhrasingContentBuilder<Msg>.() -> Unit
) : super(selector, key, accesskey, contenteditable, dir, draggable,
hidden, lang, spellcheck, style, tabindex, title, translate) {
phrasingContent.contentRestrictions.confirmAnchorAllowed()
if (href != null) {
phrasingContent.contentRestrictions.confirmInteractiveContentAllowed()
}
setAttributes(download, href, hreflang, rel, rev, target, type)
phrasingContent.withInteractiveContentNotAllowed(this).defineContent()
this.freeze()
}
constructor(
flowContent: KatydidFlowContentBuilderImpl<Msg>,
selector: String?,
key: Any?,
accesskey: Char?,
contenteditable: Boolean?,
dir: EDirection?,
download: String?,
draggable: Boolean?,
hidden: Boolean?,
href: String?,
hreflang: String?,
lang: String?,
rel: Iterable<EAnchorHtmlLinkType>?,
rev: Iterable<EAnchorHtmlLinkType>?,
spellcheck: Boolean?,
style: String?,
tabindex: Int?,
target: String?,
title: String?,
translate: Boolean?,
type: String?,
defineContent: KatydidFlowContentBuilder<Msg>.() -> Unit
) : super(selector, key, accesskey, contenteditable, dir, draggable,
hidden, lang, spellcheck, style, tabindex, title, translate) {
flowContent.contentRestrictions.confirmAnchorAllowed()
if (href != null) {
flowContent.contentRestrictions.confirmInteractiveContentAllowed()
}
setAttributes(download, href, hreflang, rel, rev, target, type)
flowContent.withInteractiveContentNotAllowed(this).defineContent()
this.freeze()
}
private fun setAttributes(
download: String?,
href: String?,
hreflang: String?,
rel: Iterable<EAnchorHtmlLinkType>?,
rev: Iterable<EAnchorHtmlLinkType>?,
target: String?,
type: String?
) {
this.setAttribute("download", download)
this.setAttribute("href", href)
this.setAttribute("hreflang", hreflang)
if (rel != null) {
this.setAttribute("rel", rel.joinToString(" ", transform = EAnchorHtmlLinkType::toHtmlString))
}
if (rev != null) {
this.setAttribute("rev", rev.joinToString(" ", transform = EAnchorHtmlLinkType::toHtmlString))
}
this.setAttribute("target", target)
this.setAttribute("type", type)
}
////
override val nodeName = "A"
}
//---------------------------------------------------------------------------------------------------------------------
| apache-2.0 | 7a53cfe5d311016369f4ddba70f2f27e | 30.523077 | 119 | 0.600537 | 4.997561 | false | false | false | false |
werelord/nullpod | nullpodApp/src/main/kotlin/com/cyrix/util/CxLogger.kt | 1 | 9540 |
/**
* This is modified version of CxLogger, found here:
* https://github.com/Kotlin/anko/blob/master/anko/library/static/commons/src/Logging.kt
*
* Copyright 2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("unused", "NOTHING_TO_INLINE", "NAME_SHADOWING")
@file:JvmName("Logging")
package com.cyrix.util
import android.util.Log
import com.cyrix.nullpod.BuildConfig
/**
* Interface for the Anko logger.
* Normally you should pass the logger tag to the [Log] methods, such as [Log.d] or [Log.e].
* This can be inconvenient because you should store the tag somewhere or hardcode it,
* which is considered to be a bad practice.
*
* Instead of hardcoding tags, Anko provides an [CxLogger] interface. You can just add the interface to
* any of your classes, and use any of the provided extension functions, such as
* [CxLogger.debug] or [CxLogger.error].
*
* The tag is the simple class name by default, but you can change it to anything you want just
* by overriding the [loggerTag] property.
*/
interface CxLogger {
/**
* The logger tag used in extension functions for the [CxLogger].
* Note that the tag length should not be more than 23 symbols.
*/
val loggerTag: String
get() = getTag(javaClass)
}
fun CxLogger(clazz: Class<*>): CxLogger = object : CxLogger {
override val loggerTag = getTag(clazz)
}
fun CxLogger(tag: String): CxLogger = object : CxLogger {
init {
assert(tag.length <= 23) { "The maximum tag length is 23, got $tag" }
}
override val loggerTag = tag
}
inline fun <reified T: Any> CxLogger(): CxLogger = CxLogger(T::class.java)
/**
* Send a log message with the [Log.VERBOSE] severity.
* Note that the log message will not be written if the current log level is above [Log.VERBOSE].
* The default log level is [Log.INFO].
*
* @param message the message text to log. `null` value will be represent as "null", for any other value
* the [Any.toString] will be invoked.
* @param thr an exception to log (optional).
*
* @see [Log.v].
*/
fun CxLogger.verbose(message: Any?, thr: Throwable? = null) {
log(this, message, thr, Log.VERBOSE,
{ tag, msg -> Log.v(tag, msg) },
{ tag, msg, thr -> Log.v(tag, msg, thr) })
}
/**
* Send a log message with the [Log.DEBUG] severity.
* Note that the log message will not be written if the current log level is above [Log.DEBUG].
* The default log level is [Log.INFO].
*
* @param message the message text to log. `null` value will be represent as "null", for any other value
* the [Any.toString] will be invoked.
* @param thr an exception to log (optional).
*
* @see [Log.d].
*/
fun CxLogger.debug(message: Any?, thr: Throwable? = null) {
log(this, message, thr, Log.DEBUG,
{ tag, msg -> Log.d(tag, msg) },
{ tag, msg, thr -> Log.d(tag, msg, thr) })
}
/**
* Send a log message with the [Log.INFO] severity.
* Note that the log message will not be written if the current log level is above [Log.INFO]
* (it is the default level).
*
* @param message the message text to log. `null` value will be represent as "null", for any other value
* the [Any.toString] will be invoked.
* @param thr an exception to log (optional).
*
* @see [Log.i].
*/
fun CxLogger.info(message: Any?, thr: Throwable? = null) {
log(this, message, thr, Log.INFO,
{ tag, msg -> Log.i(tag, msg) },
{ tag, msg, thr -> Log.i(tag, msg, thr) })
}
/**
* Send a log message with the [Log.WARN] severity.
* Note that the log message will not be written if the current log level is above [Log.WARN].
* The default log level is [Log.INFO].
*
* @param message the message text to log. `null` value will be represent as "null", for any other value
* the [Any.toString] will be invoked.
* @param thr an exception to log (optional).
*
* @see [Log.w].
*/
fun CxLogger.warn(message: Any?, thr: Throwable? = null) {
log(this, message, thr, Log.WARN,
{ tag, msg -> Log.w(tag, msg) },
{ tag, msg, thr -> Log.w(tag, msg, thr) })
}
/**
* Send a log message with the [Log.ERROR] severity.
* Note that the log message will not be written if the current log level is above [Log.ERROR].
* The default log level is [Log.INFO].
*
* @param message the message text to log. `null` value will be represent as "null", for any other value
* the [Any.toString] will be invoked.
* @param thr an exception to log (optional).
*
* @see [Log.e].
*/
fun CxLogger.error(message: Any?, thr: Throwable? = null) {
log(this, message, thr, Log.ERROR,
{ tag, msg -> Log.e(tag, msg) },
{ tag, msg, thr -> Log.e(tag, msg, thr) })
}
/**
* Send a log message with the "What a Terrible Failure" severity.
* Report an exception that should never happen.
*
* @param message the message text to log. `null` value will be represent as "null", for any other value
* the [Any.toString] will be invoked.
* @param thr an exception to log (optional).
*
* @see [Log.wtf].
*/
fun CxLogger.wtf(message: Any?, thr: Throwable? = null) {
if (thr != null) {
Log.wtf(loggerTag, message?.toString() ?: "null", thr)
} else {
Log.wtf(loggerTag, message?.toString() ?: "null")
}
}
/**
* Send a log message with the [Log.VERBOSE] severity.
* Note that the log message will not be written if the current log level is above [Log.VERBOSE].
* The default log level is [Log.INFO].
*
* @param message the function that returns message text to log.
* `null` value will be represent as "null", for any other value the [Any.toString] will be invoked.
*
* @see [Log.v].
*/
inline fun CxLogger.verbose(message: () -> Any?) {
val tag = loggerTag
//if (Log.isLoggable(tag, Log.VERBOSE)) {
if (BuildConfig.debugLogging) {
Log.v(tag, message()?.toString() ?: "null")
}
}
/**
* Send a log message with the [Log.DEBUG] severity.
* Note that the log message will not be written if the current log level is above [Log.DEBUG].
* The default log level is [Log.INFO].
*
* @param message the function that returns message text to log.
* `null` value will be represent as "null", for any other value the [Any.toString] will be invoked.
*
* @see [Log.d].
*/
inline fun CxLogger.debug(message: () -> Any?) {
val tag = loggerTag
//if (Log.isLoggable(tag, Log.DEBUG)) {
if (BuildConfig.debugLogging) {
Log.d(tag, message()?.toString() ?: "null")
}
}
/**
* Send a log message with the [Log.INFO] severity.
* Note that the log message will not be written if the current log level is above [Log.INFO].
* The default log level is [Log.INFO].
*
* @param message the function that returns message text to log.
* `null` value will be represent as "null", for any other value the [Any.toString] will be invoked.
*
* @see [Log.i].
*/
inline fun CxLogger.info(message: () -> Any?) {
val tag = loggerTag
//if (Log.isLoggable(tag, Log.INFO)) {
if (BuildConfig.debugLogging) {
Log.i(tag, message()?.toString() ?: "null")
}
}
/**
* Send a log message with the [Log.WARN] severity.
* Note that the log message will not be written if the current log level is above [Log.WARN].
* The default log level is [Log.INFO].
*
* @param message the function that returns message text to log.
* `null` value will be represent as "null", for any other value the [Any.toString] will be invoked.
*
* @see [Log.w].
*/
inline fun CxLogger.warn(message: () -> Any?) {
val tag = loggerTag
//if (Log.isLoggable(tag, Log.WARN)) {
Log.w(tag, message()?.toString() ?: "null")
}
/**
* Send a log message with the [Log.ERROR] severity.
* Note that the log message will not be written if the current log level is above [Log.ERROR].
* The default log level is [Log.INFO].
*
* @param message the function that returns message text to log.
* `null` value will be represent as "null", for any other value the [Any.toString] will be invoked.
*
* @see [Log.e].
*/
inline fun CxLogger.error(message: () -> Any?) {
val tag = loggerTag
//if (Log.isLoggable(tag, Log.ERROR)) {
Log.e(tag, message()?.toString() ?: "null")
}
/**
* Return the stack trace [String] of a throwable.
*/
inline fun Throwable.getStackTraceString(): String = Log.getStackTraceString(this)
private inline fun log(
logger: CxLogger,
message: Any?,
thr: Throwable?,
@Suppress("UNUSED_PARAMETER") level: Int,
f: (String, String) -> Unit,
fThrowable: (String, String, Throwable) -> Unit) {
val tag = logger.loggerTag
//if (Log.isLoggable(tag, level)) {
if (thr != null) {
fThrowable(tag, message?.toString() ?: "null", thr)
} else {
f(tag, message?.toString() ?: "null")
}
//}
}
private fun getTag(clazz: Class<*>): String {
val tag = clazz.simpleName
return if (tag.length <= 23) {
tag
} else {
tag.substring(0, 23)
}
}
| gpl-3.0 | 2da5012eb4278cc686cd20b84a74cd5b | 32.829787 | 104 | 0.647694 | 3.454019 | false | false | false | false |
vondear/RxTools | RxDemo/src/main/java/com/tamsiree/rxdemo/fragment/FragmentLoadingWay.kt | 1 | 2973 | package com.tamsiree.rxdemo.fragment
import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.tamsiree.rxdemo.R
import com.tamsiree.rxdemo.activity.ActivityLoadingDetail
import com.tamsiree.rxkit.RxImageTool
import com.tamsiree.rxkit.RxRecyclerViewDividerTool
import com.tamsiree.rxui.fragment.FragmentLazy
import com.tamsiree.rxui.view.loadingview.SpinKitView
import com.tamsiree.rxui.view.loadingview.SpriteFactory
import com.tamsiree.rxui.view.loadingview.Style
import kotlinx.android.synthetic.main.fragment_page1.*
/**
* Created by Tamsiree.
* @author tamsiree
*/
class FragmentLoadingWay : FragmentLazy() {
var colors = intArrayOf(
Color.parseColor("#99CCFF"),
Color.parseColor("#34A853"))
override fun inflateView(layoutInflater: LayoutInflater, viewGroup: ViewGroup?, savedInstanceState: Bundle?): View {
val view = layoutInflater.inflate(R.layout.fragment_page1, viewGroup, false)
return view
}
override fun initView() {
}
override fun initData() {
val recyclerView: RecyclerView = list
val layoutManager = GridLayoutManager(context, 3)
layoutManager.orientation = GridLayoutManager.VERTICAL
recyclerView.layoutManager = layoutManager
recyclerView.addItemDecoration(RxRecyclerViewDividerTool(RxImageTool.dp2px(5f)))
recyclerView.adapter = object : RecyclerView.Adapter<Holder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder {
@SuppressLint("InflateParams") val view = LayoutInflater.from(parent.context).inflate(R.layout.item_list, null)
return Holder(view)
}
override fun onBindViewHolder(holder: Holder, position: Int) {
holder.bind(position)
}
override fun getItemCount(): Int {
return Style.values().size
}
}
}
internal inner class Holder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var spinKitView: SpinKitView = itemView.findViewById(R.id.spin_kit)
fun bind(position: Int) {
var position = position
itemView.setBackgroundColor(colors[position % colors.size])
val finalPosition = position
itemView.setOnClickListener { v -> ActivityLoadingDetail.start(v.context, finalPosition) }
position %= 15
val style = Style.values()[position]
val drawable = SpriteFactory.create(style)
spinKitView.setIndeterminateDrawable(drawable!!)
}
}
companion object {
@JvmStatic
fun newInstance(): FragmentLoadingWay {
return FragmentLoadingWay()
}
}
} | apache-2.0 | e284d3243dc4c63af2b9e9e4b005a3cd | 35.268293 | 127 | 0.693239 | 4.881773 | false | false | false | false |
lare96/luna | plugins/api/event/Matcher.kt | 1 | 8445 | package api.event
import api.predef.*
import com.google.common.collect.ArrayListMultimap
import io.luna.game.event.Event
import io.luna.game.event.EventMatcher
import io.luna.game.event.EventMatcherListener
import io.luna.game.event.impl.ButtonClickEvent
import io.luna.game.event.impl.CommandEvent
import io.luna.game.event.impl.ItemClickEvent
import io.luna.game.event.impl.ItemClickEvent.*
import io.luna.game.event.impl.ItemOnItemEvent
import io.luna.game.event.impl.ItemOnObjectEvent
import io.luna.game.event.impl.NpcClickEvent
import io.luna.game.event.impl.NpcClickEvent.*
import io.luna.game.event.impl.ObjectClickEvent
import io.luna.game.event.impl.ObjectClickEvent.*
import io.luna.game.event.impl.ServerLaunchEvent
import kotlin.reflect.KClass
/**
* A model that will be used to match arbitrary arguments against events of type [E]. Matchers obtain a [K]ey
* from an event message and use the key to lookup the appropriate action to run.
*
* This provides a performance increase when there are a large amount of event listeners in a pipeline. For
* more information, see [issue #68](https://github.com/luna-rs/luna/issues/68).
*
* @author lare96
*/
abstract class Matcher<E : Event, K>(private val eventType: KClass<E>) {
companion object {
/**
* Mappings of all matchers. The event type is the key.
*/
val ALL: Map<KClass<out Event>, Matcher<*, *>>
/**
* Retrieves a [Matcher] from the backing map that is matching on events with [E].
*/
@Suppress("UNCHECKED_CAST")
inline fun <reified E : Event, K> get(): Matcher<E, K> {
return get(E::class)
}
/**
* Retrieves a [Matcher] from the backing map that is matching on events with [eventType].
*/
@Suppress("UNCHECKED_CAST")
fun <E : Event, K> get(eventType: KClass<E>): Matcher<E, K> {
val matcher = ALL[eventType]
return when (matcher) {
null -> throw NoSuchElementException("Matcher for event type $eventType was not found.")
else -> matcher as Matcher<E, K>
}
}
/**
* Determines if the [eventType] has a dedicated matcher.
*/
fun <E : Event> has(eventType: KClass<E>) = ALL.containsKey(eventType)
init {
// Map all matchers to their matching event types.
ALL = listOf(CommandMatcher,
ButtonMatcher,
ItemOnItemMatcher,
ItemOnObjectMatcher,
NpcMatcher(NpcFirstClickEvent::class),
NpcMatcher(NpcSecondClickEvent::class),
NpcMatcher(NpcThirdClickEvent::class),
NpcMatcher(NpcFourthClickEvent::class),
NpcMatcher(NpcFifthClickEvent::class),
ItemMatcher(ItemFirstClickEvent::class),
ItemMatcher(ItemSecondClickEvent::class),
ItemMatcher(ItemThirdClickEvent::class),
ItemMatcher(ItemFourthClickEvent::class),
ItemMatcher(ItemFifthClickEvent::class),
ObjectMatcher(ObjectFirstClickEvent::class),
ObjectMatcher(ObjectSecondClickEvent::class),
ObjectMatcher(ObjectThirdClickEvent::class))
.associateBy { it.eventType }
// Add all of the matcher's listeners.
ALL.values.forEach { it.addListener() }
// Small optimization, put all keys with only one listener into a different map.
on(ServerLaunchEvent::class) {
var singularCount = 0
var multiCount = 0
for (matcher in ALL.values) {
val result = matcher.optimize()
singularCount += result.first
multiCount += result.second
}
logger.debug("Action map optimization | singular: {} mappings, multi: {} mappings.",
singularCount, multiCount)
}
}
}
/**
* The map of event keys to action function instances. Will be used to match arguments.
*/
private val actions = HashMap<K, EventMatcherListener<E>>(128)
/**
* The map of event keys to multiple action function instances. Will be used to match arguments.
*/
private val multiActions = ArrayListMultimap.create<K, EventMatcherListener<E>>(128, 16)
/**
* Computes a lookup key from the event instance.
*/
abstract fun key(msg: E): K
/**
* A set containing all keys in this matcher.
*/
fun keys(): Set<K> {
val singular = actions.keys
val multi = multiActions.asMap().keys
val keys = HashSet<K>(singular.size + multi.size)
keys.addAll(singular)
keys.addAll(multi)
return keys
}
/**
* Adds or replaces an optimized listener key -> value pair.
*/
operator fun set(key: K, value: E.() -> Unit) {
val matcherListener = EventMatcherListener(value)
multiActions.put(key, matcherListener)
scriptMatchers += matcherListener
}
/**
* Adds an event listener for this matcher to the backing pipeline set.
*/
private fun addListener() {
val type = eventType.java
val pipeline = pipelines.get(type)
pipeline.setMatcher(EventMatcher<E>(this::match))
}
/**
* Matches [msg] to an event listener within this matcher.
*/
private fun match(msg: E): Boolean {
val actionKey = key(msg)
// Try a singular action.
val action = actions[actionKey]
if (action != null) {
action.apply(msg)
return true
} else {
// If not found, try multiple actions.
val multiAction = multiActions[actionKey]
if (multiAction.size > 0) {
multiAction.forEach { it.apply(msg) }
return true
}
return false
}
}
/**
* Optimizes this matcher by putting all keys with only one listener into a different map.
*/
private fun optimize(): Pair<Int, Int> {
val iterator = multiActions.asMap().entries.iterator()
while (iterator.hasNext()) {
val next = iterator.next()
val actionList = next.value
if (actionList.size == 1) {
actions[next.key] = actionList.first()
iterator.remove()
}
}
return actions.size to multiActions.size()
}
/**
* A base [Matcher] for [NpcClickEvent]s.
*/
class NpcMatcher<E : NpcClickEvent>(matchClass: KClass<E>) : Matcher<E, Int>(matchClass) {
override fun key(msg: E) = msg.npc.id
}
/**
* A base [Matcher] for [ItemClickEvent]s.
*/
class ItemMatcher<E : ItemClickEvent>(matchClass: KClass<E>) : Matcher<E, Int>(matchClass) {
override fun key(msg: E) = msg.id
}
/**
* A base [Matcher] for [ObjectClickEvent]s.
*/
class ObjectMatcher<E : ObjectClickEvent>(matchClass: KClass<E>) : Matcher<E, Int>(matchClass) {
override fun key(msg: E) = msg.id
}
/**
* A singleton [Matcher] instance for [ButtonClickEvent]s.
*/
object ButtonMatcher : Matcher<ButtonClickEvent, Int>(ButtonClickEvent::class) {
override fun key(msg: ButtonClickEvent) = msg.id
}
/**
* A singleton [Matcher] instance for [CommandEvent]s.
*/
object CommandMatcher : Matcher<CommandEvent, CommandKey>(CommandEvent::class) {
// Note: The rights value is ignored, the real key is 'msg.name'.
override fun key(msg: CommandEvent) = CommandKey(msg.name, msg.plr.rights)
}
/**
* A singleton [Matcher] instance for [ItemOnItemEvent]s.
*/
object ItemOnItemMatcher : Matcher<ItemOnItemEvent, Pair<Int, Int>>(ItemOnItemEvent::class) {
override fun key(msg: ItemOnItemEvent) = Pair(msg.usedId, msg.targetId)
}
/**
* A singleton [Matcher] instance for [ItemOnObjectEvent]s.
*/
object ItemOnObjectMatcher : Matcher<ItemOnObjectEvent, Pair<Int, Int>>(ItemOnObjectEvent::class) {
override fun key(msg: ItemOnObjectEvent) = Pair(msg.itemId, msg.objectId)
}
}
| mit | e14aa158da1a2d330160a9d050f3af32 | 34.783898 | 109 | 0.597276 | 4.444737 | false | false | false | false |
vanita5/twittnuker | twittnuker/src/main/kotlin/de/vanita5/twittnuker/util/StatusAdapterLinkClickHandler.kt | 1 | 2840 | /*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vanita5.twittnuker.util
import android.content.Context
import android.content.SharedPreferences
import android.support.v7.widget.RecyclerView
import org.mariotaku.kpreferences.get
import de.vanita5.twittnuker.Constants
import de.vanita5.twittnuker.adapter.iface.IStatusesAdapter
import de.vanita5.twittnuker.constant.displaySensitiveContentsKey
import de.vanita5.twittnuker.constant.newDocumentApiKey
import de.vanita5.twittnuker.model.UserKey
import de.vanita5.twittnuker.model.util.ParcelableMediaUtils
class StatusAdapterLinkClickHandler<out D>(context: Context, preferences: SharedPreferences) :
OnLinkClickHandler(context, null, preferences), Constants {
private var adapter: IStatusesAdapter<D>? = null
override fun openMedia(accountKey: UserKey, extraId: Long, sensitive: Boolean,
link: String, start: Int, end: Int) {
if (extraId == RecyclerView.NO_POSITION.toLong()) return
val status = adapter!!.getStatus(extraId.toInt())
val media = ParcelableMediaUtils.getAllMedia(status)
val current = StatusLinkClickHandler.findByLink(media, link)
if (current != null && current.open_browser) {
openLink(accountKey, link)
} else {
IntentUtils.openMedia(context, status, current, preferences[newDocumentApiKey],
preferences[displaySensitiveContentsKey])
}
}
override fun isMedia(link: String, extraId: Long): Boolean {
if (extraId != RecyclerView.NO_POSITION.toLong()) {
val status = adapter!!.getStatus(extraId.toInt())
val media = ParcelableMediaUtils.getAllMedia(status)
val current = StatusLinkClickHandler.findByLink(media, link)
if (current != null) return !current.open_browser
}
return super.isMedia(link, extraId)
}
fun setAdapter(adapter: IStatusesAdapter<D>) {
this.adapter = adapter
}
} | gpl-3.0 | 0542fa74b6ffcefb87404524ebd82c22 | 40.779412 | 94 | 0.717958 | 4.430577 | false | false | false | false |
usmansaleem/kt-vertx | src/main/kotlin/info/usmans/blog/vertx/NetServerVerticle.kt | 1 | 4561 | package info.usmans.blog.vertx
import io.vertx.core.AbstractVerticle
import io.vertx.core.Future
import io.vertx.core.buffer.Buffer
import io.vertx.core.net.NetServerOptions
import io.vertx.core.net.OpenSSLEngineOptions
import io.vertx.core.net.PemKeyCertOptions
import org.slf4j.LoggerFactory
/**
* A secure TCP server serving on port 8888.
*/
class NetServerVerticle(private val sslCertValue: String?, private val sslKeyValue: String?) : AbstractVerticle() {
private val logger = LoggerFactory.getLogger("info.usmans.blog.vertx.NetServerVerticle")
override fun start(startFuture: Future<Void>?) {
logger.info("Starting NetServerVerticle...")
if (sslCertValue == null || sslKeyValue == null) {
startFuture?.fail("SSL Certificates are required to start Net Server")
return
}
val netServerOptions = NetServerOptions().apply {
isSsl = true
pemKeyCertOptions = PemKeyCertOptions().apply {
certValue = Buffer.buffer(sslCertValue)
keyValue = Buffer.buffer(sslKeyValue)
}
port = SYS_NET_SERVER_DEPLOY_PORT
addEnabledSecureTransportProtocol("TLSv1.1")
addEnabledSecureTransportProtocol("TLSv1.2")
if(ENV_BLOG_ENABLE_OPENSSL)
sslEngineOptions = OpenSSLEngineOptions()
}
val server = vertx.createNetServer(netServerOptions)
server.exceptionHandler { t ->
logger.error("Unexpected exception in NetServer: ${t.message}", t)
}
server.connectHandler({ socket ->
val clientsMap = vertx.sharedData().getLocalMap<String, String>("clientsMap")
//the one-shot timer to wait for client to send password.
val timerId = vertx.setTimer(5000, {
//test whether client has been added to map or not.
if (socket.writeHandlerID() != clientsMap.get("client")) {
//close this client ...
logger.info("No message received from client in 5 seconds, closing socket. ${socket.writeHandlerID()}")
socket.close()
}
})
//we only want one authenticated client to be connected
if (clientsMap.containsKey("client")) {
logger.info("A client is already connected, closing client socket")
vertx.cancelTimer(timerId)
//close client socket
socket.close()
} else {
socket.handler({ buffer ->
//client send message, timer is not required anymore
vertx.cancelTimer(timerId)
//we want to add the client once we receive secret password from it
if (ENV_BLOG_CUSTOM_NET_PASSWORD != null && buffer.toString() == ENV_BLOG_CUSTOM_NET_PASSWORD) {
logger.info("Client connected, adding to map ${socket.writeHandlerID()}")
clientsMap.put("client", socket.writeHandlerID())
//we are good to send messages now.
} else {
logger.info("Invalid password $buffer received, closing socket")
socket.close()
}
})
}
val consumer = vertx.eventBus().consumer<String>("action-feed", { message ->
if(socket.writeHandlerID() == clientsMap.get("client")) {
logger.info("sending out message on action-feed to ${socket.writeHandlerID()}")
socket.write(message.body())
}
})
socket.closeHandler({
//in case client closed socket before sending us message
vertx.cancelTimer(timerId)
logger.info("Client Socket ${socket.writeHandlerID()} closed, clearing client map")
clientsMap.removeIfPresent("client", socket.writeHandlerID())
logger.debug("Unregistering eventbus")
consumer.unregister()
})
})
server.listen({ event ->
if (event.succeeded()) {
logger.info("NetServerVerticle server started on port ${netServerOptions.port}")
startFuture?.complete()
} else {
logger.info("NetServerVerticle server failed to start on port ${netServerOptions.port}")
startFuture?.fail(event.cause())
}
})
}
} | mit | 1f7c2a81f5983d3ee170244b00abc29f | 39.732143 | 123 | 0.574874 | 5.006586 | false | false | false | false |
chadrick-kwag/datalabeling_app | app/src/main/java/com/example/chadrick/datalabeling/Models/JWTManager.kt | 1 | 2006 | package com.example.chadrick.datalabeling.Models
import android.content.Context
import android.util.Log
import com.example.chadrick.datalabeling.Util
import java.io.BufferedReader
import java.io.File
import java.io.FileInputStream
import java.io.FileReader
/**
* Created by chadrick on 17. 12. 11.
*/
class JWTManager {
var file: File
var jwt: String = ""
var userid:String = ""
var usermail:String=""
companion object {
@Volatile private var INSTANCE: JWTManager? = null
fun getInstance(context: Context?): JWTManager? =
context?.let { INSTANCE ?: synchronized(this) {
INSTANCE ?: JWTManager(context).also { INSTANCE = it }
} }
fun getInstance():JWTManager? = INSTANCE
}
fun savejwt(newjwt: String) {
jwt = newjwt
val jsonobj = Util.decoded(jwt)
userid = jsonobj?.getString("userid") ?: ""
usermail = jsonobj?.getString("user_mail") ?: ""
file.delete()
file.writeBytes(newjwt.toByteArray())
}
fun deletejwt() {
file.delete()
}
private constructor(context: Context) {
this.file = File(context.filesDir, "/user.jwt")
if (file.exists()) {
val reader = FileReader(file)
val br = BufferedReader(reader)
val readstr = StringBuilder()
var line: String?
while (true) {
line = br.readLine()
line?.let { readstr.append(line) }
if (line == null) {
break
}
}
br.close()
val readjwt = readstr.toString()
Log.d("JWTManager", "read jwt=" + readjwt)
jwt = readjwt
// parse and extract mail and id info
val jsonobj = Util.decoded(jwt)
userid = jsonobj?.getString("userid") ?: ""
usermail = jsonobj?.getString("user_mail") ?: ""
}
}
} | mit | 62657c2b6b0de0baa150b63f49791e4d | 21.550562 | 74 | 0.547358 | 4.323276 | false | false | false | false |
slartus/4pdaClient-plus | forum/forum-impl/src/main/java/org/softeg/slartus/forpdaplus/forum/impl/ui/fingerprints/ForumDataItemFingerprint.kt | 1 | 3339 | package org.softeg.slartus.forpdaplus.forum.impl.ui.fingerprints
import android.os.Build
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.recyclerview.widget.DiffUtil
import coil.ImageLoader
import coil.decode.GifDecoder
import coil.decode.ImageDecoderDecoder
import coil.load
import org.softeg.slartus.forpdaplus.core_lib.ui.adapter.BaseViewHolder
import org.softeg.slartus.forpdaplus.core_lib.ui.adapter.Item
import org.softeg.slartus.forpdaplus.core_lib.ui.adapter.ItemFingerprint
import org.softeg.slartus.forpdaplus.forum.impl.R
import org.softeg.slartus.forpdaplus.forum.impl.databinding.LayoutForumBinding
class ForumDataItemFingerprint(
private val showImages: Boolean,
private val onClickListener: (view: View?, item: ForumDataItem) -> Unit,
private val onLongClickListener: (view: View?, item: ForumDataItem) -> Boolean
) :
ItemFingerprint<LayoutForumBinding, ForumDataItem> {
private val diffUtil = object : DiffUtil.ItemCallback<ForumDataItem>() {
override fun areItemsTheSame(
oldItem: ForumDataItem,
newItem: ForumDataItem
) = oldItem.id == newItem.id
override fun areContentsTheSame(
oldItem: ForumDataItem,
newItem: ForumDataItem
) = oldItem == newItem
}
override fun getLayoutId() = R.layout.layout_forum
override fun isRelativeItem(item: Item) = item is ForumDataItem
override fun getViewHolder(
layoutInflater: LayoutInflater,
parent: ViewGroup
): BaseViewHolder<LayoutForumBinding, ForumDataItem> {
val binding = LayoutForumBinding.inflate(layoutInflater, parent, false)
return ForumDataViewHolder(binding, showImages, onClickListener, onLongClickListener)
}
override fun getDiffUtil() = diffUtil
}
class ForumDataViewHolder(
binding: LayoutForumBinding,
showImages: Boolean,
private val onClickListener: (view: View?, item: ForumDataItem) -> Unit,
private val onLongClickListener: (view: View?, item: ForumDataItem) -> Boolean
) :
BaseViewHolder<LayoutForumBinding, ForumDataItem>(binding) {
val imageLoader = ImageLoader.Builder(itemView.context)
.componentRegistry {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
add(ImageDecoderDecoder(itemView.context))
} else {
add(GifDecoder())
}
}
.build()
init {
binding.iconImageView.isVisible = showImages
itemView.setOnClickListener { v -> onClickListener(v, item) }
itemView.setOnLongClickListener { v -> onLongClickListener(v, item) }
}
override fun onBind(item: ForumDataItem) {
super.onBind(item)
with(binding) {
titleTextView.text = item.title
descriptionTextView.text = item.description
descriptionTextView.isVisible = !item.description.isNullOrEmpty()
if (iconImageView.isVisible && !item.iconUrl.isNullOrEmpty()) {
iconImageView.load(item.iconUrl, imageLoader)
}
}
}
}
data class ForumDataItem(
val id: String?,
val title: String?,
val description: String?,
val iconUrl: String?,
val isHasForums: Boolean
) : Item | apache-2.0 | 884577d0f1e83b69147d49a4aa8d70dc | 33.081633 | 93 | 0.699311 | 4.592847 | false | false | false | false |
slartus/4pdaClient-plus | http/src/main/java/ru/slartus/http/prefs/MBFileUtils.kt | 1 | 1618 | package ru.slartus.http.prefs
import java.io.*
import java.nio.channels.FileLock
import java.nio.channels.OverlappingFileLockException
object MBFileUtils {
fun fileExists(filePath: String): Boolean {
return File(filePath).exists()
}
@Throws(IOException::class)
fun createFile(filePath: String, content: String) {
File(filePath).createNewFile()
writeToFile(content, filePath)
}
@Throws(IOException::class)
fun readFile(filePath: String): String {
val file = File(filePath)
val length = file.length().toInt()
val bytes = ByteArray(length)
val `in` = FileInputStream(file)
`in`.use {
it.read(bytes)
}
return String(bytes)
}
@Throws(IOException::class)
fun writeToFile(content: String, filePath: String) {
var writed = false
do {
try {
val stream = FileOutputStream(filePath)
val lock = stream.channel.lock()
try {
stream.use {
it.write(content.toByteArray())
writed = true
}
} finally {
lock.release()
}
}catch (ofle:OverlappingFileLockException){
try {
// Wait a bit
Thread.sleep(10)
} catch (ex: InterruptedException) {
throw InterruptedIOException("Interrupted waiting for a file lock.")
}
}
} while (!writed)
}
}
| apache-2.0 | b206a63778872f819e60a5775e017d31 | 25.096774 | 88 | 0.518541 | 4.96319 | false | false | false | false |
mwudka/aftflight-alexa | src/main/kotlin/com/mwudka/aftflight/core/ADDS.kt | 1 | 1007 | package com.mwudka.aftflight.core
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty
class StationIdentifier(val id: String) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other?.javaClass != javaClass) return false
other as StationIdentifier
if (id != other.id) return false
return true
}
override fun hashCode(): Int {
return id.hashCode()
}
override fun toString(): String {
return "StationIdentifier(id='$id')"
}
}
enum class SkyCover {
SKC, CLR, CAVOK, FEW, SCT, BKN, OVC, OVX, NSC
}
data class SkyCondition(
@JacksonXmlProperty(isAttribute = true, localName = "sky_cover") val skyCover: SkyCover,
@JacksonXmlProperty(isAttribute = true, localName = "cloud_base_ft_agl") val cloudBaseFTAGL: Int? = null
) {
override fun toString(): String {
return "SkyCondition(skyCover=$skyCover, cloudBaseFTAGL=$cloudBaseFTAGL)"
}
}
| mit | b4652b7e4d2aea783f34555e96dba411 | 26.216216 | 112 | 0.66137 | 3.828897 | false | false | false | false |
AndroidX/androidx | compose/ui/ui/src/commonMain/kotlin/androidx/compose/ui/input/pointer/util/VelocityTracker.kt | 3 | 16180 | /*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.input.pointer.util
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.input.pointer.PointerInputChange
import androidx.compose.ui.input.pointer.changedToDownIgnoreConsumed
import androidx.compose.ui.unit.Velocity
import androidx.compose.ui.util.fastForEach
import kotlin.math.abs
import kotlin.math.sqrt
private const val AssumePointerMoveStoppedMilliseconds: Int = 40
private const val HistorySize: Int = 20
// TODO(b/204895043): Keep value in sync with VelocityPathFinder.HorizonMilliSeconds
private const val HorizonMilliseconds: Int = 100
private const val MinSampleSize: Int = 3
/**
* Computes a pointer's velocity.
*
* The input data is provided by calling [addPosition]. Adding data is cheap.
*
* To obtain a velocity, call [calculateVelocity]. This will compute the velocity
* based on the data added so far. Only call this when you need to use the velocity,
* as it is comparatively expensive.
*
* The quality of the velocity estimation will be better if more data points
* have been received.
*/
class VelocityTracker {
// Circular buffer; current sample at index.
private val samples: Array<PointAtTime?> = Array(HistorySize) { null }
private var index: Int = 0
internal var currentPointerPositionAccumulator = Offset.Zero
/**
* Adds a position at the given time to the tracker.
*
* Call [resetTracking] to remove added [Offset]s.
*
* @see resetTracking
*/
// TODO(shepshapard): VelocityTracker needs to be updated to be passed vectors instead of
// positions. For velocity tracking, the only thing that is important is the change in
// position over time.
fun addPosition(timeMillis: Long, position: Offset) {
index = (index + 1) % HistorySize
samples[index] = PointAtTime(position, timeMillis)
}
/**
* Computes the estimated velocity of the pointer at the time of the last provided data point.
*
* This can be expensive. Only call this when you need the velocity.
*/
fun calculateVelocity(): Velocity {
val estimate = getVelocityEstimate().pixelsPerSecond
return Velocity(estimate.x, estimate.y)
}
/**
* Clears the tracked positions added by [addPosition].
*/
fun resetTracking() {
samples.fill(element = null)
}
/**
* Returns an estimate of the velocity of the object being tracked by the
* tracker given the current information available to the tracker.
*
* Information is added using [addPosition].
*
* Returns null if there is no data on which to base an estimate.
*/
private fun getVelocityEstimate(): VelocityEstimate {
val x: MutableList<Float> = mutableListOf()
val y: MutableList<Float> = mutableListOf()
val time: MutableList<Float> = mutableListOf()
var sampleCount = 0
var index: Int = index
// The sample at index is our newest sample. If it is null, we have no samples so return.
val newestSample: PointAtTime = samples[index] ?: return VelocityEstimate.None
var previousSample: PointAtTime = newestSample
var oldestSample: PointAtTime = newestSample
// Starting with the most recent PointAtTime sample, iterate backwards while
// the samples represent continuous motion.
do {
val sample: PointAtTime = samples[index] ?: break
val age: Float = (newestSample.time - sample.time).toFloat()
val delta: Float =
abs(sample.time - previousSample.time).toFloat()
previousSample = sample
if (age > HorizonMilliseconds || delta > AssumePointerMoveStoppedMilliseconds) {
break
}
oldestSample = sample
val position: Offset = sample.point
x.add(position.x)
y.add(position.y)
time.add(-age)
index = (if (index == 0) HistorySize else index) - 1
sampleCount += 1
} while (sampleCount < HistorySize)
if (sampleCount >= MinSampleSize) {
try {
val xFit: PolynomialFit = polyFitLeastSquares(time, x, 2)
val yFit: PolynomialFit = polyFitLeastSquares(time, y, 2)
// The 2nd coefficient is the derivative of the quadratic polynomial at
// x = 0, and that happens to be the last timestamp that we end up
// passing to polyFitLeastSquares for both x and y.
val xSlope = xFit.coefficients[1]
val ySlope = yFit.coefficients[1]
return VelocityEstimate(
pixelsPerSecond = Offset(
// Convert from pixels/ms to pixels/s
(xSlope * 1000),
(ySlope * 1000)
),
confidence = xFit.confidence * yFit.confidence,
durationMillis = newestSample.time - oldestSample.time,
offset = newestSample.point - oldestSample.point
)
} catch (exception: IllegalArgumentException) {
// TODO(b/129494918): Is catching an exception here something we really want to do?
return VelocityEstimate.None
}
}
// We're unable to make a velocity estimate but we did have at least one
// valid pointer position.
return VelocityEstimate(
pixelsPerSecond = Offset.Zero,
confidence = 1.0f,
durationMillis = newestSample.time - oldestSample.time,
offset = newestSample.point - oldestSample.point
)
}
}
/**
* Track the positions and timestamps inside this event change.
*
* For optimal tracking, this should be called for the DOWN event and all MOVE
* events, including any touch-slop-captured MOVE event.
*
* Since Compose uses relative positions inside PointerInputChange, this should be
* taken into consideration when using this method. Right now, we use the first down
* to initialize an accumulator and use subsequent deltas to simulate an actual movement
* from relative positions in PointerInputChange. This is required because VelocityTracker
* requires data that can be fit into a curve, which might not happen with relative positions
* inside a moving target for instance.
*
* @param event Pointer change to track.
*/
fun VelocityTracker.addPointerInputChange(event: PointerInputChange) {
// Register down event as the starting point for the accumulator
if (event.changedToDownIgnoreConsumed()) {
currentPointerPositionAccumulator = event.position
resetTracking()
}
// To calculate delta, for each step we want to do currentPosition - previousPosition.
// Initially the previous position is the previous position of the current event
var previousPointerPosition = event.previousPosition
@OptIn(ExperimentalComposeUiApi::class)
event.historical.fastForEach {
// Historical data happens within event.position and event.previousPosition
// That means, event.previousPosition < historical data < event.position
// Initially, the first delta will happen between the previousPosition and
// the first position in historical delta. For subsequent historical data, the
// deltas happen between themselves. That's why we need to update previousPointerPosition
// everytime.
val historicalDelta = it.position - previousPointerPosition
previousPointerPosition = it.position
// Update the current position with the historical delta and add it to the tracker
currentPointerPositionAccumulator += historicalDelta
addPosition(it.uptimeMillis, currentPointerPositionAccumulator)
}
// For the last position in the event
// If there's historical data, the delta is event.position - lastHistoricalPoint
// If there's no historical data, the delta is event.position - event.previousPosition
val delta = event.position - previousPointerPosition
currentPointerPositionAccumulator += delta
addPosition(event.uptimeMillis, currentPointerPositionAccumulator)
}
private data class PointAtTime(val point: Offset, val time: Long)
/**
* A two dimensional velocity estimate.
*
* VelocityEstimates are computed by [VelocityTracker.getImpulseVelocity]. An
* estimate's [confidence] measures how well the velocity tracker's position
* data fit a straight line, [durationMillis] is the time that elapsed between the
* first and last position sample used to compute the velocity, and [offset]
* is similarly the difference between the first and last positions.
*
* See also:
*
* * VelocityTracker, which computes [VelocityEstimate]s.
* * Velocity, which encapsulates (just) a velocity vector and provides some
* useful velocity operations.
*/
private data class VelocityEstimate(
/** The number of pixels per second of velocity in the x and y directions. */
val pixelsPerSecond: Offset,
/**
* A value between 0.0 and 1.0 that indicates how well [VelocityTracker]
* was able to fit a straight line to its position data.
*
* The value of this property is 1.0 for a perfect fit, 0.0 for a poor fit.
*/
val confidence: Float,
/**
* The time that elapsed between the first and last position sample used
* to compute [pixelsPerSecond].
*/
val durationMillis: Long,
/**
* The difference between the first and last position sample used
* to compute [pixelsPerSecond].
*/
val offset: Offset
) {
companion object {
val None = VelocityEstimate(Offset.Zero, 1f, 0, Offset.Zero)
}
}
/**
* TODO (shepshapard): If we want to support varying weights for each position, we could accept a
* 3rd FloatArray of weights for each point and use them instead of the [DefaultWeight].
*/
private const val DefaultWeight = 1f
/**
* Fits a polynomial of the given degree to the data points.
*
* If the [degree] is larger than or equal to the number of points, a polynomial will be returned
* with coefficients of the value 0 for all degrees larger than or equal to the number of points.
* For example, if 2 data points are provided and a quadratic polynomial (degree of 2) is requested,
* the resulting polynomial ax^2 + bx + c is guaranteed to have a = 0;
*
* Throws an IllegalArgumentException if:
* <ul>
* <li>[degree] is not a positive integer.
* <li>[x] and [y] are not the same size.
* <li>[x] or [y] are empty.
* <li>(some other reason that
* </ul>
*
*/
internal fun polyFitLeastSquares(
/** The x-coordinates of each data point. */
x: List<Float>,
/** The y-coordinates of each data point. */
y: List<Float>,
degree: Int
): PolynomialFit {
if (degree < 1) {
throw IllegalArgumentException("The degree must be at positive integer")
}
if (x.size != y.size) {
throw IllegalArgumentException("x and y must be the same length")
}
if (x.isEmpty()) {
throw IllegalArgumentException("At least one point must be provided")
}
val truncatedDegree =
if (degree >= x.size) {
x.size - 1
} else {
degree
}
val coefficients = MutableList(degree + 1) { 0.0f }
// Shorthands for the purpose of notation equivalence to original C++ code.
val m: Int = x.size
val n: Int = truncatedDegree + 1
// Expand the X vector to a matrix A, pre-multiplied by the weights.
val a = Matrix(n, m)
for (h in 0 until m) {
a.set(0, h, DefaultWeight)
for (i in 1 until n) {
a.set(i, h, a.get(i - 1, h) * x[h])
}
}
// Apply the Gram-Schmidt process to A to obtain its QR decomposition.
// Orthonormal basis, column-major ordVectorer.
val q = Matrix(n, m)
// Upper triangular matrix, row-major order.
val r = Matrix(n, n)
for (j in 0 until n) {
for (h in 0 until m) {
q.set(j, h, a.get(j, h))
}
for (i in 0 until j) {
val dot: Float = q.getRow(j) * q.getRow(i)
for (h in 0 until m) {
q.set(j, h, q.get(j, h) - dot * q.get(i, h))
}
}
val norm: Float = q.getRow(j).norm()
if (norm < 0.000001) {
// TODO(b/129494471): Determine what this actually means and see if there are
// alternatives to throwing an Exception here.
// Vectors are linearly dependent or zero so no solution.
throw IllegalArgumentException(
"Vectors are linearly dependent or zero so no " +
"solution. TODO(shepshapard), actually determine what this means"
)
}
val inverseNorm: Float = 1.0f / norm
for (h in 0 until m) {
q.set(j, h, q.get(j, h) * inverseNorm)
}
for (i in 0 until n) {
r.set(j, i, if (i < j) 0.0f else q.getRow(j) * a.getRow(i))
}
}
// Solve R B = Qt W Y to find B. This is easy because R is upper triangular.
// We just work from bottom-right to top-left calculating B's coefficients.
val wy = Vector(m)
for (h in 0 until m) {
wy[h] = y[h] * DefaultWeight
}
for (i in n - 1 downTo 0) {
coefficients[i] = q.getRow(i) * wy
for (j in n - 1 downTo i + 1) {
coefficients[i] -= r.get(i, j) * coefficients[j]
}
coefficients[i] /= r.get(i, i)
}
// Calculate the coefficient of determination (confidence) as:
// 1 - (sumSquaredError / sumSquaredTotal)
// ...where sumSquaredError is the residual sum of squares (variance of the
// error), and sumSquaredTotal is the total sum of squares (variance of the
// data) where each has been weighted.
var yMean = 0.0f
for (h in 0 until m) {
yMean += y[h]
}
yMean /= m
var sumSquaredError = 0.0f
var sumSquaredTotal = 0.0f
for (h in 0 until m) {
var term = 1.0f
var err: Float = y[h] - coefficients[0]
for (i in 1 until n) {
term *= x[h]
err -= term * coefficients[i]
}
sumSquaredError += DefaultWeight * DefaultWeight * err * err
val v = y[h] - yMean
sumSquaredTotal += DefaultWeight * DefaultWeight * v * v
}
val confidence =
if (sumSquaredTotal <= 0.000001f) 1f else 1f - (sumSquaredError / sumSquaredTotal)
return PolynomialFit(coefficients, confidence)
}
internal data class PolynomialFit(
val coefficients: List<Float>,
val confidence: Float
)
private class Vector(
val length: Int
) {
val elements: Array<Float> = Array(length) { 0.0f }
operator fun get(i: Int) = elements[i]
operator fun set(i: Int, value: Float) {
elements[i] = value
}
operator fun times(a: Vector): Float {
var result = 0.0f
for (i in 0 until length) {
result += this[i] * a[i]
}
return result
}
fun norm(): Float = sqrt(this * this)
}
private class Matrix(rows: Int, cols: Int) {
private val elements: Array<Vector> = Array(rows) { Vector(cols) }
fun get(row: Int, col: Int): Float {
return elements[row][col]
}
fun set(row: Int, col: Int, value: Float) {
elements[row][col] = value
}
fun getRow(row: Int): Vector {
return elements[row]
}
} | apache-2.0 | 2fa2a627d69dcab37d8743c6c9fdc10a | 35.280269 | 100 | 0.644005 | 4.257895 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/lang/core/psi/ext/RsPatFieldFull.kt | 3 | 1308 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.psi.ext
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import org.rust.lang.core.psi.RsPatFieldFull
import org.rust.lang.core.psi.RsPatStruct
import org.rust.lang.core.resolve.collectResolveVariants
import org.rust.lang.core.resolve.processStructPatternFieldResolveVariants
import org.rust.lang.core.resolve.ref.ResolveCacheDependency
import org.rust.lang.core.resolve.ref.RsReference
import org.rust.lang.core.resolve.ref.RsReferenceCached
val RsPatFieldFull.parentStructPattern: RsPatStruct
get() = ancestorStrict()!!
abstract class RsPatFieldFullImplMixin(node: ASTNode) : RsElementImpl(node), RsPatFieldFull {
override val referenceNameElement: PsiElement
get() = identifier ?: integerLiteral!!
override fun getReference(): RsReference = object : RsReferenceCached<RsPatFieldFull>(this@RsPatFieldFullImplMixin) {
override fun resolveInner(): List<RsElement> =
collectResolveVariants(element.referenceName) { processStructPatternFieldResolveVariants(element, it) }
override val cacheDependency: ResolveCacheDependency
get() = ResolveCacheDependency.LOCAL_AND_RUST_STRUCTURE
}
}
| mit | dea4f349d148fee8c3a36923766968b4 | 37.470588 | 121 | 0.78211 | 4.302632 | false | false | false | false |
oleksiyp/mockk | dsl/common/src/main/kotlin/io/mockk/API.kt | 1 | 103590 | @file:Suppress("DEPRECATION", "NOTHING_TO_INLINE")
package io.mockk
import io.mockk.InternalPlatformDsl.toStr
import io.mockk.MockKGateway.*
import kotlin.coroutines.experimental.Continuation
import kotlin.reflect.KClass
/**
* Exception thrown by library
*/
class MockKException(message: String, ex: Throwable? = null) : RuntimeException(message, ex)
/**
* DSL entry points.
*/
@Suppress("NOTHING_TO_INLINE")
object MockKDsl {
/**
* Builds a new mock for specified class
*/
inline fun <reified T : Any> internalMockk(
name: String? = null,
relaxed: Boolean = false,
vararg moreInterfaces: KClass<*>,
relaxUnitFun: Boolean = false,
block: T.() -> Unit = {}
): T {
val mock = MockKGateway.implementation().mockFactory.mockk(
T::class,
name,
relaxed,
moreInterfaces,
relaxUnitFun
)
block(mock)
return mock
}
/**
* Builds a new spy for specified class. Initializes object via default constructor.
*/
inline fun <T : Any> internalSpyk(
objToCopy: T,
name: String? = null,
vararg moreInterfaces: KClass<*>,
recordPrivateCalls: Boolean = false,
block: T.() -> Unit = {}
): T {
val spy = MockKGateway.implementation().mockFactory.spyk(
null,
objToCopy,
name,
moreInterfaces,
recordPrivateCalls
)
block(spy)
return spy
}
/**
* Builds a new spy for specified class. Copies fields from provided object
*/
inline fun <reified T : Any> internalSpyk(
name: String? = null,
vararg moreInterfaces: KClass<*>,
recordPrivateCalls: Boolean = false,
block: T.() -> Unit = {}
): T {
val spy = MockKGateway.implementation().mockFactory.spyk(
T::class,
null,
name,
moreInterfaces,
recordPrivateCalls
)
block(spy)
return spy
}
/**
* Creates new capturing slot
*/
inline fun <reified T : Any> internalSlot() = CapturingSlot<T>()
/**
* Starts a block of stubbing. Part of DSL.
*/
fun <T> internalEvery(stubBlock: MockKMatcherScope.() -> T): MockKStubScope<T, T> =
MockKGateway.implementation().stubber.every(stubBlock, null)
/**
* Starts a block of stubbing for coroutines. Part of DSL.
*/
fun <T> internalCoEvery(stubBlock: suspend MockKMatcherScope.() -> T): MockKStubScope<T, T> =
MockKGateway.implementation().stubber.every(null, stubBlock)
/**
* Verifies calls happened in the past. Part of DSL
*/
fun internalVerify(
ordering: Ordering = Ordering.UNORDERED,
inverse: Boolean = false,
atLeast: Int = 1,
atMost: Int = Int.MAX_VALUE,
exactly: Int = -1,
timeout: Long = 0,
verifyBlock: MockKVerificationScope.() -> Unit
) {
internalCheckExactlyAtMostAtLeast(exactly, atLeast, atMost, ordering)
val min = if (exactly != -1) exactly else atLeast
val max = if (exactly != -1) exactly else atMost
MockKGateway.implementation().verifier.verify(
VerificationParameters(ordering, min, max, inverse, timeout),
verifyBlock,
null
)
}
/**
* Verify for coroutines
*/
fun internalCoVerify(
ordering: Ordering = Ordering.UNORDERED,
inverse: Boolean = false,
atLeast: Int = 1,
atMost: Int = Int.MAX_VALUE,
exactly: Int = -1,
timeout: Long = 0,
verifyBlock: suspend MockKVerificationScope.() -> Unit
) {
internalCheckExactlyAtMostAtLeast(exactly, atLeast, atMost, ordering)
val min = if (exactly != -1) exactly else atLeast
val max = if (exactly != -1) exactly else atMost
MockKGateway.implementation().verifier.verify(
VerificationParameters(ordering, min, max, inverse, timeout),
null,
verifyBlock
)
}
@PublishedApi
internal fun internalCheckExactlyAtMostAtLeast(exactly: Int, atLeast: Int, atMost: Int, ordering: Ordering) {
if (exactly != -1 && (atLeast != 1 || atMost != Int.MAX_VALUE)) {
throw MockKException("specify either atLeast/atMost or exactly")
}
if (exactly < -1) {
throw MockKException("exactly should be positive")
}
if (atLeast < 0) {
throw MockKException("atLeast should be positive")
}
if (atMost < 0) {
throw MockKException("atMost should be positive")
}
if (atLeast > atMost) {
throw MockKException("atLeast should less or equal atMost")
}
if (ordering != Ordering.UNORDERED) {
if (atLeast != 1 || atMost != Int.MAX_VALUE || exactly != -1) {
throw MockKException("atLeast, atMost, exactly is only allowed in unordered verify block")
}
}
}
/**
* Shortcut for ordered calls verification
*/
fun internalVerifyOrder(
inverse: Boolean = false,
verifyBlock: MockKVerificationScope.() -> Unit
) {
internalVerify(Ordering.ORDERED, inverse, verifyBlock = verifyBlock)
}
/**
* Shortcut for all calls verification
*/
fun internalVerifyAll(
inverse: Boolean = false,
verifyBlock: MockKVerificationScope.() -> Unit
) {
internalVerify(Ordering.ALL, inverse, verifyBlock = verifyBlock)
}
/**
* Shortcut for sequence calls verification
*/
fun internalVerifySequence(
inverse: Boolean = false,
verifyBlock: MockKVerificationScope.() -> Unit
) {
internalVerify(Ordering.SEQUENCE, inverse, verifyBlock = verifyBlock)
}
/**
* Shortcut for ordered calls verification
*/
fun internalCoVerifyOrder(
inverse: Boolean = false,
verifyBlock: suspend MockKVerificationScope.() -> Unit
) {
internalCoVerify(Ordering.ORDERED, inverse, verifyBlock = verifyBlock)
}
/**
* Shortcut for all calls verification
*/
fun internalCoVerifyAll(
inverse: Boolean = false,
verifyBlock: suspend MockKVerificationScope.() -> Unit
) {
internalCoVerify(Ordering.ALL, inverse, verifyBlock = verifyBlock)
}
/**
* Shortcut for sequence calls verification
*/
fun internalCoVerifySequence(
inverse: Boolean = false,
verifyBlock: suspend MockKVerificationScope.() -> Unit
) {
internalCoVerify(Ordering.SEQUENCE, inverse, verifyBlock = verifyBlock)
}
/**
* Exclude calls from recording
*
* @param current if current recorded calls should be filtered out
*/
fun internalExcludeRecords(
current: Boolean = true,
excludeBlock: MockKMatcherScope.() -> Unit
) {
MockKGateway.implementation().excluder.exclude(
ExclusionParameters(current),
excludeBlock,
null
)
}
/**
* Exclude calls from recording for a suspend block
*
* @param current if current recorded calls should be filtered out
*/
fun internalCoExcludeRecords(
current: Boolean = true,
excludeBlock: suspend MockKMatcherScope.() -> Unit
) {
MockKGateway.implementation().excluder.exclude(
ExclusionParameters(current),
null,
excludeBlock
)
}
/**
* Checks if all recorded calls were verified.
*/
fun internalConfirmVerified(vararg mocks: Any) {
for (mock in mocks) {
MockKGateway.implementation().verificationAcknowledger.acknowledgeVerified(mock)
}
}
/**
* Resets information associated with mock
*/
inline fun internalClearMocks(
firstMock: Any,
vararg mocks: Any,
answers: Boolean = true,
recordedCalls: Boolean = true,
childMocks: Boolean = true,
verificationMarks: Boolean = true,
exclusionRules: Boolean = true
) {
MockKGateway.implementation().clearer.clear(
arrayOf(firstMock, *mocks),
MockKGateway.ClearOptions(
answers,
recordedCalls,
childMocks,
verificationMarks,
exclusionRules
)
)
}
/**
* Registers instance factory and returns object able to do deregistration.
*/
inline fun <reified T : Any> internalRegisterInstanceFactory(noinline instanceFactory: () -> T): Deregisterable {
val factoryObj = object : MockKGateway.InstanceFactory {
override fun instantiate(cls: KClass<*>): Any? {
if (T::class == cls) {
return instanceFactory()
}
return null
}
}
MockKGateway.implementation().instanceFactoryRegistry.registerFactory(factoryObj)
return object : Deregisterable {
override fun deregister() {
MockKGateway.implementation().instanceFactoryRegistry.deregisterFactory(factoryObj)
}
}
}
/**
* Executes block of code with registering and unregistering instance factory.
*/
inline fun <reified T : Any, R> internalWithInstanceFactory(noinline instanceFactory: () -> T, block: () -> R): R {
return internalRegisterInstanceFactory(instanceFactory).use {
block()
}
}
/**
* Declares static mockk. Deprecated
*/
inline fun <reified T : Any> internalStaticMockk() = MockKStaticScope(T::class)
/**
* Declares static mockk. Deprecated
*/
inline fun internalStaticMockk(vararg kClass: KClass<out Any>) = MockKStaticScope(*kClass)
/**
* Declares object mockk. Deprecated
*/
inline fun internalObjectMockk(objs: Array<out Any>, recordPrivateCalls: Boolean = false) =
MockKObjectScope(*objs, recordPrivateCalls = recordPrivateCalls)
/**
* Declares constructor mockk. Deprecated
*/
inline fun <reified T : Any> internalConstructorMockk(
recordPrivateCalls: Boolean = false,
localToThread: Boolean = false
) =
MockKConstructorScope(T::class, recordPrivateCalls, localToThread)
/**
* Builds a mock for a class. Deprecated
*/
inline fun <T : Any> internalMockkClass(
type: KClass<T>,
name: String?,
relaxed: Boolean,
vararg moreInterfaces: KClass<*>,
relaxUnitFun: Boolean = false,
block: T.() -> Unit
): T {
val mock = MockKGateway.implementation().mockFactory.mockk(type, name, relaxed, moreInterfaces, relaxUnitFun)
block(mock)
return mock
}
/**
* Initializes
*/
inline fun internalInitAnnotatedMocks(
targets: List<Any>,
overrideRecordPrivateCalls: Boolean = false,
relaxUnitFun: Boolean = false,
relaxed: Boolean = false
) =
MockKGateway.implementation().mockInitializer.initAnnotatedMocks(
targets,
overrideRecordPrivateCalls,
relaxUnitFun,
relaxed
)
/**
* Object mockk
*/
inline fun internalMockkObject(vararg objects: Any, recordPrivateCalls: Boolean = false) {
val factory = MockKGateway.implementation().objectMockFactory
objects.forEach {
val cancellation = factory.objectMockk(it, recordPrivateCalls)
internalClearMocks(it)
MockKCancellationRegistry
.subRegistry(MockKCancellationRegistry.Type.OBJECT)
.cancelPut(it, cancellation)
}
}
/**
* Cancel object mocks.
*/
inline fun internalUnmockkObject(vararg objects: Any) {
objects.forEach {
MockKCancellationRegistry
.subRegistry(MockKCancellationRegistry.Type.OBJECT)
.cancel(it)
}
}
/**
* Clear object mocks.
*/
inline fun internalClearObjectMockk(
vararg objects: Any,
answers: Boolean = true,
recordedCalls: Boolean = true,
childMocks: Boolean = true,
verificationMarks: Boolean = true,
exclusionRules: Boolean = true
) {
for (obj in objects) {
MockKGateway.implementation().objectMockFactory.clear(
obj,
MockKGateway.ClearOptions(
answers,
recordedCalls,
childMocks,
verificationMarks,
exclusionRules
)
)
}
}
/**
* Static mockk
*/
inline fun internalMockkStatic(vararg classes: KClass<*>) {
val factory = MockKGateway.implementation().staticMockFactory
classes.forEach {
val cancellation = factory.staticMockk(it)
internalClearStaticMockk(it)
MockKCancellationRegistry
.subRegistry(MockKCancellationRegistry.Type.STATIC)
.cancelPut(it, cancellation)
}
}
/**
* Cancel static mocks.
*/
inline fun internalUnmockkStatic(vararg classes: KClass<*>) {
classes.forEach {
MockKCancellationRegistry
.subRegistry(MockKCancellationRegistry.Type.STATIC)
.cancel(it)
}
}
/**
* Clear static mocks.
*/
inline fun internalClearStaticMockk(
vararg classes: KClass<*>,
answers: Boolean = true,
recordedCalls: Boolean = true,
childMocks: Boolean = true,
verificationMarks: Boolean = true,
exclusionRules: Boolean = true
) {
for (type in classes) {
MockKGateway.implementation().staticMockFactory.clear(
type,
MockKGateway.ClearOptions(
answers,
recordedCalls,
childMocks,
verificationMarks,
exclusionRules
)
)
}
}
/**
* Constructor mockk
*/
inline fun internalMockkConstructor(
vararg classes: KClass<*>,
recordPrivateCalls: Boolean = false,
localToThread: Boolean = true
) {
val factory = MockKGateway.implementation().constructorMockFactory
classes.forEach {
val cancellation = factory.constructorMockk(it, recordPrivateCalls, localToThread)
internalClearConstructorMockk(it)
MockKCancellationRegistry
.subRegistry(MockKCancellationRegistry.Type.CONSTRUCTOR)
.cancelPut(it, cancellation)
}
}
/**
* Cancel constructor mocks.
*/
inline fun internalUnmockkConstructor(vararg classes: KClass<*>) {
classes.forEach {
MockKCancellationRegistry
.subRegistry(MockKCancellationRegistry.Type.CONSTRUCTOR)
.cancel(it)
}
}
/**
* Clear constructor mocks.
*/
inline fun internalClearConstructorMockk(
vararg classes: KClass<*>,
answers: Boolean = true,
recordedCalls: Boolean = true,
childMocks: Boolean = true,
verificationMarks: Boolean = true,
exclusionRules: Boolean = true
) {
for (type in classes) {
MockKGateway.implementation().constructorMockFactory.clear(
type,
MockKGateway.ClearOptions(
answers,
recordedCalls,
childMocks,
verificationMarks,
exclusionRules
)
)
}
}
/**
* Unmockk everything
*/
inline fun internalUnmockkAll() {
MockKCancellationRegistry.cancelAll()
}
inline fun internalClearAllMocks(
answers: Boolean = true,
recordedCalls: Boolean = true,
childMocks: Boolean = true,
regularMocks: Boolean = true,
objectMocks: Boolean = true,
staticMocks: Boolean = true,
constructorMocks: Boolean = true,
verificationMarks: Boolean = true,
exclusionRules: Boolean = true
) {
val options = MockKGateway.ClearOptions(
answers,
recordedCalls,
childMocks,
verificationMarks,
exclusionRules
)
val implementation = MockKGateway.implementation()
if (regularMocks) {
implementation.clearer.clearAll(options)
}
if (objectMocks) {
implementation.objectMockFactory.clearAll(options)
}
if (staticMocks) {
implementation.staticMockFactory.clearAll(options)
}
if (constructorMocks) {
implementation.constructorMockFactory.clearAll(options)
}
}
/*
* Checks if provided mock is mock of certain type
*/
fun internalIsMockKMock(
mock: Any,
regular: Boolean = true,
spy: Boolean = false,
objectMock: Boolean = false,
staticMock: Boolean = false,
constructorMock: Boolean = false
): Boolean {
val typeChecker = MockKGateway.implementation().mockTypeChecker
return when {
regular && typeChecker.isRegularMock(mock) -> true
spy && typeChecker.isSpy(mock) -> true
objectMock && typeChecker.isObjectMock(mock) -> true
staticMock && typeChecker.isStaticMock(mock) -> true
constructorMock && typeChecker.isConstructorMock(mock) -> true
else -> false
}
}
}
/**
* Verification ordering
*/
enum class Ordering {
/**
* Order is not important. Some calls just should happen
*/
UNORDERED,
/**
* Order is not important. All calls should happen
*/
ALL,
/**
* Order is important, but not all calls are checked
*/
ORDERED,
/**
* Order is important and all calls should be specified
*/
SEQUENCE
}
/**
* Basic stub/verification scope. Part of DSL.
*
* Inside of the scope you can interact with mocks.
* You can chain calls to the mock, put argument matchers instead of arguments,
* capture arguments, combine matchers in and/or/not expressions.
*
* It's not required to specify all arguments as matchers,
* if the argument value is constant it's automatically replaced with eq() matcher.
* .
* Handling arguments that have defaults fetched from function (alike System.currentTimeMillis())
* can be an issue, because it's not a constant. Such arguments can always be replaced
* with some matcher.
*
* Provided information is gathered and associated with mock
*/
open class MockKMatcherScope(
@PublishedApi
internal val callRecorder: CallRecorder,
val lambda: CapturingSlot<Function<*>>
) {
inline fun <reified T : Any> match(matcher: Matcher<T>): T {
return callRecorder.matcher(matcher, T::class)
}
inline fun <reified T : Any> match(noinline matcher: (T) -> Boolean): T =
match(FunctionMatcher(matcher, T::class))
inline fun <reified T : Any> matchNullable(noinline matcher: (T?) -> Boolean): T =
match(FunctionWithNullableArgMatcher(matcher, T::class))
inline fun <reified T : Any> eq(value: T, inverse: Boolean = false): T =
match(EqMatcher(value, inverse = inverse))
inline fun <reified T : Any> neq(value: T): T = eq(value, true)
inline fun <reified T : Any> refEq(value: T, inverse: Boolean = false): T =
match(EqMatcher(value, ref = true, inverse = inverse))
inline fun <reified T : Any> nrefEq(value: T) = refEq(value, true)
inline fun <reified T : Any> any(): T = match(ConstantMatcher(true))
inline fun <reified T : Any> capture(lst: MutableList<T>): T = match(CaptureMatcher(lst, T::class))
inline fun <reified T : Any> capture(lst: CapturingSlot<T>): T = match(CapturingSlotMatcher(lst, T::class))
inline fun <reified T : Any> captureNullable(lst: MutableList<T?>): T = match(CaptureNullableMatcher(lst, T::class))
inline fun <reified T : Comparable<T>> cmpEq(value: T): T = match(ComparingMatcher(value, 0, T::class))
inline fun <reified T : Comparable<T>> more(value: T, andEquals: Boolean = false): T =
match(ComparingMatcher(value, if (andEquals) 2 else 1, T::class))
inline fun <reified T : Comparable<T>> less(value: T, andEquals: Boolean = false): T =
match(ComparingMatcher(value, if (andEquals) -2 else -1, T::class))
inline fun <reified T : Comparable<T>> range(
from: T,
to: T,
fromInclusive: Boolean = true,
toInclusive: Boolean = true
): T = and(more(from, fromInclusive), less(to, toInclusive))
inline fun <reified T : Any> and(left: T, right: T) = match(AndOrMatcher(true, left, right))
inline fun <reified T : Any> or(left: T, right: T) = match(AndOrMatcher(false, left, right))
inline fun <reified T : Any> not(value: T) = match(NotMatcher(value))
inline fun <reified T : Any> isNull(inverse: Boolean = false) = match(NullCheckMatcher<T>(inverse))
inline fun <reified T : Any, R : T> ofType(cls: KClass<R>) = match(OfTypeMatcher<T>(cls))
inline fun <reified T : Any> ofType() = match(OfTypeMatcher<T>(T::class))
inline fun <reified T : Any> anyVararg() = varargAllNullable<T> { true }
inline fun anyBooleanVararg() = anyVararg<Boolean>().toBooleanArray()
inline fun anyByteVararg() = anyVararg<Byte>().toByteArray()
inline fun anyCharVararg() = anyVararg<Char>().toCharArray()
inline fun anyShortVararg() = anyVararg<Short>().toShortArray()
inline fun anyIntVararg() = anyVararg<Int>().toIntArray()
inline fun anyLongVararg() = anyVararg<Long>().toLongArray()
inline fun anyFloatVararg() = anyVararg<Float>().toFloatArray()
inline fun anyDoubleVararg() = anyVararg<Double>().toDoubleArray()
inline fun <reified T : Any> varargAll(noinline matcher: MockKVarargScope.(T) -> Boolean) =
varargAllNullable<T> {
when (it) {
null -> false
else -> matcher(it)
}
}
inline fun <reified T : Any> varargAllNullable(noinline matcher: MockKVarargScope.(T?) -> Boolean) =
arrayOf(callRecorder.matcher(VarargMatcher(true, matcher), T::class))
inline fun varargAllBoolean(noinline matcher: MockKVarargScope.(Boolean) -> Boolean) =
varargAll(matcher).toBooleanArray()
inline fun varargAllByte(noinline matcher: MockKVarargScope.(Byte) -> Boolean) =
varargAll(matcher).toByteArray()
inline fun varargAllChar(noinline matcher: MockKVarargScope.(Char) -> Boolean) =
varargAll(matcher).toCharArray()
inline fun varargAllShort(noinline matcher: MockKVarargScope.(Short) -> Boolean) =
varargAll(matcher).toShortArray()
inline fun varargAllInt(noinline matcher: MockKVarargScope.(Int) -> Boolean) =
varargAll(matcher).toIntArray()
inline fun varargAllLong(noinline matcher: MockKVarargScope.(Long) -> Boolean) =
varargAll(matcher).toLongArray()
inline fun varargAllFloat(noinline matcher: MockKVarargScope.(Float) -> Boolean) =
varargAll(matcher).toFloatArray()
inline fun varargAllDouble(noinline matcher: MockKVarargScope.(Double) -> Boolean) =
varargAll(matcher).toDoubleArray()
inline fun <reified T : Any> varargAny(noinline matcher: MockKVarargScope.(T) -> Boolean) =
varargAnyNullable<T> {
when (it) {
null -> false
else -> matcher(it)
}
}
inline fun <reified T : Any> varargAnyNullable(noinline matcher: MockKVarargScope.(T?) -> Boolean) =
arrayOf(callRecorder.matcher(VarargMatcher(false, matcher), T::class))
inline fun varargAnyBoolean(noinline matcher: MockKVarargScope.(Boolean) -> Boolean) =
varargAny(matcher).toBooleanArray()
inline fun varargAnyByte(noinline matcher: MockKVarargScope.(Byte) -> Boolean) =
varargAny(matcher).toByteArray()
inline fun varargAnyChar(noinline matcher: MockKVarargScope.(Char) -> Boolean) =
varargAny(matcher).toCharArray()
inline fun varargAnyShort(noinline matcher: MockKVarargScope.(Short) -> Boolean) =
varargAny(matcher).toShortArray()
inline fun varargAnyInt(noinline matcher: MockKVarargScope.(Int) -> Boolean) =
varargAny(matcher).toIntArray()
inline fun varargAnyLong(noinline matcher: MockKVarargScope.(Long) -> Boolean) =
varargAny(matcher).toLongArray()
inline fun varargAnyFloat(noinline matcher: MockKVarargScope.(Float) -> Boolean) =
varargAny(matcher).toFloatArray()
inline fun varargAnyDouble(noinline matcher: MockKVarargScope.(Double) -> Boolean) =
varargAny(matcher).toDoubleArray()
class MockKVarargScope(val position: Int, val nArgs: Int)
inline fun <reified T : () -> R, R> invoke() = match(InvokeMatcher<T> { it() })
inline fun <reified T : (A1) -> R, R, A1> invoke(arg1: A1) = match(InvokeMatcher<T> { it(arg1) })
inline fun <reified T : (A1, A2) -> R, R, A1, A2> invoke(arg1: A1, arg2: A2) =
match(InvokeMatcher<T> { it(arg1, arg2) })
inline fun <reified T : (A1, A2, A3) -> R, R, A1, A2, A3> invoke(arg1: A1, arg2: A2, arg3: A3) =
match(InvokeMatcher<T> { it(arg1, arg2, arg3) })
inline fun <reified T : (A1, A2, A3, A4) -> R, R, A1, A2, A3, A4> invoke(arg1: A1, arg2: A2, arg3: A3, arg4: A4) =
match(InvokeMatcher<T> { it(arg1, arg2, arg3, arg4) })
inline fun <reified T : (A1, A2, A3, A4, A5) -> R, R, A1, A2, A3, A4, A5> invoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5
) = match(InvokeMatcher<T> { it(arg1, arg2, arg3, arg4, arg5) })
inline fun <reified T : (A1, A2, A3, A4, A5, A6) -> R, R, A1, A2, A3, A4, A5, A6> invoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6
) = match(InvokeMatcher<T> { it(arg1, arg2, arg3, arg4, arg5, arg6) })
inline fun <reified T : (A1, A2, A3, A4, A5, A6, A7) -> R, R, A1, A2, A3, A4, A5, A6, A7> invoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6,
arg7: A7
) = match(InvokeMatcher<T> { it(arg1, arg2, arg3, arg4, arg5, arg6, arg7) })
inline fun <reified T : (A1, A2, A3, A4, A5, A6, A7, A8) -> R, R, A1, A2, A3, A4, A5, A6, A7, A8> invoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6,
arg7: A7,
arg8: A8
) = match(InvokeMatcher<T> { it(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8) })
inline fun <reified T : (A1, A2, A3, A4, A5, A6, A7, A8, A9) -> R, R, A1, A2, A3, A4, A5, A6, A7, A8, A9> invoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6,
arg7: A7,
arg8: A8,
arg9: A9
) = match(InvokeMatcher<T> { it(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9) })
inline fun <reified T : (A1, A2, A3, A4, A5, A6, A7, A8, A9, A10) -> R, R, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10> invoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6,
arg7: A7,
arg8: A8,
arg9: A9,
arg10: A10
) = match(InvokeMatcher<T> { it(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10) })
inline fun <reified T : (A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11) -> R, R, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11> invoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6,
arg7: A7,
arg8: A8,
arg9: A9,
arg10: A10,
arg11: A11
) = match(InvokeMatcher<T> { it(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11) })
inline fun <reified T : (A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12) -> R, R, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12> invoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6,
arg7: A7,
arg8: A8,
arg9: A9,
arg10: A10,
arg11: A11,
arg12: A12
) = match(InvokeMatcher<T> { it(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12) })
inline fun <reified T : (A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13) -> R, R, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13> invoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6,
arg7: A7,
arg8: A8,
arg9: A9,
arg10: A10,
arg11: A11,
arg12: A12,
arg13: A13
) = match(InvokeMatcher<T> { it(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13) })
inline fun <reified T : (A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14) -> R, R, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14> invoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6,
arg7: A7,
arg8: A8,
arg9: A9,
arg10: A10,
arg11: A11,
arg12: A12,
arg13: A13,
arg14: A14
) = match(InvokeMatcher<T> {
it(
arg1,
arg2,
arg3,
arg4,
arg5,
arg6,
arg7,
arg8,
arg9,
arg10,
arg11,
arg12,
arg13,
arg14
)
})
inline fun <reified T : (A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15) -> R, R, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15> invoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6,
arg7: A7,
arg8: A8,
arg9: A9,
arg10: A10,
arg11: A11,
arg12: A12,
arg13: A13,
arg14: A14,
arg15: A15
) = match(InvokeMatcher<T> {
it(
arg1,
arg2,
arg3,
arg4,
arg5,
arg6,
arg7,
arg8,
arg9,
arg10,
arg11,
arg12,
arg13,
arg14,
arg15
)
})
inline fun <reified T : (A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16) -> R, R, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16> invoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6,
arg7: A7,
arg8: A8,
arg9: A9,
arg10: A10,
arg11: A11,
arg12: A12,
arg13: A13,
arg14: A14,
arg15: A15,
arg16: A16
) = match(InvokeMatcher<T> {
it(
arg1,
arg2,
arg3,
arg4,
arg5,
arg6,
arg7,
arg8,
arg9,
arg10,
arg11,
arg12,
arg13,
arg14,
arg15,
arg16
)
})
inline fun <reified T : (A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17) -> R, R, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17> invoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6,
arg7: A7,
arg8: A8,
arg9: A9,
arg10: A10,
arg11: A11,
arg12: A12,
arg13: A13,
arg14: A14,
arg15: A15,
arg16: A16,
arg17: A17
) = match(InvokeMatcher<T> {
it(
arg1,
arg2,
arg3,
arg4,
arg5,
arg6,
arg7,
arg8,
arg9,
arg10,
arg11,
arg12,
arg13,
arg14,
arg15,
arg16,
arg17
)
})
inline fun <reified T : (A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18) -> R, R, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18> invoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6,
arg7: A7,
arg8: A8,
arg9: A9,
arg10: A10,
arg11: A11,
arg12: A12,
arg13: A13,
arg14: A14,
arg15: A15,
arg16: A16,
arg17: A17,
arg18: A18
) = match(InvokeMatcher<T> {
it(
arg1,
arg2,
arg3,
arg4,
arg5,
arg6,
arg7,
arg8,
arg9,
arg10,
arg11,
arg12,
arg13,
arg14,
arg15,
arg16,
arg17,
arg18
)
})
inline fun <reified T : (A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19) -> R, R, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19> invoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6,
arg7: A7,
arg8: A8,
arg9: A9,
arg10: A10,
arg11: A11,
arg12: A12,
arg13: A13,
arg14: A14,
arg15: A15,
arg16: A16,
arg17: A17,
arg18: A18,
arg19: A19
) = match(InvokeMatcher<T> {
it(
arg1,
arg2,
arg3,
arg4,
arg5,
arg6,
arg7,
arg8,
arg9,
arg10,
arg11,
arg12,
arg13,
arg14,
arg15,
arg16,
arg17,
arg18,
arg19
)
})
inline fun <reified T : (A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19, A20) -> R, R, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19, A20> invoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6,
arg7: A7,
arg8: A8,
arg9: A9,
arg10: A10,
arg11: A11,
arg12: A12,
arg13: A13,
arg14: A14,
arg15: A15,
arg16: A16,
arg17: A17,
arg18: A18,
arg19: A19,
arg20: A20
) = match(InvokeMatcher<T> {
it(
arg1,
arg2,
arg3,
arg4,
arg5,
arg6,
arg7,
arg8,
arg9,
arg10,
arg11,
arg12,
arg13,
arg14,
arg15,
arg16,
arg17,
arg18,
arg19,
arg20
)
})
inline fun <reified T : (A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19, A20, A21) -> R, R, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19, A20, A21> invoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6,
arg7: A7,
arg8: A8,
arg9: A9,
arg10: A10,
arg11: A11,
arg12: A12,
arg13: A13,
arg14: A14,
arg15: A15,
arg16: A16,
arg17: A17,
arg18: A18,
arg19: A19,
arg20: A20,
arg21: A21
) = match(InvokeMatcher<T> {
it(
arg1,
arg2,
arg3,
arg4,
arg5,
arg6,
arg7,
arg8,
arg9,
arg10,
arg11,
arg12,
arg13,
arg14,
arg15,
arg16,
arg17,
arg18,
arg19,
arg20,
arg21
)
})
inline fun <reified T : (A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19, A20, A21, A22) -> R, R, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19, A20, A21, A22> invoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6,
arg7: A7,
arg8: A8,
arg9: A9,
arg10: A10,
arg11: A11,
arg12: A12,
arg13: A13,
arg14: A14,
arg15: A15,
arg16: A16,
arg17: A17,
arg18: A18,
arg19: A19,
arg20: A20,
arg21: A21,
arg22: A22
) = match(InvokeMatcher<T> {
it(
arg1,
arg2,
arg3,
arg4,
arg5,
arg6,
arg7,
arg8,
arg9,
arg10,
arg11,
arg12,
arg13,
arg14,
arg15,
arg16,
arg17,
arg18,
arg19,
arg20,
arg21,
arg22
)
})
inline fun <reified T : suspend () -> R, R> coInvoke() =
match(InvokeMatcher<T> { InternalPlatformDsl.runCoroutine { it() } })
inline fun <reified T : suspend (A1) -> R, R, A1> coInvoke(arg1: A1) =
match(InvokeMatcher<T> { InternalPlatformDsl.runCoroutine { it(arg1) } })
inline fun <reified T : suspend (A1, A2) -> R, R, A1, A2> coInvoke(arg1: A1, arg2: A2) =
match(InvokeMatcher<T> { InternalPlatformDsl.runCoroutine { it(arg1, arg2) } })
inline fun <reified T : suspend (A1, A2, A3) -> R, R, A1, A2, A3> coInvoke(arg1: A1, arg2: A2, arg3: A3) =
match(InvokeMatcher<T> { InternalPlatformDsl.runCoroutine { it(arg1, arg2, arg3) } })
inline fun <reified T : suspend (A1, A2, A3, A4) -> R, R, A1, A2, A3, A4> coInvoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4
) = match(InvokeMatcher<T> { InternalPlatformDsl.runCoroutine { it(arg1, arg2, arg3, arg4) } })
inline fun <reified T : suspend (A1, A2, A3, A4, A5) -> R, R, A1, A2, A3, A4, A5> coInvoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5
) = match(InvokeMatcher<T> { InternalPlatformDsl.runCoroutine { it(arg1, arg2, arg3, arg4, arg5) } })
inline fun <reified T : suspend (A1, A2, A3, A4, A5, A6) -> R, R, A1, A2, A3, A4, A5, A6> coInvoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6
) = match(InvokeMatcher<T> { InternalPlatformDsl.runCoroutine { it(arg1, arg2, arg3, arg4, arg5, arg6) } })
inline fun <reified T : suspend (A1, A2, A3, A4, A5, A6, A7) -> R, R, A1, A2, A3, A4, A5, A6, A7> coInvoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6,
arg7: A7
) = match(InvokeMatcher<T> { InternalPlatformDsl.runCoroutine { it(arg1, arg2, arg3, arg4, arg5, arg6, arg7) } })
inline fun <reified T : suspend (A1, A2, A3, A4, A5, A6, A7, A8) -> R, R, A1, A2, A3, A4, A5, A6, A7, A8> coInvoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6,
arg7: A7,
arg8: A8
) = match(InvokeMatcher<T> {
InternalPlatformDsl.runCoroutine {
it(
arg1,
arg2,
arg3,
arg4,
arg5,
arg6,
arg7,
arg8
)
}
})
inline fun <reified T : suspend (A1, A2, A3, A4, A5, A6, A7, A8, A9) -> R, R, A1, A2, A3, A4, A5, A6, A7, A8, A9> coInvoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6,
arg7: A7,
arg8: A8,
arg9: A9
) = match(InvokeMatcher<T> {
InternalPlatformDsl.runCoroutine {
it(
arg1,
arg2,
arg3,
arg4,
arg5,
arg6,
arg7,
arg8,
arg9
)
}
})
inline fun <reified T : suspend (A1, A2, A3, A4, A5, A6, A7, A8, A9, A10) -> R, R, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10> coInvoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6,
arg7: A7,
arg8: A8,
arg9: A9,
arg10: A10
) = match(InvokeMatcher<T> {
InternalPlatformDsl.runCoroutine {
it(
arg1,
arg2,
arg3,
arg4,
arg5,
arg6,
arg7,
arg8,
arg9,
arg10
)
}
})
inline fun <reified T : suspend (A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11) -> R, R, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11> coInvoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6,
arg7: A7,
arg8: A8,
arg9: A9,
arg10: A10,
arg11: A11
) = match(InvokeMatcher<T> {
InternalPlatformDsl.runCoroutine {
it(
arg1,
arg2,
arg3,
arg4,
arg5,
arg6,
arg7,
arg8,
arg9,
arg10,
arg11
)
}
})
inline fun <reified T : suspend (A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12) -> R, R, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12> coInvoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6,
arg7: A7,
arg8: A8,
arg9: A9,
arg10: A10,
arg11: A11,
arg12: A12
) = match(InvokeMatcher<T> {
InternalPlatformDsl.runCoroutine {
it(
arg1,
arg2,
arg3,
arg4,
arg5,
arg6,
arg7,
arg8,
arg9,
arg10,
arg11,
arg12
)
}
})
inline fun <reified T : suspend (A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13) -> R, R, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13> coInvoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6,
arg7: A7,
arg8: A8,
arg9: A9,
arg10: A10,
arg11: A11,
arg12: A12,
arg13: A13
) = match(InvokeMatcher<T> {
InternalPlatformDsl.runCoroutine {
it(
arg1,
arg2,
arg3,
arg4,
arg5,
arg6,
arg7,
arg8,
arg9,
arg10,
arg11,
arg12,
arg13
)
}
})
inline fun <reified T : suspend (A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14) -> R, R, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14> coInvoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6,
arg7: A7,
arg8: A8,
arg9: A9,
arg10: A10,
arg11: A11,
arg12: A12,
arg13: A13,
arg14: A14
) = match(InvokeMatcher<T> {
InternalPlatformDsl.runCoroutine {
it(
arg1,
arg2,
arg3,
arg4,
arg5,
arg6,
arg7,
arg8,
arg9,
arg10,
arg11,
arg12,
arg13,
arg14
)
}
})
inline fun <reified T : suspend (A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15) -> R, R, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15> coInvoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6,
arg7: A7,
arg8: A8,
arg9: A9,
arg10: A10,
arg11: A11,
arg12: A12,
arg13: A13,
arg14: A14,
arg15: A15
) = match(InvokeMatcher<T> {
InternalPlatformDsl.runCoroutine {
it(
arg1,
arg2,
arg3,
arg4,
arg5,
arg6,
arg7,
arg8,
arg9,
arg10,
arg11,
arg12,
arg13,
arg14,
arg15
)
}
})
inline fun <reified T : suspend (A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16) -> R, R, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16> coInvoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6,
arg7: A7,
arg8: A8,
arg9: A9,
arg10: A10,
arg11: A11,
arg12: A12,
arg13: A13,
arg14: A14,
arg15: A15,
arg16: A16
) = match(InvokeMatcher<T> {
InternalPlatformDsl.runCoroutine {
it(
arg1,
arg2,
arg3,
arg4,
arg5,
arg6,
arg7,
arg8,
arg9,
arg10,
arg11,
arg12,
arg13,
arg14,
arg15,
arg16
)
}
})
inline fun <reified T : suspend (A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17) -> R, R, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17> coInvoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6,
arg7: A7,
arg8: A8,
arg9: A9,
arg10: A10,
arg11: A11,
arg12: A12,
arg13: A13,
arg14: A14,
arg15: A15,
arg16: A16,
arg17: A17
) = match(InvokeMatcher<T> {
InternalPlatformDsl.runCoroutine {
it(
arg1,
arg2,
arg3,
arg4,
arg5,
arg6,
arg7,
arg8,
arg9,
arg10,
arg11,
arg12,
arg13,
arg14,
arg15,
arg16,
arg17
)
}
})
inline fun <reified T : suspend (A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18) -> R, R, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18> coInvoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6,
arg7: A7,
arg8: A8,
arg9: A9,
arg10: A10,
arg11: A11,
arg12: A12,
arg13: A13,
arg14: A14,
arg15: A15,
arg16: A16,
arg17: A17,
arg18: A18
) = match(InvokeMatcher<T> {
InternalPlatformDsl.runCoroutine {
it(
arg1,
arg2,
arg3,
arg4,
arg5,
arg6,
arg7,
arg8,
arg9,
arg10,
arg11,
arg12,
arg13,
arg14,
arg15,
arg16,
arg17,
arg18
)
}
})
inline fun <reified T : suspend (A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19) -> R, R, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19> coInvoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6,
arg7: A7,
arg8: A8,
arg9: A9,
arg10: A10,
arg11: A11,
arg12: A12,
arg13: A13,
arg14: A14,
arg15: A15,
arg16: A16,
arg17: A17,
arg18: A18,
arg19: A19
) = match(InvokeMatcher<T> {
InternalPlatformDsl.runCoroutine {
it(
arg1,
arg2,
arg3,
arg4,
arg5,
arg6,
arg7,
arg8,
arg9,
arg10,
arg11,
arg12,
arg13,
arg14,
arg15,
arg16,
arg17,
arg18,
arg19
)
}
})
inline fun <reified T : suspend (A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19, A20) -> R, R, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19, A20> coInvoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6,
arg7: A7,
arg8: A8,
arg9: A9,
arg10: A10,
arg11: A11,
arg12: A12,
arg13: A13,
arg14: A14,
arg15: A15,
arg16: A16,
arg17: A17,
arg18: A18,
arg19: A19,
arg20: A20
) = match(InvokeMatcher<T> {
InternalPlatformDsl.runCoroutine {
it(
arg1,
arg2,
arg3,
arg4,
arg5,
arg6,
arg7,
arg8,
arg9,
arg10,
arg11,
arg12,
arg13,
arg14,
arg15,
arg16,
arg17,
arg18,
arg19,
arg20
)
}
})
inline fun <reified T : suspend (A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19, A20, A21) -> R, R, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19, A20, A21> coInvoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6,
arg7: A7,
arg8: A8,
arg9: A9,
arg10: A10,
arg11: A11,
arg12: A12,
arg13: A13,
arg14: A14,
arg15: A15,
arg16: A16,
arg17: A17,
arg18: A18,
arg19: A19,
arg20: A20,
arg21: A21
) = match(InvokeMatcher<T> {
InternalPlatformDsl.runCoroutine {
it(
arg1,
arg2,
arg3,
arg4,
arg5,
arg6,
arg7,
arg8,
arg9,
arg10,
arg11,
arg12,
arg13,
arg14,
arg15,
arg16,
arg17,
arg18,
arg19,
arg20,
arg21
)
}
})
inline fun <reified T : suspend (A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19, A20, A21, A22) -> R, R, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19, A20, A21, A22> coInvoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6,
arg7: A7,
arg8: A8,
arg9: A9,
arg10: A10,
arg11: A11,
arg12: A12,
arg13: A13,
arg14: A14,
arg15: A15,
arg16: A16,
arg17: A17,
arg18: A18,
arg19: A19,
arg20: A20,
arg21: A21,
arg22: A22
) = match(InvokeMatcher<T> {
InternalPlatformDsl.runCoroutine {
it(
arg1,
arg2,
arg3,
arg4,
arg5,
arg6,
arg7,
arg8,
arg9,
arg10,
arg11,
arg12,
arg13,
arg14,
arg15,
arg16,
arg17,
arg18,
arg19,
arg20,
arg21,
arg22
)
}
})
inline fun <reified T : Any> allAny(): T = match(AllAnyMatcher())
inline fun <reified T : Any> array(vararg matchers: Matcher<Any>): T = match(ArrayMatcher(matchers.toList()))
@Suppress("NOTHING_TO_INLINE")
inline fun <R, T : Any> R.hint(cls: KClass<T>, n: Int = 1): R {
callRecorder.hintNextReturnType(cls, n)
return this
}
/**
* Captures lambda function. Captured lambda<(A1, A2, ...) -> R>().invoke(...) can be used in answer scope.
*/
@Suppress("UNCHECKED_CAST")
inline fun <reified T : Function<*>> captureLambda(): T {
val matcher = CapturingSlotMatcher(lambda as CapturingSlot<T>, T::class)
return callRecorder.matcher(matcher, T::class)
}
/**
* Captures coroutine. Captured coroutine<suspend (A1, A2, ...) -> R>().coInvoke(...) can be used in answer scope.
*/
@Suppress("UNCHECKED_CAST")
inline fun <reified T : Any> captureCoroutine(): T {
val matcher = CapturingSlotMatcher(lambda as CapturingSlot<T>, T::class)
return callRecorder.matcher(matcher, T::class)
}
inline fun <reified T : Any> coMatch(noinline matcher: suspend (T) -> Boolean): T = match {
InternalPlatformDsl.runCoroutine {
matcher(it)
}
}
inline fun <reified T : Any> coMatchNullable(noinline matcher: suspend (T?) -> Boolean): T = matchNullable {
InternalPlatformDsl.runCoroutine {
matcher(it)
}
}
operator fun Any.get(name: String) =
DynamicCall(this, name, { any() })
infix fun Any.invoke(name: String) =
DynamicCallLong(this, name, { any() })
infix fun Any.invokeNoArgs(name: String) =
invoke(name).withArguments(listOf())
@Suppress("CAST_NEVER_SUCCEEDS")
infix fun Any.invokeReturnsUnit(name: String) = invoke(name) as Unit
infix fun Any.getProperty(name: String) =
InternalPlatformDsl.dynamicGet(this, name)
infix fun Any.setProperty(name: String) = DynamicSetProperty(this, name)
class DynamicSetProperty(val self: Any, val name: String) {
infix fun value(value: Any?) {
InternalPlatformDsl.dynamicSet(self, name, value)
}
}
class DynamicCall(
val self: Any,
val methodName: String,
val anyContinuationGen: () -> Continuation<*>
) {
operator fun invoke(vararg args: Any?) =
InternalPlatformDsl.dynamicCall(self, methodName, args, anyContinuationGen)
}
class DynamicCallLong(
val self: Any,
val methodName: String,
val anyContinuationGen: () -> Continuation<*>
) {
infix fun withArguments(args: List<Any?>) =
InternalPlatformDsl.dynamicCall(self, methodName, args.toTypedArray(), anyContinuationGen)
}
inline fun <reified T : Any> anyConstructed(): T =
MockKGateway.implementation().constructorMockFactory.mockPlaceholder(T::class)
}
/**
* Part of DSL. Additional operations for verification scope.
*/
class MockKVerificationScope(
callRecorder: CallRecorder,
lambda: CapturingSlot<Function<*>>
) : MockKMatcherScope(callRecorder, lambda) {
@Deprecated(
"'assert' is problematic in case of many calls being verified",
ReplaceWith("match(assertion)")
)
inline fun <reified T : Any> assert(msg: String? = null, noinline assertion: (T) -> Boolean): T =
match(AssertMatcher({ assertion(it as T) }, msg, T::class))
@Deprecated(
"'assertNullable' is problematic in case of many calls being verified",
ReplaceWith("matchNullable(assertion)")
)
inline fun <reified T : Any> assertNullable(msg: String? = null, noinline assertion: (T?) -> Boolean): T =
match(AssertMatcher(assertion, msg, T::class, nullable = true))
@Deprecated("'run' seems to be too wide name, so replaced with 'withArg'", ReplaceWith("withArg(captureBlock)"))
inline fun <reified T : Any> run(noinline captureBlock: MockKAssertScope.(T) -> Unit): T = match {
MockKAssertScope(it).captureBlock(it)
true
}
@Deprecated(
"'runNullable' seems to be too wide name, so replaced with 'withNullableArg'",
ReplaceWith("withNullableArg(captureBlock)")
)
inline fun <reified T : Any> runNullable(noinline captureBlock: MockKAssertScope.(T?) -> Unit): T = matchNullable {
MockKAssertScope(it).captureBlock(it)
true
}
inline fun <reified T : Any> withArg(noinline captureBlock: MockKAssertScope.(T) -> Unit): T = run(captureBlock)
inline fun <reified T : Any> withNullableArg(noinline captureBlock: MockKAssertScope.(T?) -> Unit): T =
runNullable(captureBlock)
@Deprecated(
"'coAssert' is problematic in case of many calls being verified",
ReplaceWith("coMatch(assertion)")
)
inline fun <reified T : Any> coAssert(msg: String? = null, noinline assertion: suspend (T) -> Boolean): T =
assert(msg) {
InternalPlatformDsl.runCoroutine {
assertion(it)
}
}
@Deprecated(
"'coAssertNullable' is problematic in case of many calls being verified",
ReplaceWith("coMatchNullable(assertion)")
)
inline fun <reified T : Any> coAssertNullable(msg: String? = null, noinline assertion: suspend (T?) -> Boolean): T =
assertNullable(msg) {
InternalPlatformDsl.runCoroutine {
assertion(it)
}
}
@Deprecated(
"'coRun' seems to be too wide name, so replaced with 'coWithArg'",
ReplaceWith("withNullableArg(captureBlock)")
)
inline fun <reified T : Any> coRun(noinline captureBlock: suspend MockKAssertScope.(T) -> Unit): T = run {
InternalPlatformDsl.runCoroutine {
captureBlock(it)
}
}
@Deprecated(
"'coRunNullable' seems to be too wide name, so replaced with 'coWithNullableArg'",
ReplaceWith("withNullableArg(captureBlock)")
)
inline fun <reified T : Any> coRunNullable(noinline captureBlock: suspend MockKAssertScope.(T?) -> Unit): T =
runNullable {
InternalPlatformDsl.runCoroutine {
captureBlock(it)
}
}
inline fun <reified T : Any> coWithArg(noinline captureBlock: suspend MockKAssertScope.(T) -> Unit): T =
coRun(captureBlock)
inline fun <reified T : Any> coWithNullableArg(noinline captureBlock: suspend MockKAssertScope.(T?) -> Unit): T =
coRunNullable(captureBlock)
infix fun Any.wasNot(called: Called) {
listOf(this) wasNot called
}
@Suppress("UNUSED_PARAMETER")
infix fun List<Any>.wasNot(called: Called) {
callRecorder.wasNotCalled(this)
}
}
/**
* Part of DSL. Object to represent phrase "wasNot Called"
*/
object Called
typealias called = Called
/**
* Part of DSL. Scope for assertions on arguments during verifications.
*/
class MockKAssertScope(val actual: Any?)
fun MockKAssertScope.checkEquals(expected: Any?) {
if (!InternalPlatformDsl.deepEquals(expected, actual)) {
throw AssertionError(formatAssertMessage(actual, expected))
}
}
fun MockKAssertScope.checkEquals(msg: String, expected: Any?) {
if (!InternalPlatformDsl.deepEquals(expected, actual)) {
throw AssertionError(formatAssertMessage(actual, expected, msg))
}
}
private fun formatAssertMessage(actual: Any?, expected: Any?, message: String? = null): String {
val msgFormatted = if (message != null) "$message " else ""
return "${msgFormatted}expected [$expected] but found [$actual]"
}
/**
* Part of DSL. Object to represent phrase "just Runs"
*/
object Runs
typealias runs = Runs
/**
* Stub scope. Part of DSL
*
* Allows to specify function result
*/
class MockKStubScope<T, B>(
private val answerOpportunity: AnswerOpportunity<T>,
private val callRecorder: CallRecorder,
private val lambda: CapturingSlot<Function<*>>
) {
infix fun answers(answer: Answer<T>): MockKAdditionalAnswerScope<T, B> {
answerOpportunity.provideAnswer(answer)
return MockKAdditionalAnswerScope(answerOpportunity, callRecorder, lambda)
}
infix fun returns(returnValue: T) = answers(ConstantAnswer(returnValue))
infix fun returnsMany(values: List<T>) = answers(ManyAnswersAnswer(values.allConst()))
fun returnsMany(vararg values: T) = returnsMany(values.toList())
@Suppress("UNCHECKED_CAST")
infix fun returnsArgument(n: Int): MockKAdditionalAnswerScope<T, B> =
this answers { invocation.args[n] as T }
infix fun throws(ex: Throwable) = answers(ThrowingAnswer(ex))
infix fun answers(answer: MockKAnswerScope<T, B>.(Call) -> T) =
answers(FunctionAnswer { MockKAnswerScope<T, B>(lambda, it).answer(it) })
@Suppress("UNUSED_PARAMETER")
infix fun <K : Any> propertyType(cls: KClass<K>) = MockKStubScope<T, K>(answerOpportunity, callRecorder, lambda)
@Suppress("UNUSED_PARAMETER")
infix fun <K : Any> nullablePropertyType(cls: KClass<K>) =
MockKStubScope<T, K?>(answerOpportunity, callRecorder, lambda)
infix fun coAnswers(answer: suspend MockKAnswerScope<T, B>.(Call) -> T) =
answers(CoFunctionAnswer { MockKAnswerScope<T, B>(lambda, it).answer(it) })
}
/**
* Part of DSL. Answer placeholder for Unit returning functions.
*/
@Suppress("UNUSED_PARAMETER")
infix fun MockKStubScope<Unit, Unit>.just(runs: Runs) = answers(ConstantAnswer(Unit))
/**
* Scope to chain additional answers to reply. Part of DSL
*/
class MockKAdditionalAnswerScope<T, B>(
private val answerOpportunity: AnswerOpportunity<T>,
private val callRecorder: CallRecorder,
private val lambda: CapturingSlot<Function<*>>
) {
infix fun andThenAnswer(answer: Answer<T>): MockKAdditionalAnswerScope<T, B> {
answerOpportunity.provideAnswer(answer)
return this
}
infix fun andThen(returnValue: T) = andThenAnswer(ConstantAnswer(returnValue))
infix fun andThenMany(values: List<T>) = andThenAnswer(ManyAnswersAnswer(values.allConst()))
fun andThenMany(vararg values: T) = andThenMany(values.toList())
infix fun andThenThrows(ex: Throwable) = andThenAnswer(ThrowingAnswer(ex))
infix fun andThen(answer: MockKAnswerScope<T, B>.(Call) -> T) =
andThenAnswer(FunctionAnswer { MockKAnswerScope<T, B>(lambda, it).answer(it) })
infix fun coAndThen(answer: suspend MockKAnswerScope<T, B>.(Call) -> T) =
andThenAnswer(CoFunctionAnswer { MockKAnswerScope<T, B>(lambda, it).answer(it) })
}
internal fun <T> List<T>.allConst() = this.map { ConstantAnswer(it) }
/**
* Scope for answering functions. Part of DSL
*/
class MockKAnswerScope<T, B>(
@PublishedApi
internal val lambda: CapturingSlot<Function<*>>,
val call: Call
) {
val invocation = call.invocation
val matcher = call.matcher
val self
get() = invocation.self
val method
get() = invocation.method
val args
get() = invocation.args
val nArgs
get() = invocation.args.size
inline fun <reified T> firstArg() = invocation.args[0] as T
inline fun <reified T> secondArg() = invocation.args[1] as T
inline fun <reified T> thirdArg() = invocation.args[2] as T
inline fun <reified T> lastArg() = invocation.args.last() as T
inline fun <reified T> arg(n: Int) = invocation.args[n] as T
@Suppress("NOTHING_TO_INLINE")
inline fun <T> MutableList<T>.captured() = last()
@Suppress("UNCHECKED_CAST")
inline fun <reified T : Function<*>> lambda() = lambda as CapturingSlot<T>
@Suppress("UNCHECKED_CAST")
inline fun <reified T : Any> coroutine() = lambda as CapturingSlot<T>
val nothing = null
@Suppress("UNCHECKED_CAST")
fun callOriginal(): T = call.invocation.originalCall.invoke() as T
@Suppress("UNCHECKED_CAST")
val value: B
get() = valueAny as B
val valueAny: Any?
get() = firstArg()
private val backingFieldValue: BackingFieldValue? by lazy { call.fieldValueProvider() }
@Suppress("UNCHECKED_CAST")
var fieldValue: B
set(value) {
fieldValueAny = value
}
get() = fieldValueAny as B
var fieldValueAny: Any?
set(value) {
val fv = backingFieldValue
?: throw MockKException("no backing field found for '${call.invocation.method.name}'")
fv.setter(value)
}
get() {
val fv = backingFieldValue
?: throw MockKException("no backing field found for '${call.invocation.method.name}'")
return fv.getter()
}
}
/**
* Cancelable mocking scope
*/
abstract class MockKUnmockKScope {
fun mock() {
val cancellation = doMock()
MockKCancellationRegistry.pushCancellation(cancellation)
}
fun unmock() {
val cancellation = MockKCancellationRegistry.popCancellation() ?: throw MockKException("Not mocked")
cancellation.invoke()
}
protected abstract fun doMock(): () -> Unit
abstract fun clear(
answers: Boolean = true,
recordedCalls: Boolean = true,
childMocks: Boolean = true,
verificationMarks: Boolean = true,
exclusionRules: Boolean = true
)
operator fun plus(scope: MockKUnmockKScope): MockKUnmockKScope = MockKUnmockKCompositeScope(this, scope)
}
typealias MockKCancellation = () -> Unit
object MockKCancellationRegistry {
enum class Type { OBJECT, STATIC, CONSTRUCTOR }
class RegistryPerType {
private val mapTl = InternalPlatformDsl.threadLocal { mutableMapOf<Any, MockKCancellation>() }
fun cancelPut(key: Any, newCancellation: MockKCancellation) {
val map = mapTl.value
map.remove(key)?.invoke()
map[key] = newCancellation
}
fun cancelAll() {
val map = mapTl.value
map.values.forEach { it() }
map.clear()
}
fun cancel(key: Any) {
mapTl.value.remove(key)?.invoke()
}
}
private val stack = InternalPlatformDsl.threadLocal { mutableListOf<MockKCancellation>() }
private val perType = mapOf(
Type.OBJECT to RegistryPerType(),
Type.STATIC to RegistryPerType(),
Type.CONSTRUCTOR to RegistryPerType()
)
fun subRegistry(type: Type) = perType[type]!!
fun pushCancellation(cancellation: MockKCancellation) = stack.value.add(cancellation)
fun popCancellation(): (MockKCancellation)? {
val list = stack.value
return if (list.isEmpty())
null
else
list.removeAt(list.size - 1)
}
fun cancelAll() {
stack.value.apply { forEach { it() } }.clear()
perType.values.forEach { it.cancelAll() }
}
}
/**
* Composite of two scopes. Part of DSL
*/
class MockKUnmockKCompositeScope(
val first: MockKUnmockKScope,
val second: MockKUnmockKScope
) : MockKUnmockKScope() {
override fun doMock(): MockKCancellation {
first.mock()
second.mock()
return {
first.unmock()
second.unmock()
}
}
override fun clear(
answers: Boolean,
recordedCalls: Boolean,
childMocks: Boolean,
verificationMarks: Boolean,
exclusionRules: Boolean
) {
first.clear(
answers,
recordedCalls,
childMocks,
verificationMarks,
exclusionRules
)
second.clear(
answers,
recordedCalls,
childMocks,
verificationMarks,
exclusionRules
)
}
}
/**
* Scope for static mockks. Part of DSL
*/
class MockKStaticScope(vararg val staticTypes: KClass<*>) : MockKUnmockKScope() {
override fun doMock(): MockKCancellation {
val factory = MockKGateway.implementation().staticMockFactory
val cancellations = staticTypes.map {
factory.staticMockk(it)
}
return { cancellations.forEach { it() } }
}
override fun clear(
answers: Boolean,
recordedCalls: Boolean,
childMocks: Boolean,
verificationMarks: Boolean,
exclusionRules: Boolean
) {
for (type in staticTypes) {
MockKGateway.implementation().staticMockFactory.clear(
type,
MockKGateway.ClearOptions(
answers,
recordedCalls,
childMocks,
verificationMarks,
exclusionRules
)
)
}
}
inline fun <reified T : Any> and() = MockKStaticScope(T::class, *staticTypes)
}
/**
* Scope for object mockks. Part of DSL
*/
class MockKObjectScope(vararg val objects: Any, val recordPrivateCalls: Boolean = false) : MockKUnmockKScope() {
override fun doMock(): MockKCancellation {
val factory = MockKGateway.implementation().objectMockFactory
val cancellations = objects.map {
factory.objectMockk(it, recordPrivateCalls)
}
return { cancellations.forEach { it() } }
}
override fun clear(
answers: Boolean,
recordedCalls: Boolean,
childMocks: Boolean,
verificationMarks: Boolean,
exclusionRules: Boolean
) {
for (obj in objects) {
MockKGateway.implementation().objectMockFactory.clear(
obj,
MockKGateway.ClearOptions(
answers,
recordedCalls,
childMocks,
verificationMarks,
exclusionRules
)
)
}
}
@Suppress("NOTHING_TO_INLINE")
inline fun and(obj: Any) = MockKObjectScope(obj, *objects)
}
/**
* Scope for constructor calls. Part of DSL.
*/
class MockKConstructorScope<T : Any>(
val type: KClass<T>,
val recordPrivateCalls: Boolean,
val localToThread: Boolean
) : MockKUnmockKScope() {
override fun doMock(): MockKCancellation {
return MockKGateway.implementation().constructorMockFactory.constructorMockk(
type, recordPrivateCalls, localToThread
)
}
override fun clear(
answers: Boolean,
recordedCalls: Boolean,
childMocks: Boolean,
verificationMarks: Boolean,
exclusionRules: Boolean
) {
MockKGateway.implementation().constructorMockFactory.clear(
type,
MockKGateway.ClearOptions(
answers,
recordedCalls,
childMocks,
verificationMarks,
exclusionRules
)
)
}
}
/**
* Wraps block of code for safe resource allocation and deallocation. Part of DSL
*/
inline fun <T> MockKUnmockKScope.use(block: () -> T): T {
mock()
return try {
block()
} finally {
unmock()
}
}
/**
* Slot allows to capture one value.
*
* If this values is lambda then it's possible to invoke it.
*/
class CapturingSlot<T : Any>() {
var isCaptured = false
var isNull = false
lateinit var captured: T
fun clear() {
isCaptured = false
isNull = false
}
override fun toString(): String =
"slot(${if (isCaptured) "captured=${if (isNull) "null" else captured.toStr()}" else ""})"
}
inline fun <reified T : () -> R, R> CapturingSlot<T>.invoke() = captured.invoke()
inline fun <reified T : (A1) -> R, R, A1> CapturingSlot<T>.invoke(arg1: A1) = captured.invoke(arg1)
inline fun <reified T : (A1, A2) -> R, R, A1, A2> CapturingSlot<T>.invoke(arg1: A1, arg2: A2) =
captured.invoke(arg1, arg2)
inline fun <reified T : (A1, A2, A3) -> R, R, A1, A2, A3> CapturingSlot<T>.invoke(arg1: A1, arg2: A2, arg3: A3) =
captured.invoke(arg1, arg2, arg3)
inline fun <reified T : (A1, A2, A3, A4) -> R, R, A1, A2, A3, A4> CapturingSlot<T>.invoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4
) = captured.invoke(arg1, arg2, arg3, arg4)
inline fun <reified T : (A1, A2, A3, A4, A5) -> R, R, A1, A2, A3, A4, A5> CapturingSlot<T>.invoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5
) = captured.invoke(arg1, arg2, arg3, arg4, arg5)
inline fun <reified T : (A1, A2, A3, A4, A5, A6) -> R, R, A1, A2, A3, A4, A5, A6> CapturingSlot<T>.invoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6
) = captured.invoke(arg1, arg2, arg3, arg4, arg5, arg6)
inline fun <reified T : (A1, A2, A3, A4, A5, A6, A7) -> R, R, A1, A2, A3, A4, A5, A6, A7> CapturingSlot<T>.invoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6,
arg7: A7
) = captured.invoke(arg1, arg2, arg3, arg4, arg5, arg6, arg7)
inline fun <reified T : (A1, A2, A3, A4, A5, A6, A7, A8) -> R, R, A1, A2, A3, A4, A5, A6, A7, A8> CapturingSlot<T>.invoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6,
arg7: A7,
arg8: A8
) = captured.invoke(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8)
inline fun <reified T : (A1, A2, A3, A4, A5, A6, A7, A8, A9) -> R, R, A1, A2, A3, A4, A5, A6, A7, A8, A9> CapturingSlot<T>.invoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6,
arg7: A7,
arg8: A8,
arg9: A9
) = captured.invoke(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9)
inline fun <reified T : (A1, A2, A3, A4, A5, A6, A7, A8, A9, A10) -> R, R, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10> CapturingSlot<T>.invoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6,
arg7: A7,
arg8: A8,
arg9: A9,
arg10: A10
) = captured.invoke(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10)
inline fun <reified T : (A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11) -> R, R, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11> CapturingSlot<T>.invoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6,
arg7: A7,
arg8: A8,
arg9: A9,
arg10: A10,
arg11: A11
) = captured.invoke(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11)
inline fun <reified T : (A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12) -> R, R, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12> CapturingSlot<T>.invoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6,
arg7: A7,
arg8: A8,
arg9: A9,
arg10: A10,
arg11: A11,
arg12: A12
) = captured.invoke(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12)
inline fun <reified T : (A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13) -> R, R, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13> CapturingSlot<T>.invoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6,
arg7: A7,
arg8: A8,
arg9: A9,
arg10: A10,
arg11: A11,
arg12: A12,
arg13: A13
) = captured.invoke(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13)
inline fun <reified T : (A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14) -> R, R, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14> CapturingSlot<T>.invoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6,
arg7: A7,
arg8: A8,
arg9: A9,
arg10: A10,
arg11: A11,
arg12: A12,
arg13: A13,
arg14: A14
) = captured.invoke(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14)
inline fun <reified T : (A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15) -> R, R, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15> CapturingSlot<T>.invoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6,
arg7: A7,
arg8: A8,
arg9: A9,
arg10: A10,
arg11: A11,
arg12: A12,
arg13: A13,
arg14: A14,
arg15: A15
) = captured.invoke(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15)
inline fun <reified T : (A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16) -> R, R, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16> CapturingSlot<T>.invoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6,
arg7: A7,
arg8: A8,
arg9: A9,
arg10: A10,
arg11: A11,
arg12: A12,
arg13: A13,
arg14: A14,
arg15: A15,
arg16: A16
) = captured.invoke(
arg1,
arg2,
arg3,
arg4,
arg5,
arg6,
arg7,
arg8,
arg9,
arg10,
arg11,
arg12,
arg13,
arg14,
arg15,
arg16
)
inline fun <reified T : (A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17) -> R, R, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17> CapturingSlot<T>.invoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6,
arg7: A7,
arg8: A8,
arg9: A9,
arg10: A10,
arg11: A11,
arg12: A12,
arg13: A13,
arg14: A14,
arg15: A15,
arg16: A16,
arg17: A17
) = captured.invoke(
arg1,
arg2,
arg3,
arg4,
arg5,
arg6,
arg7,
arg8,
arg9,
arg10,
arg11,
arg12,
arg13,
arg14,
arg15,
arg16,
arg17
)
inline fun <reified T : (A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18) -> R, R, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18> CapturingSlot<T>.invoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6,
arg7: A7,
arg8: A8,
arg9: A9,
arg10: A10,
arg11: A11,
arg12: A12,
arg13: A13,
arg14: A14,
arg15: A15,
arg16: A16,
arg17: A17,
arg18: A18
) = captured.invoke(
arg1,
arg2,
arg3,
arg4,
arg5,
arg6,
arg7,
arg8,
arg9,
arg10,
arg11,
arg12,
arg13,
arg14,
arg15,
arg16,
arg17,
arg18
)
inline fun <reified T : (A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19) -> R, R, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19> CapturingSlot<T>.invoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6,
arg7: A7,
arg8: A8,
arg9: A9,
arg10: A10,
arg11: A11,
arg12: A12,
arg13: A13,
arg14: A14,
arg15: A15,
arg16: A16,
arg17: A17,
arg18: A18,
arg19: A19
) = captured.invoke(
arg1,
arg2,
arg3,
arg4,
arg5,
arg6,
arg7,
arg8,
arg9,
arg10,
arg11,
arg12,
arg13,
arg14,
arg15,
arg16,
arg17,
arg18,
arg19
)
inline fun <reified T : (A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19, A20) -> R, R, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19, A20> CapturingSlot<T>.invoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6,
arg7: A7,
arg8: A8,
arg9: A9,
arg10: A10,
arg11: A11,
arg12: A12,
arg13: A13,
arg14: A14,
arg15: A15,
arg16: A16,
arg17: A17,
arg18: A18,
arg19: A19,
arg20: A20
) = captured.invoke(
arg1,
arg2,
arg3,
arg4,
arg5,
arg6,
arg7,
arg8,
arg9,
arg10,
arg11,
arg12,
arg13,
arg14,
arg15,
arg16,
arg17,
arg18,
arg19,
arg20
)
inline fun <reified T : (A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19, A20, A21) -> R, R, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19, A20, A21> CapturingSlot<T>.invoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6,
arg7: A7,
arg8: A8,
arg9: A9,
arg10: A10,
arg11: A11,
arg12: A12,
arg13: A13,
arg14: A14,
arg15: A15,
arg16: A16,
arg17: A17,
arg18: A18,
arg19: A19,
arg20: A20,
arg21: A21
) = captured.invoke(
arg1,
arg2,
arg3,
arg4,
arg5,
arg6,
arg7,
arg8,
arg9,
arg10,
arg11,
arg12,
arg13,
arg14,
arg15,
arg16,
arg17,
arg18,
arg19,
arg20,
arg21
)
inline fun <reified T : (A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19, A20, A21, A22) -> R, R, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19, A20, A21, A22> CapturingSlot<T>.invoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6,
arg7: A7,
arg8: A8,
arg9: A9,
arg10: A10,
arg11: A11,
arg12: A12,
arg13: A13,
arg14: A14,
arg15: A15,
arg16: A16,
arg17: A17,
arg18: A18,
arg19: A19,
arg20: A20,
arg21: A21,
arg22: A22
) = captured.invoke(
arg1,
arg2,
arg3,
arg4,
arg5,
arg6,
arg7,
arg8,
arg9,
arg10,
arg11,
arg12,
arg13,
arg14,
arg15,
arg16,
arg17,
arg18,
arg19,
arg20,
arg21,
arg22
)
inline fun <reified T : suspend () -> R, R> CapturingSlot<T>.coInvoke() =
InternalPlatformDsl.runCoroutine { captured.invoke() }
inline fun <reified T : suspend (A1) -> R, R, A1> CapturingSlot<T>.coInvoke(arg1: A1) =
InternalPlatformDsl.runCoroutine { captured.invoke(arg1) }
inline fun <reified T : suspend (A1, A2) -> R, R, A1, A2> CapturingSlot<T>.coInvoke(arg1: A1, arg2: A2) =
InternalPlatformDsl.runCoroutine { captured.invoke(arg1, arg2) }
inline fun <reified T : suspend (A1, A2, A3) -> R, R, A1, A2, A3> CapturingSlot<T>.coInvoke(
arg1: A1,
arg2: A2,
arg3: A3
) = InternalPlatformDsl.runCoroutine { captured.invoke(arg1, arg2, arg3) }
inline fun <reified T : suspend (A1, A2, A3, A4) -> R, R, A1, A2, A3, A4> CapturingSlot<T>.coInvoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4
) = InternalPlatformDsl.runCoroutine { captured.invoke(arg1, arg2, arg3, arg4) }
inline fun <reified T : suspend (A1, A2, A3, A4, A5) -> R, R, A1, A2, A3, A4, A5> CapturingSlot<T>.coInvoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5
) = InternalPlatformDsl.runCoroutine { captured.invoke(arg1, arg2, arg3, arg4, arg5) }
inline fun <reified T : suspend (A1, A2, A3, A4, A5, A6) -> R, R, A1, A2, A3, A4, A5, A6> CapturingSlot<T>.coInvoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6
) = InternalPlatformDsl.runCoroutine { captured.invoke(arg1, arg2, arg3, arg4, arg5, arg6) }
inline fun <reified T : suspend (A1, A2, A3, A4, A5, A6, A7) -> R, R, A1, A2, A3, A4, A5, A6, A7> CapturingSlot<T>.coInvoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6,
arg7: A7
) = InternalPlatformDsl.runCoroutine { captured.invoke(arg1, arg2, arg3, arg4, arg5, arg6, arg7) }
inline fun <reified T : suspend (A1, A2, A3, A4, A5, A6, A7, A8) -> R, R, A1, A2, A3, A4, A5, A6, A7, A8> CapturingSlot<T>.coInvoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6,
arg7: A7,
arg8: A8
) = InternalPlatformDsl.runCoroutine { captured.invoke(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8) }
inline fun <reified T : suspend (A1, A2, A3, A4, A5, A6, A7, A8, A9) -> R, R, A1, A2, A3, A4, A5, A6, A7, A8, A9> CapturingSlot<T>.coInvoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6,
arg7: A7,
arg8: A8,
arg9: A9
) = InternalPlatformDsl.runCoroutine { captured.invoke(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9) }
inline fun <reified T : suspend (A1, A2, A3, A4, A5, A6, A7, A8, A9, A10) -> R, R, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10> CapturingSlot<T>.coInvoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6,
arg7: A7,
arg8: A8,
arg9: A9,
arg10: A10
) = InternalPlatformDsl.runCoroutine { captured.invoke(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10) }
inline fun <reified T : suspend (A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11) -> R, R, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11> CapturingSlot<T>.coInvoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6,
arg7: A7,
arg8: A8,
arg9: A9,
arg10: A10,
arg11: A11
) = InternalPlatformDsl.runCoroutine {
captured.invoke(
arg1,
arg2,
arg3,
arg4,
arg5,
arg6,
arg7,
arg8,
arg9,
arg10,
arg11
)
}
inline fun <reified T : suspend (A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12) -> R, R, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12> CapturingSlot<T>.coInvoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6,
arg7: A7,
arg8: A8,
arg9: A9,
arg10: A10,
arg11: A11,
arg12: A12
) = InternalPlatformDsl.runCoroutine {
captured.invoke(
arg1,
arg2,
arg3,
arg4,
arg5,
arg6,
arg7,
arg8,
arg9,
arg10,
arg11,
arg12
)
}
inline fun <reified T : suspend (A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13) -> R, R, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13> CapturingSlot<T>.coInvoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6,
arg7: A7,
arg8: A8,
arg9: A9,
arg10: A10,
arg11: A11,
arg12: A12,
arg13: A13
) = InternalPlatformDsl.runCoroutine {
captured.invoke(
arg1,
arg2,
arg3,
arg4,
arg5,
arg6,
arg7,
arg8,
arg9,
arg10,
arg11,
arg12,
arg13
)
}
inline fun <reified T : suspend (A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14) -> R, R, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14> CapturingSlot<T>.coInvoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6,
arg7: A7,
arg8: A8,
arg9: A9,
arg10: A10,
arg11: A11,
arg12: A12,
arg13: A13,
arg14: A14
) = InternalPlatformDsl.runCoroutine {
captured.invoke(
arg1,
arg2,
arg3,
arg4,
arg5,
arg6,
arg7,
arg8,
arg9,
arg10,
arg11,
arg12,
arg13,
arg14
)
}
inline fun <reified T : suspend (A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15) -> R, R, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15> CapturingSlot<T>.coInvoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6,
arg7: A7,
arg8: A8,
arg9: A9,
arg10: A10,
arg11: A11,
arg12: A12,
arg13: A13,
arg14: A14,
arg15: A15
) = InternalPlatformDsl.runCoroutine {
captured.invoke(
arg1,
arg2,
arg3,
arg4,
arg5,
arg6,
arg7,
arg8,
arg9,
arg10,
arg11,
arg12,
arg13,
arg14,
arg15
)
}
inline fun <reified T : suspend (A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16) -> R, R, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16> CapturingSlot<T>.coInvoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6,
arg7: A7,
arg8: A8,
arg9: A9,
arg10: A10,
arg11: A11,
arg12: A12,
arg13: A13,
arg14: A14,
arg15: A15,
arg16: A16
) = InternalPlatformDsl.runCoroutine {
captured.invoke(
arg1,
arg2,
arg3,
arg4,
arg5,
arg6,
arg7,
arg8,
arg9,
arg10,
arg11,
arg12,
arg13,
arg14,
arg15,
arg16
)
}
inline fun <reified T : suspend (A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17) -> R, R, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17> CapturingSlot<T>.coInvoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6,
arg7: A7,
arg8: A8,
arg9: A9,
arg10: A10,
arg11: A11,
arg12: A12,
arg13: A13,
arg14: A14,
arg15: A15,
arg16: A16,
arg17: A17
) = InternalPlatformDsl.runCoroutine {
captured.invoke(
arg1,
arg2,
arg3,
arg4,
arg5,
arg6,
arg7,
arg8,
arg9,
arg10,
arg11,
arg12,
arg13,
arg14,
arg15,
arg16,
arg17
)
}
inline fun <reified T : suspend (A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18) -> R, R, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18> CapturingSlot<T>.coInvoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6,
arg7: A7,
arg8: A8,
arg9: A9,
arg10: A10,
arg11: A11,
arg12: A12,
arg13: A13,
arg14: A14,
arg15: A15,
arg16: A16,
arg17: A17,
arg18: A18
) = InternalPlatformDsl.runCoroutine {
captured.invoke(
arg1,
arg2,
arg3,
arg4,
arg5,
arg6,
arg7,
arg8,
arg9,
arg10,
arg11,
arg12,
arg13,
arg14,
arg15,
arg16,
arg17,
arg18
)
}
inline fun <reified T : suspend (A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19) -> R, R, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19> CapturingSlot<T>.coInvoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6,
arg7: A7,
arg8: A8,
arg9: A9,
arg10: A10,
arg11: A11,
arg12: A12,
arg13: A13,
arg14: A14,
arg15: A15,
arg16: A16,
arg17: A17,
arg18: A18,
arg19: A19
) = InternalPlatformDsl.runCoroutine {
captured.invoke(
arg1,
arg2,
arg3,
arg4,
arg5,
arg6,
arg7,
arg8,
arg9,
arg10,
arg11,
arg12,
arg13,
arg14,
arg15,
arg16,
arg17,
arg18,
arg19
)
}
inline fun <reified T : suspend (A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19, A20) -> R, R, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19, A20> CapturingSlot<T>.coInvoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6,
arg7: A7,
arg8: A8,
arg9: A9,
arg10: A10,
arg11: A11,
arg12: A12,
arg13: A13,
arg14: A14,
arg15: A15,
arg16: A16,
arg17: A17,
arg18: A18,
arg19: A19,
arg20: A20
) = InternalPlatformDsl.runCoroutine {
captured.invoke(
arg1,
arg2,
arg3,
arg4,
arg5,
arg6,
arg7,
arg8,
arg9,
arg10,
arg11,
arg12,
arg13,
arg14,
arg15,
arg16,
arg17,
arg18,
arg19,
arg20
)
}
inline fun <reified T : suspend (A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19, A20, A21) -> R, R, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19, A20, A21> CapturingSlot<T>.coInvoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6,
arg7: A7,
arg8: A8,
arg9: A9,
arg10: A10,
arg11: A11,
arg12: A12,
arg13: A13,
arg14: A14,
arg15: A15,
arg16: A16,
arg17: A17,
arg18: A18,
arg19: A19,
arg20: A20,
arg21: A21
) = InternalPlatformDsl.runCoroutine {
captured.invoke(
arg1,
arg2,
arg3,
arg4,
arg5,
arg6,
arg7,
arg8,
arg9,
arg10,
arg11,
arg12,
arg13,
arg14,
arg15,
arg16,
arg17,
arg18,
arg19,
arg20,
arg21
)
}
inline fun <reified T : suspend (A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19, A20, A21, A22) -> R, R, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19, A20, A21, A22> CapturingSlot<T>.coInvoke(
arg1: A1,
arg2: A2,
arg3: A3,
arg4: A4,
arg5: A5,
arg6: A6,
arg7: A7,
arg8: A8,
arg9: A9,
arg10: A10,
arg11: A11,
arg12: A12,
arg13: A13,
arg14: A14,
arg15: A15,
arg16: A16,
arg17: A17,
arg18: A18,
arg19: A19,
arg20: A20,
arg21: A21,
arg22: A22
) = InternalPlatformDsl.runCoroutine {
captured.invoke(
arg1,
arg2,
arg3,
arg4,
arg5,
arg6,
arg7,
arg8,
arg9,
arg10,
arg11,
arg12,
arg13,
arg14,
arg15,
arg16,
arg17,
arg18,
arg19,
arg20,
arg21,
arg22
)
}
/**
* Checks if argument is matching some criteria
*/
interface Matcher<in T> {
fun match(arg: T?): Boolean
fun substitute(map: Map<Any, Any>): Matcher<T> = this
}
/**
* Checks if argument is of specific type
*/
interface TypedMatcher {
val argumentType: KClass<*>
fun checkType(arg: Any?): Boolean {
if (argumentType.simpleName === null) {
return true
}
return argumentType.isInstance(arg)
}
}
/**
* Allows to substitute matcher to find correct chained call
*/
interface EquivalentMatcher {
fun equivalent(): Matcher<Any>
}
/**
* Captures the argument
*/
interface CapturingMatcher {
fun capture(arg: Any?)
}
/**
* Matcher composed from several other matchers.
*
* Allows to build matching expressions. Alike "and(eq(5), capture(lst))"
*/
interface CompositeMatcher<T> {
val operandValues: List<T>
var subMatchers: List<Matcher<T>>?
}
/**
* Provides return value for mocked function
*/
interface Answer<out T> {
fun answer(call: Call): T
suspend fun coAnswer(call: Call): T = answer(call)
}
/**
* Manipulable field value
*/
class BackingFieldValue(
val name: String,
val getter: () -> Any?,
val setter: (Any?) -> Unit
)
typealias BackingFieldValueProvider = () -> BackingFieldValue?
/**
* Call happened for stubbed mock
*/
data class Call(
val retType: KClass<*>,
val invocation: Invocation,
val matcher: InvocationMatcher,
val fieldValueProvider: BackingFieldValueProvider
)
/**
* Provides information about method
*/
data class MethodDescription(
val name: String,
val returnType: KClass<*>,
val returnsUnit: Boolean,
val returnsNothing: Boolean,
val isSuspend: Boolean,
val declaringClass: KClass<*>,
val paramTypes: List<KClass<*>>,
val varArgsArg: Int,
val privateCall: Boolean
) {
override fun toString() = "$name(${argsToStr()})"
fun argsToStr() = paramTypes.map(this::argToStr).joinToString(", ")
fun argToStr(argType: KClass<*>) = argType.simpleName
fun isToString() = name == "toString" && paramTypes.isEmpty()
fun isHashCode() = name == "hashCode" && paramTypes.isEmpty()
fun isEquals() = name == "equals" && paramTypes.size == 1 && paramTypes[0] == Any::class
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is MethodDescription) return false
return when {
name != other.name -> false
returnType != other.returnType -> false
declaringClass != other.declaringClass -> false
paramTypes != other.paramTypes -> false
else -> true
}
}
override fun hashCode(): Int {
var result = name.hashCode()
result = 31 * result + returnType.hashCode()
result = 31 * result + declaringClass.hashCode()
result = 31 * result + paramTypes.hashCode()
return result
}
}
/**
* Mock invocation
*/
data class Invocation(
val self: Any,
val stub: Any,
val method: MethodDescription,
val args: List<Any?>,
val timestamp: Long,
val callStack: () -> List<StackElement>,
val originalCall: () -> Any?,
val fieldValueProvider: BackingFieldValueProvider
) {
fun substitute(map: Map<Any, Any>) = Invocation(
self.internalSubstitute(map),
stub,
method.internalSubstitute(map),
args.internalSubstitute(map),
timestamp,
callStack,
originalCall,
fieldValueProvider
)
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Invocation) return false
return when {
self !== other.self -> false
method != other.method -> false
args != other.args -> false
else -> true
}
}
override fun hashCode(): Int {
var result = InternalPlatformDsl.identityHashCode(self)
result = 31 * result + method.hashCode()
result = 31 * result + args.hashCode()
return result
}
override fun toString(): String =
"$self.${method.name}(${args.joinToString(", ", transform = { it.toStr() })})"
}
/**
* Element of stack trace.
*/
data class StackElement(
val className: String,
val fileName: String,
val methodName: String,
val line: Int,
val nativeMethod: Boolean
)
/**
* Checks if invocation is matching via number of matchers
*/
data class InvocationMatcher(
val self: Any,
val method: MethodDescription,
val args: List<Matcher<Any>>,
val allAny: Boolean
) {
fun substitute(map: Map<Any, Any>) = InvocationMatcher(
self.internalSubstitute(map),
method.internalSubstitute(map),
args.internalSubstitute(map),
allAny
)
fun match(invocation: Invocation): Boolean {
if (self !== invocation.self) {
return false
}
if (method != invocation.method) {
return false
}
if (allAny) {
if (args.size < invocation.args.size) {
return false
}
} else {
if (args.size != invocation.args.size) {
return false
}
}
for (i in 0 until invocation.args.size) {
val matcher = args[i]
val arg = invocation.args[i]
if (matcher is TypedMatcher) {
if (!matcher.checkType(arg)) {
return false
}
}
if (!matcher.match(arg)) {
return false
}
}
return true
}
fun captureAnswer(invocation: Invocation) {
for ((idx, argMatcher) in args.withIndex()) {
if (argMatcher is CapturingMatcher) {
argMatcher.capture(invocation.args[idx])
}
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is InvocationMatcher) return false
return when {
self !== other.self -> false
method != other.method -> false
args != other.args -> false
else -> true
}
}
override fun hashCode(): Int {
var result = InternalPlatformDsl.identityHashCode(self)
result = 31 * result + method.hashCode()
result = 31 * result + args.hashCode()
return result
}
override fun toString(): String {
return "$self.${method.name}(${args.joinToString(", ")}))"
}
}
/**
* Matched call
*/
data class RecordedCall(
val retValue: Any?,
val isRetValueMock: Boolean,
val retType: KClass<*>,
val matcher: InvocationMatcher,
val selfChain: RecordedCall?,
val argChains: List<Any>?
) {
override fun toString(): String {
return "RecordedCall(retValue=${retValue.toStr()}, retType=${retType.toStr()}, isRetValueMock=$isRetValueMock matcher=$matcher)"
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is RecordedCall) return false
return when {
retValue !== other.retValue -> false
isRetValueMock != other.isRetValueMock -> false
retType != other.retType -> false
matcher != other.matcher -> false
selfChain != other.selfChain -> false
argChains != other.argChains -> false
else -> true
}
}
override fun hashCode(): Int {
var result = retValue?.let { InternalPlatformDsl.identityHashCode(it) } ?: 0
result = 31 * result + isRetValueMock.hashCode()
result = 31 * result + retType.hashCode()
result = 31 * result + matcher.hashCode()
result = 31 * result + (selfChain?.hashCode() ?: 0)
result = 31 * result + (argChains?.hashCode() ?: 0)
return result
}
}
/**
* Allows to deregister something was registered before
*/
interface Deregisterable {
fun deregister()
}
inline fun <T : Deregisterable, R> T.use(block: (T) -> R): R {
try {
return block(this)
} finally {
try {
this.deregister()
} catch (closeException: Throwable) {
// skip
}
}
}
@Suppress("UNCHECKED_CAST")
fun <T> T.internalSubstitute(map: Map<Any, Any>): T {
return (map[this as Any? ?: return null as T] ?: this) as T
}
fun <T : Any> List<T>.internalSubstitute(map: Map<Any, Any>) = this.map { it.internalSubstitute(map) }
| apache-2.0 | 10fedb69fdabdc414fe6762b62c78588 | 25.650373 | 270 | 0.530196 | 3.26278 | false | false | false | false |
andstatus/andstatus | app/src/main/kotlin/org/andstatus/app/data/DataUpdater.kt | 1 | 22371 | /*
* Copyright (c) 2012-2017 yvolk (Yuri Volkov), http://yurivolkov.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.andstatus.app.data
import android.content.ContentValues
import android.net.Uri
import io.vavr.control.Try
import org.andstatus.app.account.MyAccount
import org.andstatus.app.actor.GroupType
import org.andstatus.app.context.MyContextHolder
import org.andstatus.app.context.MyPreferences
import org.andstatus.app.database.table.ActivityTable
import org.andstatus.app.database.table.ActorTable
import org.andstatus.app.database.table.NoteTable
import org.andstatus.app.net.social.AActivity
import org.andstatus.app.net.social.AObjectType
import org.andstatus.app.net.social.ActivityType
import org.andstatus.app.net.social.Actor
import org.andstatus.app.net.social.InputTimelinePage
import org.andstatus.app.net.social.Note
import org.andstatus.app.net.social.TimelinePosition
import org.andstatus.app.note.KeywordsFilter
import org.andstatus.app.service.CommandData
import org.andstatus.app.service.CommandEnum
import org.andstatus.app.service.CommandExecutionContext
import org.andstatus.app.timeline.meta.TimelineType
import org.andstatus.app.util.MyLog
import org.andstatus.app.util.RelativeTime
import org.andstatus.app.util.SharedPreferencesUtil
import org.andstatus.app.util.StringUtil
import org.andstatus.app.util.TriState
import org.andstatus.app.util.UriUtils
import java.util.*
/**
* Stores (updates) notes and actors
* from a Social network into a database.
*
* @author [email protected]
*/
class DataUpdater(private val execContext: CommandExecutionContext) {
private val lum: LatestActorActivities = LatestActorActivities()
private val keywordsFilter: KeywordsFilter = KeywordsFilter(
SharedPreferencesUtil.getString(MyPreferences.KEY_FILTER_HIDE_NOTES_BASED_ON_KEYWORDS, ""))
constructor(ma: MyAccount) : this(CommandExecutionContext(
ma.myContext.takeIf { !it.isEmptyOrExpired } ?: MyContextHolder.myContextHolder.getNow(),
CommandData.newAccountCommand(CommandEnum.EMPTY, ma)
)) {
}
fun onActivity(mbActivity: AActivity?): AActivity? {
return onActivity(mbActivity, true)
}
fun onActivity(activity: AActivity?, saveLum: Boolean): AActivity? {
return onActivityInternal(activity, saveLum, 0)
}
// TODO: return non nullable value
private fun onActivityInternal(activity: AActivity?, saveLum: Boolean, recursing: Int): AActivity? {
if (activity == null ||
activity.getObjectType() == AObjectType.EMPTY ||
recursing > MAX_RECURSING) {
return activity
}
updateObjActor(activity.accountActor.update(activity.getActor()), recursing + 1)
when (activity.getObjectType()) {
AObjectType.ACTIVITY -> onActivityInternal(activity.getActivity(), false, recursing + 1)
AObjectType.NOTE -> updateNote(activity, recursing + 1)
AObjectType.ACTOR -> updateObjActor(activity, recursing + 1)
else -> return activity
}
updateActivity(activity)
if (saveLum && recursing == 0) {
saveLum()
}
return activity
}
private fun updateActivity(activity: AActivity) {
if (activity.isSubscribedByMe().notFalse
&& activity.getUpdatedDate() > 0 && (activity.isMyActorOrAuthor(execContext.myContext)
|| activity.getNote().audience().containsMe(execContext.myContext))) {
activity.setSubscribedByMe(TriState.TRUE)
}
if (activity.isNotified().unknown && execContext.myContext.users.isMe(activity.getActor()) &&
activity.getNote().getStatus().isPresentAtServer() &&
MyQuery.activityIdToTriState(ActivityTable.NOTIFIED, activity.getId()).isTrue) {
activity.setNotified(TriState.FALSE)
}
activity.save(execContext.myContext)
lum.onNewActorActivity(ActorActivity(activity.getActor().actorId, activity.getId(), activity.getUpdatedDate()))
if (!activity.isAuthorActor()) {
lum.onNewActorActivity(ActorActivity(activity.getAuthor().actorId, activity.getId(), activity.getUpdatedDate()))
}
execContext.getResult().onNotificationEvent(activity.getNewNotificationEventType())
}
fun saveLum() {
lum.save()
}
private fun updateNote(activity: AActivity, recursing: Int) {
if (recursing > MAX_RECURSING) return
updateNote1(activity, recursing)
onActivities(execContext, activity.getNote().replies.toMutableList())
}
private fun updateNote1(activity: AActivity, recursing: Int) {
val method = "updateNote1"
val note = activity.getNote()
try {
val me = execContext.myContext.accounts.fromActorOfSameOrigin(activity.accountActor)
if (me.nonValid) {
MyLog.w(this, "$method; my account is invalid, skipping: $activity")
return
}
updateObjActor(me.actor.update(me.actor, activity.getActor()), recursing + 1)
if (activity.isAuthorActor()) {
activity.setAuthor(activity.getActor())
} else {
updateObjActor(activity.getActor().update(me.actor, activity.getAuthor()), recursing + 1)
}
if (note.noteId == 0L) {
note.noteId = MyQuery.oidToId(OidEnum.NOTE_OID, note.origin.id, note.oid)
}
val updatedDateStored: Long
val statusStored: DownloadStatus
if (note.noteId != 0L) {
statusStored = DownloadStatus.load(
MyQuery.noteIdToLongColumnValue(NoteTable.NOTE_STATUS, note.noteId))
updatedDateStored = MyQuery.noteIdToLongColumnValue(NoteTable.UPDATED_DATE, note.noteId)
} else {
updatedDateStored = 0
statusStored = DownloadStatus.ABSENT
}
/*
* Is the row first time retrieved from a Social Network?
* Note can already exist in this these cases:
* 1. There was only "a stub" stored (without a sent date and content)
* 2. Note was "unsent" i.e. it had content, but didn't have oid
*/
val isFirstTimeLoaded = (note.getStatus() == DownloadStatus.LOADED || note.noteId == 0L) &&
statusStored != DownloadStatus.LOADED
val isFirstTimeSent = !isFirstTimeLoaded && note.noteId != 0L &&
StringUtil.nonEmptyNonTemp(note.oid) &&
statusStored.isUnsentDraft() &&
StringUtil.isEmptyOrTemp(MyQuery.idToOid(execContext.myContext,
OidEnum.NOTE_OID, note.noteId, 0))
if (note.getStatus() == DownloadStatus.UNKNOWN && isFirstTimeSent) {
note.setStatus(DownloadStatus.SENT)
}
val isDraftUpdated = !isFirstTimeLoaded && !isFirstTimeSent && note.getStatus().isUnsentDraft()
val isNewerThanInDatabase = note.updatedDate > updatedDateStored
if (!isFirstTimeLoaded && !isFirstTimeSent && !isDraftUpdated && !isNewerThanInDatabase) {
MyLog.v("Note") { "Skipped note as not younger $note" }
return
}
// TODO: move as toContentValues() into Note
val values = ContentValues()
if (isFirstTimeLoaded || note.noteId == 0L) {
values.put(NoteTable.INS_DATE, MyLog.uniqueCurrentTimeMS)
}
values.put(NoteTable.NOTE_STATUS, note.getStatus().save())
if (isNewerThanInDatabase) {
values.put(NoteTable.UPDATED_DATE, note.updatedDate)
}
if (activity.getAuthor().actorId != 0L) {
values.put(NoteTable.AUTHOR_ID, activity.getAuthor().actorId)
}
if (UriUtils.nonEmptyOid(note.oid)) {
values.put(NoteTable.NOTE_OID, note.oid)
}
values.put(NoteTable.ORIGIN_ID, note.origin.id)
if (UriUtils.nonEmptyOid(note.conversationOid)) {
values.put(NoteTable.CONVERSATION_OID, note.conversationOid)
}
if (note.hasSomeContent()) {
values.put(NoteTable.NAME, note.getName())
values.put(NoteTable.SUMMARY, note.summary)
values.put(NoteTable.SENSITIVE, if (note.isSensitive()) 1 else 0)
values.put(NoteTable.CONTENT, note.content)
values.put(NoteTable.CONTENT_TO_SEARCH, note.getContentToSearch())
}
updateInReplyTo(activity, values)
activity.getNote().audience().lookupUsers()
for (actor in note.audience().evaluateAndGetActorsToSave(activity.getAuthor())) {
updateObjActor(activity.getActor().update(me.actor, actor), recursing + 1)
}
if (!note.via.isNullOrEmpty()) {
values.put(NoteTable.VIA, note.via)
}
if (!note.url.isNullOrEmpty()) {
values.put(NoteTable.URL, note.url)
}
if (note.audience().visibility.isKnown()) {
values.put(NoteTable.VISIBILITY, note.audience().visibility.id)
}
if (note.getLikesCount() > 0) {
values.put(NoteTable.LIKES_COUNT, note.getLikesCount())
}
if (note.getReblogsCount() > 0) {
values.put(NoteTable.REBLOGS_COUNT, note.getReblogsCount())
}
if (note.getRepliesCount() > 0) {
values.put(NoteTable.REPLIES_COUNT, note.getRepliesCount())
}
if (note.lookupConversationId() != 0L) {
values.put(NoteTable.CONVERSATION_ID, note.getConversationId())
}
if (note.getStatus().mayUpdateContent() && shouldSaveAttachments(isFirstTimeLoaded, isDraftUpdated)) {
values.put(NoteTable.ATTACHMENTS_COUNT, note.attachments.size)
}
if (MyLog.isVerboseEnabled()) {
MyLog.v(this) {
((if (note.noteId == 0L) "insertNote" else "updateNote " + note.noteId)
+ ":" + note.getStatus()
+ (if (isFirstTimeLoaded) " new;" else "")
+ (if (isDraftUpdated) " draft updated;" else "")
+ (if (isFirstTimeSent) " just sent;" else "")
+ if (isNewerThanInDatabase) " newer, updated at " + Date(note.updatedDate) + ";" else "")
}
}
if ( MyContextHolder.myContextHolder.getNow().isTestRun) {
MyContextHolder.myContextHolder.getNow().putAssertionData(MSG_ASSERTION_KEY, values)
}
if (note.noteId == 0L) {
val msgUri = execContext.getContext().contentResolver.insert(
MatchedUri.getMsgUri(me.actorId, 0), values) ?: Uri.EMPTY
note.noteId = ParsedUri.fromUri(msgUri).getNoteId()
if (note.getConversationId() == 0L) {
val values2 = ContentValues()
values2.put(NoteTable.CONVERSATION_ID, note.setConversationIdFromMsgId())
execContext.getContext().contentResolver.update(msgUri, values2, null, null)
}
MyLog.v("Note") { "Added $note" }
if (!note.hasSomeContent() && note.getStatus().canBeDownloaded) {
Note.requestDownload(me, note.noteId, false)
}
} else {
val msgUri: Uri = MatchedUri.getMsgUri(me.actorId, note.noteId)
execContext.getContext().contentResolver.update(msgUri, values, null, null)
MyLog.v("Note") { "Updated $note" }
}
if (note.getStatus().mayUpdateContent()) {
note.audience().save(activity.getAuthor(), note.noteId, note.audience().visibility, false)
if (shouldSaveAttachments(isFirstTimeLoaded, isDraftUpdated)) {
note.attachments.save(execContext, note.noteId)
}
if (keywordsFilter.matchedAny(note.getContentToSearch())) {
activity.setNotified(TriState.FALSE)
} else {
if (note.getStatus() == DownloadStatus.LOADED) {
execContext.getResult().incrementDownloadedCount()
execContext.getResult().incrementNewCount()
}
}
}
} catch (e: Exception) {
MyLog.e(this, method, e)
}
}
private fun shouldSaveAttachments(isFirstTimeLoaded: Boolean, isDraftUpdated: Boolean): Boolean {
return isFirstTimeLoaded || isDraftUpdated
}
private fun updateInReplyTo(activity: AActivity, values: ContentValues) {
val inReply = activity.getNote().inReplyTo
if (!inReply.getNote().oid.isNullOrEmpty()) {
if (UriUtils.nonRealOid(inReply.getNote().conversationOid)) {
inReply.getNote().setConversationOid(activity.getNote().conversationOid)
}
DataUpdater(execContext).onActivity(inReply)
if (inReply.getNote().noteId != 0L) {
activity.getNote().audience().add(inReply.getAuthor())
values.put(NoteTable.IN_REPLY_TO_NOTE_ID, inReply.getNote().noteId)
if (inReply.getAuthor().actorId != 0L) {
values.put(NoteTable.IN_REPLY_TO_ACTOR_ID, inReply.getAuthor().actorId)
}
}
}
}
fun updateObjActor(activity: AActivity, recursing: Int) {
if (recursing > MAX_RECURSING) return
val objActor = activity.getObjActor()
val method = "updateObjActor"
if (objActor.dontStore()) {
MyLog.v(this) { method + "; don't store: " + objActor.uniqueName }
return
}
val me = execContext.myContext.accounts.fromActorOfSameOrigin(activity.accountActor)
if (me.nonValid) {
if (activity.accountActor == objActor) {
MyLog.d(this, method + "; adding my account " + activity.accountActor)
} else {
MyLog.w(this, method + "; my account is invalid, skipping: " + activity.toString())
return
}
}
fixActorUpdatedDate(activity, objActor)
objActor.lookupActorId()
if (objActor.actorId == 0L) {
if (objActor.cannotAdd) {
MyLog.v(this) { "$method; Skipping invalid new: $objActor" }
return
}
} else if (objActor.isNotFullyDefined() && objActor.isMyFriend.unknown
&& activity.followedByActor().unknown && objActor.groupType == GroupType.UNKNOWN) {
MyLog.v(this) { "$method; Skipping existing partially defined: $objActor" }
return
}
objActor.lookupUser()
if (shouldWeUpdateActor(method, objActor)) {
updateObjActor2(activity, recursing, me)
} else {
updateFriendships(activity, me)
execContext.myContext.users.reload(objActor)
}
MyLog.v(this) { "$method; $objActor" }
}
private fun shouldWeUpdateActor(method: String, objActor: Actor): Boolean {
val updatedDateStored = MyQuery.actorIdToLongColumnValue(ActorTable.UPDATED_DATE, objActor.actorId)
if (updatedDateStored > RelativeTime.SOME_TIME_AGO && updatedDateStored >= objActor.getUpdatedDate()) {
MyLog.v(this) { "$method; Skipped actor update as not younger $objActor" }
return false
}
return true
}
private fun updateObjActor2(activity: AActivity, recursing: Int, me: MyAccount) {
val method = "updateObjActor2"
try {
val actor = activity.getObjActor()
val actorOid = if (actor.actorId == 0L && !actor.isOidReal()) actor.toTempOid() else actor.oid
val values = ContentValues()
if (actor.actorId == 0L || actor.isFullyDefined()) {
if (actor.actorId == 0L || actor.isOidReal()) {
values.put(ActorTable.ACTOR_OID, actorOid)
}
// Substitute required empty values with some temporary for a new entry only!
var username = actor.getUsername()
if (SharedPreferencesUtil.isEmpty(username)) {
username = StringUtil.toTempOid(actorOid)
}
values.put(ActorTable.USERNAME, username)
values.put(ActorTable.WEBFINGER_ID, actor.getWebFingerId())
var realName = actor.getRealName()
if (SharedPreferencesUtil.isEmpty(realName)) {
realName = username
}
values.put(ActorTable.REAL_NAME, realName)
// End of required attributes
}
if (actor.groupType != GroupType.UNKNOWN) {
values.put(ActorTable.GROUP_TYPE, actor.groupType.id)
}
if (actor.getParentActorId() != 0L) {
values.put(ActorTable.PARENT_ACTOR_ID, actor.getParentActorId())
}
if (actor.hasAvatar()) {
values.put(ActorTable.AVATAR_URL, actor.getAvatarUrl())
}
if (!SharedPreferencesUtil.isEmpty(actor.getSummary())) {
values.put(ActorTable.SUMMARY, actor.getSummary())
}
if (!SharedPreferencesUtil.isEmpty(actor.getHomepage())) {
values.put(ActorTable.HOMEPAGE, actor.getHomepage())
}
if (!SharedPreferencesUtil.isEmpty(actor.getProfileUrl())) {
values.put(ActorTable.PROFILE_PAGE, actor.getProfileUrl())
}
if (!SharedPreferencesUtil.isEmpty(actor.location)) {
values.put(ActorTable.LOCATION, actor.location)
}
if (actor.notesCount > 0) {
values.put(ActorTable.NOTES_COUNT, actor.notesCount)
}
if (actor.favoritesCount > 0) {
values.put(ActorTable.FAVORITES_COUNT, actor.favoritesCount)
}
if (actor.followingCount > 0) {
values.put(ActorTable.FOLLOWING_COUNT, actor.followingCount)
}
if (actor.followersCount > 0) {
values.put(ActorTable.FOLLOWERS_COUNT, actor.followersCount)
}
if (actor.getCreatedDate() > 0) {
values.put(ActorTable.CREATED_DATE, actor.getCreatedDate())
}
if (actor.getUpdatedDate() > 0) {
values.put(ActorTable.UPDATED_DATE, actor.getUpdatedDate())
}
actor.saveUser()
val actorUri: Uri = MatchedUri.getActorUri(me.actorId, actor.actorId)
if (actor.actorId == 0L) {
values.put(ActorTable.ORIGIN_ID, actor.origin.id)
values.put(ActorTable.USER_ID, actor.user.userId)
actor.actorId = ParsedUri.fromUri(
execContext.getContext().contentResolver.insert(actorUri, values))
.getActorId()
} else if (values.size() > 0) {
execContext.getContext().contentResolver.update(actorUri, values, null, null)
}
actor.endpoints.save(actor.actorId)
updateFriendships(activity, me)
actor.avatarFile.resetAvatarErrors(execContext.myContext)
execContext.myContext.users.reload(actor)
if (actor.isNotFullyDefined() && actor.canGetActor()) {
actor.requestDownload(false)
}
actor.requestAvatarDownload()
if (actor.hasLatestNote()) {
updateNote(actor.getLatestActivity(), recursing + 1)
}
} catch (e: Exception) {
MyLog.e(this, "$method; $activity", e)
}
}
private fun updateFriendships(activity: AActivity, me: MyAccount) {
val actor = activity.getObjActor()
GroupMembership.setFriendshipAndReload(execContext.myContext, me.actor, actor.isMyFriend, actor)
GroupMembership.setFriendshipAndReload(execContext.myContext, activity.getActor(), activity.followedByActor(), actor)
}
private fun fixActorUpdatedDate(activity: AActivity, actor: Actor) {
if (actor.getCreatedDate() <= RelativeTime.SOME_TIME_AGO && actor.getUpdatedDate() <= RelativeTime.SOME_TIME_AGO) return
if (actor.getUpdatedDate() <= RelativeTime.SOME_TIME_AGO || activity.type == ActivityType.FOLLOW || activity.type == ActivityType.UNDO_FOLLOW) {
actor.setUpdatedDate(Math.max(activity.getUpdatedDate(), actor.getCreatedDate()))
}
}
fun downloadOneNoteBy(actor: Actor): Try<Unit> {
return execContext.getConnection()
.getTimeline(true, TimelineType.SENT.connectionApiRoutine, TimelinePosition.EMPTY,
TimelinePosition.EMPTY, 1, actor)
.map { page: InputTimelinePage ->
for (item in page.items) {
onActivity(item, false)
}
saveLum()
}
}
companion object {
const val MAX_RECURSING = 4
val MSG_ASSERTION_KEY: String = "updateNote"
fun onActivities(execContext: CommandExecutionContext, activities: List<AActivity>) {
val dataUpdater = DataUpdater(execContext)
for (mbActivity in activities) {
dataUpdater.onActivity(mbActivity)
}
}
}
}
| apache-2.0 | 1e55b1aa3768f71078b96e89bb617c81 | 45.997899 | 152 | 0.599794 | 4.584221 | false | false | false | false |
minecraft-dev/MinecraftDev | src/main/kotlin/platform/mixin/handlers/ModifyArgHandler.kt | 1 | 5217 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mixin.handlers
import com.demonwav.mcdev.platform.mixin.inspection.injector.MethodSignature
import com.demonwav.mcdev.platform.mixin.inspection.injector.ParameterGroup
import com.demonwav.mcdev.platform.mixin.util.fakeResolve
import com.demonwav.mcdev.platform.mixin.util.getParameter
import com.demonwav.mcdev.platform.mixin.util.toPsiType
import com.demonwav.mcdev.util.constantValue
import com.demonwav.mcdev.util.descriptor
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiAnnotation
import com.intellij.psi.PsiMethod
import org.objectweb.asm.Type
import org.objectweb.asm.tree.AbstractInsnNode
import org.objectweb.asm.tree.ClassNode
import org.objectweb.asm.tree.MethodInsnNode
import org.objectweb.asm.tree.MethodNode
class ModifyArgHandler : InjectorAnnotationHandler() {
override fun isInsnAllowed(insn: AbstractInsnNode): Boolean {
return insn is MethodInsnNode
}
override fun expectedMethodSignature(
annotation: PsiAnnotation,
targetClass: ClassNode,
targetMethod: MethodNode
): List<MethodSignature>? {
val index = annotation.findDeclaredAttributeValue("index")?.constantValue as? Int
val validSingleArgTypes = mutableSetOf<String>()
var mayHaveValidFullSignature = true
var validFullSignature: String? = null
val insns = resolveInstructions(annotation, targetClass, targetMethod).ifEmpty { return emptyList() }
for (insn in insns) {
if (insn.insn !is MethodInsnNode) return null
// normalize return type so whole signature matches
val desc = insn.insn.desc.replaceAfterLast(')', "V")
if (index == null) {
val validArgTypes = Type.getArgumentTypes(desc).mapTo(mutableListOf()) { it.descriptor }
// remove duplicates completely, they are invalid
val toRemove = validArgTypes.filter { e -> validArgTypes.count { it == e } > 1 }.toSet()
validArgTypes.removeIf { toRemove.contains(it) }
if (validArgTypes.isEmpty()) {
return listOf()
}
if (validSingleArgTypes.isEmpty()) {
validSingleArgTypes.addAll(validArgTypes)
} else {
validSingleArgTypes.retainAll(validArgTypes)
if (validSingleArgTypes.isEmpty()) {
return listOf()
}
}
} else {
val singleArgType = Type.getArgumentTypes(desc).getOrNull(index)?.descriptor ?: return listOf()
if (validSingleArgTypes.isEmpty()) {
validSingleArgTypes += singleArgType
} else {
validSingleArgTypes.removeIf { it != singleArgType }
if (validSingleArgTypes.isEmpty()) {
return listOf()
}
}
}
if (mayHaveValidFullSignature) {
if (validFullSignature == null) {
validFullSignature = desc
} else {
if (desc != validFullSignature) {
validFullSignature = null
mayHaveValidFullSignature = false
}
}
}
}
// get the source method for parameter names
val (bytecodeClass, bytecodeMethod) = (insns[0].insn as MethodInsnNode).fakeResolve()
val sourceMethod = insns[0].target as? PsiMethod
val elementFactory = JavaPsiFacade.getElementFactory(annotation.project)
return validSingleArgTypes.flatMap { type ->
val paramList = sourceMethod?.parameterList
val psiParameter = paramList?.parameters?.firstOrNull { it.type.descriptor == type }
val psiType = psiParameter?.type ?: Type.getType(type).toPsiType(elementFactory, null)
val singleSignature = MethodSignature(
listOf(
ParameterGroup(
listOf(
sanitizedParameter(psiType, psiParameter?.name)
)
)
),
psiType
)
if (validFullSignature != null) {
val fullParamGroup = ParameterGroup(
Type.getArgumentTypes(validFullSignature).withIndex().map { (index, argType) ->
val psiParam = paramList?.let { bytecodeMethod.getParameter(bytecodeClass, index, it) }
sanitizedParameter(
psiParam?.type ?: argType.toPsiType(elementFactory),
psiParam?.name
)
}
)
listOf(
singleSignature,
MethodSignature(listOf(fullParamGroup), psiType)
)
} else {
listOf(singleSignature)
}
}
}
}
| mit | 2d0fa3ce2c6a8f07ad5b39d98fd035fc | 39.757813 | 111 | 0.578302 | 5.423077 | false | false | false | false |
PassionateWsj/YH-Android | app/src/main/java/com/intfocus/template/model/response/mine_page/FeedbackList.kt | 1 | 2811 | package com.intfocus.template.model.response.mine_page
import com.google.gson.annotations.SerializedName
import com.intfocus.template.model.response.BaseResult
/**
* @author liuruilin
* @data 2017/12/1
* @describe
*/
class FeedbackList: BaseResult() {
/**
* code : 200
* message : 获取数据列表成功
* current_page : 0
* page_size : 15
* total_page : 15
* data : [{"id":210,"title":"生意人问题反馈","content":"测试","images":["/images/feedback-210-48cb2c983ce84020baf0b8f7893642df.png"],"replies":[{"id":1,"content":"测试","images":["/images/feedback-reply-d0d653c4ba9e4f01bb4b76d9a1bb389f.png","/images/feedback-reply-65a01382393f4114ae99092370e1191e.png"],"created_at":"2017-11-17 17:30:30"}],"user_num":"13564379606","app_version":"0.0.2","platform":"ios","platform_version":"iphoneos","progress_state":0,"progress_content":null,"publicly":false,"created_at":"2017-08-15 10:55:49"}]
*/
var current_page: Int = 0
var page_size: Int = 0
var total_page: Int = 0
@SerializedName("data")
var data: List<FeedbackListItemData>? = null
class FeedbackListItemData {
/**
* id : 210
* title : 生意人问题反馈
* content : 测试
* images : ["/images/feedback-210-48cb2c983ce84020baf0b8f7893642df.png"]
* replies : [{"id":1,"content":"测试","images":["/images/feedback-reply-d0d653c4ba9e4f01bb4b76d9a1bb389f.png","/images/feedback-reply-65a01382393f4114ae99092370e1191e.png"],"created_at":"2017-11-17 17:30:30"}]
* user_num : 13564379606
* app_version : 0.0.2
* platform : ios
* platform_version : iphoneos
* progress_state : 0
* progress_content : null
* publicly : false
* created_at : 2017-08-15 10:55:49
*/
var id: Int = 0
var title: String? = null
var content: String? = null
var user_num: String? = null
var app_version: String? = null
var platform: String? = null
var platform_version: String? = null
var progress_state: Int = 0
var progress_content: Any? = null
var publicly: Boolean = false
var created_at: String? = null
var images: List<String>? = null
var replies: List<Replies>? = null
class Replies {
/**
* id : 1
* content : 测试
* images : ["/images/feedback-reply-d0d653c4ba9e4f01bb4b76d9a1bb389f.png","/images/feedback-reply-65a01382393f4114ae99092370e1191e.png"]
* created_at : 2017-11-17 17:30:30
*/
var id: Int = 0
var content: String? = null
var created_at: String? = null
var images: List<String>? = null
}
}
}
| gpl-3.0 | e12e07ec40aec87bc5d2b215e518b008 | 37.690141 | 525 | 0.599199 | 3.278043 | false | false | false | false |
fredyw/leetcode | src/main/kotlin/leetcode/Problem2279.kt | 1 | 864 | package leetcode
/**
* https://leetcode.com/problems/maximum-bags-with-full-capacity-of-rocks/
*/
class Problem2279 {
fun maximumBags(capacity: IntArray, rocks: IntArray, additionalRocks: Int): Int {
var answer = 0
data class Bag(val capacity: Int, val rock: Int)
val list = mutableListOf<Bag>()
for ((i, c) in capacity.withIndex()) {
if (c == rocks[i]) {
answer++
} else {
list += Bag(c, rocks[i])
}
}
var additional = additionalRocks
list.sortBy { it.capacity - it.rock }
for (i in 0 until list.size) {
val diff = list[i].capacity - list[i].rock
if (diff > additional) {
break
}
additional -= diff
answer++
}
return answer
}
}
| mit | 851dd52bfb8eb4b56d71d053aac88dad | 27.8 | 85 | 0.503472 | 4.094787 | false | false | false | false |
NanaGlutamate/Random | code/test/test.kt | 1 | 1599 | fun main(args: Array<String>) {
val t = Classify()
val k = Classify()
val a = Random()
var w = Array<Int>(100, {0})
for(i in 1..10000){
val (b, c) = a.getRandom()
t.classify(b)
k.classify(c)
w[(10 * b) + c]++
}
println("tens: " + t.toString())
println("single: " + k.toString())
w.forEachIndexed{ i, number -> print("$i:$number ")}
}
class Random {
@Volatile var now = 0
var temp = 0
fun add(){
temp = now
temp++
now = temp
}
fun getRandom(): Pair<Int, Int>{
for(i in 1..25){
thread (start = true){
for(j in 1..10000){
add()
}
}
}
while(Thread.activeCount() > 2)
Thread.yield()
var t = Math.floorMod(now,100)
val k = t / 10
t = Math.floorMod(t, 10)
return Pair(k, t)
}
}
class Classify{
var a = Array<Int>(10, {0})
var goTo = Array<Array<Int>>(10, {Array(10, {0})})
var earlier: Int? = null
fun classify(number: Int){
a[number]++
if(earlier != null)
goTo[earlier!!][number]++
earlier = number
}
override fun toString(): String {
var temp: String = ""
a.forEach { temp += it.toString() + " " }
temp += "\n\n"
goTo.forEachIndexed {
i, array ->
temp += "$i -> "
array.forEachIndexed{ j, number ->
temp += "$j,$number; "
}
temp += "\n"
}
return temp
}
}
| mit | c6be71cbc3f34b55ace080da3853d205 | 23.6 | 56 | 0.439024 | 3.650685 | false | false | false | false |
westnordost/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/max_weight/AddMaxWeightForm.kt | 1 | 6578 | package de.westnordost.streetcomplete.quests.max_weight
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.ArrayAdapter
import android.widget.EditText
import android.widget.Spinner
import androidx.appcompat.app.AlertDialog
import androidx.core.content.getSystemService
import androidx.core.view.isInvisible
import androidx.core.view.isVisible
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.ktx.allowOnlyNumbers
import de.westnordost.streetcomplete.ktx.numberOrNull
import de.westnordost.streetcomplete.quests.AbstractQuestFormAnswerFragment
import de.westnordost.streetcomplete.quests.OtherAnswer
import de.westnordost.streetcomplete.util.TextChangedWatcher
import de.westnordost.streetcomplete.view.image_select.ImageListPickerDialog
import kotlinx.android.synthetic.main.quest_maxweight.*
class AddMaxWeightForm : AbstractQuestFormAnswerFragment<MaxWeightAnswer>() {
override val contentLayoutResId = R.layout.quest_maxweight
override val otherAnswers = listOf(
OtherAnswer(R.string.quest_maxweight_answer_other_sign) { onUnsupportedSign() },
OtherAnswer(R.string.quest_generic_answer_noSign) { confirmNoSign() }
)
private var sign: MaxWeightSign? = null
private val maxWeightInput: EditText? get() = inputSignContainer.findViewById(R.id.maxWeightInput)
private val weightUnitSelect: Spinner? get() = inputSignContainer.findViewById(R.id.weightUnitSelect)
private val weightLimitUnits get() = countryInfo.weightLimitUnits.map { it.toWeightMeasurementUnit() }
override fun isFormComplete() = getWeightFromInput() != null
override fun isRejectingClose() = sign != null || getWeightFromInput() != null
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
selectSignButton.setOnClickListener { showSignSelectionDialog() }
if (savedInstanceState != null) {
onLoadInstanceState(savedInstanceState)
}
selectSignButton.isVisible = sign == null
if (sign == null) inputSignContainer.removeAllViews()
initMaxWeightInput()
}
private fun onLoadInstanceState(savedInstanceState: Bundle) {
sign = savedInstanceState.getString(MAX_WEIGHT_SIGN)?.let { MaxWeightSign.valueOf(it) }
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
sign?.let { outState.putString(MAX_WEIGHT_SIGN, it.name) }
}
private fun initMaxWeightInput() {
val maxWeightInput = maxWeightInput ?: return
maxWeightInput.addTextChangedListener(TextChangedWatcher { checkIsFormComplete() })
maxWeightInput.allowOnlyNumbers()
inputSignContainer.setOnClickListener { focusMaxWeightInput() }
val units = weightLimitUnits.map { it.toDisplayString() }
weightUnitSelect?.adapter = ArrayAdapter(requireContext(), R.layout.spinner_item_centered, units)
weightUnitSelect?.setSelection(0)
}
private fun focusMaxWeightInput() {
val maxWeightInput = maxWeightInput ?: return
maxWeightInput.requestFocus()
Handler(Looper.getMainLooper()).post {
val imm = activity?.getSystemService<InputMethodManager>()
imm?.showSoftInput(maxWeightInput, InputMethodManager.SHOW_IMPLICIT)
}
}
private fun showSignSelectionDialog() {
val ctx = context ?: return
val items = MaxWeightSign.values().map { it.asItem(layoutInflater) }
ImageListPickerDialog(ctx, items, R.layout.cell_labeled_icon_select, 2) { selected ->
selected.value?.let { setMaxWeightSign(it) }
checkIsFormComplete()
}.show()
}
private fun setMaxWeightSign(sign: MaxWeightSign) {
this.sign = sign
selectSignButton.isInvisible = true
inputSignContainer.removeAllViews()
layoutInflater.inflate(sign.layoutResourceId, inputSignContainer)
initMaxWeightInput()
focusMaxWeightInput()
inputSignContainer.scaleX = 3f
inputSignContainer.scaleY = 3f
inputSignContainer.animate().scaleX(1f).scaleY(1f)
}
override fun onClickOk() {
if (userSelectedUnrealisticWeight()) {
confirmUnusualInput { applyMaxWeightFormAnswer() }
} else {
applyMaxWeightFormAnswer()
}
}
private fun userSelectedUnrealisticWeight(): Boolean {
val weight = getWeightFromInput() ?: return false
val w = weight.toMetricTons()
return w > 25 || w < 2
}
private fun applyMaxWeightFormAnswer() {
applyAnswer(MaxWeight(sign!!, getWeightFromInput()!!))
}
private fun getWeightFromInput(): Weight? {
val input = maxWeightInput?.numberOrNull ?: return null
val unit = weightLimitUnits[weightUnitSelect?.selectedItemPosition ?: 0]
return when(unit) {
WeightMeasurementUnit.SHORT_TON -> ShortTons(input)
WeightMeasurementUnit.POUND -> ImperialPounds(input.toInt())
WeightMeasurementUnit.TON -> MetricTons(input)
}
}
private fun onUnsupportedSign() {
activity?.let { AlertDialog.Builder(it)
.setMessage(R.string.quest_maxweight_unsupported_sign_request_photo)
.setPositiveButton(android.R.string.ok) { _, _ -> composeNote() }
.setNegativeButton(R.string.quest_leave_new_note_no) { _, _ -> skipQuest() }
.show()
}
}
private fun confirmNoSign() {
activity?.let { AlertDialog.Builder(it)
.setTitle(R.string.quest_generic_confirmation_title)
.setPositiveButton(R.string.quest_generic_confirmation_yes) { _, _ -> applyAnswer(NoMaxWeightSign) }
.setNegativeButton(R.string.quest_generic_confirmation_no, null)
.show()
}
}
private fun confirmUnusualInput(callback: () -> (Unit)) {
activity?.let { AlertDialog.Builder(it)
.setTitle(R.string.quest_generic_confirmation_title)
.setMessage(R.string.quest_maxweight_unusualInput_confirmation_description)
.setPositiveButton(R.string.quest_generic_confirmation_yes) { _, _ -> callback() }
.setNegativeButton(R.string.quest_generic_confirmation_no, null)
.show()
}
}
companion object {
private const val MAX_WEIGHT_SIGN = "max_weight_sign"
}
}
| gpl-3.0 | abfde3f1f8e460d12f50216216b5df1d | 37.244186 | 112 | 0.695196 | 4.606443 | false | false | false | false |
grueni75/GeoDiscoverer | Source/Platform/Target/Android/mobile/src/main/java/com/untouchableapps/android/geodiscoverer/ui/component/GDTextField.kt | 1 | 3677 | //============================================================================
// Name : GDTextField.kt
// Author : Matthias Gruenewald
// Copyright : Copyright 2010-2021 Matthias Gruenewald
//
// This file is part of GeoDiscoverer.
//
// GeoDiscoverer is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// GeoDiscoverer is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with GeoDiscoverer. If not, see <http://www.gnu.org/licenses/>.
//
//============================================================================
package com.untouchableapps.android.geodiscoverer.ui.component
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.shape.ZeroCornerSize
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.LocalTextStyle
import androidx.compose.material.TextField
import androidx.compose.material.TextFieldColors
import androidx.compose.material.TextFieldDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.input.VisualTransformation
import com.untouchableapps.android.geodiscoverer.GDApplication
import com.untouchableapps.android.geodiscoverer.ui.theme.Material2Theme
// Missing component in material3
// Replace later when eventually available
@Composable
fun GDTextField(
value: String,
onValueChange: (String) -> Unit,
modifier: Modifier = Modifier,
enabled: Boolean = true,
readOnly: Boolean = false,
textStyle: TextStyle = LocalTextStyle.current,
label: @Composable (() -> Unit)? = null,
placeholder: @Composable (() -> Unit)? = null,
leadingIcon: @Composable (() -> Unit)? = null,
trailingIcon: @Composable (() -> Unit)? = null,
isError: Boolean = false,
visualTransformation: VisualTransformation = VisualTransformation.None,
keyboardOptions: KeyboardOptions = KeyboardOptions.Default,
keyboardActions: KeyboardActions = KeyboardActions(),
singleLine: Boolean = false,
maxLines: Int = Int.MAX_VALUE,
interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },
shape: Shape =
androidx.compose.material.MaterialTheme.shapes.small.copy(bottomEnd = ZeroCornerSize, bottomStart = ZeroCornerSize)
) {
Material2Theme {
var colors = TextFieldDefaults.textFieldColors(
textColor = MaterialTheme.colorScheme.onBackground
)
TextField(
value = value,
onValueChange = onValueChange,
modifier = modifier,
enabled = enabled,
readOnly = readOnly,
textStyle = textStyle,
label = label,
placeholder = placeholder,
leadingIcon = leadingIcon,
trailingIcon=trailingIcon,
isError = isError,
visualTransformation = visualTransformation,
keyboardOptions = keyboardOptions,
keyboardActions = keyboardActions,
singleLine = singleLine,
maxLines = maxLines,
interactionSource = interactionSource,
shape = shape,
colors = colors
)
}
}
| gpl-3.0 | 8a0b7e65ddcf16b6b447ce23b86654f6 | 38.537634 | 119 | 0.727223 | 4.702046 | false | false | false | false |
buxapp/gradle-foss-dependencies | src/main/kotlin/com/getbux/android/gradle/FossDependenciesPlugin.kt | 1 | 1891 | package com.getbux.android.gradle
import com.getbux.android.gradle.render.HtmlRenderer
import com.getbux.android.gradle.task.GenerateFossDependenciesTask
import com.github.jk1.license.LicenseReportPlugin
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.plugins.ExtensionAware
@Suppress("unused")
class FossDependenciesPlugin : Plugin<Project> {
lateinit var extension: FossDependenciesExtension
lateinit var extensionDependencies: FossDependenciesExtension.DependenciesExtension
override fun apply(project: Project) {
extension = project.extensions.create("fossDependencies", FossDependenciesExtension::class.java)
extensionDependencies = (extension as ExtensionAware).extensions.create("dependencies", FossDependenciesExtension.DependenciesExtension::class.java)
setupReportPlugin(project)
val reportTask = project.getTasksByName("generateLicenseReport", false).first()
reportTask.setOnlyIf { true }
reportTask.outputs.upToDateWhen { false }
project.task(mapOf("type" to GenerateFossDependenciesTask::class.java), "generateFossDependencies").apply {
dependsOn(reportTask)
}
}
private fun setupReportPlugin(project: Project) {
project.apply(mapOf("plugin" to LicenseReportPlugin::class.java))
val htmlRenderer = HtmlRenderer()
val reportExtension = project.extensions.getByType(LicenseReportPlugin.LicenseReportExtension::class.java).apply {
renderer = htmlRenderer
}
project.afterEvaluate {
htmlRenderer.title = extension.htmlTitle
htmlRenderer.fileDir = reportExtension.outputDir
htmlRenderer.ignoredDependenciesRegExes = extensionDependencies.ignoredDependencies
htmlRenderer.manualLicenses = extensionDependencies.manualLicenses
}
}
}
| apache-2.0 | 69487758b6d736e191ce4ce69ea6a803 | 38.395833 | 156 | 0.748281 | 4.751256 | false | false | false | false |
spkingr/50-android-kotlin-projects-in-100-days | ProjectBasicMVP/app/src/main/java/me/liuqingwen/android/projectbasicmvp/ui/ViewBindings.kt | 1 | 8182 | package me.liuqingwen.kotlinandroidviewbindings
/**
* Created by Qingwen on 2018-2-12, project: ProjectBasicMVP.
*
* @Author: Qingwen
* @DateTime: 2018-2-12
* @Package: me.liuqingwen.android.projectbasicmvp.ui in project: ProjectBasicMVP
*
* Notice: If you are using this class or file, check it and do some modification.
*
* This is the code from the [KotlinAndroidViewBindings](https://github.com/MarcinMoskala/KotlinAndroidViewBindings)
*/
import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.support.annotation.IdRes
import android.view.View
import android.widget.EditText
import kotlin.properties.ReadOnlyProperty
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
/**
* Bind the click action to the button or other views
*/
fun Activity.bindToClickEvent(@IdRes viewId: Int): ReadWriteProperty<Any?, () -> Unit> = ClickEventActionBinding(
lazy { this.findViewById<View>(viewId) })
/*fun Fragment.bindToClickEvent(@IdRes viewId: Int): ReadWriteProperty<Any?, () -> Unit> = ClickEventActionBinding(
lazy { this.view!!.findViewById<View>(viewId) })*/
private class ClickEventActionBinding(viewProvider: Lazy<View>): ReadWriteProperty<Any?, () -> Unit>
{
companion object
{
private val EMPTY_ACTION = {}
}
private val view by viewProvider
private var action:(() -> Unit)? = null
override fun getValue(thisRef: Any?, property: KProperty<*>) = this.action ?: ClickEventActionBinding.EMPTY_ACTION
override fun setValue(thisRef: Any?, property: KProperty<*>, value: () -> Unit)
{
if (this.action == null)
{
this.view.setOnClickListener {
this.action?.invoke()
}
}
this.action = value
}
}
/**
* bindToEditorActions
*/
fun Activity.bindToEditorActions(@IdRes editTextId: Int, predicate: (Int?, Int?) -> Boolean):ReadWriteProperty<Any?, () -> Unit> = EditorActionBinding(
lazy { this.findViewById<EditText>(editTextId) }, predicate)
private class EditorActionBinding(editTextViewProvider: Lazy<EditText>, private val predicate: (Int?, Int?) -> Boolean): ReadWriteProperty<Any?, () -> Unit>
{
companion object
{
private val EMPTY_ACTION = {}
}
private val editText by editTextViewProvider
private var action:(() -> Unit)? = null
override fun getValue(thisRef: Any?, property: KProperty<*>): () -> Unit = this.action ?: EditorActionBinding.EMPTY_ACTION
override fun setValue(thisRef: Any?, property: KProperty<*>, value: () -> Unit)
{
if (this.action == null)
{
this.editText.setOnEditorActionListener { _, actionId, event ->
val handleAction = this.predicate(actionId, event.keyCode)
if (handleAction)
{
this.action?.invoke()
}
handleAction
}
}
this.action = value
}
}
/**
* Bind the error of the EditText view
*/
fun Activity.bindToErrorId(@IdRes editTextId: Int, context: Context): ReadWriteProperty<Any?, Int?> = EditTextViewErrorBinding(
lazy { this.findViewById<EditText>(editTextId) }, context)
private class EditTextViewErrorBinding(editTextViewProvider: Lazy<EditText>, private val context: Context): ReadWriteProperty<Any?, Int?>
{
private val editText by editTextViewProvider
private var currentErrorId:Int? = null
override fun getValue(thisRef: Any?, property: KProperty<*>) = this.currentErrorId
override fun setValue(thisRef: Any?, property: KProperty<*>, value: Int?)
{
this.currentErrorId = value
this.editText.error = value?.let { this.context.getString(it) }
}
}
/**
* Bind the view's focus action
*/
fun Activity.bindToRequestFocus(@IdRes viewId: Int): ReadOnlyProperty<Any?, ()->Unit> = RequestFocusBinding(
lazy { this.findViewById<View>(viewId) })
private class RequestFocusBinding(viewProvider: Lazy<View>): ReadOnlyProperty<Any?, ()->Unit>
{
private val view by viewProvider
private val requestFocus by lazy { { this.view.requestFocus(); Unit } }
override fun getValue(thisRef: Any?, property: KProperty<*>) = this.requestFocus
}
/**
* Bind the text to the EditText view
*/
fun Activity.bindToEditText(@IdRes editTextId: Int): ReadWriteProperty<Any?, String> = EditTextViewBinding(
lazy { this.findViewById<EditText>(editTextId) })
private class EditTextViewBinding(editTextViewProvider: Lazy<EditText>): ReadWriteProperty<Any?, String>
{
private val editText by editTextViewProvider
override fun getValue(thisRef: Any?, property: KProperty<*>) = this.editText.text.toString()
override fun setValue(thisRef: Any?, property: KProperty<*>, value: String) = this.editText.setText(value)
}
/**
* Bind the visibility of two views
*/
fun Activity.bindToLoadings(@IdRes progressViewId: Int, @IdRes hiddenViewId: Int):ReadWriteProperty<Any?, Boolean> = ProgressViewLoadingBinding(
lazy { this.findViewById<View>(progressViewId) }, lazy { this.findViewById<View>(hiddenViewId) })
private class ProgressViewLoadingBinding(progressViewProvider: Lazy<View>, hiddenViewProvider: Lazy<View>): ReadWriteProperty<Any?, Boolean>
{
private val progressView by progressViewProvider
private val hiddenView by hiddenViewProvider
override fun getValue(thisRef: Any?, property: KProperty<*>) = this.progressView.visibility == View.VISIBLE
override fun setValue(thisRef: Any?, property: KProperty<*>, value: Boolean)
{
this.progressView.visibility = if (value) View.VISIBLE else View.INVISIBLE
this.hiddenView.visibility = if (value) View.INVISIBLE else View.VISIBLE
}
}
/**
* Just bind the visibility of the view(ProgressBar)
*/
fun Activity.bindToViewVisibility(@IdRes id:Int, isGone: Boolean = false):ReadWriteProperty<Any?, Boolean> = ViewVisibilityBinding(lazy { this.findViewById<View>(id) }, isGone)
private class ViewVisibilityBinding(viewProvider: Lazy<View>, private val isGone: Boolean = false): ReadWriteProperty<Any?, Boolean>
{
private val view by viewProvider
override fun getValue(thisRef: Any?, property: KProperty<*>) = this.view.visibility == View.VISIBLE
override fun setValue(thisRef: Any?, property: KProperty<*>, value: Boolean)
{
this.view.visibility = if (value) View.VISIBLE else if(this.isGone) View.GONE else View.INVISIBLE
}
}
/**
* Bind the [Dialog] to the loading view
* **This function may lead to memory leaks...**
*/
fun bindToLoadingDialog(progressViewProvider: () -> Dialog): ReadWriteProperty<Any?, Boolean> = ProgressLoadingBinding(lazy(progressViewProvider))
private class ProgressLoadingBinding(progressViewProvider: Lazy<Dialog>) : ReadWriteProperty<Any?, Boolean>
{
private val progressView by progressViewProvider
private var isProgressVisible = false
private var isCancelListenerSet = false
override fun getValue(thisRef: Any?, property: KProperty<*>) = this.isProgressVisible
override fun setValue(thisRef: Any?, property: KProperty<*>, value: Boolean)
{
if (value != this.isProgressVisible)
{
this.isProgressVisible = value
if (value) this.progressView.show() else this.progressView.hide()
if (value && !this.isCancelListenerSet)
{
this.isCancelListenerSet = true
this.progressView.setOnCancelListener { this.isProgressVisible = false }
}
}
}
}
/**
* Bind the view state(enabled/disabled) to the boolean property
*/
fun Activity.bindToState(@IdRes viewId: Int): ReadWriteProperty<Any?, Boolean> = StateBinding(lazy { this.findViewById<View>(viewId) })
private class StateBinding(viewProvider: Lazy<View>):ReadWriteProperty<Any?, Boolean>
{
private val view by viewProvider
override fun getValue(thisRef: Any?, property: KProperty<*>) = view.isEnabled
override fun setValue(thisRef: Any?, property: KProperty<*>, value: Boolean)
{
if (view.isEnabled != value)
{
view.isEnabled = value
}
}
}
| mit | 4490ff84b44c48fdf945d0f54179d900 | 37.59434 | 176 | 0.69384 | 4.439501 | false | false | false | false |
NerdNumber9/TachiyomiEH | app/src/main/java/exh/util/NakedTrie.kt | 1 | 11047 | package exh.util
import android.util.SparseArray
import java.util.*
class NakedTrieNode<T>(val key: Int, var parent: NakedTrieNode<T>?) {
val children = SparseArray<NakedTrieNode<T>>(1)
var hasData: Boolean = false
var data: T? = null
// Walks in ascending order
// Consumer should return true to continue walking, false to stop walking
inline fun walk(prefix: String, consumer: (String, T) -> Boolean, leavesOnly: Boolean) {
// Special case root
if(hasData && (!leavesOnly || children.size() <= 0)) {
if(!consumer(prefix, data as T)) return
}
val stack = LinkedList<Pair<String, NakedTrieNode<T>>>()
SparseArrayValueCollection(children, true).forEach {
stack += prefix + it.key.toChar() to it
}
while(!stack.isEmpty()) {
val (key, bottom) = stack.removeLast()
SparseArrayValueCollection(bottom.children, true).forEach {
stack += key + it.key.toChar() to it
}
if(bottom.hasData && (!leavesOnly || bottom.children.size() <= 0)) {
if(!consumer(key, bottom.data as T)) return
}
}
}
fun getAsNode(key: String): NakedTrieNode<T>? {
var current = this
for(c in key) {
current = current.children.get(c.toInt()) ?: return null
if(!current.hasData) return null
}
return current
}
}
/**
* Fast, memory efficient and flexible trie implementation with implementation details exposed
*/
class NakedTrie<T> : MutableMap<String, T> {
/**
* Returns the number of key/value pairs in the map.
*/
override var size: Int = 0
private set
/**
* Returns `true` if the map is empty (contains no elements), `false` otherwise.
*/
override fun isEmpty() = size <= 0
/**
* Removes all elements from this map.
*/
override fun clear() {
root.children.clear()
root.hasData = false
root.data = null
size = 0
}
val root = NakedTrieNode<T>(-1, null)
private var version: Long = 0
override fun put(key: String, value: T): T? {
// Traverse to node location in tree, making parent nodes if required
var current = root
for(c in key) {
val castedC = c.toInt()
var node = current.children.get(castedC)
if(node == null) {
node = NakedTrieNode(castedC, current)
current.children.put(castedC, node)
}
current = node
}
// Add data to node or replace existing data
val previous = if(current.hasData) {
current.data
} else {
current.hasData = true
size++
null
}
current.data = value
version++
return previous
}
override fun get(key: String): T? {
val current = getAsNode(key) ?: return null
return if(current.hasData) current.data else null
}
fun getAsNode(key: String): NakedTrieNode<T>? {
return root.getAsNode(key)
}
override fun containsKey(key: String): Boolean {
var current = root
for(c in key) {
current = current.children.get(c.toInt()) ?: return false
if(!current.hasData) return false
}
return current.hasData
}
/**
* Removes the specified key and its corresponding value from this map.
*
* @return the previous value associated with the key, or `null` if the key was not present in the map.
*/
override fun remove(key: String): T? {
// Traverse node tree while keeping track of the nodes we have visited
val nodeStack = LinkedList<NakedTrieNode<T>>()
for(c in key) {
val bottomOfStack = nodeStack.last
val current = bottomOfStack.children.get(c.toInt()) ?: return null
if(!current.hasData) return null
nodeStack.add(bottomOfStack)
}
// Mark node as having no data
val bottomOfStack = nodeStack.last
bottomOfStack.hasData = false
val oldData = bottomOfStack.data
bottomOfStack.data = null // Clear data field for GC
// Remove nodes that we visited that are useless
for(curBottom in nodeStack.descendingIterator()) {
val parent = curBottom.parent ?: break
if(!curBottom.hasData && curBottom.children.size() <= 0) {
// No data or child nodes, this node is useless, discard
parent.children.remove(curBottom.key)
} else break
}
version++
size--
return oldData
}
/**
* Updates this map with key/value pairs from the specified map [from].
*/
override fun putAll(from: Map<out String, T>) {
// No way to optimize this so yeah...
from.forEach { (s, u) ->
put(s, u)
}
}
// Walks in ascending order
// Consumer should return true to continue walking, false to stop walking
inline fun walk(consumer: (String, T) -> Boolean) {
walk(consumer, false)
}
// Walks in ascending order
// Consumer should return true to continue walking, false to stop walking
inline fun walk(consumer: (String, T) -> Boolean, leavesOnly: Boolean) {
root.walk("", consumer, leavesOnly)
}
fun getOrPut(key: String, producer: () -> T): T {
// Traverse to node location in tree, making parent nodes if required
var current = root
for(c in key) {
val castedC = c.toInt()
var node = current.children.get(castedC)
if(node == null) {
node = NakedTrieNode(castedC, current)
current.children.put(castedC, node)
}
current = node
}
// Add data to node or replace existing data
if(!current.hasData) {
current.hasData = true
current.data = producer()
size++
version++
}
return current.data as T
}
// Includes root
fun subMap(prefix: String, leavesOnly: Boolean = false): Map<String, T> {
val node = getAsNode(prefix) ?: return emptyMap()
return object : Map<String, T> {
/**
* Returns a read-only [Set] of all key/value pairs in this map.
*/
override val entries: Set<Map.Entry<String, T>>
get() {
val out = mutableSetOf<Map.Entry<String, T>>()
node.walk("", { k, v ->
out.add(AbstractMap.SimpleImmutableEntry(k, v))
true
}, leavesOnly)
return out
}
/**
* Returns a read-only [Set] of all keys in this map.
*/
override val keys: Set<String>
get() {
val out = mutableSetOf<String>()
node.walk("", { k, _ ->
out.add(k)
true
}, leavesOnly)
return out
}
/**
* Returns the number of key/value pairs in the map.
*/
override val size: Int get() {
var s = 0
node.walk("", { _, _ -> s++; true }, leavesOnly)
return s
}
/**
* Returns a read-only [Collection] of all values in this map. Note that this collection may contain duplicate values.
*/
override val values: Collection<T>
get() {
val out = mutableSetOf<T>()
node.walk("", { _, v ->
out.add(v)
true
}, leavesOnly)
return out
}
/**
* Returns `true` if the map contains the specified [key].
*/
override fun containsKey(key: String): Boolean {
if(!key.startsWith(prefix)) return false
val childNode = node.getAsNode(key.removePrefix(prefix)) ?: return false
return childNode.hasData && (!leavesOnly || childNode.children.size() <= 0)
}
/**
* Returns `true` if the map maps one or more keys to the specified [value].
*/
override fun containsValue(value: T): Boolean {
node.walk("", { _, v ->
if(v == value) return true
true
}, leavesOnly)
return false
}
/**
* Returns the value corresponding to the given [key], or `null` if such a key is not present in the map.
*/
override fun get(key: String): T? {
if(!key.startsWith(prefix)) return null
val childNode = node.getAsNode(key.removePrefix(prefix)) ?: return null
if(!childNode.hasData || (leavesOnly && childNode.children.size() > 0)) return null
return childNode.data
}
/**
* Returns `true` if the map is empty (contains no elements), `false` otherwise.
*/
override fun isEmpty(): Boolean {
if(node.children.size() <= 0 && !root.hasData) return true
if(!leavesOnly) return false
node.walk("", { _, _ -> return false }, leavesOnly)
return true
}
}
}
// Slow methods below
/**
* Returns `true` if the map maps one or more keys to the specified [value].
*/
override fun containsValue(value: T): Boolean {
walk { _, t ->
if(t == value) {
return true
}
true
}
return false
}
/**
* Returns a [MutableSet] of all key/value pairs in this map.
*/
override val entries: MutableSet<MutableMap.MutableEntry<String, T>>
get() = FakeMutableSet.fromSet(mutableSetOf<MutableMap.MutableEntry<String, T>>().apply {
walk { k, v ->
this += FakeMutableEntry.fromPair(k, v)
true
}
})
/**
* Returns a [MutableSet] of all keys in this map.
*/
override val keys: MutableSet<String>
get() = FakeMutableSet.fromSet(mutableSetOf<String>().apply {
walk { k, _ ->
this += k
true
}
})
/**
* Returns a [MutableCollection] of all values in this map. Note that this collection may contain duplicate values.
*/
override val values: MutableCollection<T>
get() = FakeMutableCollection.fromCollection(mutableListOf<T>().apply {
walk { _, v ->
this += v
true
}
})
} | apache-2.0 | 467964375de97b9d1e7ec960d1264e78 | 31.023188 | 130 | 0.517154 | 4.665118 | false | false | false | false |
Heiner1/AndroidAPS | app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NsClientReceiverDelegate.kt | 1 | 3438 | package info.nightscout.androidaps.plugins.general.nsclient
import info.nightscout.androidaps.R
import info.nightscout.androidaps.events.EventChargingState
import info.nightscout.androidaps.events.EventNetworkChange
import info.nightscout.androidaps.events.EventPreferenceChange
import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.receivers.ReceiverStatusStore
import info.nightscout.androidaps.interfaces.ResourceHelper
import info.nightscout.shared.sharedPreferences.SP
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class NsClientReceiverDelegate @Inject constructor(
private val rxBus: RxBus,
private val rh: ResourceHelper,
private val sp: SP,
private val receiverStatusStore: ReceiverStatusStore
) {
private var allowedChargingState = true
private var allowedNetworkState = true
var allowed = true
var blockingReason = ""
fun grabReceiversState() {
receiverStatusStore.updateNetworkStatus()
}
fun onStatusEvent(ev: EventPreferenceChange) {
when {
ev.isChanged(rh, R.string.key_ns_wifi) ||
ev.isChanged(rh, R.string.key_ns_cellular) ||
ev.isChanged(rh, R.string.key_ns_wifi_ssids) ||
ev.isChanged(rh, R.string.key_ns_allow_roaming) -> {
receiverStatusStore.updateNetworkStatus()
receiverStatusStore.lastNetworkEvent?.let { onStatusEvent(it) }
}
ev.isChanged(rh, R.string.key_ns_charging) ||
ev.isChanged(rh, R.string.key_ns_battery) -> {
receiverStatusStore.broadcastChargingState()
}
}
}
fun onStatusEvent(ev: EventChargingState) {
val newChargingState = calculateStatus(ev)
if (newChargingState != allowedChargingState) {
allowedChargingState = newChargingState
blockingReason = rh.gs(R.string.blocked_by_charging)
processStateChange()
}
}
fun onStatusEvent(ev: EventNetworkChange) {
val newNetworkState = calculateStatus(ev)
if (newNetworkState != allowedNetworkState) {
allowedNetworkState = newNetworkState
blockingReason = rh.gs(R.string.blocked_by_connectivity)
processStateChange()
}
}
private fun processStateChange() {
val newAllowedState = allowedChargingState && allowedNetworkState
if (newAllowedState != allowed) {
allowed = newAllowedState
rxBus.send(EventPreferenceChange(rh.gs(R.string.key_nsclientinternal_paused)))
}
}
fun calculateStatus(ev: EventChargingState): Boolean =
!ev.isCharging && sp.getBoolean(R.string.key_ns_battery, true) ||
ev.isCharging && sp.getBoolean(R.string.key_ns_charging, true)
fun calculateStatus(ev: EventNetworkChange): Boolean =
ev.mobileConnected && sp.getBoolean(R.string.key_ns_cellular, true) && !ev.roaming ||
ev.mobileConnected && sp.getBoolean(R.string.key_ns_cellular, true) && ev.roaming && sp.getBoolean(R.string.key_ns_allow_roaming, true) ||
ev.wifiConnected && sp.getBoolean(R.string.key_ns_wifi, true) && sp.getString(R.string.key_ns_wifi_ssids, "").isEmpty() ||
ev.wifiConnected && sp.getBoolean(R.string.key_ns_wifi, true) && sp.getString(R.string.key_ns_wifi_ssids, "").split(";").contains(ev.ssid)
} | agpl-3.0 | 72fc165998ea6bf1d8130dd9bcd520d0 | 40.433735 | 150 | 0.678883 | 4.167273 | false | false | false | false |
Heiner1/AndroidAPS | database/src/main/java/info/nightscout/androidaps/database/entities/TemporaryBasal.kt | 1 | 2621 | package info.nightscout.androidaps.database.entities
import androidx.room.Embedded
import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.Index
import androidx.room.PrimaryKey
import info.nightscout.androidaps.database.TABLE_TEMPORARY_BASALS
import info.nightscout.androidaps.database.embedments.InterfaceIDs
import info.nightscout.androidaps.database.interfaces.DBEntryWithTimeAndDuration
import info.nightscout.androidaps.database.interfaces.TraceableDBEntry
import java.util.*
@Entity(tableName = TABLE_TEMPORARY_BASALS,
foreignKeys = [ForeignKey(
entity = TemporaryBasal::class,
parentColumns = ["id"],
childColumns = ["referenceId"])],
indices = [
Index("id"),
Index("isValid"),
Index("nightscoutId"),
Index("pumpType"),
Index("endId"),
Index("pumpSerial"),
Index("temporaryId"),
Index("referenceId"),
Index("timestamp")
])
data class TemporaryBasal(
@PrimaryKey(autoGenerate = true)
override var id: Long = 0,
override var version: Int = 0,
override var dateCreated: Long = -1,
override var isValid: Boolean = true,
override var referenceId: Long? = null,
@Embedded
override var interfaceIDs_backing: InterfaceIDs? = InterfaceIDs(),
override var timestamp: Long,
override var utcOffset: Long = TimeZone.getDefault().getOffset(timestamp).toLong(),
var type: Type,
var isAbsolute: Boolean,
var rate: Double,
override var duration: Long
) : TraceableDBEntry, DBEntryWithTimeAndDuration {
init {
require(duration > 0)
}
private fun contentEqualsTo(other: TemporaryBasal): Boolean =
isValid == other.isValid &&
timestamp == other.timestamp &&
utcOffset == other.utcOffset &&
isAbsolute == other.isAbsolute &&
type == other.type &&
duration == other.duration &&
rate == other.rate
fun onlyNsIdAdded(previous: TemporaryBasal): Boolean =
previous.id != id &&
contentEqualsTo(previous) &&
previous.interfaceIDs.nightscoutId == null &&
interfaceIDs.nightscoutId != null
enum class Type {
NORMAL,
EMULATED_PUMP_SUSPEND,
PUMP_SUSPEND,
SUPERBOLUS,
FAKE_EXTENDED // in memory only
;
companion object {
fun fromString(name: String?) = values().firstOrNull { it.name == name } ?: NORMAL
}
}
val isInProgress: Boolean
get() = System.currentTimeMillis() in timestamp..timestamp + duration
} | agpl-3.0 | 487d7db3f948e54e1c0fb87fd2127ef2 | 30.97561 | 94 | 0.652423 | 4.818015 | false | false | false | false |
hurricup/intellij-community | plugins/settings-repository/src/settings/IcsSettings.kt | 1 | 3379 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.settingsRepository
import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.core.util.DefaultPrettyPrinter
import com.fasterxml.jackson.databind.ObjectMapper
import com.intellij.openapi.util.io.FileUtil
import com.intellij.util.*
import java.nio.file.Path
private val DEFAULT_COMMIT_DELAY = 10 * Time.MINUTE
class MyPrettyPrinter : DefaultPrettyPrinter() {
init {
_arrayIndenter = DefaultPrettyPrinter.NopIndenter.instance
}
override fun createInstance() = MyPrettyPrinter()
override fun writeObjectFieldValueSeparator(jg: JsonGenerator) {
jg.writeRaw(": ")
}
override fun writeEndObject(jg: JsonGenerator, nrOfEntries: Int) {
if (!_objectIndenter.isInline) {
--_nesting
}
if (nrOfEntries > 0) {
_objectIndenter.writeIndentation(jg, _nesting)
}
jg.writeRaw('}')
}
override fun writeEndArray(jg: JsonGenerator, nrOfValues: Int) {
if (!_arrayIndenter.isInline) {
--_nesting
}
jg.writeRaw(']')
}
}
fun saveSettings(settings: IcsSettings, settingsFile: Path) {
val serialized = ObjectMapper().writer(MyPrettyPrinter()).writeValueAsBytes(settings)
if (serialized.size <= 2) {
settingsFile.delete()
}
else {
settingsFile.write(serialized)
}
}
fun loadSettings(settingsFile: Path): IcsSettings {
if (!settingsFile.exists()) {
return IcsSettings()
}
val settings = ObjectMapper().readValue(settingsFile.toFile(), IcsSettings::class.java)
if (settings.commitDelay <= 0) {
settings.commitDelay = DEFAULT_COMMIT_DELAY
}
return settings
}
@JsonInclude(value = JsonInclude.Include.NON_DEFAULT)
@JsonIgnoreProperties(ignoreUnknown = true)
class IcsSettings {
var shareProjectWorkspace = false
var commitDelay = DEFAULT_COMMIT_DELAY
var doNoAskMapProject = false
var readOnlySources: List<ReadonlySource> = SmartList()
var autoSync = true
}
@JsonInclude(value = JsonInclude.Include.NON_DEFAULT)
@JsonIgnoreProperties(ignoreUnknown = true)
class ReadonlySource(var url: String? = null, var active: Boolean = true) {
val path: String?
@JsonIgnore
get() {
if (url == null) {
return null
}
else {
var fileName = PathUtilRt.getFileName(url!!)
val suffix = ".git"
if (fileName.endsWith(suffix)) {
fileName = fileName.substring(0, fileName.length - suffix.length)
}
// the convention is that the .git extension should be used for bare repositories
return "${FileUtil.sanitizeFileName(fileName, false)}.${Integer.toHexString(url!!.hashCode())}.git"
}
}
} | apache-2.0 | 873cd1f0cf84c4e1a5163fc431632c4f | 29.45045 | 107 | 0.719148 | 4.234336 | false | false | false | false |
marklogic/java-client-api | ml-development-tools/src/test/kotlin/com/marklogic/client/test/dbfunction/fntestgen.kt | 1 | 96697 | /*
* Copyright (c) 2020 MarkLogic Corporation
*
* 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.marklogic.client.test.dbfunction
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.node.ArrayNode
import com.fasterxml.jackson.databind.node.ObjectNode
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import com.marklogic.client.DatabaseClientFactory
import com.marklogic.client.document.TextDocumentManager
import com.marklogic.client.io.DocumentMetadataHandle
import com.marklogic.client.io.FileHandle
import com.marklogic.client.io.StringHandle
import com.marklogic.client.tools.proxy.Generator
import java.io.File
import java.lang.Exception
import java.lang.IllegalStateException
import kotlin.system.exitProcess
const val TEST_PACKAGE = "com.marklogic.client.test.dbfunction.generated"
val generator = Generator()
val atomicMap = generator.getAtomicDataTypes()
val documentMap = generator.getDocumentDataTypes().filterNot{entry -> (entry.key == "anyDocument")}
val mapper = jacksonObjectMapper()
val serializer = mapper.writerWithDefaultPrettyPrinter()
enum class TestVariant {
VALUE, NULL, EMPTY
}
fun getAtomicMappingImports(): String {
return """
import javax.xml.bind.DatatypeConverter;
import javax.xml.datatype.DatatypeFactory;
import java.time.format.DateTimeFormatter;
import java.util.regex.Pattern;
import javax.xml.datatype.DatatypeConfigurationException;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.time.OffsetTime;
"""
}
fun getAtomicMappingMembers(): String {
return """
DatatypeFactory datatypeFactory = null;
{
try {
datatypeFactory = DatatypeFactory.newInstance();
} catch (DatatypeConfigurationException e) {
throw new RuntimeException(e);
}
}
private BigDecimal asBigDecimal(String value) {
return DatatypeConverter.parseDecimal(value);
}
private Date asDate(String value) {
return DatatypeConverter.parseTime(value).getTime();
}
private Duration asDuration(String value) {
return Duration.parse(value);
}
private LocalDate asLocalDate(String value) {
return DateTimeFormatter.ISO_LOCAL_DATE.parse(value, LocalDate::from);
}
private LocalDateTime asLocalDateTime(String value) {
return DateTimeFormatter.ISO_LOCAL_DATE_TIME.parse(value, LocalDateTime::from);
}
private LocalTime asLocalTime(String value) {
return DateTimeFormatter.ISO_LOCAL_TIME.parse(value, LocalTime::from);
}
private OffsetDateTime asOffsetDateTime(String value) {
return DateTimeFormatter.ISO_OFFSET_DATE_TIME.parse(value, OffsetDateTime::from);
}
private OffsetTime asOffsetTime(String value) {
return DateTimeFormatter.ISO_OFFSET_TIME.parse(value, OffsetTime::from);
}
private String asString(Object value) {
return value.toString();
}
private String asString(BigDecimal value) {
return DatatypeConverter.printDecimal(value);
}
private String asString(Date value) {
Calendar cal = Calendar.getInstance();
cal.setTime(value);
return DatatypeConverter.printDateTime(cal);
}
private String asString(Duration value) {
return value.toString();
}
private String asString(LocalDate value) {
return value.format(DateTimeFormatter.ISO_LOCAL_DATE);
}
private String asString(LocalDateTime value) {
return value.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
}
private String asString(LocalTime value) {
return value.format(DateTimeFormatter.ISO_LOCAL_TIME);
}
private String asString(OffsetDateTime value) {
return value.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
}
private String asString(OffsetTime value) {
return value.format(DateTimeFormatter.ISO_OFFSET_TIME);
}
"""
}
fun getAtomicMappingConstructors(): Map<String,Map<String,String>> {
return mapOf(
"date" to mapOf(
"java.time.LocalDate" to "asLocalDate"
),
"dateTime" to mapOf(
"java.util.Date" to "asDate",
"java.time.LocalDateTime" to "asLocalDateTime",
"java.time.OffsetDateTime" to "asOffsetDateTime"
),
"dayTimeDuration" to mapOf(
"java.time.Duration" to "asDuration"
),
"decimal" to mapOf(
"java.math.BigDecimal" to "asBigDecimal"
),
"time" to mapOf(
"java.time.LocalTime" to "asLocalTime",
"java.time.OffsetTime" to "asOffsetTime"
)
)
}
fun getDocumentMappingImports(): String {
return """
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stax.StAXSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.FactoryConfigurationError;
"""
}
fun getDocumentMappingMembers(): String {
return """
private ObjectMapper mapper = new ObjectMapper();
private TransformerFactory transformerFactory = null;
{
try {
transformerFactory = TransformerFactory.newInstance();
} catch(TransformerFactoryConfigurationError e) {
throw new RuntimeException(e);
}
}
private Transformer transformer = null;
{
try {
transformer = transformerFactory.newTransformer();
} catch(TransformerConfigurationException e) {
throw new RuntimeException(e);
}
}
private Pattern xmlPrologPattern = Pattern.compile("^\\s*<\\?xml[^>]*>\\s*");
private Stream<String> InputStreamAsString(Stream<InputStream> items) {
return items.map(this::asString);
}
private String asString(InputStream item) {
if (item == null) return null;
try (InputStreamReader reader = new InputStreamReader(item)) {
StringBuffer buffer = new StringBuffer();
char[] chars = new char[1024];
int len = 0;
while ((len = reader.read(chars)) != -1) {
buffer.append(chars, 0, len);
}
return buffer.toString();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private Stream<String> StringAsString(Stream<String> items) {
return items;
}
private String asString(String item) {
return item;
}
private Stream<String> JsonParserAsString(Stream<JsonParser> items) {
return items.map(this::asString);
}
private String asString(JsonParser item) {
if (item == null) return null;
try {
StringWriter writer = new StringWriter();
JsonGenerator generator = mapper.getFactory().createGenerator(writer);
item.nextToken();
generator.copyCurrentStructure(item);
generator.close();
writer.flush();
return writer.toString();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private Stream<String> ArrayNodeAsString(Stream<ArrayNode> items) {
return items.map(this::asString);
}
private String asString(ArrayNode item) {
if (item == null) return null;
try {
return mapper.writeValueAsString(item).replaceAll(",",", ");
} catch(JsonProcessingException e) {
throw new RuntimeException(e);
}
}
private Stream<String> ObjectNodeAsString(Stream<ObjectNode> items) {
return items.map(this::asString);
}
private String asString(ObjectNode item) {
if (item == null) return null;
try {
return mapper.writeValueAsString(item);
} catch(JsonProcessingException e) {
throw new RuntimeException(e);
}
}
private Stream<String> JsonNodeAsString(Stream<JsonNode> items) {
return items.map(this::asString);
}
private String asString(JsonNode item) {
if (item == null) return null;
try {
return mapper.writeValueAsString(item);
} catch(JsonProcessingException e) {
throw new RuntimeException(e);
}
}
private Stream<String> DocumentAsString(Stream<Document> items) {
return items.map(this::asString);
}
private String asString(Document item) {
if (item == null) return null;
return asString(new DOMSource(item));
}
private Stream<String> InputSourceAsString(Stream<InputSource> items) {
return items.map(this::asString);
}
private String asString(InputSource item) {
if (item == null) return null;
return asString(new SAXSource(item));
}
private Stream<String> XMLEventReaderAsString(Stream<XMLEventReader> items) {
return items.map(this::asString);
}
private String asString(XMLEventReader item) {
if (item == null) return null;
try {
return asString(new StAXSource(item));
} catch (XMLStreamException e) {
throw new RuntimeException(e);
}
}
private Stream<String> XMLStreamReaderAsString(Stream<XMLStreamReader> items) {
return items.map(this::asString);
}
private String asString(XMLStreamReader item) {
if (item == null) return null;
return asString(new StAXSource(item));
}
private Stream<String> SourceAsString(Stream<Source> items) {
return items.map(this::asString);
}
private String asString(Source source) {
if (source == null) return null;
try {
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
transformer.transform(source, result);
writer.flush();
String out = writer.toString();
Matcher prologMatcher = xmlPrologPattern.matcher(out);
return prologMatcher.replaceFirst("");
} catch (TransformerException e) {
throw new RuntimeException(e);
}
}
private byte[] binaryDocumentAsByteArray(String value) {
return DatatypeConverter.parseBase64Binary(value);
}
private InputStream binaryDocumentAsInputStream(String value) {
return new ByteArrayInputStream(binaryDocumentAsByteArray(value));
}
private ArrayNode arrayAsArrayNode(String value) {
try {
return mapper.readValue(value, ArrayNode.class);
} catch(IOException e) {
throw new RuntimeException(e);
}
}
private JsonParser arrayAsJsonParser(String value) {
return jsonDocumentAsJsonParser(value);
}
private InputStream arrayAsInputStream(String value) {
return jsonDocumentAsInputStream(value);
}
private Reader arrayAsReader(String value) {
return jsonDocumentAsReader(value);
}
private String arrayAsString(String value) {
return jsonDocumentAsString(value);
}
private ObjectNode objectAsObjectNode(String value) {
try {
return mapper.readValue(value, ObjectNode.class);
} catch(IOException e) {
throw new RuntimeException(e);
}
}
private JsonParser objectAsJsonParser(String value) {
return jsonDocumentAsJsonParser(value);
}
private InputStream objectAsInputStream(String value) {
return jsonDocumentAsInputStream(value);
}
private Reader objectAsReader(String value) {
return jsonDocumentAsReader(value);
}
private String objectAsString(String value) {
return jsonDocumentAsString(value);
}
private ArrayNode jsonDocumentAsArrayNode(String value) {
try {
return mapper.readValue(value, ArrayNode.class);
} catch(IOException e) {
throw new RuntimeException(e);
}
}
private ObjectNode jsonDocumentAsObjectNode(String value) {
try {
return mapper.readValue(value, ObjectNode.class);
} catch(IOException e) {
throw new RuntimeException(e);
}
}
private JsonNode jsonDocumentAsJsonNode(String value) {
try {
return mapper.readTree(value);
} catch(IOException e) {
throw new RuntimeException(e);
}
}
private JsonParser jsonDocumentAsJsonParser(String value) {
try {
return mapper.getFactory().createParser(value);
} catch(IOException e) {
throw new RuntimeException(e);
}
}
private InputStream jsonDocumentAsInputStream(String value) {
return new ByteArrayInputStream(value.getBytes(Charset.forName("UTF-8")));
}
private Reader jsonDocumentAsReader(String value) {
return new StringReader(value);
}
private String jsonDocumentAsString(String value) {
return value;
}
private InputStream textDocumentAsInputStream(String value) {
return new ByteArrayInputStream(value.getBytes(Charset.forName("UTF-8")));
}
private Reader textDocumentAsReader(String value) {
return new StringReader(value);
}
private String textDocumentAsString(String value) {
return value;
}
private Document xmlDocumentAsDocument(String value) {
try {
return DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(
xmlDocumentAsInputStream(value)
);
} catch(SAXException e) {
throw new RuntimeException(e);
} catch(IOException e) {
throw new RuntimeException(e);
} catch (ParserConfigurationException e) {
throw new RuntimeException(e);
}
}
private InputSource xmlDocumentAsInputSource(String value) {
return new InputSource(xmlDocumentAsReader(value));
}
private InputStream xmlDocumentAsInputStream(String value) {
return new ByteArrayInputStream(value.getBytes(Charset.forName("UTF-8")));
}
private Reader xmlDocumentAsReader(String value) {
return new StringReader(value);
}
private Source xmlDocumentAsSource(String value) {
return new StreamSource(xmlDocumentAsReader(value));
}
private String xmlDocumentAsString(String value) {
return value;
}
private XMLEventReader xmlDocumentAsXMLEventReader(String value) {
try {
return XMLInputFactory.newFactory().createXMLEventReader(
xmlDocumentAsReader(value)
);
} catch(XMLStreamException e) {
throw new RuntimeException(e);
} catch(FactoryConfigurationError e) {
throw new RuntimeException(e);
}
}
private XMLStreamReader xmlDocumentAsXMLStreamReader(String value) {
try {
return XMLInputFactory.newFactory().createXMLStreamReader(
xmlDocumentAsReader(value)
);
} catch(XMLStreamException e) {
throw new RuntimeException(e);
} catch(FactoryConfigurationError e) {
throw new RuntimeException(e);
}
}
"""
}
fun getDocumentMappingConstructors(): Map<String,Map<String,String>> {
return mapOf(
"array" to mapOf(
"java.io.InputStream" to "arrayAsInputStream",
"java.lang.String" to "arrayAsString",
"com.fasterxml.jackson.databind.node.ArrayNode" to "arrayAsArrayNode",
"com.fasterxml.jackson.core.JsonParser" to "arrayAsJsonParser"
),
"object" to mapOf(
"java.io.InputStream" to "objectAsInputStream",
"java.lang.String" to "objectAsString",
"com.fasterxml.jackson.databind.node.ObjectNode" to "objectAsObjectNode",
"com.fasterxml.jackson.core.JsonParser" to "objectAsJsonParser"
),
"jsonDocument" to mapOf(
"java.io.InputStream" to "jsonDocumentAsInputStream",
"java.lang.String" to "jsonDocumentAsString",
"com.fasterxml.jackson.databind.JsonNode" to "jsonDocumentAsJsonNode",
"com.fasterxml.jackson.core.JsonParser" to "jsonDocumentAsJsonParser"
),
"textDocument" to mapOf(
"java.io.InputStream" to "textDocumentAsInputStream",
"java.lang.String" to "textDocumentAsString"
),
"xmlDocument" to mapOf(
"org.w3c.dom.Document" to "xmlDocumentAsDocument",
"org.xml.sax.InputSource" to "xmlDocumentAsInputSource",
"java.io.InputStream" to "xmlDocumentAsInputStream",
"javax.xml.transform.Source" to "xmlDocumentAsSource",
"java.lang.String" to "xmlDocumentAsString",
"javax.xml.stream.XMLEventReader" to "xmlDocumentAsXMLEventReader",
"javax.xml.stream.XMLStreamReader" to "xmlDocumentAsXMLStreamReader"
)
)
}
fun main(args: Array<String>) {
try {
when (args.size) {
1 -> dbfTestGenerate(args[0], "latest")
2 -> dbfTestGenerate(args[0], args[1])
else -> {
System.err.println("usage: fntestgen testDir [release]")
exitProcess(-1)
}
}
} catch (e: Exception) {
e.printStackTrace()
}
}
fun getExtensions(release: String) : List<String> {
return when (release) {
"release4" -> listOf("sjs", "xqy")
"release5",
"latest" -> listOf("mjs", "sjs", "xqy")
else -> {
System.err.println("unknown release: $release")
System.err.println("valid releases are one of release4, release5, or latest")
exitProcess(-1)
}
}
}
fun dbfTestGenerate(testDir: String, release: String) {
val modExtensions = getExtensions(release)
val javaBaseDir = testDir+"java/"
val testPath = javaBaseDir+TEST_PACKAGE.replace(".", "/")+"/"
val jsonPath = testDir+"ml-modules/root/dbfunctiondef/generated/"
val endpointBase = "/dbf/test/"
File(testPath).mkdirs()
File(jsonPath).mkdirs()
val host = System.getenv("TEST_HOST") ?: "localhost"
val db = DatabaseClientFactory.newClient(
host,
8000,
"DBFUnitTest",
DatabaseClientFactory.DigestAuthContext("admin", "admin")
)
val modDb = DatabaseClientFactory.newClient(
host,
8000,
"DBFUnitTestModules",
DatabaseClientFactory.DigestAuthContext("admin", "admin")
)
val docMgr = db.newJSONDocumentManager()
val modMgr = modDb.newTextDocumentManager()
val docMeta = DocumentMetadataHandle()
var docPerm = docMeta.permissions
docPerm.add("rest-reader", DocumentMetadataHandle.Capability.READ)
docPerm.add("rest-writer", DocumentMetadataHandle.Capability.UPDATE)
val modMeta = DocumentMetadataHandle()
docPerm = modMeta.permissions
docPerm.add("rest-reader", DocumentMetadataHandle.Capability.READ)
docPerm.add("rest-reader", DocumentMetadataHandle.Capability.EXECUTE)
docPerm.add("rest-writer", DocumentMetadataHandle.Capability.UPDATE)
val testdefFile = File(testDir+"resources/testdef.json")
val testdefs = mapper.readValue<ObjectNode>(testdefFile)
docMgr.write("/dbf/test.json", docMeta, FileHandle(testdefFile))
val mappedTestdefFile = File(testDir+"resources/mappedTestdef.json")
val mappedTestdefs = mapper.readValue<ObjectNode>(mappedTestdefFile)
docMgr.write("/dbf/mappedTest.json", docMeta, FileHandle(mappedTestdefFile))
val atomicNames = atomicMap.keys.toTypedArray()
val atomicMax = atomicNames.size - 1
val documentNames = documentMap.keys.toTypedArray()
val documentMax = documentNames.size - 1
// TODO: remove after fix for internal bug 52334
val multiDocNames = documentNames.filterNot{documentName -> (documentName == "object")}.toTypedArray()
val multiDocMax = documentMax - 1
val multipleTestTypes = listOf(
mapOf("nullable" to false, "multiple" to true),
mapOf("nullable" to true, "multiple" to true)
)
val nonMultipleTestTypes = listOf(
mapOf("nullable" to false, "multiple" to false),
mapOf("nullable" to true, "multiple" to false)
)
val allTestTypes = listOf(
mapOf("nullable" to false, "multiple" to false),
mapOf("nullable" to true, "multiple" to false),
mapOf("nullable" to false, "multiple" to true),
mapOf("nullable" to true, "multiple" to true)
)
val allAtomicParams = atomicNames.indices.map{i ->
val atomicCurr = atomicNames[i]
val testMultiple = (i % 3) == 0
val testNullable = (i % 2) == 0
mapOf(
"name" to "param"+(i + 1), "datatype" to atomicCurr,
"multiple" to testMultiple, "nullable" to testNullable
)
}
val allDocumentParams = documentNames.indices.map{i ->
val documentCurr = documentNames[i]
// TODO: restore after fix for internal bug 52334
// val testMultiple = (i % 3) == 0
val testMultiple = if (documentCurr == "object") false else ((i % 3) == 0)
val testNullable = (i % 2) == 0
mapOf(
"name" to "param"+(i + 1), "datatype" to documentCurr,
"multiple" to testMultiple, "nullable" to testNullable
)
}
if (true) {
val responseBodyTypes = listOf("none", "text", "document", "multipart")
for (responseBodyNum in responseBodyTypes.indices) {
val responseBodyType = responseBodyTypes[responseBodyNum]
val responseBody = responseBodyType.capitalize()
val requestBodyTypes = listOf("none", "urlencoded", "multipart")
for (requestBodyNum in requestBodyTypes.indices) {
val requestBodyType = requestBodyTypes[requestBodyNum]
val requestBody = requestBodyType.capitalize()
val modExtension = modExtensions[(responseBodyNum + requestBodyNum) % modExtensions.size]
val requestParams =
if (responseBodyType === "none")
null
else
// TODO: mix of multiple and nullable based on modulo
when (requestBodyType) {
"none" -> null
"urlencoded" -> listOf(mapOf(
"name" to "param1", "datatype" to atomicNames[responseBodyNum],
"multiple" to true, "nullable" to false
))
"multipart" -> listOf(mapOf(
"name" to "param1", "datatype" to multiDocNames[responseBodyNum % multiDocMax],
"multiple" to true, "nullable" to false
))
else -> throw IllegalStateException("""unknown request body type ${requestBodyType}""")
}
val responseReturnValue =
if (requestBodyType === "none")
null
else
when (responseBodyType) {
"none" -> null
"text" -> mapOf(
"datatype" to atomicNames[requestBodyNum],
"multiple" to true, "nullable" to false
)
"document" -> mapOf(
"datatype" to documentNames[requestBodyNum % documentMax],
"multiple" to false, "nullable" to false
)
"multipart" -> mapOf(
"datatype" to multiDocNames[requestBodyNum % multiDocMax],
"multiple" to true, "nullable" to false
)
else -> throw IllegalStateException("""unknown response body type $responseBodyType""")
}
for (endpointMethod in listOf("post")) {
val testBaseStart = endpointMethod+"Of"+requestBody
val testBaseEnd = "For$responseBody"
val testBundle = testBaseStart+testBaseEnd
val bundleTested = testBundle.capitalize()+"Bundle"
val bundleTester = bundleTested+"Test"
val bundleJSONPath = "$jsonPath$testBundle/"
val bundleFilename = bundleJSONPath+"service.json"
val bundleEndpoint = "$endpointBase$testBundle/"
val bundleJSONString = serializer.writeValueAsString(mapOf(
"endpointDirectory" to bundleEndpoint,
"\$javaClass" to "$TEST_PACKAGE.$bundleTested"
))
File(bundleJSONPath).mkdirs()
File(bundleFilename).writeText(bundleJSONString, Charsets.UTF_8)
val testingFuncs = mutableListOf<String>()
when(responseBodyType) {
"none" -> {
when(requestBodyType) {
"none" -> {
val testName = testBaseStart+testBaseEnd+"0"
val noneJSONString = serializer.writeValueAsString(
if (responseReturnValue === null) mapOf("functionName" to testName)
else mapOf("functionName" to testName, "return" to responseReturnValue)
)
persistServerdef(
modMgr, bundleEndpoint, testName, modMeta, noneJSONString, null, modExtension
)
generateClientdef(
bundleJSONPath, bundleEndpoint, testName, noneJSONString, null, modExtension
)
testingFuncs.add(
generateJUnitCallTest(testName, null, responseReturnValue, testdefs)
)
// TODO: negative tests
// TODO: response tests
}
"urlencoded" -> {
// test of all atomic parameters
val allParamFuncName = testBaseStart+"All"+testBaseEnd+"0"
val allParamJSONString = serializer.writeValueAsString(
if (responseReturnValue === null) mapOf(
"functionName" to allParamFuncName, "params" to allAtomicParams
)
else mapOf(
"functionName" to allParamFuncName, "params" to allAtomicParams, "return" to responseReturnValue
)
)
persistServerdef(
modMgr, bundleEndpoint, allParamFuncName, modMeta, allParamJSONString, allAtomicParams, modExtension
)
generateClientdef(
bundleJSONPath, bundleEndpoint, allParamFuncName, allParamJSONString, allAtomicParams, modExtension
)
testingFuncs.add(
generateJUnitCallTest(allParamFuncName, allAtomicParams, responseReturnValue, testdefs)
)
testingFuncs.add(
generateJUnitCallTest(
allParamFuncName, allAtomicParams, responseReturnValue, testdefs, TestVariant.NULL
)
)
testingFuncs.add(
generateJUnitCallTest(
allParamFuncName, allAtomicParams, responseReturnValue, testdefs, TestVariant.EMPTY
)
)
for (i in atomicNames.indices) {
val atomicCurr = atomicNames[i]
for (testNum in allTestTypes.indices) {
val testType = allTestTypes[testNum]
val testMultiple = testType["multiple"] as Boolean
val testNullable = testType["nullable"] as Boolean
val funcParams = listOf(mapOf(
"name" to "param1", "datatype" to atomicCurr,
"multiple" to testMultiple, "nullable" to testNullable
))
val testName = testBaseStart+atomicCurr.capitalize()+testBaseEnd+testNum
val testdef =
if (responseReturnValue === null) mapOf(
"functionName" to testName, "params" to funcParams
)
else mapOf(
"functionName" to testName, "params" to funcParams, "return" to responseReturnValue
)
val testJSONString = serializer.writeValueAsString(testdef)
persistServerdef(
modMgr, bundleEndpoint, testName, modMeta, testJSONString, funcParams, modExtension
)
generateClientdef(
bundleJSONPath, bundleEndpoint, testName, testJSONString, funcParams, modExtension
)
testingFuncs.add(
generateJUnitCallTest(testName, funcParams, responseReturnValue, testdefs)
)
if (testNullable) {
testingFuncs.add(
generateJUnitCallTest(testName, funcParams, responseReturnValue, testdefs, TestVariant.NULL)
)
if (testMultiple) {
testingFuncs.add(
generateJUnitCallTest(testName, funcParams, responseReturnValue, testdefs, TestVariant.EMPTY)
)
}
} else {
// negative test of actual null value for expected non-nullable value
val nullErrName = testName+"NullErr"
val nullErrServerdef = replaceFuncName(testdef, nullErrName)
persistServerdef(
modMgr, bundleEndpoint, nullErrName, modMeta,
serializer.writeValueAsString(nullErrServerdef), funcParams, modExtension
)
val nullErrClientParams = replaceParamValue(funcParams, "nullable", true)
val nullErrClientdef = replaceFuncParams(nullErrServerdef, nullErrClientParams)
generateClientdef(
bundleJSONPath, bundleEndpoint, nullErrName,
serializer.writeValueAsString(nullErrClientdef), nullErrClientParams, modExtension
)
testingFuncs.add(
generateJUnitCallTest(
nullErrName, nullErrClientParams, responseReturnValue, testdefs, TestVariant.NULL, true
)
)
if (!testMultiple) {
// negative test of actual multiple values for expected single value
val multiErrName = testName+"MultiErr"
val multiErrServerdef = replaceFuncName(testdef, multiErrName)
persistServerdef(
modMgr, bundleEndpoint, multiErrName, modMeta,
serializer.writeValueAsString(multiErrServerdef), funcParams, modExtension
)
val multiErrClientParams = replaceParamValue(funcParams, "multiple", true)
val multiErrClientdef = replaceFuncParams(multiErrServerdef, multiErrClientParams)
generateClientdef(
bundleJSONPath, bundleEndpoint, multiErrName,
serializer.writeValueAsString(multiErrClientdef), multiErrClientParams, modExtension
)
testingFuncs.add(
generateJUnitCallTest(
multiErrName, multiErrClientParams, responseReturnValue, testdefs, TestVariant.VALUE, true
)
)
}
if (atomicCurr != "string") {
// negative test of actual uncastable data type for expected current data type
val typeErrName = testName+"TypeErr"
val typeErrServerdef = replaceFuncName(testdef, typeErrName)
persistServerdef(
modMgr, bundleEndpoint, typeErrName, modMeta,
serializer.writeValueAsString(typeErrServerdef), funcParams, modExtension
)
val typeErrClientParams = replaceParamValue(
funcParams, "datatype", uncastableAtomicType(testdefs, atomicCurr)
)
val typeErrClientdef = replaceFuncParams(typeErrServerdef, typeErrClientParams)
generateClientdef(
bundleJSONPath, bundleEndpoint, typeErrName,
serializer.writeValueAsString(typeErrClientdef), typeErrClientParams, modExtension
)
testingFuncs.add(
generateJUnitCallTest(
typeErrName, typeErrClientParams, responseReturnValue, testdefs, TestVariant.VALUE, true
)
)
}
// negative test of actual multiple arity for expected single arity
val atomicOther = atomicNames[if (i == atomicMax) 0 else i + 1]
val arityErrName = testName+"ArityErr"
val arityErrServerdef = replaceFuncName(testdef, arityErrName)
persistServerdef(
modMgr, bundleEndpoint, arityErrName, modMeta,
serializer.writeValueAsString(arityErrServerdef), funcParams, modExtension
)
val arityErrClientParams = funcParams.plus(mapOf("name" to "param2", "datatype" to atomicOther))
val arityErrClientdef = replaceFuncParams(arityErrServerdef, arityErrClientParams)
generateClientdef(
bundleJSONPath, bundleEndpoint, arityErrName,
serializer.writeValueAsString(arityErrClientdef), arityErrClientParams, modExtension
)
testingFuncs.add(
generateJUnitCallTest(
arityErrName, arityErrClientParams, responseReturnValue, testdefs, TestVariant.VALUE, true
)
)
}
}
}
}
"multipart" -> {
// test of all document parameters
val allParamFuncName = testBaseStart+"All"+testBaseEnd+"0"
val allParamJSONString = serializer.writeValueAsString(
if (responseReturnValue === null) mapOf(
"functionName" to allParamFuncName, "params" to allDocumentParams
)
else mapOf(
"functionName" to allParamFuncName, "params" to allDocumentParams, "return" to responseReturnValue
)
)
persistServerdef(
modMgr, bundleEndpoint, allParamFuncName, modMeta, allParamJSONString, allDocumentParams, modExtension
)
generateClientdef(
bundleJSONPath, bundleEndpoint, allParamFuncName, allParamJSONString, allDocumentParams, modExtension
)
testingFuncs.add(
generateJUnitCallTest(allParamFuncName, allDocumentParams, responseReturnValue, testdefs)
)
testingFuncs.add(
generateJUnitCallTest(
allParamFuncName, allDocumentParams, responseReturnValue, testdefs, TestVariant.NULL
)
)
testingFuncs.add(
generateJUnitCallTest(
allParamFuncName, allDocumentParams, responseReturnValue, testdefs, TestVariant.EMPTY
)
)
for (i in documentNames.indices) {
val docCurr = documentNames[i]
val atomic1 = atomicNames[i]
val atomic2 = atomicNames[if (i == atomicMax) 0 else i + 1]
val docTestTypes = allTestTypes
for (testNum in docTestTypes.indices) {
val testType = docTestTypes[testNum]
// TODO: restore after fix for internal bug 52334
// val testMultiple = testType.get("multiple") as Boolean
val testMultiple = if (docCurr == "object") false else (testType["multiple"] as Boolean)
val testNullable = testType["nullable"] as Boolean
val docFuncParams = listOf(mapOf(
"name" to "param1", "datatype" to docCurr,
"multiple" to testMultiple, "nullable" to testNullable
))
val testMax = 2
val docTestName = testBaseStart+docCurr.capitalize()+testBaseEnd+(testNum * testMax)
val docTestdef =
if (responseReturnValue === null) mapOf(
"functionName" to docTestName, "params" to docFuncParams
)
else mapOf(
"functionName" to docTestName, "params" to docFuncParams, "return" to responseReturnValue
)
for (j in 1 .. testMax) {
val funcParams =
if (j < testMax) docFuncParams
else docFuncParams + listOf(
mapOf("name" to "param2", "datatype" to atomic1),
mapOf("name" to "param3", "datatype" to atomic2)
)
val testName = testBaseStart+docCurr.capitalize()+testBaseEnd+((testNum * testMax) + j - 1)
val testdef1 = replaceFuncName(docTestdef, testName)
val testdef2 =
if (j < testMax) testdef1
else replaceFuncParams(testdef1, funcParams)
val testJSONString = serializer.writeValueAsString(testdef2)
persistServerdef(
modMgr, bundleEndpoint, testName, modMeta, testJSONString, funcParams, modExtension
)
generateClientdef(
bundleJSONPath, bundleEndpoint, testName, testJSONString, funcParams, modExtension
)
testingFuncs.add(
generateJUnitCallTest(testName, funcParams, responseReturnValue, testdefs)
)
}
if (testNullable) {
testingFuncs.add(
generateJUnitCallTest(
docTestName, docFuncParams, responseReturnValue, testdefs, TestVariant.NULL
)
)
if (testMultiple) {
testingFuncs.add(
generateJUnitCallTest(
docTestName, docFuncParams, responseReturnValue, testdefs, TestVariant.EMPTY
)
)
}
} else {
// negative test of actual null value for expected non-nullable value
val nullErrName = docTestName+"NullErr"
val nullErrServerdef = replaceFuncName(docTestdef, nullErrName)
persistServerdef(
modMgr, bundleEndpoint, nullErrName, modMeta,
serializer.writeValueAsString(nullErrServerdef), docFuncParams, modExtension
)
val nullErrClientParams = replaceParamValue(docFuncParams, "nullable", true)
val nullErrClientdef = replaceFuncParams(nullErrServerdef, nullErrClientParams)
generateClientdef(
bundleJSONPath, bundleEndpoint, nullErrName,
serializer.writeValueAsString(nullErrClientdef), nullErrClientParams, modExtension
)
testingFuncs.add(
generateJUnitCallTest(
nullErrName, nullErrClientParams, responseReturnValue, testdefs, TestVariant.NULL, true
)
)
if (!testMultiple) {
// negative test of actual multiple values for expected single value
val multiErrName = docTestName+"MultiErr"
val multiErrServerdef = replaceFuncName(docTestdef, multiErrName)
persistServerdef(
modMgr, bundleEndpoint, multiErrName, modMeta,
serializer.writeValueAsString(multiErrServerdef), docFuncParams, modExtension
)
val multiErrClientParams = replaceParamValue(docFuncParams, "multiple", true)
val multiErrClientdef = replaceFuncParams(multiErrServerdef, multiErrClientParams)
generateClientdef(
bundleJSONPath, bundleEndpoint, multiErrName,
serializer.writeValueAsString(multiErrClientdef), multiErrClientParams, modExtension
)
testingFuncs.add(
generateJUnitCallTest(
multiErrName, multiErrClientParams, responseReturnValue, testdefs, TestVariant.VALUE, true
)
)
}
if (docCurr === "jsonDocument" || docCurr === "xmlDocument") {
// negative test of actual different data type for expected current data type
val docOther =
when (docCurr) {
"array", "object", "jsonDocument" -> "xmlDocument"
"xmlDocument" -> "jsonDocument"
else -> throw IllegalArgumentException("No type error test for $docCurr")
}
val typeErrName = docTestName+"TypeErr"
val typeErrServerdef = replaceFuncName(docTestdef, typeErrName)
persistServerdef(
modMgr, bundleEndpoint, typeErrName, modMeta,
serializer.writeValueAsString(typeErrServerdef), docFuncParams, modExtension
)
val typeErrClientParams = replaceParamValue(docFuncParams, "datatype", docOther)
val typeErrClientdef = replaceFuncParams(typeErrServerdef, typeErrClientParams)
generateClientdef(
bundleJSONPath, bundleEndpoint, typeErrName,
serializer.writeValueAsString(typeErrClientdef), typeErrClientParams, modExtension
)
testingFuncs.add(
generateJUnitCallTest(
typeErrName, typeErrClientParams, responseReturnValue, testdefs, TestVariant.VALUE, true
)
)
}
// negative test of actual multiple arity for expected single arity
val atomicOther = atomicNames[if (i == atomicMax) 0 else i + 1]
val arityErrName = docTestName+"ArityErr"
val arityErrServerdef = replaceFuncName(docTestdef, arityErrName)
persistServerdef(
modMgr, bundleEndpoint, arityErrName, modMeta,
serializer.writeValueAsString(arityErrServerdef), docFuncParams, modExtension
)
val arityErrClientParams = docFuncParams.plus(mapOf("name" to "param2", "datatype" to atomicOther))
val arityErrClientdef = replaceFuncParams(arityErrServerdef, arityErrClientParams)
generateClientdef(
bundleJSONPath, bundleEndpoint, arityErrName,
serializer.writeValueAsString(arityErrClientdef), arityErrClientParams, modExtension
)
testingFuncs.add(
generateJUnitCallTest(
arityErrName, arityErrClientParams, responseReturnValue, testdefs, TestVariant.VALUE, true
)
)
}
}
}
}
else -> throw IllegalStateException("""unknown request body type $requestBodyType""")
}} // end of branching on request body type
"text" -> {
for (i in atomicNames.indices) {
val atomicCurr = atomicNames[i]
for (testNum in nonMultipleTestTypes.indices) {
val testType = nonMultipleTestTypes[testNum]
val testNullable = testType["nullable"] as Boolean
val funcReturn = mapOf(
"datatype" to atomicCurr, "nullable" to testNullable
)
val testName = testBaseStart+testBaseEnd+atomicCurr.capitalize()+testNum
val testdef =
if (requestParams === null) mapOf(
"functionName" to testName, "return" to funcReturn
)
else mapOf(
"functionName" to testName, "params" to requestParams, "return" to funcReturn
)
val testJSONString = serializer.writeValueAsString(testdef)
persistServerdef(
modMgr, bundleEndpoint, testName, modMeta, testJSONString, requestParams, modExtension
)
generateClientdef(
bundleJSONPath, bundleEndpoint, testName, testJSONString, requestParams, modExtension
)
testingFuncs.add(
generateJUnitCallTest(testName, requestParams, funcReturn, testdefs)
)
if (testNullable) {
// positive test of actual null value for expected nullable value
val nulledTestName = testName+"ReturnNull"
val nulledTestdef = replaceFuncName(testdef, nulledTestName)
val nulledTestJSONString = serializer.writeValueAsString(nulledTestdef)
persistServerdef(
modMgr, bundleEndpoint, nulledTestName, modMeta, nulledTestJSONString, requestParams, modExtension
)
generateClientdef(
bundleJSONPath, bundleEndpoint, nulledTestName, nulledTestJSONString, requestParams, modExtension
)
testingFuncs.add(
generateJUnitCallTest(
nulledTestName, requestParams, funcReturn, testdefs, TestVariant.NULL
)
)
} else {
/* TODO: enable the tests appropriate for non-multiple single value response
// TODO: client-side errors when null returned for any non-nullable
if (!testMultiple) {
val mappedType = getJavaDataType(atomicCurr, null, "atomic", testNullable, testMultiple)
if (mappedType !== "String") {
// negative test of actual null value for expected non-nullable value
val nulledTestName = testName+"ErrReturnNull"
val nulledTestdef = replaceFuncName(testdef, nulledTestName)
val nulledTestJSONString = serializer.writeValueAsString(nulledTestdef)
generateClientdef(bundleJSONPath, bundleEndpoint, nulledTestName, nulledTestJSONString, modExtension)
testingFuncs.add(
generateJUnitCallTest(
nulledTestName, requestParams, funcReturn, testdefs, expectError=true
)
)
persistServerdef(modMgr, bundleEndpoint, nulledTestName, modMeta, nulledTestJSONString, modExtension)
// TODO: return one for testMultiple of true
// any non-true string coerces to false
if (atomicCurr != "boolean") {
// negative test of actual uncastable data type for expected current data type
val typeErrName = testName+"TypeErr"
val typeErrClientdef = replaceFuncName(testdef, typeErrName)
generateClientdef(
bundleJSONPath, bundleEndpoint, typeErrName,
serializer.writeValueAsString(typeErrClientdef), modExtension
)
testingFuncs.add(
generateJUnitCallTest(
typeErrName, requestParams, funcReturn, testdefs, expectError=true
)
)
val typeErrFuncReturn = replaceDataType(funcReturn, uncastableAtomicType(testdefs, atomicCurr))
val typeErrServerdef = replaceFuncReturn(typeErrClientdef, typeErrFuncReturn)
persistServerdef(
modMgr, bundleEndpoint, typeErrName, modMeta,
serializer.writeValueAsString(typeErrServerdef), modExtension
)
}
}
// negative test of actual multiple values for expected single value
val multiErrName = testName+"MultiErr"
val multiErrClientdef = replaceFuncName(testdef, multiErrName)
generateClientdef(
bundleJSONPath, bundleEndpoint, multiErrName,
serializer.writeValueAsString(multiErrClientdef), modExtension
)
testingFuncs.add(
generateJUnitCallTest(
multiErrName, requestParams, funcReturn, testdefs, expectError=true
)
)
val multiErrServerReturn = replaceMultiple(funcReturn, true)
val multiErrServerdef = replaceFuncReturn(multiErrClientdef, multiErrServerReturn)
persistServerdef(
modMgr, bundleEndpoint, multiErrName, modMeta,
serializer.writeValueAsString(multiErrServerdef), modExtension
)
} */
}
}
}}
"document" -> {
for (i in documentNames.indices) {
val docCurr = documentNames[i]
// TODO: atomics as well as documents
// val atomic1 = atomicNames[i]
// val atomic2 = atomicNames[if (i == atomicMax) 0 else i + 1]
val docTestTypes = nonMultipleTestTypes
for (testNum in docTestTypes.indices) {
val testType = docTestTypes[testNum]
// TODO: restore after fix for internal bug 52334
// val testMultiple = testType.get("multiple") as Boolean
val testMultiple = if (docCurr == "object") false else (testType["multiple"] as Boolean)
val testNullable = testType["nullable"] as Boolean
val funcReturn = mapOf(
"datatype" to docCurr,
"multiple" to testMultiple, "nullable" to testNullable
)
val testName = testBaseStart+testBaseEnd+docCurr.capitalize()+testNum
val testdef =
if (requestParams === null) mapOf(
"functionName" to testName, "return" to funcReturn
)
else mapOf(
"functionName" to testName, "params" to requestParams, "return" to funcReturn
)
val testJSONString = serializer.writeValueAsString(testdef)
persistServerdef(modMgr, bundleEndpoint, testName, modMeta, testJSONString, requestParams, modExtension)
generateClientdef(bundleJSONPath, bundleEndpoint, testName, testJSONString, requestParams, modExtension)
testingFuncs.add(
generateJUnitCallTest(testName, requestParams, funcReturn, testdefs)
)
if (testNullable) {
// positive test of actual null value for expected nullable value
val nulledTestName = testName+"ReturnNull"
val nulledTestdef = replaceFuncName(testdef, nulledTestName)
val nulledTestJSONString = serializer.writeValueAsString(nulledTestdef)
persistServerdef(
modMgr, bundleEndpoint, nulledTestName, modMeta, nulledTestJSONString, requestParams, modExtension
)
generateClientdef(
bundleJSONPath, bundleEndpoint, nulledTestName, nulledTestJSONString, requestParams, modExtension
)
testingFuncs.add(
generateJUnitCallTest(
nulledTestName, requestParams, funcReturn, testdefs, TestVariant.NULL
)
)
} else {
// TODO: client-side errors when null returned for any non-nullable
// negative test of actual null value for expected non-nullable value
val nulledTestName = testName+"ErrReturnNull"
val nulledTestdef = replaceFuncName(testdef, nulledTestName)
val nulledTestJSONString = serializer.writeValueAsString(nulledTestdef)
generateClientdef(
bundleJSONPath, bundleEndpoint, nulledTestName, nulledTestJSONString, requestParams, modExtension
)
testingFuncs.add(
generateJUnitCallTest(
nulledTestName, requestParams, funcReturn, testdefs, expectError=true
)
)
persistServerdef(
modMgr, bundleEndpoint, nulledTestName, modMeta, nulledTestJSONString, requestParams, modExtension
)
// TODO: return one for testMultiple of true
// negative test of actual uncastable data type for expected current data type
val docOther = pickDocOther(multiDocNames, multiDocMax, docCurr, i)
val typeErrName = testName+"TypeErr"
val typeErrClientdef = replaceFuncName(testdef, typeErrName)
generateClientdef(
bundleJSONPath, bundleEndpoint, typeErrName,
serializer.writeValueAsString(typeErrClientdef), requestParams, modExtension
)
testingFuncs.add(
generateJUnitCallTest(
typeErrName, requestParams, funcReturn, testdefs, expectError=true
)
)
val typeErrFuncReturn = replaceDataType(funcReturn, docOther)
val typeErrServerdef = replaceFuncReturn(typeErrClientdef, typeErrFuncReturn)
persistServerdef(
modMgr, bundleEndpoint, typeErrName, modMeta,
serializer.writeValueAsString(typeErrServerdef), requestParams, modExtension
)
}
}
}}
"multipart" -> {
for (i in multiDocNames.indices) {
val docCurr = multiDocNames[i]
// TODO: atomics as well as documents
// val atomic1 = atomicNames[i]
// val atomic2 = atomicNames[if (i == atomicMax) 0 else i + 1]
val docTestTypes = multipleTestTypes
for (testNum in docTestTypes.indices) {
val testType = docTestTypes[testNum]
// TODO: restore after fix for internal bug 52334
// val testMultiple = testType.get("multiple") as Boolean
val testMultiple = if (docCurr == "object") false else (testType["multiple"] as Boolean)
val testNullable = testType["nullable"] as Boolean
val funcReturn = mapOf(
"datatype" to docCurr,
"multiple" to testMultiple, "nullable" to testNullable
)
val testName = testBaseStart + testBaseEnd + docCurr.capitalize() + testNum
val testdef =
if (requestParams === null) mapOf(
"functionName" to testName, "return" to funcReturn
)
else mapOf(
"functionName" to testName, "params" to requestParams, "return" to funcReturn
)
val testJSONString = serializer.writeValueAsString(testdef)
persistServerdef(
modMgr, bundleEndpoint, testName, modMeta, testJSONString, requestParams, modExtension
)
generateClientdef(
bundleJSONPath, bundleEndpoint, testName, testJSONString, requestParams, modExtension
)
testingFuncs.add(
generateJUnitCallTest(testName, requestParams, funcReturn, testdefs)
)
if (testNullable) {
// positive test of actual null value for expected nullable value
val nulledTestName = testName+"ReturnNull"
val nulledTestdef = replaceFuncName(testdef, nulledTestName)
val nulledTestJSONString = serializer.writeValueAsString(nulledTestdef)
persistServerdef(
modMgr, bundleEndpoint, nulledTestName, modMeta, nulledTestJSONString, requestParams, modExtension
)
generateClientdef(
bundleJSONPath, bundleEndpoint, nulledTestName, nulledTestJSONString, requestParams, modExtension
)
testingFuncs.add(
generateJUnitCallTest(
nulledTestName, requestParams, funcReturn, testdefs, TestVariant.NULL
)
)
} else {
// TODO: client-side errors when null returned for any non-nullable
if (!testMultiple) {
// negative test of actual null value for expected non-nullable value
val nulledTestName = testName+"ErrReturnNull"
val nulledTestdef = replaceFuncName(testdef, nulledTestName)
val nulledTestJSONString = serializer.writeValueAsString(nulledTestdef)
generateClientdef(
bundleJSONPath, bundleEndpoint, nulledTestName, nulledTestJSONString, requestParams, modExtension
)
testingFuncs.add(
generateJUnitCallTest(
nulledTestName, requestParams, funcReturn, testdefs, expectError=true
)
)
persistServerdef(
modMgr, bundleEndpoint, nulledTestName, modMeta, nulledTestJSONString, requestParams, modExtension
)
// negative test of actual uncastable data type for expected current data type
val docOther = pickDocOther(multiDocNames, multiDocMax, docCurr, i)
val typeErrName = testName+"TypeErr"
val typeErrClientdef = replaceFuncName(testdef, typeErrName)
generateClientdef(
bundleJSONPath, bundleEndpoint, typeErrName,
serializer.writeValueAsString(typeErrClientdef), requestParams, modExtension
)
testingFuncs.add(
generateJUnitCallTest(
typeErrName, requestParams, funcReturn, testdefs, expectError=true
)
)
val typeErrFuncReturn = replaceDataType(funcReturn, docOther)
val typeErrServerdef = replaceFuncReturn(typeErrClientdef, typeErrFuncReturn)
persistServerdef(
modMgr, bundleEndpoint, typeErrName, modMeta,
serializer.writeValueAsString(typeErrServerdef), requestParams, modExtension
)
// negative test of actual multiple values for expected single value
val multiErrName = testName+"MultiErr"
val multiErrClientdef = replaceFuncName(testdef, multiErrName)
generateClientdef(
bundleJSONPath, bundleEndpoint, multiErrName,
serializer.writeValueAsString(multiErrClientdef), requestParams, modExtension
)
testingFuncs.add(
generateJUnitCallTest(
multiErrName, requestParams, funcReturn, testdefs, expectError=true
)
)
val multiErrServerReturn = replaceMultiple(funcReturn, true)
val multiErrServerdef = replaceFuncReturn(multiErrClientdef, multiErrServerReturn)
persistServerdef(
modMgr, bundleEndpoint, multiErrName, modMeta,
serializer.writeValueAsString(multiErrServerdef), requestParams, modExtension
)
}
}
}
}}
else -> throw IllegalStateException("""unknown response body type $responseBodyType""")
} // end of branching on response body type
generator.serviceBundleToJava(bundleFilename, javaBaseDir)
writeJUnitRequestTest(
"$testPath$bundleTester.java",
generateJUnitTest(bundleTested, bundleTester, testingFuncs)
)
} // end of iteration on endpoint methods
} // end of iteration on request body types
} // end of iteration on response body types
}
// TODO: function parameterized for atomics or documents
if (true) {
val atomicMappingConstructors = getAtomicMappingConstructors()
val atomicMappingBundle = "mapAtomics"
val atomicMappingBundleTested = atomicMappingBundle.capitalize()+"Bundle"
val atomicMappingBundleTester = atomicMappingBundleTested+"Test"
val atomicMappingBundleJSONPath = "$jsonPath$atomicMappingBundle/"
val atomicMappingBundleFilename = atomicMappingBundleJSONPath+"service.json"
val atomicMappingBundleEndpoint = "$endpointBase$atomicMappingBundle/"
val atomicMappingBundleJSONString = serializer.writeValueAsString(mapOf(
"endpointDirectory" to atomicMappingBundleEndpoint,
"\$javaClass" to "$TEST_PACKAGE.$atomicMappingBundleTested"
))
File(atomicMappingBundleJSONPath).mkdirs()
File(atomicMappingBundleFilename).writeText(atomicMappingBundleJSONString, Charsets.UTF_8)
val atomicMappingTestingFuncs = mutableListOf<String>()
val atomicMappingDatatypes = atomicMappingConstructors.keys.toTypedArray()
for (datatypeNum in atomicMappingDatatypes.indices) {
val datatype = atomicMappingDatatypes[datatypeNum]
val testBaseStart = atomicMappingBundle+datatype.capitalize()
val datatypeConstructors = atomicMappingConstructors[datatype] as Map<String,String>
val modExtension = modExtensions[datatypeNum % modExtensions.size]
for (mappedType in datatypeConstructors.keys) {
// mappedType.capitalize().replace('.', '_')
val testMapped = mappedType.split('.').joinToString("") { word -> word.capitalize() }
val mappedConstructor = datatypeConstructors[mappedType] as String
val typeConstructors = mapOf(datatype to mappedConstructor)
for (testNum in allTestTypes.indices) {
val testType = allTestTypes[testNum]
// TODO: restore after fix for internal bug 52334
// val testMultiple = testType.get("multiple") as Boolean
val testMultiple = if (datatype == "object") false else (testType["multiple"] as Boolean)
val testNullable = testType["nullable"] as Boolean
val funcParams = listOf(mapOf(
"name" to "param1", "datatype" to datatype,
"multiple" to testMultiple, "nullable" to testNullable,
"\$javaClass" to mappedType
))
var testName = testBaseStart+"Of"+testMapped+"ForNone"+testNum
var testdef = mapOf("functionName" to testName, "params" to funcParams)
var testJSONString = serializer.writeValueAsString(testdef)
persistServerdef(
modMgr, atomicMappingBundleEndpoint, testName, modMeta, testJSONString, funcParams, modExtension
)
generateClientdef(
atomicMappingBundleJSONPath, atomicMappingBundleEndpoint, testName, testJSONString, funcParams, modExtension
)
atomicMappingTestingFuncs.add(
generateJUnitCallTest(
testName, funcParams, null, testdefs,
typeConstructors = typeConstructors, mappedTestdefs = mappedTestdefs
)
)
val funcReturn = mapOf(
"datatype" to datatype, "multiple" to testMultiple, "nullable" to testNullable,
"\$javaClass" to mappedType
)
testName = testBaseStart+"OfNoneForText"+testMapped+testNum
testdef = mapOf("functionName" to testName, "return" to funcReturn)
testJSONString = serializer.writeValueAsString(testdef)
persistServerdef(
modMgr, atomicMappingBundleEndpoint, testName, modMeta, testJSONString, null, modExtension
)
generateClientdef(
atomicMappingBundleJSONPath, atomicMappingBundleEndpoint, testName, testJSONString, null, modExtension
)
atomicMappingTestingFuncs.add(
generateJUnitCallTest(
testName, null, funcReturn, testdefs,
typeConstructors = typeConstructors, mappedTestdefs = mappedTestdefs
)
)
}
}
}
generator.serviceBundleToJava(atomicMappingBundleFilename, javaBaseDir)
writeJUnitRequestTest(
"$testPath$atomicMappingBundleTester.java",
generateJUnitTest(atomicMappingBundleTested, atomicMappingBundleTester, atomicMappingTestingFuncs,
extraImports = getAtomicMappingImports(), extraMembers = getAtomicMappingMembers())
)
}
if (true) {
val documentMappingConstructors = getDocumentMappingConstructors()
val documentMappingBundle = "mapDocuments"
val documentMappingBundleTested = documentMappingBundle.capitalize()+"Bundle"
val documentMappingBundleTester = documentMappingBundleTested+"Test"
val documentMappingBundleJSONPath = "$jsonPath$documentMappingBundle/"
val documentMappingBundleFilename = documentMappingBundleJSONPath+"service.json"
val documentMappingBundleEndpoint = "$endpointBase$documentMappingBundle/"
val documentMappingBundleJSONString = serializer.writeValueAsString(mapOf(
"endpointDirectory" to documentMappingBundleEndpoint,
"\$javaClass" to "$TEST_PACKAGE.$documentMappingBundleTested"
))
File(documentMappingBundleJSONPath).mkdirs()
File(documentMappingBundleFilename).writeText(documentMappingBundleJSONString, Charsets.UTF_8)
val documentMappingTestingFuncs = mutableListOf<String>()
val documentMappedDatatypes = documentMappingConstructors.keys.toTypedArray()
for (datatypeNum in documentMappedDatatypes.indices) {
val datatype = documentMappedDatatypes[datatypeNum]
val testBaseStart = documentMappingBundle+datatype.capitalize()
val datatypeConstructors = documentMappingConstructors[datatype] as Map<String,String>
val modExtension = modExtensions[datatypeNum % modExtensions.size]
for (mappedType in datatypeConstructors.keys) {
val testMapped = mappedType.split('.').joinToString("") { word -> word.capitalize() }
val mappedConstructor = datatypeConstructors[mappedType] as String
val typeConstructors = mapOf(datatype to mappedConstructor)
for (testNum in allTestTypes.indices) {
val testType = allTestTypes[testNum]
// TODO: restore after fix for internal bug 52334
// val testMultiple = testType.get("multiple") as Boolean
val testMultiple = if (datatype == "object") false else (testType["multiple"] as Boolean)
val testNullable = testType["nullable"] as Boolean
val funcParams = listOf(mapOf(
"name" to "param1", "datatype" to datatype,
"multiple" to testMultiple, "nullable" to testNullable,
"\$javaClass" to mappedType
))
var testName = testBaseStart + "Of" + testMapped + "ForNone" + testNum
var testdef = mapOf("functionName" to testName, "params" to funcParams)
var testJSONString = serializer.writeValueAsString(testdef)
persistServerdef(
modMgr, documentMappingBundleEndpoint, testName, modMeta, testJSONString, funcParams, modExtension
)
generateClientdef(
documentMappingBundleJSONPath, documentMappingBundleEndpoint, testName, testJSONString, funcParams, modExtension
)
documentMappingTestingFuncs.add(
generateJUnitCallTest(
testName, funcParams, null, testdefs,
typeConstructors = typeConstructors, mappedTestdefs = mappedTestdefs
)
)
val funcReturn = mapOf(
"datatype" to datatype, "multiple" to testMultiple, "nullable" to testNullable,
"\$javaClass" to mappedType
)
testName = testBaseStart+"OfNoneForText"+testMapped+testNum
testdef = mapOf("functionName" to testName, "return" to funcReturn)
testJSONString = serializer.writeValueAsString(testdef)
persistServerdef(
modMgr, documentMappingBundleEndpoint, testName, modMeta, testJSONString, null, modExtension
)
generateClientdef(
documentMappingBundleJSONPath, documentMappingBundleEndpoint, testName, testJSONString, null, modExtension
)
documentMappingTestingFuncs.add(
generateJUnitCallTest(
testName, null, funcReturn, testdefs,
typeConstructors = typeConstructors, mappedTestdefs = mappedTestdefs
)
)
}
}
}
// System.out.println(documentMappingTestingFuncs.joinToString("\n"))
generator.serviceBundleToJava(documentMappingBundleFilename, javaBaseDir)
writeJUnitRequestTest(
"$testPath$documentMappingBundleTester.java",
generateJUnitTest(documentMappingBundleTested, documentMappingBundleTester, documentMappingTestingFuncs,
extraImports = getDocumentMappingImports(), extraMembers = getDocumentMappingMembers())
)
}
if (true) {
for (testType in listOf("negative", "positive")) {
val testList =
when (testType) {
"negative" -> listOf("badExecution")
"positive" -> listOf("anyDocument", "decoratorBase", "decoratorCustom", "described", "mimetype", "sessions")
else -> throw IllegalStateException("Unknown test type of $testType")
}
for (testName in testList) {
val testModMgr = modMgr
val manualBundleJSONPath = "${testDir}ml-modules/root/dbfunctiondef/${testType}/${testName}/"
val manualBundleEndpoint = "$endpointBase$testName/"
val manualBundleFilename = manualBundleJSONPath+"service.json"
generator.serviceBundleToJava(manualBundleFilename, javaBaseDir)
File(manualBundleJSONPath)
.listFiles()
.filter{file -> (file.extension == "api")}
.forEach{apiFile ->
val baseName = apiFile.nameWithoutExtension
val apiName = "$baseName.api"
val modFile = listOf(".sjs", ".xqy", ".mjs").fold(null as File?, {found: File?, extension: String ->
if (found != null) {
found
} else {
val candidate = File(manualBundleJSONPath + baseName + extension)
if (candidate.exists()) {
candidate
} else {
null
}
}
})
if (modFile == null) {
throw IllegalArgumentException("could not find module for $apiName")
}
val modName = modFile.name
testModMgr.write(
testModMgr.newWriteSet()
.add(manualBundleEndpoint+apiName, docMeta, FileHandle(apiFile))
.add(manualBundleEndpoint+modName, modMeta, FileHandle(modFile))
)
}
}}
}
if (true) {
val moduleInitName = "initializer"
val moduleInitParams = allTestTypes.mapIndexed{i, testdef -> mapOf(
"name" to "param" + (i + 1),
"datatype" to atomicNames[i],
"multiple" to testdef["multiple"],
"nullable" to testdef["nullable"]
)}
val moduleInitReturn = mapOf("datatype" to "boolean")
val moduleInitTestdef = mapOf(
"functionName" to moduleInitName,
"params" to moduleInitParams,
"return" to moduleInitReturn
)
val moduleInitTestString = serializer.writeValueAsString(moduleInitTestdef)
for (modExtension in modExtensions) {
val moduleInitBundle = "moduleInit"+modExtension.capitalize()
val moduleInitBundleTested = moduleInitBundle.capitalize()+"Bundle"
val moduleInitBundleTester = moduleInitBundleTested+"Test"
val moduleInitBundleJSONPath = "$jsonPath$moduleInitBundle/"
val moduleInitBundleFilename = moduleInitBundleJSONPath+"service.json"
val moduleInitBundleEndpoint = "$endpointBase$moduleInitBundle/"
val moduleInitBundleJSONString = serializer.writeValueAsString(mapOf(
"endpointDirectory" to moduleInitBundleEndpoint,
"\$javaClass" to "$TEST_PACKAGE.$moduleInitBundleTested"
))
File(moduleInitBundleJSONPath).mkdirs()
File(moduleInitBundleFilename).writeText(moduleInitBundleJSONString, Charsets.UTF_8)
val moduleInitAPIName = "$moduleInitName.api"
val moduleInitAPIFilename = moduleInitBundleJSONPath+moduleInitAPIName
val moduleInitAPIFile = File(moduleInitAPIFilename)
val moduleInitModName = "$moduleInitName.$modExtension"
val moduleInitModFilename = moduleInitBundleJSONPath+moduleInitModName
val moduleInitModFile = File(moduleInitModFilename)
moduleInitAPIFile.writeText(moduleInitTestString, Charsets.UTF_8)
if (moduleInitModFile.exists()) {
moduleInitModFile.delete()
}
generator.endpointDeclToModStubImpl(moduleInitAPIFilename, modExtension)
moduleInitModFile.appendText("""
${
when (modExtension) {
"mjs", "sjs" -> "true;"
"xqy" -> "fn:true()"
else -> IllegalArgumentException("unknown module extension: $modExtension")
}}
""", Charsets.UTF_8)
generator.serviceBundleToJava(moduleInitBundleFilename, javaBaseDir)
modMgr.write(
modMgr.newWriteSet()
.add(moduleInitBundleEndpoint+moduleInitAPIName, docMeta, FileHandle(moduleInitAPIFile))
.add(moduleInitBundleEndpoint+moduleInitModName, modMeta, FileHandle(moduleInitModFile))
)
val moduleInitTestingFunctions = listOf(
generateJUnitCallTest(moduleInitName, moduleInitParams, moduleInitReturn, testdefs)
)
writeJUnitRequestTest(
"$testPath$moduleInitBundleTester.java",
generateJUnitTest(moduleInitBundleTested, moduleInitBundleTester, moduleInitTestingFunctions)
)
}
}
db.release()
}
fun pickDocOther(documentNames: Array<String>, documentMax: Int, docCurr: String, i: Int
) : String {
return when (docCurr) {
"array", "object", "jsonDocument" -> "xmlDocument"
"xmlDocument" -> "jsonDocument"
else -> documentNames[if (i == documentMax) 0 else i + 1]
}
}
fun replaceFuncName(funcdef: Map<String,*>, funcName: String) : Map<String,*> {
return replaceKeyValue(funcdef, "functionName", funcName)
}
fun replaceFuncParams(funcdef: Map<String,*>, funcParams: List<Map<String,*>>) : Map<String,*> {
return replaceKeyValue(funcdef, "params", funcParams)
}
fun replaceParamValue(funcParams: List<Map<String,*>>, key: String, value: Any) : List<Map<String,*>> {
return funcParams.map{funcParam -> replaceKeyValue(funcParam, key, value)}
}
fun replaceFuncReturn(funcdef: Map<String,*>, funcReturn: Map<String,*>) : Map<String,*> {
return replaceKeyValue(funcdef, "return", funcReturn)
}
fun replaceDataType(typed: Map<String,*>, dataType: String) : Map<String,*> {
return replaceKeyValue(typed, "datatype", dataType)
}
fun replaceMultiple(typed: Map<String,*>, isMultiple: Boolean) : Map<String,*> {
return replaceKeyValue(typed, "multiple", isMultiple)
}
fun replaceKeyValue(originalMap: Map<String,*>, key: String, value: Any) : Map<String,*> {
return originalMap.mapValues{entry ->
if (entry.key === key) value else entry.value
}
}
fun uncastableAtomicType(testdefs: ObjectNode, dataType: String) : String {
return if (testdefs.withArray(dataType)[0].isBoolean) "double" else "boolean"
}
fun persistServerdef(modMgr: TextDocumentManager, endpointBase: String, funcName: String,
modMeta: DocumentMetadataHandle, funcdef: String, funcParams: List<Map<String,*>>?, modExtension: String
) {
val docIdBase = endpointBase+funcName
val apiId = "$docIdBase.api"
val moduleId = "$docIdBase.$modExtension"
val apiHandle = StringHandle(funcdef)
val moduleDoc = makeModuleDoc(docIdBase, funcParams, funcdef, modExtension)
modMgr.write(
modMgr.newWriteSet().add(apiId, modMeta, apiHandle).add(moduleId, modMeta, StringHandle(moduleDoc))
)
}
fun generateClientdef(jsonPath: String, endpointBase: String, funcName: String,
funcdef: String, funcParams: List<Map<String,*>>?, modExtension: String) {
val funcPathBase = jsonPath+funcName
val funcClientJSON = "$funcPathBase.api"
val moduleClientPath = "$funcPathBase.$modExtension"
val moduleClientDoc = makeModuleDoc(endpointBase+funcName, funcParams, funcdef, modExtension)
File(funcClientJSON).writeText(funcdef, Charsets.UTF_8)
File(moduleClientPath).writeText(moduleClientDoc, Charsets.UTF_8)
}
// TODO: call makeModuleDoc() only once per definition and use for both project filesystem and modules database
fun makeModuleDoc(docIdBase: String, funcParams: List<Map<String,*>>?, funcdef: String, modExtension: String
) : String {
val convertedParams = mapper.convertValue<ArrayNode>(funcParams, ArrayNode::class.java)
val prologSource = generator.getEndpointProlog(modExtension)
val paramSource = generator.getEndpointParamSource(atomicMap, documentMap, modExtension, convertedParams)
val paramNames = funcParams?.map{param -> param["name"] as String} ?: emptyList()
return if (modExtension === "mjs" || modExtension === "sjs") """$prologSource
$paramSource
const inspector = require('/dbf/test/testInspector.sjs');
const errorList = [];
const funcdef = ${funcdef};
let fields = {};
${paramNames.joinToString("") { paramName ->
"""fields = inspector.addField(
'${docIdBase}', fields, '${paramName}', $paramName
);
"""
}}
fields = inspector.getFields(funcdef, fields, errorList);
inspector.makeResult('${docIdBase}', funcdef, fields, errorList);
"""
else """$prologSource
$paramSource
let ${'$'}errorList := json:array()
let ${'$'}funcdef := xdmp:from-json-string('${funcdef}')
let ${'$'}fields := map:map()
${paramNames.joinToString("") { paramName ->
"""let ${'$'}fields := xdmp:apply(xdmp:function(xs:QName("addField"), "/dbf/test/testInspector.sjs"),
"$docIdBase", ${'$'}fields, "$paramName", ${'$'}${paramName}
)
"""
}}
let ${'$'}fields := xdmp:apply(xdmp:function(xs:QName("getFields"), "/dbf/test/testInspector.sjs"),
${'$'}funcdef, ${'$'}fields, ${'$'}errorList
)
return xdmp:apply(xdmp:function(xs:QName("makeResult"), "/dbf/test/testInspector.sjs"),
"$docIdBase", ${'$'}funcdef, ${'$'}fields, ${'$'}errorList
)
"""
}
fun serializeArg(paramTest: JsonNode, mappedType: String, testConstructor: String?) : String {
val text = paramTest.asText()
val argRaw =
when(mappedType) {
"String" -> "\"" + text + "\""
"Float" -> text+"F"
"float" -> text+"F"
"Long" -> text+"L"
"long" -> text+"L"
"InputStream" -> """new ByteArrayInputStream(DatatypeConverter.parseBase64Binary("$text"))"""
"Reader" -> """new StringReader("$text")"""
else ->
// TODO: binary document mapping
if (mappedType.contains('.')) "\"" + text + "\""
else text
}
return if (testConstructor === null) argRaw
else """${testConstructor}(${argRaw})"""
}
fun writeJUnitRequestTest(testingFilename: String, testingSrc: String) {
val testingFile = File(testingFilename)
testingFile.writeText(testingSrc)
}
fun generateJUnitTest(
testedClass: String, testingClass: String, funcTests: List<String>,
extraImports: String = "", extraMembers: String = ""
): String {
return """package ${TEST_PACKAGE};
// IMPORTANT: Do not edit. This file is generated.
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringReader;
import java.io.Reader;
import java.io.IOException;
import java.util.Arrays;
import java.util.stream.Stream;
import javax.xml.bind.DatatypeConverter;
import java.lang.reflect.Array;
$extraImports
import org.junit.Test;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.marklogic.client.test.dbfunction.DBFunctionTestUtil;
public class $testingClass {
$testedClass testObj = ${testedClass}.on(DBFunctionTestUtil.db);
void assertBytesStreamEqual(String testName, String[] expectedVals, Stream<byte[]> actual) throws IOException {
byte[][] actualVals = actual.toArray(size -> new byte[size][]);
assertEquals(testName, expectedVals.length, actualVals.length);
for (int i=0; i < expectedVals.length; i++) {
assertBytesEqual(testName, expectedVals[i], actualVals[i]);
}
}
void assertBytesEqual(String testName, String[] expectedVals, Stream<InputStream> actual) throws IOException {
InputStream[] actualVals = actual.toArray(size -> new InputStream[size]);
assertEquals(testName, expectedVals.length, actualVals.length);
for (int i=0; i < expectedVals.length; i++) {
assertBytesEqual(testName, expectedVals[i], actualVals[i]);
}
}
void assertBytesEqual(String testName, String expectedVal, InputStream actualVal) throws IOException {
assertTrue(testName, (actualVal != null));
byte[] expected = DatatypeConverter.parseBase64Binary(expectedVal);
byte[] actual = new byte[expected.length];
int actualLen = actualVal.read(actual);
boolean noExtraLen = (actualVal.read() == -1);
actualVal.close();
assertTrue(testName, noExtraLen);
assertBytesEqual(testName, expected, actual);
}
void assertBytesEqual(String testName, String expectedVal, byte[] actual) {
assertBytesEqual(testName, DatatypeConverter.parseBase64Binary(expectedVal), actual);
}
void assertBytesEqual(String testName, byte[] expected, byte[] actual) {
assertTrue(testName, (actual != null && actual.length != 0));
assertEquals(testName, expected.length, actual.length);
assertArrayEquals(testName, expected, actual);
}
void assertEqual(String testName, String[] expectedVals, Stream<?> actual) {
assertStringEqual(testName, expectedVals, actual.map(e -> e.toString()));
}
void assertStringEqual(String testName, String[] expectedVals, Stream<String> actual) {
String[] actualVals = actual.toArray(size -> new String[size]);
assertEquals(testName, expectedVals.length, actualVals.length);
for (int i=0; i < expectedVals.length; i++) {
assertStringEqual(testName, expectedVals[i], actualVals[i]);
}
}
void assertStringEqual(String testName, String expected, String actual) {
assertCharsEqual(testName,
expected.replaceAll(", ",",").toCharArray(),
actual.trim().replaceAll(", ",",").toCharArray()
);
}
void assertCharsEqual(String testName, String[] expectedVals, Stream<Reader> actual) throws IOException {
Reader[] actualVals = actual.toArray(size -> new Reader[size]);
assertEquals(testName, expectedVals.length, actualVals.length);
for (int i=0; i < expectedVals.length; i++) {
assertCharsEqual(testName, expectedVals[i], actualVals[i]);
}
}
void assertCharsEqual(String testName, String expectedVal, Reader actualVal) throws IOException {
assertTrue(testName, (actualVal != null));
char[] expected = expectedVal.toCharArray();
char[] actual = new char[expected.length];
actualVal.read(actual);
actualVal.close();
assertCharsEqual(testName, expected, actual);
}
void assertCharsEqual(String testName, String expected, char[] actual) {
assertCharsEqual(testName, expected.toCharArray(), actual);
}
void assertCharsEqual(String testName, char[] expected, char[] actual) {
assertTrue(testName, (actual != null && actual.length != 0));
assertEquals(testName, expected.length, actual.length);
assertArrayEquals(testName, expected, actual);
}
private <T> void assertStreamEquals(String msg, Stream<T> expected, Stream<T> actual, Class<T> as) {
assertArrayEquals(msg,
expected.toArray(size -> (T[]) Array.newInstance(as, size)),
actual.toArray(size -> (T[]) Array.newInstance(as, size))
);
}
$extraMembers
${funcTests.joinToString("\n")}
}
"""
}
fun generateJUnitCallTest(
funcName: String, funcParams: List<Map<String,*>>?, funcReturn: Map<String,*>?,
typeTests: ObjectNode, testVariant: TestVariant = TestVariant.VALUE,
expectError: Boolean = false, typeConstructors: Map<String,String>? = null,
mappedTestdefs: ObjectNode? = null
): String {
// TODO: treat NULL and EMPTY differently
val testType =
when(testVariant) {
TestVariant.NULL -> "NulledTest"
TestVariant.EMPTY -> "EmptyTest"
else -> "Test"
}
val testName = funcName+testType
val testingArgs = funcParams?.joinToString(", ") { funcParam ->
testVal(typeTests, funcParam, testVariant, typeConstructors = typeConstructors, mappedTestdefs = mappedTestdefs)
} ?: ""
val returnType = funcReturn?.get("datatype") as String?
val returnMapping = funcReturn?.get("\$javaClass") as String?
val returnKind = getDataKind(returnType, funcReturn)
val returnMultiple = funcReturn?.get("multiple") == true
val returnNullable = funcReturn?.get("nullable") == true
val returnMappedType =
if (returnType === null || returnKind === null) null
else generator.getJavaDataType(returnType, returnMapping, returnKind, returnMultiple)
val returnCustom = returnMapping !== null && returnMappedType?.contains('.') == true
val returnConstructor =
if (typeConstructors === null || !returnCustom) null
else typeConstructors[returnType]?.substringAfter(returnType+"As")
val returnAssign =
if (returnMappedType === null) ""
else if (!returnMultiple) "$returnMappedType return1 = "
else "Stream<$returnMappedType> return1 = "
val asserter =
if (expectError || testVariant != TestVariant.VALUE || returnMappedType === null || returnKind === "document")
null
else
"assertEquals"
val assertExpected =
if (testVariant != TestVariant.VALUE || returnType === null || returnMappedType === null || returnKind === null)
null
else if (returnKind === "atomic")
testVal(
typeTests, returnType, returnNullable, returnMultiple, returnMappedType, testVariant,
typeConstructors = typeConstructors, mappedTestdefs = mappedTestdefs
)
else if (returnMultiple)
typeTests.withArray(returnType).joinToString(",") { testVal -> "\"" + testVal.asText() + "\"" }
else
"\""+typeTests.withArray(returnType)[0].asText()+"\""
val assertActual =
if (asserter === null)
""
else if (returnType == "double")
"return1, 0.1);"
else if (returnType == "float")
"return1, 0.1F);"
else if (returnKind === "atomic" && returnMultiple && returnConstructor != null)
"""return1, ${returnConstructor.substringAfter("as")}.class);"""
else
"return1);"
val assertion =
if (expectError)
"""fail("no error for negative test");"""
else if (returnMappedType === null)
""
else if (testVariant != TestVariant.VALUE)
if (!returnMultiple) """assertNull("$testName", return1);"""
else if (returnKind === "atomic") """assertEquals("$testName", 0, return1.length);"""
else """assertEquals("$testName", 0, return1.count());"""
// TODO: factor out similar to parameters
else if (returnKind === "document")
if (returnType === "binaryDocument")
if (returnMultiple)
if (returnConstructor !== null)
"""assertBytesStreamEqual("$testName", new String[]{${assertExpected}}, ${returnConstructor}AsBytes(return1));"""
else
"""assertBytesEqual("$testName", new String[]{${assertExpected}}, return1);"""
else
if (returnCustom)
"""assertBytesEqual("$testName", ${assertExpected}, asBytes(return1));"""
else
"""assertBytesEqual("$testName", ${assertExpected}, return1);"""
else
if (returnMultiple)
if (returnConstructor !== null)
"""assertStringEqual("$testName", new String[]{${assertExpected}}, ${returnConstructor}AsString(return1));"""
else
"""assertCharsEqual("$testName", new String[]{${assertExpected}}, return1);"""
else
if (returnCustom)
"""assertStringEqual("$testName", ${assertExpected}, asString(return1));"""
else
"""assertCharsEqual("$testName", ${assertExpected}, return1);"""
else if (returnMultiple)
if (returnConstructor !== null)
"""assertStreamEquals("$testName", ${assertExpected}, $assertActual"""
else
"""assertStringEqual("$testName", new String[]{${assertExpected}}, $assertActual"""
else if (returnNullable && generator.getPrimitiveDataTypes().containsKey(returnType))
"""${asserter}("$testName", ${returnMappedType}.valueOf(${assertExpected}), $assertActual"""
else if (returnType == "double" || returnType == "float")
"""${asserter}("$testName", ${assertExpected}, $assertActual"""
else
"""${asserter}("$testName", (Object) ${assertExpected}, $assertActual"""
// TODO: assert read() = -1 and close()
return """
@Test
public void ${testName}() {
try {
${returnAssign}testObj.${funcName}(
$testingArgs
);
$assertion
} catch(Exception e) {
${
if (expectError) ""
else """fail(e.getClass().getSimpleName()+": "+e.getMessage());"""
}
}
}
"""
}
fun testVal(
typeTests: ObjectNode?, typedef: Map<String,*>, testVariant: TestVariant,
typeConstructors: Map<String,String>? = null, mappedTestdefs: ObjectNode? = null
) : String {
val dataType = typedef["datatype"] as String
val mapping = typedef["\$javaClass"] as String?
val dataKind = getDataKind(dataType, typedef) as String
val isMultiple = typedef["multiple"] == true
val isNullable = typedef["nullable"] == true
val mappedType = generator.getJavaDataType(dataType, mapping, dataKind, isMultiple)
return testVal(
typeTests, dataType, isNullable, isMultiple, mappedType, testVariant, typeConstructors, mappedTestdefs
)
}
fun testVal(
typeTests: ObjectNode?, dataType: String, isNullable: Boolean, isMultiple: Boolean,
mappedType: String, testVariant: TestVariant,
typeConstructors: Map<String,String>? = null, mappedTestdefs: ObjectNode? = null
) : String {
val mappedTestVals = mappedTestdefs?.withArray(mappedType)
val testValues =
if (mappedTestVals !== null && mappedTestVals.size() > 0) mappedTestVals
else typeTests?.withArray(dataType)
val testConstructor =
if (typeConstructors === null) null
else typeConstructors[dataType]
return if (testValues === null || testValues.size() == 0 || (isNullable && testVariant === TestVariant.NULL)) {
"null"
} else if (isNullable && isMultiple && testVariant === TestVariant.EMPTY) {
"""Stream.empty()"""
} else if (isMultiple) {
"""Stream.of(${testValues.joinToString(", ") { testValue ->
serializeArg(testValue, mappedType, testConstructor)
}})"""
} else {
serializeArg(testValues[0], mappedType, testConstructor)
}
}
fun getDataKind(dataType: String?, typedef: Map<String,*>?) : String? {
val dataKind = typedef?.get("dataKind")
return if (dataKind !== null) {
dataKind as String
} else if (dataType === null) {
null
} else if (dataType.endsWith("Document") || dataType == "array" || dataType == "object") {
"document"
} else {
"atomic"
}
}
| apache-2.0 | e8832f71ef1c9a6147f0973d55ff1afd | 44.291335 | 127 | 0.609409 | 4.864034 | false | true | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.