content
stringlengths 0
13M
| path
stringlengths 4
263
| contentHash
stringlengths 1
10
|
---|---|---|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.changeSignature.ui
import com.intellij.psi.PsiElement
import com.intellij.refactoring.changeSignature.ParameterTableModelItemBase
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.idea.refactoring.changeSignature.KotlinMethodDescriptor
import org.jetbrains.kotlin.idea.refactoring.changeSignature.KotlinParameterInfo
class KotlinSecondaryConstructorParameterTableModel(
methodDescriptor: KotlinMethodDescriptor,
defaultValueContext: PsiElement
) : KotlinCallableParameterTableModel(
methodDescriptor,
defaultValueContext,
NameColumn<KotlinParameterInfo, ParameterTableModelItemBase<KotlinParameterInfo>>(defaultValueContext.project),
TypeColumn<KotlinParameterInfo, ParameterTableModelItemBase<KotlinParameterInfo>>(defaultValueContext.project, KotlinFileType.INSTANCE),
DefaultValueColumn<KotlinParameterInfo, ParameterTableModelItemBase<KotlinParameterInfo>>(
defaultValueContext.project,
KotlinFileType.INSTANCE
),
DefaultParameterColumn(),
) | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/ui/KotlinSecondaryConstructorParameterTableModel.kt | 4192846588 |
// 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.intentions
import com.intellij.java.refactoring.JavaRefactoringBundle
import com.intellij.openapi.editor.Editor
import com.intellij.psi.*
import com.intellij.psi.impl.source.tree.LeafPsiElement
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.refactoring.RefactoringBundle
import com.intellij.refactoring.util.CommonRefactoringUtil
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.intentions.ConvertToScopeIntention.ScopeFunction.*
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.search.ideaExtensions.KotlinReferencesSearchParameters
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType
import org.jetbrains.kotlin.psi.psiUtil.siblings
sealed class ConvertToScopeIntention(private val scopeFunction: ScopeFunction) : SelfTargetingIntention<KtExpression>(
KtExpression::class.java,
KotlinBundle.lazyMessage("convert.to.0", scopeFunction.functionName)
) {
enum class ScopeFunction(val functionName: String, val isParameterScope: Boolean) {
ALSO(functionName = "also", isParameterScope = true),
APPLY(functionName = "apply", isParameterScope = false),
RUN(functionName = "run", isParameterScope = false),
WITH(functionName = "with", isParameterScope = false);
val receiver = if (isParameterScope) "it" else "this"
}
private data class RefactoringTargetAndItsValueExpression(
val targetElement: PsiElement,
val targetElementValue: PsiElement
)
private data class ScopedFunctionCallAndBlock(
val scopeFunctionCall: KtExpression,
val block: KtBlockExpression
)
override fun isApplicableTo(element: KtExpression, caretOffset: Int) = tryApplyTo(element, dryRun = true)
override fun applyTo(element: KtExpression, editor: Editor?) {
if (!tryApplyTo(element, dryRun = false)) {
val message = RefactoringBundle.getCannotRefactorMessage(
JavaRefactoringBundle.message("refactoring.is.not.supported.in.the.current.context", text)
)
CommonRefactoringUtil.showErrorHint(element.project, editor, message, text, null)
}
}
private fun KtExpression.tryGetExpressionToApply(referenceName: String): KtExpression? {
val childOfBlock = PsiTreeUtil.findFirstParent(this) {
it.parent is KtBlockExpression
} as? KtExpression ?: return null
return if (childOfBlock is KtProperty || childOfBlock.isTarget(referenceName)) childOfBlock else null
}
private fun tryApplyTo(element: KtExpression, dryRun: Boolean): Boolean {
val invalidElementToRefactoring = when (element) {
is KtProperty -> !element.isLocal
is KtCallExpression -> false
is KtDotQualifiedExpression -> false
else -> true
}
if (invalidElementToRefactoring) return false
val (referenceElement, referenceName) = element.tryExtractReferenceName() ?: return false
val expressionToApply = element.tryGetExpressionToApply(referenceName) ?: return false
val (firstTarget, lastTarget) = expressionToApply.collectTargetElementsRange(referenceName, greedy = !dryRun) ?: return false
val refactoringTarget = tryGetFirstElementToRefactoring(expressionToApply, firstTarget) ?: return false
if (dryRun) return true
val psiFactory = KtPsiFactory(expressionToApply)
val (scopeFunctionCall, block) = createScopeFunctionCall(
psiFactory,
refactoringTarget.targetElement
) ?: return false
replaceReference(referenceElement, refactoringTarget.targetElementValue, lastTarget, psiFactory)
block.addRange(refactoringTarget.targetElementValue, lastTarget)
if (!scopeFunction.isParameterScope) {
removeRedundantThisQualifiers(block)
}
with(firstTarget) {
parent.addBefore(scopeFunctionCall, this)
parent.deleteChildRange(this, lastTarget)
}
return true
}
private fun removeRedundantThisQualifiers(block: KtBlockExpression) {
val thisDotSomethingExpressions = block.collectDescendantsOfType<KtDotQualifiedExpression> {
it.receiverExpression is KtThisExpression && it.selectorExpression !== null
}
thisDotSomethingExpressions.forEach { thisDotSomethingExpression ->
thisDotSomethingExpression.selectorExpression?.let { selector ->
thisDotSomethingExpression.replace(selector)
}
}
}
private fun tryGetFirstElementToRefactoring(expressionToApply: KtExpression, firstTarget: PsiElement)
: RefactoringTargetAndItsValueExpression? {
val property by lazy(LazyThreadSafetyMode.NONE) { expressionToApply.prevProperty() }
val propertyOrFirst = when (scopeFunction) {
ALSO, APPLY -> property
RUN, WITH -> firstTarget
} ?: return null
val isCorrectFirstOrProperty = when (scopeFunction) {
ALSO, APPLY -> propertyOrFirst is KtProperty && propertyOrFirst.name !== null && propertyOrFirst.initializer !== null
RUN -> propertyOrFirst is KtDotQualifiedExpression
WITH -> propertyOrFirst is KtDotQualifiedExpression
}
if (!isCorrectFirstOrProperty) return null
return RefactoringTargetAndItsValueExpression(propertyOrFirst, property?.nextSibling ?: firstTarget)
}
private fun replaceReference(element: PsiElement, firstTarget: PsiElement, lastTarget: PsiElement, psiFactory: KtPsiFactory) {
val replacement by lazy(LazyThreadSafetyMode.NONE) {
if (scopeFunction.isParameterScope)
psiFactory.createSimpleName(scopeFunction.receiver)
else
psiFactory.createThisExpression()
}
val searchParameters = KotlinReferencesSearchParameters(
element, element.useScope, ignoreAccessScope = false
)
val range = PsiTreeUtil.getElementsOfRange(firstTarget, lastTarget)
ReferencesSearch.search(searchParameters)
.mapNotNull { it.element as? KtNameReferenceExpression }
.filter { reference ->
range.any { rangeElement -> PsiTreeUtil.isAncestor(rangeElement, reference, /* strict = */ true) }
}
.forEach { referenceInRange ->
referenceInRange.replace(replacement)
}
}
private fun KtExpression.tryExtractReferenceName(): Pair<PsiElement, String>? {
return when (scopeFunction) {
ALSO, APPLY -> {
val property = prevProperty()
val name = property?.name
if (name !== null) property to name else null
}
RUN, WITH -> {
val receiver = (this as? KtDotQualifiedExpression)
?.let { getLeftMostReceiverExpression() } as? KtNameReferenceExpression
val declaration = receiver?.mainReference?.resolve()
val name = receiver?.getReferencedName()
if (declaration !== null && declaration !is PsiPackage && name !== null) declaration to name else null
}
}
}
private fun KtExpression.collectTargetElementsRange(referenceName: String, greedy: Boolean): Pair<PsiElement, PsiElement>? {
return when (scopeFunction) {
ALSO, APPLY -> {
val firstTarget = this as? KtProperty ?: this.prevProperty() ?: this
val lastTargetSequence = firstTarget.collectTargetElements(referenceName, forward = true)
val lastTarget = if (firstTarget === this)
if (greedy) lastTargetSequence.lastOrNull()
else lastTargetSequence.firstOrNull()
else
if (greedy) lastTargetSequence.lastWithPersistedElementOrNull(elementShouldPersist = this)
else lastTargetSequence.firstOrNull { this === it }
if (lastTarget !== null) firstTarget to lastTarget else null
}
RUN, WITH -> {
val firstTarget = collectTargetElements(referenceName, forward = false).lastOrNull() ?: this
val lastTarget =
if (greedy) collectTargetElements(referenceName, forward = true).lastOrNull() ?: this
else this
firstTarget to lastTarget
}
}
}
private fun KtExpression.collectTargetElements(referenceName: String, forward: Boolean): Sequence<PsiElement> =
siblings(forward, withItself = false)
.filter { it !is PsiWhiteSpace && it !is PsiComment && !(it is LeafPsiElement && it.elementType == KtTokens.SEMICOLON) }
.takeWhile { it.isTarget(referenceName) }
private fun PsiElement.isTarget(referenceName: String): Boolean {
when (this) {
is KtDotQualifiedExpression -> {
val callExpr = callExpression ?: return false
if (callExpr.lambdaArguments.isNotEmpty() ||
callExpr.valueArguments.any { it.text == scopeFunction.receiver }
) return false
val leftMostReceiver = getLeftMostReceiverExpression()
if (leftMostReceiver.text != referenceName) return false
if (leftMostReceiver.mainReference?.resolve() is PsiClass) return false
}
is KtCallExpression -> {
val valueArguments = this.valueArguments
if (valueArguments.none { it.getArgumentExpression()?.text == referenceName }) return false
if (lambdaArguments.isNotEmpty() || valueArguments.any { it.text == scopeFunction.receiver }) return false
}
is KtBinaryExpression -> {
val left = this.left ?: return false
val right = this.right ?: return false
if (left !is KtDotQualifiedExpression && left !is KtCallExpression
&& right !is KtDotQualifiedExpression && right !is KtCallExpression
) return false
if ((left is KtDotQualifiedExpression || left is KtCallExpression) && !left.isTarget(referenceName)) return false
if ((right is KtDotQualifiedExpression || right is KtCallExpression) && !right.isTarget(referenceName)) return false
}
else -> return false
}
return !anyDescendantOfType<KtNameReferenceExpression> { it.text == scopeFunction.receiver }
}
private fun KtExpression.prevProperty(): KtProperty? = PsiTreeUtil.findFirstParent(this) {
it.parent is KtBlockExpression
}
?.siblings(forward = false, withItself = true)
?.firstOrNull { it is KtProperty && it.isLocal } as? KtProperty
private fun createScopeFunctionCall(factory: KtPsiFactory, element: PsiElement): ScopedFunctionCallAndBlock? {
val scopeFunctionName = scopeFunction.functionName
val (scopeFunctionCall, callExpression) = when (scopeFunction) {
ALSO, APPLY -> {
if (element !is KtProperty) return null
val propertyName = element.name ?: return null
val initializer = element.initializer ?: return null
val initializerPattern = when (initializer) {
is KtDotQualifiedExpression, is KtCallExpression, is KtConstantExpression, is KtParenthesizedExpression -> initializer.text
else -> "(${initializer.text})"
}
val property = factory.createProperty(
name = propertyName,
type = element.typeReference?.text,
isVar = element.isVar,
initializer = "$initializerPattern.$scopeFunctionName {}"
)
val callExpression = (property.initializer as? KtDotQualifiedExpression)?.callExpression ?: return null
property to callExpression
}
RUN -> {
if (element !is KtDotQualifiedExpression) return null
val scopeFunctionCall = factory.createExpressionByPattern(
"$0.$scopeFunctionName {}",
element.getLeftMostReceiverExpression()
) as? KtQualifiedExpression ?: return null
val callExpression = scopeFunctionCall.callExpression ?: return null
scopeFunctionCall to callExpression
}
WITH -> {
if (element !is KtDotQualifiedExpression) return null
val scopeFunctionCall = factory.createExpressionByPattern(
"$scopeFunctionName($0) {}",
element.getLeftMostReceiverExpression()
) as? KtCallExpression ?: return null
scopeFunctionCall to scopeFunctionCall
}
}
val body = callExpression.lambdaArguments
.firstOrNull()
?.getLambdaExpression()
?.bodyExpression
?: return null
return ScopedFunctionCallAndBlock(scopeFunctionCall, body)
}
}
class ConvertToAlsoIntention : ConvertToScopeIntention(ALSO)
class ConvertToApplyIntention : ConvertToScopeIntention(APPLY)
class ConvertToRunIntention : ConvertToScopeIntention(RUN)
class ConvertToWithIntention : ConvertToScopeIntention(WITH)
| plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertToScopeIntention.kt | 2955122979 |
package org.jetbrains.completion.full.line.local
import org.junit.jupiter.api.Assertions.assertFalse
class MavenMetadataTest : XmlSerializationTest() {
fun `test encode & decode MavenMetadata`() {
val schema = MavenMetadata(
Versioning(
"a.b.c",
"c.b.a",
listOf("p", "0"),
987654321
)
)
val xmlString = schema.fromPattern()
val models = decodeFromXml<MavenMetadata>(xmlString)
assertEqualsWithoutIndent(schema, models)
val raw = encodeToXml(schema)
// Check that group and artifact are not in string and add them, because pattern contains them.
val group = xml("<groupId>ml.intellij</groupId>")
val art = xml("<artifactId>completion-engine</artifactId>")
assertFalse(raw.contains(group), "Group was added by serialization")
assertFalse(raw.contains(art), "Artifact was added by serialization")
val fixed = encodeToXml(schema).lines().toMutableList()
.apply { addAll(1, listOf(group, art)) }
.joinToString("\n")
assertEqualsWithoutIndent(xmlString, fixed)
}
fun `test pattern in test`() {
val schema = MavenMetadata(
Versioning(
"1.2.3",
"3.2.1",
listOf("1a", "2b", "3c"),
1234567890
)
)
val expected = xml(
"""
<metadata>
<groupId>ml.intellij</groupId>
<artifactId>completion-engine</artifactId>
<versioning>
<latest>1.2.3</latest>
<release>3.2.1</release>
<versions>
<version>1a</version>
<version>2b</version>
<version>3c</version>
</versions>
<lastUpdated>1234567890</lastUpdated>
</versioning>
</metadata>
""".trimIndent()
)
val xml = schema.fromPattern()
assertEqualsWithoutIndent(expected, xml)
}
private fun MavenMetadata.fromPattern(): String {
val versions = versioning.versions.joinToString("\n") {
xml("<version>$it</version>")
}
return xml(
"""
<metadata>
<groupId>ml.intellij</groupId>
<artifactId>completion-engine</artifactId>
<versioning>
<latest>${versioning.latest}</latest>
<release>${versioning.release}</release>
<versions>
${versions}
</versions>
<lastUpdated>${versioning.lastUpdated}</lastUpdated>
</versioning>
</metadata>
""".trimIndent()
)
}
}
| plugins/full-line/test/org/jetbrains/completion/full/line/local/MavenMetadataTest.kt | 852766900 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiWhiteSpace
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.psiUtil.getNextSiblingIgnoringWhitespace
import org.jetbrains.kotlin.psi.psiUtil.getPrevSiblingIgnoringWhitespace
class ConvertLineCommentToBlockCommentIntention : SelfTargetingIntention<PsiComment>(
PsiComment::class.java,
KotlinBundle.lazyMessage("replace.with.block.comment")
) {
override fun isApplicableTo(element: PsiComment, caretOffset: Int): Boolean = element.isEndOfLineComment()
override fun applyTo(element: PsiComment, editor: Editor?) {
val project = element.project
var firstComment = element
while (true) {
firstComment = firstComment.prevComment() ?: break
}
val indent = (firstComment.prevSibling as? PsiWhiteSpace)?.text?.reversed()?.takeWhile { it == ' ' || it == '\t' } ?: ""
val comments = mutableListOf(firstComment)
var nextComment = firstComment
while (true) {
nextComment = nextComment.nextComment() ?: break
comments.add(nextComment)
}
val blockComment = if (comments.size == 1)
"/* ${comments.first().commentText()} */"
else
comments.joinToString(separator = "\n", prefix = "/*\n", postfix = "\n$indent*/") {
"$indent${it.commentText()}"
}
comments.drop(1).forEach {
(it.prevSibling as? PsiWhiteSpace)?.delete()
it.delete()
}
firstComment.replace(KtPsiFactory(project).createComment(blockComment))
}
}
private fun PsiElement.isEndOfLineComment() = node.elementType == KtTokens.EOL_COMMENT
private fun PsiComment.commentText() = text.substring(2).replace("/*", "/ *").replace("*/", "* /").trim()
private fun PsiComment.nextComment(): PsiComment? = (getNextSiblingIgnoringWhitespace() as? PsiComment)?.takeIf { it.isEndOfLineComment() }
private fun PsiComment.prevComment(): PsiComment? = (getPrevSiblingIgnoringWhitespace() as? PsiComment)?.takeIf { it.isEndOfLineComment() }
| plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertLineCommentToBlockCommentIntention.kt | 1223415920 |
// FIR_COMPARISON
package test
class T
<selection>fun foo(t: test.T) {}</selection>
| plugins/kotlin/idea/tests/testData/shortenRefsFir/types/ParameterType.kt | 1582905223 |
package test
import test.Foo<caret>
class Foo
fun main() {
Foo()
} | plugins/kotlin/idea/tests/testData/intentions/introduceImportAlias/inImport.kt | 2200037875 |
// FLOW: OUT
open class A() {
open val foo = 1
}
open class B(override val foo: Int) : A()
class C : B(1) {
override val foo = <caret>3
}
fun test(a: A, b: B, c: C) {
val x = a.foo
val y = b.foo
val z = c.foo
}
| plugins/kotlin/idea/tests/testData/slicer/outflow/overridingParameter.kt | 588583251 |
// 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 com.intellij.util.io.impl
import com.intellij.openapi.util.JDOMUtil
import com.intellij.util.io.FileTextMatcher
object FileTextMatchers {
val exact = object : FileTextMatcher {
override fun matches(actualText: String, expectedText: String): Boolean =
actualText == expectedText
}
val lines = object : FileTextMatcher {
override fun matches(actualText: String, expectedText: String): Boolean =
actualText.lines() == expectedText.lines()
}
val ignoreBlankLines = object : FileTextMatcher {
override fun matches(actualText: String, expectedText: String): Boolean =
actualText.lines().filter { it.isNotBlank() } == expectedText.lines().filter { it.isNotBlank() }
}
val ignoreXmlFormatting = object : FileTextMatcher {
override fun matches(actualText: String, expectedText: String): Boolean {
val trimmed = expectedText.trim()
if (trimmed.startsWith('<') && trimmed.endsWith('>')) {
return JDOMUtil.areElementsEqual(JDOMUtil.load(actualText), JDOMUtil.load(expectedText))
}
return actualText == expectedText
}
}
}
| platform/testFramework/src/com/intellij/util/io/impl/FileTextMatchers.kt | 1066727489 |
// WITH_STDLIB
fun foo(list: List<String>): Int? {
var index = 0
<caret>for (s in list) {
val x = s.length * index
index++
if (x > 0) return x
}
return null
} | plugins/kotlin/idea/tests/testData/intentions/useWithIndex/simple.kt | 2381664145 |
package org.ccci.gto.android.common.util.xmlpull
import org.xmlpull.v1.XmlPullParser
/**
* Skip the current XML tag (and all of it's children)
*/
fun XmlPullParser.skipTag() {
require(XmlPullParser.START_TAG, null, null)
// loop until we process all nested tags
var depth = 1
while (depth > 0) {
when (next()) {
XmlPullParser.START_TAG -> depth++
XmlPullParser.END_TAG -> depth--
}
}
}
| gto-support-util/src/main/java/org/ccci/gto/android/common/util/xmlpull/XmlPullParser.kt | 3584999120 |
package onGetter
fun main(args: Array<String>) {
val a = A(1)
// EXPRESSION: prop
// RESULT: 1: I
// STEP_INTO: 1
//Breakpoint!
a.prop
}
class A(val prop: Int) | plugins/kotlin/jvm-debugger/test/testData/evaluation/singleBreakpoint/onGetter.kt | 1415288383 |
/*
*
* * Apache License
* *
* * Copyright [2017] Sinyuk
* *
* * 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.sinyuk.fanfou.ui
import android.support.v4.view.ViewPager.PageTransformer
import android.view.View
abstract class ABaseTransformer : PageTransformer {
/**
* Indicates if the default animations of the view pager should be used.
*
* @return
*/
protected val isPagingEnabled: Boolean
get() = false
/**
* Called each [.transformPage].
*
* @param page
* Apply the transformation to this page
* @param position
* Position of page relative to the current front-and-center position of the pager. 0 is front and
* center. 1 is one full page position to the right, and -1 is one page position to the left.
*/
protected abstract fun onTransform(page: View, position: Float)
/**
* Apply a property transformation to the given page. For most use cases, this method should not be overridden.
* Instead use [.transformPage] to perform typical transformations.
*
* @param page
* Apply the transformation to this page
* @param position
* Position of page relative to the current front-and-center position of the pager. 0 is front and
* center. 1 is one full page position to the right, and -1 is one page position to the left.
*/
override fun transformPage(page: View, position: Float) {
onPreTransform(page, position)
onTransform(page, position)
onPostTransform(page, position)
}
/**
* If the position offset of a fragment is less than negative one or greater than one, returning true will set the
* fragment alpha to 0f. Otherwise fragment alpha is always defaulted to 1f.
*
* @return
*/
protected fun hideOffscreenPages(): Boolean {
return true
}
/**
* Called each [.transformPage] before {[.onTransform].
*
*
* The default implementation attempts to reset all view properties. This is useful when toggling transforms that do
* not modify the same page properties. For instance changing from a transformation that applies rotation to a
* transformation that fades can inadvertently leave a fragment stuck with a rotation or with some degree of applied
* alpha.
*
* @param page
* Apply the transformation to this page
* @param position
* Position of page relative to the current front-and-center position of the pager. 0 is front and
* center. 1 is one full page position to the right, and -1 is one page position to the left.
*/
protected fun onPreTransform(page: View, position: Float) {
val width = page.width.toFloat()
page.rotationX = 0f
page.rotationY = 0f
page.rotation = 0f
page.scaleX = 1f
page.scaleY = 1f
page.pivotX = 0f
page.pivotY = 0f
page.translationY = 0f
page.translationX = if (isPagingEnabled) 0f else -width * position
if (hideOffscreenPages()) {
page.alpha = if (position <= -1f || position >= 1f) 0f else 1f
page.isEnabled = false
} else {
page.isEnabled = true
page.alpha = 1f
}
}
/**
* Called each [.transformPage] after [.onTransform].
*
* @param page
* Apply the transformation to this page
* @param position
* Position of page relative to the current front-and-center position of the pager. 0 is front and
* center. 1 is one full page position to the right, and -1 is one page position to the left.
*/
protected fun onPostTransform(page: View, position: Float) {}
companion object {
/**
* Same as [Math.min] without double casting, zero closest to infinity handling, or NaN support.
*
* @param val
* @param min
* @return
*/
fun min(value: Float, min: Float) = if (value < min) min else value
}
} | presentation/src/main/java/com/sinyuk/fanfou/ui/ABaseTransformer.kt | 3855599326 |
/*
* Copyright 2017 The Hyve
*
* 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.radarcns.detail
import android.app.AlertDialog
import android.content.Context
import android.content.SharedPreferences
import android.text.InputType
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import org.radarbase.android.MainActivity
import org.radarbase.android.source.BaseSourceState
import org.radarbase.android.source.SourceProvider
import org.radarbase.android.source.SourceServiceConnection
import org.radarbase.android.source.SourceStatusListener
import org.radarbase.android.util.Boast
import org.radarbase.android.util.ChangeRunner
import org.radarcns.detail.MainActivityViewImpl.Companion.truncate
import org.slf4j.LoggerFactory
/**
* Displays a single source row.
*/
class SourceRowView internal constructor(
private val mainActivity: MainActivity,
provider: SourceProvider<*>, root: ViewGroup
) {
private val connection: SourceServiceConnection<*> = provider.connection
private val mStatusIcon: View
private val mBatteryLabel: ImageView
private val sourceNameLabel: TextView
private val devicePreferences: SharedPreferences
private val filter = ChangeRunner("")
private var sourceState: BaseSourceState? = null
private var sourceName: String? = null
private val batteryLevelCache = ChangeRunner<Float>()
private val sourceNameCache = ChangeRunner<String>()
private val statusCache = ChangeRunner<SourceStatusListener.Status>()
private val splitRegex = this.mainActivity.getString(R.string.filter_split_regex).toRegex()
init {
devicePreferences = this.mainActivity.getSharedPreferences("device." + connection.serviceClassName, Context.MODE_PRIVATE)
logger.info("Creating source row for provider {} and connection {}", provider, connection)
val inflater = this.mainActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
inflater.inflate(R.layout.activity_overview_source_row, root)
(root.getChildAt(root.childCount - 1) as TableRow).apply {
mStatusIcon = findViewById(R.id.status_icon)
sourceNameLabel = findViewById(R.id.sourceNameLabel)
mBatteryLabel = findViewById(R.id.batteryStatusLabel)
findViewById<Button>(R.id.filterSourceButton).apply {
if (provider.isFilterable) {
setOnClickListener { dialogFilterSource() }
isEnabled = true
}
text = provider.displayName
}
findViewById<View>(R.id.refreshButton)
.setOnClickListener { reconnectSource() }
}
setFilter(devicePreferences.getString("filter", "") ?: "")
}
private fun dialogFilterSource() {
val input = EditText(mainActivity).apply {
inputType = InputType.TYPE_CLASS_TEXT
setText(filter.value)
}
AlertDialog.Builder(this.mainActivity).apply {
setTitle(R.string.filter_title)
setPositiveButton(R.string.ok) { _, _ -> setFilter(input.text.toString().trim { it <= ' ' }) }
setNegativeButton(R.string.cancel, null)
setView(LinearLayout(mainActivity).apply {
orientation = LinearLayout.VERTICAL
setPadding(70, 0, 70, 0)
// Label
addView(TextView(mainActivity).apply {
setText(R.string.filter_help_label)
})
addView(input)
})
}.show()
}
private fun setFilter(newValue: String) {
filter.applyIfChanged(newValue) {
devicePreferences.edit()
.putString("filter", it)
.apply()
val allowed = it.split(splitRegex)
logger.info("setting source filter {}", allowed)
mainActivity.radarService?.setAllowedSourceIds(connection, allowed)
}
}
private fun reconnectSource() {
try {
// will restart scanning after disconnect
if (connection.isRecording) {
connection.stopRecording()
}
} catch (iobe: IndexOutOfBoundsException) {
Boast.makeText(this.mainActivity, "Could not restart scanning, there is no valid row index associated with this button.", Toast.LENGTH_LONG).show()
logger.warn(iobe.message)
}
}
fun update() {
sourceState = connection.sourceState
sourceName = when (sourceState?.status) {
SourceStatusListener.Status.CONNECTED,
SourceStatusListener.Status.CONNECTING -> connection.sourceName
?.replace("Empatica", "")
?.trim { c -> c <= ' ' }
else -> null
}
}
fun display() {
updateBattery()
updateSourceName()
updateSourceStatus()
}
private fun updateSourceStatus() {
statusCache.applyIfChanged(sourceState?.status ?: SourceStatusListener.Status.DISCONNECTED) { status ->
logger.info("Source status is {}", status)
mStatusIcon.setBackgroundResource(when(status) {
SourceStatusListener.Status.CONNECTED -> R.drawable.status_connected
SourceStatusListener.Status.DISCONNECTED -> R.drawable.status_disconnected
SourceStatusListener.Status.READY -> R.drawable.status_searching
SourceStatusListener.Status.CONNECTING -> R.drawable.status_searching
else -> sourceStatusIconDefault
})
}
}
private fun updateBattery() {
batteryLevelCache.applyIfChanged(sourceState?.batteryLevel ?: Float.NaN) {
mBatteryLabel.setImageResource(when {
it.isNaN() -> R.drawable.ic_battery_unknown
it < 0.1 -> R.drawable.ic_battery_empty
it < 0.3 -> R.drawable.ic_battery_low
it < 0.6 -> R.drawable.ic_battery_50
it < 0.85 -> R.drawable.ic_battery_80
else -> R.drawable.ic_battery_full
})
}
}
private fun updateSourceName() {
// \u2014 == —
sourceNameCache.applyIfChanged(sourceName ?: "\u2014") {
sourceNameLabel.text = it.truncate(MAX_UI_SOURCE_NAME_LENGTH)
}
}
companion object {
private val logger = LoggerFactory.getLogger(SourceRowView::class.java)
private const val MAX_UI_SOURCE_NAME_LENGTH = 10
private const val sourceStatusIconDefault = R.drawable.status_searching
}
}
| app/src/main/java/org/radarcns/detail/SourceRowView.kt | 4145335182 |
package net.simno.dmach.db
import android.content.Context
import androidx.room.Room
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import kotlinx.coroutines.runBlocking
import net.simno.dmach.data.defaultPatch
import net.simno.dmach.db.PatchRepository.Companion.toEntity
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object DbModule {
@Provides
@Singleton
fun providePatchDatabase(@ApplicationContext context: Context): PatchDatabase {
val db = Room
.databaseBuilder(context, PatchDatabase::class.java, PatchDatabase.NAME)
.addMigrations(PatchDatabase.MIGRATION_2_3)
.fallbackToDestructiveMigration()
.build()
val dao = db.patchDao()
runBlocking {
if (dao.count() == 0) {
val defaultPatch = defaultPatch()
dao.insertPatch(defaultPatch.toEntity(defaultPatch.title))
}
}
return db
}
@Provides
@Singleton
fun providePatchRepository(patchDatabase: PatchDatabase): PatchRepository {
return PatchRepository(patchDatabase.patchDao())
}
}
| app/src/main/java/net/simno/dmach/db/DbModule.kt | 1852325460 |
package bj.vinylbrowser.order
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import bj.vinylbrowser.R
import bj.vinylbrowser.common.BaseController
import bj.vinylbrowser.main.MainActivity
import bj.vinylbrowser.main.MainComponent
import bj.vinylbrowser.utils.analytics.AnalyticsTracker
import kotlinx.android.synthetic.main.controller_order.view.*
import javax.inject.Inject
/**
* Created by Josh Laird on 30/05/2017.
*/
class OrderController(val id: String) : BaseController(), OrderContract.View {
@Inject lateinit var presenter: OrderPresenter
@Inject lateinit var tracker: AnalyticsTracker
@Inject lateinit var epxController: OrderEpxController
constructor(args: Bundle) : this(args.getString("id"))
override fun setupComponent(mainComponent: MainComponent) {
mainComponent
.orderComponentBuilder()
.orderModule(OrderModule(this))
.build()
.inject(this)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup): View {
setupComponent((activity as MainActivity).mainComponent)
val view = inflater.inflate(R.layout.controller_order, container, false)
setupToolbar(view.toolbar, id)
setupRecyclerView(view.recyclerView, epxController)
presenter.fetchOrderDetails(id)
return view
}
override fun onAttach(view: View) {
super.onAttach(view)
tracker.send(applicationContext!!.getString(R.string.order_activity), applicationContext!!.getString(R.string.order_activity), applicationContext!!.getString(R.string.loaded), "onResume", "1")
}
override fun retry() {
tracker.send(applicationContext!!.getString(R.string.order_activity), applicationContext!!.getString(R.string.order_activity), applicationContext!!.getString(R.string.clicked), "retry", "1")
presenter.fetchOrderDetails(id)
}
} | app/src/main/java/bj/vinylbrowser/order/OrderController.kt | 1641243675 |
package com.zwq65.unity.algorithm.dataStructures
/**
* ================================================
*
* Created by NIRVANA on 2020/6/17.
* Contact with <[email protected]>
* ================================================
*/
class FixedCapacityStackOfStrings(capacity: Int) {
private val s: Array<String?> = arrayOfNulls(capacity)
private var N = 0
val isEmpty: Boolean
get() = N == 0
fun push(item: String?) {
s[N++] = item
}
fun pop(): String? {
return s[--N]
}
} | app/src/test/java/com/zwq65/unity/algorithm/dataStructures/FixedCapacityStackOfStrings.kt | 3857096610 |
package org.maxur.mserv.core.command
/** The Command with some Application Logic */
abstract class Command {
private val events = ArrayList<Event>()
/** Execute command */
fun execute(): List<Event> {
run()
return events
}
protected fun post(event: Event) {
this.events.add(event)
}
protected fun post(events: List<Event>) {
this.events.addAll(events)
}
protected abstract fun run()
} | maxur-mserv-core/src/main/kotlin/org/maxur/mserv/core/command/Command.kt | 2507435585 |
package ch.rmy.android.http_shortcuts.data.domains.shortcuts
import ch.rmy.android.framework.data.BaseRepository
import ch.rmy.android.framework.data.RealmFactory
import ch.rmy.android.framework.data.RealmTransactionContext
import ch.rmy.android.framework.extensions.detachFromRealm
import ch.rmy.android.framework.extensions.swap
import ch.rmy.android.framework.utils.UUIDUtils.newUUID
import ch.rmy.android.http_shortcuts.data.domains.categories.CategoryId
import ch.rmy.android.http_shortcuts.data.domains.getBase
import ch.rmy.android.http_shortcuts.data.domains.getCategoryById
import ch.rmy.android.http_shortcuts.data.domains.getShortcutById
import ch.rmy.android.http_shortcuts.data.domains.getShortcutByNameOrId
import ch.rmy.android.http_shortcuts.data.domains.getTemporaryShortcut
import ch.rmy.android.http_shortcuts.data.models.ShortcutModel
import ch.rmy.android.http_shortcuts.icons.ShortcutIcon
import io.realm.kotlin.deleteFromRealm
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import javax.inject.Inject
class ShortcutRepository
@Inject
constructor(
realmFactory: RealmFactory,
) : BaseRepository(realmFactory) {
suspend fun getShortcutById(shortcutId: ShortcutId): ShortcutModel =
query {
getShortcutById(shortcutId)
}
.first()
suspend fun getShortcutsByIds(shortcutIds: Collection<ShortcutId>): List<ShortcutModel> =
queryItem {
getBase()
}
.shortcuts.filter { it.id in shortcutIds }
suspend fun getShortcutByNameOrId(shortcutNameOrId: ShortcutNameOrId): ShortcutModel =
queryItem {
getShortcutByNameOrId(shortcutNameOrId)
}
fun getObservableShortcuts(): Flow<List<ShortcutModel>> =
observeList {
getBase().findFirst()!!.categories
}
.map { categories ->
categories.flatMap { category ->
category.shortcuts
}
}
suspend fun getShortcuts(): List<ShortcutModel> =
queryItem {
getBase()
}
.shortcuts
suspend fun moveShortcutToCategory(shortcutId: ShortcutId, targetCategoryId: CategoryId) {
commitTransaction {
moveShortcut(shortcutId, targetCategoryId = targetCategoryId)
}
}
suspend fun swapShortcutPositions(categoryId: CategoryId, shortcutId1: ShortcutId, shortcutId2: ShortcutId) {
commitTransaction {
getCategoryById(categoryId)
.findFirst()
?.shortcuts
?.swap(shortcutId1, shortcutId2) { id }
}
}
private fun RealmTransactionContext.moveShortcut(shortcutId: ShortcutId, targetPosition: Int? = null, targetCategoryId: CategoryId? = null) {
val shortcut = getShortcutById(shortcutId)
.findFirst() ?: return
val categories = getBase()
.findFirst()
?.categories ?: return
val targetCategory = if (targetCategoryId != null) {
getCategoryById(targetCategoryId)
.findFirst()
} else {
categories.first { category -> category.shortcuts.any { it.id == shortcutId } }
} ?: return
for (category in categories) {
category.shortcuts.remove(shortcut)
}
if (targetPosition != null) {
targetCategory.shortcuts.add(targetPosition, shortcut)
} else {
targetCategory.shortcuts.add(shortcut)
}
}
suspend fun duplicateShortcut(shortcutId: ShortcutId, newName: String, newPosition: Int?, categoryId: CategoryId) {
commitTransaction {
val shortcut = getShortcutById(shortcutId)
.findFirst()
?: return@commitTransaction
val newShortcut = copyShortcut(shortcut, newUUID())
newShortcut.name = newName
moveShortcut(newShortcut.id, newPosition, categoryId)
}
}
suspend fun createTemporaryShortcutFromShortcut(shortcutId: ShortcutId) {
commitTransaction {
val shortcut = getShortcutById(shortcutId)
.findFirst()!!
copyShortcut(shortcut, ShortcutModel.TEMPORARY_ID)
}
}
suspend fun copyTemporaryShortcutToShortcut(shortcutId: ShortcutId, categoryId: CategoryId?) {
commitTransaction {
val temporaryShortcut = getTemporaryShortcut()
.findFirst() ?: return@commitTransaction
val shortcut = copyShortcut(temporaryShortcut, shortcutId)
if (categoryId != null) {
val category = getCategoryById(categoryId)
.findFirst()
?: return@commitTransaction
if (category.shortcuts.none { it.id == shortcutId }) {
category.shortcuts.add(shortcut)
}
}
}
}
private fun RealmTransactionContext.copyShortcut(sourceShortcut: ShortcutModel, targetShortcutId: ShortcutId): ShortcutModel =
sourceShortcut.detachFromRealm()
.apply {
id = targetShortcutId
parameters.forEach { parameter ->
parameter.id = newUUID()
}
headers.forEach { header ->
header.id = newUUID()
}
}
.let(::copyOrUpdate)
suspend fun deleteShortcut(shortcutId: ShortcutId) {
commitTransaction {
getShortcutById(shortcutId)
.findFirst()
?.apply {
headers.deleteAllFromRealm()
parameters.deleteAllFromRealm()
responseHandling?.deleteFromRealm()
deleteFromRealm()
}
}
}
suspend fun setIcon(shortcutId: ShortcutId, icon: ShortcutIcon) {
commitTransaction {
getShortcutById(shortcutId)
.findFirst()
?.icon = icon
}
}
suspend fun setName(shortcutId: ShortcutId, name: String) {
commitTransaction {
getShortcutById(shortcutId)
.findFirst()
?.name = name
}
}
suspend fun setDescription(shortcutId: ShortcutId, description: String) {
commitTransaction {
getShortcutById(shortcutId)
.findFirst()
?.description = description
}
}
}
| HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/data/domains/shortcuts/ShortcutRepository.kt | 3827139163 |
// GENERATED
package com.fkorotkov.kubernetes.autoscaling.v2beta2
import io.fabric8.kubernetes.api.model.autoscaling.v2beta2.ContainerResourceMetricSource as v2beta2_ContainerResourceMetricSource
import io.fabric8.kubernetes.api.model.autoscaling.v2beta2.ContainerResourceMetricStatus as v2beta2_ContainerResourceMetricStatus
import io.fabric8.kubernetes.api.model.autoscaling.v2beta2.MetricSpec as v2beta2_MetricSpec
import io.fabric8.kubernetes.api.model.autoscaling.v2beta2.MetricStatus as v2beta2_MetricStatus
fun v2beta2_MetricSpec.`containerResource`(block: v2beta2_ContainerResourceMetricSource.() -> Unit = {}) {
if(this.`containerResource` == null) {
this.`containerResource` = v2beta2_ContainerResourceMetricSource()
}
this.`containerResource`.block()
}
fun v2beta2_MetricStatus.`containerResource`(block: v2beta2_ContainerResourceMetricStatus.() -> Unit = {}) {
if(this.`containerResource` == null) {
this.`containerResource` = v2beta2_ContainerResourceMetricStatus()
}
this.`containerResource`.block()
}
| DSLs/kubernetes/dsl/src/main/kotlin-gen/com/fkorotkov/kubernetes/autoscaling/v2beta2/containerResource.kt | 1708384860 |
package com.sksamuel.kotest.matchers
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.matchers.ints.between
import io.kotest.core.spec.style.StringSpec
import io.kotest.matchers.and
import io.kotest.matchers.or
import io.kotest.matchers.shouldBe
class LogicalMatchOperatorsTest : StringSpec({
"and should pass if both tests pass" {
1 shouldBe (between(0, 2) and between(1, 3))
}
"and should fail if first test fails" {
shouldThrow<AssertionError> {
1 shouldBe (between(2, 3) and between(1, 3))
}
}
"and should fail if second test fails" {
shouldThrow<AssertionError> {
1 shouldBe (between(0, 3) and between(4, 5))
}
}
"or should pass if both tests pass" {
1 shouldBe (between(0, 2) or between(0, 3))
}
"or should pass if first test fails and second passes" {
1 shouldBe (between(2, 3) or between(1, 3))
}
"or should pass if first test passes and second fails" {
1 shouldBe (between(2, 3) or between(1, 3))
}
"or should fail if both tests fail" {
shouldThrow<AssertionError> {
1 shouldBe (between(2, 3) or between(4, 5))
}
}
"should support multiple nested clauses" {
1 shouldBe ((between(1, 2) and between(1,
4)) or between(4, 5))
1 shouldBe ((between(5, 6) and between(7,
8)) or between(1, 5))
}
})
| kotest-assertions/kotest-assertions-core/src/jvmTest/kotlin/com/sksamuel/kotest/matchers/LogicalMatchOperatorsTest.kt | 453487651 |
package com.dreampany.framework.misc
import io.reactivex.Scheduler
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import javax.inject.Inject
/**
* Created by Hawladar Roman on 5/22/2018.
* BJIT Group
* [email protected]
*/
class RxFacade @Inject constructor() {
fun io(): Scheduler {
return Schedulers.io()
}
fun compute(): Scheduler {
return Schedulers.computation()
}
fun ui(): Scheduler {
return AndroidSchedulers.mainThread()
}
} | frame/src/main/kotlin/com/dreampany/framework/misc/RxFacade.kt | 956806129 |
package io.sentry.android.core
import android.Manifest
import android.content.Context
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import io.sentry.android.core.util.Permissions
import kotlin.test.BeforeTest
import kotlin.test.Test
import kotlin.test.assertNotNull
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class PermissionsTest {
private lateinit var context: Context
@BeforeTest
fun `set up`() {
context = ApplicationProvider.getApplicationContext()
}
@Test
fun `isConnected won't throw exception`() {
assertNotNull(Permissions.hasPermission(context, Manifest.permission.ACCESS_NETWORK_STATE))
}
}
| sentry-android-core/src/test/java/io/sentry/android/core/PermissionsTest.kt | 3618811276 |
package com.byoutline.secretsauce.utils
import android.Manifest
import android.annotation.SuppressLint
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import androidx.databinding.ObservableBoolean
import android.net.ConnectivityManager
import android.os.Build
import androidx.core.content.ContextCompat
import com.byoutline.secretsauce.lifecycle.AttachableViewModel
/**
* Transforms Android broadcasts into [android.databinding.ObservableBoolean].
* @author Sebastian Kacprzak <nait at naitbit.com>
*/
class NetworkChangeReceiver
(
private val connectivityManager: ConnectivityManager,
val connectedOrConnecting: ObservableBoolean = ObservableBoolean()
) : BroadcastReceiver() {
private var context: Context? = null
override fun onReceive(context: Context, intent: Intent) {
connectedOrConnecting.set(connected())
}
@SuppressLint("MissingPermission")
fun connected(): Boolean {
val ctx = context ?: return true
if (Build.VERSION.SDK_INT >= 23 && ContextCompat.checkSelfPermission(
ctx,
Manifest.permission.ACCESS_NETWORK_STATE
) != PackageManager.PERMISSION_GRANTED) {
LogUtils.LOGW(TAG, "No permission to read connection state, returning connected=true")
return true
}
val activeNetInfo = connectivityManager.activeNetworkInfo
return activeNetInfo != null && activeNetInfo.isConnectedOrConnecting
}
fun register(context: Context) {
this.context = context
context.registerReceiver(
this,
IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)
)
}
fun unregister(context: Context) {
context.unregisterReceiver(this)
this.context = null
}
companion object {
private val TAG = LogUtils.internalMakeLogTag(NetworkChangeReceiver::class.java)
}
}
class NetworkChangeViewModel(private val receiver: NetworkChangeReceiver) : AttachableViewModel<Context>() {
val connectedOrConnecting = receiver.connectedOrConnecting
override fun onAttach(view: Context) {
receiver.register(view)
super.onAttach(view)
registerDetachAction { receiver.unregister(view) }
}
} | SecretSauce/src/main/java/com/byoutline/secretsauce/utils/NetworkChangeReceiver.kt | 3006297748 |
/*
* Copyright 2016 lizhaotailang
*
* 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.marktony.zhihudaily.data
import android.annotation.SuppressLint
import android.arch.persistence.room.ColumnInfo
import android.arch.persistence.room.Entity
import android.arch.persistence.room.PrimaryKey
import android.arch.persistence.room.TypeConverters
import android.os.Parcelable
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
import com.marktony.zhihudaily.database.converter.StringTypeConverter
import kotlinx.android.parcel.Parcelize
@Entity(tableName = "zhihu_daily_content")
@TypeConverters(StringTypeConverter::class)
@Parcelize
@SuppressLint("ParcelCreator")
data class ZhihuDailyContent(
@ColumnInfo(name = "body")
@Expose
@SerializedName("body")
val body: String,
@ColumnInfo(name = "image_source")
@Expose
@SerializedName("image_source")
val imageSource: String,
@ColumnInfo(name = "title")
@Expose
@SerializedName("title")
val title: String,
@ColumnInfo(name = "image")
@Expose
@SerializedName("image")
val image: String,
@ColumnInfo(name = "share_url")
@Expose
@SerializedName("share_url")
val shareUrl: String,
@ColumnInfo(name = "js")
@Expose
@SerializedName("js")
val js: List<String>,
@Expose
@SerializedName("ga_prefix")
val gaPrefix: String,
@ColumnInfo(name = "images")
@Expose
@SerializedName("images")
val images: List<String>,
@ColumnInfo(name = "type")
@Expose
@SerializedName("type")
val type: Int,
@PrimaryKey
@ColumnInfo(name = "id")
@Expose
@SerializedName("id")
val id: Int = 0,
@ColumnInfo(name = "css")
@Expose
@SerializedName("css")
val css: List<String>
) : Parcelable | app/src/main/java/com/marktony/zhihudaily/data/ZhihuDailyContent.kt | 2776669932 |
/*
* MIT License
*
* Copyright (c) 2017 atlarge-research
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.atlarge.opendc.model.odc.topology.network
import com.atlarge.opendc.simulator.Entity
/**
* A generic interface for a network unit in a cloud network.
*
* @author Fabian Mastenbroek ([email protected])
*/
interface NetworkUnit : Entity<Unit>
| opendc-model-odc/core/src/main/kotlin/com/atlarge/opendc/model/odc/topology/network/NetworkUnit.kt | 1601239515 |
/*
* Copyright 2018 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.unconsciousness.bukkit.unconsciousness
import com.rpkit.characters.bukkit.character.RPKCharacter
import com.rpkit.core.database.Entity
class RPKUnconsciousState(
override var id: Int = 0,
val character: RPKCharacter,
var deathTime: Long
) : Entity | bukkit/rpk-unconsciousness-bukkit/src/main/kotlin/com/rpkit/unconsciousness/bukkit/unconsciousness/RPKUnconsciousState.kt | 2598487704 |
package it.achdjian.paolo.cs5463.dagger
import android.content.SharedPreferences
import android.preference.PreferenceManager
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v7.app.AppCompatActivity
import dagger.Component
import dagger.Module
import dagger.Provides
import it.achdjian.paolo.cs5463.MainActivity
import it.achdjian.paolo.cs5463.MeasureRegistersFragment
import it.achdjian.paolo.cs5463.Register.LoadRegister
import it.achdjian.paolo.cs5463.Register.Register2View
import it.achdjian.paolo.cs5463.Register.RegistersValue
import it.achdjian.paolo.cs5463.RegistersAdapter
import it.achdjian.paolo.cs5463.SectionsPageAdapter
import it.achdjian.paolo.cs5463.domusEngine.ConnectionStatus
import it.achdjian.paolo.cs5463.domusEngine.DomusEngine
import it.achdjian.paolo.cs5463.zigbee.ZDevices
import javax.inject.Singleton
@Module
object StaticModule{
@JvmStatic
@Provides
@Singleton
fun fragmentManager(mainActivity: AppCompatActivity): FragmentManager {
return mainActivity.supportFragmentManager
}
}
@Singleton
@Component(modules = arrayOf(CS5463Module::class))
interface ApplicationComponent {
}
@Module
class MainActivityModule(val mainActivity: MainActivity) {
@Provides
@Singleton
fun fragmentManager(): FragmentManager {
return mainActivity.supportFragmentManager;
}
}
@Singleton
@Component(modules = arrayOf(CS5463Module::class, MainActivityModule::class))
interface MainActivityComponent {
fun inject(mainActivity: MainActivity)
fun sectionsPageAdapter(): SectionsPageAdapter
}
@Module
class FragmentModule(val fragment:Fragment){
@Provides
@Singleton
fun getSharedPreferences(): SharedPreferences {
return PreferenceManager.getDefaultSharedPreferences(fragment.activity.application)
}
@Provides
@Singleton
fun mainActivity(): MainActivity {
return fragment.activity as MainActivity
}
}
@Singleton
@Component(modules = arrayOf(FragmentModule::class))
interface MeasureRegistersFragmentComponent{
fun inject(fragment: MeasureRegistersFragment)
fun loadRegister(): LoadRegister
fun registerValue(): RegistersValue
fun registersAdapter(): RegistersAdapter
fun register2View(): Register2View
} | cs5463/app/src/main/java/it/achdjian/paolo/cs5463/dagger/DaggerModules.kt | 3777237953 |
/*
* 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.chat.bukkit.command.unmute
import com.rpkit.chat.bukkit.RPKChatBukkit
import com.rpkit.chat.bukkit.chatchannel.RPKChatChannelProvider
import com.rpkit.players.bukkit.profile.RPKMinecraftProfileProvider
import org.bukkit.command.Command
import org.bukkit.command.CommandExecutor
import org.bukkit.command.CommandSender
import org.bukkit.entity.Player
/**
* Unmute command.
* Unmutes a chat channel.
*/
class UnmuteCommand(private val plugin: RPKChatBukkit): CommandExecutor {
override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean {
if (sender is Player) {
if (args.isNotEmpty()) {
val minecraftProfileProvider = plugin.core.serviceManager.getServiceProvider(RPKMinecraftProfileProvider::class)
val chatChannelProvider = plugin.core.serviceManager.getServiceProvider(RPKChatChannelProvider::class)
val minecraftProfile = minecraftProfileProvider.getMinecraftProfile(sender)
if (minecraftProfile != null) {
val chatChannel = chatChannelProvider.getChatChannel(args[0])
if (chatChannel != null) {
if (sender.hasPermission("rpkit.chat.command.unmute.${chatChannel.name}")) {
chatChannel.addListener(minecraftProfile)
sender.sendMessage(plugin.messages["unmute-valid", mapOf(
Pair("channel", chatChannel.name)
)])
} else {
sender.sendMessage(plugin.messages["no-permission-unmute", mapOf(
Pair("channel", chatChannel.name)
)])
}
} else {
sender.sendMessage(plugin.messages["unmute-invalid-chatchannel"])
}
} else {
sender.sendMessage(plugin.messages["no-minecraft-profile"])
}
} else {
sender.sendMessage(plugin.messages["unmute-usage"])
}
} else {
sender.sendMessage(plugin.messages["not-from-console"])
}
return true
}
} | bukkit/rpk-chat-bukkit/src/main/kotlin/com/rpkit/chat/bukkit/command/unmute/UnmuteCommand.kt | 1500355686 |
package com.orgzly.android.reminders
import org.joda.time.DateTime
data class NoteReminder(val runTime: DateTime, val payload: NoteReminderPayload) | app/src/main/java/com/orgzly/android/reminders/NoteReminder.kt | 701739672 |
package org.evomaster.core.search.gene.sql
import org.evomaster.client.java.controller.api.dto.database.schema.DatabaseType
import org.evomaster.core.search.gene.numeric.IntegerGene
import org.evomaster.core.search.gene.string.StringGene
import org.evomaster.core.search.service.Randomness
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Disabled
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
class SqlMultidimensionalArrayGeneTest {
private val rand = Randomness()
@BeforeEach
fun initRand() {
rand.updateSeed(42)
}
private fun sampleOneDimensionalArrayOfIntegerGenes(size: Int): SqlMultidimensionalArrayGene<IntegerGene> {
val gene = SqlMultidimensionalArrayGene(
"matrix",
template = IntegerGene("element"),
numberOfDimensions = 1
)
gene.doInitialize(rand)
do {
gene.randomize(rand, tryToForceNewValue = false)
} while (gene.getDimensionSize(0) != size)
return gene
}
private fun sampleTwoDimensionalArrayOfIntegerGenes(rows: Int,
columns: Int,
databaseType: DatabaseType = DatabaseType.POSTGRES): SqlMultidimensionalArrayGene<IntegerGene> {
val gene = SqlMultidimensionalArrayGene(
"matrix",
databaseType = databaseType,
template = IntegerGene("element"),
numberOfDimensions = 2
)
gene.doInitialize(rand)
do {
gene.randomize(rand, tryToForceNewValue = false)
} while (gene.getDimensionSize(0) != rows
|| gene.getDimensionSize(1) != columns)
return gene
}
private fun sampleThreeDimensionalArrayOfIntegerGenes(rows: Int, columns: Int, pages: Int): SqlMultidimensionalArrayGene<IntegerGene> {
val gene = SqlMultidimensionalArrayGene(
"matrix",
template = IntegerGene("element"),
numberOfDimensions = 3
)
gene.doInitialize(rand)
do {
gene.randomize(rand, tryToForceNewValue = false)
} while (gene.getDimensionSize(0) != rows
|| gene.getDimensionSize(1) != columns
|| gene.getDimensionSize(2) != pages)
return gene
}
@Test
fun testInvalidNumberOfDimensions() {
assertThrows<IllegalArgumentException> {
SqlMultidimensionalArrayGene(
"array",
template = IntegerGene("element"),
numberOfDimensions = -2
)
}
}
@Test
fun testZeroNumberOfDimensionsArray() {
assertThrows<IllegalArgumentException> {
SqlMultidimensionalArrayGene(
"multidimensionaArray",
template = IntegerGene("element"),
numberOfDimensions = 0
)
}
}
@Test
fun testOneDimensionalArrayIsValid() {
val gene = sampleOneDimensionalArrayOfIntegerGenes(3)
assertTrue(gene.isLocallyValid())
}
@Test
fun testTwoDimensionalArrayIsValid() {
val gene = sampleTwoDimensionalArrayOfIntegerGenes(3,2)
assertTrue(gene.isLocallyValid())
}
@Test
fun testThreeDimensionalArrayIsValid() {
val gene = sampleThreeDimensionalArrayOfIntegerGenes(3,2,3)
assertTrue(gene.isLocallyValid())
}
@Test
fun testValidDimensionIndex() {
val gene = SqlMultidimensionalArrayGene(
"array",
template = IntegerGene("element"),
numberOfDimensions = 1
)
assertFalse(gene.initialized)
gene.doInitialize(rand)
assertTrue(gene.initialized)
assertTrue(gene.getDimensionSize(0) >= 0)
}
@Test
fun testInvalidDimensionIndex() {
val gene = sampleOneDimensionalArrayOfIntegerGenes(3)
assertThrows<IndexOutOfBoundsException> {
gene.getDimensionSize(1)
}
}
@Test
fun testOneDimensionalArrayGetElement() {
val gene = sampleOneDimensionalArrayOfIntegerGenes(3)
assertEquals(3, gene.getDimensionSize(0))
assertThrows<IndexOutOfBoundsException> {
gene.getElement(listOf(-1))
}
gene.getElement(listOf(0))
gene.getElement(listOf(1))
gene.getElement(listOf(2))
assertThrows<IndexOutOfBoundsException> {
gene.getElement(listOf(3))
}
/**
* All genes should be recursively initialized
*/
// TODO FixME
//assertTrue(elem0.initialized)
//assertTrue(elem1.initialized)
//assertTrue(elem2.initialized)
}
@Test
fun testIncorrectGetElementListOfIndexes() {
val gene = sampleTwoDimensionalArrayOfIntegerGenes(2, 3)
assertThrows<IllegalArgumentException> {
gene.getElement(listOf())
}
assertThrows<IllegalArgumentException> {
gene.getElement(listOf(1))
}
assertThrows<IllegalArgumentException> {
gene.getElement(listOf(1, 1, 1))
}
}
@Test
fun testTwoDimensionalArrayGetElement() {
val gene = sampleTwoDimensionalArrayOfIntegerGenes(rows = 3, columns = 2)
assertEquals(2, gene.numberOfDimensions)
assertEquals(3, gene.getDimensionSize(0))
assertEquals(2, gene.getDimensionSize(1))
}
@Test
fun testThreeDimensionalArray() {
val gene = sampleThreeDimensionalArrayOfIntegerGenes(rows = 2, columns = 3, pages = 4)
assertEquals(2, gene.getDimensionSize(0))
assertEquals(3, gene.getDimensionSize(1))
assertEquals(4, gene.getDimensionSize(2))
gene.getElement(listOf(1, 2, 3))
}
@Test
fun testContainsSameValueAsWithEmptyArrays() {
val emptyArray0 = sampleOneDimensionalArrayOfIntegerGenes(0)
assertEquals(0, emptyArray0.getDimensionSize(0))
val emptyArray1 = sampleOneDimensionalArrayOfIntegerGenes(0)
assertEquals(0, emptyArray1.getDimensionSize(0))
assertEquals(true, emptyArray0.containsSameValueAs(emptyArray1))
}
@Test
fun testContainsSameValueAsWithNonEmptyArrays() {
val nonEmptyArray0 = sampleOneDimensionalArrayOfIntegerGenes(2)
nonEmptyArray0.getElement(listOf(0)).value = 0
nonEmptyArray0.getElement(listOf(1)).value = 1
val nonEmptyArray1 = sampleOneDimensionalArrayOfIntegerGenes(2)
nonEmptyArray1.getElement(listOf(0)).value = 0
nonEmptyArray1.getElement(listOf(1)).value = 1
assertEquals(true, nonEmptyArray0.containsSameValueAs(nonEmptyArray1))
}
@Test
fun testNotContainsSameValue() {
val nonEmptyArray = sampleOneDimensionalArrayOfIntegerGenes(1)
val emptyArray = sampleOneDimensionalArrayOfIntegerGenes(0)
assertEquals(false, nonEmptyArray.containsSameValueAs(emptyArray))
assertEquals(false, emptyArray.containsSameValueAs(nonEmptyArray))
}
@Test
fun testContainsSameValueAsWithDifferentElement() {
val array = sampleThreeDimensionalArrayOfIntegerGenes(1, 1, 1)
val copy = array.copy() as SqlMultidimensionalArrayGene<IntegerGene>
assertTrue(array.containsSameValueAs(copy))
copy.getElement(listOf(0, 0, 0)).value++
assertFalse(array.containsSameValueAs(copy))
}
@Test
fun testValues() {
val array = sampleThreeDimensionalArrayOfIntegerGenes(3, 3, 3)
array.getElement(listOf(0, 0, 0)).value = 1
array.getElement(listOf(1, 1, 1)).value = 2
array.getElement(listOf(2, 2, 2)).value = 0
assertEquals(1, array.getElement(listOf(0, 0, 0)).value)
assertEquals(2, array.getElement(listOf(1, 1, 1)).value)
assertEquals(0, array.getElement(listOf(2, 2, 2)).value)
}
@Test
fun testCopyValuesFrom() {
val nonEmptyArray = sampleThreeDimensionalArrayOfIntegerGenes(3, 3, 3)
nonEmptyArray.getElement(listOf(0, 0, 0)).value = 1
nonEmptyArray.getElement(listOf(1, 1, 1)).value = 2
nonEmptyArray.getElement(listOf(2, 2, 2)).value = 0
val copiedArray = sampleThreeDimensionalArrayOfIntegerGenes(3, 3, 3)
copiedArray.copyValueFrom(nonEmptyArray)
assertEquals(1, copiedArray.getElement(listOf(0, 0, 0)).value)
assertEquals(2, copiedArray.getElement(listOf(1, 1, 1)).value)
assertEquals(0, copiedArray.getElement(listOf(2, 2, 2)).value)
assertTrue(copiedArray.isLocallyValid())
}
@Test
fun testCopyValuesFromWithDifferentDimensions() {
val nonEmptyArray = sampleTwoDimensionalArrayOfIntegerGenes(2, 3)
val copiedArray = sampleOneDimensionalArrayOfIntegerGenes(2)
assertThrows<IllegalArgumentException> {
copiedArray.copyValueFrom(nonEmptyArray)
}
}
@Test
fun testBindValuesBasedOn() {
val sourceArray = sampleThreeDimensionalArrayOfIntegerGenes(2, 3, 1)
val targetArray = sampleThreeDimensionalArrayOfIntegerGenes(1, 5, 1)
assertEquals(true, targetArray.bindValueBasedOn(sourceArray))
assertEquals(2, targetArray.getDimensionSize(0))
assertEquals(3, targetArray.getDimensionSize(1))
assertEquals(1, targetArray.getDimensionSize(2))
assertTrue(targetArray.isLocallyValid())
}
@Test
fun testFailedBindValuesBasedOn() {
val sourceArray = sampleThreeDimensionalArrayOfIntegerGenes(2, 3, 1)
val targetArray = sampleTwoDimensionalArrayOfIntegerGenes(2, 3)
assertFalse( targetArray.bindValueBasedOn(sourceArray))
}
@Test
fun testFailedBindValuesBasedOnDifferentTemplates() {
val sourceArray = SqlMultidimensionalArrayGene(
"multidimensionaArray",
template = IntegerGene("element"),
numberOfDimensions = 3
)
val targetArray = SqlMultidimensionalArrayGene(
"multidimensionaArray",
template = StringGene("element"),
numberOfDimensions = 3
)
assertFalse( targetArray.bindValueBasedOn(sourceArray))
}
@Test
fun testGetPrintableValueOfArray() {
val gene = sampleOneDimensionalArrayOfIntegerGenes(3)
gene.getElement(listOf(0)).value = 1
gene.getElement(listOf(1)).value = 2
gene.getElement(listOf(2)).value = 3
assertEquals("\"{1, 2, 3}\"", gene.getValueAsPrintableString())
assertTrue(gene.isLocallyValid())
}
@Test
fun testGetPrintableValueOfSquareMatrix() {
val gene = sampleTwoDimensionalArrayOfIntegerGenes(2, 2)
gene.getElement(listOf(0, 0)).value = 1
gene.getElement(listOf(0, 1)).value = 2
gene.getElement(listOf(1, 0)).value = 3
gene.getElement(listOf(1, 1)).value = 4
assertEquals("\"{{1, 2}, {3, 4}}\"", gene.getValueAsPrintableString())
assertTrue(gene.isLocallyValid())
}
@Test
fun testGetPrintableValueOfNonSquareMatrixAsArray() {
val gene = sampleTwoDimensionalArrayOfIntegerGenes(rows = 1, columns = 3)
gene.getElement(listOf(0, 0)).value = 1
gene.getElement(listOf(0, 1)).value = 2
gene.getElement(listOf(0, 2)).value = 3
assertEquals("\"{{1, 2, 3}}\"", gene.getValueAsPrintableString())
assertTrue(gene.isLocallyValid())
}
@Test
fun testGetPrintableValueOfNonSquareMatrixAsVector() {
val gene = sampleTwoDimensionalArrayOfIntegerGenes(rows = 3, columns = 1)
gene.getElement(listOf(0, 0)).value = 1
gene.getElement(listOf(1, 0)).value = 2
gene.getElement(listOf(2, 0)).value = 3
assertEquals("\"{{1}, {2}, {3}}\"", gene.getValueAsPrintableString())
assertTrue(gene.isLocallyValid())
}
@Test
fun testGetPrintableValueOfEmptyArray() {
val gene = sampleOneDimensionalArrayOfIntegerGenes(0)
assertEquals("\"{}\"", gene.getValueAsPrintableString())
assertTrue(gene.isLocallyValid())
}
@Test
fun testGetPrintableValueOfStringGenesNonEmptyArray() {
val gene = SqlMultidimensionalArrayGene(
"matrix",
template = StringGene("element"),
numberOfDimensions = 1
)
gene.doInitialize(rand)
do {
gene.randomize(rand, tryToForceNewValue = false)
} while (gene.getDimensionSize(0) != 2)
gene.getElement(listOf(0)).value = "Hello"
gene.getElement(listOf(1)).value = "World"
assertEquals("\"{\"Hello\", \"World\"}\"", gene.getValueAsPrintableString())
assertTrue(gene.isLocallyValid())
}
// TODO FixMe. It is not clear how mutation weight should be computed
@Disabled
@Test
fun testMutationWeight() {
val gene = sampleTwoDimensionalArrayOfIntegerGenes(2, 1)
(gene.getElement(listOf(0, 0))).value = 1
(gene.getElement(listOf(1, 0))).value = 2
val w0 = (gene.getElement(listOf(0, 0))).mutationWeight()
val w1 = (gene.getElement(listOf(0, 0))).mutationWeight()
val DELTA = 1e-15
assertEquals(1.0 + w0 + w1, gene.mutationWeight(), DELTA)
}
@Test
fun testFlatView() {
val gene = sampleTwoDimensionalArrayOfIntegerGenes(2, 3)
assertEquals(6, gene.flatView().filterIsInstance<IntegerGene>().size)
}
@Test
fun testContainsSameValueAsDiffDimensions() {
val gene = sampleTwoDimensionalArrayOfIntegerGenes(2, 3)
val copy = gene.copy()
assertTrue(gene.containsSameValueAs(copy))
assertTrue(copy.isLocallyValid())
}
@Test
fun testContainsSameValueArray() {
val gene = sampleOneDimensionalArrayOfIntegerGenes(4)
val copy = gene.copy()
assertTrue(gene.containsSameValueAs(copy))
assertTrue(copy.isLocallyValid())
}
@Test
fun testGetPrintableValueOfStringGenesNonEmptyArrayWithH2() {
val gene = SqlMultidimensionalArrayGene(
"matrix",
databaseType = DatabaseType.H2,
template = StringGene("element"),
numberOfDimensions = 1
)
gene.doInitialize(rand)
do {
gene.randomize(rand, tryToForceNewValue = false)
} while (gene.getDimensionSize(0) != 2)
gene.getElement(listOf(0)).value = "Hello"
gene.getElement(listOf(1)).value = "World"
assertEquals("ARRAY[SINGLE_APOSTROPHE_PLACEHOLDERHelloSINGLE_APOSTROPHE_PLACEHOLDER, SINGLE_APOSTROPHE_PLACEHOLDERWorldSINGLE_APOSTROPHE_PLACEHOLDER]", gene.getValueAsPrintableString())
assertTrue(gene.isLocallyValid())
}
@Test
fun testGetPrintableValueOfNonSquareMatrixAsVectorH2() {
val gene = sampleTwoDimensionalArrayOfIntegerGenes(rows = 3, columns = 1, databaseType = DatabaseType.H2)
gene.getElement(listOf(0, 0)).value = 1
gene.getElement(listOf(1, 0)).value = 2
gene.getElement(listOf(2, 0)).value = 3
assertEquals("ARRAY[ARRAY[1], ARRAY[2], ARRAY[3]]", gene.getValueAsPrintableString())
assertTrue(gene.isLocallyValid())
}
} | core/src/test/kotlin/org/evomaster/core/search/gene/sql/SqlMultidimensionalArrayGeneTest.kt | 3365747279 |
package chat.rocket.android.chatrooms.adapter
import android.view.View
import androidx.recyclerview.widget.RecyclerView
abstract class ViewHolder<T : ItemHolder<*>>(
itemView: View
) : RecyclerView.ViewHolder(itemView) {
var data: T? = null
fun bind(data: T) {
this.data = data
bindViews(data)
}
abstract fun bindViews(data: T)
} | app/src/main/java/chat/rocket/android/chatrooms/adapter/ViewHolder.kt | 3485154438 |
package com.petrulak.cleankotlin.ui.example3.fragment
import android.util.Log
import com.petrulak.cleankotlin.di.scope.ViewScope
import com.petrulak.cleankotlin.domain.interactor.definition.GetWeatherRemotelyUseCase
import com.petrulak.cleankotlin.domain.model.Weather
import com.petrulak.cleankotlin.platform.bus.data.DataBus
import com.petrulak.cleankotlin.platform.bus.event.EventBus
import com.petrulak.cleankotlin.platform.bus.event.events.BaseEvent
import com.petrulak.cleankotlin.platform.bus.event.events.FragmentSyncEvent
import com.petrulak.cleankotlin.platform.extensions.getDisposableSingleObserver
import com.petrulak.cleankotlin.ui.base.BasePresenterImpl
import com.petrulak.cleankotlin.ui.example3.fragment.Example3Contract.View
import dagger.internal.Preconditions.checkNotNull
import io.reactivex.disposables.CompositeDisposable
import java.util.*
import javax.inject.Inject
@ViewScope
class Example3Presenter
@Inject
constructor(private val getWeatherRemotelyUseCase: GetWeatherRemotelyUseCase,
private val dataBus: DataBus,
private val eventBus: EventBus) : BasePresenterImpl(), Example3Contract.Presenter {
private var view: View? = null
private val dataDisposable = CompositeDisposable()
override fun attachView(view: View) {
this.view = checkNotNull(view)
}
override fun start() {
super.start()
refresh()
subscribeToData()
subscribeToFragmentSyncEvents()
// subscribeToDummyEvents()
}
private fun subscribeToData() {
val disposable = dataBus.weatherDataBus.flowable.subscribe({ view?.showWeather(it) })
dataDisposable.add(disposable)
}
private fun subscribeToFragmentSyncEvents() {
val disposable = eventBus.fragmentSyncEvent.flowable.subscribe({ processEvent(it) })
disposables.add(disposable)
}
/**
* You can consume data/payload which is included in the event.
*/
private fun subscribeToDummyEvents() {
val disposable = eventBus.weatherDummyEvent.flowable.subscribe({ processDummyEvent(it) })
disposables.add(disposable)
}
private fun processDummyEvent(event: BaseEvent<Weather>) {
//payload can be null, we have to perform null check
event.payload?.let {
val payload = it
Log.e("Hello", "This is payload: $payload")
}
}
private fun processEvent(event: BaseEvent<Any>) {
when (event.eventType) {
FragmentSyncEvent.ACTION_SYNC_OFF -> dataDisposable.clear()
FragmentSyncEvent.ACTION_SYNC_ON -> subscribeToData()
}
}
override fun stop() {
super.stop()
dataDisposable.clear()
}
override fun refresh() {
val disposable = getWeatherRemotelyUseCase
.execute("London,uk")
.subscribeWith(getDisposableSingleObserver({ onSuccess(it) }, { onError(it) }))
disposables.add(disposable)
}
private fun onSuccess(weather: Weather) {
//Changing visibility value manually to see changes in the UI
val modified = Weather(weather.id, weather.name, Random().nextInt(80 - 65) + 65)
dataBus.weatherDataBus.emmit(modified)
view?.showWeather(modified)
}
private fun onError(t: Throwable) {
}
}
| app/src/main/java/com/petrulak/cleankotlin/ui/example3/fragment/Example3Presenter.kt | 598611873 |
package com.coboltforge.dontmind.multivnc
import kotlinx.serialization.Serializable
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import java.io.Reader
import java.io.Writer
/**
* Import/Export Utility
*/
object ImportExport {
/**
* Current version of [Container].
*/
private const val VERSION = 1
@Serializable
private data class Container(
val version: Int,
val connections: List<ConnectionBean>,
val metaKeys: List<MetaKeyBean>,
val metaLists: List<MetaList>
)
private val serializer = Json {
encodeDefaults = false
ignoreUnknownKeys = true
prettyPrint = true
}
/**
* Exports database to given [writer].
*/
fun exportDatabase(db: VncDatabase, writer: Writer) {
val container = Container(
VERSION,
db.connectionDao.all,
db.metaKeyDao.all,
db.metaListDao.all
)
val json = serializer.encodeToString(container)
writer.write(json)
}
/**
* Reads JSON data from given [reader] and imports it into [db].
*/
fun importDatabase(db: VncDatabase, reader: Reader) {
val json = reader.readText()
val container = serializer.decodeFromString<Container>(json)
db.runInTransaction {
container.connections.forEach {
if (db.connectionDao.get(it.id) == null)
db.connectionDao.insert(it)
else
db.connectionDao.update(it)
}
container.metaKeys.forEach {
if (db.metaKeyDao.get(it.id) == null)
db.metaKeyDao.insert(it)
else
db.metaKeyDao.update(it)
}
container.metaLists.forEach {
if (db.metaListDao.get(it.id) == null)
db.metaListDao.insert(it)
else
db.metaListDao.update(it)
}
}
}
} | android/app/src/main/java/com/coboltforge/dontmind/multivnc/ImportExport.kt | 3864818431 |
package org.protozoo.component.task.command
import org.apache.karaf.shell.api.action.Command
import org.apache.karaf.shell.api.action.lifecycle.Service
/**
* List all the components currently installed.
*/
@Command(scope = TaskCommandConstants.TASK_COMMAND, name = TaskCommandConstants.LIST_FUNCTION, description = "Display available tasks")
@Service
class ListAction : TaskAction() {
override fun execute() : Any? {
val tasks = manager.getAll()
if (tasks.count() == 0) {
println("No components registered")
} else {
for (task in tasks) {
println("> " + task.title + ", " + task.description)
}
}
return null
}
} | component/taskcommand/src/main/kotlin/org.protozoo.component.task.command/ListAction.kt | 2687223027 |
package com.github.premnirmal.ticker.news
import android.os.Bundle
import android.view.View
import androidx.activity.viewModels
import com.github.mikephil.charting.animation.Easing
import com.github.mikephil.charting.charts.LineChart
import com.github.premnirmal.ticker.base.BaseGraphActivity
import com.github.premnirmal.ticker.components.InAppMessage
import com.github.premnirmal.ticker.isNetworkOnline
import com.github.premnirmal.ticker.model.HistoryProvider.Range
import com.github.premnirmal.ticker.network.data.Quote
import com.github.premnirmal.ticker.showDialog
import com.github.premnirmal.ticker.viewBinding
import com.github.premnirmal.tickerwidget.R
import com.github.premnirmal.tickerwidget.databinding.ActivityGraphBinding
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class GraphActivity : BaseGraphActivity<ActivityGraphBinding>() {
companion object {
const val TICKER = "TICKER"
private const val DURATION = 2000
}
override val simpleName: String = "GraphActivity"
override val binding: (ActivityGraphBinding) by viewBinding(ActivityGraphBinding::inflate)
private lateinit var ticker: String
protected lateinit var quote: Quote
private val viewModel: GraphViewModel by viewModels()
override var range: Range = Range.THREE_MONTH
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setupGraphView()
ticker = checkNotNull(intent.getStringExtra(TICKER))
viewModel.quote.observe(this) { quote ->
this.quote = quote
binding.tickerName.text = ticker
binding.desc.text = quote.name
viewModel.data.observe(this) { data ->
dataPoints = data
loadGraph(ticker, quote)
}
}
viewModel.error.observe(this) {
showErrorAndFinish()
}
viewModel.fetchStock(ticker)
binding.groupPeriod.setOnCheckedChangeListener { _, checkedId ->
val view = findViewById<View>(checkedId)
updateRange(view)
}
val view = when (range) {
Range.ONE_DAY -> binding.oneDay
Range.TWO_WEEKS -> binding.twoWeeks
Range.ONE_MONTH -> binding.oneMonth
Range.THREE_MONTH -> binding.threeMonth
Range.ONE_YEAR -> binding.oneYear
Range.FIVE_YEARS -> binding.fiveYears
Range.MAX -> binding.max
else -> throw UnsupportedOperationException("Range not supported")
}
binding.groupPeriod.check(view.id)
}
override fun onStart() {
super.onStart()
if (dataPoints == null) {
fetchGraphData()
}
}
private fun showErrorAndFinish() {
InAppMessage.showToast(this, R.string.error_symbol)
finish()
}
override fun fetchGraphData() {
if (isNetworkOnline()) {
binding.graphView.visibility = View.INVISIBLE
binding.progress.visibility = View.VISIBLE
viewModel.fetchHistoricalDataByRange(ticker, range)
} else {
showDialog(getString(R.string.no_network_message),
{ _, _ -> finish() }, cancelable = false)
}
}
override fun onGraphDataAdded(graphView: LineChart) {
binding.progress.visibility = View.GONE
binding.graphView.visibility = View.VISIBLE
graphView.animateX(DURATION, Easing.EasingOption.EaseInOutCubic)
}
override fun onNoGraphData(graphView: LineChart) {
binding.progress.visibility = View.GONE
binding.graphView.visibility = View.VISIBLE
}
} | app/src/main/kotlin/com/github/premnirmal/ticker/news/GraphActivity.kt | 398043272 |
package com.gdgchicagowest.windycitydevcon.ext
/**
* Set of chars for a half-byte.
*/
private val CHARS = arrayOf('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f')
/**
* Returns the string of two characters representing the HEX value of the byte.
*/
internal fun Byte.toHexString() : String {
val i = this.toInt()
val char2 = CHARS[i and 0x0f]
val char1 = CHARS[i shr 4 and 0x0f]
return "$char1$char2"
}
/**
* Returns the HEX representation of ByteArray data.
*/
internal fun ByteArray.toHexString() : String {
val builder = StringBuilder()
for (b in this) {
builder.append(b.toHexString())
}
return builder.toString()
} | core/src/main/kotlin/com/gdgchicagowest/windycitydevcon/ext/Bytes.kt | 4019021013 |
package com.binlly.fastpeak.base.net
import android.content.Context
import android.net.ConnectivityManager
import com.binlly.fastpeak.service.Services
/**
* Created by yy on 2017/8/23.
*/
object Net {
fun isAvailable(): Boolean {
val mConnectivityManager = Services.app().getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val mNetworkInfo = mConnectivityManager.activeNetworkInfo
if (mNetworkInfo != null) return mNetworkInfo.isAvailable
return false
}
fun isWifi(context: Context): Boolean {
val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
return cm.activeNetworkInfo.type == ConnectivityManager.TYPE_WIFI
}
} | app/src/main/java/com/binlly/fastpeak/base/net/Net.kt | 3764971714 |
package com.binlly.fastpeak.business.test.model
import com.chad.library.adapter.base.entity.MultiItemEntity
import java.io.Serializable
class TestModel: MultiItemEntity, Serializable {
var item_type: Int = 0
val isSectionType: Boolean
get() = item_type == TYPE_SECTION
val isEnvType: Boolean
get() = item_type == TYPE_ENV
val isBuildType: Boolean
get() = item_type == TYPE_BUILD
val isMockType: Boolean
get() = item_type == TYPE_MOCK
val isRouterType: Boolean
get() = item_type == TYPE_ROUTER
override fun getItemType(): Int {
return item_type
}
lateinit var section: String
lateinit var env: EnvModel
lateinit var build: BuildModel
lateinit var mock: MockModel
lateinit var router: RouterModel
var valueColor: Int = 0
data class EnvModel(var key: String, var value: String, var isSelected: Boolean = false)
data class BuildModel(var key: String, var value: String)
data class MockModel(var key: String, var value: String)
data class RouterModel(var key: String, var value: String)
companion object {
private const val serialVersionUID = -4241242337755076267L
val TYPE_SECTION = 0
val TYPE_ENV = 1
val TYPE_BUILD = 2
val TYPE_MOCK = 3
val TYPE_ROUTER = 4
}
} | app/src/main/java/com/binlly/fastpeak/business/test/model/TestModel.kt | 614220119 |
package com.github.zxj5470.bugktdoc
import com.github.zxj5470.bugktdoc.options.BugKtDocGlobalSettings
import com.intellij.CommonBundle
import com.intellij.openapi.components.ServiceManager
import com.intellij.util.PlatformUtils
import org.jetbrains.annotations.NonNls
import org.jetbrains.annotations.PropertyKey
import org.jetbrains.kotlin.idea.intentions.SpecifyTypeExplicitlyIntention
import org.jetbrains.kotlin.psi.KtCallableDeclaration
import java.util.*
val globalSettings
get() = ServiceManager.getService(BugKtDocGlobalSettings::class.java).settings
val isTheFirstTime
get() = globalSettings.theFirstTile
val pluginActive
get() = globalSettings.useBugKtDoc
val isAlwaysShowUnitReturnType
get() = globalSettings.alwaysShowUnitReturnType
val isAlwaysShowClassFieldProperty
get() = globalSettings.alwaysShowClassFieldProperty
val isAlwaysShowConstructor
get() = globalSettings.alwaysShowConstructor
/**
* @ref https://github.com/ice1000/julia-intellij/blob/master/src/org/ice1000/julia/lang/julia-infos.kt
* class [JuliaBundle]
*/
object BugKtDocBundle {
@NonNls
private const val BUNDLE = "BugKtDocBundle"
private val bundle: ResourceBundle by lazy { ResourceBundle.getBundle(BUNDLE) }
@JvmStatic
fun message(@PropertyKey(resourceBundle = BUNDLE) key: String, vararg params: Any) =
CommonBundle.message(bundle, key, *params)
}
inline val KtCallableDeclaration.itsType
get() = SpecifyTypeExplicitlyIntention.getTypeForDeclaration(this).unwrap().toString()
val isKotlinNative
get() = PlatformUtils.isAppCode() || PlatformUtils.isCLion() | src/main/kotlin/com/github/zxj5470/bugktdoc/BugKtDocTools.kt | 436348026 |
/*-
* ========================LICENSE_START=================================
* ids-container-manager
* %%
* Copyright (C) 2019 Fraunhofer AISEC
* %%
* 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.
* =========================LICENSE_END==================================
*/
package de.fhg.aisec.ids.comm.unixsocket
import org.slf4j.LoggerFactory
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock
class TrustmeUnixSocketResponseHandler {
private val lock = ReentrantLock()
private val condition = lock.newCondition()
private val LOG = LoggerFactory.getLogger(TrustmeUnixSocketResponseHandler::class.java)
private var rsp: ByteArray? = null
fun handleResponse(rsp: ByteArray): Boolean {
lock.withLock {
this.rsp = rsp.clone()
condition.signal()
return true
}
}
fun waitForResponse(): ByteArray {
lock.withLock {
while (rsp == null) {
try {
condition.await()
} catch (e: InterruptedException) {
LOG.error(e.message, e)
}
}
val result = rsp!!
LOG.debug("received response byte length: {}", result.size)
rsp = null
return result
}
}
}
| ids-container-manager/src/main/kotlin/de/fhg/aisec/ids/comm/unixsocket/TrustmeUnixSocketResponseHandler.kt | 34884891 |
package domain.processing.services
import domain.global.errors.SaveException
import domain.processing.entities.objects.ParameterEntity
import domain.processing.entities.objects.StepEntity
import domain.processing.entities.objects.TaskEntity
import neo4j.utils.Neo4jSessionFactory
import org.junit.After
import org.junit.Test
import org.junit.Assert.*
import org.junit.Before
import org.neo4j.ogm.session.Session
import java.util.*
/**
* Created by Christian Sperandio on 10/04/2016.
*/
class TaskServiceTest {
private lateinit var session: Session
@Before
fun setUp() {
session = Neo4jSessionFactory.getNeo4jSession()
println("Session=" + session)
}
@After
fun tearDown() {
}
@Test
fun saveWithSuccess() {
val task = TaskEntity(this.javaClass.name + ": My Task")
val step = StepEntity("My First Step")
step.parameters = setOf(ParameterEntity("A Parameter"))
task.steps = setOf<StepEntity>(step)
val taskService = TaskService(session)
try {
taskService.save(task)
assertNotNull(task.id)
taskService.delete(task)
} catch (e: Exception) {
e.printStackTrace()
fail()
}
}
@Test
fun saveWithFailure() {
val task = TaskEntity(this.javaClass.name + ": My Task")
val step = StepEntity("My First Step")
task.steps = setOf<StepEntity>(step)
val taskService = TaskService(session)
try {
taskService.save(task)
taskService.delete(task)
fail()
} catch (e: Exception) {}
}
/**
* In this test below, the task creation fails because the task's name is not modified.
*/
@Test
fun failTaskCreationFromTemplate() {
val taskService = TaskService(session)
try {
val template = taskService.findByTemplateUUID("0f4a77f60b-ba74-435e-9f78-7ab8dcaa5a31")
assertNull(template)
} catch(e: SaveException) {
}
}
/**
* In this test below, the task creation fails the template UUID is not found
*/
@Test
fun failTaskCreationFromUnknownTemplate() {
val taskService = TaskService(session)
try {
val template = taskService.findByTemplateUUID("unknown template")
assertNull(template)
} catch(e: SaveException) {
}
}
@Test
fun successTaskCreationFromTemplate() {
val taskService = TaskService(session)
try {
val task = taskService.findByTemplateUUID("0f4af60b-ba74-435e-9f78-7ab8dcaa5a31")
assertNotNull(task)
task?.name = task?.name + " [" + UUID.randomUUID() + "]"
task?.updateParameter("firstInputFilename", "/the/first/file")
val id = taskService.saveFromTemplate(task!!)
assertNotNull(id)
} catch(e: SaveException) {
e.printStackTrace()
fail("The system must not accept 2 task with the same name.")
}
}
}
| src/test/kotlin/domain/processing/services/TaskServiceTest.kt | 317710417 |
/*
*
* * Copyright (C) 2018 The Android Open Source Project
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package com.example.background.imgur
import com.google.gson.annotations.SerializedName
/**
* The Imgur API post image response.
*/
class PostImageResponse {
@SerializedName("data")
val data: UploadedImage? = null
@SerializedName("success")
val isSuccess: Boolean = false
@SerializedName("status")
val status: Int = 0
class UploadedImage {
@SerializedName("id")
val id: String? = null
@SerializedName("link")
val link: String? = null
}
}
| WorkManager/lib/src/main/java/com/example/background/imgur/PostImageResponse.kt | 943189668 |
package coil.fetch
import coil.ImageLoader
import coil.decode.DataSource
import coil.decode.ImageSource
import coil.request.Options
import java.nio.ByteBuffer
import okio.Buffer
internal class ByteBufferFetcher(
private val data: ByteBuffer,
private val options: Options
) : Fetcher {
override suspend fun fetch(): FetchResult {
val source = try {
Buffer().apply { write(data) }
} finally {
// Reset the position so we can read the byte buffer again.
data.position(0)
}
return SourceResult(
source = ImageSource(source, options.context),
mimeType = null,
dataSource = DataSource.MEMORY
)
}
class Factory : Fetcher.Factory<ByteBuffer> {
override fun create(data: ByteBuffer, options: Options, imageLoader: ImageLoader): Fetcher {
return ByteBufferFetcher(data, options)
}
}
}
| coil-base/src/main/java/coil/fetch/ByteBufferFetcher.kt | 4234831049 |
package com.zj.example.kotlin.shengshiyuan.helloworld
/**
* Created by zhengjiong
* date: 2018/10/6 17:40
*/
class HelloKotlin74 {
/**
* 属性(properties)
*
* 一个Kotlin属性会被编译为3部分Java元素
* 1.一个getter方法
* 2.一个setter方法
* 3.一个私有的字段(field), 其名字与Kotlin的属性名一样
*
* 可以反编译后查看.
*
* 如果Kotlin属性名以is开头,那么命名约定会发生一些变化:
* 1.getter方法名与属性名一样
* 2.setter方法名则是将is替换为set
*
* 这种规则适用于任何类型,而不单单是Boolean类型.
*/
var name:String = "张三"
var isStudent:String = "yes"
fun test1() {
}
} | src/main/kotlin/com/zj/example/kotlin/shengshiyuan/helloworld/74.HelloKotlin-Java调用Kotlin.kt | 533352906 |
@file:JvmName("RxNestedScrollView")
@file:JvmMultifileClass
package com.jakewharton.rxbinding4.core
import androidx.annotation.CheckResult
import androidx.core.widget.NestedScrollView
import androidx.core.widget.NestedScrollView.OnScrollChangeListener
import com.jakewharton.rxbinding4.view.ViewScrollChangeEvent
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.core.Observer
import io.reactivex.rxjava3.android.MainThreadDisposable
import com.jakewharton.rxbinding4.internal.checkMainThread
/**
* Create an observable of scroll-change events for `view`.
*
* *Warning:* The created observable keeps a strong reference to `view`.
* Unsubscribe to free this reference.
*/
@CheckResult
fun NestedScrollView.scrollChangeEvents(): Observable<ViewScrollChangeEvent> {
return NestedScrollViewScrollChangeEventObservable(this)
}
private class NestedScrollViewScrollChangeEventObservable(
private val view: NestedScrollView
) : Observable<ViewScrollChangeEvent>() {
override fun subscribeActual(observer: Observer<in ViewScrollChangeEvent>) {
if (!checkMainThread(observer)) {
return
}
val listener = Listener(view, observer)
observer.onSubscribe(listener)
view.setOnScrollChangeListener(listener)
}
private class Listener(
private val view: NestedScrollView,
private val observer: Observer<in ViewScrollChangeEvent>
) : MainThreadDisposable(), OnScrollChangeListener {
override fun onScrollChange(
v: NestedScrollView, scrollX: Int, scrollY: Int, oldScrollX: Int,
oldScrollY: Int
) {
if (!isDisposed) {
observer.onNext(ViewScrollChangeEvent(view, scrollX, scrollY, oldScrollX, oldScrollY))
}
}
override fun onDispose() {
view.setOnScrollChangeListener(null as OnScrollChangeListener?)
}
}
}
| rxbinding-core/src/main/java/com/jakewharton/rxbinding4/core/NestedScrollViewScrollChangeEventObservable.kt | 1937785962 |
package net.perfectdreams.loritta.morenitta.gifs
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.morenitta.utils.extensions.readImage
import java.awt.image.BufferedImage
import java.io.File
import javax.imageio.stream.FileImageOutputStream
object GetOverHereGIF {
suspend fun getGIF(toUse: BufferedImage): File {
var fileName = LorittaBot.TEMP + "getoverherescorpion-" + System.currentTimeMillis() + ".gif"
var output = FileImageOutputStream(File(fileName))
val writer = GifSequenceWriter(output, BufferedImage.TYPE_INT_ARGB, 10, true)
val scaled = toUse.getScaledInstance(50, 50, BufferedImage.SCALE_SMOOTH)
for (i in 0..52) {
val file = File(LorittaBot.ASSETS + "getoverhere/scorpion_${i.toString().padStart(6, '0')}.png")
if (file.exists()) {
var ogImage = readImage(File(LorittaBot.ASSETS + "getoverhere/scorpion_${i.toString().padStart(6, '0')}.png"))
var image = BufferedImage(ogImage.width, ogImage.height, BufferedImage.TYPE_INT_ARGB)
image.graphics.drawImage(ogImage, 0, 0, null)
if (i in 0..4) {
image.graphics.drawImage(scaled, 9, 27, null)
}
if (i == 5) {
image.graphics.drawImage(scaled, 49, 27, null)
}
if (i == 6) {
image.graphics.drawImage(scaled, 124, 27, null)
}
if (i == 7) {
image.graphics.drawImage(scaled, 107, 27, null)
}
if (i in 8..9) {
image.graphics.drawImage(scaled, 118, 24, null)
}
if (i == 10) {
image.graphics.drawImage(scaled, 85, 12, null)
}
writer.writeToSequence(image)
}
}
writer.close()
output.close()
return File(fileName)
}
} | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/gifs/GetOverHereGIF.kt | 3620348549 |
package net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.utils.notifications
import net.perfectdreams.discordinteraktions.common.builder.message.embed
import net.perfectdreams.discordinteraktions.common.utils.field
import net.perfectdreams.loritta.common.utils.LorittaColors
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.ApplicationCommandContext
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.CinnamonSlashCommandExecutor
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.discordinteraktions.common.commands.options.SlashCommandArguments
import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.utils.declarations.NotificationsCommand
import net.perfectdreams.loritta.cinnamon.discord.utils.UserId
import net.perfectdreams.loritta.cinnamon.discord.utils.toKordColor
import net.perfectdreams.loritta.cinnamon.pudding.data.CorreiosPackageUpdateUserNotification
import net.perfectdreams.loritta.cinnamon.pudding.data.DailyTaxTaxedUserNotification
import net.perfectdreams.loritta.cinnamon.pudding.data.DailyTaxWarnUserNotification
import net.perfectdreams.loritta.cinnamon.pudding.data.UnknownUserNotification
class NotificationsListExecutor(loritta: LorittaBot) : CinnamonSlashCommandExecutor(loritta) {
override suspend fun execute(context: ApplicationCommandContext, args: SlashCommandArguments) {
context.deferChannelMessageEphemerally()
val notifications = context.loritta.pudding.notifications.getUserNotifications(UserId(context.user.id), 10, 0)
context.sendEphemeralMessage {
embed {
title = context.i18nContext.get(NotificationsCommand.I18N_PREFIX.List.Title)
for (notification in notifications) {
field(
"[${notification.id}] ${
when (notification) {
is DailyTaxTaxedUserNotification -> context.i18nContext.get(NotificationsCommand.I18N_PREFIX.DailyTaxTaxedUserNotification)
is DailyTaxWarnUserNotification -> context.i18nContext.get(NotificationsCommand.I18N_PREFIX.DailyTaxWarnUserNotification)
is CorreiosPackageUpdateUserNotification -> context.i18nContext.get(NotificationsCommand.I18N_PREFIX.CorreiosPackageUpdate)
is UnknownUserNotification -> context.i18nContext.get(NotificationsCommand.I18N_PREFIX.UnknownNotification)
}}",
"<t:${notification.timestamp.epochSeconds}:d> <t:${notification.timestamp.epochSeconds}:t> | <t:${notification.timestamp.epochSeconds}:R>",
false
)
}
color = LorittaColors.LorittaAqua.toKordColor()
}
}
}
} | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/vanilla/utils/notifications/NotificationsListExecutor.kt | 2649508493 |
package io.github.sandeepraju
import io.github.sandeepraju.utils.Database
import io.github.sandeepraju.utils.Image
import java.net.InetSocketAddress
import java.nio.ByteBuffer
import java.nio.channels.SelectionKey
import java.nio.channels.Selector
import java.nio.channels.ServerSocketChannel
import java.nio.channels.SocketChannel
class AsyncServer : Server {
// selector is the Java wrapper around select() system call
val selector = Selector.open()
// create a socket to listen for traffic
val channel = ServerSocketChannel.open()
override fun listen(host: String, port: Int): Unit {
println("[${this.javaClass.simpleName}] Server listening at $host:$port")
channel.bind(InetSocketAddress(host, port))
channel.configureBlocking(false)
// register the socket channel to notify when any client "connects"
channel.register(selector, channel.validOps())
// start the event loop
while (true) {
// check if any channels are ready
selector.select()
// fetch all the keys of the channels that are ready
// on the operations we registered
val readyChannelKeys = selector.selectedKeys().iterator()
while(readyChannelKeys.hasNext()) {
val currentChannelKey = readyChannelKeys.next()
when {
currentChannelKey.isAcceptable -> { // we got a new connection
// accept the new connection and register it to the selector
// so that selector notifies us when it is ready to read the data
val acceptedChannel = (currentChannelKey.channel() as ServerSocketChannel).accept()
acceptedChannel.configureBlocking(false)
acceptedChannel.register(selector, SelectionKey.OP_READ)
}
currentChannelKey.isReadable -> { // the socket is ready to be read now
// read the data onto a buffer
val data = ByteBuffer.allocate(256)
val rwChannel = currentChannelKey.channel() as SocketChannel
rwChannel.read(data)
println(String(data.array(), 0, data.position()).trim())
// CPU intensive
Image.process("/tmp/hello.png")
// I/O intensive
// Database.query("SELECT * FROM users;")
rwChannel.configureBlocking(false)
rwChannel.register(selector, SelectionKey.OP_WRITE)
}
currentChannelKey.isWritable -> { // the socket is ready to be written now
// write response to the socket
val rwChannel = currentChannelKey.channel() as SocketChannel
rwChannel.write(ByteBuffer.wrap("pong".toByteArray()))
// close the channel
rwChannel.close()
}
}
// remove the current socket from the selector since we processed it
readyChannelKeys.remove()
}
}
}
}
fun main(args: Array<String>) {
AsyncServer().listen("0.0.0.0", 9999)
} | kotlin/src/main/kotlin/io/github/sandeepraju/ServerWithEventloop.kt | 163890468 |
/*
* 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.handler
import com.netflix.spinnaker.orca.ExecutionStatus
import com.netflix.spinnaker.orca.events.ExecutionStarted
import com.netflix.spinnaker.orca.pipeline.model.Pipeline
import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository
import com.netflix.spinnaker.orca.q.*
import com.netflix.spinnaker.spek.shouldEqual
import com.nhaarman.mockito_kotlin.*
import org.jetbrains.spek.api.dsl.context
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
import org.jetbrains.spek.subject.SubjectSpek
import org.springframework.context.ApplicationEventPublisher
object StartExecutionHandlerSpec : SubjectSpek<StartExecutionHandler>({
val queue: Queue = mock()
val repository: ExecutionRepository = mock()
val publisher: ApplicationEventPublisher = mock()
subject {
StartExecutionHandler(queue, repository, publisher)
}
fun resetMocks() = reset(queue, repository, publisher)
describe("starting an execution") {
context("with a single initial stage") {
val pipeline = pipeline {
stage {
type = singleTaskStage.type
}
}
val message = StartExecution(Pipeline::class.java, pipeline.id, "foo")
beforeGroup {
whenever(repository.retrievePipeline(message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("marks the execution as running") {
verify(repository).updateStatus(message.executionId, ExecutionStatus.RUNNING)
}
it("starts the first stage") {
verify(queue).push(StartStage(
message.executionType,
message.executionId,
"foo",
pipeline.stages.first().id
))
}
it("publishes an event") {
verify(publisher).publishEvent(check<ExecutionStarted> {
it.executionType shouldEqual message.executionType
it.executionId shouldEqual message.executionId
})
}
}
context("with multiple initial stages") {
val pipeline = pipeline {
stage {
type = singleTaskStage.type
}
stage {
type = singleTaskStage.type
}
}
val message = StartExecution(Pipeline::class.java, pipeline.id, "foo")
beforeGroup {
whenever(repository.retrievePipeline(message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("starts all the initial stages") {
argumentCaptor<StartStage>().apply {
verify(queue, times(2)).push(capture())
allValues.map { it.stageId }.toSet() shouldEqual pipeline.stages.map { it.id }.toSet()
}
}
}
}
})
| orca-queue/src/test/kotlin/com/netflix/spinnaker/orca/q/handler/StartExecutionHandlerSpec.kt | 1005782233 |
package com.ghstudios.android.data.classes
import com.ghstudios.android.ITintedIcon
import com.ghstudios.android.mhgendatabase.R
enum class MeowsterType(val type:Int){
STONE(0),
FISH(1),
GRASS(2),
NUTS(3),
BONE(4),
BAIT(5),
HONEY(6),
INSECT(7),
MUSHROOM(8)
}
class MeowsterRewards : ITintedIcon {
var item:Item? = null
var location:String? = null
var isRare: Boolean = false
var rank: String? = null
var count:Int = 0
var percentage: Int = 0
var type: MeowsterType? = null
override fun getIconResourceString(): String {
return when(type){
MeowsterType.STONE -> "icon_ore"
MeowsterType.BAIT -> "icon_bait"
MeowsterType.BONE -> "icon_bone"
MeowsterType.FISH -> "icon_fish"
MeowsterType.GRASS -> "icon_herb"
MeowsterType.HONEY -> "icon_webbing"
MeowsterType.INSECT -> "icon_bug"
MeowsterType.MUSHROOM -> "icon_mushroom"
else -> "icon_unknown"
}
}
override fun getColorArrayId(): Int {
return R.array.item_colors
}
override fun getIconColorIndex(): Int {
return 0
}
}
| app/src/main/java/com/ghstudios/android/data/classes/MeowsterRewards.kt | 3548973357 |
package com.pinterest.ktlint.reporter.plain
import com.pinterest.ktlint.core.Reporter
import com.pinterest.ktlint.core.ReporterProvider
import com.pinterest.ktlint.reporter.plain.internal.Color
import java.io.PrintStream
public class PlainReporterProvider : ReporterProvider {
override val id: String = "plain"
override fun get(out: PrintStream, opt: Map<String, String>): Reporter =
PlainReporter(
out,
verbose = opt["verbose"]?.emptyOrTrue() ?: false,
groupByFile = opt["group_by_file"]?.emptyOrTrue() ?: false,
shouldColorOutput = opt["color"]?.emptyOrTrue() ?: false,
outputColor = getColor(opt["color_name"]),
pad = opt["pad"]?.emptyOrTrue() ?: false
)
private fun String.emptyOrTrue() = this == "" || this == "true"
private fun getColor(colorInput: String?): Color {
return Color.values().firstOrNull { it.name == colorInput } ?: throw IllegalArgumentException("Invalid color parameter.")
}
}
| ktlint-reporter-plain/src/main/kotlin/com/pinterest/ktlint/reporter/plain/PlainReporterProvider.kt | 3310662790 |
//package ir.iais.utilities.javautils.validators.annotations
//
//import ir.iais.utilities.javautils.validators.DbUniqueFieldValidator
//import javax.validation.Constraint
//import javax.validation.Payload
//import kotlin.reflect.KClass
//
///** unique field MUST be a Lookup at couchbase database */
//@Target(AnnotationTarget.CLASS, AnnotationTarget.FILE, AnnotationTarget.ANNOTATION_CLASS)
//@Retention(AnnotationRetention.RUNTIME)
//@Repeatable
//@Constraint(validatedBy = arrayOf(DbUniqueFieldValidator::class))
//@MustBeDocumented
//annotation class DbUniqueField(val message: String = DbUniqueFieldValidator.MESSAGE,
// val groups: Array<KClass<*>> = arrayOf(),
// val payload: Array<KClass<out Payload>> = arrayOf(),
// /** @return The first field
// */
// val fields: Array<String>)
//
//
//
| src/main/java/ir/iais/utilities/javautils/validators/annotations/DbUniqueField.kt | 2634434398 |
package com.kazakago.preferhythm.samplekotlin
import org.junit.Assert.assertEquals
import org.junit.Test
/**
* Example local unit test, which will execute on the development machine (host).
* @see [Testing documentation](http://d.android.com/tools/testing)
*/
class ExampleUnitTest {
@Test
@Throws(Exception::class)
fun addition_isCorrect() {
assertEquals(4, (2 + 2).toLong())
}
} | samplekotlin/src/test/java/com/kazakago/preferhythm/samplekotlin/ExampleUnitTest.kt | 230670905 |
data class Tuple11<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(val item1: T1, val item2: T2, val item3: T3, val item4: T4, val item5: T5, val item6: T6, val item7: T7, val item8: T8, val item9: T9, val item10: T10, val item11: T11) {
}
| src/main/kotlin/com/github/kmizu/kollection/tuples/Tuple11.kt | 2926743383 |
/*
* Copyright (C) 2016 - Niklas Baudy, Ruben Gees, Mario Đanić and contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.vanniktech.emoji.facebook.category
import com.vanniktech.emoji.facebook.FacebookEmoji
internal object SmileysAndPeopleCategoryChunk3 {
internal val EMOJIS: List<FacebookEmoji> = listOf(
FacebookEmoji(String(intArrayOf(0x1F9DF), 0, 1), listOf("zombie"), 53, 13, true),
FacebookEmoji(String(intArrayOf(0x1F9DF, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("male_zombie"), 53, 12, false),
FacebookEmoji(String(intArrayOf(0x1F9DF, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("female_zombie"), 53, 11, false),
FacebookEmoji(
String(intArrayOf(0x1F486), 0, 1), listOf("massage"), 26, 10, true,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F486, 0x1F3FB), 0, 2), emptyList<String>(), 26, 11, false),
FacebookEmoji(String(intArrayOf(0x1F486, 0x1F3FC), 0, 2), emptyList<String>(), 26, 12, false),
FacebookEmoji(String(intArrayOf(0x1F486, 0x1F3FD), 0, 2), emptyList<String>(), 26, 13, false),
FacebookEmoji(String(intArrayOf(0x1F486, 0x1F3FE), 0, 2), emptyList<String>(), 26, 14, false),
FacebookEmoji(String(intArrayOf(0x1F486, 0x1F3FF), 0, 2), emptyList<String>(), 26, 15, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F486, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man-getting-massage"), 26, 4, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F486, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 26, 5, false),
FacebookEmoji(String(intArrayOf(0x1F486, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 26, 6, false),
FacebookEmoji(String(intArrayOf(0x1F486, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 26, 7, false),
FacebookEmoji(String(intArrayOf(0x1F486, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 26, 8, false),
FacebookEmoji(String(intArrayOf(0x1F486, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 26, 9, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F486, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman-getting-massage"), 25, 59, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F486, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 25, 60, false),
FacebookEmoji(String(intArrayOf(0x1F486, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 26, 0, false),
FacebookEmoji(String(intArrayOf(0x1F486, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 26, 1, false),
FacebookEmoji(String(intArrayOf(0x1F486, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 26, 2, false),
FacebookEmoji(String(intArrayOf(0x1F486, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 26, 3, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F487), 0, 1), listOf("haircut"), 26, 28, true,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F487, 0x1F3FB), 0, 2), emptyList<String>(), 26, 29, false),
FacebookEmoji(String(intArrayOf(0x1F487, 0x1F3FC), 0, 2), emptyList<String>(), 26, 30, false),
FacebookEmoji(String(intArrayOf(0x1F487, 0x1F3FD), 0, 2), emptyList<String>(), 26, 31, false),
FacebookEmoji(String(intArrayOf(0x1F487, 0x1F3FE), 0, 2), emptyList<String>(), 26, 32, false),
FacebookEmoji(String(intArrayOf(0x1F487, 0x1F3FF), 0, 2), emptyList<String>(), 26, 33, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F487, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man-getting-haircut"), 26, 22, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F487, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 26, 23, false),
FacebookEmoji(String(intArrayOf(0x1F487, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 26, 24, false),
FacebookEmoji(String(intArrayOf(0x1F487, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 26, 25, false),
FacebookEmoji(String(intArrayOf(0x1F487, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 26, 26, false),
FacebookEmoji(String(intArrayOf(0x1F487, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 26, 27, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F487, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman-getting-haircut"), 26, 16, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F487, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 26, 17, false),
FacebookEmoji(String(intArrayOf(0x1F487, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 26, 18, false),
FacebookEmoji(String(intArrayOf(0x1F487, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 26, 19, false),
FacebookEmoji(String(intArrayOf(0x1F487, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 26, 20, false),
FacebookEmoji(String(intArrayOf(0x1F487, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 26, 21, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F6B6), 0, 1), listOf("walking"), 37, 27, true,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F6B6, 0x1F3FB), 0, 2), emptyList<String>(), 37, 28, false),
FacebookEmoji(String(intArrayOf(0x1F6B6, 0x1F3FC), 0, 2), emptyList<String>(), 37, 29, false),
FacebookEmoji(String(intArrayOf(0x1F6B6, 0x1F3FD), 0, 2), emptyList<String>(), 37, 30, false),
FacebookEmoji(String(intArrayOf(0x1F6B6, 0x1F3FE), 0, 2), emptyList<String>(), 37, 31, false),
FacebookEmoji(String(intArrayOf(0x1F6B6, 0x1F3FF), 0, 2), emptyList<String>(), 37, 32, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F6B6, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man-walking"), 37, 21, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F6B6, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 37, 22, false),
FacebookEmoji(String(intArrayOf(0x1F6B6, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 37, 23, false),
FacebookEmoji(String(intArrayOf(0x1F6B6, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 37, 24, false),
FacebookEmoji(String(intArrayOf(0x1F6B6, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 37, 25, false),
FacebookEmoji(String(intArrayOf(0x1F6B6, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 37, 26, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F6B6, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman-walking"), 37, 15, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F6B6, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 37, 16, false),
FacebookEmoji(String(intArrayOf(0x1F6B6, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 37, 17, false),
FacebookEmoji(String(intArrayOf(0x1F6B6, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 37, 18, false),
FacebookEmoji(String(intArrayOf(0x1F6B6, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 37, 19, false),
FacebookEmoji(String(intArrayOf(0x1F6B6, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 37, 20, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F9CD), 0, 1), listOf("standing_person"), 46, 30, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F9CD, 0x1F3FB), 0, 2), emptyList<String>(), 46, 31, false),
FacebookEmoji(String(intArrayOf(0x1F9CD, 0x1F3FC), 0, 2), emptyList<String>(), 46, 32, false),
FacebookEmoji(String(intArrayOf(0x1F9CD, 0x1F3FD), 0, 2), emptyList<String>(), 46, 33, false),
FacebookEmoji(String(intArrayOf(0x1F9CD, 0x1F3FE), 0, 2), emptyList<String>(), 46, 34, false),
FacebookEmoji(String(intArrayOf(0x1F9CD, 0x1F3FF), 0, 2), emptyList<String>(), 46, 35, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F9CD, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man_standing"), 46, 24, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F9CD, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 46, 25, false),
FacebookEmoji(String(intArrayOf(0x1F9CD, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 46, 26, false),
FacebookEmoji(String(intArrayOf(0x1F9CD, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 46, 27, false),
FacebookEmoji(String(intArrayOf(0x1F9CD, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 46, 28, false),
FacebookEmoji(String(intArrayOf(0x1F9CD, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 46, 29, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F9CD, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman_standing"), 46, 18, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F9CD, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 46, 19, false),
FacebookEmoji(String(intArrayOf(0x1F9CD, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 46, 20, false),
FacebookEmoji(String(intArrayOf(0x1F9CD, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 46, 21, false),
FacebookEmoji(String(intArrayOf(0x1F9CD, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 46, 22, false),
FacebookEmoji(String(intArrayOf(0x1F9CD, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 46, 23, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F9CE), 0, 1), listOf("kneeling_person"), 46, 48, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F9CE, 0x1F3FB), 0, 2), emptyList<String>(), 46, 49, false),
FacebookEmoji(String(intArrayOf(0x1F9CE, 0x1F3FC), 0, 2), emptyList<String>(), 46, 50, false),
FacebookEmoji(String(intArrayOf(0x1F9CE, 0x1F3FD), 0, 2), emptyList<String>(), 46, 51, false),
FacebookEmoji(String(intArrayOf(0x1F9CE, 0x1F3FE), 0, 2), emptyList<String>(), 46, 52, false),
FacebookEmoji(String(intArrayOf(0x1F9CE, 0x1F3FF), 0, 2), emptyList<String>(), 46, 53, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F9CE, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man_kneeling"), 46, 42, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F9CE, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 46, 43, false),
FacebookEmoji(String(intArrayOf(0x1F9CE, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 46, 44, false),
FacebookEmoji(String(intArrayOf(0x1F9CE, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 46, 45, false),
FacebookEmoji(String(intArrayOf(0x1F9CE, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 46, 46, false),
FacebookEmoji(String(intArrayOf(0x1F9CE, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 46, 47, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F9CE, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman_kneeling"), 46, 36, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F9CE, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 46, 37, false),
FacebookEmoji(String(intArrayOf(0x1F9CE, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 46, 38, false),
FacebookEmoji(String(intArrayOf(0x1F9CE, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 46, 39, false),
FacebookEmoji(String(intArrayOf(0x1F9CE, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 46, 40, false),
FacebookEmoji(String(intArrayOf(0x1F9CE, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 46, 41, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F9D1, 0x200D, 0x1F9AF), 0, 3), listOf("person_with_probing_cane"), 49, 6, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F9D1, 0x1F3FB, 0x200D, 0x1F9AF), 0, 4), emptyList<String>(), 49, 7, false),
FacebookEmoji(String(intArrayOf(0x1F9D1, 0x1F3FC, 0x200D, 0x1F9AF), 0, 4), emptyList<String>(), 49, 8, false),
FacebookEmoji(String(intArrayOf(0x1F9D1, 0x1F3FD, 0x200D, 0x1F9AF), 0, 4), emptyList<String>(), 49, 9, false),
FacebookEmoji(String(intArrayOf(0x1F9D1, 0x1F3FE, 0x200D, 0x1F9AF), 0, 4), emptyList<String>(), 49, 10, false),
FacebookEmoji(String(intArrayOf(0x1F9D1, 0x1F3FF, 0x200D, 0x1F9AF), 0, 4), emptyList<String>(), 49, 11, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F468, 0x200D, 0x1F9AF), 0, 3), listOf("man_with_probing_cane"), 15, 23, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F468, 0x1F3FB, 0x200D, 0x1F9AF), 0, 4), emptyList<String>(), 15, 24, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x1F3FC, 0x200D, 0x1F9AF), 0, 4), emptyList<String>(), 15, 25, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x1F3FD, 0x200D, 0x1F9AF), 0, 4), emptyList<String>(), 15, 26, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x1F3FE, 0x200D, 0x1F9AF), 0, 4), emptyList<String>(), 15, 27, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x1F3FF, 0x200D, 0x1F9AF), 0, 4), emptyList<String>(), 15, 28, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F469, 0x200D, 0x1F9AF), 0, 3), listOf("woman_with_probing_cane"), 18, 52, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FB, 0x200D, 0x1F9AF), 0, 4), emptyList<String>(), 18, 53, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FC, 0x200D, 0x1F9AF), 0, 4), emptyList<String>(), 18, 54, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FD, 0x200D, 0x1F9AF), 0, 4), emptyList<String>(), 18, 55, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FE, 0x200D, 0x1F9AF), 0, 4), emptyList<String>(), 18, 56, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FF, 0x200D, 0x1F9AF), 0, 4), emptyList<String>(), 18, 57, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F9D1, 0x200D, 0x1F9BC), 0, 3), listOf("person_in_motorized_wheelchair"), 49, 36, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F9D1, 0x1F3FB, 0x200D, 0x1F9BC), 0, 4), emptyList<String>(), 49, 37, false),
FacebookEmoji(String(intArrayOf(0x1F9D1, 0x1F3FC, 0x200D, 0x1F9BC), 0, 4), emptyList<String>(), 49, 38, false),
FacebookEmoji(String(intArrayOf(0x1F9D1, 0x1F3FD, 0x200D, 0x1F9BC), 0, 4), emptyList<String>(), 49, 39, false),
FacebookEmoji(String(intArrayOf(0x1F9D1, 0x1F3FE, 0x200D, 0x1F9BC), 0, 4), emptyList<String>(), 49, 40, false),
FacebookEmoji(String(intArrayOf(0x1F9D1, 0x1F3FF, 0x200D, 0x1F9BC), 0, 4), emptyList<String>(), 49, 41, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F468, 0x200D, 0x1F9BC), 0, 3), listOf("man_in_motorized_wheelchair"), 15, 53, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F468, 0x1F3FB, 0x200D, 0x1F9BC), 0, 4), emptyList<String>(), 15, 54, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x1F3FC, 0x200D, 0x1F9BC), 0, 4), emptyList<String>(), 15, 55, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x1F3FD, 0x200D, 0x1F9BC), 0, 4), emptyList<String>(), 15, 56, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x1F3FE, 0x200D, 0x1F9BC), 0, 4), emptyList<String>(), 15, 57, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x1F3FF, 0x200D, 0x1F9BC), 0, 4), emptyList<String>(), 15, 58, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F469, 0x200D, 0x1F9BC), 0, 3), listOf("woman_in_motorized_wheelchair"), 19, 21, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FB, 0x200D, 0x1F9BC), 0, 4), emptyList<String>(), 19, 22, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FC, 0x200D, 0x1F9BC), 0, 4), emptyList<String>(), 19, 23, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FD, 0x200D, 0x1F9BC), 0, 4), emptyList<String>(), 19, 24, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FE, 0x200D, 0x1F9BC), 0, 4), emptyList<String>(), 19, 25, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FF, 0x200D, 0x1F9BC), 0, 4), emptyList<String>(), 19, 26, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F9D1, 0x200D, 0x1F9BD), 0, 3), listOf("person_in_manual_wheelchair"), 49, 42, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F9D1, 0x1F3FB, 0x200D, 0x1F9BD), 0, 4), emptyList<String>(), 49, 43, false),
FacebookEmoji(String(intArrayOf(0x1F9D1, 0x1F3FC, 0x200D, 0x1F9BD), 0, 4), emptyList<String>(), 49, 44, false),
FacebookEmoji(String(intArrayOf(0x1F9D1, 0x1F3FD, 0x200D, 0x1F9BD), 0, 4), emptyList<String>(), 49, 45, false),
FacebookEmoji(String(intArrayOf(0x1F9D1, 0x1F3FE, 0x200D, 0x1F9BD), 0, 4), emptyList<String>(), 49, 46, false),
FacebookEmoji(String(intArrayOf(0x1F9D1, 0x1F3FF, 0x200D, 0x1F9BD), 0, 4), emptyList<String>(), 49, 47, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F468, 0x200D, 0x1F9BD), 0, 3), listOf("man_in_manual_wheelchair"), 15, 59, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F468, 0x1F3FB, 0x200D, 0x1F9BD), 0, 4), emptyList<String>(), 15, 60, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x1F3FC, 0x200D, 0x1F9BD), 0, 4), emptyList<String>(), 16, 0, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x1F3FD, 0x200D, 0x1F9BD), 0, 4), emptyList<String>(), 16, 1, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x1F3FE, 0x200D, 0x1F9BD), 0, 4), emptyList<String>(), 16, 2, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x1F3FF, 0x200D, 0x1F9BD), 0, 4), emptyList<String>(), 16, 3, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F469, 0x200D, 0x1F9BD), 0, 3), listOf("woman_in_manual_wheelchair"), 19, 27, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FB, 0x200D, 0x1F9BD), 0, 4), emptyList<String>(), 19, 28, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FC, 0x200D, 0x1F9BD), 0, 4), emptyList<String>(), 19, 29, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FD, 0x200D, 0x1F9BD), 0, 4), emptyList<String>(), 19, 30, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FE, 0x200D, 0x1F9BD), 0, 4), emptyList<String>(), 19, 31, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FF, 0x200D, 0x1F9BD), 0, 4), emptyList<String>(), 19, 32, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F3C3), 0, 1), listOf("runner", "running"), 8, 26, true,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F3C3, 0x1F3FB), 0, 2), emptyList<String>(), 8, 27, false),
FacebookEmoji(String(intArrayOf(0x1F3C3, 0x1F3FC), 0, 2), emptyList<String>(), 8, 28, false),
FacebookEmoji(String(intArrayOf(0x1F3C3, 0x1F3FD), 0, 2), emptyList<String>(), 8, 29, false),
FacebookEmoji(String(intArrayOf(0x1F3C3, 0x1F3FE), 0, 2), emptyList<String>(), 8, 30, false),
FacebookEmoji(String(intArrayOf(0x1F3C3, 0x1F3FF), 0, 2), emptyList<String>(), 8, 31, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F3C3, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man-running"), 8, 20, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F3C3, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 8, 21, false),
FacebookEmoji(String(intArrayOf(0x1F3C3, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 8, 22, false),
FacebookEmoji(String(intArrayOf(0x1F3C3, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 8, 23, false),
FacebookEmoji(String(intArrayOf(0x1F3C3, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 8, 24, false),
FacebookEmoji(String(intArrayOf(0x1F3C3, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 8, 25, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F3C3, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman-running"), 8, 14, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F3C3, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 8, 15, false),
FacebookEmoji(String(intArrayOf(0x1F3C3, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 8, 16, false),
FacebookEmoji(String(intArrayOf(0x1F3C3, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 8, 17, false),
FacebookEmoji(String(intArrayOf(0x1F3C3, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 8, 18, false),
FacebookEmoji(String(intArrayOf(0x1F3C3, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 8, 19, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F483), 0, 1), listOf("dancer"), 25, 46, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F483, 0x1F3FB), 0, 2), emptyList<String>(), 25, 47, false),
FacebookEmoji(String(intArrayOf(0x1F483, 0x1F3FC), 0, 2), emptyList<String>(), 25, 48, false),
FacebookEmoji(String(intArrayOf(0x1F483, 0x1F3FD), 0, 2), emptyList<String>(), 25, 49, false),
FacebookEmoji(String(intArrayOf(0x1F483, 0x1F3FE), 0, 2), emptyList<String>(), 25, 50, false),
FacebookEmoji(String(intArrayOf(0x1F483, 0x1F3FF), 0, 2), emptyList<String>(), 25, 51, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F57A), 0, 1), listOf("man_dancing"), 31, 26, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F57A, 0x1F3FB), 0, 2), emptyList<String>(), 31, 27, false),
FacebookEmoji(String(intArrayOf(0x1F57A, 0x1F3FC), 0, 2), emptyList<String>(), 31, 28, false),
FacebookEmoji(String(intArrayOf(0x1F57A, 0x1F3FD), 0, 2), emptyList<String>(), 31, 29, false),
FacebookEmoji(String(intArrayOf(0x1F57A, 0x1F3FE), 0, 2), emptyList<String>(), 31, 30, false),
FacebookEmoji(String(intArrayOf(0x1F57A, 0x1F3FF), 0, 2), emptyList<String>(), 31, 31, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F574, 0xFE0F), 0, 2), listOf("man_in_business_suit_levitating"), 30, 59, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F574, 0x1F3FB), 0, 2), emptyList<String>(), 30, 60, false),
FacebookEmoji(String(intArrayOf(0x1F574, 0x1F3FC), 0, 2), emptyList<String>(), 31, 0, false),
FacebookEmoji(String(intArrayOf(0x1F574, 0x1F3FD), 0, 2), emptyList<String>(), 31, 1, false),
FacebookEmoji(String(intArrayOf(0x1F574, 0x1F3FE), 0, 2), emptyList<String>(), 31, 2, false),
FacebookEmoji(String(intArrayOf(0x1F574, 0x1F3FF), 0, 2), emptyList<String>(), 31, 3, false),
),
),
FacebookEmoji(String(intArrayOf(0x1F46F), 0, 1), listOf("dancers"), 23, 16, true),
FacebookEmoji(String(intArrayOf(0x1F46F, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("men-with-bunny-ears-partying", "man-with-bunny-ears-partying"), 23, 15, false),
FacebookEmoji(String(intArrayOf(0x1F46F, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("women-with-bunny-ears-partying", "woman-with-bunny-ears-partying"), 23, 14, false),
FacebookEmoji(
String(intArrayOf(0x1F9D6), 0, 1), listOf("person_in_steamy_room"), 50, 59, true,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F9D6, 0x1F3FB), 0, 2), emptyList<String>(), 50, 60, true),
FacebookEmoji(String(intArrayOf(0x1F9D6, 0x1F3FC), 0, 2), emptyList<String>(), 51, 0, true),
FacebookEmoji(String(intArrayOf(0x1F9D6, 0x1F3FD), 0, 2), emptyList<String>(), 51, 1, true),
FacebookEmoji(String(intArrayOf(0x1F9D6, 0x1F3FE), 0, 2), emptyList<String>(), 51, 2, true),
FacebookEmoji(String(intArrayOf(0x1F9D6, 0x1F3FF), 0, 2), emptyList<String>(), 51, 3, true),
),
),
FacebookEmoji(
String(intArrayOf(0x1F9D6, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man_in_steamy_room"), 50, 53, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F9D6, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 50, 54, false),
FacebookEmoji(String(intArrayOf(0x1F9D6, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 50, 55, false),
FacebookEmoji(String(intArrayOf(0x1F9D6, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 50, 56, false),
FacebookEmoji(String(intArrayOf(0x1F9D6, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 50, 57, false),
FacebookEmoji(String(intArrayOf(0x1F9D6, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 50, 58, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F9D6, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman_in_steamy_room"), 50, 47, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F9D6, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 50, 48, false),
FacebookEmoji(String(intArrayOf(0x1F9D6, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 50, 49, false),
FacebookEmoji(String(intArrayOf(0x1F9D6, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 50, 50, false),
FacebookEmoji(String(intArrayOf(0x1F9D6, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 50, 51, false),
FacebookEmoji(String(intArrayOf(0x1F9D6, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 50, 52, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F9D7), 0, 1), listOf("person_climbing"), 51, 16, true,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F9D7, 0x1F3FB), 0, 2), emptyList<String>(), 51, 17, true),
FacebookEmoji(String(intArrayOf(0x1F9D7, 0x1F3FC), 0, 2), emptyList<String>(), 51, 18, true),
FacebookEmoji(String(intArrayOf(0x1F9D7, 0x1F3FD), 0, 2), emptyList<String>(), 51, 19, true),
FacebookEmoji(String(intArrayOf(0x1F9D7, 0x1F3FE), 0, 2), emptyList<String>(), 51, 20, true),
FacebookEmoji(String(intArrayOf(0x1F9D7, 0x1F3FF), 0, 2), emptyList<String>(), 51, 21, true),
),
),
FacebookEmoji(
String(intArrayOf(0x1F9D7, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man_climbing"), 51, 10, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F9D7, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 51, 11, false),
FacebookEmoji(String(intArrayOf(0x1F9D7, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 51, 12, false),
FacebookEmoji(String(intArrayOf(0x1F9D7, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 51, 13, false),
FacebookEmoji(String(intArrayOf(0x1F9D7, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 51, 14, false),
FacebookEmoji(String(intArrayOf(0x1F9D7, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 51, 15, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F9D7, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman_climbing"), 51, 4, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F9D7, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 51, 5, false),
FacebookEmoji(String(intArrayOf(0x1F9D7, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 51, 6, false),
FacebookEmoji(String(intArrayOf(0x1F9D7, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 51, 7, false),
FacebookEmoji(String(intArrayOf(0x1F9D7, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 51, 8, false),
FacebookEmoji(String(intArrayOf(0x1F9D7, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 51, 9, false),
),
),
FacebookEmoji(String(intArrayOf(0x1F93A), 0, 1), listOf("fencer"), 42, 31, false),
FacebookEmoji(
String(intArrayOf(0x1F3C7), 0, 1), listOf("horse_racing"), 8, 52, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F3C7, 0x1F3FB), 0, 2), emptyList<String>(), 8, 53, false),
FacebookEmoji(String(intArrayOf(0x1F3C7, 0x1F3FC), 0, 2), emptyList<String>(), 8, 54, false),
FacebookEmoji(String(intArrayOf(0x1F3C7, 0x1F3FD), 0, 2), emptyList<String>(), 8, 55, false),
FacebookEmoji(String(intArrayOf(0x1F3C7, 0x1F3FE), 0, 2), emptyList<String>(), 8, 56, false),
FacebookEmoji(String(intArrayOf(0x1F3C7, 0x1F3FF), 0, 2), emptyList<String>(), 8, 57, false),
),
),
FacebookEmoji(String(intArrayOf(0x26F7, 0xFE0F), 0, 2), listOf("skier"), 58, 1, false),
FacebookEmoji(
String(intArrayOf(0x1F3C2), 0, 1), listOf("snowboarder"), 8, 8, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F3C2, 0x1F3FB), 0, 2), emptyList<String>(), 8, 9, false),
FacebookEmoji(String(intArrayOf(0x1F3C2, 0x1F3FC), 0, 2), emptyList<String>(), 8, 10, false),
FacebookEmoji(String(intArrayOf(0x1F3C2, 0x1F3FD), 0, 2), emptyList<String>(), 8, 11, false),
FacebookEmoji(String(intArrayOf(0x1F3C2, 0x1F3FE), 0, 2), emptyList<String>(), 8, 12, false),
FacebookEmoji(String(intArrayOf(0x1F3C2, 0x1F3FF), 0, 2), emptyList<String>(), 8, 13, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F3CC, 0xFE0F), 0, 2), listOf("golfer"), 9, 47, true,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F3CC, 0x1F3FB), 0, 2), emptyList<String>(), 9, 48, false),
FacebookEmoji(String(intArrayOf(0x1F3CC, 0x1F3FC), 0, 2), emptyList<String>(), 9, 49, false),
FacebookEmoji(String(intArrayOf(0x1F3CC, 0x1F3FD), 0, 2), emptyList<String>(), 9, 50, false),
FacebookEmoji(String(intArrayOf(0x1F3CC, 0x1F3FE), 0, 2), emptyList<String>(), 9, 51, false),
FacebookEmoji(String(intArrayOf(0x1F3CC, 0x1F3FF), 0, 2), emptyList<String>(), 9, 52, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F3C4), 0, 1), listOf("surfer"), 8, 44, true,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F3C4, 0x1F3FB), 0, 2), emptyList<String>(), 8, 45, false),
FacebookEmoji(String(intArrayOf(0x1F3C4, 0x1F3FC), 0, 2), emptyList<String>(), 8, 46, false),
FacebookEmoji(String(intArrayOf(0x1F3C4, 0x1F3FD), 0, 2), emptyList<String>(), 8, 47, false),
FacebookEmoji(String(intArrayOf(0x1F3C4, 0x1F3FE), 0, 2), emptyList<String>(), 8, 48, false),
FacebookEmoji(String(intArrayOf(0x1F3C4, 0x1F3FF), 0, 2), emptyList<String>(), 8, 49, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F3C4, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man-surfing"), 8, 38, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F3C4, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 8, 39, false),
FacebookEmoji(String(intArrayOf(0x1F3C4, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 8, 40, false),
FacebookEmoji(String(intArrayOf(0x1F3C4, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 8, 41, false),
FacebookEmoji(String(intArrayOf(0x1F3C4, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 8, 42, false),
FacebookEmoji(String(intArrayOf(0x1F3C4, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 8, 43, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F3C4, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman-surfing"), 8, 32, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F3C4, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 8, 33, false),
FacebookEmoji(String(intArrayOf(0x1F3C4, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 8, 34, false),
FacebookEmoji(String(intArrayOf(0x1F3C4, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 8, 35, false),
FacebookEmoji(String(intArrayOf(0x1F3C4, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 8, 36, false),
FacebookEmoji(String(intArrayOf(0x1F3C4, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 8, 37, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F6A3), 0, 1), listOf("rowboat"), 36, 18, true,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F6A3, 0x1F3FB), 0, 2), emptyList<String>(), 36, 19, false),
FacebookEmoji(String(intArrayOf(0x1F6A3, 0x1F3FC), 0, 2), emptyList<String>(), 36, 20, false),
FacebookEmoji(String(intArrayOf(0x1F6A3, 0x1F3FD), 0, 2), emptyList<String>(), 36, 21, false),
FacebookEmoji(String(intArrayOf(0x1F6A3, 0x1F3FE), 0, 2), emptyList<String>(), 36, 22, false),
FacebookEmoji(String(intArrayOf(0x1F6A3, 0x1F3FF), 0, 2), emptyList<String>(), 36, 23, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F6A3, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man-rowing-boat"), 36, 12, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F6A3, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 36, 13, false),
FacebookEmoji(String(intArrayOf(0x1F6A3, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 36, 14, false),
FacebookEmoji(String(intArrayOf(0x1F6A3, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 36, 15, false),
FacebookEmoji(String(intArrayOf(0x1F6A3, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 36, 16, false),
FacebookEmoji(String(intArrayOf(0x1F6A3, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 36, 17, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F6A3, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman-rowing-boat"), 36, 6, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F6A3, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 36, 7, false),
FacebookEmoji(String(intArrayOf(0x1F6A3, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 36, 8, false),
FacebookEmoji(String(intArrayOf(0x1F6A3, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 36, 9, false),
FacebookEmoji(String(intArrayOf(0x1F6A3, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 36, 10, false),
FacebookEmoji(String(intArrayOf(0x1F6A3, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 36, 11, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F3CA), 0, 1), listOf("swimmer"), 9, 11, true,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F3CA, 0x1F3FB), 0, 2), emptyList<String>(), 9, 12, false),
FacebookEmoji(String(intArrayOf(0x1F3CA, 0x1F3FC), 0, 2), emptyList<String>(), 9, 13, false),
FacebookEmoji(String(intArrayOf(0x1F3CA, 0x1F3FD), 0, 2), emptyList<String>(), 9, 14, false),
FacebookEmoji(String(intArrayOf(0x1F3CA, 0x1F3FE), 0, 2), emptyList<String>(), 9, 15, false),
FacebookEmoji(String(intArrayOf(0x1F3CA, 0x1F3FF), 0, 2), emptyList<String>(), 9, 16, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F3CA, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man-swimming"), 9, 5, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F3CA, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 9, 6, false),
FacebookEmoji(String(intArrayOf(0x1F3CA, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 9, 7, false),
FacebookEmoji(String(intArrayOf(0x1F3CA, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 9, 8, false),
FacebookEmoji(String(intArrayOf(0x1F3CA, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 9, 9, false),
FacebookEmoji(String(intArrayOf(0x1F3CA, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 9, 10, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F3CA, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman-swimming"), 8, 60, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F3CA, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 9, 0, false),
FacebookEmoji(String(intArrayOf(0x1F3CA, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 9, 1, false),
FacebookEmoji(String(intArrayOf(0x1F3CA, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 9, 2, false),
FacebookEmoji(String(intArrayOf(0x1F3CA, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 9, 3, false),
FacebookEmoji(String(intArrayOf(0x1F3CA, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 9, 4, false),
),
),
FacebookEmoji(
String(intArrayOf(0x26F9, 0xFE0F), 0, 2), listOf("person_with_ball"), 58, 15, true,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x26F9, 0x1F3FB), 0, 2), emptyList<String>(), 58, 16, false),
FacebookEmoji(String(intArrayOf(0x26F9, 0x1F3FC), 0, 2), emptyList<String>(), 58, 17, false),
FacebookEmoji(String(intArrayOf(0x26F9, 0x1F3FD), 0, 2), emptyList<String>(), 58, 18, false),
FacebookEmoji(String(intArrayOf(0x26F9, 0x1F3FE), 0, 2), emptyList<String>(), 58, 19, false),
FacebookEmoji(String(intArrayOf(0x26F9, 0x1F3FF), 0, 2), emptyList<String>(), 58, 20, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F3CB, 0xFE0F), 0, 2), listOf("weight_lifter"), 9, 29, true,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F3CB, 0x1F3FB), 0, 2), emptyList<String>(), 9, 30, false),
FacebookEmoji(String(intArrayOf(0x1F3CB, 0x1F3FC), 0, 2), emptyList<String>(), 9, 31, false),
FacebookEmoji(String(intArrayOf(0x1F3CB, 0x1F3FD), 0, 2), emptyList<String>(), 9, 32, false),
FacebookEmoji(String(intArrayOf(0x1F3CB, 0x1F3FE), 0, 2), emptyList<String>(), 9, 33, false),
FacebookEmoji(String(intArrayOf(0x1F3CB, 0x1F3FF), 0, 2), emptyList<String>(), 9, 34, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F6B4), 0, 1), listOf("bicyclist"), 36, 52, true,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F6B4, 0x1F3FB), 0, 2), emptyList<String>(), 36, 53, false),
FacebookEmoji(String(intArrayOf(0x1F6B4, 0x1F3FC), 0, 2), emptyList<String>(), 36, 54, false),
FacebookEmoji(String(intArrayOf(0x1F6B4, 0x1F3FD), 0, 2), emptyList<String>(), 36, 55, false),
FacebookEmoji(String(intArrayOf(0x1F6B4, 0x1F3FE), 0, 2), emptyList<String>(), 36, 56, false),
FacebookEmoji(String(intArrayOf(0x1F6B4, 0x1F3FF), 0, 2), emptyList<String>(), 36, 57, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F6B4, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man-biking"), 36, 46, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F6B4, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 36, 47, false),
FacebookEmoji(String(intArrayOf(0x1F6B4, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 36, 48, false),
FacebookEmoji(String(intArrayOf(0x1F6B4, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 36, 49, false),
FacebookEmoji(String(intArrayOf(0x1F6B4, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 36, 50, false),
FacebookEmoji(String(intArrayOf(0x1F6B4, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 36, 51, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F6B4, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman-biking"), 36, 40, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F6B4, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 36, 41, false),
FacebookEmoji(String(intArrayOf(0x1F6B4, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 36, 42, false),
FacebookEmoji(String(intArrayOf(0x1F6B4, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 36, 43, false),
FacebookEmoji(String(intArrayOf(0x1F6B4, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 36, 44, false),
FacebookEmoji(String(intArrayOf(0x1F6B4, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 36, 45, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F6B5), 0, 1), listOf("mountain_bicyclist"), 37, 9, true,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F6B5, 0x1F3FB), 0, 2), emptyList<String>(), 37, 10, false),
FacebookEmoji(String(intArrayOf(0x1F6B5, 0x1F3FC), 0, 2), emptyList<String>(), 37, 11, false),
FacebookEmoji(String(intArrayOf(0x1F6B5, 0x1F3FD), 0, 2), emptyList<String>(), 37, 12, false),
FacebookEmoji(String(intArrayOf(0x1F6B5, 0x1F3FE), 0, 2), emptyList<String>(), 37, 13, false),
FacebookEmoji(String(intArrayOf(0x1F6B5, 0x1F3FF), 0, 2), emptyList<String>(), 37, 14, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F6B5, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man-mountain-biking"), 37, 3, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F6B5, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 37, 4, false),
FacebookEmoji(String(intArrayOf(0x1F6B5, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 37, 5, false),
FacebookEmoji(String(intArrayOf(0x1F6B5, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 37, 6, false),
FacebookEmoji(String(intArrayOf(0x1F6B5, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 37, 7, false),
FacebookEmoji(String(intArrayOf(0x1F6B5, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 37, 8, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F6B5, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman-mountain-biking"), 36, 58, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F6B5, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 36, 59, false),
FacebookEmoji(String(intArrayOf(0x1F6B5, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 36, 60, false),
FacebookEmoji(String(intArrayOf(0x1F6B5, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 37, 0, false),
FacebookEmoji(String(intArrayOf(0x1F6B5, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 37, 1, false),
FacebookEmoji(String(intArrayOf(0x1F6B5, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 37, 2, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F938), 0, 1), listOf("person_doing_cartwheel"), 42, 7, true,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F938, 0x1F3FB), 0, 2), emptyList<String>(), 42, 8, false),
FacebookEmoji(String(intArrayOf(0x1F938, 0x1F3FC), 0, 2), emptyList<String>(), 42, 9, false),
FacebookEmoji(String(intArrayOf(0x1F938, 0x1F3FD), 0, 2), emptyList<String>(), 42, 10, false),
FacebookEmoji(String(intArrayOf(0x1F938, 0x1F3FE), 0, 2), emptyList<String>(), 42, 11, false),
FacebookEmoji(String(intArrayOf(0x1F938, 0x1F3FF), 0, 2), emptyList<String>(), 42, 12, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F938, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man-cartwheeling"), 42, 1, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F938, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 42, 2, false),
FacebookEmoji(String(intArrayOf(0x1F938, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 42, 3, false),
FacebookEmoji(String(intArrayOf(0x1F938, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 42, 4, false),
FacebookEmoji(String(intArrayOf(0x1F938, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 42, 5, false),
FacebookEmoji(String(intArrayOf(0x1F938, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 42, 6, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F938, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman-cartwheeling"), 41, 56, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F938, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 41, 57, false),
FacebookEmoji(String(intArrayOf(0x1F938, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 41, 58, false),
FacebookEmoji(String(intArrayOf(0x1F938, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 41, 59, false),
FacebookEmoji(String(intArrayOf(0x1F938, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 41, 60, false),
FacebookEmoji(String(intArrayOf(0x1F938, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 42, 0, false),
),
),
FacebookEmoji(String(intArrayOf(0x1F93C), 0, 1), listOf("wrestlers"), 42, 34, true),
FacebookEmoji(String(intArrayOf(0x1F93C, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man-wrestling"), 42, 33, false),
FacebookEmoji(String(intArrayOf(0x1F93C, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman-wrestling"), 42, 32, false),
FacebookEmoji(
String(intArrayOf(0x1F93D), 0, 1), listOf("water_polo"), 42, 47, true,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F93D, 0x1F3FB), 0, 2), emptyList<String>(), 42, 48, false),
FacebookEmoji(String(intArrayOf(0x1F93D, 0x1F3FC), 0, 2), emptyList<String>(), 42, 49, false),
FacebookEmoji(String(intArrayOf(0x1F93D, 0x1F3FD), 0, 2), emptyList<String>(), 42, 50, false),
FacebookEmoji(String(intArrayOf(0x1F93D, 0x1F3FE), 0, 2), emptyList<String>(), 42, 51, false),
FacebookEmoji(String(intArrayOf(0x1F93D, 0x1F3FF), 0, 2), emptyList<String>(), 42, 52, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F93D, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man-playing-water-polo"), 42, 41, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F93D, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 42, 42, false),
FacebookEmoji(String(intArrayOf(0x1F93D, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 42, 43, false),
FacebookEmoji(String(intArrayOf(0x1F93D, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 42, 44, false),
FacebookEmoji(String(intArrayOf(0x1F93D, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 42, 45, false),
FacebookEmoji(String(intArrayOf(0x1F93D, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 42, 46, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F93D, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman-playing-water-polo"), 42, 35, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F93D, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 42, 36, false),
FacebookEmoji(String(intArrayOf(0x1F93D, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 42, 37, false),
FacebookEmoji(String(intArrayOf(0x1F93D, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 42, 38, false),
FacebookEmoji(String(intArrayOf(0x1F93D, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 42, 39, false),
FacebookEmoji(String(intArrayOf(0x1F93D, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 42, 40, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F93E), 0, 1), listOf("handball"), 43, 4, true,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F93E, 0x1F3FB), 0, 2), emptyList<String>(), 43, 5, false),
FacebookEmoji(String(intArrayOf(0x1F93E, 0x1F3FC), 0, 2), emptyList<String>(), 43, 6, false),
FacebookEmoji(String(intArrayOf(0x1F93E, 0x1F3FD), 0, 2), emptyList<String>(), 43, 7, false),
FacebookEmoji(String(intArrayOf(0x1F93E, 0x1F3FE), 0, 2), emptyList<String>(), 43, 8, false),
FacebookEmoji(String(intArrayOf(0x1F93E, 0x1F3FF), 0, 2), emptyList<String>(), 43, 9, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F93E, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man-playing-handball"), 42, 59, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F93E, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 42, 60, false),
FacebookEmoji(String(intArrayOf(0x1F93E, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 43, 0, false),
FacebookEmoji(String(intArrayOf(0x1F93E, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 43, 1, false),
FacebookEmoji(String(intArrayOf(0x1F93E, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 43, 2, false),
FacebookEmoji(String(intArrayOf(0x1F93E, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 43, 3, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F93E, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman-playing-handball"), 42, 53, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F93E, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 42, 54, false),
FacebookEmoji(String(intArrayOf(0x1F93E, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 42, 55, false),
FacebookEmoji(String(intArrayOf(0x1F93E, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 42, 56, false),
FacebookEmoji(String(intArrayOf(0x1F93E, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 42, 57, false),
FacebookEmoji(String(intArrayOf(0x1F93E, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 42, 58, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F939), 0, 1), listOf("juggling"), 42, 25, true,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F939, 0x1F3FB), 0, 2), emptyList<String>(), 42, 26, false),
FacebookEmoji(String(intArrayOf(0x1F939, 0x1F3FC), 0, 2), emptyList<String>(), 42, 27, false),
FacebookEmoji(String(intArrayOf(0x1F939, 0x1F3FD), 0, 2), emptyList<String>(), 42, 28, false),
FacebookEmoji(String(intArrayOf(0x1F939, 0x1F3FE), 0, 2), emptyList<String>(), 42, 29, false),
FacebookEmoji(String(intArrayOf(0x1F939, 0x1F3FF), 0, 2), emptyList<String>(), 42, 30, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F939, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man-juggling"), 42, 19, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F939, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 42, 20, false),
FacebookEmoji(String(intArrayOf(0x1F939, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 42, 21, false),
FacebookEmoji(String(intArrayOf(0x1F939, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 42, 22, false),
FacebookEmoji(String(intArrayOf(0x1F939, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 42, 23, false),
FacebookEmoji(String(intArrayOf(0x1F939, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 42, 24, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F939, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman-juggling"), 42, 13, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F939, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 42, 14, false),
FacebookEmoji(String(intArrayOf(0x1F939, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 42, 15, false),
FacebookEmoji(String(intArrayOf(0x1F939, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 42, 16, false),
FacebookEmoji(String(intArrayOf(0x1F939, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 42, 17, false),
FacebookEmoji(String(intArrayOf(0x1F939, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 42, 18, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F9D8), 0, 1), listOf("person_in_lotus_position"), 51, 34, true,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F9D8, 0x1F3FB), 0, 2), emptyList<String>(), 51, 35, true),
FacebookEmoji(String(intArrayOf(0x1F9D8, 0x1F3FC), 0, 2), emptyList<String>(), 51, 36, true),
FacebookEmoji(String(intArrayOf(0x1F9D8, 0x1F3FD), 0, 2), emptyList<String>(), 51, 37, true),
FacebookEmoji(String(intArrayOf(0x1F9D8, 0x1F3FE), 0, 2), emptyList<String>(), 51, 38, true),
FacebookEmoji(String(intArrayOf(0x1F9D8, 0x1F3FF), 0, 2), emptyList<String>(), 51, 39, true),
),
),
FacebookEmoji(
String(intArrayOf(0x1F9D8, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man_in_lotus_position"), 51, 28, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F9D8, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 51, 29, false),
FacebookEmoji(String(intArrayOf(0x1F9D8, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 51, 30, false),
FacebookEmoji(String(intArrayOf(0x1F9D8, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 51, 31, false),
FacebookEmoji(String(intArrayOf(0x1F9D8, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 51, 32, false),
FacebookEmoji(String(intArrayOf(0x1F9D8, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 51, 33, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F9D8, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman_in_lotus_position"), 51, 22, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F9D8, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 51, 23, false),
FacebookEmoji(String(intArrayOf(0x1F9D8, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 51, 24, false),
FacebookEmoji(String(intArrayOf(0x1F9D8, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 51, 25, false),
FacebookEmoji(String(intArrayOf(0x1F9D8, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 51, 26, false),
FacebookEmoji(String(intArrayOf(0x1F9D8, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 51, 27, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F6C0), 0, 1), listOf("bath"), 37, 42, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F6C0, 0x1F3FB), 0, 2), emptyList<String>(), 37, 43, false),
FacebookEmoji(String(intArrayOf(0x1F6C0, 0x1F3FC), 0, 2), emptyList<String>(), 37, 44, false),
FacebookEmoji(String(intArrayOf(0x1F6C0, 0x1F3FD), 0, 2), emptyList<String>(), 37, 45, false),
FacebookEmoji(String(intArrayOf(0x1F6C0, 0x1F3FE), 0, 2), emptyList<String>(), 37, 46, false),
FacebookEmoji(String(intArrayOf(0x1F6C0, 0x1F3FF), 0, 2), emptyList<String>(), 37, 47, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F6CC), 0, 1), listOf("sleeping_accommodation"), 37, 54, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F6CC, 0x1F3FB), 0, 2), emptyList<String>(), 37, 55, false),
FacebookEmoji(String(intArrayOf(0x1F6CC, 0x1F3FC), 0, 2), emptyList<String>(), 37, 56, false),
FacebookEmoji(String(intArrayOf(0x1F6CC, 0x1F3FD), 0, 2), emptyList<String>(), 37, 57, false),
FacebookEmoji(String(intArrayOf(0x1F6CC, 0x1F3FE), 0, 2), emptyList<String>(), 37, 58, false),
FacebookEmoji(String(intArrayOf(0x1F6CC, 0x1F3FF), 0, 2), emptyList<String>(), 37, 59, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F9D1, 0x200D, 0x1F91D, 0x200D, 0x1F9D1), 0, 5), listOf("people_holding_hands"), 48, 41, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F9D1, 0x1F3FB, 0x200D, 0x1F91D, 0x200D, 0x1F9D1, 0x1F3FB), 0, 7), emptyList<String>(), 48, 42, false),
FacebookEmoji(String(intArrayOf(0x1F9D1, 0x1F3FC, 0x200D, 0x1F91D, 0x200D, 0x1F9D1, 0x1F3FB), 0, 7), emptyList<String>(), 48, 47, false),
FacebookEmoji(String(intArrayOf(0x1F9D1, 0x1F3FC, 0x200D, 0x1F91D, 0x200D, 0x1F9D1, 0x1F3FC), 0, 7), emptyList<String>(), 48, 48, false),
FacebookEmoji(String(intArrayOf(0x1F9D1, 0x1F3FD, 0x200D, 0x1F91D, 0x200D, 0x1F9D1, 0x1F3FB), 0, 7), emptyList<String>(), 48, 52, false),
FacebookEmoji(String(intArrayOf(0x1F9D1, 0x1F3FD, 0x200D, 0x1F91D, 0x200D, 0x1F9D1, 0x1F3FC), 0, 7), emptyList<String>(), 48, 53, false),
FacebookEmoji(String(intArrayOf(0x1F9D1, 0x1F3FD, 0x200D, 0x1F91D, 0x200D, 0x1F9D1, 0x1F3FD), 0, 7), emptyList<String>(), 48, 54, false),
FacebookEmoji(String(intArrayOf(0x1F9D1, 0x1F3FE, 0x200D, 0x1F91D, 0x200D, 0x1F9D1, 0x1F3FB), 0, 7), emptyList<String>(), 48, 57, false),
FacebookEmoji(String(intArrayOf(0x1F9D1, 0x1F3FE, 0x200D, 0x1F91D, 0x200D, 0x1F9D1, 0x1F3FC), 0, 7), emptyList<String>(), 48, 58, false),
FacebookEmoji(String(intArrayOf(0x1F9D1, 0x1F3FE, 0x200D, 0x1F91D, 0x200D, 0x1F9D1, 0x1F3FD), 0, 7), emptyList<String>(), 48, 59, false),
FacebookEmoji(String(intArrayOf(0x1F9D1, 0x1F3FE, 0x200D, 0x1F91D, 0x200D, 0x1F9D1, 0x1F3FE), 0, 7), emptyList<String>(), 48, 60, false),
FacebookEmoji(String(intArrayOf(0x1F9D1, 0x1F3FF, 0x200D, 0x1F91D, 0x200D, 0x1F9D1, 0x1F3FB), 0, 7), emptyList<String>(), 49, 1, false),
FacebookEmoji(String(intArrayOf(0x1F9D1, 0x1F3FF, 0x200D, 0x1F91D, 0x200D, 0x1F9D1, 0x1F3FC), 0, 7), emptyList<String>(), 49, 2, false),
FacebookEmoji(String(intArrayOf(0x1F9D1, 0x1F3FF, 0x200D, 0x1F91D, 0x200D, 0x1F9D1, 0x1F3FD), 0, 7), emptyList<String>(), 49, 3, false),
FacebookEmoji(String(intArrayOf(0x1F9D1, 0x1F3FF, 0x200D, 0x1F91D, 0x200D, 0x1F9D1, 0x1F3FE), 0, 7), emptyList<String>(), 49, 4, false),
FacebookEmoji(String(intArrayOf(0x1F9D1, 0x1F3FF, 0x200D, 0x1F91D, 0x200D, 0x1F9D1, 0x1F3FF), 0, 7), emptyList<String>(), 49, 5, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F46D), 0, 1), listOf("two_women_holding_hands", "women_holding_hands"), 22, 31, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F46D, 0x1F3FB), 0, 2), emptyList<String>(), 22, 32, false),
FacebookEmoji(String(intArrayOf(0x1F46D, 0x1F3FC), 0, 2), emptyList<String>(), 22, 33, false),
FacebookEmoji(String(intArrayOf(0x1F46D, 0x1F3FD), 0, 2), emptyList<String>(), 22, 34, false),
FacebookEmoji(String(intArrayOf(0x1F46D, 0x1F3FE), 0, 2), emptyList<String>(), 22, 35, false),
FacebookEmoji(String(intArrayOf(0x1F46D, 0x1F3FF), 0, 2), emptyList<String>(), 22, 36, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FC, 0x200D, 0x1F91D, 0x200D, 0x1F469, 0x1F3FB), 0, 7), emptyList<String>(), 22, 41, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FD, 0x200D, 0x1F91D, 0x200D, 0x1F469, 0x1F3FB), 0, 7), emptyList<String>(), 22, 45, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FD, 0x200D, 0x1F91D, 0x200D, 0x1F469, 0x1F3FC), 0, 7), emptyList<String>(), 22, 46, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FE, 0x200D, 0x1F91D, 0x200D, 0x1F469, 0x1F3FB), 0, 7), emptyList<String>(), 22, 49, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FE, 0x200D, 0x1F91D, 0x200D, 0x1F469, 0x1F3FC), 0, 7), emptyList<String>(), 22, 50, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FE, 0x200D, 0x1F91D, 0x200D, 0x1F469, 0x1F3FD), 0, 7), emptyList<String>(), 22, 51, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FF, 0x200D, 0x1F91D, 0x200D, 0x1F469, 0x1F3FB), 0, 7), emptyList<String>(), 22, 53, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FF, 0x200D, 0x1F91D, 0x200D, 0x1F469, 0x1F3FC), 0, 7), emptyList<String>(), 22, 54, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FF, 0x200D, 0x1F91D, 0x200D, 0x1F469, 0x1F3FD), 0, 7), emptyList<String>(), 22, 55, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FF, 0x200D, 0x1F91D, 0x200D, 0x1F469, 0x1F3FE), 0, 7), emptyList<String>(), 22, 56, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F46B), 0, 1), listOf("man_and_woman_holding_hands", "woman_and_man_holding_hands", "couple"), 21, 40, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F46B, 0x1F3FB), 0, 2), emptyList<String>(), 21, 41, false),
FacebookEmoji(String(intArrayOf(0x1F46B, 0x1F3FC), 0, 2), emptyList<String>(), 21, 42, false),
FacebookEmoji(String(intArrayOf(0x1F46B, 0x1F3FD), 0, 2), emptyList<String>(), 21, 43, false),
FacebookEmoji(String(intArrayOf(0x1F46B, 0x1F3FE), 0, 2), emptyList<String>(), 21, 44, false),
FacebookEmoji(String(intArrayOf(0x1F46B, 0x1F3FF), 0, 2), emptyList<String>(), 21, 45, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FB, 0x200D, 0x1F91D, 0x200D, 0x1F468, 0x1F3FC), 0, 7), emptyList<String>(), 21, 46, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FB, 0x200D, 0x1F91D, 0x200D, 0x1F468, 0x1F3FD), 0, 7), emptyList<String>(), 21, 47, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FB, 0x200D, 0x1F91D, 0x200D, 0x1F468, 0x1F3FE), 0, 7), emptyList<String>(), 21, 48, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FB, 0x200D, 0x1F91D, 0x200D, 0x1F468, 0x1F3FF), 0, 7), emptyList<String>(), 21, 49, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FC, 0x200D, 0x1F91D, 0x200D, 0x1F468, 0x1F3FB), 0, 7), emptyList<String>(), 21, 50, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FC, 0x200D, 0x1F91D, 0x200D, 0x1F468, 0x1F3FD), 0, 7), emptyList<String>(), 21, 51, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FC, 0x200D, 0x1F91D, 0x200D, 0x1F468, 0x1F3FE), 0, 7), emptyList<String>(), 21, 52, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FC, 0x200D, 0x1F91D, 0x200D, 0x1F468, 0x1F3FF), 0, 7), emptyList<String>(), 21, 53, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FD, 0x200D, 0x1F91D, 0x200D, 0x1F468, 0x1F3FB), 0, 7), emptyList<String>(), 21, 54, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FD, 0x200D, 0x1F91D, 0x200D, 0x1F468, 0x1F3FC), 0, 7), emptyList<String>(), 21, 55, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FD, 0x200D, 0x1F91D, 0x200D, 0x1F468, 0x1F3FE), 0, 7), emptyList<String>(), 21, 56, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FD, 0x200D, 0x1F91D, 0x200D, 0x1F468, 0x1F3FF), 0, 7), emptyList<String>(), 21, 57, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FE, 0x200D, 0x1F91D, 0x200D, 0x1F468, 0x1F3FB), 0, 7), emptyList<String>(), 21, 58, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FE, 0x200D, 0x1F91D, 0x200D, 0x1F468, 0x1F3FC), 0, 7), emptyList<String>(), 21, 59, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FE, 0x200D, 0x1F91D, 0x200D, 0x1F468, 0x1F3FD), 0, 7), emptyList<String>(), 21, 60, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FE, 0x200D, 0x1F91D, 0x200D, 0x1F468, 0x1F3FF), 0, 7), emptyList<String>(), 22, 0, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FF, 0x200D, 0x1F91D, 0x200D, 0x1F468, 0x1F3FB), 0, 7), emptyList<String>(), 22, 1, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FF, 0x200D, 0x1F91D, 0x200D, 0x1F468, 0x1F3FC), 0, 7), emptyList<String>(), 22, 2, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FF, 0x200D, 0x1F91D, 0x200D, 0x1F468, 0x1F3FD), 0, 7), emptyList<String>(), 22, 3, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FF, 0x200D, 0x1F91D, 0x200D, 0x1F468, 0x1F3FE), 0, 7), emptyList<String>(), 22, 4, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F46C), 0, 1), listOf("two_men_holding_hands", "men_holding_hands"), 22, 5, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F46C, 0x1F3FB), 0, 2), emptyList<String>(), 22, 6, false),
FacebookEmoji(String(intArrayOf(0x1F46C, 0x1F3FC), 0, 2), emptyList<String>(), 22, 7, false),
FacebookEmoji(String(intArrayOf(0x1F46C, 0x1F3FD), 0, 2), emptyList<String>(), 22, 8, false),
FacebookEmoji(String(intArrayOf(0x1F46C, 0x1F3FE), 0, 2), emptyList<String>(), 22, 9, false),
FacebookEmoji(String(intArrayOf(0x1F46C, 0x1F3FF), 0, 2), emptyList<String>(), 22, 10, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x1F3FC, 0x200D, 0x1F91D, 0x200D, 0x1F468, 0x1F3FB), 0, 7), emptyList<String>(), 22, 15, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x1F3FD, 0x200D, 0x1F91D, 0x200D, 0x1F468, 0x1F3FB), 0, 7), emptyList<String>(), 22, 19, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x1F3FD, 0x200D, 0x1F91D, 0x200D, 0x1F468, 0x1F3FC), 0, 7), emptyList<String>(), 22, 20, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x1F3FE, 0x200D, 0x1F91D, 0x200D, 0x1F468, 0x1F3FB), 0, 7), emptyList<String>(), 22, 23, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x1F3FE, 0x200D, 0x1F91D, 0x200D, 0x1F468, 0x1F3FC), 0, 7), emptyList<String>(), 22, 24, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x1F3FE, 0x200D, 0x1F91D, 0x200D, 0x1F468, 0x1F3FD), 0, 7), emptyList<String>(), 22, 25, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x1F3FF, 0x200D, 0x1F91D, 0x200D, 0x1F468, 0x1F3FB), 0, 7), emptyList<String>(), 22, 27, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x1F3FF, 0x200D, 0x1F91D, 0x200D, 0x1F468, 0x1F3FC), 0, 7), emptyList<String>(), 22, 28, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x1F3FF, 0x200D, 0x1F91D, 0x200D, 0x1F468, 0x1F3FD), 0, 7), emptyList<String>(), 22, 29, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x1F3FF, 0x200D, 0x1F91D, 0x200D, 0x1F468, 0x1F3FE), 0, 7), emptyList<String>(), 22, 30, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F48F), 0, 1), listOf("couplekiss"), 26, 41, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F48F, 0x1F3FB), 0, 2), emptyList<String>(), 26, 42, false),
FacebookEmoji(String(intArrayOf(0x1F48F, 0x1F3FC), 0, 2), emptyList<String>(), 26, 43, false),
FacebookEmoji(String(intArrayOf(0x1F48F, 0x1F3FD), 0, 2), emptyList<String>(), 26, 44, false),
FacebookEmoji(String(intArrayOf(0x1F48F, 0x1F3FE), 0, 2), emptyList<String>(), 26, 45, false),
FacebookEmoji(String(intArrayOf(0x1F48F, 0x1F3FF), 0, 2), emptyList<String>(), 26, 46, false),
),
),
FacebookEmoji(String(intArrayOf(0x1F469, 0x200D, 0x2764, 0xFE0F, 0x200D, 0x1F48B, 0x200D, 0x1F468), 0, 8), listOf("woman-kiss-man"), 20, 42, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x200D, 0x2764, 0xFE0F, 0x200D, 0x1F48B, 0x200D, 0x1F468), 0, 8), listOf("man-kiss-man"), 16, 48, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x200D, 0x2764, 0xFE0F, 0x200D, 0x1F48B, 0x200D, 0x1F469), 0, 8), listOf("woman-kiss-woman"), 21, 7, false),
FacebookEmoji(
String(intArrayOf(0x1F491), 0, 1), listOf("couple_with_heart"), 27, 7, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F491, 0x1F3FB), 0, 2), emptyList<String>(), 27, 8, false),
FacebookEmoji(String(intArrayOf(0x1F491, 0x1F3FC), 0, 2), emptyList<String>(), 27, 9, false),
FacebookEmoji(String(intArrayOf(0x1F491, 0x1F3FD), 0, 2), emptyList<String>(), 27, 10, false),
FacebookEmoji(String(intArrayOf(0x1F491, 0x1F3FE), 0, 2), emptyList<String>(), 27, 11, false),
FacebookEmoji(String(intArrayOf(0x1F491, 0x1F3FF), 0, 2), emptyList<String>(), 27, 12, false),
),
),
FacebookEmoji(String(intArrayOf(0x1F469, 0x200D, 0x2764, 0xFE0F, 0x200D, 0x1F468), 0, 6), listOf("woman-heart-man"), 19, 51, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x200D, 0x2764, 0xFE0F, 0x200D, 0x1F468), 0, 6), listOf("man-heart-man"), 16, 22, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x200D, 0x2764, 0xFE0F, 0x200D, 0x1F469), 0, 6), listOf("woman-heart-woman"), 20, 16, false),
FacebookEmoji(String(intArrayOf(0x1F46A), 0, 1), listOf("family"), 21, 39, true),
FacebookEmoji(String(intArrayOf(0x1F468, 0x200D, 0x1F469, 0x200D, 0x1F466), 0, 5), listOf("man-woman-boy"), 14, 43, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x200D, 0x1F469, 0x200D, 0x1F467), 0, 5), listOf("man-woman-girl"), 14, 45, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x200D, 0x1F469, 0x200D, 0x1F467, 0x200D, 0x1F466), 0, 7), listOf("man-woman-girl-boy"), 14, 46, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x200D, 0x1F469, 0x200D, 0x1F466, 0x200D, 0x1F466), 0, 7), listOf("man-woman-boy-boy"), 14, 44, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x200D, 0x1F469, 0x200D, 0x1F467, 0x200D, 0x1F467), 0, 7), listOf("man-woman-girl-girl"), 14, 47, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x200D, 0x1F468, 0x200D, 0x1F466), 0, 5), listOf("man-man-boy"), 14, 38, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x200D, 0x1F468, 0x200D, 0x1F467), 0, 5), listOf("man-man-girl"), 14, 40, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x200D, 0x1F468, 0x200D, 0x1F467, 0x200D, 0x1F466), 0, 7), listOf("man-man-girl-boy"), 14, 41, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x200D, 0x1F468, 0x200D, 0x1F466, 0x200D, 0x1F466), 0, 7), listOf("man-man-boy-boy"), 14, 39, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x200D, 0x1F468, 0x200D, 0x1F467, 0x200D, 0x1F467), 0, 7), listOf("man-man-girl-girl"), 14, 42, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x200D, 0x1F469, 0x200D, 0x1F466), 0, 5), listOf("woman-woman-boy"), 18, 11, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x200D, 0x1F469, 0x200D, 0x1F467), 0, 5), listOf("woman-woman-girl"), 18, 13, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x200D, 0x1F469, 0x200D, 0x1F467, 0x200D, 0x1F466), 0, 7), listOf("woman-woman-girl-boy"), 18, 14, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x200D, 0x1F469, 0x200D, 0x1F466, 0x200D, 0x1F466), 0, 7), listOf("woman-woman-boy-boy"), 18, 12, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x200D, 0x1F469, 0x200D, 0x1F467, 0x200D, 0x1F467), 0, 7), listOf("woman-woman-girl-girl"), 18, 15, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x200D, 0x1F466), 0, 3), listOf("man-boy"), 14, 34, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x200D, 0x1F466, 0x200D, 0x1F466), 0, 5), listOf("man-boy-boy"), 14, 33, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x200D, 0x1F467), 0, 3), listOf("man-girl"), 14, 37, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x200D, 0x1F467, 0x200D, 0x1F466), 0, 5), listOf("man-girl-boy"), 14, 35, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x200D, 0x1F467, 0x200D, 0x1F467), 0, 5), listOf("man-girl-girl"), 14, 36, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x200D, 0x1F466), 0, 3), listOf("woman-boy"), 18, 7, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x200D, 0x1F466, 0x200D, 0x1F466), 0, 5), listOf("woman-boy-boy"), 18, 6, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x200D, 0x1F467), 0, 3), listOf("woman-girl"), 18, 10, false),
)
}
| emoji-facebook/src/commonMain/kotlin/com/vanniktech/emoji/facebook/category/SmileysAndPeopleCategoryChunk3.kt | 2429144406 |
package me.giacoppo.examples.kotlin.mvp.data.source.tmdb
import io.reactivex.Observable
import me.giacoppo.examples.kotlin.mvp.bean.Show
import me.giacoppo.examples.kotlin.mvp.data.source.tmdb.model.mapper.TVShowMapper
import me.giacoppo.examples.kotlin.mvp.repository.ShowsRepository
/**
* Implementation of ShowsRepository based on Retrofit
*
* @author Giuseppe Giacoppo
*/
class TMDBShowsRepository(private val source: TMDBDataSource) : ShowsRepository{
private val mapper by lazy { TVShowMapper() }
override fun populars(): Observable<List<Show>> {
return source.getPopularShows().map{it.results.map(mapper)}
}
override fun show(id: Int): Observable<Show> {
return source.getShow(id).map(mapper)
}
} | data/src/main/java/me/giacoppo/examples/kotlin/mvp/data/source/tmdb/TMDBShowsRepository.kt | 593717099 |
/*
* Copyright @ 2019 - present 8x8, 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 org.jitsi.nlj.rtp
import io.kotest.core.spec.IsolationMode
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
import io.mockk.mockk
import org.jitsi.nlj.resources.logging.StdoutLogger
import org.jitsi.nlj.rtp.bandwidthestimation.BandwidthEstimator
import org.jitsi.nlj.util.bytes
import org.jitsi.rtp.rtcp.rtcpfb.transport_layer_fb.tcc.RtcpFbTccPacketBuilder
import org.jitsi.utils.time.FakeClock
import java.util.logging.Level
class TransportCcEngineTest : FunSpec() {
override fun isolationMode(): IsolationMode? = IsolationMode.InstancePerLeaf
private val bandwidthEstimator: BandwidthEstimator = mockk(relaxed = true)
private val clock: FakeClock = FakeClock()
private val logger = StdoutLogger(_level = Level.INFO)
private val lossListener = object : LossListener {
var numReceived = 0
var numLost = 0
override fun packetReceived(previouslyReportedLost: Boolean) {
numReceived++
if (previouslyReportedLost) {
numLost--
}
}
override fun packetLost(numLost: Int) {
this.numLost += numLost
}
}
private val transportCcEngine = TransportCcEngine(bandwidthEstimator, logger, clock).also {
it.addLossListener(lossListener)
}
init {
test("Missing packet reports") {
transportCcEngine.mediaPacketSent(4, 1300.bytes)
val tccPacket = with(RtcpFbTccPacketBuilder(mediaSourceSsrc = 123, feedbackPacketSeqNum = 0)) {
SetBase(1, 100)
AddReceivedPacket(1, 100)
AddReceivedPacket(2, 110)
AddReceivedPacket(3, 120)
AddReceivedPacket(4, 130)
build()
}
transportCcEngine.rtcpPacketReceived(tccPacket, clock.instant())
with(transportCcEngine.getStatistics()) {
numMissingPacketReports shouldBe 3
numDuplicateReports shouldBe 0
numPacketsReportedAfterLost shouldBe 0
numPacketsUnreported shouldBe 0
}
lossListener.numReceived shouldBe 1
lossListener.numLost shouldBe 0
}
test("Duplicate packet reports") {
transportCcEngine.mediaPacketSent(4, 1300.bytes)
val tccPacket = with(RtcpFbTccPacketBuilder(mediaSourceSsrc = 123, feedbackPacketSeqNum = 1)) {
SetBase(4, 130)
AddReceivedPacket(4, 130)
build()
}
transportCcEngine.rtcpPacketReceived(tccPacket, clock.instant())
val tccPacket2 = with(RtcpFbTccPacketBuilder(mediaSourceSsrc = 123, feedbackPacketSeqNum = 2)) {
SetBase(4, 130)
AddReceivedPacket(4, 130)
build()
}
transportCcEngine.rtcpPacketReceived(tccPacket2, clock.instant())
with(transportCcEngine.getStatistics()) {
numMissingPacketReports shouldBe 0
numDuplicateReports shouldBe 1
numPacketsReportedAfterLost shouldBe 0
numPacketsUnreported shouldBe 0
}
lossListener.numReceived shouldBe 1
lossListener.numLost shouldBe 0
}
test("Packets reported after lost") {
transportCcEngine.mediaPacketSent(4, 1300.bytes)
transportCcEngine.mediaPacketSent(5, 1300.bytes)
val tccPacket = with(RtcpFbTccPacketBuilder(mediaSourceSsrc = 123, feedbackPacketSeqNum = 1)) {
SetBase(4, 130)
AddReceivedPacket(5, 130)
build()
}
transportCcEngine.rtcpPacketReceived(tccPacket, clock.instant())
lossListener.numReceived shouldBe 1
lossListener.numLost shouldBe 1
val tccPacket2 = with(RtcpFbTccPacketBuilder(mediaSourceSsrc = 123, feedbackPacketSeqNum = 2)) {
SetBase(4, 130)
AddReceivedPacket(4, 130)
build()
}
transportCcEngine.rtcpPacketReceived(tccPacket2, clock.instant())
with(transportCcEngine.getStatistics()) {
numMissingPacketReports shouldBe 0
numDuplicateReports shouldBe 0
numPacketsReportedAfterLost shouldBe 1
numPacketsUnreported shouldBe 0
}
lossListener.numReceived shouldBe 2
lossListener.numLost shouldBe 0
}
test("Packet unreported") {
transportCcEngine.mediaPacketSent(4, 1300.bytes)
/* Force the report of sequence 4 to be evicted from the packet history */
transportCcEngine.mediaPacketSent(1004, 1300.bytes)
with(transportCcEngine.getStatistics()) {
numMissingPacketReports shouldBe 0
numDuplicateReports shouldBe 0
numPacketsReportedAfterLost shouldBe 0
numPacketsUnreported shouldBe 1
}
lossListener.numReceived shouldBe 0
lossListener.numLost shouldBe 0
}
}
}
| jitsi-media-transform/src/test/kotlin/org/jitsi/nlj/rtp/TransportCcEngineTest.kt | 1001436814 |
/*
* Copyright 2021 The Cross-Media Measurement 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.wfanet.measurement.common.crypto
import com.google.common.truth.Truth.assertThat
import com.google.protobuf.kotlin.toByteStringUtf8
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import org.wfanet.measurement.common.crypto.testing.FIXED_SERVER_CERT_DER_FILE
import org.wfanet.measurement.common.crypto.testing.FIXED_SERVER_KEY_DER_FILE
import org.wfanet.measurement.common.crypto.testing.loadSigningKey
@RunWith(JUnit4::class)
class SigningKeyHandleTest {
@Test
fun `sign generates valid signature`() {
val signingKey = loadSigningKey(FIXED_SERVER_CERT_DER_FILE, FIXED_SERVER_KEY_DER_FILE)
val signature = signingKey.sign(MESSAGE_BINARY)
assertThat(signingKey.certificate.verifySignature(MESSAGE_BINARY, signature)).isTrue()
}
companion object {
private const val MESSAGE = "A message to sign"
private val MESSAGE_BINARY = MESSAGE.toByteStringUtf8()
}
}
| src/test/kotlin/org/wfanet/measurement/common/crypto/SigningKeyHandleTest.kt | 1508473871 |
package com.jetbrains.rider.plugins.unity.run.configurations
import com.intellij.execution.impl.CheckableRunConfigurationEditor
import com.intellij.openapi.options.SettingsEditor
import com.intellij.openapi.project.Project
import com.intellij.openapi.rd.defineNestedLifetime
import com.jetbrains.rd.util.lifetime.LifetimeDefinition
class UnityAttachToEditorSettingsEditor(project: Project) : SettingsEditor<UnityAttachToEditorRunConfiguration>(),
CheckableRunConfigurationEditor<UnityAttachToEditorRunConfiguration> {
private val lifetimeDefinition: LifetimeDefinition = project.defineNestedLifetime()
private val viewModel: UnityAttachToEditorViewModel = UnityAttachToEditorViewModel(lifetimeDefinition.lifetime, project)
private val form: UnityAttachToEditorForm = UnityAttachToEditorForm(viewModel)
init {
// This doesn't work, because this editor seems to be wrapped, and any listeners
// subscribe to the wrapper, not this class, so firing this doesn't do any good.
viewModel.pid.advise(lifetimeDefinition.lifetime) { fireEditorStateChanged() }
}
override fun checkEditorData(configuration: UnityAttachToEditorRunConfiguration) {
configuration.pid = viewModel.pid.value
}
override fun resetEditorFrom(configuration: UnityAttachToEditorRunConfiguration) {
viewModel.pid.value = configuration.pid
}
override fun applyEditorTo(configuration: UnityAttachToEditorRunConfiguration) {
checkEditorData(configuration)
}
override fun createEditor() = form.panel
override fun disposeEditor() {
lifetimeDefinition.terminate()
}
} | rider/src/main/kotlin/com/jetbrains/rider/plugins/unity/run/configurations/UnityAttachToEditorSettingsEditor.kt | 745634035 |
package com.cout970.magneticraft.misc.render
/**
* Created by cout970 on 16/07/2016.
*/
class AnimationTimer {
var active = true
var lastTime = System.currentTimeMillis()
var animationStage = 0f
fun updateAnimation() {
animationStage += getDelta().toFloat()
resetDelta()
}
fun resetDelta() {
lastTime = System.currentTimeMillis()
}
fun getDelta() = (System.currentTimeMillis() - lastTime).toDouble() / 1000
fun getRotationState(speed: Float): Float {
return (animationStage * speed) % 360
}
fun getMotionState(speed: Float): Float {
return Math.sin(Math.toRadians(getRotationState(speed).toDouble())).toFloat()
}
} | src/main/kotlin/com/cout970/magneticraft/misc/render/AnimationTimer.kt | 700910382 |
package com.github.shynixn.petblocks.api.persistence.entity
import com.github.shynixn.petblocks.api.business.proxy.PetProxy
/**
* Created by Shynixn 2019.
* <p>
* Version 1.2
* <p>
* MIT License
* <p>
* Copyright (c) 2019 by Shynixn
* <p>
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* <p>
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* <p>
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
interface PetPostSpawn {
/**
* Owner of the pet getting spawned.
*/
val player: Any
/**
* Pet which was spawned.
*/
val pet: PetProxy
} | petblocks-api/src/main/kotlin/com/github/shynixn/petblocks/api/persistence/entity/PetPostSpawn.kt | 2116910652 |
package reactivecircus.flowbinding.material
import androidx.fragment.app.FragmentActivity
import androidx.test.filters.LargeTest
import com.google.android.material.datepicker.MaterialDatePicker
import com.google.common.truth.Truth.assertThat
import org.junit.Test
import reactivecircus.blueprint.testing.currentActivity
import reactivecircus.flowbinding.material.fixtures.MaterialFragment1
import reactivecircus.flowbinding.testing.FlowRecorder
import reactivecircus.flowbinding.testing.clickOkButtonOnDatePicker
import reactivecircus.flowbinding.testing.launchTest
import reactivecircus.flowbinding.testing.recordWith
import java.util.Calendar
import java.util.TimeZone
@LargeTest
class MaterialDatePickerPositiveButtonClickFlowTest {
@Test
fun materialDatePickerPositiveButtonClicks() {
launchTest<MaterialFragment1> {
val recorder = FlowRecorder<Long>(testScope)
val timestamp = Calendar.getInstance(TimeZone.getTimeZone("UTC")).apply {
set(Calendar.YEAR, 2019)
set(Calendar.MONTH, 9)
set(Calendar.MINUTE, 28)
set(Calendar.HOUR_OF_DAY, 0)
set(Calendar.MINUTE, 0)
set(Calendar.SECOND, 0)
set(Calendar.MILLISECOND, 0)
}.timeInMillis
val picker = MaterialDatePicker.Builder.datePicker()
.setSelection(timestamp)
.build()
picker.positiveButtonClicks().recordWith(recorder)
recorder.assertNoMoreValues()
picker.show((currentActivity() as FragmentActivity).supportFragmentManager, toString())
clickOkButtonOnDatePicker()
assertThat(recorder.takeValue())
.isEqualTo(timestamp)
cancelTestScope()
recorder.clearValues()
picker.show((currentActivity() as FragmentActivity).supportFragmentManager, toString())
clickOkButtonOnDatePicker()
recorder.assertNoMoreValues()
}
}
}
| flowbinding-material/src/androidTest/java/reactivecircus/flowbinding/material/MaterialDatePickerPositiveButtonClickFlowTest.kt | 215711015 |
package io.particle.mesh.setup.flow.setupsteps
import io.particle.mesh.setup.flow.FlowUiDelegate
import io.particle.mesh.setup.flow.MeshSetupStep
import io.particle.mesh.setup.flow.Scopes
import io.particle.mesh.setup.flow.context.SetupContexts
class StepShowEthernetOptionsUi(private val flowUi: FlowUiDelegate) : MeshSetupStep() {
override suspend fun doRunStep(ctxs: SetupContexts, scopes: Scopes) {
flowUi.showEthernetOptionsUi(ctxs.ble.connectingToTargetUiShown)
}
}
| mesh/src/main/java/io/particle/mesh/setup/flow/setupsteps/StepShowEthernetOptionsUi.kt | 2035467541 |
/*
* 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.core.primitives.job
import bob.core.primitives.env.getEnv
import bob.core.primitives.task.getTask
import bob.util.jsonStringOf
import com.google.gson.Gson
import com.google.gson.JsonSyntaxException
import kotlinx.collections.immutable.toImmutableList
private data class RawJob(
val id: String?,
val name: String,
val envId: String?,
val tasks: List<String>
)
// TODO 7: Remove !! when (1) is done
fun Job.toJson() = jsonStringOf(RawJob(
this.id,
this.name,
this.env?.id,
this.tasks.map { it.id!! }
))
fun jsonToJob(json: String) = try {
val job = Gson().fromJson(json, RawJob::class.java)
val env = when (job.envId) {
null -> null
"" -> null
else -> getEnv(job.envId)
}
// TODO 4: Remove when Gson has @Required
@Suppress("SENSELESS_COMPARISON")
when {
job?.tasks == null || job.name == null -> null
else -> {
val tasks = job.tasks.map { getTask(it) }
when {
tasks.any { it == null } -> null
else -> Job(
job.id,
job.name,
env,
job.tasks.map { getTask(it)!! }.toImmutableList()
)
}
}
}
} catch (_: JsonSyntaxException) {
null
}
| src/main/kotlin/bob/core/primitives/job/Serialization.kt | 2712169279 |
package io.particle.mesh.common
import mu.KLogger
import mu.KotlinLogging
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
fun <T> KLogger.logged(): ReadWriteProperty<Any?, T?> = NullableLogWhenSetVar(this)
fun <T> KLogger.logged(initialValue: T): ReadWriteProperty<Any?, T> {
return NonNullLogWhenSetVar(initialValue, this)
}
private class NullableLogWhenSetVar<T>(logger: KLogger?) : ReadWriteProperty<Any?, T?> {
private val log: KLogger = logger ?: KotlinLogging.logger {}
private var value: T? = null
override fun getValue(thisRef: Any?, property: KProperty<*>): T? {
return value
}
override fun setValue(thisRef: Any?, property: KProperty<*>, value: T?) {
if (this.value != value) {
log.info { "'${property.name}' value being updated to: $value" }
}
this.value = value
}
}
// this seems like I'm clearly doing something wrong by needing this whole second class...
private class NonNullLogWhenSetVar<T>(initialValue: T, logger: KLogger?) :
ReadWriteProperty<Any?, T> {
private val log: KLogger = logger ?: KotlinLogging.logger {}
private var value: T = initialValue
override fun getValue(thisRef: Any?, property: KProperty<*>): T {
return value
}
override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
if (this.value != value) {
log.info { "'${property.name}' value being updated to: $value" }
}
this.value = value
}
}
| mesh/src/main/java/io/particle/mesh/common/Delegates.kt | 4236752767 |
package org.gradle.kotlin.dsl
import com.nhaarman.mockito_kotlin.any
import com.nhaarman.mockito_kotlin.eq
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.verify
import org.gradle.api.Action
import org.gradle.api.artifacts.ComponentSelection
import org.gradle.api.artifacts.ComponentSelectionRules
import org.gradle.api.artifacts.Configuration
import org.gradle.api.artifacts.ConfigurationContainer
import org.gradle.api.artifacts.ResolutionStrategy
import org.junit.Test
import org.mockito.invocation.InvocationOnMock
class ComponentSelectionRulesTest {
@Test
fun `Action method overloads are correctly selected`() {
val componentSelection = mock<ComponentSelection>()
val componentSelectionRules = mock<ComponentSelectionRules> {
on { all(any<Action<ComponentSelection>>()) }.thenAnswer {
it.executeActionOn(componentSelection)
}
}
val resolutionStrategy = mock<ResolutionStrategy> {
on { componentSelection(any<Action<ComponentSelectionRules>>()) }.thenAnswer {
it.executeActionOn(componentSelectionRules)
}
}
val conf = mock<Configuration> {
on { resolutionStrategy(any<Action<ResolutionStrategy>>()) }.thenAnswer {
it.executeActionOn(resolutionStrategy)
}
}
val configurations = mock<ConfigurationContainer> {
on { create(eq("conf"), any<Action<Configuration>>()) }.thenAnswer {
it.getArgument<Action<Configuration>>(1).execute(conf)
conf
}
}
configurations {
create("conf") {
it.resolutionStrategy {
it.componentSelection {
it.all { selection ->
selection.reject("all")
}
}
}
}
}
verify(componentSelection).reject("all")
}
private
fun <E> InvocationOnMock.executeActionOn(element: E): Any? {
getArgument<Action<E>>(0).execute(element)
return mock
}
}
| subprojects/kotlin-dsl/src/test/kotlin/org/gradle/kotlin/dsl/ComponentSelectionRulesTest.kt | 2432177814 |
/*
* 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.instantexecution.serialization.codecs
import com.google.common.collect.ImmutableList
import org.gradle.instantexecution.serialization.Codec
import org.gradle.instantexecution.serialization.ReadContext
import org.gradle.instantexecution.serialization.WriteContext
import org.gradle.instantexecution.serialization.writeCollection
object ImmutableListCodec : Codec<ImmutableList<Any>> {
override suspend fun WriteContext.encode(value: ImmutableList<Any>) {
writeCollection(value)
}
override suspend fun ReadContext.decode(): ImmutableList<Any>? {
val size = readSmallInt()
val builder = ImmutableList.builderWithExpectedSize<Any>(size)
for (i in 0 until size) {
val value = read()!!
builder.add(value)
}
return builder.build()
}
}
| subprojects/instant-execution/src/main/kotlin/org/gradle/instantexecution/serialization/codecs/ImmutableListCodec.kt | 438108605 |
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.settingsRepository.git
import com.intellij.openapi.application.ApplicationNamesInfo
import com.intellij.openapi.application.ex.ApplicationInfoEx
import org.eclipse.jgit.lib.Ref
import org.eclipse.jgit.merge.MergeMessageFormatter
import java.net.InetAddress
public interface CommitMessageFormatter {
public fun message(text: String): String = text
public fun prependMessage(builder: StringBuilder = StringBuilder()): StringBuilder = builder
public fun mergeMessage(refsToMerge: List<Ref>, target: Ref): String = MergeMessageFormatter().format(refsToMerge, target)
}
class IdeaCommitMessageFormatter : CommitMessageFormatter {
override fun message(text: String) = StringBuilder().appendCommitOwnerInfo().append(text).toString()
override fun prependMessage(builder: StringBuilder) = builder.appendCommitOwnerInfo()
override fun mergeMessage(refsToMerge: List<Ref>, target: Ref) = StringBuilder().appendCommitOwnerInfo().append(super.mergeMessage(refsToMerge, target)).toString()
fun StringBuilder.appendCommitOwnerInfo(avoidAppInfoInstantiation: Boolean = false): StringBuilder {
if (avoidAppInfoInstantiation) {
append(ApplicationNamesInfo.getInstance().productName)
}
else {
appendAppName()
}
append(' ').append('<').append(System.getProperty("user.name", "unknown-user")).append('@').append(InetAddress.getLocalHost().hostName)
append(' ')
return this
}
fun StringBuilder.appendAppName() {
val appInfo = ApplicationInfoEx.getInstanceEx()
if (appInfo != null) {
val build = appInfo.build
append(build.productCode).append('-')
if (appInfo.majorVersion != null && !appInfo.isEAP) {
append(appInfo.fullVersion)
}
else {
var buildString = build.asStringWithoutProductCode()
if (build.buildNumber == Integer.MAX_VALUE) {
buildString = buildString.replace(".SNAPSHOT", "")
}
append(buildString)
}
}
}
} | plugins/settings-repository/src/git/CommitMessageFormatter.kt | 3001946182 |
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.camera.utils
import android.content.Context
import android.util.AttributeSet
import android.util.Log
import android.view.SurfaceView
import kotlin.math.roundToInt
/**
* A [SurfaceView] that can be adjusted to a specified aspect ratio and
* performs center-crop transformation of input frames.
*/
class AutoFitSurfaceView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyle: Int = 0
) : SurfaceView(context, attrs, defStyle) {
private var aspectRatio = 0f
/**
* Sets the aspect ratio for this view. The size of the view will be
* measured based on the ratio calculated from the parameters.
*
* @param width Camera resolution horizontal size
* @param height Camera resolution vertical size
*/
fun setAspectRatio(width: Int, height: Int) {
require(width > 0 && height > 0) { "Size cannot be negative" }
aspectRatio = width.toFloat() / height.toFloat()
holder.setFixedSize(width, height)
requestLayout()
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
val width = MeasureSpec.getSize(widthMeasureSpec)
val height = MeasureSpec.getSize(heightMeasureSpec)
if (aspectRatio == 0f) {
setMeasuredDimension(width, height)
} else {
// Performs center-crop transformation of the camera frames
val newWidth: Int
val newHeight: Int
val actualRatio = if (width > height) aspectRatio else 1f / aspectRatio
if (width < height * actualRatio) {
newHeight = height
newWidth = (height * actualRatio).roundToInt()
} else {
newWidth = width
newHeight = (width / actualRatio).roundToInt()
}
Log.d(TAG, "Measured dimensions set: $newWidth x $newHeight")
setMeasuredDimension(newWidth, newHeight)
}
}
companion object {
private val TAG = AutoFitSurfaceView::class.java.simpleName
}
}
| CameraXVideo/utils/src/main/java/com/example/android/camera/utils/AutoFitSurfaceView.kt | 3597863441 |
package chat.willow.warren.handler
import chat.willow.kale.helper.CaseMapping
import chat.willow.kale.irc.message.rfc1459.QuitMessage
import chat.willow.kale.irc.prefix.Prefix
import chat.willow.kale.irc.prefix.prefix
import chat.willow.kale.irc.tag.TagStore
import chat.willow.warren.event.ConnectionLifecycleEvent
import chat.willow.warren.event.IWarrenEvent
import chat.willow.warren.event.IWarrenEventDispatcher
import chat.willow.warren.state.*
import com.nhaarman.mockito_kotlin.any
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.never
import com.nhaarman.mockito_kotlin.verify
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
class QuitHandlerTests {
lateinit var handler: QuitHandler
lateinit var connectionState: ConnectionState
lateinit var channelsState: ChannelsState
lateinit var mockEventDispatcher: IWarrenEventDispatcher
val caseMappingState = CaseMappingState(mapping = CaseMapping.RFC1459)
@Before fun setUp() {
val lifecycleState = LifecycleState.CONNECTED
connectionState = ConnectionState(server = "test.server", port = 6697, nickname = "test-nick", user = "test-nick", lifecycle = lifecycleState)
channelsState = emptyChannelsState(caseMappingState)
mockEventDispatcher = mock()
handler = QuitHandler(mockEventDispatcher, connectionState, channelsState.joined)
}
@Test fun test_handle_SourceIsNull_DoesNothing() {
channelsState.joined += ChannelState(name = "#channel", users = generateUsersFromNicks(listOf("someone", "someone-else"), mappingState = caseMappingState))
handler.handle(QuitMessage.Message(source = prefix("")), TagStore())
val expectedChannelOneState = ChannelState(name = "#channel", users = generateUsersFromNicks(listOf("someone", "someone-else"), mappingState = caseMappingState))
val expectedChannelsState = channelsStateWith(listOf(expectedChannelOneState), caseMappingState)
assertEquals(channelsState, expectedChannelsState)
}
@Test fun test_handle_SourceIsSelf_ChangesConnectionStateToDisconnected() {
channelsState.joined += ChannelState(name = "#channel", users = generateUsersFromNicks(listOf("test-nick", "someone-else"), mappingState = caseMappingState))
channelsState.joined += ChannelState(name = "#channel2", users = generateUsersFromNicks(listOf("another-person", "someone-else"), mappingState = caseMappingState))
handler.handle(QuitMessage.Message(source = Prefix(nick = "test-nick")), TagStore())
val expectedChannelOneState = ChannelState(name = "#channel", users = generateUsersFromNicks(listOf("test-nick", "someone-else"), mappingState = caseMappingState))
val expectedChannelTwoState = ChannelState(name = "#channel2", users = generateUsersFromNicks(listOf("another-person", "someone-else"), mappingState = caseMappingState))
val expectedChannelsState = channelsStateWith(listOf(expectedChannelOneState, expectedChannelTwoState), caseMappingState)
assertEquals(channelsState, expectedChannelsState)
assertEquals(connectionState.lifecycle, LifecycleState.DISCONNECTED)
}
@Test fun test_handle_SourceIsSelf_FiresDisconnectedEvent() {
handler.handle(QuitMessage.Message(source = Prefix(nick = "test-nick")), TagStore())
verify(mockEventDispatcher).fire(ConnectionLifecycleEvent(lifecycle = LifecycleState.DISCONNECTED))
}
@Test fun test_handle_SourceIsOther_RemovesUserFromChannels() {
channelsState.joined += ChannelState(name = "#channel", users = generateUsersFromNicks(listOf("test-nick", "someone-else"), mappingState = caseMappingState))
channelsState.joined += ChannelState(name = "#channel2", users = generateUsersFromNicks(listOf("another-person", "someone-else"), mappingState = caseMappingState))
handler.handle(QuitMessage.Message(source = Prefix(nick = "someone-else")), TagStore())
val expectedChannelOneState = ChannelState(name = "#channel", users = generateUsersFromNicks(listOf("test-nick"), mappingState = caseMappingState))
val expectedChannelTwoState = ChannelState(name = "#channel2", users = generateUsersFromNicks(listOf("another-person"), mappingState = caseMappingState))
val expectedChannelsState = channelsStateWith(listOf(expectedChannelOneState, expectedChannelTwoState), caseMappingState)
assertEquals(channelsState, expectedChannelsState)
}
@Test fun test_handle_SourceIsOther_DoesNotFireDisconnectedEvent() {
handler.handle(QuitMessage.Message(source = Prefix(nick = "someone-else")), TagStore())
verify(mockEventDispatcher, never()).fire(any<IWarrenEvent>())
}
} | src/test/kotlin/chat/willow/warren/handler/QuitHandlerTests.kt | 831807122 |
package com.dragbone.pizzabot
import org.junit.Test
import org.junit.Assert.*
import org.junit.BeforeClass
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
@RunWith(value = Parameterized::class)
class PizzaDayChooserTest(val cl: Class<PizzaDayChooser>) {
companion object {
@JvmStatic
@Parameterized.Parameters
fun data(): Collection<Array<Any>> {
return listOf(arrayOf<Any>(PizzaDayChooser::class.java))
}
}
private fun getPizzaDayChooser(): PizzaDayChooser {
return cl.constructors.first().newInstance(PizzaVoteState()) as PizzaDayChooser
}
@Test fun choosePizzaDay() {
val chooser = getPizzaDayChooser()
val k = mapOf(
DayOfWeek.MONDAY to 1.0,
DayOfWeek.TUESDAY to 2.5,
DayOfWeek.WEDNESDAY to 1.0
)
assertEquals(DayOfWeek.TUESDAY, chooser.choosePizzaDay(k))
}
} | src/test/kotlin/com/dragbone/pizzabot/PizzaDayChooserTest.kt | 972178414 |
package com.supercilex.robotscouter.feature.teams
import androidx.fragment.app.FragmentManager
import com.supercilex.robotscouter.TeamSelectionListener
import com.supercilex.robotscouter.core.data.getScoutBundle
import com.supercilex.robotscouter.core.data.getTeam
import com.supercilex.robotscouter.core.data.toBundle
import com.supercilex.robotscouter.core.model.Team
import com.supercilex.robotscouter.core.ui.show
import com.supercilex.robotscouter.shared.TemplateSelectorDialog
internal class TeamTemplateSelectorDialog : TemplateSelectorDialog() {
override fun onItemSelected(id: String) {
super.onItemSelected(id)
(context as TeamSelectionListener)
.onTeamSelected(getScoutBundle(requireArguments().getTeam(), true, id))
}
companion object {
private const val TAG = "TeamTemplateSelector"
fun show(manager: FragmentManager, team: Team) =
TeamTemplateSelectorDialog().show(manager, TAG, team.toBundle())
}
}
| feature/teams/src/main/java/com/supercilex/robotscouter/feature/teams/TeamTemplateSelectorDialog.kt | 3981418460 |
package org.koin.experimental.builder
import org.koin.core.logger.Level
import org.koin.core.scope.Scope
import org.koin.core.time.measureDurationForResult
import org.koin.ext.getFullName
import java.lang.reflect.Constructor
/**
* Create instance for type T and inject dependencies into 1st constructor
*/
inline fun <reified T : Any> Scope.create(): T {
val kClass = T::class
val instance: Any
logger.debug("!- creating class:${kClass.getFullName()}")
val constructor = kClass.java.constructors.firstOrNull()
?: error("No constructor found for class '${kClass.getFullName()}'")
val args = if (logger.isAt(Level.DEBUG)) {
val (_args, duration) = measureDurationForResult {
getArguments(constructor, this)
}
logger.debug("!- got arguments in $duration ms")
_args
} else {
getArguments(constructor, this)
}
instance = if (logger.isAt(Level.DEBUG)) {
val (_instance, duration) = measureDurationForResult {
createInstance(args, constructor)
}
logger.debug("!- created instance in $duration ms")
_instance
} else {
createInstance(args, constructor)
}
return instance as T
}
fun createInstance(args: Array<Any>, constructor: Constructor<out Any>): Any {
return if (args.isEmpty()) {
constructor.newInstance()
} else {
constructor.newInstance(*args)
}
}
/**
* Retrieve arguments for given constructor
*/
fun getArguments(constructor: Constructor<*>, context: Scope): Array<Any> {
val length = constructor.parameterTypes.size
return if (length == 0) emptyArray()
else {
val result = Array<Any>(length) { Unit }
for (i in 0 until length) {
val p = constructor.parameterTypes[i]
result[i] = context.get(p.kotlin, null, null)
}
result
}
} | koin-projects/koin-core-ext/src/main/kotlin/org/koin/experimental/builder/InstanceBuilder.kt | 622176236 |
/*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.architecture.blueprints.todoapp.util
/**
* Extension functions and Binding Adapters.
*/
import android.view.View
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
import com.example.android.architecture.blueprints.todoapp.Event
import com.example.android.architecture.blueprints.todoapp.R
import com.example.android.architecture.blueprints.todoapp.ScrollChildSwipeRefreshLayout
import com.google.android.material.snackbar.Snackbar
/**
* Transforms static java function Snackbar.make() to an extension function on View.
*/
fun View.showSnackbar(snackbarText: String, timeLength: Int) {
Snackbar.make(this, snackbarText, timeLength).run {
show()
}
}
/**
* Triggers a snackbar message when the value contained by snackbarTaskMessageLiveEvent is modified.
*/
fun View.setupSnackbar(
lifecycleOwner: LifecycleOwner,
snackbarEvent: LiveData<Event<Int>>,
timeLength: Int
) {
snackbarEvent.observe(lifecycleOwner, Observer { event ->
event.getContentIfNotHandled()?.let {
showSnackbar(context.getString(it), timeLength)
}
})
}
fun Fragment.setupRefreshLayout(
refreshLayout: ScrollChildSwipeRefreshLayout,
scrollUpChild: View? = null
) {
refreshLayout.setColorSchemeColors(
ContextCompat.getColor(requireActivity(), R.color.colorPrimary),
ContextCompat.getColor(requireActivity(), R.color.colorAccent),
ContextCompat.getColor(requireActivity(), R.color.colorPrimaryDark)
)
// Set the scrolling view in the custom SwipeRefreshLayout.
scrollUpChild?.let {
refreshLayout.scrollUpChild = it
}
}
| app/src/main/java/com/example/android/architecture/blueprints/todoapp/util/ViewExt.kt | 1027111205 |
/*
* Copyright (C) 2021 The Dagger 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.
*/
import com.google.common.truth.Truth.assertThat
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
class CrossCompilationRootValidationTest {
@get:Rule
val testProjectDir = TemporaryFolder()
lateinit var gradleRunner: GradleTestRunner
@Before
fun setup() {
gradleRunner = GradleTestRunner(testProjectDir)
gradleRunner.addHiltOption(
"enableAggregatingTask = true"
)
gradleRunner.addDependencies(
"implementation 'androidx.appcompat:appcompat:1.1.0'",
"implementation 'com.google.dagger:hilt-android:LOCAL-SNAPSHOT'",
"annotationProcessor 'com.google.dagger:hilt-compiler:LOCAL-SNAPSHOT'",
"testImplementation 'com.google.dagger:hilt-android-testing:LOCAL-SNAPSHOT'",
"testAnnotationProcessor 'com.google.dagger:hilt-compiler:LOCAL-SNAPSHOT'",
)
gradleRunner.addSrc(
srcPath = "minimal/MyApp.java",
srcContent =
"""
package minimal;
import android.app.Application;
@dagger.hilt.android.HiltAndroidApp
public class MyApp extends Application { }
""".trimIndent()
)
gradleRunner.setAppClassName(".MyApp")
}
@Test
fun multipleAppRootsFailure() {
gradleRunner.addSrc(
srcPath = "minimal/MyApp2.java",
srcContent =
"""
package minimal;
import android.app.Application;
@dagger.hilt.android.HiltAndroidApp
public class MyApp2 extends Application { }
""".trimIndent()
)
val result = gradleRunner.buildAndFail()
assertThat(result.getOutput()).contains(
"Cannot process multiple app roots in the same compilation unit: " +
"minimal.MyApp, minimal.MyApp2"
)
}
@Test
fun testRootsAndAppRootsFailure() {
gradleRunner.addTestSrc(
srcPath = "minimal/MyTest.java",
srcContent =
"""
package minimal;
@dagger.hilt.android.testing.HiltAndroidTest
public class MyTest { }
""".trimIndent()
)
gradleRunner.addTestSrc(
srcPath = "minimal/BadApp.java",
srcContent =
"""
package minimal;
import android.app.Application;
@dagger.hilt.android.HiltAndroidApp
public class BadApp extends Application { }
""".trimIndent()
)
gradleRunner.runAdditionalTasks("testDebug")
val result = gradleRunner.buildAndFail()
assertThat(result.getOutput()).contains(
"Cannot process test roots and app roots in the same compilation unit:"
)
assertThat(result.getOutput()).contains(
"App root in this compilation unit: minimal.BadApp"
)
assertThat(result.getOutput()).contains(
"Test roots in this compilation unit: minimal.MyTest"
)
}
}
| java/dagger/hilt/android/plugin/src/test/kotlin/CrossCompilationRootValidationTest.kt | 1087307137 |
package com.github.shynixn.blockball.bukkit.logic.business.service.nms.v1_18_R2
import com.github.shynixn.blockball.api.business.enumeration.CompatibilityArmorSlotType
import com.github.shynixn.blockball.api.business.proxy.PluginProxy
import com.github.shynixn.blockball.api.business.service.InternalVersionPacketService
import com.github.shynixn.blockball.api.business.service.LoggingService
import com.github.shynixn.blockball.api.persistence.entity.EntityMetaData
import com.github.shynixn.blockball.api.persistence.entity.Position
import com.google.inject.Inject
import com.mojang.datafixers.util.Pair
import io.netty.buffer.ByteBuf
import io.netty.buffer.Unpooled
import net.minecraft.core.Registry
import net.minecraft.network.FriendlyByteBuf
import net.minecraft.network.protocol.game.ClientboundAddMobPacket
import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket
import net.minecraft.network.protocol.game.ClientboundSetEquipmentPacket
import net.minecraft.network.protocol.game.ClientboundTeleportEntityPacket
import net.minecraft.world.entity.EntityType
import net.minecraft.world.entity.EquipmentSlot
import net.minecraft.world.item.ItemStack
import java.nio.charset.Charset
import java.util.*
class InternalVersionPacket118R2ServiceImpl @Inject constructor(
private val pluginProxy: PluginProxy
) : InternalVersionPacketService {
private val craftItemStackNmsMethod by lazy {
pluginProxy.findClazz("org.bukkit.craftbukkit.VERSION.inventory.CraftItemStack")
.getDeclaredMethod("asNMSCopy", pluginProxy.findClazz("org.bukkit.inventory.ItemStack"))
}
private val enumItemSlotClazz by lazy {
try {
pluginProxy.findClazz("net.minecraft.world.entity.EnumItemSlot")
} catch (e: Exception) {
pluginProxy.findClazz("net.minecraft.server.VERSION.EnumItemSlot")
}
}
private val mojangPairClazz by lazy {
pluginProxy.findClazz("com.mojang.datafixers.util.Pair")
}
/**
* Creates a new teleport packet.
*/
override fun createEntityTeleportPacket(entityId: Int, position: Position): Any {
val buffer = FriendlyByteBuf(Unpooled.buffer())
buffer.writeId(entityId)
buffer.writeDouble(position.x)
buffer.writeDouble(position.y)
buffer.writeDouble(position.z)
buffer.writeByte((position.yaw * 256.0f / 360.0f).toInt().toByte().toInt())
buffer.writeByte((position.pitch * 256.0f / 360.0f).toInt().toByte().toInt())
buffer.writeBoolean(false)
return ClientboundTeleportEntityPacket(buffer)
}
/**
* Creates a spawn packet.
*/
override fun createEntitySpawnPacket(entityId: Int, entityType: String, position: Position): Any {
val buffer = FriendlyByteBuf(Unpooled.buffer())
buffer.writeId(entityId)
val entityUUID = UUID.randomUUID()
buffer.writeLong(entityUUID.mostSignificantBits)
buffer.writeLong(entityUUID.leastSignificantBits)
val nmsEntityType = if (entityType == "ARMOR_STAND") {
EntityType.ARMOR_STAND
} else {
EntityType.SLIME
}
val nmsEntityId = Registry.ENTITY_TYPE.getId(nmsEntityType)
buffer.writeId(nmsEntityId)
buffer.writeDouble(position.x)
buffer.writeDouble(position.y)
buffer.writeDouble(position.z)
buffer.writeByte((position.yaw * 256.0f / 360.0f).toInt().toByte().toInt())
buffer.writeByte((position.pitch * 256.0f / 360.0f).toInt().toByte().toInt())
buffer.writeByte(0)
buffer.writeShort((mathhelperA(0.0, -3.9, 3.9) * 8000.0).toInt())
buffer.writeShort((mathhelperA(0.0, -3.9, 3.9) * 8000.0).toInt())
buffer.writeShort((mathhelperA(0.0, -3.9, 3.9) * 8000.0).toInt())
return ClientboundAddMobPacket(buffer)
}
/**
* Creates a entity metadata packet.
*/
override fun createEntityMetaDataPacket(entityId: Int, entityMetaData: EntityMetaData): Any {
// https://wiki.vg/Entity_metadata#Entity_Metadata_Format -> Value of Type field. Type of Value = Boolean -> 7.
val buffer = FriendlyByteBuf(Unpooled.buffer())
buffer.writeId(entityId)
val byteTypeValue = 0
val intTypeValue = 1
val booleanTypeValue = 7
val optChatTypeValue = 5
val rotationTypeValue = 8
if (entityMetaData.customNameVisible != null) {
buffer.writeByte(3)
buffer.writeId(booleanTypeValue)
buffer.writeBoolean(entityMetaData.customNameVisible!!)
}
if (entityMetaData.customname != null) {
val payload = "{\"text\": \"${entityMetaData.customname}\"}".toByteArray(Charset.forName("UTF-8"))
buffer.writeByte(2)
buffer.writeId(optChatTypeValue)
buffer.writeBoolean(true)
buffer.writeId(payload.size)
buffer.writeBytes(payload)
}
if (entityMetaData.slimeSize != null) {
val slimeSizeIndex = 16
buffer.writeByte(slimeSizeIndex)
buffer.writeId(intTypeValue)
buffer.writeId(entityMetaData.slimeSize!!)
}
if (entityMetaData.armorstandHeadRotation != null) {
buffer.writeByte(16)
buffer.writeId(rotationTypeValue)
buffer.writeFloat(entityMetaData.armorstandHeadRotation!!.x.toFloat())
buffer.writeFloat(entityMetaData.armorstandHeadRotation!!.y.toFloat())
buffer.writeFloat(entityMetaData.armorstandHeadRotation!!.z.toFloat())
}
if (entityMetaData.isInvisible != null) {
buffer.writeByte(0)
buffer.writeId(byteTypeValue)
buffer.writeByte(0x20)
}
if (entityMetaData.isSmall != null && entityMetaData.isSmall!!) {
buffer.writeByte(15)
buffer.writeId(byteTypeValue)
buffer.writeByte(0x01)
}
buffer.writeByte(255)
return ClientboundSetEntityDataPacket(buffer)
}
/**
* Creates an entity equipment packet.
*/
override fun <I> createEntityEquipmentPacket(entityId: Int, slot: CompatibilityArmorSlotType, itemStack: I): Any {
val nmsItemStack = craftItemStackNmsMethod.invoke(null, itemStack)
val pair = mojangPairClazz.getDeclaredConstructor(Any::class.java, Any::class.java)
.newInstance(enumItemSlotClazz.enumConstants[slot.id116], nmsItemStack)
return ClientboundSetEquipmentPacket(
entityId,
mutableListOf(pair) as MutableList<Pair<EquipmentSlot, ItemStack>>?
)
}
/**
* Mathhelper
*/
private fun mathhelperA(var0: Double, var2: Double, var4: Double): Double {
return if (var0 < var2) {
var2
} else {
if (var0 > var4) var4 else var0
}
}
/**
* Writes id.
*/
private fun ByteBuf.writeId(id: Int) {
var i = id
while (i and -128 != 0) {
writeByte(i and 127 or 128)
i = i ushr 7
}
writeByte(i)
}
}
| blockball-bukkit-plugin/bukkit-nms-118R2/src/main/java/com/github/shynixn/blockball/bukkit/logic/business/service/nms/v1_18_R2/InternalVersionPacket118R2ServiceImpl.kt | 3907360223 |
package com.github.shynixn.blockball.api.persistence.entity
import com.github.shynixn.blockball.api.business.enumeration.EffectTargetType
/**
* Created by Shynixn 2018.
* <p>
* Version 1.2
* <p>
* MIT License
* <p>
* Copyright (c) 2018 by Shynixn
* <p>
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* <p>
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* <p>
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
interface Sound {
/**
* Name of the sound.
*/
var name: String
/**
* Pitch of the sound.
*/
var pitch: Double
/**
* Volume of the sound.
*/
var volume: Double
/**
* Which players are effected.
*/
var effectingType: EffectTargetType
} | blockball-api/src/main/java/com/github/shynixn/blockball/api/persistence/entity/Sound.kt | 3380473170 |
package jp.toastkid.search
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
/**
* @author toastkidjp
*/
@RunWith(RobolectricTestRunner::class)
class SiteSearchUrlGeneratorTest {
/**
* Testing object.
*/
private val siteSearchUrlGenerator = jp.toastkid.search.SiteSearchUrlGenerator()
/**
* Check behavior.
*/
@Test
fun test() {
repeat(10) {
Assert.assertEquals(
"https://www.google.com/search?as_dt=i&as_sitesearch=www.yahoo.com&as_q=Orange",
siteSearchUrlGenerator("https://www.yahoo.com", "Orange")
)
}
}
} | search/src/test/java/jp/toastkid/search/SiteSearchUrlGeneratorTest.kt | 4136741879 |
/*
* 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.glass.notessample.viewpager
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.example.glass.notessample.R
import com.example.glass.ui.GlassGestureDetector
import kotlinx.android.synthetic.main.notes_option_layout.*
/**
* Fragment for adding new notes
*/
class AddNoteFragment : BaseViewPagerFragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.notes_option_layout, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
optionIcon.setImageResource(R.drawable.ic_add)
optionTextView.text = resources.getString(R.string.add_note)
}
override fun onGesture(gesture: GlassGestureDetector.Gesture): Boolean =
when (gesture) {
GlassGestureDetector.Gesture.TAP -> {
startVoiceRecognition(ADD_NOTE_REQUEST_CODE)
true
}
else -> super.onGesture(gesture)
}
} | NotesSample/app/src/main/java/com/example/glass/notessample/viewpager/AddNoteFragment.kt | 4178813663 |
package com.garpr.android.features.settings
import android.content.Context
import android.util.AttributeSet
import android.view.View
import androidx.core.content.ContextCompat
import com.garpr.android.R
import com.garpr.android.data.models.Region
import com.garpr.android.features.common.views.SimplePreferenceView
class RegionPreferenceView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null
) : SimplePreferenceView(context, attrs), View.OnClickListener {
var listener: Listener? = null
interface Listener {
fun onClick(v: RegionPreferenceView)
}
init {
titleText = context.getText(R.string.region)
setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_location_on_white_24dp))
setOnClickListener(this)
if (isInEditMode) {
descriptionText = context.getString(R.string.region_endpoint_format,
context.getString(R.string.norcal), context.getString(R.string.gar_pr))
}
}
override fun onClick(v: View) {
listener?.onClick(this)
}
fun setContent(region: Region) {
descriptionText = context.getString(R.string.region_endpoint_format,
region.displayName, context.getText(region.endpoint.title))
}
}
| smash-ranks-android/app/src/main/java/com/garpr/android/features/settings/RegionPreferenceView.kt | 4292900857 |
/*
* Copyright (C) 2017. Uber Technologies
*
* 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.uber.rib.core
import com.uber.rib.core.lifecycle.WorkerEvent
import io.reactivex.Observable
/** Helper to unit test [Worker] instances. */
object WorkerHelper {
/**
* Creates a [WorkerScopeProvider] that can be driven by a test observable.
*
* @param lifecycle to wrap.
* @return a [WorkerScopeProvider].
*/
@JvmStatic
open fun createScopeProvider(lifecycle: Observable<WorkerEvent>): WorkerScopeProvider {
return WorkerScopeProvider(lifecycle)
}
}
| android/libraries/rib-test/src/main/kotlin/com/uber/rib/core/WorkerHelper.kt | 2624116794 |
package com.openlattice.postgres
import com.dataloom.mappers.ObjectMappers
import com.fasterxml.jackson.module.kotlin.readValue
import com.openlattice.IdConstants.LAST_WRITE_ID
import com.openlattice.data.storage.ByteBlobDataManager
import com.openlattice.data.storage.MetadataOption
import com.openlattice.data.storage.PROPERTIES
import com.openlattice.data.storage.VALUE
import com.openlattice.edm.EdmConstants.Companion.ID_FQN
import com.openlattice.edm.EdmConstants.Companion.LAST_WRITE_FQN
import com.openlattice.edm.type.PropertyType
import com.openlattice.postgres.ResultSetAdapters.*
import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeKind
import org.apache.olingo.commons.api.edm.FullQualifiedName
import org.slf4j.LoggerFactory
import java.sql.*
import java.sql.Date
import java.time.Instant
import java.time.OffsetDateTime
import java.time.ZoneId
import java.util.*
internal class PostgresResultSetAdapters
private val logger = LoggerFactory.getLogger(PostgresResultSetAdapters::class.java)
private val mapper = ObjectMappers.newJsonMapper()
@Throws(SQLException::class)
fun getEntityPropertiesByPropertyTypeId(
rs: ResultSet,
authorizedPropertyTypes: Map<UUID, Map<UUID, PropertyType>>,
metadataOptions: Set<MetadataOption>,
byteBlobDataManager: ByteBlobDataManager
): Pair<UUID, MutableMap<UUID, MutableSet<Any>>> {
val id = id(rs)
val entitySetId = entitySetId(rs)
val propertyTypes = authorizedPropertyTypes.getValue(entitySetId)
val entity = readJsonDataColumns(
rs,
propertyTypes,
byteBlobDataManager
)
// TODO Do we need ID column in properties?
if (metadataOptions.contains(MetadataOption.LAST_WRITE)) {
entity[LAST_WRITE_ID.id] = mutableSetOf<Any>(lastWriteTyped(rs))
}
return id to entity
}
/**
* Returns linked entity data from the [ResultSet] mapped respectively by its id, entity set, origin id and property
* type id.
* Note: Do not include the linking id for the [IdConstants.ID_ID] key as a property for this adapter, because it is
* used for linked entity indexing and we preserve that key for the origin id.
* @see ConductorElasticsearchImpl.formatLinkedEntity
*/
@Throws(SQLException::class)
fun getEntityPropertiesByEntitySetIdOriginIdAndPropertyTypeId(
rs: ResultSet,
authorizedPropertyTypes: Map<UUID, Map<UUID, PropertyType>>,
metadataOptions: Set<MetadataOption>,
byteBlobDataManager: ByteBlobDataManager
): Pair<UUID, Pair<UUID, Map<UUID, MutableMap<UUID, MutableSet<Any>>>>> {
val id = id(rs)
val entitySetId = entitySetId(rs)
val propertyTypes = authorizedPropertyTypes.getValue(entitySetId)
val lastWrite = if (metadataOptions.contains(MetadataOption.LAST_WRITE)) {
Optional.of(lastWriteTyped(rs))
} else {
Optional.empty()
}
val entities = readJsonDataColumnsWithId(rs, propertyTypes, byteBlobDataManager, lastWrite)
return id to (entitySetId to entities)
}
/**
* Returns linked entity data from the [ResultSet] mapped respectively by its id, entity set, origin id and property
* full qualified name.
*/
@Throws(SQLException::class)
fun getEntityPropertiesByEntitySetIdOriginIdAndPropertyTypeFqn(
rs: ResultSet,
authorizedPropertyTypes: Map<UUID, Map<UUID, PropertyType>>,
metadataOptions: Set<MetadataOption>,
byteBlobDataManager: ByteBlobDataManager
): Pair<UUID, Pair<UUID, Map<UUID, MutableMap<FullQualifiedName, MutableSet<Any>>>>> {
val id = id(rs)
val entitySetId = entitySetId(rs)
val propertyTypes = authorizedPropertyTypes.getValue(entitySetId)
val lastWrite = if (metadataOptions.contains(MetadataOption.LAST_WRITE)) {
Optional.of(lastWriteTyped(rs))
} else {
Optional.empty()
}
val entities = readJsonDataColumnsWithId(rs, propertyTypes, byteBlobDataManager, lastWrite)
val entityByFqn = entities.mapValues { (_, propertyValues) ->
propertyValues.mapKeys {
if (it.key == LAST_WRITE_ID.id) {
LAST_WRITE_FQN
} else {
propertyTypes.getValue(it.key).type
}
}.toMutableMap()
}
return id to (entitySetId to entityByFqn)
}
@Throws(SQLException::class)
fun getEntityPropertiesByFullQualifiedName(
rs: ResultSet,
authorizedPropertyTypes: Map<UUID, Map<UUID, PropertyType>>,
metadataOptions: Set<MetadataOption>,
byteBlobDataManager: ByteBlobDataManager
): Pair<UUID, MutableMap<FullQualifiedName, MutableSet<Any>>> {
val id = id(rs)
val entitySetId = entitySetId(rs)
val propertyTypes = authorizedPropertyTypes.getValue(entitySetId)
val entity = readJsonDataColumns(rs, propertyTypes, byteBlobDataManager)
val entityByFqn = entity.mapKeys { propertyTypes.getValue(it.key).type }.toMutableMap()
entityByFqn[ID_FQN] = mutableSetOf<Any>(id.toString())
if (metadataOptions.contains(MetadataOption.LAST_WRITE)) {
entityByFqn[LAST_WRITE_FQN] = mutableSetOf<Any>(lastWriteTyped(rs))
}
return id to entityByFqn
}
@Throws(SQLException::class)
fun readJsonDataColumns(
rs: ResultSet,
propertyTypes: Map<UUID, PropertyType>,
byteBlobDataManager: ByteBlobDataManager
): MutableMap<UUID, MutableSet<Any>> {
val entity = mapper.readValue<MutableMap<UUID, MutableSet<Any>>>(rs.getString(PROPERTIES))
// Note: this call deletes all entries from result, which is not in propertyTypes (ID for example)
(entity.keys - propertyTypes.keys).forEach { entity.remove(it) }
propertyTypes.forEach { (_, propertyType) ->
if (propertyType.datatype == EdmPrimitiveTypeKind.Binary) {
val urls = entity.getOrElse(propertyType.id) { mutableSetOf() }
if (urls.isNotEmpty()) {
entity[propertyType.id] = byteBlobDataManager.getObjects(urls).toMutableSet()
}
}
}
return entity
}
@Throws(SQLException::class)
fun readJsonDataColumnsWithId(
rs: ResultSet,
propertyTypes: Map<UUID, PropertyType>,
byteBlobDataManager: ByteBlobDataManager,
lastWrite: Optional<OffsetDateTime>
): MutableMap<UUID, MutableMap<UUID, MutableSet<Any>>> {
val lastWriteIncluded = lastWrite.isPresent
val detailedEntity = mapper.readValue<MutableMap<UUID, MutableSet<MutableMap<String, Any>>>>(rs.getString(PROPERTIES))
val entities = mutableMapOf<UUID, MutableMap<UUID, MutableSet<Any>>>() // origin id -> property type id -> values
detailedEntity.forEach { (propertyTypeId, details) ->
// only select properties which are authorized
if (propertyTypes.keys.contains(propertyTypeId)) {
details.forEach { entityDetail ->
val originId = UUID.fromString(entityDetail[PostgresColumn.ID_VALUE.name] as String)
val propertyValue = entityDetail.getValue(VALUE)
if (!entities.containsKey(originId)) {
entities[originId] = mutableMapOf(propertyTypeId to mutableSetOf(propertyValue))
} else {
entities.getValue(originId)[propertyTypeId] = mutableSetOf(propertyValue)
}
if (lastWriteIncluded) {
entities.getValue(originId)[LAST_WRITE_ID.id] = mutableSetOf<Any>(lastWrite.get())
}
}
}
}
propertyTypes.forEach { (_, propertyType) ->
if (propertyType.datatype == EdmPrimitiveTypeKind.Binary) {
entities.forEach { (_, entity) ->
val urls = entity.getOrElse(propertyType.id) { mutableSetOf() }
if (urls.isNotEmpty()) {
entity[propertyType.id] = byteBlobDataManager.getObjects(urls).toMutableSet()
}
}
}
}
return entities
}
//TODO: If we are getting NPEs on read we may have to do better filtering here.
@Throws(SQLException::class)
private fun propertyValue(rs: ResultSet, propertyType: PropertyType): List<*>? {
val fqn = propertyType.type.fullQualifiedNameAsString
val arr = rs.getArray(fqn)
return if (arr != null) {
when (propertyType.datatype) {
EdmPrimitiveTypeKind.String, EdmPrimitiveTypeKind.GeographyPoint -> (arr.array as Array<String>).toList()
EdmPrimitiveTypeKind.Guid -> (arr.array as Array<UUID>).toList()
EdmPrimitiveTypeKind.Byte -> rs.getBytes(fqn)?.toList()
EdmPrimitiveTypeKind.Int16 -> (arr.array as Array<Short>).toList()
EdmPrimitiveTypeKind.Int32 -> (arr.array as Array<Int>).toList()
EdmPrimitiveTypeKind.Duration, EdmPrimitiveTypeKind.Int64 -> (arr.array as Array<Long>).toList()
EdmPrimitiveTypeKind.Date -> (arr.array as Array<Date>).map { it.toLocalDate() }
EdmPrimitiveTypeKind.TimeOfDay -> (arr.array as Array<Time>).map { it.toLocalTime() }
EdmPrimitiveTypeKind.DateTimeOffset -> (arr.array as Array<Timestamp>)
.map { ts ->
OffsetDateTime
.ofInstant(Instant.ofEpochMilli(ts.time), ZoneId.of("UTC"))
}
EdmPrimitiveTypeKind.Double -> (arr.array as Array<Double>).toList()
EdmPrimitiveTypeKind.Boolean -> (arr.array as Array<Boolean>).toList()
EdmPrimitiveTypeKind.Binary -> (arr.array as Array<String>).toList()
else -> {
logger.error(
"Unable to read property type {}.",
propertyType.id
)
null
}
}
} else {
null
}
} | src/main/kotlin/com/openlattice/postgres/PostgresResultSetAdapters.kt | 3070629681 |
package com.openlattice.hazelcast.serializers
import com.hazelcast.nio.ObjectDataInput
import com.hazelcast.nio.ObjectDataOutput
import com.kryptnostic.rhizome.hazelcast.serializers.SetStreamSerializers
import com.kryptnostic.rhizome.pods.hazelcast.SelfRegisteringStreamSerializer
import com.openlattice.hazelcast.StreamSerializerTypeIds
import com.openlattice.hazelcast.processors.AddEntitySetsToLinkingEntitySetProcessor
import org.springframework.stereotype.Component
@Component
class AddEntitySetsToLinkingEntitySetProcessorStreamSerializer:
SelfRegisteringStreamSerializer<AddEntitySetsToLinkingEntitySetProcessor> {
override fun getTypeId(): Int {
return StreamSerializerTypeIds.ADD_ENTITY_SETS_TO_LINKING_ENTITY_SET_PROCESSOR.ordinal
}
override fun destroy() { }
override fun getClazz(): Class<out AddEntitySetsToLinkingEntitySetProcessor> {
return AddEntitySetsToLinkingEntitySetProcessor::class.java
}
override fun write(out: ObjectDataOutput?, `object`: AddEntitySetsToLinkingEntitySetProcessor?) {
SetStreamSerializers.fastUUIDSetSerialize( out, `object`!!.entitySetIds )
}
override fun read(`in`: ObjectDataInput?): AddEntitySetsToLinkingEntitySetProcessor {
return AddEntitySetsToLinkingEntitySetProcessor( SetStreamSerializers.fastUUIDSetDeserialize( `in` ) )
}
} | src/main/kotlin/com/openlattice/hazelcast/serializers/AddEntitySetsToLinkingEntitySetProcessorStreamSerializer.kt | 2028536084 |
package edu.cs4730.fragcomnavlivedemo_kt
import androidx.navigation.Navigation.findNavController
import android.widget.TextView
import android.view.LayoutInflater
import android.view.ViewGroup
import android.os.Bundle
import android.view.View
import android.widget.Button
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
/**
*
*/
class SecondFragment : Fragment() {
lateinit var tv1: TextView
lateinit var tv2: TextView
lateinit var btn1: Button
lateinit var mViewModel: DataViewModel
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val myView = inflater.inflate(R.layout.fragment_second, container, false)
mViewModel = ViewModelProvider(requireActivity()).get(DataViewModel::class.java)
mViewModel.gettwoLD().observe(viewLifecycleOwner) { v -> tv1.text = "Parameter1: $v" }
mViewModel.itemLD.observe(viewLifecycleOwner) { s -> tv2.text = "Parameter1: $s" }
tv1 = myView.findViewById(R.id.sf_tv1)
tv2 = myView.findViewById(R.id.sf_tv2)
btn1 = myView.findViewById(R.id.sf_btn1)
btn1.setOnClickListener(View.OnClickListener { v -> //this is calling the interface, which call into the activity, so it
mViewModel.incr_One()
mViewModel.setItem("Called by SecondFragment")
findNavController(v).navigate(R.id.action_second_to_first)
})
return myView
}
} | Communication/FragComNavLiveDemo_kt/app/src/main/java/edu/cs4730/fragcomnavlivedemo_kt/SecondFragment.kt | 3454795941 |
/*
* Copyright (C) 2020 Moez Bhatti <[email protected]>
*
* This file is part of QKSMS.
*
* QKSMS 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.
*
* QKSMS 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 QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.moez.QKSMS.blocking
import android.content.Context
import android.content.Intent
import android.database.Cursor
import android.net.Uri
import androidx.core.database.getStringOrNull
import com.moez.QKSMS.common.util.extensions.isInstalled
import com.moez.QKSMS.extensions.map
import io.reactivex.Completable
import io.reactivex.Single
import timber.log.Timber
import java.util.*
import javax.inject.Inject
class CallBlockerBlockingClient @Inject constructor(
private val context: Context
) : BlockingClient {
class LookupResult(cursor: Cursor) {
val blockReason: String? = cursor.getStringOrNull(0)
}
override fun isAvailable(): Boolean = context.isInstalled("com.cuiet.blockCalls")
override fun getClientCapability() = BlockingClient.Capability.BLOCK_WITH_PERMISSION
override fun shouldBlock(address: String): Single<BlockingClient.Action> = lookup(address, "incomingNumber")
override fun isBlacklisted(address: String): Single<BlockingClient.Action> = lookup(address, "blacklistLookup")
private fun lookup(address: String, reason: String): Single<BlockingClient.Action> = Single.fromCallable {
val uri = Uri.parse("content://com.cuiet.blockCalls.ContProvBlockCalls/lookup/is.blocked.lookup")
return@fromCallable try {
val blockReason = context.contentResolver.query(uri, arrayOf("result"), reason, arrayOf(address), null)
?.use { cursor -> cursor.map(::LookupResult) }
?.find { result -> result.blockReason != null }
?.blockReason
when (blockReason) {
"true" -> BlockingClient.Action.Block()
else -> BlockingClient.Action.Unblock
}
} catch (e: Exception) {
Timber.w(e)
BlockingClient.Action.DoNothing
}
}
override fun block(addresses: List<String>): Completable = Completable.fromCallable {
val arrayList = ArrayList<String>()
arrayList.addAll(addresses)
val intent = Intent("com.cuiet.blockCalls.ADD_NUMBERS")
intent.putStringArrayListExtra("addresses", arrayList)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
context.startActivity(intent)
}
override fun unblock(addresses: List<String>): Completable = Completable.fromCallable {
val arrayList = ArrayList<String>()
arrayList.addAll(addresses)
val intent = Intent("com.cuiet.blockCalls.REMOVE_NUMBERS")
intent.putStringArrayListExtra("addresses", arrayList)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
context.startActivity(intent)
}
override fun openSettings() {
val intent = Intent("com.cuiet.blockCalls.OPEN_SETTINGS")
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
context.startActivity(intent)
}
}
| data/src/main/java/com/moez/QKSMS/blocking/CallBlockerBlockingClient.kt | 2345152277 |
package io.gitlab.arturbosch.detekt.rules.documentation
import io.gitlab.arturbosch.detekt.api.CodeSmell
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.Entity
import io.gitlab.arturbosch.detekt.api.Issue
import io.gitlab.arturbosch.detekt.api.Rule
import io.gitlab.arturbosch.detekt.api.Severity
import io.gitlab.arturbosch.detekt.rules.isPublicNotOverridden
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtEnumEntry
import org.jetbrains.kotlin.psi.KtObjectDeclaration
/**
* @author Artur Bosch
*/
class UndocumentedPublicClass(config: Config = Config.empty) : Rule(config) {
override val issue = Issue(javaClass.simpleName,
Severity.Maintainability,
"Public classes, interfaces and objects require documentation.")
private val searchInNestedClass = valueOrDefault(SEARCH_IN_NESTED_CLASS, true)
private val searchInInnerClass = valueOrDefault(SEARCH_IN_INNER_CLASS, true)
private val searchInInnerObject = valueOrDefault(SEARCH_IN_INNER_OBJECT, true)
private val searchInInnerInterface = valueOrDefault(SEARCH_IN_INNER_INTERFACE, true)
override fun visitClass(klass: KtClass) {
if (requiresDocumentation(klass)) {
reportIfUndocumented(klass)
}
super.visitClass(klass)
}
private fun requiresDocumentation(
klass: KtClass) = klass.isTopLevel() || klass.isInnerClass() || klass.isNestedClass() || klass.isInnerInterface()
override fun visitObjectDeclaration(declaration: KtObjectDeclaration) {
if (declaration.isCompanionWithoutName() || declaration.isLocal || !searchInInnerObject) {
return
}
reportIfUndocumented(declaration)
super.visitObjectDeclaration(declaration)
}
private fun reportIfUndocumented(element: KtClassOrObject) {
if (element.isPublicNotOverridden() && element.notEnumEntry() && element.docComment == null) {
report(CodeSmell(issue, Entity.Companion.from(element)))
}
}
private fun KtObjectDeclaration.isCompanionWithoutName() =
isCompanion() && nameAsSafeName.asString() == "Companion"
private fun KtClass.isNestedClass() = !isInterface() && !isTopLevel() && !isInner() && searchInNestedClass
private fun KtClass.isInnerClass() = !isInterface() && isInner() && searchInInnerClass
private fun KtClass.isInnerInterface() = !isTopLevel() && isInterface() && searchInInnerInterface
private fun KtClassOrObject.notEnumEntry() = this::class != KtEnumEntry::class
companion object {
const val SEARCH_IN_NESTED_CLASS = "searchInNestedClass"
const val SEARCH_IN_INNER_CLASS = "searchInInnerClass"
const val SEARCH_IN_INNER_OBJECT = "searchInInnerObject"
const val SEARCH_IN_INNER_INTERFACE = "searchInInnerInterface"
}
}
| detekt-rules/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/documentation/UndocumentedPublicClass.kt | 682531268 |
package kodando.react.native
external interface HitSlop {
var top: Number
var left: Number
var bottom: Number
var right: Number
}
| kodando-react-native/src/main/kotlin/kodando/react/native/HitSlop.kt | 1294422354 |
package me.sweetll.tucao.business.home.adapter
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import me.sweetll.tucao.R
import me.sweetll.tucao.model.json.Video
import me.sweetll.tucao.extension.formatByWan
import me.sweetll.tucao.extension.load
import me.sweetll.tucao.model.json.Channel
class RecommendAdapter(data: MutableList<Pair<Channel, List<Video>>>?): BaseQuickAdapter<Pair<Channel, List<Video>>, BaseViewHolder>(R.layout.item_recommend_video, data) {
override fun convert(helper: BaseViewHolder, item: Pair<Channel, List<Video>>) {
val channel = item.first
helper.setText(R.id.text_channel, channel.name)
item.second.take(4).forEachIndexed {
index, result ->
val thumbImg: ImageView
val playText: TextView
val titleText: TextView
when (index) {
0 -> {
thumbImg = helper.getView(R.id.img_thumb1)
playText = helper.getView(R.id.text_play1)
titleText = helper.getView(R.id.text_title1)
helper.setTag(R.id.card1, result.hid)
helper.addOnClickListener(R.id.card1)
}
1 -> {
thumbImg = helper.getView(R.id.img_thumb2)
playText = helper.getView(R.id.text_play2)
titleText = helper.getView(R.id.text_title2)
helper.setTag(R.id.card2, result.hid)
helper.addOnClickListener(R.id.card2)
}
2 -> {
thumbImg = helper.getView(R.id.img_thumb3)
playText = helper.getView(R.id.text_play3)
titleText = helper.getView(R.id.text_title3)
helper.setTag(R.id.card3, result.hid)
helper.addOnClickListener(R.id.card3)
}
else -> {
thumbImg = helper.getView(R.id.img_thumb4)
playText = helper.getView(R.id.text_play4)
titleText = helper.getView(R.id.text_title4)
helper.setTag(R.id.card4, result.hid)
helper.addOnClickListener(R.id.card4)
}
}
titleText.tag = result.thumb
thumbImg.load(mContext, result.thumb)
playText.text = result.play.formatByWan()
titleText.text = result.title
}
for (index in item.second.size .. 3) {
when (index) {
0 -> {
helper.getView<View>(R.id.card1).visibility = View.INVISIBLE
}
1 -> {
helper.getView<View>(R.id.card2).visibility = View.INVISIBLE
}
2 -> {
helper.getView<View>(R.id.card3).visibility = View.INVISIBLE
}
else -> {
helper.getView<View>(R.id.card4).visibility = View.INVISIBLE
}
}
}
if (channel.id != 0) {
helper.setText(R.id.text_more, "更多${channel.name}内容")
helper.setTag(R.id.card_more, channel.id)
helper.setGone(R.id.card_more, true)
helper.setGone(R.id.img_rank, false)
helper.addOnClickListener(R.id.card_more)
} else {
helper.setGone(R.id.card_more, false)
helper.setGone(R.id.img_rank, true)
helper.addOnClickListener(R.id.img_rank)
}
}
} | app/src/main/kotlin/me/sweetll/tucao/business/home/adapter/RecommendAdapter.kt | 3616882981 |
package cz.vhromada.catalog.gui.game
import cz.vhromada.catalog.entity.Game
import cz.vhromada.catalog.gui.common.AbstractInfoDialog
import cz.vhromada.catalog.gui.common.CatalogSwingConstants
import javax.swing.GroupLayout
import javax.swing.JCheckBox
import javax.swing.JLabel
import javax.swing.JSpinner
import javax.swing.JTextField
import javax.swing.SpinnerNumberModel
/**
* A class represents dialog for game.
*
* @author Vladimir Hromada
*/
class GameInfoDialog : AbstractInfoDialog<Game> {
/**
* Label for name
*/
private val nameLabel = JLabel("Name")
/**
* Text field for name
*/
private val nameData = JTextField()
/**
* Label for czech Wikipedia
*/
private val wikiCzLabel = JLabel("Czech Wikipedia")
/**
* Text field for czech Wikipedia
*/
private val wikiCzData = JTextField()
/**
* Label for english Wikipedia
*/
private val wikiEnLabel = JLabel("English Wikipedia")
/**
* Text field for english Wikipedia
*/
private val wikiEnData = JTextField()
/**
* Label for count of media
*/
private val mediaCountLabel = JLabel("Count of media")
/**
* Spinner for count of media
*/
private val mediaCountData = JSpinner(SpinnerNumberModel(1, 1, Integer.MAX_VALUE, 1))
/**
* Check box for crack
*/
private val crackData = JCheckBox("Crack")
/**
* Check box for serial key
*/
private val serialData = JCheckBox("Serial key")
/**
* Check box for patch
*/
private val patchData = JCheckBox("Patch")
/**
* Check box for trainer
*/
private val trainerData = JCheckBox("Trainer")
/**
* Check box for data for trainer
*/
private val trainerDataData = JCheckBox("Data for trainer")
/**
* Check box for editor
*/
private val editorData = JCheckBox("Editor")
/**
* Check box for saves
*/
private val savesData = JCheckBox("Saves")
/**
* Label for other data
*/
private val otherDataLabel = JLabel("Other data")
/**
* Text field for other data
*/
private val otherDataData = JTextField()
/**
* Label for note
*/
private val noteLabel = JLabel("Note")
/**
* Text field for note
*/
private val noteData = JTextField()
/**
* Creates a new instance of GameInfoDialog.
*/
constructor() {
init()
}
/**
* Creates a new instance of GameInfoDialog.
*
* @param game game
*/
constructor(game: Game) : super(game) {
init()
this.nameData.text = game.name
this.wikiCzData.text = game.wikiCz
this.wikiEnData.text = game.wikiEn
this.mediaCountData.value = game.mediaCount
this.crackData.isSelected = game.crack!!
this.serialData.isSelected = game.serialKey!!
this.patchData.isSelected = game.patch!!
this.trainerData.isSelected = game.trainer!!
this.trainerDataData.isSelected = game.trainerData!!
this.editorData.isSelected = game.editor!!
this.savesData.isSelected = game.saves!!
this.otherDataData.text = game.otherData
this.noteData.text = game.note
}
override fun initComponents() {
initLabelComponent(nameLabel, nameData)
initLabelComponent(wikiCzLabel, wikiCzData)
initLabelComponent(wikiEnLabel, wikiEnData)
initLabelComponent(mediaCountLabel, mediaCountData)
initLabelComponent(otherDataLabel, otherDataData)
initLabelComponent(noteLabel, noteData)
addInputValidator(nameData)
}
override fun processData(objectData: Game?): Game {
if (objectData == null) {
return Game(id = null,
name = nameData.text,
wikiCz = wikiCzData.text,
wikiEn = wikiEnData.text,
mediaCount = mediaCountData.value as Int,
crack = crackData.isSelected,
serialKey = serialData.isSelected,
patch = patchData.isSelected,
trainer = trainerData.isSelected,
trainerData = trainerDataData.isSelected,
editor = editorData.isSelected,
saves = savesData.isSelected,
otherData = otherDataData.text,
note = noteData.text,
position = null)
}
return objectData.copy(name = nameData.text,
wikiCz = wikiCzData.text,
wikiEn = wikiEnData.text,
mediaCount = mediaCountData.value as Int,
crack = crackData.isSelected,
serialKey = serialData.isSelected,
patch = patchData.isSelected,
trainer = trainerData.isSelected,
trainerData = trainerDataData.isSelected,
editor = editorData.isSelected,
saves = savesData.isSelected,
otherData = otherDataData.text,
note = noteData.text)
}
/**
* Returns true if input is valid: name isn't empty string.
*
* @return true if input is valid: name isn't empty string
*/
override fun isInputValid(): Boolean {
return nameData.text.isNotBlank()
}
override fun getHorizontalLayoutWithComponents(layout: GroupLayout, group: GroupLayout.Group): GroupLayout.Group {
return group
.addGroup(createHorizontalComponents(layout, nameLabel, nameData))
.addGroup(createHorizontalComponents(layout, wikiCzLabel, wikiCzData))
.addGroup(createHorizontalComponents(layout, wikiEnLabel, wikiEnData))
.addGroup(createHorizontalComponents(layout, mediaCountLabel, mediaCountData))
.addComponent(crackData, HORIZONTAL_LONG_COMPONENT_SIZE, HORIZONTAL_LONG_COMPONENT_SIZE, HORIZONTAL_LONG_COMPONENT_SIZE)
.addComponent(serialData, HORIZONTAL_LONG_COMPONENT_SIZE, HORIZONTAL_LONG_COMPONENT_SIZE, HORIZONTAL_LONG_COMPONENT_SIZE)
.addComponent(patchData, HORIZONTAL_LONG_COMPONENT_SIZE, HORIZONTAL_LONG_COMPONENT_SIZE, HORIZONTAL_LONG_COMPONENT_SIZE)
.addComponent(trainerData, HORIZONTAL_LONG_COMPONENT_SIZE, HORIZONTAL_LONG_COMPONENT_SIZE, HORIZONTAL_LONG_COMPONENT_SIZE)
.addComponent(trainerDataData, HORIZONTAL_LONG_COMPONENT_SIZE, HORIZONTAL_LONG_COMPONENT_SIZE, HORIZONTAL_LONG_COMPONENT_SIZE)
.addComponent(editorData, HORIZONTAL_LONG_COMPONENT_SIZE, HORIZONTAL_LONG_COMPONENT_SIZE, HORIZONTAL_LONG_COMPONENT_SIZE)
.addComponent(savesData, HORIZONTAL_LONG_COMPONENT_SIZE, HORIZONTAL_LONG_COMPONENT_SIZE, HORIZONTAL_LONG_COMPONENT_SIZE)
.addGroup(createHorizontalComponents(layout, otherDataLabel, otherDataData))
.addGroup(createHorizontalComponents(layout, noteLabel, noteData))
}
@Suppress("DuplicatedCode")
override fun getVerticalLayoutWithComponents(layout: GroupLayout, group: GroupLayout.Group): GroupLayout.Group {
return group
.addGroup(createVerticalComponents(layout, nameLabel, nameData))
.addGap(VERTICAL_GAP_SIZE)
.addGroup(createVerticalComponents(layout, wikiCzLabel, wikiCzData))
.addGap(VERTICAL_GAP_SIZE)
.addGroup(createVerticalComponents(layout, wikiEnLabel, wikiEnData))
.addGap(VERTICAL_GAP_SIZE)
.addGroup(createVerticalComponents(layout, mediaCountLabel, mediaCountData))
.addGap(VERTICAL_GAP_SIZE)
.addComponent(crackData, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE)
.addGap(VERTICAL_GAP_SIZE)
.addComponent(serialData, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE)
.addGap(VERTICAL_GAP_SIZE)
.addComponent(patchData, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE)
.addGap(VERTICAL_GAP_SIZE)
.addComponent(trainerData, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE)
.addGap(VERTICAL_GAP_SIZE)
.addComponent(trainerDataData, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE)
.addGap(VERTICAL_GAP_SIZE)
.addComponent(editorData, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE)
.addGap(VERTICAL_GAP_SIZE)
.addComponent(savesData, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE)
.addGap(VERTICAL_GAP_SIZE)
.addGroup(createVerticalComponents(layout, otherDataLabel, otherDataData))
.addGap(VERTICAL_GAP_SIZE)
.addGroup(createVerticalComponents(layout, noteLabel, noteData))
}
}
| src/main/kotlin/cz/vhromada/catalog/gui/game/GameInfoDialog.kt | 3978781869 |
package ml.adamsprogs.bimba.models
import java.io.Serializable
data class Plate(val id: ID, val departures: HashMap<Int, HashSet<Departure>>?) {
override fun toString(): String {
var result = "${id.line}=${id.stop}=${id.headsign}={"
if (departures != null) {
for ((service, column) in departures) {
result += service.toString() + ":"
for (departure in column) {
result += departure.toString() + ";"
}
}
}
result += "}"
return result
}
companion object {
/*fun fromString(string: String): Plate {
val (lineStr, stopStr, headsign, departuresString) = string.split("=")
val departures = HashMap<Int, HashSet<Departure>>()
departuresString.replace("{", "").replace("}", "").split(";")
.filter { it != "" }
.forEach {
try {
val (serviceStr, depStr) = it.split(":")
val dep = Departure.fromString(depStr)
if (departures[serviceStr] == null)
departures[serviceStr] = HashSet()
departures[serviceStr]!!.add(dep)
} catch (e: IllegalArgumentException) {
}
}
return Plate(ID(lineStr, stopStr, headsign), departures)
}
fun join(set: Set<Plate>): HashMap<String, ArrayList<Departure>> {
val departures = HashMap<String, ArrayList<Departure>>()
for (plate in set) {
for ((mode, d) in plate.departures!!) {
if (departures[mode] == null)
departures[mode] = ArrayList()
departures[mode]!!.addAll(d)
}
}
for ((mode, _) in departures) {
departures[mode]?.sortBy { it.time }
}
return departures
}*/
}
data class ID(val line: String, val stop: String, val headsign: String) : Serializable {
companion object {
val dummy = Plate.ID("", "", "")
fun fromString(string: String): ID {
val (line, stop, headsign) = string.split("|")
return ID(line,
stop, headsign)
}
}
override fun equals(other: Any?): Boolean {
if (other !is ID)
return false
return line == other.line && stop == other.stop && headsign.toLowerCase() == other.headsign.toLowerCase()
}
override fun toString(): String {
return "$line|$stop|$headsign"
}
override fun hashCode(): Int {
var result = line.hashCode()
result = 31 * result + stop.hashCode()
result = 31 * result + headsign.hashCode()
return result
}
constructor(other: Plate.ID) : this(other.line, other.stop, other.headsign)
}
} | app/src/main/java/ml/adamsprogs/bimba/models/Plate.kt | 935905687 |
/*
* Copyright (c) 2022 Brayan Oliveira <[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 com.ichi2.themes
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.Matchers.equalTo
import org.junit.jupiter.api.Test
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.EnumSource
class ThemeTest {
@ParameterizedTest
@EnumSource(value = Theme::class)
fun test_ofId_returns_theme(theme: Theme) {
assertThat(Theme.ofId(theme.id), equalTo(theme))
}
@Test
fun test_ofId_returns_fallback_if_id_is_invalid() {
assertThat(Theme.ofId("999"), equalTo(Theme.fallback))
}
}
| AnkiDroid/src/test/java/com/ichi2/themes/ThemeTest.kt | 1727119073 |
package com.ch3d.android.utils
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothManager
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
class BluetoothUtils {
companion object {
fun isBluetoothEnabled(context: Context): Boolean {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
val bluetoothManager = context.getSystemService(
Context.BLUETOOTH_SERVICE) as BluetoothManager
return bluetoothManager.adapter?.isEnabled ?: false
} else {
return BluetoothAdapter.getDefaultAdapter() != null
}
}
fun isBluetoothSupported(context: Context): Boolean {
return context.packageManager.hasSystemFeature(PackageManager.FEATURE_BLUETOOTH)
}
}
}
| app/src/main/kotlin/com/ch3d/android/utils/BluetoothUtils.kt | 1689462436 |
package com.infinum.dbinspector.domain.schema.shared
import com.infinum.dbinspector.data.models.local.cursor.input.Query
import com.infinum.dbinspector.data.models.local.cursor.output.QueryResult
import com.infinum.dbinspector.domain.Control
import com.infinum.dbinspector.domain.shared.base.BaseInteractor
import com.infinum.dbinspector.shared.BaseTest
import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.mockk
import org.junit.jupiter.api.Assertions.assertNotNull
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
import org.koin.core.module.Module
import org.koin.core.qualifier.StringQualifier
import org.koin.dsl.module
import org.koin.test.get
import org.mockito.kotlin.any
@DisplayName("SchemaRepository tests")
internal class SchemaRepositoryTest : BaseTest() {
override fun modules(): List<Module> = listOf(
module {
factory(qualifier = StringQualifier("getPage")) { mockk<BaseInteractor<Query, QueryResult>>() }
factory(qualifier = StringQualifier("getByName")) { mockk<BaseInteractor<Query, QueryResult>>() }
factory(qualifier = StringQualifier("dropByName")) { mockk<BaseInteractor<Query, QueryResult>>() }
factory { mockk<Control.Content>() }
}
)
@Test
fun `Can be instantiated`() {
val repository = object : SchemaRepository(
get(qualifier = StringQualifier("getPage")),
get(qualifier = StringQualifier("getByName")),
get(qualifier = StringQualifier("dropByName")),
get()
) {}
assertNotNull(repository)
}
@Test
fun `Get schema page calls interactor and control once`() {
val interactor: BaseInteractor<Query, QueryResult> = get(qualifier = StringQualifier("getPage"))
val control: Control.Content = get()
val repository = object : SchemaRepository(
interactor,
get(qualifier = StringQualifier("getByName")),
get(qualifier = StringQualifier("dropByName")),
control
) {}
coEvery { interactor.invoke(any()) } returns mockk()
coEvery { control.converter.invoke(any()) } returns mockk()
coEvery { control.mapper.invoke(any()) } returns mockk()
test {
repository.getPage(any())
}
coVerify(exactly = 1) { interactor.invoke(any()) }
coVerify(exactly = 1) { control.converter.invoke(any()) }
coVerify(exactly = 1) { control.mapper.invoke(any()) }
}
@Test
fun `Get schema by name calls interactor and control once`() {
val interactor: BaseInteractor<Query, QueryResult> = get(qualifier = StringQualifier("getByName"))
val control: Control.Content = get()
val repository = object : SchemaRepository(
get(qualifier = StringQualifier("getPage")),
interactor,
get(qualifier = StringQualifier("dropByName")),
control
) {}
coEvery { interactor.invoke(any()) } returns mockk()
coEvery { control.converter.invoke(any()) } returns mockk()
coEvery { control.mapper.invoke(any()) } returns mockk()
test {
repository.getByName(any())
}
coVerify(exactly = 1) { interactor.invoke(any()) }
coVerify(exactly = 1) { control.converter.invoke(any()) }
coVerify(exactly = 1) { control.mapper.invoke(any()) }
}
@Test
fun `Drop schema by name calls interactor and control once`() {
val interactor: BaseInteractor<Query, QueryResult> = get(qualifier = StringQualifier("dropByName"))
val control: Control.Content = get()
val repository = object : SchemaRepository(
get(qualifier = StringQualifier("getPage")),
get(qualifier = StringQualifier("getByName")),
interactor,
control
) {}
coEvery { interactor.invoke(any()) } returns mockk()
coEvery { control.converter.invoke(any()) } returns mockk()
coEvery { control.mapper.invoke(any()) } returns mockk()
test {
repository.dropByName(any())
}
coVerify(exactly = 1) { interactor.invoke(any()) }
coVerify(exactly = 1) { control.converter.invoke(any()) }
coVerify(exactly = 1) { control.mapper.invoke(any()) }
}
}
| dbinspector/src/test/kotlin/com/infinum/dbinspector/domain/schema/shared/SchemaRepositoryTest.kt | 920402429 |
/***************************************************************************************
* Copyright (c) 2012 Norbert Nagold <[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 com.ichi2.anki
import android.os.Bundle
import android.view.MenuItem
import androidx.fragment.app.commit
import com.ichi2.anim.ActivityTransitionAnimation
import com.ichi2.anki.StudyOptionsFragment.StudyOptionsListener
import com.ichi2.anki.dialogs.customstudy.CustomStudyDialog.CustomStudyListener
import com.ichi2.anki.dialogs.customstudy.CustomStudyDialogFactory
import com.ichi2.utils.ExtendedFragmentFactory
import com.ichi2.widget.WidgetStatus
import timber.log.Timber
class StudyOptionsActivity : NavigationDrawerActivity(), StudyOptionsListener, CustomStudyListener {
override fun onCreate(savedInstanceState: Bundle?) {
if (showedActivityFailedScreen(savedInstanceState)) {
return
}
val customStudyDialogFactory = CustomStudyDialogFactory({ this.col }, this)
customStudyDialogFactory.attachToActivity<ExtendedFragmentFactory>(this)
super.onCreate(savedInstanceState)
setContentView(R.layout.studyoptions)
// create inherited navigation drawer layout here so that it can be used by parent class
initNavigationDrawer(findViewById(android.R.id.content))
if (savedInstanceState == null) {
loadStudyOptionsFragment()
}
}
private fun loadStudyOptionsFragment() {
var withDeckOptions = false
if (intent.extras != null) {
withDeckOptions = intent.extras!!.getBoolean("withDeckOptions")
}
val currentFragment = StudyOptionsFragment.newInstance(withDeckOptions)
supportFragmentManager.commit {
replace(R.id.studyoptions_frame, currentFragment)
}
}
private val currentFragment: StudyOptionsFragment?
get() = supportFragmentManager.findFragmentById(R.id.studyoptions_frame) as StudyOptionsFragment?
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (drawerToggle.onOptionsItemSelected(item)) {
return true
}
if (item.itemId == android.R.id.home) {
closeStudyOptions()
return true
}
return super.onOptionsItemSelected(item)
}
private fun closeStudyOptions(result: Int = RESULT_OK) {
// mCompat.invalidateOptionsMenu(this);
setResult(result)
finishWithAnimation(ActivityTransitionAnimation.Direction.END)
}
override fun onBackPressed() {
if (isDrawerOpen) {
super.onBackPressed()
} else {
Timber.i("Back key pressed")
closeStudyOptions()
}
}
public override fun onStop() {
super.onStop()
if (colIsOpen()) {
WidgetStatus.update(this)
saveCollectionInBackground()
}
}
public override fun onResume() {
super.onResume()
selectNavigationItem(-1)
}
override fun onRequireDeckListUpdate() {
currentFragment!!.refreshInterface()
}
/**
* Callback methods from CustomStudyDialog
*/
override fun onCreateCustomStudySession() {
// Sched already reset by CollectionTask in CustomStudyDialog
currentFragment!!.refreshInterface()
}
override fun onExtendStudyLimits() {
// Sched needs to be reset so provide true argument
currentFragment!!.refreshInterface(true)
}
}
| AnkiDroid/src/main/java/com/ichi2/anki/StudyOptionsActivity.kt | 3890292371 |
package com.byagowi.persiancalendar.utils
import android.content.ContentResolver
import android.content.Context
import android.content.Intent
import android.net.Uri
import androidx.core.net.toUri
import com.byagowi.persiancalendar.*
import com.byagowi.persiancalendar.service.AthanNotification
import com.byagowi.persiancalendar.ui.AthanActivity
// https://stackoverflow.com/a/27788209
fun getDefaultAthanUri(context: Context): Uri =
(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" +
context.resources.getResourcePackageName(R.raw.abdulbasit) + "/" +
context.resources.getResourceTypeName(R.raw.abdulbasit) + "/" +
context.resources.getResourceEntryName(R.raw.abdulbasit)).toUri()
val Context.athanVolume: Int
get() = appPrefs.getInt(PREF_ATHAN_VOLUME, DEFAULT_ATHAN_VOLUME)
val Context.isAscendingAthanVolumeEnabled: Boolean
get() = appPrefs.getBoolean(PREF_ASCENDING_ATHAN_VOLUME, false)
fun getCustomAthanUri(context: Context): Uri? =
context.appPrefs.getString(PREF_ATHAN_URI, null)?.takeUnless { it.isEmpty() }?.toUri()
fun startAthan(context: Context, prayTimeKey: String): Any? = if (notificationAthan) {
context.startService(
Intent(context, AthanNotification::class.java)
.putExtra(KEY_EXTRA_PRAYER_KEY, prayTimeKey)
)
} else {
context.startActivity(
Intent(context, AthanActivity::class.java)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
.putExtra(KEY_EXTRA_PRAYER_KEY, prayTimeKey)
)
} | PersianCalendar/src/main/java/com/byagowi/persiancalendar/utils/AthanUtils.kt | 619968667 |
package de.westnordost.streetcomplete.data.osmnotes
import java.io.File
fun deleteImages(imagePaths: List<String>?) {
for (path in imagePaths.orEmpty()) {
val file = File(path)
if (file.exists()) {
file.delete()
}
}
}
| app/src/main/java/de/westnordost/streetcomplete/data/osmnotes/AttachPhotoUtils.kt | 3825035166 |
/*
* Copyright (c) 2018. Toshi Inc
*
* 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 com.toshi.view.adapter
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup
import com.toshi.R
import com.toshi.view.adapter.viewholder.InviteFriendViewHolder
class InviteFriendAdapter(
private val inviteFriendAction: () -> Unit
) : BaseCompoundableAdapter<InviteFriendViewHolder, Int>() {
init {
setItemList(listOf(1))
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): InviteFriendViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.list_item__invite_friend, parent, false)
return InviteFriendViewHolder(view)
}
override fun onBindViewHolder(holder: InviteFriendViewHolder, position: Int) {
holder.itemView.setOnClickListener { inviteFriendAction() }
}
override fun compoundableBindViewHolder(viewHolder: RecyclerView.ViewHolder, adapterIndex: Int) {
val typedHolder = viewHolder as? InviteFriendViewHolder ?: return
onBindViewHolder(typedHolder, adapterIndex)
}
} | app/src/main/java/com/toshi/view/adapter/InviteFriendAdapter.kt | 1557235686 |
package com.recurly.androidsdk.data.model.tokenization
import com.google.gson.annotations.SerializedName
data class RecurlyBillingInfo(
@SerializedName("first_name")
var firstName: String,
@SerializedName("last_name")
var lastName: String,
@SerializedName("company")
var company: String,
@SerializedName("address1")
var addressOne: String,
@SerializedName("address2")
var addressTwo: String,
@SerializedName("city")
var city: String,
@SerializedName("state")
var state: String,
@SerializedName("postal_code")
var postalCode: String,
@SerializedName("country")
var country: String,
@SerializedName("phone")
var phone: String,
@SerializedName("vat_number")
var vatNumber: String,
@SerializedName("tax_identifier")
var taxIdentifier: String,
@SerializedName("tax_identifier_type")
var taxIdentifierType: String
) | AndroidSdk/src/main/java/com/recurly/androidsdk/data/model/tokenization/RecurlyBillingInfo.kt | 2068278361 |
/*
* Westford Wayland Compositor.
* Copyright (C) 2016 Erik De Rijcke
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.westford.compositor.core
import com.google.auto.factory.AutoFactory
import com.google.auto.factory.Provided
import org.freedesktop.wayland.server.WlOutputResource
import org.freedesktop.wayland.shared.WlOutputTransform
import org.westford.Signal
import org.westford.compositor.core.calc.Mat4
import org.westford.compositor.core.events.OutputTransform
import javax.annotation.Nonnegative
@AutoFactory(className = "PrivateOutputFactory",
allowSubclasses = true) class Output(@param:Provided val regionFactory: FiniteRegionFactory,
@param:Provided var region: FiniteRegion,
val renderOutput: RenderOutput,
val name: String) {
val transformSignal = Signal<OutputTransform>()
val modeSignal = Signal<OutputMode>()
@Nonnegative @get:Nonnegative var scale = 1f
set(@Nonnegative scale) {
field = scale
updateOutputTransform()
}
/**
* translate from output space to compositor space
* @return
*/
var transform = Mat4.IDENTITY
private set
/**
* translate from compositor space to output space
* @return
*/
var inverseTransform = Mat4.IDENTITY
private set
var geometry = OutputGeometry(physicalWidth = 0,
physicalHeight = 0,
make = "",
model = "",
x = 0,
y = 0,
subpixel = 0,
transform = 0)
private set
var mode = OutputMode(width = 0,
height = 0,
refresh = 0,
flags = 0)
private set
fun update(resources: Set<WlOutputResource>,
outputGeometry: OutputGeometry) {
if (this.geometry != outputGeometry) {
this.geometry = outputGeometry
updateOutputTransform()
}
resources.forEach { this.notifyGeometry(it) }
}
private fun updateOutputTransform() {
val scaleMat = Transforms.SCALE(this.scale)
val x = this.geometry.x
val y = this.geometry.y
val moveMat = Transforms.TRANSLATE(x,
y)
val transformMat: Mat4
val transformNr = this.geometry.transform
if (transformNr == WlOutputTransform.NORMAL.value) {
transformMat = Mat4.IDENTITY
}
else if (transformNr == WlOutputTransform._90.value) {
transformMat = Transforms._90
}
else if (transformNr == WlOutputTransform._180.value) {
transformMat = Transforms._180
}
else if (transformNr == WlOutputTransform._270.value) {
transformMat = Transforms._270
}
else if (transformNr == WlOutputTransform.FLIPPED.value) {
transformMat = Transforms.FLIPPED
}
else if (transformNr == WlOutputTransform.FLIPPED_90.value) {
transformMat = Transforms.FLIPPED_90
}
else if (transformNr == WlOutputTransform.FLIPPED_180.value) {
transformMat = Transforms.FLIPPED_180
}
else if (transformNr == WlOutputTransform.FLIPPED_270.value) {
transformMat = Transforms.FLIPPED_270
}
else {
transformMat = Mat4.IDENTITY
}
val newTransform = transformMat * scaleMat * moveMat
if (this.transform != newTransform) {
this.transform = newTransform
this.inverseTransform = this.transform.invert()
updateRegion()
this.transformSignal.emit(OutputTransform())
}
}
private fun updateRegion() {
val regionTopLeft = this.transform * Point.ZERO
val regionBottomRight = this.transform * Point(this.mode.width,
this.mode.height)
//TODO fire region event?
//TODO check if the region is properly updated in the unit tests
this.region = this.regionFactory.create() + Rectangle.create(regionTopLeft,
regionBottomRight)
}
fun update(resources: Set<WlOutputResource>,
outputMode: OutputMode): Output {
if (this.mode != outputMode) {
this.mode = outputMode
updateRegion()
this.modeSignal.emit(outputMode)
}
resources.forEach { this.notifyMode(it) }
return this
}
fun notifyMode(wlOutputResource: WlOutputResource) {
wlOutputResource.mode(this.mode.flags,
this.mode.width,
this.mode.height,
this.mode.refresh)
}
fun notifyGeometry(wlOutputResource: WlOutputResource) {
wlOutputResource.geometry(this.geometry.x,
this.geometry.y,
this.geometry.physicalWidth,
this.geometry.physicalHeight,
this.geometry.subpixel,
this.geometry.make,
this.geometry.model,
this.geometry.transform)
}
fun local(global: Point): Point = this.inverseTransform * global
fun global(outputLocal: Point): Point = this.transform * outputLocal
}
| compositor/src/main/kotlin/org/westford/compositor/core/Output.kt | 2898173300 |
package org.wordpress.android.fluxc.store
import kotlinx.coroutines.flow.Flow
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.wordpress.android.fluxc.Dispatcher
import org.wordpress.android.fluxc.Payload
import org.wordpress.android.fluxc.action.WCOrderAction
import org.wordpress.android.fluxc.action.WCOrderAction.FETCH_ORDERS
import org.wordpress.android.fluxc.annotations.action.Action
import org.wordpress.android.fluxc.generated.ListActionBuilder
import org.wordpress.android.fluxc.model.LocalOrRemoteId.LocalId
import org.wordpress.android.fluxc.model.LocalOrRemoteId.RemoteId
import org.wordpress.android.fluxc.model.OrderEntity
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.model.WCOrderListDescriptor
import org.wordpress.android.fluxc.model.WCOrderShipmentProviderModel
import org.wordpress.android.fluxc.model.WCOrderShipmentTrackingModel
import org.wordpress.android.fluxc.model.WCOrderStatusModel
import org.wordpress.android.fluxc.model.WCOrderSummaryModel
import org.wordpress.android.fluxc.network.BaseRequest.BaseNetworkError
import org.wordpress.android.fluxc.network.rest.wpcom.wc.WooResult
import org.wordpress.android.fluxc.network.rest.wpcom.wc.order.OrderRestClient
import org.wordpress.android.fluxc.persistence.OrderSqlUtils
import org.wordpress.android.fluxc.persistence.dao.OrderMetaDataDao
import org.wordpress.android.fluxc.persistence.dao.OrderNotesDao
import org.wordpress.android.fluxc.persistence.dao.OrdersDao
import org.wordpress.android.fluxc.persistence.entity.OrderMetaDataEntity
import org.wordpress.android.fluxc.persistence.entity.OrderNoteEntity
import org.wordpress.android.fluxc.store.ListStore.FetchedListItemsPayload
import org.wordpress.android.fluxc.store.ListStore.ListError
import org.wordpress.android.fluxc.store.ListStore.ListErrorType
import org.wordpress.android.fluxc.store.WCOrderStore.OrderErrorType.GENERIC_ERROR
import org.wordpress.android.fluxc.store.WCOrderStore.UpdateOrderResult.OptimisticUpdateResult
import org.wordpress.android.fluxc.store.WCOrderStore.UpdateOrderResult.RemoteUpdateResult
import org.wordpress.android.fluxc.tools.CoroutineEngine
import org.wordpress.android.util.AppLog
import org.wordpress.android.util.AppLog.T
import org.wordpress.android.util.AppLog.T.API
import java.util.Calendar
import java.util.Locale
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class WCOrderStore @Inject constructor(
dispatcher: Dispatcher,
private val wcOrderRestClient: OrderRestClient,
private val wcOrderFetcher: WCOrderFetcher,
private val coroutineEngine: CoroutineEngine,
private val ordersDao: OrdersDao,
private val orderNotesDao: OrderNotesDao,
private val orderMetaDataDao: OrderMetaDataDao,
private val insertOrder: InsertOrder
) : Store(dispatcher) {
companion object {
const val NUM_ORDERS_PER_FETCH = 15
const val DEFAULT_ORDER_STATUS = "any"
}
class FetchOrdersPayload(
var site: SiteModel,
var statusFilter: String? = null,
var loadMore: Boolean = false
) : Payload<BaseNetworkError>()
class FetchOrderListPayload(
val listDescriptor: WCOrderListDescriptor,
val offset: Long,
val requestStartTime: Calendar = Calendar.getInstance()
) : Payload<BaseNetworkError>()
class FetchOrdersByIdsPayload(
val site: SiteModel,
val orderIds: List<Long>
) : Payload<BaseNetworkError>()
data class FetchOrdersResponsePayload(
val site: SiteModel,
val ordersWithMeta: List<Pair<OrderEntity, List<OrderMetaDataEntity>>> = emptyList(),
val statusFilter: String? = null,
val loadedMore: Boolean = false,
val canLoadMore: Boolean = false
) : Payload<OrderError>() {
val orders = ordersWithMeta.map { it.first }
constructor(error: OrderError, site: SiteModel) : this(site) {
this.error = error
}
}
class FetchOrderListResponsePayload(
val listDescriptor: WCOrderListDescriptor,
var orderSummaries: List<WCOrderSummaryModel> = emptyList(),
var loadedMore: Boolean = false,
var canLoadMore: Boolean = false,
val requestStartTime: Calendar
) : Payload<OrderError>() {
constructor(
error: OrderError,
listDescriptor: WCOrderListDescriptor,
requestStartTime: Calendar
) : this(listDescriptor, requestStartTime = requestStartTime) {
this.error = error
}
}
class FetchOrdersByIdsResponsePayload(
val site: SiteModel,
var orderIds: List<Long>,
var fetchedOrders: List<Pair<OrderEntity, List<OrderMetaDataEntity>>> = emptyList()
) : Payload<OrderError>() {
constructor(
error: OrderError,
site: SiteModel,
orderIds: List<Long>
) : this(site = site, orderIds = orderIds) {
this.error = error
}
}
class SearchOrdersPayload(
var site: SiteModel,
var searchQuery: String,
var offset: Int
) : Payload<BaseNetworkError>()
class SearchOrdersResponsePayload(
var site: SiteModel,
var searchQuery: String,
var canLoadMore: Boolean = false,
var offset: Int = 0,
var orders: List<OrderEntity> = emptyList()
) : Payload<OrderError>() {
constructor(error: OrderError, site: SiteModel, query: String) : this(site, query) {
this.error = error
}
}
class FetchOrdersCountPayload(
var site: SiteModel,
var statusFilter: String
) : Payload<BaseNetworkError>()
class FetchOrdersCountResponsePayload(
var site: SiteModel,
var statusFilter: String,
var count: Int = 0
) : Payload<OrderError>() {
constructor(error: OrderError, site: SiteModel, statusFilter: String) : this(site, statusFilter) {
this.error = error
}
}
class FetchHasOrdersResponsePayload(
var site: SiteModel,
var statusFilter: String? = null,
var hasOrders: Boolean = false
) : Payload<OrderError>() {
constructor(error: OrderError, site: SiteModel) : this(site) {
this.error = error
}
}
class UpdateOrderStatusPayload(
val order: OrderEntity,
val site: SiteModel,
val status: String
) : Payload<BaseNetworkError>()
sealed class RemoteOrderPayload : Payload<OrderError>() {
abstract val site: SiteModel
abstract val order: OrderEntity
data class Fetching(
val orderWithMeta: Pair<OrderEntity, List<OrderMetaDataEntity>>,
override val site: SiteModel
) : RemoteOrderPayload() {
override val order = orderWithMeta.first
constructor(
error: OrderError,
order: Pair<OrderEntity, List<OrderMetaDataEntity>>,
site: SiteModel
) : this(order, site) {
this.error = error
}
}
data class Updating(
override val order: OrderEntity,
override val site: SiteModel
) : RemoteOrderPayload() {
constructor(
error: OrderError,
order: OrderEntity,
site: SiteModel
) : this(order, site) {
this.error = error
}
}
}
sealed class UpdateOrderResult {
abstract val event: OnOrderChanged
data class OptimisticUpdateResult(override val event: OnOrderChanged) : UpdateOrderResult()
data class RemoteUpdateResult(override val event: OnOrderChanged) : UpdateOrderResult()
}
class FetchOrderStatusOptionsPayload(val site: SiteModel) : Payload<BaseNetworkError>()
class FetchOrderStatusOptionsResponsePayload(
val site: SiteModel,
val labels: List<WCOrderStatusModel> = emptyList()
) : Payload<OrderError>() {
constructor(error: OrderError, site: SiteModel) : this(site) {
this.error = error
}
}
class FetchOrderShipmentTrackingsResponsePayload(
var site: SiteModel,
var orderId: Long,
var trackings: List<WCOrderShipmentTrackingModel> = emptyList()
) : Payload<OrderError>() {
constructor(error: OrderError, site: SiteModel, orderId: Long) :
this(site, orderId) {
this.error = error
}
}
class AddOrderShipmentTrackingPayload(
val site: SiteModel,
var orderId: Long,
val tracking: WCOrderShipmentTrackingModel,
val isCustomProvider: Boolean
) : Payload<BaseNetworkError>()
class AddOrderShipmentTrackingResponsePayload(
val site: SiteModel,
var orderId: Long,
val tracking: WCOrderShipmentTrackingModel?
) : Payload<OrderError>() {
constructor(
error: OrderError,
site: SiteModel,
orderId: Long,
tracking: WCOrderShipmentTrackingModel
) : this(site, orderId, tracking) {
this.error = error
}
}
class DeleteOrderShipmentTrackingPayload(
val site: SiteModel,
var orderId: Long,
val tracking: WCOrderShipmentTrackingModel
) : Payload<BaseNetworkError>()
class DeleteOrderShipmentTrackingResponsePayload(
val site: SiteModel,
var orderId: Long,
val tracking: WCOrderShipmentTrackingModel?
) : Payload<OrderError>() {
constructor(
error: OrderError,
site: SiteModel,
orderId: Long,
tracking: WCOrderShipmentTrackingModel?
) : this(site, orderId, tracking) {
this.error = error
}
}
class FetchOrderShipmentProvidersPayload(
val site: SiteModel,
val order: OrderEntity
) : Payload<BaseNetworkError>()
class FetchOrderShipmentProvidersResponsePayload(
val site: SiteModel,
val order: OrderEntity,
val providers: List<WCOrderShipmentProviderModel> = emptyList()
) : Payload<OrderError>() {
constructor(error: OrderError, site: SiteModel, order: OrderEntity) : this(site, order) {
this.error = error
}
}
data class OrderError(val type: OrderErrorType = GENERIC_ERROR, val message: String = "") : OnChangedError
enum class OrderErrorType {
INVALID_PARAM,
INVALID_ID,
ORDER_STATUS_NOT_FOUND,
PLUGIN_NOT_ACTIVE,
INVALID_RESPONSE,
GENERIC_ERROR,
EMPTY_BILLING_EMAIL;
companion object {
private val reverseMap = values().associateBy(OrderErrorType::name)
fun fromString(type: String) = reverseMap[type.toUpperCase(Locale.US)] ?: GENERIC_ERROR
}
}
sealed class HasOrdersResult {
data class Success(val hasOrders: Boolean) : HasOrdersResult()
data class Failure(val error: OrderError) : HasOrdersResult()
}
// OnChanged events
data class OnOrderChanged(
val statusFilter: String? = null,
val canLoadMore: Boolean = false,
val causeOfChange: WCOrderAction? = null,
private val orderError: OrderError? = null
) : OnChanged<OrderError>() {
init {
super.error = orderError
}
}
/**
* Emitted after fetching a list of Order summaries from the network.
*/
class OnOrderSummariesFetched(
val listDescriptor: WCOrderListDescriptor,
val duration: Long
) : OnChanged<OrderError>()
class OnOrdersFetchedByIds(
val site: SiteModel,
val orderIds: List<Long>
) : OnChanged<OrderError>()
class OnOrdersSearched(
var searchQuery: String = "",
var canLoadMore: Boolean = false,
var nextOffset: Int = 0,
var searchResults: List<OrderEntity> = emptyList()
) : OnChanged<OrderError>()
class OnOrderStatusOptionsChanged(
var rowsAffected: Int
) : OnChanged<OrderError>()
class OnOrderShipmentProvidersChanged(
var rowsAffected: Int
) : OnChanged<OrderError>()
override fun onRegister() = AppLog.d(T.API, "WCOrderStore onRegister")
/**
* Given a [SiteModel] and optional statuses, returns all orders for that site matching any of those statuses.
*/
suspend fun getOrdersForSite(site: SiteModel, vararg status: String) = if (status.isEmpty()) {
ordersDao.getOrdersForSite(site.localId())
} else {
ordersDao.getOrdersForSite(site.localId(), status = status.asList())
}
/**
* Observe the changes to orders for a given [SiteModel]
*
* @param site the current site
* @param statuses an optional list of statuses to filter the list of orders, pass an empty list to include all
* orders
*/
fun observeOrdersForSite(site: SiteModel, statuses: List<String> = emptyList()): Flow<List<OrderEntity>> {
return if (statuses.isEmpty()) {
ordersDao.observeOrdersForSite(site.localId())
} else {
ordersDao.observeOrdersForSite(site.localId(), statuses)
}
}
/**
* Observe the changes to the number of orders for a given [SiteModel]
*
* @param site the current site
* @param statuses a list of statuses to filter the list of orders
*/
fun observeOrderCountForSite(
site: SiteModel,
statuses: List<String>
): Flow<Int> = ordersDao.observeOrderCountForSite(site.localId(), statuses)
fun getOrdersForDescriptor(
orderListDescriptor: WCOrderListDescriptor,
orderIds: List<Long>
): Map<Long, OrderEntity> {
val orders = ordersDao.getOrdersForSiteByRemoteIds(orderListDescriptor.site.localId(), orderIds)
return orders.associateBy { it.orderId }
}
fun getOrderSummariesByRemoteOrderIds(
site: SiteModel,
orderIds: List<Long>
): Map<RemoteId, WCOrderSummaryModel> {
val orderSummaries = OrderSqlUtils.getOrderSummariesForRemoteIds(site, orderIds)
return orderSummaries.associateBy { RemoteId(it.orderId) }
}
/**
* Given an order id and [SiteModel],
* returns the corresponding order from the database as a [OrderEntity].
*/
suspend fun getOrderByIdAndSite(orderId: Long, site: SiteModel): OrderEntity? {
return ordersDao.getOrder(orderId, site.localId())
}
/**
* Given an order id and [SiteModel],
* returns the metadata from the database for an order
*/
suspend fun getOrderMetadata(orderId: Long, site: SiteModel): List<OrderMetaDataEntity> {
return orderMetaDataDao.getOrderMetaData(orderId, site.localId())
}
/**
* Given an order id and [SiteModel],
* returns whether there is metadata in the database for an order
*/
suspend fun hasOrderMetadata(orderId: Long, site: SiteModel): Boolean {
return orderMetaDataDao.hasOrderMetaData(orderId, site.localId())
}
/**
* Returns the notes belonging to supplied [OrderEntity] as a list of [OrderNoteEntity].
*/
suspend fun getOrderNotesForOrder(site: SiteModel, orderId: Long): List<OrderNoteEntity> =
orderNotesDao.queryNotesOfOrder(siteId = site.remoteId(), orderId = RemoteId(orderId))
/**
* Returns the order status options available for the provided site [SiteModel] as a list of [WCOrderStatusModel].
*/
fun getOrderStatusOptionsForSite(site: SiteModel): List<WCOrderStatusModel> =
OrderSqlUtils.getOrderStatusOptionsForSite(site)
/**
* Returns the order status as a [WCOrderStatusModel] that matches the provided order status key.
*/
fun getOrderStatusForSiteAndKey(site: SiteModel, key: String): WCOrderStatusModel? =
OrderSqlUtils.getOrderStatusOptionForSiteByKey(site, key)
/**
* Returns shipment trackings as list of [WCOrderShipmentTrackingModel] for a single [OrderEntity]
*/
fun getShipmentTrackingsForOrder(site: SiteModel, orderId: Long): List<WCOrderShipmentTrackingModel> =
OrderSqlUtils.getShipmentTrackingsForOrder(site, orderId)
fun getShipmentTrackingByTrackingNumber(site: SiteModel, orderId: Long, trackingNumber: String) =
OrderSqlUtils.getShipmentTrackingByTrackingNumber(site, orderId, trackingNumber)
/**
* Returns the shipment providers as a list of [WCOrderShipmentProviderModel]
*/
fun getShipmentProvidersForSite(site: SiteModel): List<WCOrderShipmentProviderModel> =
OrderSqlUtils.getOrderShipmentProvidersForSite(site)
@Suppress("ComplexMethod", "UseCheckOrError")
@Subscribe(threadMode = ThreadMode.ASYNC)
override fun onAction(action: Action<*>) {
val actionType = action.type as? WCOrderAction ?: return
when (actionType) {
// remote actions
WCOrderAction.FETCH_ORDERS -> fetchOrders(action.payload as FetchOrdersPayload)
WCOrderAction.FETCH_ORDER_LIST -> fetchOrderList(action.payload as FetchOrderListPayload)
WCOrderAction.FETCH_ORDERS_BY_IDS -> fetchOrdersByIds(action.payload as FetchOrdersByIdsPayload)
WCOrderAction.FETCH_ORDERS_COUNT -> fetchOrdersCount(action.payload as FetchOrdersCountPayload)
WCOrderAction.UPDATE_ORDER_STATUS ->
throw IllegalStateException("Invalid action. Use suspendable updateOrderStatus(..) directly")
WCOrderAction.SEARCH_ORDERS -> searchOrders(action.payload as SearchOrdersPayload)
WCOrderAction.FETCH_ORDER_STATUS_OPTIONS ->
fetchOrderStatusOptions(action.payload as FetchOrderStatusOptionsPayload)
// remote responses
WCOrderAction.FETCHED_ORDERS -> handleFetchOrdersCompleted(action.payload as FetchOrdersResponsePayload)
WCOrderAction.FETCHED_ORDER_LIST ->
handleFetchOrderListCompleted(action.payload as FetchOrderListResponsePayload)
WCOrderAction.FETCHED_ORDERS_BY_IDS ->
handleFetchOrderByIdsCompleted(action.payload as FetchOrdersByIdsResponsePayload)
WCOrderAction.FETCHED_ORDERS_COUNT ->
handleFetchOrdersCountCompleted(action.payload as FetchOrdersCountResponsePayload)
WCOrderAction.SEARCHED_ORDERS -> handleSearchOrdersCompleted(action.payload as SearchOrdersResponsePayload)
WCOrderAction.FETCHED_ORDER_STATUS_OPTIONS ->
handleFetchOrderStatusOptionsCompleted(action.payload as FetchOrderStatusOptionsResponsePayload)
}
}
private fun fetchOrders(payload: FetchOrdersPayload) {
val offset = if (payload.loadMore) {
ordersDao.getOrderCountForSite(payload.site.localId())
} else {
0
}
wcOrderRestClient.fetchOrders(payload.site, offset, payload.statusFilter)
}
private fun fetchOrderList(payload: FetchOrderListPayload) {
wcOrderRestClient.fetchOrderListSummaries(
listDescriptor = payload.listDescriptor,
offset = payload.offset,
requestStartTime = payload.requestStartTime
)
}
private fun fetchOrdersByIds(payload: FetchOrdersByIdsPayload) {
payload.orderIds.chunked(NUM_ORDERS_PER_FETCH).forEach { idsToFetch ->
wcOrderRestClient.fetchOrdersByIds(payload.site, idsToFetch)
}
}
private fun searchOrders(payload: SearchOrdersPayload) {
wcOrderRestClient.searchOrders(payload.site, payload.searchQuery, payload.offset)
}
private fun fetchOrdersCount(payload: FetchOrdersCountPayload) {
with(payload) { wcOrderRestClient.fetchOrderCount(site, statusFilter) }
}
suspend fun fetchHasOrders(site: SiteModel, status: String?): HasOrdersResult {
return coroutineEngine.withDefaultContext(T.API, this, "fetchHasOrders") {
val result = wcOrderRestClient.fetchHasOrders(site, status)
return@withDefaultContext if (result.isError) {
HasOrdersResult.Failure(result.error)
} else {
HasOrdersResult.Success(result.hasOrders)
}
}
}
suspend fun fetchSingleOrder(site: SiteModel, remoteOrderId: Long): OnOrderChanged {
return coroutineEngine.withDefaultContext(T.API, this, "fetchSingleOrder") {
val result = wcOrderRestClient.fetchSingleOrder(site, remoteOrderId)
return@withDefaultContext if (result.isError) {
OnOrderChanged(orderError = result.error)
} else {
insertOrder(result.orderWithMeta)
OnOrderChanged()
}
}
}
suspend fun updateOrderStatus(
orderId: Long,
site: SiteModel,
newStatus: WCOrderStatusModel
): Flow<UpdateOrderResult> {
return coroutineEngine.flowWithDefaultContext(T.API, this, "updateOrderStatus") {
val orderModel = ordersDao.getOrder(orderId, site.localId())
if (orderModel != null) {
updateOrderStatusLocally(orderId, site.localId(), newStatus.statusKey)
val optimisticUpdateResult = OnOrderChanged(
causeOfChange = WCOrderAction.UPDATE_ORDER_STATUS
)
emit(OptimisticUpdateResult(optimisticUpdateResult))
val remotePayload = wcOrderRestClient.updateOrderStatus(orderModel, site, newStatus.statusKey)
val remoteUpdateResult: OnOrderChanged = if (remotePayload.isError) {
revertOrderStatus(remotePayload)
} else {
ordersDao.insertOrUpdateOrder(remotePayload.order)
OnOrderChanged()
}.copy(causeOfChange = WCOrderAction.UPDATE_ORDER_STATUS)
emit(RemoteUpdateResult(remoteUpdateResult))
// Needs to remain here until all event bus observables are removed from the client code
emitChange(remoteUpdateResult)
} else {
emit(
OptimisticUpdateResult(
OnOrderChanged(
orderError = OrderError(
message = "Order with id $orderId not found"
)
)
)
)
}
}
}
private suspend fun updateOrderStatusLocally(orderId: Long, localSiteId: LocalId, newStatus: String) {
val updatedOrder = ordersDao.getOrder(orderId, localSiteId)!!
.copy(status = newStatus)
ordersDao.insertOrUpdateOrder(updatedOrder)
}
@Suppress("SpreadOperator")
suspend fun fetchOrderNotes(
site: SiteModel,
orderId: Long
): WooResult<List<OrderNoteEntity>> {
return coroutineEngine.withDefaultContext(T.API, this, "fetchOrderNotes") {
val result = wcOrderRestClient.fetchOrderNotes(orderId, site)
return@withDefaultContext result.let {
if (!it.isError) {
orderNotesDao.insertNotes(*it.result!!.toTypedArray())
}
result.asWooResult()
}
}
}
suspend fun postOrderNote(
site: SiteModel,
orderId: Long,
note: String,
isCustomerNote: Boolean
): WooResult<OrderNoteEntity> {
return coroutineEngine.withDefaultContext(T.API, this, "postOrderNote") {
val result = wcOrderRestClient.postOrderNote(orderId, site, note, isCustomerNote)
return@withDefaultContext if (result.isError) {
result.asWooResult()
} else {
orderNotesDao.insertNotes(result.result!!)
result.asWooResult()
}
}
}
private fun fetchOrderStatusOptions(payload: FetchOrderStatusOptionsPayload) {
wcOrderRestClient.fetchOrderStatusOptions(payload.site)
}
suspend fun fetchOrderShipmentTrackings(orderId: Long, site: SiteModel): OnOrderChanged {
return coroutineEngine.withDefaultContext(T.API, this, "fetchOrderShipmentTrackings") {
val result = wcOrderRestClient.fetchOrderShipmentTrackings(site, orderId)
return@withDefaultContext if (result.isError) {
OnOrderChanged(orderError = result.error)
} else {
// Calculate which existing records should be deleted because they no longer exist in the payload
val existingTrackings = OrderSqlUtils.getShipmentTrackingsForOrder(
result.site,
result.orderId
)
val deleteTrackings = mutableListOf<WCOrderShipmentTrackingModel>()
existingTrackings.iterator().forEach { existing ->
var exists = false
result.trackings.iterator().forEach nti@{ newTracking ->
if (newTracking.remoteTrackingId == existing.remoteTrackingId) {
exists = true
return@nti
}
}
if (!exists) deleteTrackings.add(existing)
}
var rowsAffected = deleteTrackings.sumBy { OrderSqlUtils.deleteOrderShipmentTrackingById(it) }
// Save new shipment trackings to the database
rowsAffected += result.trackings.sumBy { OrderSqlUtils.insertOrIgnoreOrderShipmentTracking(it) }
OnOrderChanged()
}
}
}
suspend fun addOrderShipmentTracking(payload: AddOrderShipmentTrackingPayload): OnOrderChanged {
return coroutineEngine.withDefaultContext(T.API, this, "addOrderShipmentTracking") {
val result = with(payload) {
wcOrderRestClient.addOrderShipmentTrackingForOrder(
site, orderId, tracking, isCustomProvider
)
}
return@withDefaultContext if (result.isError) {
OnOrderChanged(orderError = result.error)
} else {
result.tracking?.let { OrderSqlUtils.insertOrIgnoreOrderShipmentTracking(it) }
OnOrderChanged()
}
}
}
suspend fun deleteOrderShipmentTracking(payload: DeleteOrderShipmentTrackingPayload): OnOrderChanged {
return coroutineEngine.withDefaultContext(T.API, this, "deleteOrderShipmentTracking") {
val result = with(payload) {
wcOrderRestClient.deleteShipmentTrackingForOrder(site, orderId, tracking)
}
return@withDefaultContext if (result.isError) {
OnOrderChanged(orderError = result.error)
} else {
// Remove the record from the database and send response
result.tracking?.let { OrderSqlUtils.deleteOrderShipmentTrackingById(it) }
OnOrderChanged()
}
}
}
suspend fun fetchOrderShipmentProviders(
payload: FetchOrderShipmentProvidersPayload
): OnOrderShipmentProvidersChanged {
return coroutineEngine.withDefaultContext(T.API, this, "fetchOrderShipmentProviders") {
val result = with(payload) {
wcOrderRestClient.fetchOrderShipmentProviders(site, order)
}
return@withDefaultContext if (result.isError) {
OnOrderShipmentProvidersChanged(0).also { it.error = result.error }
} else {
// Delete all providers from the db
OrderSqlUtils.deleteOrderShipmentProvidersForSite(payload.site)
// Add new list to the database
val rowsAffected = result.providers.sumBy { OrderSqlUtils.insertOrIgnoreOrderShipmentProvider(it) }
OnOrderShipmentProvidersChanged(rowsAffected)
}
}
}
@Suppress("SpreadOperator")
private fun handleFetchOrdersCompleted(payload: FetchOrdersResponsePayload) {
coroutineEngine.launch(API, this, "handleFetchOrdersCompleted") {
val onOrderChanged: OnOrderChanged = if (payload.isError) {
OnOrderChanged(orderError = payload.error)
} else {
// Clear existing uploading orders if this is a fresh fetch (loadMore = false in the original request)
// This is the simplest way of keeping our local orders in sync with remote orders
// (in case of deletions, or if the user manual changed some order IDs).
if (!payload.loadedMore) {
ordersDao.deleteOrdersForSite(payload.site.localId())
orderNotesDao.deleteOrderNotesForSite(payload.site.remoteId())
OrderSqlUtils.deleteOrderShipmentTrackingsForSite(payload.site)
}
insertOrder(*payload.ordersWithMeta.toTypedArray())
OnOrderChanged(payload.statusFilter, canLoadMore = payload.canLoadMore)
}.copy(causeOfChange = FETCH_ORDERS)
emitChange(onOrderChanged)
}
}
@Suppress("ForbiddenComment")
private fun handleFetchOrderListCompleted(payload: FetchOrderListResponsePayload) {
// TODO: Ideally we would have a separate process that prunes the following
// tables of defunct records:
// - WCOrderModel
// - WCOrderNoteModel
// - WCOrderShipmentTrackingModel
if (!payload.isError) {
// Save order summaries to the db
OrderSqlUtils.insertOrUpdateOrderSummaries(payload.orderSummaries)
// Fetch outdated or missing orders
fetchOutdatedOrMissingOrders(payload.listDescriptor.site, payload.orderSummaries)
}
val duration = Calendar.getInstance().timeInMillis - payload.requestStartTime.timeInMillis
emitChange(OnOrderSummariesFetched(listDescriptor = payload.listDescriptor, duration = duration))
mDispatcher.dispatch(ListActionBuilder.newFetchedListItemsAction(FetchedListItemsPayload(
listDescriptor = payload.listDescriptor,
remoteItemIds = payload.orderSummaries.map { it.orderId },
loadedMore = payload.loadedMore,
canLoadMore = payload.canLoadMore,
error = payload.error?.let { fetchError ->
// TODO: Use the actual error type
ListError(type = ListErrorType.GENERIC_ERROR, message = fetchError.message)
}
)))
}
private fun fetchOutdatedOrMissingOrders(site: SiteModel, fetchedSummaries: List<WCOrderSummaryModel>) {
val fetchedSummariesIds = fetchedSummaries.map { it.orderId }
val localOrdersForFetchedSummaries = ordersDao.getOrdersForSiteByRemoteIds(site.localId(), fetchedSummariesIds)
val idsToFetch = outdatedOrdersIds(fetchedSummaries, localOrdersForFetchedSummaries)
.plus(missingOrdersIds(fetchedSummariesIds, localOrdersForFetchedSummaries))
wcOrderFetcher.fetchOrders(site = site, orderIds = idsToFetch)
}
private fun outdatedOrdersIds(
fetchedSummaries: List<WCOrderSummaryModel>,
localOrdersForSiteByRemoteIds: List<OrderEntity>
): List<Long> {
val summaryModifiedDates = fetchedSummaries.associate { it.orderId to it.dateModified }
return localOrdersForSiteByRemoteIds.filter { order ->
order.dateModified != summaryModifiedDates[order.orderId]
}.map(OrderEntity::orderId)
}
private fun missingOrdersIds(
fetchedSummariesIds: List<Long>,
localOrdersForSiteByRemoteIds: List<OrderEntity>
): List<Long> {
return fetchedSummariesIds.minus(
localOrdersForSiteByRemoteIds.map(OrderEntity::orderId)
)
}
@Suppress("SpreadOperator")
private fun handleFetchOrderByIdsCompleted(payload: FetchOrdersByIdsResponsePayload) {
coroutineEngine.launch(API, this, "handleFetchOrderByIdsCompleted") {
val onOrdersFetchedByIds = if (payload.isError) {
OnOrdersFetchedByIds(payload.site, payload.orderIds).apply { error = payload.error }
} else {
OnOrdersFetchedByIds(
payload.site,
payload.fetchedOrders.map { it.first }.map { it.orderId })
}
if (!payload.isError) {
// Save the list of orders to the database
insertOrder(*payload.fetchedOrders.toTypedArray())
// Notify listeners that the list of orders has changed (only call this if there is no error)
val listTypeIdentifier = WCOrderListDescriptor.calculateTypeIdentifier(localSiteId = payload.site.id)
mDispatcher.dispatch(
ListActionBuilder.newListDataInvalidatedAction(
listTypeIdentifier
)
)
}
emitChange(onOrdersFetchedByIds)
}
}
private fun handleSearchOrdersCompleted(payload: SearchOrdersResponsePayload) {
val onOrdersSearched = if (payload.isError) {
OnOrdersSearched(payload.searchQuery)
} else {
OnOrdersSearched(payload.searchQuery, payload.canLoadMore, payload.offset, payload.orders)
}
emitChange(onOrdersSearched)
}
/**
* This is a response to a request to retrieve only the count of orders matching a filter. These
* results are not stored in the database.
*/
private fun handleFetchOrdersCountCompleted(payload: FetchOrdersCountResponsePayload) {
val onOrderChanged = if (payload.isError) {
OnOrderChanged(orderError = payload.error)
} else {
with(payload) {
OnOrderChanged(statusFilter = statusFilter)
}
}.copy(causeOfChange = WCOrderAction.FETCH_ORDERS_COUNT)
emitChange(onOrderChanged)
}
private suspend fun revertOrderStatus(payload: RemoteOrderPayload.Updating): OnOrderChanged {
updateOrderStatusLocally(
payload.order.orderId,
payload.order.localSiteId,
payload.order.status
)
return OnOrderChanged(orderError = payload.error)
}
private fun handleFetchOrderStatusOptionsCompleted(payload: FetchOrderStatusOptionsResponsePayload) {
val onOrderStatusLabelsChanged: OnOrderStatusOptionsChanged
if (payload.isError) {
onOrderStatusLabelsChanged = OnOrderStatusOptionsChanged(0).also { it.error = payload.error }
} else {
onOrderStatusLabelsChanged = onOrderStatusOptionsChanged(payload)
}
emitChange(onOrderStatusLabelsChanged)
}
private fun onOrderStatusOptionsChanged(
payload: FetchOrderStatusOptionsResponsePayload
): OnOrderStatusOptionsChanged {
val existingOptions = OrderSqlUtils.getOrderStatusOptionsForSite(payload.site)
var rowsAffected = addOrUpdateOptions(payload, existingOptions).sumBy {
OrderSqlUtils.insertOrUpdateOrderStatusOption(it)
}
rowsAffected += deleteOptions(payload, existingOptions).sumBy {
OrderSqlUtils.deleteOrderStatusOption(it)
}
return OnOrderStatusOptionsChanged(rowsAffected)
}
@Suppress("NestedBlockDepth")
private fun addOrUpdateOptions(
payload: FetchOrderStatusOptionsResponsePayload,
existingOptions: List<WCOrderStatusModel>
): List<WCOrderStatusModel> {
val addOrUpdateOptions = mutableListOf<WCOrderStatusModel>()
payload.labels.iterator().forEach { newOption ->
var exists = false
existingOptions.iterator().forEach eoi@{ existingOption ->
if (newOption.statusKey == existingOption.statusKey) {
exists = true
if (newOption.label != existingOption.label ||
newOption.statusCount != existingOption.statusCount) {
addOrUpdateOptions.add(newOption)
}
return@eoi
}
}
if (!exists) addOrUpdateOptions.add(newOption)
}
return addOrUpdateOptions
}
private fun deleteOptions(
payload: FetchOrderStatusOptionsResponsePayload,
existingOptions: List<WCOrderStatusModel>
): List<WCOrderStatusModel> {
val deleteOptions = mutableListOf<WCOrderStatusModel>()
existingOptions.iterator().forEach { existingOption ->
var exists = false
payload.labels.iterator().forEach noi@{ newOption ->
if (newOption.statusKey == existingOption.statusKey) {
exists = true
return@noi
}
}
if (!exists) deleteOptions.add(existingOption)
}
return deleteOptions
}
}
| plugins/woocommerce/src/main/kotlin/org/wordpress/android/fluxc/store/WCOrderStore.kt | 2303367433 |