repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
nrizzio/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/components/settings/app/notifications/profiles/SelectRecipientsFragment.kt | 1 | 5825 | package org.thoughtcrime.securesms.components.settings.app.notifications.profiles
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.widget.Toolbar
import androidx.fragment.app.viewModels
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import io.reactivex.rxjava3.kotlin.subscribeBy
import org.thoughtcrime.securesms.ContactSelectionListFragment
import org.thoughtcrime.securesms.LoggingFragment
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.components.ContactFilterView
import org.thoughtcrime.securesms.contacts.ContactsCursorLoader
import org.thoughtcrime.securesms.groups.SelectionLimits
import org.thoughtcrime.securesms.keyvalue.SignalStore
import org.thoughtcrime.securesms.recipients.RecipientId
import org.thoughtcrime.securesms.util.LifecycleDisposable
import org.thoughtcrime.securesms.util.Util
import org.thoughtcrime.securesms.util.ViewUtil
import org.thoughtcrime.securesms.util.views.CircularProgressMaterialButton
import java.util.Optional
import java.util.function.Consumer
/**
* Contact Selection for adding recipients to a Notification Profile.
*/
class SelectRecipientsFragment : LoggingFragment(), ContactSelectionListFragment.OnContactSelectedListener {
private val viewModel: SelectRecipientsViewModel by viewModels(factoryProducer = this::createFactory)
private val lifecycleDisposable = LifecycleDisposable()
private var addToProfile: CircularProgressMaterialButton? = null
private fun createFactory(): ViewModelProvider.Factory {
val args = SelectRecipientsFragmentArgs.fromBundle(requireArguments())
return SelectRecipientsViewModel.Factory(args.profileId, args.currentSelection?.toSet() ?: emptySet())
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val currentSelection: Array<RecipientId>? = SelectRecipientsFragmentArgs.fromBundle(requireArguments()).currentSelection
val selectionList = ArrayList<RecipientId>()
if (currentSelection != null) {
selectionList.addAll(currentSelection)
}
childFragmentManager.addFragmentOnAttachListener { _, fragment ->
fragment.arguments = Bundle().apply {
putInt(ContactSelectionListFragment.DISPLAY_MODE, getDefaultDisplayMode())
putBoolean(ContactSelectionListFragment.REFRESHABLE, false)
putBoolean(ContactSelectionListFragment.RECENTS, true)
putParcelable(ContactSelectionListFragment.SELECTION_LIMITS, SelectionLimits.NO_LIMITS)
putParcelableArrayList(ContactSelectionListFragment.CURRENT_SELECTION, selectionList)
putBoolean(ContactSelectionListFragment.HIDE_COUNT, true)
putBoolean(ContactSelectionListFragment.DISPLAY_CHIPS, true)
putBoolean(ContactSelectionListFragment.CAN_SELECT_SELF, false)
putBoolean(ContactSelectionListFragment.RV_CLIP, false)
putInt(ContactSelectionListFragment.RV_PADDING_BOTTOM, ViewUtil.dpToPx(60))
}
}
return inflater.inflate(R.layout.fragment_select_recipients_fragment, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val toolbar: Toolbar = view.findViewById(R.id.toolbar)
toolbar.setTitle(R.string.AddAllowedMembers__allowed_notifications)
toolbar.setNavigationOnClickListener { findNavController().navigateUp() }
lifecycleDisposable.bindTo(viewLifecycleOwner.lifecycle)
val contactFilterView: ContactFilterView = view.findViewById(R.id.contact_filter_edit_text)
val selectionFragment: ContactSelectionListFragment = childFragmentManager.findFragmentById(R.id.contact_selection_list_fragment) as ContactSelectionListFragment
contactFilterView.setOnFilterChangedListener {
if (it.isNullOrEmpty()) {
selectionFragment.resetQueryFilter()
} else {
selectionFragment.setQueryFilter(it)
}
}
addToProfile = view.findViewById(R.id.select_recipients_add)
addToProfile?.setOnClickListener {
lifecycleDisposable += viewModel.updateAllowedMembers()
.doOnSubscribe { addToProfile?.setSpinning() }
.doOnTerminate { addToProfile?.cancelSpinning() }
.subscribeBy(onSuccess = { findNavController().navigateUp() })
}
updateAddToProfile()
}
override fun onDestroyView() {
super.onDestroyView()
addToProfile = null
}
private fun getDefaultDisplayMode(): Int {
var mode = ContactsCursorLoader.DisplayMode.FLAG_PUSH or
ContactsCursorLoader.DisplayMode.FLAG_ACTIVE_GROUPS or
ContactsCursorLoader.DisplayMode.FLAG_HIDE_NEW or
ContactsCursorLoader.DisplayMode.FLAG_HIDE_RECENT_HEADER or
ContactsCursorLoader.DisplayMode.FLAG_GROUPS_AFTER_CONTACTS
if (Util.isDefaultSmsProvider(requireContext()) && SignalStore.misc().smsExportPhase.allowSmsFeatures()) {
mode = mode or ContactsCursorLoader.DisplayMode.FLAG_SMS
}
return mode or ContactsCursorLoader.DisplayMode.FLAG_HIDE_GROUPS_V1
}
override fun onBeforeContactSelected(recipientId: Optional<RecipientId>, number: String?, callback: Consumer<Boolean>) {
if (recipientId.isPresent) {
viewModel.select(recipientId.get())
callback.accept(true)
updateAddToProfile()
} else {
callback.accept(false)
}
}
override fun onContactDeselected(recipientId: Optional<RecipientId>, number: String?) {
if (recipientId.isPresent) {
viewModel.deselect(recipientId.get())
updateAddToProfile()
}
}
override fun onSelectionChanged() = Unit
private fun updateAddToProfile() {
val enabled = viewModel.recipients.isNotEmpty()
addToProfile?.isEnabled = enabled
addToProfile?.alpha = if (enabled) 1f else 0.5f
}
}
| gpl-3.0 | 5909ccf42bc7c9fc84a041ae2cc5199e | 40.607143 | 165 | 0.781459 | 4.953231 | false | false | false | false |
GunoH/intellij-community | plugins/evaluation-plugin/core/src/com/intellij/cce/metric/FirstTokenComparator.kt | 8 | 428 | package com.intellij.cce.metric
import com.intellij.cce.core.Suggestion
class FirstTokenComparator : SuggestionsComparator {
override fun accept(suggestion: Suggestion, expected: String): Boolean {
var firstToken = ""
for (ch in suggestion.text.trim()) {
if (ch.isLetter() || ch == '_' || ch.isDigit() && firstToken.isNotBlank()) firstToken += ch
else break
}
return firstToken == expected
}
}
| apache-2.0 | 1bdede1679c62778d17b9c72266a888e | 29.571429 | 97 | 0.679907 | 4.28 | false | false | false | false |
vovagrechka/fucking-everything | phizdets/phizdetsc/src/PhizdetsSourceGenerationVisitor.kt | 1 | 3275 | /*
* Copyright 2010-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.js.sourceMap
import org.jetbrains.kotlin.js.backend.JsToStringGenerationVisitor
import org.jetbrains.kotlin.js.backend.PhizdetsToStringGenerationVisitor
import org.jetbrains.kotlin.js.backend.ast.*
import org.jetbrains.kotlin.js.util.TextOutput
import com.intellij.util.SmartList
import vgrechka.*
class PhizdetsSourceGenerationVisitor(out: TextOutput, taggedGenOut: TextOutput, private val sourceMapBuilder: SourceMapBuilder?) : PhizdetsToStringGenerationVisitor(out, taggedGenOut), TextOutput.OutListener {
private val pendingSources = SmartList<Any>()
init {
out.setOutListener(this)
}
override fun visitProgramFragment(x: JsProgramFragment) {
x.acceptChildren(this)
}
override fun newLined() {
sourceMapBuilder?.newLine()
}
override fun indentedAfterNewLine() {
if (pendingSources.isEmpty()) return
assert(sourceMapBuilder != null)
for (source in pendingSources) {
sourceMapBuilder!!.processSourceInfo(source)
}
pendingSources.clear()
}
override fun <T: JsNode?> accept(node: T) {
if (node !is JsNameRef && node !is JsLiteral.JsThisRef) {
mapSource(node)
}
super.accept(node)
}
// @debug-source-map
private fun mapSource(node: JsNode?) {
if (sourceMapBuilder != null) {
val sourceInfo = node!!.source
// run { // @debug
// if (node is JsConditional) {
// "break on me"
// }
// }
// @debug
// val shit = node.debug_attachedShit("replacedNode")
// if (shit != null) {
// "break on me"
// }
// @debug
// if ("dt-pizda" == sourceInfo.debug_tag) {
// "break on me".toString()
// }
// @debug
// if (node.toString().contains("QUERY_STRING")) {
// "break on me".toString()
// }
if (sourceInfo != null) {
if (p.isJustNewlined) {
pendingSources.add(sourceInfo)
} else {
sourceMapBuilder.processSourceInfo(sourceInfo)
}
}
}
}
override fun beforeNodePrinted(node: JsNode) {
mapSource(node)
}
override fun visitProgram(program: JsProgram) {
// @phi-1
p.print("<?php \$GLOBALS['myFuckingDir'] = __DIR__; require_once('phi-engine.php'); @define('PHI_KILL_LONG_LOOPS', true); ")
program.acceptChildren(this)
sourceMapBuilder?.addLink()
}
}
| apache-2.0 | 59b3fd88ac4e9e9fd6374447c701957f | 28.241071 | 210 | 0.601527 | 4.231266 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/AssignToPropertyFix.kt | 3 | 3371 | // 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.quickfix
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.util.getResolutionScope
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.containingClass
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.resolve.scopes.utils.getImplicitReceiversHierarchy
import org.jetbrains.kotlin.types.KotlinType
class AssignToPropertyFix(element: KtNameReferenceExpression) : KotlinQuickFixAction<KtNameReferenceExpression>(element) {
override fun getText() = KotlinBundle.message("fix.assign.to.property")
override fun getFamilyName() = text
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val element = element ?: return
val psiFactory = KtPsiFactory(element)
if (element.getResolutionScope().getImplicitReceiversHierarchy().size == 1) {
element.replace(psiFactory.createExpressionByPattern("this.$0", element))
} else {
element.containingClass()?.name?.let {
element.replace(psiFactory.createExpressionByPattern("this@$0.$1", it, element))
}
}
}
companion object : KotlinSingleIntentionActionFactory() {
private fun KtCallableDeclaration.hasNameAndTypeOf(name: Name, type: KotlinType) =
nameAsName == name && (resolveToDescriptorIfAny() as? CallableDescriptor)?.returnType == type
override fun createAction(diagnostic: Diagnostic): KotlinQuickFixAction<KtNameReferenceExpression>? {
val expression = diagnostic.psiElement as? KtNameReferenceExpression ?: return null
val containingClass = expression.containingClass() ?: return null
val right = (expression.parent as? KtBinaryExpression)?.right ?: return null
val type = expression.analyze().getType(right) ?: return null
val name = expression.getReferencedNameAsName()
val inSecondaryConstructor = expression.getStrictParentOfType<KtSecondaryConstructor>() != null
val hasAssignableProperty = containingClass.getProperties().any {
(inSecondaryConstructor || it.isVar) && it.hasNameAndTypeOf(name, type)
}
val hasAssignablePropertyInPrimaryConstructor = containingClass.primaryConstructor?.valueParameters?.any {
it.valOrVarKeyword?.node?.elementType == KtTokens.VAR_KEYWORD &&
it.hasNameAndTypeOf(name, type)
} ?: false
if (!hasAssignableProperty && !hasAssignablePropertyInPrimaryConstructor) return null
return AssignToPropertyFix(expression)
}
}
}
| apache-2.0 | fc9f1781fe1370f87a6a13ee7a0aa734 | 50.075758 | 158 | 0.73539 | 5.267188 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/quickfix/CommonIntentionActionsTest.kt | 1 | 34397 | // 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.quickfix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.lang.jvm.*
import com.intellij.lang.jvm.actions.*
import com.intellij.lang.jvm.types.JvmSubstitutor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Pair.pair
import com.intellij.psi.*
import com.intellij.testFramework.fixtures.CodeInsightTestFixture
import com.intellij.testFramework.fixtures.LightPlatformCodeInsightFixtureTestCase
import junit.framework.TestCase
import org.jetbrains.kotlin.asJava.toLightElements
import org.jetbrains.kotlin.idea.search.allScope
import org.jetbrains.kotlin.idea.test.KotlinWithJdkAndRuntimeLightProjectDescriptor
import org.jetbrains.kotlin.psi.KtModifierListOwner
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.uast.toUElement
import org.junit.Assert
import org.junit.internal.runners.JUnit38ClassRunner
import org.junit.runner.RunWith
@RunWith(JUnit38ClassRunner::class)
class CommonIntentionActionsTest : LightPlatformCodeInsightFixtureTestCase() {
private class SimpleMethodRequest(
project: Project,
private val methodName: String,
private val modifiers: Collection<JvmModifier> = emptyList(),
private val returnType: ExpectedTypes = emptyList(),
private val annotations: Collection<AnnotationRequest> = emptyList(),
@Suppress("MissingRecentApi") parameters: List<ExpectedParameter> = emptyList(),
private val targetSubstitutor: JvmSubstitutor = PsiJvmSubstitutor(project, PsiSubstitutor.EMPTY)
) : CreateMethodRequest {
private val expectedParameters = parameters
override fun getTargetSubstitutor(): JvmSubstitutor = targetSubstitutor
override fun getModifiers() = modifiers
override fun getMethodName() = methodName
override fun getAnnotations() = annotations
@Suppress("MissingRecentApi")
override fun getExpectedParameters(): List<ExpectedParameter> = expectedParameters
override fun getReturnType() = returnType
override fun isValid(): Boolean = true
}
override fun getProjectDescriptor() = KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE_FULL_JDK
fun testMakeNotFinal() {
myFixture.configureByText(
"foo.kt", """
class Foo {
fun bar<caret>(){}
}
"""
)
myFixture.launchAction(
createModifierActions(
myFixture.atCaret(), TestModifierRequest(JvmModifier.FINAL, false)
).findWithText("Make 'bar' 'open'")
)
myFixture.checkResult(
"""
class Foo {
open fun bar(){}
}
"""
)
}
fun testMakePrivate() {
myFixture.configureByText(
"foo.kt", """
class Foo<caret> {
fun bar(){}
}
"""
)
myFixture.launchAction(
createModifierActions(
myFixture.atCaret(), TestModifierRequest(JvmModifier.PRIVATE, true)
).findWithText("Make 'Foo' 'private'")
)
myFixture.checkResult(
"""
private class Foo {
fun bar(){}
}
"""
)
}
fun testMakeNotPrivate() {
myFixture.configureByText(
"foo.kt", """
private class Foo<caret> {
fun bar(){}
}
""".trim()
)
myFixture.launchAction(
createModifierActions(
myFixture.atCaret(), TestModifierRequest(JvmModifier.PRIVATE, false)
).findWithText("Remove 'private' modifier")
)
myFixture.checkResult(
"""
class Foo {
fun bar(){}
}
""".trim(), true
)
}
fun testMakePrivatePublic() {
myFixture.configureByText(
"foo.kt", """class Foo {
| private fun <caret>bar(){}
|}""".trim().trimMargin()
)
myFixture.launchAction(
createModifierActions(
myFixture.atCaret(), TestModifierRequest(JvmModifier.PUBLIC, true)
).findWithText("Remove 'private' modifier")
)
myFixture.checkResult(
"""class Foo {
| fun <caret>bar(){}
|}""".trim().trimMargin(), true
)
}
fun testMakeProtectedPublic() {
myFixture.configureByText(
"foo.kt", """open class Foo {
| protected fun <caret>bar(){}
|}""".trim().trimMargin()
)
myFixture.launchAction(
createModifierActions(
myFixture.atCaret(), TestModifierRequest(JvmModifier.PUBLIC, true)
).findWithText("Remove 'protected' modifier")
)
myFixture.checkResult(
"""open class Foo {
| fun <caret>bar(){}
|}""".trim().trimMargin(), true
)
}
fun testMakeInternalPublic() {
myFixture.configureByText(
"foo.kt", """class Foo {
| internal fun <caret>bar(){}
|}""".trim().trimMargin()
)
myFixture.launchAction(
createModifierActions(
myFixture.atCaret(), TestModifierRequest(JvmModifier.PUBLIC, true)
).findWithText("Remove 'internal' modifier")
)
myFixture.checkResult(
"""class Foo {
| fun <caret>bar(){}
|}""".trim().trimMargin(), true
)
}
fun testAddAnnotation() {
myFixture.configureByText(
"foo.kt", """class Foo {
| fun <caret>bar(){}
|}""".trim().trimMargin()
)
myFixture.launchAction(
createAddAnnotationActions(
myFixture.findElementByText("bar", KtModifierListOwner::class.java).toLightElements().single() as PsiMethod,
annotationRequest("kotlin.jvm.JvmName", stringAttribute("name", "foo"))
).single()
)
myFixture.checkResult(
"""class Foo {
| @JvmName(name = "foo")
| fun <caret>bar(){}
|}""".trim().trimMargin(), true
)
}
fun testAddJavaAnnotationValue() {
myFixture.addFileToProject(
"pkg/myannotation/JavaAnnotation.java", """
package pkg.myannotation
public @interface JavaAnnotation {
String value();
int param() default 0;
}
""".trimIndent()
)
myFixture.configureByText(
"foo.kt", """class Foo {
| fun bar(){}
| fun baz(){}
|}""".trim().trimMargin()
)
myFixture.launchAction(
createAddAnnotationActions(
myFixture.findElementByText("bar", KtModifierListOwner::class.java).toLightElements().single() as PsiMethod,
annotationRequest("pkg.myannotation.JavaAnnotation", stringAttribute("value", "foo"), intAttribute("param", 2))
).single()
)
myFixture.launchAction(
createAddAnnotationActions(
myFixture.findElementByText("baz", KtModifierListOwner::class.java).toLightElements().single() as PsiMethod,
annotationRequest("pkg.myannotation.JavaAnnotation", intAttribute("param", 2), stringAttribute("value", "foo"))
).single()
)
myFixture.checkResult(
"""import pkg.myannotation.JavaAnnotation
|
|class Foo {
| @JavaAnnotation("foo", param = 2)
| fun bar(){}
| @JavaAnnotation(param = 2, value = "foo")
| fun baz(){}
|}""".trim().trimMargin(), true
)
}
fun testAddJavaAnnotationOnFieldWithoutTarget() {
myFixture.addFileToProject(
"pkg/myannotation/JavaAnnotation.java", """
package pkg.myannotation
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
//no @Target
@Retention(RetentionPolicy.RUNTIME)
public @interface JavaAnnotation {
String value();
int param() default 0;
}
""".trimIndent()
)
myFixture.configureByText(
"foo.kt", """class Foo {
| val bar: String = null
|}""".trim().trimMargin()
)
myFixture.launchAction(
createAddAnnotationActions(
myFixture.findElementByText("bar", KtModifierListOwner::class.java).toLightElements().single { it is PsiField } as PsiField,
annotationRequest("pkg.myannotation.JavaAnnotation")
).single()
)
myFixture.checkResult(
"""
import pkg.myannotation.JavaAnnotation
class Foo {
@field:JavaAnnotation
val bar: String = null
}
""".trimIndent(), true
)
TestCase.assertEquals(
"KtUltraLightMethodForSourceDeclaration -> org.jetbrains.annotations.NotNull," +
" KtUltraLightFieldForSourceDeclaration -> pkg.myannotation.JavaAnnotation, org.jetbrains.annotations.NotNull",
annotationsString(myFixture.findElementByText("bar", KtModifierListOwner::class.java))
)
}
fun testAddJavaAnnotationOnField() {
myFixture.addFileToProject(
"pkg/myannotation/JavaAnnotation.java", """
package pkg.myannotation
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface JavaAnnotation {
String value();
int param() default 0;
}
""".trimIndent()
)
myFixture.configureByText(
"foo.kt", """class Foo {
| val bar: String = null
|}""".trim().trimMargin()
)
myFixture.launchAction(
createAddAnnotationActions(
myFixture.findElementByText("bar", KtModifierListOwner::class.java).toLightElements().single { it is PsiField } as PsiField,
annotationRequest("pkg.myannotation.JavaAnnotation")
).single()
)
myFixture.checkResult(
"""
import pkg.myannotation.JavaAnnotation
class Foo {
@JavaAnnotation
val bar: String = null
}
""".trimIndent(), true
)
TestCase.assertEquals(
"KtUltraLightMethodForSourceDeclaration -> org.jetbrains.annotations.NotNull," +
" KtUltraLightFieldForSourceDeclaration -> pkg.myannotation.JavaAnnotation, org.jetbrains.annotations.NotNull",
annotationsString(myFixture.findElementByText("bar", KtModifierListOwner::class.java))
)
}
fun testChangeMethodType() {
myFixture.configureByText(
"foo.kt", """class Foo {
| fun <caret>bar(){}
|}""".trim().trimMargin()
)
val method = myFixture.findElementByText("bar", KtNamedFunction::class.java).toLightElements().single() as JvmMethod
val typeRequest = typeRequest("String", emptyList())
myFixture.launchAction(createChangeTypeActions(method, typeRequest).single())
myFixture.checkResult(
"""class Foo {
| fun <caret>bar(): String {}
|}""".trim().trimMargin(), true
)
}
fun testChangeMethodTypeToTypeWithAnnotations() {
myFixture.configureByText(
"foo.kt", """class Foo {
| fun <caret>bar(){}
|}""".trim().trimMargin()
)
myFixture.addFileToProject(
"pkg/myannotation/annotations.kt", """
package pkg.myannotation
@Target(AnnotationTarget.TYPE)
annotation class MyAnno
""".trimIndent()
)
val method = myFixture.findElementByText("bar", KtNamedFunction::class.java).toLightElements().single() as JvmMethod
val typeRequest = typeRequest("String", listOf(annotationRequest("pkg.myannotation.MyAnno")))
myFixture.launchAction(createChangeTypeActions(method, typeRequest).single())
myFixture.checkResult(
"""
|import pkg.myannotation.MyAnno
|
|class Foo {
| fun <caret>bar(): @MyAnno String {}
|}""".trim().trimMargin(), true
)
}
fun testChangeMethodTypeRemoveAnnotations() {
myFixture.addFileToProject(
"pkg/myannotation/annotations.kt", """
package pkg.myannotation
@Target(AnnotationTarget.TYPE)
annotation class MyAnno
""".trimIndent()
)
myFixture.configureByText(
"foo.kt", """
|import pkg.myannotation.MyAnno
|
|class Foo {
| fun <caret>bar(): @MyAnno String {}
|}""".trim().trimMargin()
)
val method = myFixture.findElementByText("bar", KtNamedFunction::class.java).toLightElements().single() as JvmMethod
val typeRequest = typeRequest(null, emptyList())
myFixture.launchAction(createChangeTypeActions(method, typeRequest).single())
myFixture.checkResult(
"""
|import pkg.myannotation.MyAnno
|
|class Foo {
| fun <caret>bar(): String {}
|}""".trim().trimMargin(), true
)
}
fun testChangeMethodTypeChangeAnnotationsOnly() {
myFixture.addFileToProject(
"pkg/myannotation/annotations.kt", """
package pkg.myannotation
@Target(AnnotationTarget.TYPE)
annotation class MyAnno
@Target(AnnotationTarget.TYPE)
annotation class MyOtherAnno
""".trimIndent()
)
myFixture.configureByText(
"foo.kt", """
|import pkg.myannotation.MyAnno
|
|class Foo {
| fun <caret>bar(): @MyAnno String {}
|}""".trim().trimMargin()
)
val method = myFixture.findElementByText("bar", KtNamedFunction::class.java).toLightElements().single() as JvmMethod
val typeRequest = typeRequest(null, listOf(annotationRequest("pkg.myannotation.MyOtherAnno")))
myFixture.launchAction(createChangeTypeActions(method, typeRequest).single())
myFixture.checkResult(
"""
|import pkg.myannotation.MyAnno
|import pkg.myannotation.MyOtherAnno
|
|class Foo {
| fun <caret>bar(): @MyOtherAnno String {}
|}""".trim().trimMargin(), true
)
}
fun testChangeMethodTypeAddJavaAnnotation() {
myFixture.addFileToProject(
"pkg/myannotation/JavaAnnotation.java", """
package pkg.myannotation
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
@Target(ElementType.TYPE)
public @interface JavaAnnotation {}
""".trimIndent()
)
myFixture.addFileToProject(
"pkg/myannotation/annotations.kt", """
package pkg.myannotation
@Target(AnnotationTarget.TYPE)
annotation class MyOtherAnno
""".trimIndent()
)
myFixture.configureByText(
"foo.kt", """
|import pkg.myannotation.MyOtherAnno
|
|class Foo {
| fun <caret>bar(): @MyOtherAnno String {}
|}""".trim().trimMargin()
)
val method = myFixture.findElementByText("bar", KtNamedFunction::class.java).toLightElements().single() as JvmMethod
val typeRequest = typeRequest(null, listOf(annotationRequest("pkg.myannotation.JavaAnnotation"), annotationRequest("pkg.myannotation.MyOtherAnno")))
myFixture.launchAction(createChangeTypeActions(method, typeRequest).single())
myFixture.checkResult(
"""
|import pkg.myannotation.JavaAnnotation
|import pkg.myannotation.MyOtherAnno
|
|class Foo {
| fun <caret>bar(): @JavaAnnotation @MyOtherAnno String {}
|}""".trim().trimMargin(), true
)
}
fun testChangeMethodTypeWithComments() {
myFixture.addFileToProject(
"pkg/myannotation/annotations.kt", """
package pkg.myannotation
@Target(AnnotationTarget.TYPE)
annotation class MyAnno
@Target(AnnotationTarget.TYPE)
annotation class MyOtherAnno
""".trimIndent()
)
myFixture.configureByText(
"foo.kt", """
|import pkg.myannotation.MyOtherAnno
|
|class Foo {
| fun <caret>bar(): @MyOtherAnno /*1*/ String {}
|}""".trim().trimMargin()
)
val method = myFixture.findElementByText("bar", KtNamedFunction::class.java).toLightElements().single() as JvmMethod
val typeRequest = typeRequest(null, listOf(annotationRequest("pkg.myannotation.MyAnno")))
myFixture.launchAction(createChangeTypeActions(method, typeRequest).single())
myFixture.checkResult(
"""
|import pkg.myannotation.MyAnno
|import pkg.myannotation.MyOtherAnno
|
|class Foo {
| fun <caret>bar(): /*1*/@MyAnno String {}
|}""".trim().trimMargin(), true
)
}
fun testChangeMethodTypeToJavaType() {
myFixture.addFileToProject(
"pkg/mytype/MyType.java", """
package pkg.mytype;
public class MyType {}
""".trimIndent()
)
myFixture.configureByText(
"foo.kt", """
|class Foo {
| fun <caret>bar() {}
|}""".trim().trimMargin()
)
val method = myFixture.findElementByText("bar", KtNamedFunction::class.java).toLightElements().single() as JvmMethod
val typeRequest = typeRequest("pkg.mytype.MyType", emptyList())
myFixture.launchAction(createChangeTypeActions(method, typeRequest).single())
myFixture.checkResult(
"""
|import pkg.mytype.MyType
|
|class Foo {
| fun <caret>bar(): MyType {}
|}""".trim().trimMargin(), true
)
}
private fun annotationsString(findElementByText: KtModifierListOwner) = findElementByText.toLightElements()
.joinToString { elem ->
"${elem.javaClass.simpleName} -> ${(elem as PsiModifierListOwner).annotations.mapNotNull { it.qualifiedName }.joinToString()}"
}
fun testDontMakePublicPublic() {
myFixture.configureByText(
"foo.kt", """class Foo {
| fun <caret>bar(){}
|}""".trim().trimMargin()
)
assertEmpty(createModifierActions(myFixture.atCaret(), TestModifierRequest(JvmModifier.PUBLIC, true)))
}
fun testDontMakeFunInObjectsOpen() {
myFixture.configureByText(
"foo.kt", """
object Foo {
fun bar<caret>(){}
}
""".trim()
)
assertEmpty(createModifierActions(myFixture.atCaret(), TestModifierRequest(JvmModifier.FINAL, false)))
}
fun testAddVoidVoidMethod() {
myFixture.configureByText(
"foo.kt", """
|class Foo<caret> {
| fun bar() {}
|}
""".trim().trimMargin()
)
myFixture.launchAction(
createMethodActions(
myFixture.atCaret(),
methodRequest(project, "baz", listOf(JvmModifier.PRIVATE), PsiType.VOID)
).findWithText("Add method 'baz' to 'Foo'")
)
myFixture.checkResult(
"""
|class Foo {
| fun bar() {}
| private fun baz() {
|
| }
|}
""".trim().trimMargin(), true
)
}
fun testAddIntIntMethod() {
myFixture.configureByText(
"foo.kt", """
|class Foo<caret> {
| fun bar() {}
|}
""".trim().trimMargin()
)
myFixture.launchAction(
createMethodActions(
myFixture.atCaret(),
SimpleMethodRequest(
project,
methodName = "baz",
modifiers = listOf(JvmModifier.PUBLIC),
returnType = expectedTypes(PsiType.INT),
parameters = expectedParams(PsiType.INT)
)
).findWithText("Add method 'baz' to 'Foo'")
)
myFixture.checkResult(
"""
|class Foo {
| fun bar() {}
| fun baz(param0: Int): Int {
| TODO("Not yet implemented")
| }
|}
""".trim().trimMargin(), true
)
}
fun testAddIntPrimaryConstructor() {
myFixture.configureByText(
"foo.kt", """
|class Foo<caret> {
|}
""".trim().trimMargin()
)
myFixture.launchAction(
createConstructorActions(
myFixture.atCaret(), constructorRequest(project, listOf(pair("param0", PsiType.INT as PsiType)))
).findWithText("Add primary constructor to 'Foo'")
)
myFixture.checkResult(
"""
|class Foo(param0: Int) {
|}
""".trim().trimMargin(), true
)
}
fun testAddIntSecondaryConstructor() {
myFixture.configureByText(
"foo.kt", """
|class <caret>Foo() {
|}
""".trim().trimMargin()
)
myFixture.launchAction(
createConstructorActions(
myFixture.atCaret(),
constructorRequest(project, listOf(pair("param0", PsiType.INT as PsiType)))
).findWithText("Add secondary constructor to 'Foo'")
)
myFixture.checkResult(
"""
|class Foo() {
| constructor(param0: Int) {
|
| }
|}
""".trim().trimMargin(), true
)
}
fun testChangePrimaryConstructorInt() {
myFixture.configureByText(
"foo.kt", """
|class <caret>Foo() {
|}
""".trim().trimMargin()
)
myFixture.launchAction(
createConstructorActions(
myFixture.atCaret(),
constructorRequest(project, listOf(pair("param0", PsiType.INT as PsiType)))
).findWithText("Add 'int' as 1st parameter to constructor 'Foo'")
)
myFixture.checkResult(
"""
|class Foo(param0: Int) {
|}
""".trim().trimMargin(), true
)
}
fun testRemoveConstructorParameters() {
myFixture.configureByText(
"foo.kt", """
|class <caret>Foo(i: Int) {
|}
""".trim().trimMargin()
)
myFixture.launchAction(
createConstructorActions(
myFixture.atCaret(),
constructorRequest(project, emptyList())
).findWithText("Remove 1st parameter from constructor 'Foo'")
)
myFixture.checkResult(
"""
|class Foo() {
|}
""".trim().trimMargin(), true
)
}
fun testAddStringVarProperty() {
myFixture.configureByText(
"foo.kt", """
|class Foo<caret> {
| fun bar() {}
|}
""".trim().trimMargin()
)
myFixture.launchAction(
createMethodActions(
myFixture.atCaret(),
SimpleMethodRequest(
project,
methodName = "setBaz",
modifiers = listOf(JvmModifier.PUBLIC),
returnType = expectedTypes(),
parameters = expectedParams(PsiType.getTypeByName("java.lang.String", project, project.allScope()))
)
).findWithText("Add 'var' property 'baz' to 'Foo'")
)
myFixture.checkResult(
"""
|class Foo {
| var baz: String = TODO("initialize me")
|
| fun bar() {}
|}
""".trim().trimMargin(), true
)
}
fun testAddLateInitStringVarProperty() {
myFixture.configureByText(
"foo.kt", """
|class Foo<caret> {
| fun bar() {}
|}
""".trim().trimMargin()
)
myFixture.launchAction(
createMethodActions(
myFixture.atCaret(),
SimpleMethodRequest(
project,
methodName = "setBaz",
modifiers = listOf(JvmModifier.PUBLIC),
returnType = expectedTypes(),
parameters = expectedParams(PsiType.getTypeByName("java.lang.String", project, project.allScope()))
)
).findWithText("Add 'lateinit var' property 'baz' to 'Foo'")
)
myFixture.checkResult(
"""
|class Foo {
| lateinit var baz: String
|
| fun bar() {}
|}
""".trim().trimMargin(), true
)
}
fun testAddStringVarField() {
myFixture.configureByText(
"foo.kt", """
|class Foo<caret> {
| fun bar() {}
|}
""".trim().trimMargin()
)
myFixture.launchAction(
createFieldActions(
myFixture.atCaret(),
FieldRequest(project, emptyList(), "java.util.Date", "baz")
).findWithText("Add 'var' property 'baz' to 'Foo'")
)
myFixture.checkResult(
"""
|import java.util.Date
|
|class Foo {
| @JvmField
| var baz: Date = TODO("initialize me")
|
| fun bar() {}
|}
""".trim().trimMargin(), true
)
}
fun testAddLateInitStringVarField() {
myFixture.configureByText(
"foo.kt", """
|class Foo<caret> {
| fun bar() {}
|}
""".trim().trimMargin()
)
myFixture.launchAction(
createFieldActions(
myFixture.atCaret(),
FieldRequest(project, listOf(JvmModifier.PRIVATE), "java.lang.String", "baz")
).findWithText("Add 'lateinit var' property 'baz' to 'Foo'")
)
myFixture.checkResult(
"""
|class Foo {
| private lateinit var baz: String
|
| fun bar() {}
|}
""".trim().trimMargin(), true
)
}
private fun createFieldActions(atCaret: JvmClass, fieldRequest: CreateFieldRequest): List<IntentionAction> =
EP_NAME.extensions.flatMap { it.createAddFieldActions(atCaret, fieldRequest) }
fun testAddStringValProperty() {
myFixture.configureByText(
"foo.kt", """
|class Foo<caret> {
| fun bar() {}
|}
""".trim().trimMargin()
)
myFixture.launchAction(
createMethodActions(
myFixture.atCaret(),
SimpleMethodRequest(
project,
methodName = "getBaz",
modifiers = listOf(JvmModifier.PUBLIC),
returnType = expectedTypes(PsiType.getTypeByName("java.lang.String", project, project.allScope())),
parameters = expectedParams()
)
).findWithText("Add 'val' property 'baz' to 'Foo'")
)
myFixture.checkResult(
"""
|class Foo {
| val baz: String = TODO("initialize me")
|
| fun bar() {}
|}
""".trim().trimMargin(), true
)
}
fun testGetMethodHasParameters() {
myFixture.configureByText(
"foo.kt", """
|class Foo<caret> {
| fun bar() {}
|}
""".trim().trimMargin()
)
myFixture.launchAction(
createMethodActions(
myFixture.atCaret(),
SimpleMethodRequest(
project,
methodName = "getBaz",
modifiers = listOf(JvmModifier.PUBLIC),
returnType = expectedTypes(PsiType.getTypeByName("java.lang.String", project, project.allScope())),
parameters = expectedParams(PsiType.getTypeByName("java.lang.String", project, project.allScope()))
)
).findWithText("Add method 'getBaz' to 'Foo'")
)
myFixture.checkResult(
"""
|class Foo {
| fun bar() {}
| fun getBaz(param0: String): String {
| TODO("Not yet implemented")
| }
|}
""".trim().trimMargin(), true
)
}
fun testSetMethodHasStringReturnType() {
myFixture.configureByText(
"foo.kt", """
|class Foo<caret> {
| fun bar() {}
|}
""".trim().trimMargin()
)
myFixture.launchAction(
createMethodActions(
myFixture.atCaret(),
SimpleMethodRequest(
project,
methodName = "setBaz",
modifiers = listOf(JvmModifier.PUBLIC),
returnType = expectedTypes(PsiType.getTypeByName("java.lang.String", project, project.allScope())),
parameters = expectedParams(PsiType.getTypeByName("java.lang.String", project, project.allScope()))
)
).findWithText("Add method 'setBaz' to 'Foo'")
)
myFixture.checkResult(
"""
|class Foo {
| fun bar() {}
| fun setBaz(param0: String): String {
| TODO("Not yet implemented")
| }
|}
""".trim().trimMargin(), true
)
}
fun testSetMethodHasTwoParameters() {
myFixture.configureByText(
"foo.kt", """
|class Foo<caret> {
| fun bar() {}
|}
""".trim().trimMargin()
)
myFixture.launchAction(
createMethodActions(
myFixture.atCaret(),
SimpleMethodRequest(
project,
methodName = "setBaz",
modifiers = listOf(JvmModifier.PUBLIC),
returnType = expectedTypes(PsiType.VOID),
parameters = expectedParams(
PsiType.getTypeByName("java.lang.String", project, project.allScope()),
PsiType.getTypeByName("java.lang.String", project, project.allScope())
)
)
).findWithText("Add method 'setBaz' to 'Foo'")
)
myFixture.checkResult(
"""
|class Foo {
| fun bar() {}
| fun setBaz(param0: String, param1: String) {
|
| }
|}
""".trim().trimMargin(), true
)
}
private fun expectedTypes(vararg psiTypes: PsiType) = psiTypes.map { expectedType(it) }
private fun expectedParams(vararg psyTypes: PsiType) =
psyTypes.mapIndexed { index, psiType -> expectedParameter(expectedTypes(psiType), "param$index") }
class FieldRequest(
private val project: Project,
val modifiers: List<JvmModifier>,
val type: String,
val name: String
) : CreateFieldRequest {
override fun getTargetSubstitutor(): JvmSubstitutor = PsiJvmSubstitutor(project, PsiSubstitutor.EMPTY)
override fun getAnnotations(): Collection<AnnotationRequest> = emptyList()
override fun getModifiers(): Collection<JvmModifier> = modifiers
override fun isConstant(): Boolean = false
override fun getFieldType(): List<ExpectedType> =
expectedTypes(PsiType.getTypeByName(type, project, project.allScope()))
override fun getFieldName(): String = name
override fun isValid(): Boolean = true
override fun getInitializer(): JvmValue? = null
}
}
internal inline fun <reified T : JvmElement> CodeInsightTestFixture.atCaret() = elementAtCaret.toUElement() as T
@Suppress("MissingRecentApi")
private class TestModifierRequest(private val _modifier: JvmModifier, private val shouldBePresent: Boolean) : ChangeModifierRequest {
override fun shouldBePresent(): Boolean = shouldBePresent
override fun isValid(): Boolean = true
override fun getModifier(): JvmModifier = _modifier
}
@Suppress("CAST_NEVER_SUCCEEDS")
internal fun List<IntentionAction>.findWithText(text: String): IntentionAction =
this.firstOrNull { it.text == text }
?: Assert.fail("intention with text '$text' was not found, only ${this.joinToString { "\"${it.text}\"" }} available") as Nothing
| apache-2.0 | 4f3b0ce68e3645bca33a138fb8e01d6e | 31.35842 | 158 | 0.53557 | 5.368659 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/project-wizard/idea/src/org/jetbrains/kotlin/tools/projectWizard/IntelliJKotlinNewProjectWizard.kt | 1 | 2545 | // 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.tools.projectWizard
import com.intellij.ide.JavaUiBundle
import com.intellij.ide.wizard.AbstractNewProjectWizardStep
import com.intellij.openapi.module.StdModuleTypes
import com.intellij.openapi.observable.properties.GraphPropertyImpl.Companion.graphProperty
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.JavaSdkType
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.projectRoots.SdkTypeId
import com.intellij.openapi.projectRoots.impl.DependentSdkType
import com.intellij.openapi.roots.ui.configuration.sdkComboBox
import com.intellij.openapi.util.Disposer
import com.intellij.ui.dsl.builder.COLUMNS_MEDIUM
import com.intellij.ui.dsl.builder.Panel
import com.intellij.ui.dsl.builder.TopGap
import com.intellij.ui.dsl.builder.columns
import com.intellij.util.io.systemIndependentPath
import org.jetbrains.kotlin.tools.projectWizard.plugins.buildSystem.BuildSystemType
import org.jetbrains.kotlin.tools.projectWizard.wizard.KotlinNewProjectWizardUIBundle
import org.jetbrains.kotlin.tools.projectWizard.wizard.NewProjectWizardModuleBuilder
internal class IntelliJKotlinNewProjectWizard : BuildSystemKotlinNewProjectWizard {
override val name = "IntelliJ"
override fun createStep(parent: KotlinNewProjectWizard.Step) = object : AbstractNewProjectWizardStep(parent) {
val wizardBuilder: NewProjectWizardModuleBuilder = NewProjectWizardModuleBuilder()
private val sdkProperty = propertyGraph.graphProperty<Sdk?> { null }
private val sdk by sdkProperty
override fun setupUI(builder: Panel) {
with(builder) {
row(JavaUiBundle.message("label.project.wizard.new.project.jdk")) {
val sdkTypeFilter = { it: SdkTypeId -> it is JavaSdkType && it !is DependentSdkType }
sdkComboBox(context, sdkProperty, StdModuleTypes.JAVA.id, sdkTypeFilter)
.columns(COLUMNS_MEDIUM)
}
}
}
override fun setupProject(project: Project) =
KotlinNewProjectWizard.generateProject(
project = project,
projectPath = parent.projectPath.systemIndependentPath,
projectName = parent.name,
sdk = sdk,
buildSystemType = BuildSystemType.Jps
)
}
} | apache-2.0 | 5f262bb021cdbc3c3ae3dbe0d7550068 | 46.148148 | 158 | 0.745383 | 5 | false | false | false | false |
zielu/GitToolBox | src/main/kotlin/zielu/gittoolbox/push/GtPushResult.kt | 1 | 839 | package zielu.gittoolbox.push
internal data class GtPushResult(
val type: PushResultType,
val output: String,
val rejectedBranches: List<String> = listOf()
) {
internal companion object {
private val success = GtPushResult(PushResultType.SUCCESS, "")
private val cancelled = GtPushResult(PushResultType.CANCELLED, "")
@JvmStatic
fun success(): GtPushResult = success
@JvmStatic
fun cancelled(): GtPushResult = cancelled
@JvmStatic
fun error(output: String): GtPushResult {
return GtPushResult(PushResultType.ERROR, output)
}
@JvmStatic
fun rejected(branches: Collection<String>): GtPushResult {
return GtPushResult(PushResultType.REJECTED, "", branches.toList())
}
}
}
internal enum class PushResultType {
SUCCESS, REJECTED, ERROR, CANCELLED, NOT_AUTHORIZED
}
| apache-2.0 | 05ae0bf37a5058d86197609b286ab281 | 24.424242 | 73 | 0.715137 | 4.535135 | false | false | false | false |
xmartlabs/bigbang | core/src/main/java/com/xmartlabs/bigbang/core/extensions/DateExtensions.kt | 2 | 8293 | @file:Suppress("unused")
package com.xmartlabs.bigbang.core.extensions
import android.content.Context
import android.text.format.DateFormat
import org.threeten.bp.Clock
import org.threeten.bp.DayOfWeek
import org.threeten.bp.Duration
import org.threeten.bp.Instant
import org.threeten.bp.LocalDate
import org.threeten.bp.LocalDateTime
import org.threeten.bp.LocalTime
import org.threeten.bp.Period
import org.threeten.bp.YearMonth
import org.threeten.bp.ZoneOffset
import org.threeten.bp.format.DateTimeFormatter
import org.threeten.bp.temporal.TemporalAccessor
import java.text.SimpleDateFormat
import java.util.Locale
object DefaultDateTimeFormatter{
/** Returns a full date formatter (yyyy-MMM-dd HH:mm:ss) */
val FULL_DATE_WITH_TIME = DateTimeFormatter.ofPattern("yyyy-MMM-dd HH:mm:ss", Locale.US)
/** Returns a ISO 8601 date formatter (yyyy-MM-dd'T'HH:mm:ss.SSS'Z') */
val ISO_8601 = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US)
}
/** Returns `this` number of milliseconds since the epoch */
val LocalDate.epochMilli
get() = this.toInstant().toEpochMilli()
/**
* Gets the android device time format.
*
* @return [DateTimeFormatter] formatted the right way.
*/
val Context.deviceTimeFormat
get() = DateTimeFormatter.ofPattern((DateFormat.getTimeFormat(this) as SimpleDateFormat).toPattern())
/**
* Gets the android device short date format.
*
* @return [DateTimeFormatter] formatted the right way.
*/
val Context.shortDateFormat
get() = DateTimeFormatter.ofPattern((DateFormat.getDateFormat(this) as SimpleDateFormat).toPattern())
/**
* Gets the android device medium date format.
*
* @return [DateTimeFormatter] formatted the right way.
*/
val Context.mediumDateFormat
get() = DateTimeFormatter.ofPattern((DateFormat.getMediumDateFormat(this) as SimpleDateFormat).toPattern())
/**
* Gets the android device long date format.
*
* @return [DateTimeFormatter] formatted the right way.
*/
val Context.longDateFormat
get() = DateTimeFormatter.ofPattern((DateFormat.getLongDateFormat(this) as SimpleDateFormat).toPattern())
/**
* Sets the `date` to the last second of the day it's in.
*
* @param date the date to update.
*
* @return a new [LocalDateTime] object, same day as `date` but starting at the last second of the day.
*/
val LocalDateTime.toLastSecond
get() = this.with(LocalTime.MAX)
/**
* Retrieves the first day of the `date` week.
*
* @param date the date whose week's first day we want to retrieve.
*
* @return a [LocalDate] instance representing the first day of the `date` week.
*/
val LocalDate.firstDayOfWeek
get() = this.with(DayOfWeek.MONDAY)
/** Converts `this` to an Instant with `ZoneOffset` offset */
fun LocalDate.toInstant(offset: ZoneOffset = ZoneOffset.UTC) = atStartOfDay(offset).toInstant()
/** Returns `this` number of seconds since the epoch */
fun LocalDate.epochSeconds(offset: ZoneOffset = ZoneOffset.UTC) = this.atStartOfDay().toEpochSecond(offset)
/** Returns a `LocalDate` instance with `milli` milliseconds since epoch */
fun localDatefromEpochMilli(milli: Long) = localDatefromEpochMilli(milli, ZoneOffset.UTC)
/** Returns a `LocalDate` instance with `milli` milliseconds since epoch at `ZoneOffset` offset */
fun localDatefromEpochMilli(milli: Long, offset: ZoneOffset = ZoneOffset.UTC) =
Instant.ofEpochMilli(milli).atZone(offset).toLocalDate()
/** Returns a `LocalDate` instance with `seconds` since epoch */
fun localDateFromEpochSeconds(seconds: Long, offset: ZoneOffset = ZoneOffset.UTC) =
Instant.ofEpochSecond(seconds).atZone(offset).toLocalDate()
/** Returns a `LocalDateTime` instance with `milli` milliseconds since epoch */
fun localDateTimeFromEpochMilli(milli: Long) = localDateTimeFromEpochMilli(milli, ZoneOffset.UTC)
/** Returns a `LocalDateTime` instance with `milli` milliseconds since epoch at `ZoneOffset` offset */
fun localDateTimeFromEpochMilli(milli: Long, offset: ZoneOffset = ZoneOffset.UTC) =
Instant.ofEpochMilli(milli).atZone(offset).toLocalDateTime()
/** Returns a `LocalDateTime` instance with `seconds` since epoch at `ZoneOffset` offset */
fun localDateTimeFromEpochSeconds(seconds: Long, offset: ZoneOffset = ZoneOffset.UTC) =
Instant.ofEpochSecond(seconds).atZone(offset).toLocalDateTime()
/**
* Converts a string representation of a date to its LocalDateTime object.
*
* @param dateAsString Date in string format.
* @param df Date format.
* *
* @return Date.
*/
fun stringToLocalDateTime(dateAsString: String, df: DateTimeFormatter) =
dateAsString.ignoreException { LocalDateTime.parse(this, df) }
/**
* Checks whether the given `date` is today or not.
*
* @param date the date to check.
* @param clock to be used to retrieve today's date.
*
* @return true if the date given by the `clock` is the same as `date`.
*/
fun LocalDate.isToday(clock: Clock = Clock.systemDefaultZone()) = this == baseDate(clock)
/**
* Retrieves a list of days ([LocalDate]s) between `startDate` and `endDate`.
* @param startDate the date before the list should start.
* *
* @param endDate the date after the list should end.
* *
* @return the list between, but not including, `startDate` and `endDate`.
*/
fun LocalDate.datesUntil(date: LocalDate) = IntRange(0, this.until(date).days)
.map(Int::toLong)
.map(this::plusDays)
/**
* Checks whether the given `date` is today or not.
* @param temporalAccessor a second local date to compare.
*
* @return true if both dates have the same month and year.
*/
fun TemporalAccessor.haveSameMonthAndYearThan(temporalAccessor: TemporalAccessor) =
YearMonth.from(this) == YearMonth.from(temporalAccessor)
/**
* Converts the integer expressed in nanoseconds to duration.
*
* @return The time expressed in duration.
*/
val Int.nanoseconds: Duration
get() = Duration.ofNanos(toLong())
/**
* Converts the integer expressed in microseconds to duration.
*
* @return The time expressed in duration.
*/
val Int.microseconds: Duration
get() = Duration.ofNanos(toLong() * 1000L)
/**
* Converts the integer expressed in milliseconds to duration.
*
* @return The time expressed in duration.
*/
val Int.milliseconds: Duration
get() = Duration.ofMillis(toLong())
/**
* Converts the integer expressed in seconds to duration.
*
* @return The time expressed in duration.
*/
val Int.seconds: Duration
get() = Duration.ofSeconds(toLong())
/**
* Converts the integer expressed in minutes to duration.
*
* @return The time expressed in duration.
*/
val Int.minutes: Duration
get() = Duration.ofMinutes(toLong())
/**
* Converts the integer expressed in hours to duration.
*
* @return The time expressed in duration.
*/
val Int.hours: Duration
get() = Duration.ofHours(toLong())
/**
* Converts the integer expressed in days to a period of time.
*
* @return The time expressed in a period.
*/
val Int.days: Period
get() = Period.ofDays(this)
/**
* Converts the integer expressed in weeks to a period of time.
*
* @return The time expressed in a period.
*/
val Int.weeks: Period
get() = Period.ofWeeks(this)
/**
* Converts the integer expressed in months to a period of time.
*
* @return The time expressed in a period.
*/
val Int.months: Period
get() = Period.ofMonths(this)
/**
* Converts the integer expressed in years to a period of time.
*
* @return The time expressed in a period.
*/
val Int.years: Period
get() = Period.ofYears(this)
/**
* Gets the LocalDateTime calculated as [current_date - duration].
*
* @return The LocalDateTime.
*/
val Duration.ago: LocalDateTime
get() = baseTime() - this
/**
* Gets the LocalDateTime calculated as [current_date + duration].
*
* @return The LocalDateTime.
*/
val Duration.fromNow: LocalDateTime
get() = baseTime() + this
/**
* Gets the LocalDateTime calculated as [current_date - period].
*
* @return The LocalDateTime.
*/
val Period.ago: LocalDate
get() = baseDate() - this
/**
* Gets the LocalDateTime calculated as [current_date + period].
*
* @return The LocalDateTime.
*/
val Period.fromNow: LocalDate
get() = baseDate() + this
private fun baseDate(clock: Clock = Clock.systemDefaultZone()) = LocalDate.now(clock)
private fun baseTime(clock: Clock = Clock.systemDefaultZone()) = LocalDateTime.now(clock)
| apache-2.0 | fe39bd662bd1df32c874edac63e9c06f | 29.488971 | 109 | 0.732907 | 3.908106 | false | false | false | false |
neverwoodsS/StudyWithKotlin | src/logic/Main.kt | 1 | 3179 | package logic
fun main(args: Array<String>) {
val answers = arrayOf('a', 'b', 'c', 'd')
(0 until 1024*1024).forEach {
val tempAnswer = it.toAnswers()
if (check(tempAnswer)) {
val answer = tempAnswer.map { answers[it] }.joinToString(", ").toUpperCase()
println(answer)
}
}
}
private fun check(answers: List<Int>): Boolean {
val counts = (0..3).map { answer -> answers.count { answer == it } }
val maxCount = counts.max() ?: 10
val minCount = counts.min() ?: 0
val answer1 = answers[0]
val answer2 = answers[1]
val answer3 = answers[2]
val answer4 = answers[3]
val answer5 = answers[4]
val answer6 = answers[5]
val answer7 = answers[6]
val answer8 = answers[7]
val answer9 = answers[8]
val answer10 = answers[9]
// 第一题的限制
// 第二题的限制
if (arrayOf(2,3,0,1)[answer2] != answer5)
return false
// 第三题的限制
when (answer3) {
0 -> if (!(answer6 == answer2 && answer6 == answer4)) return false
1 -> if (answer6 == 1 || answer2 != 1 || answer4 != 1) return false
2 -> if (answer6 != 2 || answer2 == 2 || answer4 != 2) return false
3 -> if (answer6 != 3 || answer2 != 3 || answer4 == 3) return false
}
// 第四题的限制
when (answer4) {
0 -> if (answer1 != answer5) return false
1 -> if (answer2 != answer7) return false
2 -> if (answer1 != answer9) return false
3 -> if (answer6 != answer10) return false
}
// 第五题的限制
when (answer5) {
0 -> if (answer8 != 0) return false
1 -> if (answer4 != 1) return false
2 -> if (answer9 != 2) return false
3 -> if (answer7 != 3) return false
}
// 第六题限制
when (answer6) {
0 -> if (answer2 != answer8 || answer4 != answer8) return false
1 -> if (answer1 != answer8 || answer6 != answer8) return false
2 -> if (answer3 != answer8 || answer10 != answer8) return false
3 -> if (answer5 != answer8 || answer9 != answer8) return false
}
// 第七题限制
when (answer7) {
0 -> if (counts[2] != minCount) return false
1 -> if (counts[1] != minCount) return false
2 -> if (counts[0] != minCount) return false
3 -> if (counts[3] != minCount) return false
}
// 第八题限制
val distance = arrayOf(answer7, answer5, answer2, answer10)[answer8] - answer1
if (Math.abs(distance) <= 1) {
return false
}
// 第九题限制
val flag = answer1 == answer6
val anotherFlag = arrayOf(answer6, answer10, answer2, answer9)[answer9] == answer5
if (flag == anotherFlag) return false
// 第十题限制
if (arrayOf(3,2,4,1)[answer10] != maxCount - minCount) return false
return true
}
private fun Int.toAnswers(): List<Int> {
val temp = mutableListOf<Int>()
var i = this
while (i > 0) {
temp.add(i % 4)
i /= 4
}
val result: List<Int>
if (temp.size < 10)
result = temp + List(10 - temp.size) { 0 }
else result = temp
return result.reversed()
} | mit | c6c52b0dfc0a8d2131ffaf0e9436cdfb | 27.425926 | 88 | 0.553926 | 3.379956 | false | false | false | false |
paoloach/zdomus | ZTopology/app/src/main/java/it/achdjian/paolo/ztopology/activities/node/fragments/clusters/IdentifyClusterFragment.kt | 1 | 850 | package it.achdjian.paolo.ztopology.activities.node.fragments.clusters
import android.os.Bundle
import it.achdjian.paolo.ztopology.R
import it.achdjian.paolo.ztopology.activities.NodeActivity
import it.achdjian.paolo.ztopology.zigbee.Cluster
import it.achdjian.paolo.ztopology.zigbee.ZEndpoint
/**
* Created by Paolo Achdjian on 2/27/18.
*/
class IdentifyClusterFragment : ClusterFragment() {
override fun layoutResource(): Int = R.layout.identify_cluster
override fun clusterId() = Cluster.IDENTIFY_CLUSTER
companion object {
fun newInstance(endpoint: ZEndpoint): IdentifyClusterFragment {
val fragment = IdentifyClusterFragment()
val args = Bundle()
args.putSerializable(NodeActivity.ENDPOINT, endpoint)
fragment.arguments = args
return fragment
}
}
} | gpl-2.0 | ce29a8053dcf0ff64f92b7b1a86715ca | 33.04 | 71 | 0.724706 | 4.314721 | false | false | false | false |
calintat/sensors | app/src/main/java/com/calintat/sensors/ui/SettingsUI.kt | 1 | 1314 | package com.calintat.sensors.ui
import com.calintat.sensors.R
import com.calintat.sensors.activities.SettingsActivity
import com.calintat.sensors.utils.AnkoProperties.titleTextColorResource
import org.jetbrains.anko.AnkoComponent
import org.jetbrains.anko.AnkoContext
import org.jetbrains.anko.appcompat.v7.navigationIconResource
import org.jetbrains.anko.appcompat.v7.titleResource
import org.jetbrains.anko.appcompat.v7.toolbar
import org.jetbrains.anko.design.appBarLayout
import org.jetbrains.anko.design.coordinatorLayout
import org.jetbrains.anko.frameLayout
import org.jetbrains.anko.verticalLayout
object SettingsUI : AnkoComponent<SettingsActivity> {
override fun createView(ui: AnkoContext<SettingsActivity>) = with(ui) {
coordinatorLayout {
fitsSystemWindows = true
verticalLayout {
appBarLayout {
toolbar {
navigationIconResource = R.drawable.ic_action_back
setNavigationOnClickListener { owner.finish() }
titleResource = R.string.navigation_settings
titleTextColorResource = android.R.color.white
}
}
frameLayout { id = R.id.container }
}
}
}
} | apache-2.0 | 281f61114b27a55d979ef4d2f1de9dd3 | 28.886364 | 75 | 0.675038 | 5.053846 | false | false | false | false |
orgzly/orgzly-android | app/src/main/java/com/orgzly/android/ui/repo/RepoViewModel.kt | 1 | 2199 | package com.orgzly.android.ui.repo
import com.orgzly.android.App
import com.orgzly.android.data.DataRepository
import com.orgzly.android.db.entity.Repo
import com.orgzly.android.repos.RepoWithProps
import com.orgzly.android.repos.RepoType
import com.orgzly.android.repos.SyncRepo
import com.orgzly.android.ui.CommonViewModel
import com.orgzly.android.ui.SingleLiveEvent
import com.orgzly.android.usecase.RepoCreate
import com.orgzly.android.usecase.RepoUpdate
import com.orgzly.android.usecase.UseCase
import com.orgzly.android.usecase.UseCaseRunner
open class RepoViewModel(private val dataRepository: DataRepository, open var repoId: Long) : CommonViewModel() {
val finishEvent: SingleLiveEvent<Any> = SingleLiveEvent()
val alreadyExistsEvent: SingleLiveEvent<Any> = SingleLiveEvent()
fun loadRepoProperties(): RepoWithProps? {
val repo = dataRepository.getRepo(repoId)
return if (repo != null) {
val props = dataRepository.getRepoPropsMap(repoId)
RepoWithProps(repo, props)
} else {
null
}
}
fun saveRepo(type: RepoType, url: String, props: Map<String, String> = emptyMap()) {
val repo = Repo(repoId, type, url)
val repoWithProps = RepoWithProps(repo, props)
if (repoId == 0L) {
create(repoWithProps)
} else {
update(repoWithProps)
}
}
fun update(props: RepoWithProps) {
run(RepoUpdate(props))
}
fun create(props: RepoWithProps) {
run(RepoCreate(props))
}
private fun run(useCase: UseCase) {
App.EXECUTORS.diskIO().execute {
try {
val result = UseCaseRunner.run(useCase)
// Update repo ID
repoId = result.userData as Long
finishEvent.postValue(result)
} catch (ae: RepoCreate.AlreadyExists) {
alreadyExistsEvent.postValue(true)
} catch (t: Throwable) {
errorEvent.postValue(t)
}
}
}
fun validate(repoType: RepoType, url: String): SyncRepo {
return dataRepository.getRepoInstance(repoId, repoType, url)
}
} | gpl-3.0 | f4e443c00b231917220d335c2cadea45 | 27.571429 | 113 | 0.649841 | 4.220729 | false | false | false | false |
seventhroot/elysium | bukkit/rpk-players-bukkit/src/main/kotlin/com/rpkit/players/bukkit/profile/RPKProfileImpl.kt | 1 | 1667 | package com.rpkit.players.bukkit.profile
import java.security.SecureRandom
import java.util.*
import javax.crypto.SecretKeyFactory
import javax.crypto.spec.PBEKeySpec
class RPKProfileImpl: RPKProfile {
override var id: Int = 0
override var name: String
override var passwordHash: ByteArray
override var passwordSalt: ByteArray
constructor(id: Int, name: String, passwordHash: ByteArray, passwordSalt: ByteArray) {
this.id = id
this.name = name
this.passwordHash = passwordHash
this.passwordSalt = passwordSalt
}
constructor(name: String, password: String) {
this.id = 0
this.name = name
val random = SecureRandom()
passwordSalt = ByteArray(16)
random.nextBytes(passwordSalt)
val spec = PBEKeySpec(password.toCharArray(), passwordSalt, 65536, 128)
val factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512")
passwordHash = factory.generateSecret(spec).encoded
}
override fun setPassword(password: CharArray) {
val random = SecureRandom()
passwordSalt = ByteArray(16)
random.nextBytes(passwordSalt)
val spec = PBEKeySpec(password, passwordSalt, 65536, 128)
val factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512")
passwordHash = factory.generateSecret(spec).encoded
}
override fun checkPassword(password: CharArray): Boolean {
val spec = PBEKeySpec(password, passwordSalt, 65536, 128)
val factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512")
return Arrays.equals(passwordHash, factory.generateSecret(spec).encoded)
}
} | apache-2.0 | 5dbca2b72fa2f87e8dcc25ec2d50d99a | 33.75 | 90 | 0.70066 | 4.917404 | false | false | false | false |
orgzly/orgzly-android | app/src/main/java/com/orgzly/android/db/dao/NoteAncestorDao.kt | 1 | 1771 | package com.orgzly.android.db.dao
import androidx.room.Dao
import androidx.room.Query
import androidx.room.Transaction
import com.orgzly.android.db.OrgzlyDatabase
import com.orgzly.android.db.entity.NoteAncestor
@Dao
abstract class NoteAncestorDao(val db: OrgzlyDatabase) : BaseDao<NoteAncestor> {
@Query("""
DELETE FROM note_ancestors
WHERE note_id IN (
SELECT DISTINCT d.id
FROM notes n, notes d
WHERE d.book_id = n.book_id AND n.id IN (:ids) AND d.is_cut = 0 AND n.lft <= d.lft AND d.rgt <= n.rgt
)
""")
abstract fun deleteForSubtrees(ids: Set<Long>)
/*
* "INSERT query type is not supported yet"
* https://issuetracker.google.com/issues/109900809
*
* They are now, though inspection is still not passing
* https://issuetracker.google.com/issues/109900809#comment9
*/
@Transaction
open fun insertAncestorsForNotes(ids: Set<Long>) {
ids.chunked(OrgzlyDatabase.SQLITE_MAX_VARIABLE_NUMBER).forEach { chunk ->
insertAncestorsForNotesChunk(chunk)
}
}
@Query("""
INSERT INTO note_ancestors (book_id, note_id, ancestor_note_id)
SELECT n.book_id, n.id, a.id
FROM notes n
JOIN notes a ON (n.book_id = a.book_id AND a.lft < n.lft AND n.rgt < a.rgt)
WHERE n.id IN (:ids)
""")
abstract fun insertAncestorsForNotesChunk(ids: List<Long>)
@Query("""
INSERT INTO note_ancestors (book_id, note_id, ancestor_note_id)
SELECT n.book_id, n.id, a.id
FROM notes n
JOIN notes a ON (n.book_id = a.book_id AND a.lft < n.lft AND n.rgt < a.rgt)
WHERE n.id = :noteId AND a.level > 0
""")
abstract fun insertAncestorsForNote(noteId: Long)
}
| gpl-3.0 | 2fb868274228760b966ae2ba7b277047 | 31.796296 | 113 | 0.63467 | 3.425532 | false | false | false | false |
rjhdby/motocitizen | Motocitizen/src/motocitizen/ui/rows/accident/Row.kt | 1 | 3352 | package motocitizen.ui.rows.accident
import android.app.Activity
import android.content.Context
import android.graphics.Typeface
import android.os.Build
import android.text.Html
import android.text.Spanned
import android.view.Gravity
import android.view.View
import android.widget.FrameLayout
import android.widget.LinearLayout
import motocitizen.content.accident.Accident
import motocitizen.datasources.database.StoreMessages
import motocitizen.main.R
import motocitizen.ui.Screens
import motocitizen.ui.activity.AccidentDetailsActivity
import motocitizen.ui.menus.AccidentContextMenu
import motocitizen.utils.Margins
import motocitizen.utils.getIntervalFromNowInText
import motocitizen.utils.goTo
import motocitizen.utils.margins
import org.jetbrains.anko.matchParent
import org.jetbrains.anko.textView
import org.jetbrains.anko.wrapContent
//todo refactor
abstract class Row protected constructor(context: Context, val accident: Accident) : FrameLayout(context) {
companion object {
const val ACTIVE_COLOR = 0x70FFFFFF
const val ENDED_COLOR = 0x70FFFFFF
const val HIDDEN_COLOR = 0x30FFFFFF
}
abstract val background: Int
abstract val textColor: Int
abstract val margins: Margins
private fun messagesText(accident: Accident): Spanned {
val text = formatMessagesText(accident)
return if (Build.VERSION.SDK_INT >= 24) {
Html.fromHtml(text, Html.TO_HTML_PARAGRAPH_LINES_CONSECUTIVE)
} else {
@Suppress("DEPRECATION")
Html.fromHtml(text)
}
}
//todo remove html
private fun formatMessagesText(accident: Accident): String {
if (accident.messagesCount == 0) return ""
val read = StoreMessages.getLast(accident.id)
return if (accident.messagesCount > read)
String.format("<font color=#C62828><b>(%s)</b></font>", accident.messagesCount)
else
String.format("<b>%s</b>", accident.messagesCount)
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
setMargins()
setBackgroundResource(background)
textView(context.resources.getString(R.string.accident_row_content, accident.title())) {
layoutParams = LayoutParams(matchParent, wrapContent)
minLines = 3
setTextColor(textColor)
}
textView(accident.time.getIntervalFromNowInText()) {
layoutParams = LayoutParams(matchParent, matchParent)
gravity = Gravity.END
typeface = Typeface.DEFAULT_BOLD
}
textView(messagesText(accident)) {
layoutParams = LayoutParams(matchParent, matchParent)
gravity = Gravity.BOTTOM or Gravity.END
}
setUpListeners()
}
private fun setMargins() {
layoutParams = LinearLayout.LayoutParams(matchParent, wrapContent).margins(margins)
}
private fun setUpListeners() {
setOnClickListener { clickListener() }
setOnLongClickListener { longClickListener(it) }
}
private fun clickListener() {
(context as Activity).goTo(Screens.DETAILS, mapOf(AccidentDetailsActivity.ACCIDENT_ID_KEY to accident.id))
}
private fun longClickListener(v: View): Boolean {
AccidentContextMenu(context, accident).showAsDropDown(v)
return true
}
} | mit | 905dfffc95e116fb58dbb0d808c56414 | 33.56701 | 114 | 0.703162 | 4.701262 | false | false | false | false |
EMResearch/EvoMaster | e2e-tests/spring-rest-openapi-v3/src/main/kotlin/com/foo/rest/examples/spring/openapi/v3/extraheader/ExtraHeaderRest.kt | 1 | 759 | package com.foo.rest.examples.spring.openapi.v3.extraheader
import com.sun.net.httpserver.HttpExchange
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestHeader
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import java.io.UnsupportedEncodingException
import java.net.URI
import java.net.URLDecoder
import javax.servlet.http.HttpServletRequest
@RestController
@RequestMapping(path = ["/api/extraheader"])
class ExtraHeaderRest {
@GetMapping()
open fun getHeader(@RequestHeader(name="x-a", required = true) a : String): String {
return if (a == null) {
"FALSE"
} else "OK"
}
} | lgpl-3.0 | f0480c4d0dd9fdec036b4586bbb78c86 | 28.230769 | 88 | 0.766798 | 4.102703 | false | false | false | false |
TGITS/programming-workouts | exercism/kotlin/anagram/src/test/kotlin/AnagramTest.kt | 2 | 3158 | import org.junit.Test
import org.junit.Ignore
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class AnagramTest {
@Test
fun `no matches`() =
anagramsOf("diaper")
.searchedIn("hello", "world", "zombies", "pants")
.shouldBeEmpty()
@Ignore
@Test
fun `detects two anagrams`() =
anagramsOf("master")
.searchedIn("stream", "pigeon", "maters")
.shouldBeOnly("maters", "stream")
@Ignore
@Test
fun `does not detect anagram subsets`() =
anagramsOf("good")
.searchedIn("dog", "goody")
.shouldBeEmpty()
@Ignore
@Test
fun `detects anagram`() =
anagramsOf("listen")
.searchedIn("enlists", "google", "inlets", "banana")
.shouldBeOnly("inlets")
@Ignore
@Test
fun `detects three anagrams`() =
anagramsOf("allergy")
.searchedIn("gallery", "ballerina", "regally", "clergy", "largely", "leading")
.shouldBeOnly("gallery", "largely", "regally")
@Ignore
@Test
fun `detects multiple anagrams with different case`() =
anagramsOf("nose")
.searchedIn("Eons", "ONES")
.shouldBeOnly("Eons", "ONES")
@Ignore
@Test
fun `does not detect non-anagrams with identical checksum`() =
anagramsOf("mass")
.searchedIn("last")
.shouldBeEmpty()
@Ignore
@Test
fun `detects anagrams case-insensitively`() =
anagramsOf("Orchestra")
.searchedIn("cashregister", "Carthorse", "radishes")
.shouldBeOnly("Carthorse")
@Ignore
@Test
fun `detects anagrams using case-insensitive subject`() =
anagramsOf("Orchestra")
.searchedIn("cashregister", "carthorse", "radishes")
.shouldBeOnly("carthorse")
@Ignore
@Test
fun `detects anagrams using case-insensitive possible matches`() =
anagramsOf("orchestra")
.searchedIn("cashregister", "Carthorse", "radishes")
.shouldBeOnly("Carthorse")
@Ignore
@Test
fun `does not detect an anagram if the original word is repeated`() =
anagramsOf("go")
.searchedIn("go Go GO")
.shouldBeEmpty()
@Ignore
@Test
fun `anagrams must use all letters exactly once`() =
anagramsOf("tapper")
.searchedIn("patter")
.shouldBeEmpty()
@Ignore
@Test
fun `words are not anagrams of themselves (case-insensitive)`() =
anagramsOf("BANANA")
.searchedIn("Banana")
.shouldBeEmpty()
@Ignore
@Test
fun `words other than themselves can be anagrams`() =
anagramsOf("LISTEN")
.searchedIn("Listen", "Silent", "LISTEN")
.shouldBeOnly("Silent")
}
private fun anagramsOf(source: String) = Anagram(source)
private fun Anagram.searchedIn(vararg variants: String) = this.match(setOf(*variants))
private fun Set<String>.shouldBeOnly(vararg expectation: String) = assertEquals(setOf(*expectation), this)
private fun Set<String>.shouldBeEmpty() = assertTrue(this.isEmpty())
| mit | 13d57fd95b96c66012fad7b9270fd485 | 27.709091 | 106 | 0.592464 | 3.952441 | false | true | false | false |
bvic23/storybook-intellij-plugin | src/org/bvic23/intellij/plugin/storybook/settings/SettingsController.kt | 1 | 1922 | package org.bvic23.intellij.plugin.storybook.settings
import com.intellij.openapi.options.Configurable
import com.intellij.openapi.options.ConfigurationException
import com.intellij.util.messages.MessageBus
import org.bvic23.intellij.plugin.storybook.notifications.SettingsChangeNotifier
import org.jetbrains.annotations.Nls
import javax.swing.JComponent
class SettingsController : Configurable {
private val panel = SettingsPanel()
@Nls
override fun getDisplayName(): String {
return "Storybook"
}
override fun getHelpTopic(): String? {
return null
}
override fun createComponent(): JComponent? {
panel.hostField.text = settingsManager.host
panel.portField.text = settingsManager.port
return panel.contentPanel
}
override fun isModified(): Boolean {
return getHost() != settingsManager.host ||
getPort() != settingsManager.port
}
@Throws(ConfigurationException::class)
override fun apply() {
val newHost = getHost()
val newPort = getPort()
if (newHost != "") settingsManager.host = newHost
if (newPort != "") settingsManager.port = newPort
reset()
notifySettingsChanged()
}
override fun reset() {
panel.hostField.text = settingsManager.host
panel.portField.text = settingsManager.port
}
override fun disposeUIResources() {
panel.contentPanel.removeAll()
panel.contentPanel = null
}
private fun notifySettingsChanged() {
val notifier = messageBus.syncPublisher(SettingsChangeNotifier.SETTINGS_CHANGE_TOPIC)
notifier.onSettingsChange()
}
private fun getHost() = panel.hostField.text.trim()
private fun getPort() = panel.portField.text.trim()
companion object {
lateinit var messageBus: MessageBus
lateinit var settingsManager: SettingsManager
}
}
| mit | fe512dc6eb76d5f252eaf2dbfa634ee1 | 26.855072 | 93 | 0.688345 | 5.005208 | false | true | false | false |
RP-Kit/RPKit | bukkit/rpk-stats-bukkit/src/main/kotlin/com/rpkit/stats/bukkit/placeholder/RPKStatsPlaceholderExpansion.kt | 1 | 2334 | /*
* Copyright 2022 Ren Binden
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.stats.bukkit.placeholder
import com.rpkit.characters.bukkit.character.RPKCharacterService
import com.rpkit.core.service.Services
import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfileService
import com.rpkit.stats.bukkit.RPKStatsBukkit
import com.rpkit.stats.bukkit.stat.RPKStatService
import com.rpkit.stats.bukkit.stat.RPKStatVariableService
import me.clip.placeholderapi.expansion.PlaceholderExpansion
import org.bukkit.entity.Player
class RPKStatsPlaceholderExpansion(private val plugin: RPKStatsBukkit) : PlaceholderExpansion() {
override fun persist() = true
override fun canRegister() = true
override fun getIdentifier() = "rpkstats"
override fun getAuthor() = plugin.description.authors.joinToString()
override fun getVersion() = plugin.description.version
override fun onPlaceholderRequest(player: Player, params: String): String? {
val minecraftProfileService = Services[RPKMinecraftProfileService::class.java] ?: return null
val characterService = Services[RPKCharacterService::class.java] ?: return null
val statService = Services[RPKStatService::class.java] ?: return null
val statVariableService = Services[RPKStatVariableService::class.java] ?: return null
val minecraftProfile = player.let { minecraftProfileService.getPreloadedMinecraftProfile(it) }
val character = minecraftProfile?.let { characterService.getPreloadedActiveCharacter(it) }
for (stat in statService.stats) {
if (params.lowercase() == stat.name.value.lowercase()) {
return character?.let { stat.get(character, statVariableService.statVariables) }?.toString()
}
}
return null
}
} | apache-2.0 | 47c327840f7e48a341ee89b15dff7045 | 44.784314 | 108 | 0.749786 | 4.640159 | false | false | false | false |
RichoDemus/kotlin-test | src/main/kotlin/demo/higher_order_function/HigherOrderFunction.kt | 1 | 527 | package demo.higher_order_function
fun main(args: Array<String>) {
val id = 10
val dao = { it: Int -> mapOf(Pair(80, 8080), Pair(443, 8443)).get(it) }
val port = 80
idToContainer(id)
}
//fun idToContainer(dao: KFunction1<Int, Container>):(Int) -> Container {
//fun idToContainer(dao: KFunction1<Id, Container>):(Int) -> Container {
// return {id:Int -> dao(id)}
//}
fun idToContainer(id:Int) = Id(id)
fun containerDao(id:Id) = Container(id)
data class Container(val id:Id)
data class Id(val id:Int) | apache-2.0 | a31747d5f98873785e39361ae6b651e2 | 20.12 | 75 | 0.654649 | 2.977401 | false | false | false | false |
nickthecoder/tickle | tickle-editor/src/main/kotlin/uk/co/nickthecoder/tickle/editor/scene/history/ChangeDoubleParameter.kt | 1 | 1800 | /*
Tickle
Copyright (C) 2017 Nick Robinson
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.nickthecoder.tickle.editor.scene.history
import uk.co.nickthecoder.paratask.parameters.DoubleParameter
import uk.co.nickthecoder.tickle.editor.resources.DesignActorResource
import uk.co.nickthecoder.tickle.editor.resources.ModificationType
import uk.co.nickthecoder.tickle.editor.scene.SceneEditor
class ChangeDoubleParameter(
private val actorResource: DesignActorResource,
private val parameter: DoubleParameter,
private var newValue: Double)
: Change {
private val oldValue = parameter.value
override fun redo(sceneEditor: SceneEditor) {
parameter.value = newValue
sceneEditor.sceneResource.fireChange(actorResource, ModificationType.CHANGE)
}
override fun undo(sceneEditor: SceneEditor) {
parameter.value = oldValue
sceneEditor.sceneResource.fireChange(actorResource, ModificationType.CHANGE)
}
override fun mergeWith(other: Change): Boolean {
if (other is ChangeDoubleParameter && other.actorResource == actorResource) {
other.newValue = newValue
return true
}
return false
}
}
| gpl-3.0 | 8e8b6a50377ee98b29f0ec80470d459e | 33.615385 | 85 | 0.751111 | 4.603581 | false | false | false | false |
YiiGuxing/TranslationPlugin | src/main/kotlin/cn/yiiguxing/plugin/translate/trans/Languages.kt | 1 | 8469 | package cn.yiiguxing.plugin.translate.trans
import cn.yiiguxing.plugin.translate.MyDynamicBundle
import com.intellij.util.xmlb.annotations.Attribute
import com.intellij.util.xmlb.annotations.Tag
import org.jetbrains.annotations.PropertyKey
import java.util.*
private const val LANGUAGE_BUNDLE = "messages.LanguageBundle"
private object LanguageBundle : MyDynamicBundle(LANGUAGE_BUNDLE)
@Tag("language-pair")
data class LanguagePair(
@Attribute var source: Lang = Lang.AUTO,
@Attribute var target: Lang = Lang.AUTO
)
/**
* 语言
*/
@Suppress("SpellCheckingInspection", "unused")
enum class Lang(
@PropertyKey(resourceBundle = LANGUAGE_BUNDLE)
langNameKey: String,
val code: String
) {
/** 自动检测 */
AUTO("auto", "auto"),
/** 未知语言 */
UNKNOWN("unknown", "_unknown_"),
/** 中文 */
CHINESE("chinese", "zh-CN"),
/** 英语 */
ENGLISH("english", "en"),
/** 中文(繁体) */
CHINESE_TRADITIONAL("chinese.traditional", "zh-TW"),
/** 文言文 */
CHINESE_CLASSICAL("chinese.classical", "zh-CLASSICAL"),
/** 粤语 */
CHINESE_CANTONESE("chinese.cantonese", "zh-CANTONESE"),
/** 阿尔巴尼亚语 */
ALBANIAN("albanian", "sq"),
/** 阿拉伯语 */
ARABIC("arabic", "ar"),
/** 阿姆哈拉语 */
AMHARIC("amharic", "am"),
/** 阿塞拜疆语 */
AZERBAIJANI("azerbaijani", "az"),
/** 爱尔兰语 */
IRISH("irish", "ga"),
/** 爱沙尼亚语 */
ESTONIAN("estonian", "et"),
/** 奥利亚语 */
ORIYA("oriya", "or"),
/** 巴斯克语 */
BASQUE("basque", "eu"),
/** 白俄罗斯语 */
BELARUSIAN("belarusian", "be"),
/** 保加利亚语 */
BULGARIAN("bulgarian", "bg"),
/** 冰岛语 */
ICELANDIC("icelandic", "is"),
/** 波兰语 */
POLISH("polish", "pl"),
/** 波斯尼亚语 */
BOSNIAN("bosnian", "bs"),
/** 波斯语 */
PERSIAN("persian", "fa"),
/** 布尔语(南非荷兰语) */
AFRIKAANS("afrikaans", "af"),
/** 鞑靼语 */
TATAR("tatar", "tt"),
/** 丹麦语 */
DANISH("danish", "da"),
/** 德语 */
GERMAN("german", "de"),
/** 俄语 */
RUSSIAN("russian", "ru"),
/** 法语 */
FRENCH("french", "fr"),
/** 菲律宾语 */
FILIPINO("filipino", "tl"),
/** 芬兰语 */
FINNISH("finnish", "fi"),
/** 弗里西语 */
FRISIAN("frisian", "fy"),
/** 高棉语 */
KHMER("khmer", "km"),
/** 格鲁吉亚语 */
GEORGIAN("georgian", "ka"),
/** 古吉拉特语 */
GUJARATI("gujarati", "gu"),
/** 哈萨克语 */
KAZAKH("kazakh", "kk"),
/** 海地克里奥尔语 */
HAITIAN_CREOLE("haitianCreole", "ht"),
/** 韩语 */
KOREAN("korean", "ko"),
/** 豪萨语 */
HAUSA("hausa", "ha"),
/** 荷兰语 */
DUTCH("dutch", "nl"),
/** 吉尔吉斯语 */
KYRGYZ("kyrgyz", "ky"),
/** 加利西亚语 */
GALICIAN("galician", "gl"),
/** 加泰罗尼亚语 */
CATALAN("catalan", "ca"),
/** 捷克语 */
CZECH("czech", "cs"),
/** 卡纳达语 */
KANNADA("kannada", "kn"),
/** 科西嘉语 */
CORSICAN("corsican", "co"),
/** 克罗地亚语 */
CROATIAN("croatian", "hr"),
/** 库尔德语 */
KURDISH("kurdish", "ku"),
/** 拉丁语 */
LATIN("latin", "la"),
/** 拉脱维亚语 */
LATVIAN("latvian", "lv"),
/** 老挝语 */
LAO("lao", "lo"),
/** 立陶宛语 */
LITHUANIAN("lithuanian", "lt"),
/** 卢森堡语 */
LUXEMBOURGISH("luxembourgish", "lb"),
/** 卢旺达语 */
KINYARWANDA("kinyarwanda", "rw"),
/** 罗马尼亚语 */
ROMANIAN("romanian", "ro"),
/** 马尔加什语 */
MALAGASY("malagasy", "mg"),
/** 马耳他语 */
MALTESE("maltese", "mt"),
/** 马拉地语 */
MARATHI("marathi", "mr"),
/** 马拉雅拉姆语 */
MALAYALAM("malayalam", "ml"),
/** 马来语 */
MALAY("malay", "ms"),
/** 马其顿语 */
MACEDONIAN("macedonian", "mk"),
/** 毛利语 */
MAORI("maori", "mi"),
/** 蒙古语 */
MONGOLIAN("mongolian", "mn"),
/** 孟加拉语 */
BENGALI("bengali", "bn"),
/** 缅甸语 */
MYANMAR("myanmar", "my"),
/** 苗语 */
HMONG("hmong", "hmn"),
/** 南非科萨语 */
XHOSA("xhosa", "xh"),
/** 南非祖鲁语 */
ZULU("zulu", "zu"),
/** 尼泊尔语 */
NEPALI("nepali", "ne"),
/** 挪威语 */
NORWEGIAN("norwegian", "no"),
/** 旁遮普语 */
PUNJABI("punjabi", "pa"),
/** 葡萄牙语 */
PORTUGUESE("portuguese", "pt"),
/** 普什图语 */
PASHTO("pashto", "ps"),
/** 齐切瓦语 */
CHICHEWA("chichewa", "ny"),
/** 日语 */
JAPANESE("japanese", "ja"),
/** 瑞典语 */
SWEDISH("swedish", "sv"),
/** 萨摩亚语 */
SAMOAN("samoan", "sm"),
/** 塞尔维亚语 */
SERBIAN("serbian", "sr"),
/** 塞索托语 */
SESOTHO("sesotho", "st"),
/** 僧伽罗语 */
SINHALA("sinhala", "si"),
/** 世界语 */
ESPERANTO("esperanto", "eo"),
/** 斯洛伐克语 */
SLOVAK("slovak", "sk"),
/** 斯洛文尼亚语 */
SLOVENIAN("slovenian", "sl"),
/** 斯瓦希里语 */
SWAHILI("swahili", "sw"),
/** 苏格兰盖尔语 */
SCOTS_GAELIC("scotsGaelic", "gd"),
/** 宿务语 */
CEBUANO("cebuano", "ceb"),
/** 索马里语 */
SOMALI("somali", "so"),
/** 塔吉克语 */
TAJIK("tajik", "tg"),
/** 泰卢固语 */
TELUGU("telugu", "te"),
/** 泰米尔语 */
TAMIL("tamil", "ta"),
/** 泰语 */
THAI("thai", "th"),
/** 土耳其语 */
TURKISH("turkish", "tr"),
/** 土库曼语 */
TURKMEN("turkmen", "tk"),
/** 威尔士语 */
WELSH("welsh", "cy"),
/** 维吾尔语 */
UYGHUR("uyghur", "ug"),
/** 乌尔都语 */
URDU("urdu", "ur"),
/** 乌克兰语 */
UKRAINIAN("ukrainian", "uk"),
/** 乌兹别克语(乌孜别克语) */
UZBEK("uzbek", "uz"),
/** 西班牙语 */
SPANISH("spanish", "es"),
/** 希伯来语 */
HEBREW("hebrew", "iw"),
/** 希腊语 */
GREEK("greek", "el"),
/** 夏威夷语 */
HAWAIIAN("hawaiian", "haw"),
/** 信德语 */
SINDHI("sindhi", "sd"),
/** 匈牙利语 */
HUNGARIAN("hungarian", "hu"),
/** 修纳语 */
SHONA("shona", "sn"),
/** 亚美尼亚语 */
ARMENIAN("armenian", "hy"),
/** 伊博语 */
IGBO("igbo", "ig"),
/** 意大利语 */
ITALIAN("italian", "it"),
/** 意第绪语 */
YIDDISH("yiddish", "yi"),
/** 印地语 */
HINDI("hindi", "hi"),
/** 印尼巽他语 */
SUNDANESE("sundanese", "su"),
/** 印尼语 */
INDONESIAN("indonesian", "id"),
/** 印尼爪哇语 */
JAVANESE("javanese", "jw"),
/** 约鲁巴语 */
YORUBA("yoruba", "yo"),
/** 越南语 */
VIETNAMESE("vietnamese", "vi");
val langName: String = LanguageBundle.getMessage(langNameKey)
companion object {
private val cachedValues: List<Lang> by lazy { values().filter { it != UNKNOWN }.sortedBy { it.langName } }
private val mapping: Map<String, Lang> by lazy { values().asSequence().map { it.code to it }.toMap() }
val default: Lang
get() {
val dynamicBundleLanguage = (MyDynamicBundle.dynamicLocale ?: Locale.ENGLISH).language
val localeLanguage =
if (dynamicBundleLanguage != Locale.ENGLISH.language) dynamicBundleLanguage
else Locale.getDefault().language
return when (localeLanguage) {
Locale.CHINESE.language -> when (Locale.getDefault().country) {
"HK", "TW" -> CHINESE_TRADITIONAL
else -> CHINESE
}
else -> values().find { it.code.equals(localeLanguage, ignoreCase = true) } ?: ENGLISH
}
}
/**
* Returns the [language][Lang] corresponding to the given [code].
*/
operator fun get(code: String): Lang = mapping[code] ?: UNKNOWN
fun sortedValues(): List<Lang> = when (Locale.getDefault()) {
Locale.CHINESE,
Locale.CHINA -> values().filter { it != UNKNOWN }
else -> cachedValues
}
}
}
| mit | 0bb4aacded1a14e5826bcea7c047cf42 | 17.637931 | 115 | 0.485926 | 2.558147 | false | false | false | false |
YiiGuxing/TranslationPlugin | src/main/kotlin/cn/yiiguxing/plugin/translate/trans/text/NamedTranslationDocument.kt | 1 | 2521 | package cn.yiiguxing.plugin.translate.trans.text
import cn.yiiguxing.plugin.translate.ui.StyledViewer
import cn.yiiguxing.plugin.translate.util.text.appendString
import cn.yiiguxing.plugin.translate.util.text.getStyleOrAdd
import cn.yiiguxing.plugin.translate.util.text.setParagraphStyle
import com.intellij.ui.JBColor
import com.intellij.ui.scale.JBUIScale
import javax.swing.text.StyleConstants
import javax.swing.text.StyleContext
class NamedTranslationDocument(
val name: String,
val document: TranslationDocument
) : TranslationDocument {
override val text: String
get() = "$name\n${document.text}"
private fun appendName(viewer: StyledViewer) {
viewer.styledDocument.apply {
setParagraphStyle(style = TITLE_PARAGRAPH_STYLE)
if (length > 0) {
setParagraphStyle(style = TITLE_PARAGRAPH_STYLE2, replace = false)
}
appendString("$name\n", TITLE_STYLE)
setParagraphStyle(style = TITLE_END_PARAGRAPH_STYLE)
}
}
override fun applyTo(viewer: StyledViewer) {
viewer.initStyle()
appendName(viewer)
document.applyTo(viewer)
}
override fun toString(): String = text
companion object {
private const val TITLE_STYLE = "named_translation_document_title"
private const val TITLE_PARAGRAPH_STYLE = "named_translation_document_title_ps"
private const val TITLE_PARAGRAPH_STYLE2 = "named_translation_document_title_ps2"
private const val TITLE_END_PARAGRAPH_STYLE = "named_translation_document_title_eps"
private fun StyledViewer.initStyle() {
val styledDocument = styledDocument
val defaultStyle = getStyle(StyleContext.DEFAULT_STYLE)
styledDocument.getStyleOrAdd(TITLE_PARAGRAPH_STYLE, defaultStyle) { style ->
StyleConstants.setSpaceBelow(style, JBUIScale.scale(3f))
}
styledDocument.getStyleOrAdd(TITLE_PARAGRAPH_STYLE2, defaultStyle) { style ->
StyleConstants.setSpaceAbove(style, JBUIScale.scale(16f))
}
styledDocument.getStyleOrAdd(TITLE_END_PARAGRAPH_STYLE, defaultStyle) { style ->
StyleConstants.setSpaceAbove(style, 0f)
StyleConstants.setSpaceBelow(style, 0f)
}
styledDocument.getStyleOrAdd(TITLE_STYLE, defaultStyle) { style ->
StyleConstants.setForeground(style, JBColor(0x6E6E6E, 0xAFB1B3))
}
}
}
} | mit | a5ac0478bc7ac5c0dee9ff8321a820c6 | 38.40625 | 92 | 0.677509 | 4.43058 | false | false | false | false |
colinrtwhite/LicensesDialog | library/src/main/java/com/colinrtwhite/licensesdialog/LineWidthBreakTextView.kt | 1 | 983 | package com.colinrtwhite.licensesdialog
import android.content.Context
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatTextView
import kotlin.math.ceil
import kotlin.math.max
/**
* A TextView which wraps its width to the length of its longest line.
*/
internal class LineWidthBreakTextView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : AppCompatTextView(context, attrs, defStyleAttr) {
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
layout?.let {
val width = compoundPaddingLeft + computeMaxLineWidth() + compoundPaddingRight
setMeasuredDimension(max(width, minimumWidth), measuredHeight)
}
}
private fun computeMaxLineWidth(): Int {
var maxWidth = 0.0f
for (i in 0 until layout.lineCount) {
maxWidth = max(maxWidth, layout.getLineWidth(i))
}
return ceil(maxWidth.toDouble()).toInt()
}
} | apache-2.0 | 00d0cee55070ff1209f9a5cc177e190d | 27.941176 | 81 | 0.771109 | 3.96371 | false | false | false | false |
sugarmanz/Pandroid | app/src/main/java/com/jeremiahzucker/pandroid/request/json/v5/method/auth/PartnerLogin.kt | 1 | 779 | package com.jeremiahzucker.pandroid.request.json.v5.method.auth
import com.jeremiahzucker.pandroid.request.BaseMethod
/**
* Created by jzucker on 7/1/17.
* https://6xq.net/pandora-apidoc/json/authentication/#partner-login
*/
object PartnerLogin : BaseMethod() {
data class RequestBody(
val username: String = "android",
val password: String = "AC7IBG09A3DTSYM4R41UJWL07VLN8JI7",
val deviceModel: String = "android-generic",
val version: String = "5",
val includeUrls: Boolean? = null,
val returnDeviceType: Boolean? = null,
val returnUpdatePromptVersions: Boolean? = null
)
data class ResponseBody(
val syncTime: String,
val partnerId: String,
val partnerAuthToken: String
)
}
| mit | de6b892f558f367f141fd2975a8c1278 | 30.16 | 68 | 0.676508 | 3.727273 | false | false | false | false |
MaibornWolff/codecharta | analysis/import/MetricGardenerImporter/src/main/kotlin/de/maibornwolff/codecharta/importer/metricgardenerimporter/ParserDialog.kt | 1 | 1678 | package de.maibornwolff.codecharta.importer.metricgardenerimporter
import com.github.kinquirer.KInquirer
import com.github.kinquirer.components.promptConfirm
import com.github.kinquirer.components.promptInput
import de.maibornwolff.codecharta.tools.interactiveparser.ParserDialogInterface
class ParserDialog {
companion object : ParserDialogInterface {
override fun collectParserArgs(): List<String> {
val isJsonFile: Boolean =
KInquirer.promptConfirm(
message = "Do you already have a MetricGardener json-File?",
default = false
)
val inputFile = KInquirer.promptInput(
message = if (isJsonFile) "Which MetricGardener json-File do you want to import?"
else "What Project do you want to parse?",
hint = if (isJsonFile) "path/to/metricgardener/file.json" else "path/to/my/project"
)
val outputFileName: String = KInquirer.promptInput(
message = "What is the name of the output file? If empty, the result will be returned in the terminal",
hint = "path/to/output/filename.cc.json"
)
val isCompressed = (outputFileName.isEmpty()) || KInquirer.promptConfirm(
message = "Do you want to compress the output file?",
default = true
)
return listOfNotNull(
inputFile,
"--output-file=$outputFileName",
if (isCompressed) null else "--not-compressed",
if (isJsonFile) "--is-json-file" else null
)
}
}
}
| bsd-3-clause | d7ba72e51dd244beff80e764595d8875 | 38.952381 | 119 | 0.604887 | 5.27673 | false | false | false | false |
chrsep/Kingfish | app/src/main/java/com/directdev/portal/interactors/AuthInteractor.kt | 1 | 5906 | package com.directdev.portal.interactors
import com.directdev.portal.network.NetworkHelper
import com.directdev.portal.repositories.FlagRepository
import com.directdev.portal.repositories.TimeStampRepository
import com.directdev.portal.repositories.UserCredRepository
import com.directdev.portal.utils.SigninException
import io.reactivex.Single
import org.joda.time.Minutes
import java.net.URLDecoder
import java.net.URLEncoder
import javax.inject.Inject
import javax.inject.Named
/**-------------------------------------------------------------------------------------------------
* Handles everything related to authenticating with Binusmaya
*------------------------------------------------------------------------------------------------*/
class AuthInteractor @Inject constructor(
private val bimayApi: NetworkHelper,
private val userCredRepo: UserCredRepository,
private val flagRepo: FlagRepository,
@Named("auth") private val timeStampRepo: TimeStampRepository
) {
private var isRequesting = false
private lateinit var request: Single<String>
// Regex patterns to extract data from index.html and loader.js
private val loaderPattern = "<script src=\".*login/loader.*\""
private val fieldsPattern = "<input type=\"hidden\" name=\".*\" value=\".*\" />"
private val usernamePattern = "<input type=\"text\" name=\".*placeholder=\"Username\""
private val passwordPattern = "<input type=\"password\" name=\".*placeholder=\"Password\""
private val buttonPattern = "<input type=\"submit\" name=\".*value=\"Login\""
// Returns a Single containing the authenticated cookie
fun execute(
username: String = userCredRepo.getUsername(),
password: String = userCredRepo.getPassword()
): Single<String> {
if (!isSyncOverdue()) return Single.just(userCredRepo.getCookie())
var indexHtml = ""
var cookie = ""
request = if (isRequesting) request else bimayApi.getIndexHtml().flatMap {
val headerMap = it.headers().toMultimap()
indexHtml = it.body()?.string() ?: ""
cookie = headerMap["Set-Cookie"]?.reduce { acc, s -> "$acc; $s" } ?: ""
// Extracts the link to loader.php from index.html
val result = Regex(loaderPattern).find(indexHtml)?.value ?: ""
val serial = URLDecoder.decode(result.substring(40, result.length - 1), "UTF-8")
// Retrieve loader.js from loader.php
bimayApi.getLoaderJs(cookie, serial, "https://binusmaya.binus.ac.id/login/")
}.flatMap {
val loaderJs = it.body()?.string() ?: ""
val fieldsMap = constructFields(indexHtml, loaderJs, username, password)
// Authenticate with Binusmaya using the extracted fields from index.html & loader.js as
// the request parameter
bimayApi.authenticate(cookie, fieldsMap)
}.map {
// Checks if login is successful
val redirectLocation = it.headers().get("Location") ?: "none"
if (redirectLocation != "https://binusmaya.binus.ac.id/block_user.php")
throw SigninException(redirectLocation)
}.flatMap {
bimayApi.switchRole(cookie)
}.map {
cookie
}.doAfterSuccess {
userCredRepo.saveAll(username, password, cookie)
timeStampRepo.updateLastSyncDate()
flagRepo.save(isLoggedIn = true)
}.doAfterTerminate {
isRequesting = false
}
isRequesting = true
return request
}
fun resetLastSyncDate() = timeStampRepo.resetLastSyncDate()
/*----------------------------------------------------------------------------------------------
* To sign in, 4 fields are required:
* 1. Password field: randomized key, password as value (extracted from login page's Index.html)
* 2. Username field: randomized key, username as value (extracted from login page's Index.html)
* 3&4. Field with randomized key and value (extracted from loader.php, which returned a js file)
*
* The function below extracts all of this and combined them into one single HashMap.
*--------------------------------------------------------------------------------------------*/
private fun constructFields(
indexHtml: String,
loaderJs: String,
username: String,
password: String
): HashMap<String, String> {
val user = Regex(usernamePattern).find(indexHtml)?.value ?: ""
val pass = Regex(passwordPattern).find(indexHtml)?.value ?: ""
val button = Regex(buttonPattern).find(indexHtml)?.value ?: ""
val extraFields = Regex(fieldsPattern).findAll(loaderJs).toList()[0].value.split(" ")
val userStr = decodeHtml(user.substring(25, user.length - 45))
val passStr = decodeHtml(pass.substring(29, pass.length - 24))
val buttonStr = decodeHtml(button.substring(27, button.length - 15))
val fieldsMap = HashMap<String, String>()
fieldsMap[passStr] = password
fieldsMap[userStr] = username
fieldsMap[buttonStr] = "Login"
fieldsMap[decodeHtml(extraFields[2].substring(6, extraFields[2].length - 1))] = decodeHtml(extraFields[3].substring(7, extraFields[3].length - 1))
fieldsMap[decodeHtml(extraFields[6].substring(6, extraFields[6].length - 1))] = decodeHtml(extraFields[7].substring(7, extraFields[7].length - 1))
return fieldsMap
}
private fun decodeHtml(input: String) = URLDecoder.decode(input,"UTF-8")
// TODO: This is similar to the one from journalInteractor, might be able to be refactored out
fun isSyncOverdue(): Boolean {
val minutesInt = Minutes.minutesBetween(timeStampRepo.getLastSync(), timeStampRepo.today()).minutes
return Math.abs(minutesInt) > 25
}
} | gpl-3.0 | e9ca72ad8cbd747376aed65bc97568fd | 47.418033 | 154 | 0.61683 | 4.588967 | false | false | false | false |
eugeis/ee | ee-lang_item/src/main/kotlin/ee/lang/ItemApi.kt | 1 | 15648 | package ee.lang
import ee.common.ext.joinSurroundIfNotEmptyTo
import org.slf4j.LoggerFactory
import java.util.*
private val log = LoggerFactory.getLogger("ItemApi")
open class Item(adapt: Item.() -> Unit = {}) : ItemB<Item>(adapt)
@Suppress("UNCHECKED_CAST")
open class ItemB<B : ItemI<B>>(var _adapt: B.() -> Unit = {}) : ItemI<B> {
private var _name: String = ""
private var _namespace: String = ""
private var _doc: CommentI<*> = CommentEmpty
private var _parent: ItemI<*> = EMPTY
private var _internal: Boolean = false
private var _derivedFrom: ItemI<*> = EMPTY
private var _derivedItems: MutableList<ItemI<*>> = arrayListOf()
private var _derivedAsType: String = ""
private var _initialized: Boolean = false
protected var _adaptDerive: B.() -> Unit = {}
override fun init(): B {
if (!isInitialized()) {
_initialized = true
_adapt(this as B)
}
return this as B
}
override fun extendAdapt(adapt: B.() -> Unit): B {
val oldAdapt = _adapt
_adapt = {
oldAdapt()
adapt()
}
//if already initialized, we need to apply for current instance
if (isInitialized()) (this as B).adapt()
return this as B
}
override fun isInitialized(): Boolean = _initialized
override fun name(): String = _name
override fun name(value: String): B = apply { _name = value }
override fun namespace(): String = _namespace
override fun namespace(value: String): B = apply { _namespace = value }
override fun doc(): CommentI<*> = _doc
override fun doc(value: CommentI<*>): B = apply { _doc = value }
override fun parent(): ItemI<*> = _parent
override fun parent(value: ItemI<*>): B = apply { _parent = value }
override fun onDerived(derived: ItemI<*>) {
_derivedItems.add(derived)
}
override fun derivedItems(): List<ItemI<*>> = _derivedItems
override fun derivedFrom(): ItemI<*> = _derivedFrom
override fun derivedFrom(value: ItemI<*>): B = apply {
_derivedFrom = value
value.onDerived(this)
}
override fun derivedAsType(): String = _derivedAsType
override fun derivedAsType(value: String): B = apply { _derivedAsType = value }
override fun derive(adapt: B.() -> Unit): B {
init()
val ret = copy()
ret.derivedFrom(this)
ret.adapt()
//ret.extendAdapt(adapt)
return ret
}
override fun deriveWithParent(adapt: B.() -> Unit): B {
init()
val ret = copyWithParent()
ret.derivedFrom(this)
ret.adapt()
//ret.extendAdapt(adapt)
return ret
}
override fun deriveSubType(adapt: B.() -> Unit): B {
init()
val ret = createType()
if (ret != null) {
ret.name(name())
ret.derivedFrom(this)
ret.adapt()
//ret.extendAdapt(adapt)
ret.init()
if (ret is MultiHolderI<*, *>) {
ret.fillSupportsItems()
}
return ret
}
return this as B
}
override fun copy(): B {
val ret = createType()
return if (ret != null) {
ret.parent(EMPTY)
fill(ret)
if (ret is MultiHolderI<*, *>) {
ret.fillSupportsItems()
}
ret
} else {
log.debug("can't create a new instance of null.")
this as B
}
}
override fun copyWithParent(): B {
val ret = createType()
return if (ret != null) {
ret.parent(parent())
fill(ret)
if (ret is MultiHolderI<*, *>) {
ret.fillSupportsItems()
}
ret
} else {
log.debug("Can't create a new instance of null.")
this as B
}
}
protected open fun createType(): B? {
var ret = createType(javaClass)
if (ret == null) {
log.trace("can't create instance of '{}', try to use the superclass {}", javaClass, javaClass.superclass)
ret = createType(javaClass.superclass)
}
return ret
}
protected open fun createType(type: Class<*>): B? {
val constructor = type.constructors.find {
it.toString().contains("(kotlin.jvm.functions.Function1)")
}
if (constructor != null) return constructor.newInstance(_adaptDerive) as B
return null
}
protected open fun fill(item: B) {
item.init()
if (item.name().isEmpty()) item.name(_name)
if (item.namespace().isEmpty()) item.namespace(_namespace)
if (item.doc().isEMPTY()) {
val doc = _doc
item.doc(doc.copy())
}
}
override fun <T : ItemI<*>> apply(code: T.() -> Unit): T {
(this as T).code()
return this
}
override fun <R> applyAndReturn(code: () -> R): R = code()
override fun toDsl(builder: StringBuilder, indent: String) {
builder.append("$indent${name()}@${Integer.toHexString(hashCode())}")
}
override fun toDsl(): String {
val builder = StringBuilder()
toDsl(builder, "")
return builder.toString()
}
override fun isInternal(): Boolean = _internal
open fun internal(value: Boolean): ItemI<*> = apply { _internal = value }
companion object {
val EMPTY = ItemEmpty
}
}
@Suppress("UNCHECKED_CAST")
abstract class MultiHolder<I, B : MultiHolderI<I, B>>(private val _type: Class<I>, adapt: B.() -> Unit = {}) :
ItemB<B>(adapt), MultiHolderI<I, B> {
override fun init(): B {
if (!isInitialized()) super.init()
items().filterIsInstance<ItemI<*>>().forEach {
if (!it.isInitialized() || (it is MultiHolderI<*, *> && it.parent() == this)) {
it.init()
}
}
return this as B
}
override fun createType(type: Class<*>): B? {
var constructor = type.constructors.find {
it.toString().contains("(java.lang.Class,kotlin.jvm.functions.Function1)")
}
if (constructor != null) return constructor.newInstance(_type, _adaptDerive) as B
constructor = type.constructors.find {
it.toString().contains("(kotlin.jvm.functions.Function1)")
}
if (constructor != null) return constructor.newInstance(_adaptDerive) as B
return null
}
override fun <T : I> addItems(items: Collection<T>): B = apply { items.forEach { addItem(it) } }
override fun containsItem(item: I): Boolean = items().contains(item)
override fun <T> supportsItemType(itemType: Class<T>): Boolean = itemType.isAssignableFrom(_type)
override fun <T> supportsItem(item: T): Boolean = _type.isInstance(item)
fun itemType(): Class<I> = _type
protected fun fillThisOrNonInternalAsParentAndInit(child: I) {
if (child is ItemI<*>) {
if (child.parent().isEMPTY()) {
if (child.isInternal() || !this.isInternal()) {
child.parent(this)
} else {
child.parent(findParentNonInternal() ?: this)
}
if (isInitialized() && !child.isInitialized()) {
child.init()
} else {
if (child.namespace() == "" && parent().namespace() != "") {
if (child.javaClass.toString().contains("StructureUnit")) {
child.namespace(parent().namespace())
} else {
child.namespace(parent().namespace())
}
}
}
} else {
log.trace(
"can't set as parent '${this}(${this.name()})' to '$child(${child.name()})', because current parent is ${child.parent()}(${
child.parent().name()
})"
)
}
}
}
override fun <T> fillSupportsItem(item: T): Boolean {
if (supportsItem(item) && !containsItem(item as I)) {
addItem(item)
return true
}
return false
}
override fun fillSupportsItems() {
val items = items().filterIsInstance<ItemI<*>>()
val plainItems = items.filter { !it.name().startsWith("_") }
val containers = items.filterIsInstance<MultiHolderI<*, *>>().filter {
it.name().startsWith("_") && !it.name().startsWith("__")
}
plainItems.forEach { plainItem ->
containers.forEach { container -> container.fillSupportsItem(plainItem) }
}
}
//renderer
override fun toDsl(builder: StringBuilder, indent: String) {
super.toDsl(builder, indent)
toDslChildren(builder, indent)
}
open fun toDslChildren(builder: StringBuilder, indent: String) {
items().joinSurroundIfNotEmptyTo(builder, "", " {\n", "$indent}") {
if (it is ItemI<*>) {
it.toDsl(builder, "$indent ")
"\n"
} else {
"$it"
}
}
}
}
@Suppress("UNCHECKED_CAST")
open class ListMultiHolder<I>(_type: Class<I>, adapt: ListMultiHolder<I>.() -> Unit = {}) :
ListMultiHolderB<I, ListMultiHolder<I>>(_type, adapt) {
companion object {
fun <I> empty(): ListMultiHolder<I> = ListMultiHolder(Any::class.java) as ListMultiHolder<I>
}
}
@Suppress("UNCHECKED_CAST")
open class ListMultiHolderB<I, B : ListMultiHolderI<I, B>>(
_type: Class<I>, value: B.() -> Unit = {},
private val _items: MutableList<I> = arrayListOf()
) : MultiHolder<I, B>(_type, value), ListMultiHolderI<I, B>,
MutableList<I> by _items {
override fun <T : I> addItem(item: T): T {
fillThisOrNonInternalAsParentAndInit(item)
_items.add(item)
return item
}
override fun items(): Collection<I> = _items
override fun createType(type: Class<*>): B? {
var constructor = type.constructors.find {
it.toString().contains("(java.lang.Class,kotlin.jvm.functions.Function1,java.util.List)")
}
if (constructor != null) return constructor.newInstance(itemType(), _adaptDerive, ArrayList<I>()) as B
constructor = type.constructors.find {
it.toString().contains("(java.lang.Class,kotlin.jvm.functions.Function1)")
}
if (constructor != null) return constructor.newInstance(itemType(), _adaptDerive) as B
constructor = type.constructors.find {
it.toString().contains("(kotlin.jvm.functions.Function1)")
}
if (constructor != null) return constructor.newInstance(_adaptDerive) as B
return null
}
override fun fill(item: B) {
super.fill(item)
val itemToFill = item as ListMultiHolderI<I, B>
_items.forEach {
if (it is ItemI<*> && it.parent() == this) {
itemToFill.addItem(it.copy() as I)
} else if (it is ItemI<*> && it.parent() == this.parent()) {
//don't need to copy, because it will be grouped by fillSupported
} else {
itemToFill.addItem(it)
}
}
}
companion object {
fun <I> empty(): ListMultiHolder<I> = ListMultiHolder(Any::class.java) as ListMultiHolder<I>
}
}
open class MapMultiHolder<I>(_type: Class<I>, adapt: MapMultiHolder<I>.() -> Unit = {}) :
MapMultiHolderB<I, MapMultiHolder<I>>(_type, adapt)
@Suppress("UNCHECKED_CAST")
open class MapMultiHolderB<I, B : MapMultiHolderI<I, B>>(
_type: Class<I>, adapt: B.() -> Unit = {},
private val _items: MutableMap<String, I> = TreeMap()
) : MultiHolder<I, B>(_type, adapt), MapMultiHolderI<I, B> {
override fun <T : I> addItem(item: T): T {
if (item is ItemI<*>) {
addItem(item.name(), item)
} else {
fillThisOrNonInternalAsParentAndInit(item)
_items[item.toString()] = item
}
return item
}
override fun removeItem(childName: String) {
_items.remove(childName)
}
override fun <T : I> addItem(childName: String, item: T): T {
fillThisOrNonInternalAsParentAndInit(item)
_items[childName] = item
return item
}
override fun items(): Collection<I> = _items.values
override fun itemsMap(): Map<String, I> = _items
open fun <T : I> item(name: String): T? {
val ret = _items[name]
return if (ret != null) ret as T else null
}
open fun <T : I> item(name: String, internal: Boolean, factory: () -> T): T {
val ret = _items[name]
return if (ret == null) {
val item = factory()
if (item is ItemB<*>) {
item.internal(internal)
}
addItem(name, item)
} else {
ret as T
}
}
override fun createType(type: Class<*>): B? {
var constructor = type.constructors.find {
it.toString().contains("(java.lang.Class,kotlin.jvm.functions.Function1,java.util.Map)")
}
if (constructor != null) return constructor.newInstance(itemType(), _adaptDerive, TreeMap<String, I>()) as B
constructor = type.constructors.find {
it.toString().contains("(java.lang.Class,kotlin.jvm.functions.Function1)")
}
if (constructor != null) return constructor.newInstance(itemType(), _adaptDerive) as B
constructor = type.constructors.find {
it.toString().contains("(kotlin.jvm.functions.Function1)")
}
if (constructor != null) return constructor.newInstance(_adaptDerive) as B
return null
}
override fun fill(item: B) {
super.fill(item)
val itemToFill = item as MapMultiHolderI<I, B>
_items.forEach {
val value = it.value
if (value is ItemI<*> && value.parent() == this) {
itemToFill.addItem(it.key, value.copy() as I)
} else {
itemToFill.addItem(it.key, value)
}
}
}
}
open class Composite(adapt: Composite.() -> Unit = {}) : CompositeB<Composite>(adapt)
open class CompositeB<B : CompositeI<B>>(adapt: B.() -> Unit = {}) :
MapMultiHolderB<ItemI<*>, B>(ItemI::class.java, adapt), CompositeI<B> {
open fun <R> itemAsMap(
name: String, type: Class<R>, attachParent: Boolean = false,
internal: Boolean = false
): MapMultiHolderB<R, *> {
return item(name, internal) { MapMultiHolder(type) { name(name) } }
}
open fun <R> itemAsList(name: String, type: Class<R>, internal: Boolean = false): ListMultiHolder<R> {
return item(name, internal) { ListMultiHolder(type) { name(name) } }
}
open fun <T : Any> attr(name: String): T? = attributes().item(name)
open fun <T : Any> attr(name: String, factory: () -> T, attachParent: Boolean = false): T =
attributes().item(name, false, factory)
override fun <T : Any> attr(name: String, attr: T?): T? {
if (attr != null) {
attributes().addItem(name, attr)
} else {
attributes().removeItem(name)
}
return attr
}
override fun attributes(): MapMultiHolderB<Any, *> = itemAsMap(
"__attributes",
Any::class.java, attachParent = true, internal = true
)
}
open class Comment(adapt: Comment.() -> Unit = {}) : ListMultiHolderB<String, Comment>(String::class.java, adapt),
CommentI<Comment> | apache-2.0 | 065105dd90f67c7a237b15ae6108a71e | 30.360721 | 143 | 0.556876 | 4.13094 | false | false | false | false |
lanhuaguizha/Christian | common/src/main/java/com/christian/common/data/source/remote/GospelRemoteDataSource.kt | 1 | 4804 | package com.christian.common.data.source.remote
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.map
import com.christian.common.GOSPELS
import com.christian.common.GOSPEL_EN
import com.christian.common.GOSPEL_ZH
import com.christian.common.data.Gospel
import com.christian.common.data.Result
import com.christian.common.data.source.GospelDataSource
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.FirebaseFirestoreSettings
import com.google.firebase.firestore.ktx.toObject
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine
class GospelRemoteDataSource : GospelDataSource {
private val observableWritings = MutableLiveData<Result<List<Gospel>>>()
private var firebaseFirestore: FirebaseFirestore = FirebaseFirestore.getInstance()
init {
val settings = FirebaseFirestoreSettings.Builder()
.setPersistenceEnabled(true)
.build()
firebaseFirestore.firestoreSettings = settings
}
// Insert
override suspend fun saveGospel(gospel: Gospel, selectedLanguage: String): Result<Void>? {
val gospels = when {
selectedLanguage.contains("en_") -> GOSPEL_EN
selectedLanguage.contains("zh_") -> GOSPEL_ZH
else -> GOSPELS
}
return suspendCoroutine { continuation ->
firebaseFirestore.collection(gospels).document(gospel.gospelId)
.set(gospel).addOnSuccessListener {
continuation.resume(Result.Success(it))
}.addOnFailureListener {
continuation.resume(Result.Error(it))
}
}
}
// Delete
override suspend fun clearCompletedWritings() {
// WRITINGS_CACHE_DATA = WRITINGS_CACHE_DATA.filterValues {
// !it.isCompleted
// } as LinkedHashMap<String, Writing>
}
// Update
// Query
override suspend fun getGospel(writingId: String): Result<Gospel> {
// Simulate network by delaying the execution.
return suspendCoroutine { continuation ->
firebaseFirestore.collection(GOSPELS).document(writingId).get().addOnSuccessListener {
it.toObject<Gospel>()?.let { it1 -> continuation.resume(Result.Success(it1)) }
}
}
}
override suspend fun deleteAllWritings() {
// WRITINGS_CACHE_DATA.clear()
}
override suspend fun deleteWriting(writingId: String, selectedLanguage: String): Result<Void>? {
val gospels = when {
selectedLanguage.contains("zh_") -> GOSPEL_EN
selectedLanguage.contains("en_") -> GOSPEL_ZH
else -> GOSPELS
}
return suspendCoroutine { continuation ->
firebaseFirestore.collection(gospels).document(writingId)
.delete().addOnSuccessListener {
continuation.resume(Result.Success(it))
}.addOnFailureListener {
continuation.resume(Result.Error(it))
}
}
}
// Update
override suspend fun completeWriting(gospel: Gospel) {
// val completedTask = Writing(writing.title, writing.description, true, writing.id)
// TASKS_SERVICE_DATA[writing.id] = completedTask
}
override suspend fun completeWriting(writingId: String) {
// Not required for the remote data source
}
override suspend fun activateWriting(gospel: Gospel) {
// val activeTask = Writing(writing.title, writing.description, false, writing.id)
// TASKS_SERVICE_DATA[writing.id] = activeTask
}
override suspend fun activateWriting(writingId: String) {
// Not required for the remote data source
}
// Query
override fun observeWritings(): LiveData<Result<List<Gospel>>> {
return observableWritings
}
override fun observeWriting(writingId: String): LiveData<Result<Gospel>> {
return observableWritings.map { writings ->
when (writings) {
is Result.Loading -> Result.Loading
is Result.Error -> Result.Error(writings.exception)
is Result.Success -> {
val writing = writings.data.firstOrNull() { it.gospelId == writingId }
?: return@map Result.Error(Exception("Not found"))
Result.Success(writing)
}
}
}
}
override suspend fun getGospels(): Result<List<Gospel>> {
TODO("Not yet implemented")
}
override suspend fun refreshWritings() {
// observableWritings.value = getWritings()
}
override suspend fun refreshWriting(writingId: String) {
refreshWritings()
}
} | gpl-3.0 | 3e7173aadd4343d854d90b1a514910f3 | 34.592593 | 100 | 0.64259 | 4.66861 | false | false | false | false |
google/horologist | media-ui/src/androidTest/java/com/google/android/horologist/media/ui/components/PlayPauseProgressButtonTest.kt | 1 | 3756 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.
*/
@file:OptIn(ExperimentalHorologistMediaUiApi::class)
package com.google.android.horologist.media.ui.components
import androidx.compose.ui.semantics.ProgressBarRangeInfo
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.hasAnyChild
import androidx.compose.ui.test.hasContentDescription
import androidx.compose.ui.test.hasProgressBarRangeInfo
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.performClick
import androidx.test.filters.FlakyTest
import com.google.android.horologist.media.ui.ExperimentalHorologistMediaUiApi
import com.google.android.horologist.test.toolbox.matchers.hasProgressBar
import org.junit.Rule
import org.junit.Test
@FlakyTest(detail = "https://github.com/google/horologist/issues/407")
class PlayPauseProgressButtonTest {
@get:Rule
val composeTestRule = createComposeRule()
@Test
fun givenIsPlaying_thenPauseButtonIsDisplayed() {
// given
var clicked = false
composeTestRule.setContent {
PlayPauseProgressButton(
onPlayClick = {},
onPauseClick = { clicked = true },
enabled = true,
playing = true,
percent = 0f
)
}
// then
composeTestRule.onNode(hasProgressBar())
.assertExists()
composeTestRule.onNode(hasAnyChild(hasContentDescription("Pause")))
.assertIsDisplayed()
.performClick()
// assert that the click event was assigned to the correct button
composeTestRule.waitUntil(timeoutMillis = 1_000) { clicked }
composeTestRule.onNode(hasAnyChild(hasContentDescription("Play")))
.assertDoesNotExist()
}
@Test
fun givenIsNOTPlaying_thenPlayButtonIsDisplayed() {
// given
var clicked = false
composeTestRule.setContent {
PlayPauseProgressButton(
onPlayClick = { clicked = true },
onPauseClick = {},
enabled = true,
playing = false,
percent = 0f
)
}
// then
composeTestRule.onNode(hasProgressBar())
.assertExists()
composeTestRule.onNode(hasAnyChild(hasContentDescription("Play")))
.assertIsDisplayed()
.performClick()
// assert that the click event was assigned to the correct button
composeTestRule.waitUntil(timeoutMillis = 1_000) { clicked }
composeTestRule.onNode(hasAnyChild(hasContentDescription("Pause")))
.assertDoesNotExist()
}
@Test
fun givenPercentIsNan_thenProgressIsZero() {
// given
composeTestRule.setContent {
PlayPauseProgressButton(
onPlayClick = {},
onPauseClick = {},
enabled = true,
playing = false,
percent = Float.NaN
)
}
// then
composeTestRule.onNode(hasProgressBarRangeInfo(ProgressBarRangeInfo(0f, 0.0f..1.0f)))
.assertIsDisplayed()
}
}
| apache-2.0 | bb5d2dab7141b9e422212658bbba8807 | 31.66087 | 93 | 0.651225 | 5.082544 | false | true | false | false |
googlemaps/android-samples | ApiDemos/kotlin/app/src/gms/java/com/example/kotlindemos/MyLocationDemoActivity.kt | 1 | 6975 | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.example.kotlindemos
import android.Manifest
import android.annotation.SuppressLint
import android.content.pm.PackageManager
import android.location.Location
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.app.ActivityCompat.OnRequestPermissionsResultCallback
import androidx.core.content.ContextCompat
import com.example.kotlindemos.PermissionUtils.PermissionDeniedDialog.Companion.newInstance
import com.example.kotlindemos.PermissionUtils.isPermissionGranted
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.GoogleMap.OnMyLocationButtonClickListener
import com.google.android.gms.maps.GoogleMap.OnMyLocationClickListener
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.SupportMapFragment
/**
* This demo shows how GMS Location can be used to check for changes to the users location. The
* "My Location" button uses GMS Location to set the blue dot representing the users location.
* Permission for [Manifest.permission.ACCESS_FINE_LOCATION] and [Manifest.permission.ACCESS_COARSE_LOCATION]
* are requested at run time. If either permission is not granted, the Activity is finished with an error message.
*/
class MyLocationDemoActivity : AppCompatActivity(),
OnMyLocationButtonClickListener,
OnMyLocationClickListener, OnMapReadyCallback,
OnRequestPermissionsResultCallback {
/**
* Flag indicating whether a requested permission has been denied after returning in
* [.onRequestPermissionsResult].
*/
private var permissionDenied = false
private lateinit var map: GoogleMap
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.my_location_demo)
val mapFragment =
supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragment?
mapFragment?.getMapAsync(this)
}
override fun onMapReady(googleMap: GoogleMap) {
map = googleMap
googleMap.setOnMyLocationButtonClickListener(this)
googleMap.setOnMyLocationClickListener(this)
enableMyLocation()
}
/**
* Enables the My Location layer if the fine location permission has been granted.
*/
@SuppressLint("MissingPermission")
private fun enableMyLocation() {
// [START maps_check_location_permission]
// 1. Check if permissions are granted, if so, enable the my location layer
if (ContextCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_FINE_LOCATION
) == PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_COARSE_LOCATION
) == PackageManager.PERMISSION_GRANTED
) {
map.isMyLocationEnabled = true
return
}
// 2. If if a permission rationale dialog should be shown
if (ActivityCompat.shouldShowRequestPermissionRationale(
this,
Manifest.permission.ACCESS_FINE_LOCATION
) || ActivityCompat.shouldShowRequestPermissionRationale(
this,
Manifest.permission.ACCESS_COARSE_LOCATION
)
) {
PermissionUtils.RationaleDialog.newInstance(
LOCATION_PERMISSION_REQUEST_CODE, true
).show(supportFragmentManager, "dialog")
return
}
// 3. Otherwise, request permission
ActivityCompat.requestPermissions(
this,
arrayOf(
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION
),
LOCATION_PERMISSION_REQUEST_CODE
)
// [END maps_check_location_permission]
}
override fun onMyLocationButtonClick(): Boolean {
Toast.makeText(this, "MyLocation button clicked", Toast.LENGTH_SHORT)
.show()
// Return false so that we don't consume the event and the default behavior still occurs
// (the camera animates to the user's current position).
return false
}
override fun onMyLocationClick(location: Location) {
Toast.makeText(this, "Current location:\n$location", Toast.LENGTH_LONG)
.show()
}
// [START maps_check_location_permission_result]
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray
) {
if (requestCode != LOCATION_PERMISSION_REQUEST_CODE) {
super.onRequestPermissionsResult(
requestCode,
permissions,
grantResults
)
return
}
if (isPermissionGranted(
permissions,
grantResults,
Manifest.permission.ACCESS_FINE_LOCATION
) || isPermissionGranted(
permissions,
grantResults,
Manifest.permission.ACCESS_COARSE_LOCATION
)
) {
// Enable the my location layer if the permission has been granted.
enableMyLocation()
} else {
// Permission was denied. Display an error message
// [START_EXCLUDE]
// Display the missing permission error dialog when the fragments resume.
permissionDenied = true
// [END_EXCLUDE]
}
}
// [END maps_check_location_permission_result]
override fun onResumeFragments() {
super.onResumeFragments()
if (permissionDenied) {
// Permission was not granted, display error dialog.
showMissingPermissionError()
permissionDenied = false
}
}
/**
* Displays a dialog with error message explaining that the location permission is missing.
*/
private fun showMissingPermissionError() {
newInstance(true).show(supportFragmentManager, "dialog")
}
companion object {
/**
* Request code for location permission request.
*
* @see .onRequestPermissionsResult
*/
private const val LOCATION_PERMISSION_REQUEST_CODE = 1
}
} | apache-2.0 | 2b32f26380bdc24d5eff980b84d8cf79 | 36.505376 | 114 | 0.66681 | 5.411171 | false | false | false | false |
wordpress-mobile/WordPress-FluxC-Android | example/src/test/java/org/wordpress/android/fluxc/wc/shippinglabels/WCShippingLabelStoreTest.kt | 1 | 35713 | package org.wordpress.android.fluxc.wc.shippinglabels
import com.yarolegovich.wellsql.WellSql
import org.assertj.core.api.Assertions.assertThat
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.kotlin.any
import org.mockito.kotlin.anyOrNull
import org.mockito.kotlin.mock
import org.mockito.kotlin.times
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import org.robolectric.shadows.ShadowLooper
import org.wordpress.android.fluxc.SingleStoreWellSqlConfigForTests
import org.wordpress.android.fluxc.TestSiteSqlUtils
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.model.shippinglabels.WCAddressVerificationResult
import org.wordpress.android.fluxc.model.shippinglabels.WCAddressVerificationResult.Valid
import org.wordpress.android.fluxc.model.shippinglabels.WCPackagesResult
import org.wordpress.android.fluxc.model.shippinglabels.WCPackagesResult.CustomPackage
import org.wordpress.android.fluxc.model.shippinglabels.WCPackagesResult.PredefinedOption
import org.wordpress.android.fluxc.model.shippinglabels.WCPackagesResult.PredefinedOption.PredefinedPackage
import org.wordpress.android.fluxc.model.shippinglabels.WCPaymentMethod
import org.wordpress.android.fluxc.model.shippinglabels.WCShippingAccountSettings
import org.wordpress.android.fluxc.model.shippinglabels.WCShippingLabelCreationEligibility
import org.wordpress.android.fluxc.model.shippinglabels.WCShippingLabelMapper
import org.wordpress.android.fluxc.model.shippinglabels.WCShippingLabelModel
import org.wordpress.android.fluxc.model.shippinglabels.WCShippingLabelModel.ShippingLabelAddress
import org.wordpress.android.fluxc.model.shippinglabels.WCShippingLabelModel.ShippingLabelAddress.Type.DESTINATION
import org.wordpress.android.fluxc.model.shippinglabels.WCShippingLabelModel.ShippingLabelAddress.Type.ORIGIN
import org.wordpress.android.fluxc.model.shippinglabels.WCShippingLabelModel.ShippingLabelPackage
import org.wordpress.android.fluxc.model.shippinglabels.WCShippingLabelPackageData
import org.wordpress.android.fluxc.model.shippinglabels.WCShippingRatesResult
import org.wordpress.android.fluxc.model.shippinglabels.WCShippingRatesResult.ShippingOption
import org.wordpress.android.fluxc.model.shippinglabels.WCShippingRatesResult.ShippingPackage
import org.wordpress.android.fluxc.network.BaseRequest.GenericErrorType.NETWORK_ERROR
import org.wordpress.android.fluxc.network.BaseRequest.GenericErrorType.UNKNOWN
import org.wordpress.android.fluxc.network.rest.wpcom.wc.WooError
import org.wordpress.android.fluxc.network.rest.wpcom.wc.WooErrorType.GENERIC_ERROR
import org.wordpress.android.fluxc.network.rest.wpcom.wc.WooErrorType.INVALID_RESPONSE
import org.wordpress.android.fluxc.network.rest.wpcom.wc.WooPayload
import org.wordpress.android.fluxc.network.rest.wpcom.wc.WooResult
import org.wordpress.android.fluxc.network.rest.wpcom.wc.shippinglabels.LabelItem
import org.wordpress.android.fluxc.network.rest.wpcom.wc.shippinglabels.SLCreationEligibilityApiResponse
import org.wordpress.android.fluxc.network.rest.wpcom.wc.shippinglabels.ShippingLabelRestClient
import org.wordpress.android.fluxc.network.rest.wpcom.wc.shippinglabels.ShippingLabelRestClient.ShippingRatesApiResponse.ShippingOption.Rate
import org.wordpress.android.fluxc.network.rest.wpcom.wc.shippinglabels.ShippingLabelRestClient.VerifyAddressResponse
import org.wordpress.android.fluxc.persistence.WellSqlConfig
import org.wordpress.android.fluxc.store.WCShippingLabelStore
import org.wordpress.android.fluxc.test
import org.wordpress.android.fluxc.tools.initCoroutineEngine
import java.math.BigDecimal
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
@Suppress("LargeClass")
@Config(manifest = Config.NONE)
@RunWith(RobolectricTestRunner::class)
class WCShippingLabelStoreTest {
private val restClient = mock<ShippingLabelRestClient>()
private val orderId = 25L
private val refundShippingLabelId = 12L
private val site = SiteModel().apply { id = 321 }
private val errorSite = SiteModel().apply { id = 123 }
private val mapper = WCShippingLabelMapper()
private lateinit var store: WCShippingLabelStore
private val sampleShippingLabelApiResponse = WCShippingLabelTestUtils.generateSampleShippingLabelApiResponse()
private val error = WooError(INVALID_RESPONSE, NETWORK_ERROR, "Invalid site ID")
private val printPaperSize = "label"
private val samplePrintShippingLabelApiResponse =
WCShippingLabelTestUtils.generateSamplePrintShippingLabelApiResponse()
private val address = ShippingLabelAddress(country = "CA", address = "1370 Lewisham Dr.")
private val successfulVerifyAddressApiResponse = VerifyAddressResponse(
isSuccess = true,
isTrivialNormalization = false,
suggestedAddress = address,
error = null
)
private val samplePackagesApiResponse = WCShippingLabelTestUtils.generateSampleGetPackagesApiResponse()
private val sampleAccountSettingsApiResponse = WCShippingLabelTestUtils.generateSampleAccountSettingsApiResponse()
private val sampleShippingRatesApiResponse = WCShippingLabelTestUtils.generateSampleGetShippingRatesApiResponse()
private val samplePurchaseShippingLabelsResponse =
WCShippingLabelTestUtils.generateSamplePurchaseShippingLabelsApiResponse()
private val originAddress = ShippingLabelAddress(
"Company",
"Ondrej Ruttkay",
"",
"US",
"NY",
"42 Jewel St.",
"",
"Brooklyn",
"11222"
)
private val destAddress = ShippingLabelAddress(
"Company",
"Ondrej Ruttkay",
"",
"US",
"NY",
"82 Jewel St.",
"",
"Brooklyn",
"11222"
)
private val packages = listOf(
ShippingLabelPackage(
"Krabka 1",
"medium_flat_box_top",
10f,
10f,
10f,
10f,
false
),
ShippingLabelPackage(
"Krabka 2",
"medium_flat_box_side",
5f,
5f,
5f,
5f,
false
)
)
private val purchaseLabelPackagesData = listOf(
WCShippingLabelPackageData(
id = "id1",
boxId = "medium_flat_box_top",
isLetter = false,
height = 10f,
width = 10f,
length = 10f,
weight = 10f,
shipmentId = "shp_id",
rateId = "rate_id",
serviceId = "service-1",
serviceName = "USPS - Priority Mail International label",
carrierId = "usps",
products = listOf(10)
)
)
private val sampleListOfOneCustomPackage = listOf(
CustomPackage(
"Package 1",
false,
"10 x 10 x 10",
1.0f
)
)
private val sampleListOfOnePredefinedPackage = listOf(
PredefinedOption(
title = "USPS Priority Mail Flat Rate Boxes",
carrier = "usps",
predefinedPackages = listOf(
PredefinedPackage(
id = "small_flat_box",
title = "Small Flat Box",
isLetter = false,
dimensions = "10 x 10 x 10",
boxWeight = 1.0f
)
)
)
)
@Before
fun setUp() {
val appContext = RuntimeEnvironment.application.applicationContext
val config = SingleStoreWellSqlConfigForTests(
appContext,
listOf(
SiteModel::class.java,
WCShippingLabelModel::class.java,
WCShippingLabelCreationEligibility::class.java
),
WellSqlConfig.ADDON_WOOCOMMERCE
)
WellSql.init(config)
config.reset()
store = WCShippingLabelStore(
restClient,
initCoroutineEngine(),
mapper
)
// Insert the site into the db so it's available later when testing shipping labels
TestSiteSqlUtils.siteSqlUtils.insertOrUpdateSite(site)
}
@Test
fun `fetch shipping labels for order`() = test {
val result = fetchShippingLabelsForOrder()
val shippingLabelModels = mapper.map(sampleShippingLabelApiResponse!!, site)
assertThat(result.model?.size).isEqualTo(shippingLabelModels.size)
assertThat(result.model?.first()?.remoteOrderId).isEqualTo(shippingLabelModels.first().remoteOrderId)
assertThat(result.model?.first()?.localSiteId).isEqualTo(shippingLabelModels.first().localSiteId)
assertThat(result.model?.first()?.remoteShippingLabelId)
.isEqualTo(shippingLabelModels.first().remoteShippingLabelId)
assertThat(result.model?.first()?.carrierId).isEqualTo(shippingLabelModels.first().carrierId)
assertThat(result.model?.first()?.packageName).isEqualTo(shippingLabelModels.first().packageName)
assertThat(result.model?.first()?.refundableAmount).isEqualTo(shippingLabelModels.first().refundableAmount)
assertThat(result.model?.first()?.rate).isEqualTo(shippingLabelModels.first().rate)
assertThat(result.model?.first()?.getProductNameList()?.size)
.isEqualTo(shippingLabelModels.first().getProductNameList().size)
assertThat(result.model?.first()?.getProductIdsList()?.size)
.isEqualTo(shippingLabelModels.first().getProductIdsList().size)
assertThat(result.model?.get(1)?.getProductIdsList()?.size).isEqualTo(0)
assertNotNull(result.model?.first()?.refund)
val invalidRequestResult = store.fetchShippingLabelsForOrder(errorSite, orderId)
assertThat(invalidRequestResult.model).isNull()
assertThat(invalidRequestResult.error).isEqualTo(error)
}
@Test
fun `get stored shipping labels for order`() = test {
fetchShippingLabelsForOrder()
val storedShippingLabelsList = store.getShippingLabelsForOrder(site, orderId)
val shippingLabelModels = mapper.map(sampleShippingLabelApiResponse!!, site)
assertThat(storedShippingLabelsList.size).isEqualTo(shippingLabelModels.size)
assertThat(storedShippingLabelsList.first().remoteOrderId).isEqualTo(shippingLabelModels.first().remoteOrderId)
assertThat(storedShippingLabelsList.first().localSiteId).isEqualTo(shippingLabelModels.first().localSiteId)
assertThat(storedShippingLabelsList.first().remoteShippingLabelId)
.isEqualTo(shippingLabelModels.first().remoteShippingLabelId)
assertThat(storedShippingLabelsList.first().carrierId).isEqualTo(shippingLabelModels.first().carrierId)
assertThat(storedShippingLabelsList.first().packageName).isEqualTo(shippingLabelModels.first().packageName)
assertThat(storedShippingLabelsList.first().refundableAmount)
.isEqualTo(shippingLabelModels.first().refundableAmount)
assertThat(storedShippingLabelsList.first().rate).isEqualTo(shippingLabelModels.first().rate)
assertNotNull(storedShippingLabelsList.first().refund)
assertThat(storedShippingLabelsList.first().getProductNameList().size)
.isEqualTo(shippingLabelModels.first().getProductNameList().size)
assertThat(storedShippingLabelsList.first().getProductIdsList().size)
.isEqualTo(shippingLabelModels.first().getProductIdsList().size)
assertThat(storedShippingLabelsList[1].getProductIdsList().size).isEqualTo(0)
val invalidRequestResult = store.getShippingLabelsForOrder(errorSite, orderId)
assertThat(invalidRequestResult.size).isEqualTo(0)
}
@Test
fun `refund shipping label for order`() = test {
val result = refundShippingLabelForOrder()
assertTrue(result.model!!)
val invalidRequestResult = store.refundShippingLabelForOrder(errorSite, orderId, refundShippingLabelId)
assertThat(invalidRequestResult.model).isNull()
assertThat(invalidRequestResult.error).isEqualTo(error)
}
@Test
fun `print shipping label for order`() = test {
val result = printShippingLabelForOrder()
assertThat(result.model).isEqualTo(samplePrintShippingLabelApiResponse?.b64Content)
val invalidRequestResult = store.printShippingLabel(errorSite, printPaperSize, refundShippingLabelId)
assertThat(invalidRequestResult.model).isNull()
assertThat(invalidRequestResult.error).isEqualTo(error)
}
@Test
fun `verify shipping address`() = test {
val result = verifyAddress(ORIGIN)
assertThat(result.model).isEqualTo(Valid(address, successfulVerifyAddressApiResponse.isTrivialNormalization))
val invalidRequestResult = verifyAddress(DESTINATION)
assertThat(invalidRequestResult.model).isNull()
assertThat(invalidRequestResult.error).isEqualTo(error)
}
@Test
@Suppress("LongMethod")
fun `get shipping rates`() = test {
val expectedRatesResult = WCShippingRatesResult(
listOf(
ShippingPackage(
"default_box",
listOf(
ShippingOption(
"default",
listOf(
Rate(
title = "USPS - Media Mail",
insurance = "100",
rate = BigDecimal(3.5),
rateId = "rate_cb976896a09c4171a93ace57ed66ce5b",
serviceId = "MediaMail",
carrierId = "usps",
shipmentId = "shp_0a9b3ff983c6427eaf1e24cb344de36a",
hasTracking = false,
retailRate = BigDecimal(3.5),
isSelected = false,
isPickupFree = false,
deliveryDays = 2,
deliveryDateGuaranteed = false,
deliveryDate = null
),
Rate(
title = "FedEx - Ground",
insurance = "100",
rate = BigDecimal(21.5),
rateId = "rate_1b202bd43a8c4c929c73bb46989ef745",
serviceId = "FEDEX_GROUND",
carrierId = "fedex",
shipmentId = "shp_0a9b3ff983c6427eaf1e24cb344de36a",
hasTracking = false,
retailRate = BigDecimal(21.5),
isSelected = false,
isPickupFree = false,
deliveryDays = 1,
deliveryDateGuaranteed = true,
deliveryDate = null
)
)
),
ShippingOption(
"with_signature",
listOf(
Rate(
title = "USPS - Media Mail",
insurance = "100",
rate = BigDecimal(13.5),
rateId = "rate_cb976896a09c4171a93ace57ed66ce5b",
serviceId = "MediaMail",
carrierId = "usps",
shipmentId = "shp_0a9b3ff983c6427eaf1e24cb344de36a",
hasTracking = true,
retailRate = BigDecimal(13.5),
isSelected = false,
isPickupFree = true,
deliveryDays = 2,
deliveryDateGuaranteed = false,
deliveryDate = null
),
Rate(
title = "FedEx - Ground",
insurance = "100",
rate = BigDecimal(121.5),
rateId = "rate_1b202bd43a8c4c929c73bb46989ef745",
serviceId = "FEDEX_GROUND",
carrierId = "fedex",
shipmentId = "shp_0a9b3ff983c6427eaf1e24cb344de36a",
hasTracking = true,
retailRate = BigDecimal(121.5),
isSelected = false,
isPickupFree = true,
deliveryDays = 1,
deliveryDateGuaranteed = true,
deliveryDate = null
)
)
)
)
)
)
)
val result = getShippingRates()
assertThat(result.model).isEqualTo(expectedRatesResult)
}
@Test
fun `get packages`() = test {
val expectedResult = WCPackagesResult(
listOf(
CustomPackage("Krabica", false, "1 x 2 x 3", 1f),
CustomPackage("Obalka", true, "2 x 3 x 4", 5f)
),
listOf(
PredefinedOption("USPS Priority Mail Flat Rate Boxes",
"usps",
listOf(
PredefinedPackage(
"small_flat_box",
"Small Flat Rate Box",
false,
"21.91 x 13.65 x 4.13",
0f
),
PredefinedPackage(
"medium_flat_box_top",
"Medium Flat Rate Box 1, Top Loading",
false,
"28.57 x 22.22 x 15.24",
0f
)
)
),
PredefinedOption(
"DHL Express",
"dhlexpress",
listOf(PredefinedPackage(
"LargePaddedPouch",
"Large Padded Pouch",
true,
"30.22 x 35.56 x 2.54",
0f
))
)
)
)
val result = getPackages()
assertThat(result.model).isEqualTo(expectedResult)
val invalidRequestResult = getPackages(true)
assertThat(invalidRequestResult.model).isNull()
assertThat(invalidRequestResult.error).isEqualTo(error)
}
@Test
fun `get account settings`() = test {
val expectedPaymentMethodList = listOf(WCPaymentMethod(
paymentMethodId = 4144354,
name = "John Doe",
cardType = "visa",
cardDigits = "5454",
expiry = "2023-12-31"
))
val result = getAccountSettings()
val model = result.model!!
assertThat(model.canManagePayments).isTrue()
assertThat(model.lastUsedBoxId).isEqualTo("small_flat_box")
assertThat(model.selectedPaymentMethodId).isEqualTo(4144354)
assertThat(model.paymentMethods).isEqualTo(expectedPaymentMethodList)
val invalidRequestResult = getAccountSettings(true)
assertThat(invalidRequestResult.model).isNull()
assertThat(invalidRequestResult.error).isEqualTo(error)
}
@Test
fun `purchase shipping label error`() = test {
whenever(restClient.purchaseShippingLabels(
any(),
any(),
any(),
any(),
any(),
anyOrNull(),
any()
))
.thenReturn(WooPayload(error))
val invalidRequestResult = store.purchaseShippingLabels(
site,
orderId,
originAddress,
destAddress,
purchaseLabelPackagesData,
null
)
assertThat(invalidRequestResult.model).isNull()
assertThat(invalidRequestResult.error).isEqualTo(error)
}
@Test
@Suppress("LongMethod")
fun `purchase shipping labels with polling`() = test {
val response = WooPayload(samplePurchaseShippingLabelsResponse)
whenever(restClient.purchaseShippingLabels(
any(),
any(),
any(),
any(),
any(),
anyOrNull(),
any()
)).thenReturn(response)
val statusIntermediateResponse = WCShippingLabelTestUtils.generateSampleShippingLabelsStatusApiResponse(false)
val statusDoneReponse = WCShippingLabelTestUtils.generateSampleShippingLabelsStatusApiResponse(true)
whenever(restClient.fetchShippingLabelsStatus(any(), any(), any()))
.thenReturn(WooPayload(statusIntermediateResponse))
.thenReturn(WooPayload(statusDoneReponse))
ShadowLooper.runUiThreadTasksIncludingDelayedTasks()
val result = store.purchaseShippingLabels(
site,
orderId,
originAddress,
destAddress,
purchaseLabelPackagesData,
null
)
val shippingLabelModels = mapper.map(
samplePurchaseShippingLabelsResponse,
orderId,
originAddress,
destAddress,
site
)
verify(restClient).purchaseShippingLabels(
any(),
any(),
any(),
any(),
any(),
anyOrNull(),
any()
)
verify(restClient).fetchShippingLabelsStatus(
site,
orderId,
samplePurchaseShippingLabelsResponse.labels!!.map { it.labelId!! })
verify(restClient).fetchShippingLabelsStatus(
site,
orderId,
statusIntermediateResponse.labels!!
.filter { it.status != LabelItem.STATUS_PURCHASED }
.map { it.labelId!! })
assertThat(result.model!!.size).isEqualTo(shippingLabelModels.size)
assertThat(result.model!!.first().remoteOrderId).isEqualTo(shippingLabelModels.first().remoteOrderId)
assertThat(result.model!!.first().localSiteId).isEqualTo(shippingLabelModels.first().localSiteId)
assertThat(result.model!!.first().remoteShippingLabelId)
.isEqualTo(shippingLabelModels.first().remoteShippingLabelId)
assertThat(result.model!!.first().carrierId).isEqualTo(shippingLabelModels.first().carrierId)
assertThat(result.model!!.first().packageName).isEqualTo(shippingLabelModels.first().packageName)
assertThat(result.model!!.first().refundableAmount).isEqualTo(shippingLabelModels.first().refundableAmount)
}
@Test
fun `purchase shipping labels with polling fail after 3 retries`() = test {
val response = WooPayload(samplePurchaseShippingLabelsResponse)
whenever(restClient.purchaseShippingLabels(
any(),
any(),
any(),
any(),
any(),
anyOrNull(),
any()
)).thenReturn(response)
whenever(restClient.fetchShippingLabelsStatus(any(), any(), any())).thenReturn(WooPayload(error))
val result = store.purchaseShippingLabels(
site,
orderId,
originAddress,
destAddress,
purchaseLabelPackagesData,
null
)
verify(restClient).purchaseShippingLabels(
any(),
any(),
any(),
any(),
any(),
anyOrNull(),
any()
)
verify(restClient, times(3)).fetchShippingLabelsStatus(
site,
orderId,
samplePurchaseShippingLabelsResponse.labels!!.map { it.labelId!! })
assertThat(result.error).isEqualTo(error)
}
@Test
fun `purchase shipping labels with polling one label failed`() = test {
val response = WooPayload(samplePurchaseShippingLabelsResponse)
whenever(restClient.purchaseShippingLabels(
any(),
any(),
any(),
any(),
any(),
anyOrNull(),
any()
)).thenReturn(response)
val statusIntermediateResponse = WCShippingLabelTestUtils.generateSampleShippingLabelsStatusApiResponse(false)
val statusErrorResponse = WCShippingLabelTestUtils.generateErrorShippingLabelsStatusApiResponse()
whenever(restClient.fetchShippingLabelsStatus(any(), any(), any()))
.thenReturn(WooPayload(statusIntermediateResponse))
.thenReturn(WooPayload(statusErrorResponse))
val result = store.purchaseShippingLabels(
site,
orderId,
originAddress,
destAddress,
purchaseLabelPackagesData,
null
)
assertThat(result.isError).isTrue()
assertThat(result.error.message).isEqualTo(statusErrorResponse.labels!!.first().error)
}
@Test
fun `fetch shipping label eligibility`() = test {
val result = fetchSLCreationEligibility(
canCreatePackage = false,
canCreatePaymentMethod = false,
canCreateCustomsForm = false,
isEligible = true,
isError = false
)
assertThat(result.model).isNotNull
assertThat(result.model!!.isEligible).isTrue
val failedResult = fetchSLCreationEligibility(
canCreatePackage = false,
canCreatePaymentMethod = false,
canCreateCustomsForm = false,
isError = true
)
assertThat(failedResult.model).isNull()
assertThat(failedResult.error).isEqualTo(error)
}
@Test
fun `get stored eligibility`() = test {
fetchSLCreationEligibility(
canCreatePackage = false,
canCreatePaymentMethod = false,
canCreateCustomsForm = false,
isEligible = true,
isError = false
)
val eligibility = store.isOrderEligibleForShippingLabelCreation(
site = site,
orderId = orderId,
canCreatePackage = false,
canCreatePaymentMethod = false,
canCreateCustomsForm = false
)
assertThat(eligibility).isNotNull
assertThat(eligibility!!.isEligible).isTrue
}
@Test
fun `invalidate cached data if parameters are different`() = test {
fetchSLCreationEligibility(
canCreatePackage = false,
canCreatePaymentMethod = false,
canCreateCustomsForm = false,
isEligible = true,
isError = false
)
val eligibility = store.isOrderEligibleForShippingLabelCreation(
site = site,
orderId = orderId,
canCreatePackage = true,
canCreatePaymentMethod = false,
canCreateCustomsForm = false
)
assertThat(eligibility).isNull()
}
@Test
fun `creating packages returns true if the API call succeeds`() = test {
val response = WooPayload(true)
whenever(restClient.createPackages(site = any(), customPackages = any(), predefinedOptions = any()))
.thenReturn(response)
val expectedResult = WooResult(true)
val successfulRequestResult = store.createPackages(
site = site,
customPackages = sampleListOfOneCustomPackage,
predefinedPackages = emptyList()
)
assertEquals(successfulRequestResult, expectedResult)
}
@Test
fun `creating packages returns error if the API call fails`() = test {
// In practice, the API returns more specific error message(s) depending on the error case.
// In `createPackages()` that error message isn't modified further, so here we use a mock message instead.
val errorMessage = "error message"
val response = WooPayload<Boolean>(WooError(GENERIC_ERROR, UNKNOWN, errorMessage))
whenever(restClient.createPackages(site = any(), customPackages = any(), predefinedOptions = any()))
.thenReturn(response)
val expectedResult = WooResult<Boolean>(response.error)
val errorRequestResult = store.createPackages(
site = site,
customPackages = emptyList(),
predefinedPackages = sampleListOfOnePredefinedPackage
)
assertEquals(errorRequestResult, expectedResult)
assertEquals(expectedResult.error.message, errorMessage)
}
private suspend fun fetchShippingLabelsForOrder(): WooResult<List<WCShippingLabelModel>> {
val fetchShippingLabelsPayload = WooPayload(sampleShippingLabelApiResponse)
whenever(restClient.fetchShippingLabelsForOrder(orderId, site)).thenReturn(fetchShippingLabelsPayload)
whenever(restClient.fetchShippingLabelsForOrder(orderId, errorSite)).thenReturn(WooPayload(error))
return store.fetchShippingLabelsForOrder(site, orderId)
}
private suspend fun refundShippingLabelForOrder(): WooResult<Boolean> {
val refundShippingLabelPayload = WooPayload(sampleShippingLabelApiResponse)
whenever(restClient.refundShippingLabelForOrder(
site, orderId, refundShippingLabelId
)).thenReturn(refundShippingLabelPayload)
whenever(restClient.refundShippingLabelForOrder(
errorSite, orderId, refundShippingLabelId
)).thenReturn(WooPayload(error))
return store.refundShippingLabelForOrder(site, orderId, refundShippingLabelId)
}
private suspend fun printShippingLabelForOrder(): WooResult<String> {
val printShippingLabelPayload = WooPayload(samplePrintShippingLabelApiResponse)
whenever(restClient.printShippingLabels(
site, printPaperSize, listOf(refundShippingLabelId)
)).thenReturn(printShippingLabelPayload)
whenever(restClient.printShippingLabels(
errorSite, printPaperSize, listOf(refundShippingLabelId)
)).thenReturn(WooPayload(error))
return store.printShippingLabel(site, printPaperSize, refundShippingLabelId)
}
private suspend fun verifyAddress(type: ShippingLabelAddress.Type): WooResult<WCAddressVerificationResult> {
val verifyAddressPayload = WooPayload(successfulVerifyAddressApiResponse)
whenever(restClient.verifyAddress(
site,
address,
ORIGIN
)).thenReturn(verifyAddressPayload)
whenever(restClient.verifyAddress(
site,
address,
DESTINATION
)).thenReturn(WooPayload(error))
return store.verifyAddress(site, address, type)
}
private suspend fun getShippingRates(): WooResult<WCShippingRatesResult> {
val rates = WooPayload(sampleShippingRatesApiResponse)
whenever(restClient.getShippingRates(any(), any(), any(), any(), any(), anyOrNull()))
.thenReturn(rates)
return store.getShippingRates(site, orderId, originAddress, destAddress, packages, null)
}
private suspend fun getPackages(isError: Boolean = false): WooResult<WCPackagesResult> {
val getPackagesPayload = WooPayload(samplePackagesApiResponse)
if (isError) {
whenever(restClient.getPackageTypes(any())).thenReturn(WooPayload(error))
} else {
whenever(restClient.getPackageTypes(any())).thenReturn(getPackagesPayload)
}
return store.getPackageTypes(site)
}
private suspend fun getAccountSettings(isError: Boolean = false): WooResult<WCShippingAccountSettings> {
if (isError) {
whenever(restClient.getAccountSettings(any())).thenReturn(WooPayload(error))
} else {
val accountSettingsPayload = WooPayload(sampleAccountSettingsApiResponse)
whenever(restClient.getAccountSettings(any())).thenReturn(accountSettingsPayload)
}
return store.getAccountSettings(site)
}
private suspend fun fetchSLCreationEligibility(
canCreatePackage: Boolean,
canCreatePaymentMethod: Boolean,
canCreateCustomsForm: Boolean,
isEligible: Boolean = false,
isError: Boolean = false
): WooResult<WCShippingLabelCreationEligibility> {
if (isError) {
whenever(restClient.checkShippingLabelCreationEligibility(any(), any(), any(), any(), any()))
.thenReturn(WooPayload(error))
} else {
val result = SLCreationEligibilityApiResponse(
isEligible = isEligible,
reason = if (isEligible) null else "reason"
)
whenever(restClient.checkShippingLabelCreationEligibility(any(), any(), any(), any(), any()))
.thenReturn(WooPayload(result))
}
return store.fetchShippingLabelCreationEligibility(
site = site,
orderId = orderId,
canCreatePackage = canCreatePackage,
canCreatePaymentMethod = canCreatePaymentMethod,
canCreateCustomsForm = canCreateCustomsForm
)
}
}
| gpl-2.0 | 1645c117e7c09e3b588bcd458a76e7c2 | 42.552439 | 140 | 0.585305 | 5.479975 | false | true | false | false |
jshmrsn/karg | src/main/java/com/jshmrsn/karg/internal/ArgumentsInternal.kt | 1 | 7375 | package com.jshmrsn.karg.internal
import com.jshmrsn.karg.InvalidArgumentsException
import com.jshmrsn.karg.RawArguments
internal interface ArgumentToken
internal class ValueArgumentToken(val value: String) : ArgumentToken {
var isClaimed = false
private set
fun claim(): String {
this.isClaimed = true
return value
}
}
internal class ShortNameArgumentToken(val shortNames: List<Char>) : ArgumentToken {
private val unclaimedShortNames = shortNames.toMutableList()
val immutableUnclaimedShortNames: List<Char> get() = this.unclaimedShortNames.toList()
fun claim(shortNamesToCheck: List<Char>): Char? {
shortNamesToCheck.forEach { shortNameToCheck ->
if (this.unclaimedShortNames.remove(shortNameToCheck)) {
return shortNameToCheck
}
}
return null
}
}
internal class NameArgumentToken(val name: String) : ArgumentToken {
var isClaimed = false
private set
fun claim(namesToCheck: List<String>): Boolean {
namesToCheck.forEach { nameToCheck ->
if (this.name == nameToCheck) {
this.isClaimed = true
return true
}
}
return false
}
}
internal class RawArgumentsImplementation(val rawArguments: List<String>) : RawArguments
internal class RawArgumentsForInspectionImplementation() : RawArguments
internal class ArgumentsParser(rawArguments: RawArguments,
positionalUntilSeparator: Boolean = false) {
val isForHelp: Boolean
val isForInspection: Boolean
private val argumentTokens: List<ArgumentToken>
private val postSeparatorStrings: List<String>
init {
if (rawArguments is RawArgumentsImplementation) {
val argumentTokens = mutableListOf<ArgumentToken>()
val postSeparatorStrings = mutableListOf<String>()
var hasReachedSeparator = false
var defaultPositional = positionalUntilSeparator
rawArguments.rawArguments.forEach { rawArgument ->
if (rawArgument == "---") {
defaultPositional = !defaultPositional
} else if (hasReachedSeparator || defaultPositional) {
postSeparatorStrings.add(rawArgument)
} else if (rawArgument == "--") {
hasReachedSeparator = true
} else if (rawArgument.startsWith("--")) {
val name = rawArgument.substring(2)
argumentTokens.add(NameArgumentToken(name))
} else if (rawArgument.startsWith("-")) {
val shortNames = rawArgument.substring(1).toList()
argumentTokens.add(ShortNameArgumentToken(shortNames))
} else {
argumentTokens.add(ValueArgumentToken(rawArgument))
}
}
this.argumentTokens = argumentTokens
this.postSeparatorStrings = postSeparatorStrings
this.isForHelp = parseFlag("help", namesToCheck = listOf("help"), shortNamesToCheck = listOf('h')) == true
this.isForInspection = this.isForHelp
} else if (rawArguments is RawArgumentsForInspectionImplementation) {
this.isForHelp = false
this.isForInspection = true
this.argumentTokens = listOf()
this.postSeparatorStrings = listOf()
} else {
throw InvalidArgumentsException("Provided raw arguments should always be obtained through a call to parseArguments or inspectArguments")
}
}
fun parseFlag(name: String, namesToCheck: List<String>, shortNamesToCheck: List<Char>): Boolean? {
var result: Boolean? = null
val inverseNamesToCheck = namesToCheck.map { "no-" + it }
this.argumentTokens.forEach { token ->
if (token is NameArgumentToken) {
if (token.claim(inverseNamesToCheck)) {
if (result != null)
throw InvalidArgumentsException("Flag provided multiple times: $name")
result = false
} else if (token.claim(namesToCheck)) {
if (result != null)
throw InvalidArgumentsException("Flag provided multiple times: $name")
result = true
}
} else if (token is ShortNameArgumentToken) {
val claimedShortName = token.claim(shortNamesToCheck)
if (claimedShortName != null) {
if (result != null)
throw InvalidArgumentsException("Flag provided multiple times: $name")
result = true
}
}
}
return result
}
fun parseMultiParameter(name: String, namesToCheck: List<String>, shortNamesToCheck: List<Char>): List<String> {
var tokenIndex = 0
val result = mutableListOf<String>()
while (tokenIndex < this.argumentTokens.size) {
val token = this.argumentTokens[tokenIndex]
val nextToken = this.argumentTokens.getOrNull(tokenIndex + 1)
if (token is NameArgumentToken) {
if (token.claim(namesToCheck)) {
if (nextToken is ValueArgumentToken) {
result.add(nextToken.claim())
} else {
throw InvalidArgumentsException("Expected value for parameter $name (${token.name})")
}
}
} else if (token is ShortNameArgumentToken) {
val claimedShortName = token.claim(shortNamesToCheck)
if (claimedShortName != null) {
if (nextToken is ValueArgumentToken) {
result.add(nextToken.claim())
} else {
throw InvalidArgumentsException("Expected value for parameter $name ($claimedShortName)")
}
}
}
tokenIndex++
}
return result
}
fun parseParameter(name: String, namesToCheck: List<String>, shortNamesToCheck: List<Char>): String? {
val results = this.parseMultiParameter(name, namesToCheck, shortNamesToCheck)
if (results.size > 1)
throw InvalidArgumentsException("Multiple values provided for parameter: " + name)
return results.firstOrNull()
}
fun parsePositionalArguments(): List<String> {
val positionalArguments = arrayListOf<String>()
this.argumentTokens.forEach { token ->
if (token is ValueArgumentToken) {
if (!token.isClaimed) {
positionalArguments.add(token.claim())
}
}
}
return positionalArguments + this.postSeparatorStrings
}
fun finalize() {
if (!this.isForInspection) {
this.argumentTokens.forEach { token ->
if (token is NameArgumentToken) {
if (!token.isClaimed) {
throw InvalidArgumentsException("Unclaimed name argument: " + token.name)
}
} else if (token is ShortNameArgumentToken) {
val unclaimedShortNames = token.immutableUnclaimedShortNames
if (!unclaimedShortNames.isEmpty()) {
throw InvalidArgumentsException("Unclaimed short-named arguments: " + unclaimedShortNames.joinToString(", "))
}
} else if (token is ValueArgumentToken) {
if (!token.isClaimed) {
throw InvalidArgumentsException("Unclaimed argument value: " + token.value)
}
}
}
}
}
}
| mit | e640fb0d39d9c1ace8bdcecdc3396586 | 33.624413 | 145 | 0.618305 | 4.916667 | false | false | false | false |
chrisbanes/tivi | data/src/main/java/app/tivi/data/resultentities/EpisodeWithSeason.kt | 1 | 1347 | /*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.tivi.data.resultentities
import androidx.room.Embedded
import androidx.room.Relation
import app.tivi.data.entities.Episode
import app.tivi.data.entities.Season
import java.util.Objects
class EpisodeWithSeason {
@Embedded
var episode: Episode? = null
@Suppress("PropertyName")
@Relation(parentColumn = "season_id", entityColumn = "id")
var _seasons: List<Season> = emptyList()
val season: Season?
get() = _seasons.getOrNull(0)
override fun equals(other: Any?): Boolean = when {
other === this -> true
other is EpisodeWithSeason -> episode == other.episode && _seasons == other._seasons
else -> false
}
override fun hashCode(): Int = Objects.hash(episode, _seasons)
}
| apache-2.0 | d0d2ca66583c7de1ccc2586a33c0c773 | 30.325581 | 92 | 0.705271 | 4.131902 | false | false | false | false |
MyDogTom/detekt | detekt-rules/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/performance/ForEachOnRangeSpec.kt | 1 | 1197 | package io.gitlab.arturbosch.detekt.rules.performance
import io.gitlab.arturbosch.detekt.test.lint
import org.assertj.core.api.Assertions
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.given
import org.jetbrains.spek.api.dsl.it
class ForEachOnRangeSpec : Spek({
given("a kt file with using a forEach on a range") {
val code = """
package foo
fun test() {
(1..10).forEach {
println(it)
}
}
"""
it("should report the forEach usage") {
val findings = ForEachOnRange().lint(code)
Assertions.assertThat(findings).hasSize(1)
}
}
given("a kt file with using any other method on a range") {
val code = """
package foo
fun test() {
(1..10).isEmpty()
}
"""
it("should report not report any issues") {
val findings = ForEachOnRange().lint(code)
Assertions.assertThat(findings).isEmpty()
}
}
given("a kt file with using a forEach on a list") {
val code = """
package foo
fun test() {
listOf<Int>(1, 2, 3).forEach {
println(it)
}
}
"""
it("should report not report any issues") {
val findings = ForEachOnRange().lint(code)
Assertions.assertThat(findings).isEmpty()
}
}
})
| apache-2.0 | 88fb1574ae5ed01adaa41bec6240da4f | 19.288136 | 60 | 0.651629 | 3.183511 | false | true | false | false |
jtransc/jtransc | benchmark_kotlin_mpp/wip/jzlib/Adler32.kt | 1 | 3935 | /* -*-mode:java; c-basic-offset:2; -*- */ /*
Copyright (c) 2000-2011 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This program is based on zlib-1.1.3, so all credit should go authors
* Jean-loup Gailly([email protected]) and Mark Adler([email protected])
* and contributors of zlib.
*/
package com.jtransc.compression.jzlib
class Adler32 : Checksum {
private var s1 = 1
private var s2 = 0
override fun reset(init: Int) {
s1 = init shr 0 and 0xffff
s2 = init shr 16 and 0xffff
}
override fun reset() {
s1 = 1
s2 = 0
}
override val value: Int
get() = s2 shl 16 or s1
override fun update(buf: ByteArray?, index: Int, len: Int) {
var index = index
var len = len
if (len == 1) {
s1 += buf!![index++].toInt() and 0xff
s2 += s1
s1 %= BASE
s2 %= BASE
return
}
var len1 = len / NMAX
val len2 = len % NMAX
while (len1-- > 0) {
var k = NMAX
len -= k
while (k-- > 0) {
s1 += buf!![index++].toInt() and 0xff
s2 += s1
}
s1 %= BASE
s2 %= BASE
}
var k = len2
len -= k
while (k-- > 0) {
s1 += buf!![index++].toInt() and 0xff
s2 += s1
}
s1 %= BASE
s2 %= BASE
}
override fun copy(): Adler32? {
val foo = Adler32()
foo.s1 = s1
foo.s2 = s2
return foo
}
companion object {
// largest prime smaller than 65536
private const val BASE = 65521
// NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1
private const val NMAX = 5552
// The following logic has come from zlib.1.2.
fun combine(adler1: Long, adler2: Long, len2: Long): Long {
val BASEL = BASE.toLong()
var sum1: Long
var sum2: Long
val rem: Long // unsigned int
rem = len2 % BASEL
sum1 = adler1 and 0xffffL
sum2 = rem * sum1
sum2 %= BASEL // MOD(sum2);
sum1 += (adler2 and 0xffffL) + BASEL - 1
sum2 += (adler1 shr 16 and 0xffffL) + (adler2 shr 16 and 0xffffL) + BASEL - rem
if (sum1 >= BASEL) sum1 -= BASEL
if (sum1 >= BASEL) sum1 -= BASEL
if (sum2 >= BASEL shl 1) sum2 -= BASEL shl 1
if (sum2 >= BASEL) sum2 -= BASEL
return sum1 or (sum2 shl 16)
} /*
private java.util.zip.Adler32 adler=new java.util.zip.Adler32();
public void update(byte[] buf, int index, int len){
if(buf==null) {adler.reset();}
else{adler.update(buf, index, len);}
}
public void reset(){
adler.reset();
}
public void reset(long init){
if(init==1L){
adler.reset();
}
else{
System.err.println("unsupported operation");
}
}
public long getValue(){
return adler.getValue();
}
*/
}
} | apache-2.0 | 419b4cfeb03005a572d729cbd1f3560b | 27.941176 | 82 | 0.666582 | 3.230706 | false | false | false | false |
Sjtek/sjtekcontrol-core | core/src/main/kotlin/nl/sjtek/control/core/settings/SettingsManager.kt | 1 | 2345 | package nl.sjtek.control.core.settings
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import nl.sjtek.control.data.parsers.LampHolder
import nl.sjtek.control.data.parsers.QuotesHolder
import nl.sjtek.control.data.parsers.UserHolder
import nl.sjtek.control.data.staticdata.Lamp
import nl.sjtek.control.data.staticdata.User
import org.slf4j.LoggerFactory
import java.io.File
object SettingsManager {
private const val PATH_CONFIG = "/var/sjtekcontrol/config.json"
private const val PATH_USERS = "/var/sjtekcontrol/users.json"
private const val PATH_QUOTES = "/var/sjtekcontrol/quotes.json"
private const val PATH_LAMPS = "/var/sjtekcontrol/lamps.json"
private val logger = LoggerFactory.getLogger(javaClass)
val settings: Settings
val users: List<User>
val quotes: List<String>
val lamps: Map<Int, Lamp>
val jsonUsers: String
get() = GsonBuilder().setPrettyPrinting().create().toJson(users)
val jsonQuotes: String
get() = GsonBuilder().setPrettyPrinting().create().toJson(quotes)
val jsonLamps: String
get() = GsonBuilder().setPrettyPrinting().create().toJson(lamps)
init {
settings = load(PATH_CONFIG, Settings::class.java) ?: Settings()
users = load(PATH_USERS, UserHolder::class.java)?.users ?: listOf()
logger.info("Loaded ${users.size} users")
quotes = load(PATH_QUOTES, QuotesHolder::class.java)?.quotes ?: listOf()
logger.info("Loaded ${quotes.size} quotes")
lamps = load(PATH_LAMPS, LampHolder::class.java)?.lamps ?: mapOf()
logger.info("Loaded ${lamps.size} lamps")
}
fun getUser(name: String?): User? {
if (name == null) return null
return users.find { it.username == name }
}
fun getUser(request: spark.Request): User? {
val userName = request.queryParams("user")
return getUser(userName)
}
private fun <T> load(path: String, clazz: Class<T>): T? {
val jsonString = try {
File(path).readText()
} catch (e: Exception) {
logger.error("Failed loading $path", e)
return null
}
return try {
Gson().fromJson<T>(jsonString, clazz)
} catch (e: Exception) {
logger.error("Failed parsing $path", e)
null
}
}
} | gpl-3.0 | 9b8bf4b796524ea86641c82502650956 | 34.014925 | 80 | 0.65032 | 3.90183 | false | false | false | false |
msebire/intellij-community | platform/platform-impl/src/com/intellij/internal/statistic/eventLog/EventLogConfiguration.kt | 1 | 2751 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.internal.statistic.eventLog
import com.google.common.hash.Hashing
import com.intellij.internal.statistic.DeviceIdManager
import com.intellij.openapi.application.ApplicationInfo
import com.intellij.openapi.application.impl.ApplicationInfoImpl
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.util.BuildNumber
import com.intellij.openapi.util.text.StringUtil
import com.intellij.util.containers.ContainerUtil
import java.nio.charset.StandardCharsets
import java.security.SecureRandom
import java.util.*
import java.util.prefs.Preferences
object EventLogConfiguration {
private val LOG = Logger.getInstance(EventLogConfiguration::class.java)
private const val SALT_PREFERENCE_KEY = "feature_usage_event_log_salt"
const val version: Int = 6
val sessionId: String = UUID.randomUUID().toString().shortedUUID()
val deviceId: String = DeviceIdManager.getOrGenerateId()
val bucket: Int = deviceId.asBucket()
val build: String = ApplicationInfo.getInstance().build.asBuildNumber()
private val salt: ByteArray = getOrGenerateSalt()
private val anonymizedCache = ContainerUtil.newHashMap<String, String>()
fun anonymize(data: String): String {
if (StringUtil.isEmptyOrSpaces(data)) {
return data
}
if (anonymizedCache.containsKey(data)) {
return anonymizedCache[data] ?: ""
}
val hasher = Hashing.sha256().newHasher()
hasher.putBytes(salt)
hasher.putString(data, StandardCharsets.UTF_8)
val result = hasher.hash().toString()
anonymizedCache[data] = result
return result
}
private fun String.shortedUUID(): String {
val start = this.lastIndexOf('-')
if (start > 0 && start + 1 < this.length) {
return this.substring(start + 1)
}
return this
}
private fun BuildNumber.asBuildNumber(): String {
val str = this.asStringWithoutProductCodeAndSnapshot()
return if (str.endsWith(".")) str + "0" else str
}
private fun String.asBucket(): Int {
return Math.abs(this.hashCode()) % 256
}
private fun getOrGenerateSalt(): ByteArray {
val companyName = ApplicationInfoImpl.getShadowInstance().shortCompanyName
val name = if (StringUtil.isEmptyOrSpaces(companyName)) "jetbrains" else companyName.toLowerCase(Locale.US)
val prefs = Preferences.userRoot().node(name)
var salt = prefs.getByteArray(SALT_PREFERENCE_KEY, null)
if (salt == null) {
salt = ByteArray(32)
SecureRandom().nextBytes(salt)
prefs.putByteArray(SALT_PREFERENCE_KEY, salt)
LOG.info("Generating salt for the device")
}
return salt
}
}
| apache-2.0 | fcba47ad14768b42e2ea638db916381b | 33.3875 | 140 | 0.736823 | 4.232308 | false | false | false | false |
microg/android_packages_apps_GmsCore | play-services-nearby-core-ui/src/main/kotlin/org/microg/gms/nearby/core/ui/ExposureNotificationsAppFragment.kt | 1 | 2205 | /*
* SPDX-FileCopyrightText: 2020, microG Project Team
* SPDX-License-Identifier: Apache-2.0
*/
package org.microg.gms.nearby.core.ui
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.provider.Settings
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.content.res.AppCompatResources
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import org.microg.gms.nearby.core.ui.databinding.ExposureNotificationsAppFragmentBinding
import org.microg.gms.ui.getApplicationInfoIfExists
class ExposureNotificationsAppFragment : Fragment(R.layout.exposure_notifications_app_fragment) {
private lateinit var binding: ExposureNotificationsAppFragmentBinding
val packageName: String?
get() = arguments?.getString("package")
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
binding = ExposureNotificationsAppFragmentBinding.inflate(inflater, container, false)
binding.callbacks = object : ExposureNotificationsAppFragmentCallbacks {
override fun onAppClicked() {
val intent = Intent()
intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
val uri: Uri = Uri.fromParts("package", packageName, null)
intent.data = uri
context!!.startActivity(intent)
}
}
childFragmentManager.findFragmentById(R.id.sub_preferences)?.arguments = arguments
return binding.root
}
override fun onResume() {
super.onResume()
lifecycleScope.launchWhenResumed {
val pm = requireContext().packageManager
val applicationInfo = pm.getApplicationInfoIfExists(packageName)
binding.appName = applicationInfo?.loadLabel(pm)?.toString() ?: packageName
binding.appIcon = applicationInfo?.loadIcon(pm)
?: AppCompatResources.getDrawable(requireContext(), android.R.mipmap.sym_def_app_icon)
}
}
}
interface ExposureNotificationsAppFragmentCallbacks {
fun onAppClicked()
}
| apache-2.0 | 8ab43683bfd3ebb08072e8a059f16131 | 39.090909 | 116 | 0.722449 | 4.966216 | false | false | false | false |
cemrich/zapp | app/src/main/java/de/christinecoenen/code/zapp/app/livestream/repository/ProgramInfoRepository.kt | 1 | 1288 | package de.christinecoenen.code.zapp.app.livestream.repository
import de.christinecoenen.code.zapp.app.livestream.api.IZappBackendApiService
import de.christinecoenen.code.zapp.app.livestream.api.model.Channel
import de.christinecoenen.code.zapp.app.livestream.api.model.Channel.Companion.getById
import de.christinecoenen.code.zapp.app.livestream.model.LiveShow
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
class ProgramInfoRepository(private val zappApi: IZappBackendApiService) {
private val cache = ProgramInfoCache()
/**
* @throws IllegalArgumentException if a wrong channel id is passed
* @throws RuntimeException if api response is empty and no show in cache
*/
suspend fun getShow(channelId: String): LiveShow = withContext(Dispatchers.IO) {
val newChannel = getById(channelId)
return@withContext getShow(newChannel)
}
private suspend fun getShow(channel: Channel): LiveShow {
val cachedShow = cache.getShow(channel)
if (cachedShow != null) {
return cachedShow
}
val showResponse = zappApi.getShows(channel.toString())
if (!showResponse.isSuccess) {
throw RuntimeException("Show response was empty")
}
val liveShow = showResponse.show.toLiveShow()
cache.save(channel, liveShow)
return liveShow
}
}
| mit | b2edf44cd3e83e951ed088d4033d2c4f | 29.666667 | 86 | 0.786491 | 3.810651 | false | false | false | false |
wespeakapp/WeSpeakAndroid | app/src/main/java/com/example/aleckstina/wespeakandroid/fragment/ProfileFragment.kt | 1 | 1459 | package com.example.aleckstina.wespeakandroid.fragment
import android.databinding.DataBindingUtil
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.android.databinding.library.baseAdapters.BR
import com.example.aleckstina.wespeakandroid.R
import com.example.aleckstina.wespeakandroid.databinding.ProfileFragmentBinding
import com.example.aleckstina.wespeakandroid.model.User
/**
* Created by aleckstina on 10/6/17.
*/
class ProfileFragment : Fragment() {
private var mPage : Int = 0
override fun onCreate(savedInstanceState: Bundle?) {
mPage = arguments.getInt(ARG_PAGE);
super.onCreate(savedInstanceState)
}
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View {
val test_user = User("Elon Musk", "https://i.ytimg.com/vi/tnBQmEqBCY0/maxresdefault.jpg")
val mProfileView = inflater?.inflate(R.layout.profile_fragment, container, false)
val binding : ProfileFragmentBinding = DataBindingUtil.bind(mProfileView)
binding.setVariable(BR.user, test_user)
return binding.root
}
companion object {
val ARG_PAGE = "ARG_PAGE"
fun newInstance(page: Int) : ProfileFragment {
val args = Bundle()
args.putInt(ARG_PAGE, page)
val fragment = ProfileFragment()
fragment.arguments = args
return fragment
}
}
} | mit | f9f2c7877ba016c25491c8f5bab9a72a | 30.73913 | 114 | 0.755997 | 4.098315 | false | false | false | false |
pdvrieze/ProcessManager | PE-common/src/commonMain/kotlin/org/w3/soapEnvelope/Subcode.kt | 1 | 2045 | /*
* Copyright (c) 2018.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2009.09.24 at 08:12:58 PM CEST
//
package org.w3.soapEnvelope
import kotlinx.serialization.Serializable
import nl.adaptivity.xmlutil.QName
import nl.adaptivity.xmlutil.QNameSerializer
import nl.adaptivity.xmlutil.serialization.XmlSerialName
/**
*
*
* Java class for subcode complex type.
*
*
* The following schema fragment specifies the expected content contained within
* this class.
*
* ```
* <complexType name="subcode">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="Value" type="{http://www.w3.org/2001/XMLSchema}QName"/>
* <element name="Subcode" type="{http://www.w3.org/2003/05/soap-envelope}subcode" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* ```
*/
@Serializable
@XmlSerialName("Subcode", Envelope.NAMESPACE, Envelope.PREFIX)
class Subcode(
@Serializable(QNameSerializer::class) @XmlSerialName("Value", Envelope.NAMESPACE, Envelope.PREFIX)
val value: QName,
val subcode: Subcode? = null
)
| lgpl-3.0 | a7ad79b97f79b5f5e144ab2a8703a4c7 | 32.52459 | 124 | 0.732518 | 3.691336 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/view/RotatedCircleDrawable.kt | 2 | 1096 | package de.westnordost.streetcomplete.view
import android.graphics.Canvas
import android.graphics.ColorFilter
import android.graphics.Path
import android.graphics.Rect
import android.graphics.drawable.Drawable
import androidx.core.graphics.toRectF
/** Container that contains another drawable but rotates it and clips it so it is a circle */
class RotatedCircleDrawable(val drawable: Drawable) : Drawable() {
var rotation: Float = 0f
set(value) {
field = value
invalidateSelf()
}
override fun draw(canvas: Canvas) {
val w = bounds.width()
val h = bounds.height()
val path = Path()
path.addOval(Rect(0, 0, w,h).toRectF(), Path.Direction.CW)
canvas.clipPath(path)
canvas.rotate(rotation, w/2f, h/2f)
drawable.bounds = bounds
drawable.draw(canvas)
}
override fun setAlpha(alpha: Int) {
drawable.alpha = alpha
}
override fun setColorFilter(colorFilter: ColorFilter?) {
drawable.colorFilter = colorFilter
}
override fun getOpacity(): Int = drawable.opacity
} | gpl-3.0 | ee983def4414de7d99ca64b92f6e7b41 | 27.128205 | 93 | 0.678832 | 4.264591 | false | false | false | false |
lure0xaos/CoffeeTime | util/src/main/kotlin/gargoyle/ct/util/prop/impl/simple/CTSimpleProperty.kt | 1 | 1052 | package gargoyle.ct.util.prop.impl.simple
import gargoyle.ct.util.prop.impl.CTBaseObservableProperty
import java.text.MessageFormat
import kotlin.reflect.KClass
abstract class CTSimpleProperty<T : Any> : CTBaseObservableProperty<T> {
private lateinit var value: T
@Suppress("UNCHECKED_CAST")
protected constructor(name: String, def: T) : super(def::class as KClass<T>, name) {
value = def
}
protected constructor(type: KClass<T>, name: String) : super(type, name)
override fun set(value: T) {
val oldValue = get()
if (oldValue == value) {
return
}
this.value = value
val thread = firePropertyChange(value, oldValue)
try {
thread?.join()
} catch (ex: InterruptedException) {
throw IllegalStateException(ex)
}
}
override fun get(): T {
return value
}
override fun toString(): String {
return MessageFormat.format("CTSimpleProperty'{'name=''{0}'', value={1}'}'", name, value)
}
}
| unlicense | 5a8524a6406bea483b8f3fd8ac3aabcf | 26.684211 | 97 | 0.620722 | 4.191235 | false | false | false | false |
Ruben-Sten/TeXiFy-IDEA | src/nl/hannahsten/texifyidea/intentions/LatexLeftRightParenthesesIntention.kt | 1 | 5927 | package nl.hannahsten.texifyidea.intentions
import com.intellij.codeInsight.hint.HintManager
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiWhiteSpace
import nl.hannahsten.texifyidea.util.containsKeyOrValue
import nl.hannahsten.texifyidea.util.files.document
import nl.hannahsten.texifyidea.util.files.isLatexFile
import nl.hannahsten.texifyidea.util.findKeys
import nl.hannahsten.texifyidea.util.inMathContext
/**
* @author Hannah Schellekens
*/
open class LatexLeftRightParenthesesIntention : TexifyIntentionBase("Change to \\left..\\right") {
companion object {
private val brackets = mapOf(
"(" to ")",
"[" to "]",
"<" to ">"
)
}
override fun isAvailable(project: Project, editor: Editor?, file: PsiFile?): Boolean {
if (editor == null || file == null || !file.isLatexFile()) {
return false
}
val element = file.findElementAt(editor.caretModel.offset - 1) ?: return false
if (!element.inMathContext() || element is PsiComment) {
return false
}
val (lookbehind, lookahead) = scan(editor, file) ?: return false
return brackets.containsKeyOrValue(lookbehind) || brackets.containsKeyOrValue(lookahead)
}
override fun invoke(project: Project, editor: Editor?, file: PsiFile?) {
if (editor == null || file == null || !file.isLatexFile()) {
return
}
val caret = editor.caretModel
val (lookbehind, lookahead) = scan(editor, file) ?: return
if (brackets.containsKey(lookahead)) {
replaceForward(editor, caret.offset, file)
}
else if (brackets.containsKey(lookbehind)) {
replaceForward(editor, caret.offset - 1, file)
}
else if (brackets.containsValue(lookbehind)) {
replaceBackward(editor, caret.offset - 1, file)
}
else if (brackets.containsValue(lookahead)) {
replaceBackward(editor, caret.offset, file)
}
}
private fun replaceForward(editor: Editor, offset: Int, file: PsiFile) {
val document = editor.document
val open = document.getText(TextRange.from(offset, 1))
val close = brackets[open]
// Scan document.
var current = offset
var nested = 0
var closeOffset: Int? = null
while (++current < file.textLength) {
val char = document.getText(TextRange.from(current, 1))
// Ignore comments.
val element = file.findElementAt(current)
if (element is PsiComment) {
continue
}
if (!element!!.inMathContext() && element !is PsiWhiteSpace) {
break
}
// Open nesting
if (char == open) {
nested++
continue
}
// Close nesting
if (char == close && nested > 0) {
nested--
continue
}
// Whenever met at correct closure
if (char == close && nested <= 0) {
closeOffset = current
break
}
}
if (closeOffset == null) {
HintManager.getInstance().showErrorHint(editor, "Could not find matching close '$close'")
return
}
// Replace stuff
runWriteAction {
document.replaceString(closeOffset, closeOffset + 1, "\\right$close")
document.replaceString(offset, offset + 1, "\\left$open")
editor.caretModel.moveToOffset(offset + 6)
}
}
private fun replaceBackward(editor: Editor, offset: Int, file: PsiFile) {
val document = editor.document
val close = document.getText(TextRange.from(offset, 1))
val open = brackets.findKeys(close).first()
// Scan document.
var current = offset
var nested = 0
var openOffset: Int? = null
while (--current < file.textLength) {
val char = document.getText(TextRange.from(current, 1))
// Ignore comments.
val element = file.findElementAt(current)
if (element is PsiComment) {
continue
}
if (!element!!.inMathContext()) {
break
}
// Open nesting
if (char == close) {
nested++
continue
}
// Close nesting
if (char == open && nested > 0) {
nested--
continue
}
// Whenever met at correct closure
if (char == open && nested <= 0) {
openOffset = current
break
}
}
if (openOffset == null) {
HintManager.getInstance().showErrorHint(editor, "Could not find matching open '$close'")
return
}
// Replace stuff
runWriteAction {
document.replaceString(offset, offset + 1, "\\right$close")
document.replaceString(openOffset, openOffset + 1, "\\left$open")
}
}
private fun scan(editor: Editor, file: PsiFile): Pair<String, String>? {
val caret = editor.caretModel
val document = file.document() ?: return null
// Check document ranges.
if (caret.offset >= document.textLength) return null
if (caret.offset - 1 < 0) return null
val lookbehind = document.getText(TextRange.from(caret.offset - 1, 1))
val lookahead = document.getText(TextRange.from(caret.offset, 1))
return Pair(lookbehind, lookahead)
}
} | mit | c5862b50847a24ed61928e6cfe2c47c4 | 30.700535 | 101 | 0.568416 | 4.858197 | false | false | false | false |
debop/debop4k | debop4k-core/src/test/kotlin/debop4k/core/collections/permutations/SortedTest.kt | 1 | 1657 | /*
* Copyright (c) 2016. KESTI co, ltd
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package debop4k.core.collections.permutations
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
/**
* SortedTest
* @author [email protected]
*/
class SortedTest : AbstractPermutationTest() {
@Test
fun testSortEmptySeq() {
assertThat(emptyPermutation.sorted()).isEmpty()
}
@Test
fun testSortSingleSeq() {
val single = permutationOf(17)
assertThat(single.sorted()).isEqualTo(permutationOf(17))
}
@Test
fun testSortFixedSeq() {
val fixed = permutationOf(17, 3, 15, 9, 4)
assertThat(fixed.sorted()).isEqualTo(permutationOf(3, 4, 9, 15, 17))
}
@Test
fun testLazyFiniteSeq() {
val lazy = lazy()
log.debug("lazy={}", lazy.mkString(lazy = false))
assertThat(lazy.sorted()).isEqualTo(permutationOf(expectedList.sorted()))
}
@Test
fun testSortStringSeq() {
val fixed = permutationOf("ab", "c", "", "ghjkl", "def")
val sorted = fixed.sorted { s1, s2 -> s1.length - s2.length }
assertThat(sorted).isEqualTo(permutationOf("", "c", "ab", "def", "ghjkl"))
}
} | apache-2.0 | 3bf289bb6fa017afe5101d8689a2fff4 | 27.586207 | 78 | 0.691611 | 3.740406 | false | true | false | false |
herolynx/elepantry-android | app/src/main/java/com/herolynx/elepantry/resources/view/menu/UserViewsMenu.kt | 1 | 7856 | package com.herolynx.elepantry.resources.view.menu
import android.app.ProgressDialog
import android.os.Bundle
import android.support.design.widget.FloatingActionButton
import android.support.design.widget.NavigationView
import android.support.design.widget.Snackbar
import android.support.v4.view.GravityCompat
import android.support.v4.widget.DrawerLayout
import android.support.v7.app.ActionBarDrawerToggle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.Toolbar
import android.view.Menu
import android.view.MenuItem
import android.widget.LinearLayout
import com.google.firebase.analytics.FirebaseAnalytics
import com.herolynx.elepantry.R
import com.herolynx.elepantry.core.log.debug
import com.herolynx.elepantry.core.log.metrics
import com.herolynx.elepantry.core.log.viewVisit
import com.herolynx.elepantry.core.ui.notification.WithProgressDialog
import com.herolynx.elepantry.drive.Drives
import com.herolynx.elepantry.ext.android.Permissions
import com.herolynx.elepantry.resources.core.model.View
import com.herolynx.elepantry.resources.core.service.ResourceView
import com.herolynx.elepantry.resources.view.list.DriveList
import com.herolynx.elepantry.resources.view.tags.ResourceTagsActivity
import com.herolynx.elepantry.user.view.menu.UserBadge
abstract class UserViewsMenu : AppCompatActivity(), WithProgressDialog {
abstract val layoutId: Int
abstract val topMenuId: Int
private var menuCtrl: UserViewsMenuCtrl? = null
override var mProgressDialog: ProgressDialog? = null
protected var blockScreen = false
protected var analytics: FirebaseAnalytics? = null
protected var loadDefaultItem: () -> Unit = {}
protected var closeMenu: () -> Unit = {}
private val topMenuItems: MutableList<MenuItem> = mutableListOf()
protected var fabEditButton: FloatingActionButton? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Permissions.requestWriteExternalStoragePermission(this)
analytics = FirebaseAnalytics.getInstance(this)
analytics?.viewVisit(this)
setContentView(R.layout.menu_frame)
val toolbar = findViewById(R.id.toolbar) as Toolbar
menuCtrl = UserViewsMenuCtrl(this)
setSupportActionBar(toolbar)
initMenu(menuCtrl!!)
initToolbar(toolbar)
initView()
initAdditionalMenuActions()
}
private fun initAdditionalMenuActions() {
fabEditButton = findViewById(R.id.fab_actio_edit) as FloatingActionButton
fabEditButton?.visibility = android.view.View.INVISIBLE
fabEditButton?.setOnClickListener({ view ->
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show()
})
}
private fun initView() {
val viewPlaceholder = findViewById(R.id.layout_placeholder) as LinearLayout
val view = layoutInflater.inflate(layoutId, viewPlaceholder, false)
viewPlaceholder.addView(view)
}
private fun initMenu(menuCtrl: UserViewsMenuCtrl) {
val navigationView = findViewById(R.id.nav_view) as NavigationView
val menuLayout = findViewById(R.id.left_menu_layout) as LinearLayout
val userBadge = UserBadge.create(this, navigationView)
menuLayout.addView(userBadge.layout)
userBadge.display()
val menuLeft = layoutInflater.inflate(R.layout.menu_user_views, navigationView, false)
menuLeft.findViewById(R.id.add_new_view).setOnClickListener {
analytics?.metrics("ViewAdd")
menuCtrl?.handleAddNewView()
closeMenu()
}
menuLeft.findViewById(R.id.sign_out).setOnClickListener {
menuCtrl.handleSignOutAction()
}
menuLayout.addView(menuLeft)
initDriveViews(menuLeft.findViewById(R.id.drive_views) as RecyclerView)
initUserViews(menuLeft.findViewById(R.id.user_views) as RecyclerView, menuCtrl)
}
private fun initDriveViews(layout: RecyclerView) {
debug("[initDriveViews] Creating...")
val listAdapter = DriveList.adapter(
activity = this,
onClickHandler = { driveItem ->
onViewChange(driveItem.asView())
},
refreshClickHandler = { start ->
showProgressBar(start)
if (!start) {
runOnUiThread {
closeMenu()
refreshView()
}
}
}
)
layout.adapter = listAdapter
val linearLayoutManager = LinearLayoutManager(this)
layout.layoutManager = linearLayoutManager
Drives.drives(this)
.map { drive ->
listAdapter.add(drive)
listAdapter.sort()
listAdapter.notifyDataSetChanged()
}
}
private fun initUserViews(layout: RecyclerView, menuCtrl: UserViewsMenuCtrl) {
debug("[initUserViews] Creating...")
val listAdapter = UserViewsList.adapter(
clickHandler = { v ->
closeMenu()
analytics?.metrics("ViewChange", id = v.id, name = v.name, value = v.type.toString())
onViewChange(v)
},
editHandler = { v ->
closeMenu()
analytics?.metrics("ViewEdit", id = v.id, name = v.name)
ResourceTagsActivity.navigate(this, v)
}
)
layout.adapter = listAdapter
val linearLayoutManager = LinearLayoutManager(this)
layout.layoutManager = linearLayoutManager
menuCtrl.getUserViews()
.subscribe { v ->
debug("[initUserViews] Adding view: $v")
listAdapter.add(v)
listAdapter.sort()
listAdapter.notifyDataSetChanged()
}
}
private fun showProgressBar(start: Boolean) {
blockScreen = start
if (start)
runOnUiThread { showProgressDialog(this) }
else
runOnUiThread { hideProgressDialog() }
}
protected open fun refreshView() {
//empty
}
protected abstract fun onViewChange(
v: View,
rv: ResourceView = menuCtrl!!.getResourceView(v)
): Boolean
private fun initToolbar(toolbar: Toolbar) {
val drawer = findViewById(R.id.drawer_layout) as DrawerLayout
val toggle = ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close)
closeMenu = { drawer.closeDrawer(GravityCompat.START) }
drawer.setDrawerListener(toggle)
toggle.syncState()
}
override fun onBackPressed() {
super.onBackPressed()
val drawer = findViewById(R.id.drawer_layout) as DrawerLayout
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START)
} else {
super.onBackPressed()
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(topMenuId, menu)
var i = 0
while (i < menu.size()) {
topMenuItems.add(menu.getItem(i))
i++
}
return true
}
protected fun topMenuItems() = topMenuItems.toList()
override fun onOptionsItemSelected(item: MenuItem): Boolean {
debug("[TopMenu] Item selected - item: ${item.title}, action id: ${item.itemId}")
return super.onOptionsItemSelected(item)
}
} | gpl-3.0 | 43aae7fbb343c2d26588e19e2a6f8157 | 36.414286 | 105 | 0.647785 | 4.882536 | false | false | false | false |
ansman/okhttp | okhttp/src/main/kotlin/okhttp3/internal/connection/Exchange.kt | 3 | 9284 | /*
* Copyright (C) 2019 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 okhttp3.internal.connection
import java.io.IOException
import java.net.ProtocolException
import java.net.SocketException
import okhttp3.EventListener
import okhttp3.Headers
import okhttp3.Request
import okhttp3.Response
import okhttp3.ResponseBody
import okhttp3.internal.http.ExchangeCodec
import okhttp3.internal.http.RealResponseBody
import okhttp3.internal.ws.RealWebSocket
import okio.Buffer
import okio.ForwardingSink
import okio.ForwardingSource
import okio.Sink
import okio.Source
import okio.buffer
/**
* Transmits a single HTTP request and a response pair. This layers connection management and events
* on [ExchangeCodec], which handles the actual I/O.
*/
class Exchange(
internal val call: RealCall,
internal val eventListener: EventListener,
internal val finder: ExchangeFinder,
private val codec: ExchangeCodec
) {
/** True if the request body need not complete before the response body starts. */
internal var isDuplex: Boolean = false
private set
/** True if there was an exception on the connection to the peer. */
internal var hasFailure: Boolean = false
private set
internal val connection: RealConnection = codec.connection
internal val isCoalescedConnection: Boolean
get() = finder.address.url.host != connection.route().address.url.host
@Throws(IOException::class)
fun writeRequestHeaders(request: Request) {
try {
eventListener.requestHeadersStart(call)
codec.writeRequestHeaders(request)
eventListener.requestHeadersEnd(call, request)
} catch (e: IOException) {
eventListener.requestFailed(call, e)
trackFailure(e)
throw e
}
}
@Throws(IOException::class)
fun createRequestBody(request: Request, duplex: Boolean): Sink {
this.isDuplex = duplex
val contentLength = request.body!!.contentLength()
eventListener.requestBodyStart(call)
val rawRequestBody = codec.createRequestBody(request, contentLength)
return RequestBodySink(rawRequestBody, contentLength)
}
@Throws(IOException::class)
fun flushRequest() {
try {
codec.flushRequest()
} catch (e: IOException) {
eventListener.requestFailed(call, e)
trackFailure(e)
throw e
}
}
@Throws(IOException::class)
fun finishRequest() {
try {
codec.finishRequest()
} catch (e: IOException) {
eventListener.requestFailed(call, e)
trackFailure(e)
throw e
}
}
fun responseHeadersStart() {
eventListener.responseHeadersStart(call)
}
@Throws(IOException::class)
fun readResponseHeaders(expectContinue: Boolean): Response.Builder? {
try {
val result = codec.readResponseHeaders(expectContinue)
result?.initExchange(this)
return result
} catch (e: IOException) {
eventListener.responseFailed(call, e)
trackFailure(e)
throw e
}
}
fun responseHeadersEnd(response: Response) {
eventListener.responseHeadersEnd(call, response)
}
@Throws(IOException::class)
fun openResponseBody(response: Response): ResponseBody {
try {
val contentType = response.header("Content-Type")
val contentLength = codec.reportedContentLength(response)
val rawSource = codec.openResponseBodySource(response)
val source = ResponseBodySource(rawSource, contentLength)
return RealResponseBody(contentType, contentLength, source.buffer())
} catch (e: IOException) {
eventListener.responseFailed(call, e)
trackFailure(e)
throw e
}
}
@Throws(IOException::class)
fun trailers(): Headers = codec.trailers()
@Throws(SocketException::class)
fun newWebSocketStreams(): RealWebSocket.Streams {
call.timeoutEarlyExit()
return codec.connection.newWebSocketStreams(this)
}
fun webSocketUpgradeFailed() {
bodyComplete(-1L, responseDone = true, requestDone = true, e = null)
}
fun noNewExchangesOnConnection() {
codec.connection.noNewExchanges()
}
fun cancel() {
codec.cancel()
}
/**
* Revoke this exchange's access to streams. This is necessary when a follow-up request is
* required but the preceding exchange hasn't completed yet.
*/
fun detachWithViolence() {
codec.cancel()
call.messageDone(this, requestDone = true, responseDone = true, e = null)
}
private fun trackFailure(e: IOException) {
hasFailure = true
finder.trackFailure(e)
codec.connection.trackFailure(call, e)
}
fun <E : IOException?> bodyComplete(
bytesRead: Long,
responseDone: Boolean,
requestDone: Boolean,
e: E
): E {
if (e != null) {
trackFailure(e)
}
if (requestDone) {
if (e != null) {
eventListener.requestFailed(call, e)
} else {
eventListener.requestBodyEnd(call, bytesRead)
}
}
if (responseDone) {
if (e != null) {
eventListener.responseFailed(call, e)
} else {
eventListener.responseBodyEnd(call, bytesRead)
}
}
return call.messageDone(this, requestDone, responseDone, e)
}
fun noRequestBody() {
call.messageDone(this, requestDone = true, responseDone = false, e = null)
}
/** A request body that fires events when it completes. */
private inner class RequestBodySink(
delegate: Sink,
/** The exact number of bytes to be written, or -1L if that is unknown. */
private val contentLength: Long
) : ForwardingSink(delegate) {
private var completed = false
private var bytesReceived = 0L
private var closed = false
@Throws(IOException::class)
override fun write(source: Buffer, byteCount: Long) {
check(!closed) { "closed" }
if (contentLength != -1L && bytesReceived + byteCount > contentLength) {
throw ProtocolException(
"expected $contentLength bytes but received ${bytesReceived + byteCount}")
}
try {
super.write(source, byteCount)
this.bytesReceived += byteCount
} catch (e: IOException) {
throw complete(e)
}
}
@Throws(IOException::class)
override fun flush() {
try {
super.flush()
} catch (e: IOException) {
throw complete(e)
}
}
@Throws(IOException::class)
override fun close() {
if (closed) return
closed = true
if (contentLength != -1L && bytesReceived != contentLength) {
throw ProtocolException("unexpected end of stream")
}
try {
super.close()
complete(null)
} catch (e: IOException) {
throw complete(e)
}
}
private fun <E : IOException?> complete(e: E): E {
if (completed) return e
completed = true
return bodyComplete(bytesReceived, responseDone = false, requestDone = true, e = e)
}
}
/** A response body that fires events when it completes. */
internal inner class ResponseBodySource(
delegate: Source,
private val contentLength: Long
) : ForwardingSource(delegate) {
private var bytesReceived = 0L
private var invokeStartEvent = true
private var completed = false
private var closed = false
init {
if (contentLength == 0L) {
complete(null)
}
}
@Throws(IOException::class)
override fun read(sink: Buffer, byteCount: Long): Long {
check(!closed) { "closed" }
try {
val read = delegate.read(sink, byteCount)
if (invokeStartEvent) {
invokeStartEvent = false
eventListener.responseBodyStart(call)
}
if (read == -1L) {
complete(null)
return -1L
}
val newBytesReceived = bytesReceived + read
if (contentLength != -1L && newBytesReceived > contentLength) {
throw ProtocolException("expected $contentLength bytes but received $newBytesReceived")
}
bytesReceived = newBytesReceived
if (newBytesReceived == contentLength) {
complete(null)
}
return read
} catch (e: IOException) {
throw complete(e)
}
}
@Throws(IOException::class)
override fun close() {
if (closed) return
closed = true
try {
super.close()
complete(null)
} catch (e: IOException) {
throw complete(e)
}
}
fun <E : IOException?> complete(e: E): E {
if (completed) return e
completed = true
// If the body is closed without reading any bytes send a responseBodyStart() now.
if (e == null && invokeStartEvent) {
invokeStartEvent = false
eventListener.responseBodyStart(call)
}
return bodyComplete(bytesReceived, responseDone = true, requestDone = false, e = e)
}
}
}
| apache-2.0 | 394c0ce99eea4300d1ce1a0eee1eb6c4 | 26.963855 | 100 | 0.66383 | 4.4 | false | false | false | false |
McPringle/moodini | src/main/kotlin/ch/fihlon/moodini/server/RuntimeExceptionMapper.kt | 1 | 3011 | /*
* Moodini
* Copyright (C) 2016-2017 Marcus Fihlon
*
* 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 ch.fihlon.moodini.server
import mu.KotlinLogging
import java.util.ConcurrentModificationException
import javax.json.Json
import javax.ws.rs.NotFoundException
import javax.ws.rs.WebApplicationException
import javax.ws.rs.core.MediaType
import javax.ws.rs.core.Response
import javax.ws.rs.core.Response.Status
import javax.ws.rs.core.Response.Status.CONFLICT
import javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR
import javax.ws.rs.core.Response.Status.METHOD_NOT_ALLOWED
import javax.ws.rs.core.Response.Status.NOT_FOUND
import javax.ws.rs.ext.ExceptionMapper
import javax.ws.rs.ext.Provider
@Provider
class RuntimeExceptionMapper : ExceptionMapper<RuntimeException> {
private val logger = KotlinLogging.logger {}
override fun toResponse(exception: RuntimeException): Response {
logger.error(exception, { exception.message })
return handleException(exception)
}
private fun handleException(throwable: Throwable?): Response {
val response: Response
when (throwable) {
is ConcurrentModificationException -> response =
createResponse(CONFLICT, throwable.message!!)
is NotFoundException -> response =
createResponse(NOT_FOUND, throwable.message!!)
is UnsupportedOperationException -> response =
createResponse(METHOD_NOT_ALLOWED, throwable.message!!)
is WebApplicationException -> response =
createResponse(Response.Status.fromStatusCode(throwable.response.status), throwable.message!!)
else -> {
if (throwable?.cause == null) {
response = createResponse(INTERNAL_SERVER_ERROR, throwable?.message!!)
} else {
response = handleException(throwable.cause!!)
}
}
}
return response
}
private fun createResponse(status: Status, message: String): Response {
val entity = Json.createObjectBuilder()
.add("status", status.statusCode)
.add("message", message)
.build()
return Response.status(status)
.type(MediaType.APPLICATION_JSON)
.entity(entity).build()
}
}
| agpl-3.0 | 0c35af2d976a8b2a49de43eb64c151c9 | 37.113924 | 114 | 0.678844 | 4.697348 | false | false | false | false |
tomhenne/Jerusalem | src/main/java/de/esymetric/jerusalem/osmDataRepresentation/osm2ownMaps/longOsm2OwnMaps/LongOsmNodeID2OwnIDMapFile.kt | 1 | 4643 | package de.esymetric.jerusalem.osmDataRepresentation.osm2ownMaps.longOsm2OwnMaps
import java.io.*
import java.nio.ByteBuffer
class LongOsmNodeID2OwnIDMapFile(var dataDirectoryPath: String) : LongOsmNodeID2OwnIDMap {
var currentFileNumber = -1
var currentFilePath: String? = null
var currentFileIsModified = false
var entries = IntArray(NUMBER_OF_ENTRIES_PER_FILE) { i -> -1 }
var buf: ByteBuffer? = null
override val numberOfUsedArrays: Int
get() = 0
fun isCurrentlyOpenFile(osmNodeID: Long): Boolean {
return isCurrentlyOpenFile(getFileNumber(osmNodeID))
}
fun isCurrentlyOpenFile(fileNumber: Int): Boolean {
return fileNumber == currentFileNumber
}
fun openFile(fileNumber: Int): Boolean {
if (isCurrentlyOpenFile(fileNumber)) return true
if (currentFileNumber != -1) closeFile()
// load file
currentFileNumber = fileNumber
currentFilePath = getMapFilePath(fileNumber)
val f = File(currentFilePath)
if (f.exists()) {
print("$$fileNumber")
return readIntegers()
}
// need to clear buffer?
print("*$fileNumber")
return true
}
fun closeFile(): Boolean {
if (currentFileNumber == -1) return true
if (!currentFileIsModified) return true
val success = writeIntegers()
print("+$currentFileNumber")
currentFileIsModified = false
System.gc()
return success
}
private fun writeIntegers(): Boolean {
if (buf == null) buf = ByteBuffer.allocate(4 * NUMBER_OF_ENTRIES_PER_FILE) else buf!!.clear()
for (i in entries) buf!!.putInt(i)
buf!!.rewind()
var out: FileOutputStream? = null
try {
out = FileOutputStream(currentFilePath)
val file = out.channel
file.write(buf)
file.close()
} catch (e: IOException) {
e.printStackTrace()
return false
} finally {
safeClose(out)
buf = null
}
return true
}
private fun readIntegers(): Boolean {
var `in`: FileInputStream? = null
try {
`in` = FileInputStream(currentFilePath)
val file = `in`.channel
if (buf == null) buf = ByteBuffer.allocate(4 * NUMBER_OF_ENTRIES_PER_FILE) else buf!!.clear()
file.read(buf)
buf!!.rewind()
for (i in entries.indices) {
entries[i] = buf!!.int
}
file.close()
} catch (e: IOException) {
e.printStackTrace()
return false
} finally {
safeClose(`in`)
}
return true
}
override fun put(osmNodeID: Long, ownNodeID: Int): Boolean {
val fileNumber = getFileNumber(osmNodeID)
if (!openFile(fileNumber)) return false
val indexInFile = getIndexInFile(osmNodeID, fileNumber)
entries[indexInFile] = ownNodeID
currentFileIsModified = true
return true
}
private fun getMapFilePath(fileNumber: Int): String {
return dataDirectoryPath + File.separatorChar + DIR + File.separatorChar + FILENAME + fileNumber + ".data"
}
override fun get(osmNodeID: Long): Int {
val fileNumber = getFileNumber(osmNodeID)
if (!openFile(fileNumber)) return -1
val indexInFile = getIndexInFile(osmNodeID, fileNumber)
return entries[indexInFile]
}
override fun close() {
closeFile()
if (buf != null) {
buf!!.clear()
buf = null
}
}
override fun delete() {}
companion object {
const val DIR = "longOsm2OwnMap"
const val FILENAME = "map_"
const val NUMBER_OF_ENTRIES_PER_FILE = 50000000 // 50 Mio Speicherbedarf 200 MB
const val FILE_SIZE = NUMBER_OF_ENTRIES_PER_FILE * 4
fun getFileNumber(osmNodeID: Long): Int {
return (osmNodeID / NUMBER_OF_ENTRIES_PER_FILE.toLong()).toInt()
}
fun getIndexInFile(osmNodeID: Long, fileNumber: Int): Int {
return (osmNodeID - fileNumber.toLong() * NUMBER_OF_ENTRIES_PER_FILE.toLong()).toInt()
}
private fun safeClose(out: OutputStream?) {
try {
out?.close()
} catch (e: IOException) {
// do nothing
}
}
private fun safeClose(out: InputStream?) {
try {
out?.close()
} catch (e: IOException) {
// do nothing
}
}
}
} | apache-2.0 | 8ab0b00e5825663f725daf6fd2f1eb8f | 29.552632 | 114 | 0.573336 | 4.551961 | false | false | false | false |
ken-kentan/student-portal-plus | app/src/main/java/jp/kentan/studentportalplus/ui/login/ValidationResult.kt | 1 | 385 | package jp.kentan.studentportalplus.ui.login
data class ValidationResult(
val isEmptyUsername: Boolean = false,
val isInvalidUsername: Boolean = false,
val isEmptyPassword: Boolean = false,
val isInvalidPassword: Boolean = false
) {
val isError: Boolean
get() = isEmptyUsername || isInvalidUsername || isEmptyPassword || isInvalidPassword
} | gpl-3.0 | 6b06c5fc226e82742cf5086a53d37cd0 | 34.090909 | 92 | 0.706494 | 5.065789 | false | false | false | false |
NextFaze/dev-fun | demo/src/main/java/com/nextfaze/devfun/demo/Session.kt | 1 | 685 | package com.nextfaze.devfun.demo
import com.nextfaze.devfun.function.DeveloperFunction
import org.joda.time.DateTime
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class Session @Inject constructor() {
private val log = logger()
var user: User? = null
@DeveloperFunction
private fun logCurrentUser() = log.d { "user=$user" }
}
enum class Gender { OTHER, FEMALE, MALE }
data class User(
val givenName: CharSequence,
val familyName: CharSequence,
val userName: CharSequence,
val password: CharSequence,
val email: CharSequence,
val dataOfBirth: DateTime,
val gender: Gender
) {
val id = "$userName".hashCode()
}
| apache-2.0 | c0bdbb5fa1606ccfa1d1d4f0432d71f6 | 21.833333 | 57 | 0.716788 | 4.029412 | false | false | false | false |
sys1yagi/mastodon4j | mastodon4j/src/main/java/com/sys1yagi/mastodon4j/api/entity/Notification.kt | 1 | 976 | package com.sys1yagi.mastodon4j.api.entity
import com.google.gson.annotations.SerializedName
/**
* see more https://github.com/tootsuite/documentation/blob/master/Using-the-API/API.md#notification
*/
class Notification(
@SerializedName("id")
val id: Long = 0L, // The notification ID
@SerializedName("type")
val type: String = Type.Mention.value, // One of: "mention", "reblog", "favourite", "follow"
@SerializedName("created_at")
val createdAt: String = "", // The time the notification was created
@SerializedName("account")
val account: Account? = null, // The Account sending the notification to the user
@SerializedName("status")
val status: Status? = null // The Status associated with the notification, if applicable
) {
enum class Type(val value: String) {
Mention("mention"),
Reblog("reblog"),
Favourite("favourite"),
Follow("follow")
}
}
| mit | 2af10ae6ab9a9611704b35d6e8b94148 | 31.533333 | 100 | 0.646516 | 4.188841 | false | false | false | false |
dafi/photoshelf | app/src/main/java/com/ternaryop/photoshelf/fragment/preference/PreferenceCategorySelector.kt | 1 | 1233 | package com.ternaryop.photoshelf.fragment.preference
import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
import com.ternaryop.photoshelf.R
private const val CATEGORY_KEY_IMPORT = "category_key_import"
private const val CATEGORY_KEY_IMAGE = "category_key_image"
/**
* Created by dave on 17/03/18.
* Select preference by category key
*/
object PreferenceCategorySelector {
fun openScreen(
caller: PreferenceFragmentCompat,
pref: Preference,
fragment: Fragment
): Boolean {
val fm = caller.activity?.supportFragmentManager ?: return false
val args = fragment.arguments ?: Bundle()
args.putString(PreferenceFragmentCompat.ARG_PREFERENCE_ROOT, pref.key)
fragment.arguments = args
fm.beginTransaction()
.add(R.id.content_frame, fragment, pref.key)
.addToBackStack(pref.key)
.commit()
return true
}
fun fragmentFromCategory(key: String?): Fragment? = when (key) {
CATEGORY_KEY_IMPORT -> ImportPreferenceFragment()
CATEGORY_KEY_IMAGE -> ImagePreferenceFragment()
else -> null
}
}
| mit | 06283bd4a30a415e7d8830a35556beab | 30.615385 | 78 | 0.695053 | 4.566667 | false | false | false | false |
tasks/tasks | app/src/androidTest/java/org/tasks/location/LocationServiceAndroidTest.kt | 1 | 2585 | package org.tasks.location
import android.location.Location
import android.location.LocationManager.GPS_PROVIDER
import android.location.LocationManager.NETWORK_PROVIDER
import dagger.hilt.android.testing.HiltAndroidTest
import dagger.hilt.android.testing.UninstallModules
import kotlinx.coroutines.runBlocking
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
import org.tasks.injection.InjectingTestCase
import org.tasks.injection.ProductionModule
import org.tasks.time.DateTime
import javax.inject.Inject
@UninstallModules(ProductionModule::class)
@HiltAndroidTest
class LocationServiceAndroidTest : InjectingTestCase() {
@Inject lateinit var service: LocationServiceAndroid
@Inject lateinit var locationManager: MockLocationManager
@Test
fun sortByAccuracy() = runBlocking {
newLocation(NETWORK_PROVIDER, 45.0, 46.0, 50f, DateTime(2021, 2, 4, 13, 35, 45, 121))
newLocation(GPS_PROVIDER, 45.1, 46.1, 30f, DateTime(2021, 2, 4, 13, 33, 45, 121))
assertEquals(MapPosition(45.1, 46.1), service.currentLocation())
}
@Test
fun sortWithStaleLocation() = runBlocking {
newLocation(GPS_PROVIDER, 45.1, 46.1, 30f, DateTime(2021, 2, 4, 13, 33, 44, 121))
newLocation(NETWORK_PROVIDER, 45.0, 46.0, 50f, DateTime(2021, 2, 4, 13, 35, 45, 121))
assertEquals(MapPosition(45.0, 46.0), service.currentLocation())
}
@Test
fun useNewerUpdateWhenAccuracySame() = runBlocking {
newLocation(GPS_PROVIDER, 45.1, 46.1, 50f, DateTime(2021, 2, 4, 13, 35, 45, 100))
newLocation(NETWORK_PROVIDER, 45.0, 46.0, 50f, DateTime(2021, 2, 4, 13, 35, 45, 121))
assertEquals(MapPosition(45.0, 46.0), service.currentLocation())
}
@Test
fun returnCachedLocation() = runBlocking {
newLocation(GPS_PROVIDER, 45.1, 46.1, 50f, DateTime(2021, 2, 4, 13, 35, 45, 100))
service.currentLocation()
locationManager.clearLocations()
assertEquals(MapPosition(45.1, 46.1), service.currentLocation())
}
@Test
fun nullWhenNoPosition() = runBlocking {
assertNull(service.currentLocation())
}
private fun newLocation(
provider: String,
latitude: Double,
longitude: Double,
accuracy: Float,
time: DateTime) {
locationManager.addLocations(Location(provider).apply {
this.latitude = latitude
this.longitude = longitude
this.accuracy = accuracy
this.time = time.millis
})
}
} | gpl-3.0 | f66c0f18a3edc48cd80f4e6d7a377d44 | 33.026316 | 93 | 0.683559 | 3.989198 | false | true | false | false |
nemerosa/ontrack | ontrack-extension-general/src/main/java/net/nemerosa/ontrack/extension/general/BuildLinkDecorationExtension.kt | 1 | 3062 | package net.nemerosa.ontrack.extension.general
import net.nemerosa.ontrack.extension.api.DecorationExtension
import net.nemerosa.ontrack.extension.support.AbstractExtension
import net.nemerosa.ontrack.model.labels.MainBuildLinksFilterService
import net.nemerosa.ontrack.model.labels.MainBuildLinksService
import net.nemerosa.ontrack.model.structure.*
import net.nemerosa.ontrack.ui.controller.EntityURIBuilder
import org.springframework.stereotype.Component
import java.util.*
@Component
class BuildLinkDecorationExtension(
extensionFeature: GeneralExtensionFeature,
private val structureService: StructureService,
private val uriBuilder: EntityURIBuilder,
private val mainBuildLinksService: MainBuildLinksService,
private val mainBuildLinksFilterService: MainBuildLinksFilterService,
private val buildDisplayNameService: BuildDisplayNameService
) : AbstractExtension(extensionFeature), DecorationExtension<BuildLinkDecorationList> {
override fun getScope(): EnumSet<ProjectEntityType> = EnumSet.of(ProjectEntityType.BUILD)
override fun getDecorations(entity: ProjectEntity): List<Decoration<BuildLinkDecorationList>> {
// Gets the main build links of the source project
val labels = mainBuildLinksService.getMainBuildLinksConfig(entity.project).labels
// Gets the main links from this build
var extraLinks = false
val mainLinks = structureService.getBuildsUsedBy(entity as Build, 0, Int.MAX_VALUE) { target ->
val mainLink = labels.isEmpty() || mainBuildLinksFilterService.isMainBuidLink(target, labels)
// There are extra links if a target build is NOT a main link
extraLinks = extraLinks || !mainLink
// OK
mainLink
}.pageItems
// Checks if there are extra links (besides the main ones)
val extraLink = if (extraLinks) {
uriBuilder.getEntityPage(entity)
} else {
null
}
// No main links, no extra link ==> no decoration at all
if (mainLinks.isEmpty() && extraLink == null) {
return emptyList()
} else {
// Decoration items for the main links
val decorations = mainLinks.map { getDecoration(it) }
// Global decoration
return listOf(
Decoration.of(
this,
BuildLinkDecorationList(
decorations,
extraLink
)
)
)
}
}
protected fun getDecoration(build: Build): BuildLinkDecoration {
// Gets the list of promotion runs for this build
val promotionRuns = structureService.getLastPromotionRunsForBuild(build.id)
// Gets the label to use for the decoration
val label = buildDisplayNameService.getBuildDisplayName(build)
// Decoration
return build.asBuildLinkDecoration(uriBuilder, promotionRuns, label)
}
}
| mit | d1bba55a747641fd093325d2fb21f7fb | 42.126761 | 105 | 0.669497 | 5.137584 | false | false | false | false |
d9n/intellij-rust | src/main/kotlin/org/rust/lang/core/parser/RustParserDefinition.kt | 1 | 2395 | package org.rust.lang.core.parser
import com.intellij.lang.ASTNode
import com.intellij.lang.LanguageUtil
import com.intellij.lang.ParserDefinition
import com.intellij.lang.PsiParser
import com.intellij.lexer.Lexer
import com.intellij.openapi.project.Project
import com.intellij.psi.FileViewProvider
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.TokenType
import com.intellij.psi.tree.IFileElementType
import com.intellij.psi.tree.TokenSet
import org.rust.lang.core.lexer.RsLexer
import org.rust.lang.core.psi.RS_COMMENTS
import org.rust.lang.core.psi.RS_EOL_COMMENTS
import org.rust.lang.core.psi.RsElementTypes
import org.rust.lang.core.psi.RsElementTypes.STRING_LITERAL
import org.rust.lang.core.psi.RsTokenType
import org.rust.lang.core.psi.RsFile
import org.rust.lang.core.stubs.RsFileStub
class RustParserDefinition : ParserDefinition {
override fun createFile(viewProvider: FileViewProvider): PsiFile? =
RsFile(viewProvider)
override fun spaceExistanceTypeBetweenTokens(left: ASTNode, right: ASTNode): ParserDefinition.SpaceRequirements {
if (left.elementType in RS_EOL_COMMENTS) return ParserDefinition.SpaceRequirements.MUST_LINE_BREAK
return LanguageUtil.canStickTokensTogetherByLexer(left, right, RsLexer())
}
override fun getFileNodeType(): IFileElementType = RsFileStub.Type
override fun getStringLiteralElements(): TokenSet =
TokenSet.create(STRING_LITERAL)
override fun getWhitespaceTokens(): TokenSet =
TokenSet.create(TokenType.WHITE_SPACE)
override fun getCommentTokens() = RS_COMMENTS
override fun createElement(node: ASTNode?): PsiElement =
RsElementTypes.Factory.createElement(node)
override fun createLexer(project: Project?): Lexer = RsLexer()
override fun createParser(project: Project?): PsiParser = RustParser()
companion object {
@JvmField val BLOCK_COMMENT = RsTokenType("<BLOCK_COMMENT>")
@JvmField val EOL_COMMENT = RsTokenType("<EOL_COMMENT>")
@JvmField val INNER_BLOCK_DOC_COMMENT = RsTokenType("<INNER_BLOCK_DOC_COMMENT>")
@JvmField val OUTER_BLOCK_DOC_COMMENT = RsTokenType("<OUTER_BLOCK_DOC_COMMENT>")
@JvmField val INNER_EOL_DOC_COMMENT = RsTokenType("<INNER_EOL_DOC_COMMENT>")
@JvmField val OUTER_EOL_DOC_COMMENT = RsTokenType("<OUTER_EOL_DOC_COMMENT>")
}
}
| mit | 34e51a80ec61bf1922d4423f7dae3c5d | 39.59322 | 117 | 0.765344 | 4.238938 | false | false | false | false |
olonho/carkot | car_srv/clients/flash/src/main/java/client/Client.kt | 1 | 994 | package client
import io.netty.bootstrap.Bootstrap
import io.netty.channel.nio.NioEventLoopGroup
import io.netty.channel.socket.nio.NioSocketChannel
import io.netty.handler.codec.http.HttpRequest
import java.net.ConnectException
class Client constructor(val host: String, val port: Int) {
fun sendRequest(request: HttpRequest) {
val group = NioEventLoopGroup(1)
try {
val bootstrap = Bootstrap()
bootstrap.group(group).channel(NioSocketChannel().javaClass).handler(ClientInitializer())
val channelFuture = bootstrap.connect(host, port).sync()
val channel = channelFuture.channel()
channel.writeAndFlush(request)
channel.closeFuture().sync()
} catch (e: InterruptedException) {
ClientHandler.requestResult.code = 2
} catch (e: ConnectException) {
ClientHandler.requestResult.code = 1
} finally {
group.shutdownGracefully()
}
}
} | mit | 23772b655de599e240641c670e3397b0 | 34.535714 | 101 | 0.667002 | 4.733333 | false | false | false | false |
iovation/launchkey-android-whitelabel-sdk | demo-app/app/src/kotlinApp/java/com/launchkey/android/authenticator/demo/ui/adapter/DemoSessionsAdapter.kt | 2 | 2392 | package com.launchkey.android.authenticator.demo.ui.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView.OnItemClickListener
import android.widget.BaseAdapter
import android.widget.Button
import android.widget.TextView
import com.launchkey.android.authenticator.demo.R
import com.launchkey.android.authenticator.sdk.core.authentication_management.Session
import java.util.*
class DemoSessionsAdapter(private val context: Context, private val mSessions: List<Session>, private val mItemClickListener: OnItemClickListener?) : BaseAdapter() {
private val mInternalClickListener = View.OnClickListener { v ->
if (v != null && v.tag != null) {
val position = v.tag as Int
mItemClickListener?.onItemClick(null, v, position, position.toLong())
}
}
override fun getCount(): Int {
return mSessions.size
}
override fun getItem(position: Int): Session {
return mSessions[position]
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
//Relying on the authorizations layout for items
var v = convertView
if (v == null) {
v = LayoutInflater.from(context)
.inflate(R.layout.demo_authorizations_item, parent, false)
}
val s = getItem(position)
//fetch an application's icon via its url with Application.getAppIcon()
val name = v!!.findViewById<TextView>(R.id.demo_authorizations_item_name)
name.text = s.name
//TODO: Update usage of ID as placeholder for potential context being sent
val context = v.findViewById<TextView>(R.id.demo_authorizations_item_context)
context.text = s.id
val millisAgo = System.currentTimeMillis() - s.createdAtMillis
val action = v.findViewById<TextView>(R.id.demo_authorizations_item_text_action)
action.text = String.format(Locale.getDefault(), "%d seconds ago", millisAgo / 1000)
val button = v.findViewById<Button>(R.id.demo_authorizations_item_button)
button.text = "LOG OUT"
button.setOnClickListener(mInternalClickListener)
button.tag = position
return v
}
} | mit | 7d8d5cf26e7ac5218f3bc5b9461c4c8b | 37.596774 | 165 | 0.693562 | 4.446097 | false | false | false | false |
kesco/SlideBack-Xposed | app/src/main/kotlin/com/kesco/xposed/slideback/view/dialog/SourceUsedDialog.kt | 1 | 2042 | package com.kesco.xposed.slideback.view.dialog
import android.app.Dialog
import android.content.DialogInterface
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.support.v4.app.DialogFragment
import android.support.v7.app.AlertDialog
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.TextView
import com.kesco.xposed.slideback.R
class SourceUsedDialog : DialogFragment(), DialogInterface.OnClickListener {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val builder = AlertDialog.Builder(activity)
builder.setTitle(R.string.software_license)
builder.setAdapter(DialogAdapter(), this)
return builder.create()
}
override fun onClick(dialog: DialogInterface, which: Int) {
when (which) {
0 -> {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse("http://github.com/rovo89/Xposed"))
context.startActivity(intent)
}
}
dialog.dismiss()
}
inner class DialogAdapter : BaseAdapter() {
val inflater = LayoutInflater.from(activity)
override fun getCount(): Int = 1
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View? {
val holder = inflater.inflate(R.layout.item_about_dialog, parent, false)
val tvTitle = holder.findViewById(R.id.tv_title) as TextView
val tvContent = holder.findViewById(R.id.tv_content) as TextView
when (position) {
0 -> {
tvTitle.setText(R.string.xpose_framework)
tvContent.setText(R.string.apache_license)
}
else -> throw UnsupportedOperationException()
}
return holder
}
override fun getItem(position: Int): Any? = null
override fun getItemId(position: Int): Long = position.toLong()
}
}
| mit | 33c131898485d9b36b32760576503176 | 33.033333 | 101 | 0.657199 | 4.537778 | false | false | false | false |
Le-Chiffre/Yttrium | Router/src/com/rimmer/yttrium/router/Router.kt | 2 | 3696 | package com.rimmer.yttrium.router
import com.rimmer.yttrium.Task
import com.rimmer.yttrium.router.plugin.Plugin
import com.rimmer.yttrium.serialize.BodyContent
import com.rimmer.yttrium.serialize.Reader
import com.rimmer.yttrium.serialize.Writer
import java.util.*
class RoutePlugin(val plugin: Plugin<in Any>, val context: Any)
class BuilderQuery(
val name: String, val optional: Boolean, val default: Any?,
val description: String, val type: Class<*>, val reader: Reader?
)
class Router(plugins: List<Plugin<in Any>>) {
val pluginMap = plugins.associateBy { it.name }
val routes = ArrayList<Route>()
fun addRoute(
method: HttpMethod,
version: Int,
properties: List<RouteProperty>,
funSegments: List<PathSegment>,
funQueries: List<BuilderQuery>,
plugins: List<Plugin<in Any>>,
writer: Writer<*>?,
call: RouteContext.(Array<Any?>) -> Task<*>
) {
val args = ArrayList<Arg>()
val segments = ArrayList<Segment>()
funSegments.transformSegments(args, segments, ArgVisibility.Default)
funQueries.forEach {
args.add(Arg(it.name, ArgVisibility.Default, false, it.optional, it.default, it.type, it.reader))
}
// Create a route modifier for plugins.
val modifier = object: RouteModifier {
override val segments: List<Segment> get() = segments
override val args: List<Arg> get() = args
override fun provideFunArg(index: Int) {
args[index] = args[index].copy(visibility = ArgVisibility.Internal)
}
override fun addPath(s: List<PathSegment>): Int {
val id = args.size
s.transformSegments(args, segments, ArgVisibility.External)
return id
}
override fun addArg(name: String, type: Class<*>, reader: Reader?): Int {
val id = args.size
args.add(Arg(name, ArgVisibility.External, false, false, null, type, reader))
return id
}
override fun addOptional(name: String, type: Class<*>, reader: Reader?, default: Any?): Int {
val id = args.size
args.add(Arg(name, ArgVisibility.External, false, true, default, type, reader))
return id
}
}
// Apply all plugins for this route.
val usedPlugins = plugins.map { RoutePlugin(it, it.modifyRoute(modifier, properties)!!) }
// If the segment list is still empty, we add a dummy element to simplify handler code.
if(segments.isEmpty()) {
segments.add(Segment("", null, -1))
}
// Create the route and handler.
val name = "$method ${buildSwaggerPath(segments)}"
val bodyQuery = args.indexOfFirst { it.type === BodyContent::class.java }
routes.add(Route(
name, method, version,
segments.toTypedArray(),
segments.filter { it.arg != null }.toTypedArray(),
args.toTypedArray(),
writer,
if(bodyQuery == -1) null else bodyQuery,
RouteHandler(usedPlugins, call)
))
}
}
private fun Collection<PathSegment>.transformSegments(
args: MutableList<Arg>,
segments: MutableList<Segment>,
visibility: ArgVisibility
) {
forEach {
if(it.type == null) {
segments.add(Segment(it.name, null, -1))
} else {
val arg = Arg(it.name, visibility, true, false, null, it.type, it.reader)
val i = args.size
args.add(arg)
segments.add(Segment(it.name, arg, i))
}
}
} | mit | 1a685db9bdfd0468b2346f9e879951fd | 33.877358 | 109 | 0.595779 | 4.322807 | false | false | false | false |
cashapp/sqldelight | sqldelight-idea-plugin/src/test/kotlin/app/cash/sqldelight/intellij/SqlDelightFixtureTestCase.kt | 1 | 2674 | /*
* Copyright (C) 2018 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 app.cash.sqldelight.intellij
import app.cash.sqldelight.core.SqlDelightDatabaseName
import app.cash.sqldelight.core.SqlDelightFileIndex
import app.cash.sqldelight.core.SqlDelightProjectService
import app.cash.sqldelight.core.SqldelightParserUtil
import app.cash.sqldelight.core.lang.SqlDelightFile
import app.cash.sqldelight.dialects.sqlite_3_18.SqliteDialect
import app.cash.sqldelight.intellij.gradle.FileIndexMap
import com.intellij.openapi.project.rootManager
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiDirectory
import com.intellij.testFramework.fixtures.LightJavaCodeInsightFixtureTestCase
abstract class SqlDelightFixtureTestCase : LightJavaCodeInsightFixtureTestCase() {
protected val sqldelightDir = "main/sqldelight/com/sample"
open val fixtureDirectory: String = ""
override fun getTestDataPath() = "testData/$fixtureDirectory"
override fun setUp() {
super.setUp()
SqliteDialect().setup()
SqldelightParserUtil.overrideSqlParser()
FileIndexMap.defaultIndex = LightFileIndex()
SqlDelightProjectService.getInstance(project).dialect = SqliteDialect()
}
inner class LightFileIndex : SqlDelightFileIndex {
override val isConfigured = true
override val packageName = "com.example"
override val className = "MyDatabase"
override fun packageName(file: SqlDelightFile) = "com.example"
override val contentRoot = module.rootManager.contentRoots.single()
override val dependencies = emptyList<SqlDelightDatabaseName>()
override val deriveSchemaFromMigrations = false
override fun outputDirectory(file: SqlDelightFile) = outputDirectories()
override fun outputDirectories() = listOf("")
override fun sourceFolders(
file: SqlDelightFile,
includeDependencies: Boolean,
): List<PsiDirectory> {
return listOf(myFixture.file.parent!!)
}
override fun sourceFolders(
file: VirtualFile,
includeDependencies: Boolean,
): Collection<VirtualFile> {
return listOf(module.rootManager.contentRoots.first())
}
}
}
| apache-2.0 | b163e39fef2cd54c5014d6178576a76e | 36.138889 | 82 | 0.768138 | 4.666667 | false | true | false | false |
edsilfer/star-wars-wiki | app/src/main/java/br/com/edsilfer/android/starwarswiki/infrastructure/database/GenericDAO.kt | 1 | 1701 | package br.com.tyllt.infrastructure.database
import android.util.Log
import io.realm.Realm
import io.realm.RealmObject
import io.realm.exceptions.RealmPrimaryKeyConstraintException
open class GenericDAO<E : RealmObject>(val mType: Class<E>, val mColumnID: String) {
open fun create(source: E): E? {
val realm = Realm.getDefaultInstance()
var realmObject: E? = null
realm.executeTransaction {
try {
realmObject = realm.copyToRealm(source)
} catch (e: RealmPrimaryKeyConstraintException) {
Log.e(GenericDAO::class.simpleName, "Attemp to add a register with the same previous primary key")
}
}
realm.close()
return realmObject
}
open fun read(id: Long): E? {
val realm = Realm.getDefaultInstance()
val realmObject = realm.where(mType).equalTo(mColumnID, id).findFirst()
return realmObject
}
open fun list(): List<E> {
val realm = Realm.getDefaultInstance()
return realm.where(mType).findAll().toList()
}
open fun update(source: E) {
val realm = Realm.getDefaultInstance()
realm.executeTransaction {
realm.copyToRealmOrUpdate(source)
}
realm.close()
}
open fun delete(id: Long) {
val realm = Realm.getDefaultInstance()
realm.executeTransaction {
val realmObject = read(id)
realmObject?.deleteFromRealm()
}
realm.close()
}
open fun deleteAll() {
val realm = Realm.getDefaultInstance()
realm.executeTransaction {
realm.delete(mType)
}
realm.close()
}
} | apache-2.0 | 8d44ab5d5a73bb519f9a1d6cec72237d | 28.344828 | 114 | 0.610229 | 4.660274 | false | false | false | false |
Devifish/ReadMe | app/src/main/java/cn/devifish/readme/view/base/BaseViewHolder.kt | 1 | 1252 | package cn.devifish.readme.view.base
import android.support.v7.widget.RecyclerView
import android.view.View
/**
* Created by zhang on 2017/2/22.
* 基类
* @author zhang
*/
abstract class BaseViewHolder<M> constructor(itemView: View, listener: BaseViewHolder.OnItemClickListener? = null) : RecyclerView.ViewHolder(itemView), View.OnClickListener, View.OnLongClickListener {
interface OnItemClickListener {
fun onItemClick(view: View, position: Int)
fun onItemLongClick(view: View, position: Int)
}
private var listener: OnItemClickListener? = null
set(value) {
field = value
itemView.setOnClickListener(this)
itemView.setOnLongClickListener(this)
}
init {
if (listener != null) {
this.listener = listener
}
}
abstract fun bind(m: M)
override fun onClick(view: View) {
val position = adapterPosition
if (position != RecyclerView.NO_POSITION) listener!!.onItemClick(view, position)
}
override fun onLongClick(view: View): Boolean {
val position = adapterPosition
if (position != RecyclerView.NO_POSITION) listener!!.onItemLongClick(view, position)
return true
}
}
| apache-2.0 | 03d5ee440ef03342052cc056f80c58fc | 26.733333 | 200 | 0.66266 | 4.622222 | false | false | false | false |
slartus/4pdaClient-plus | forpdanotifyservice/src/main/java/org/softeg/slartus/forpdanotifyservice/favorites/FavoritesNotifier.kt | 1 | 6388 | package org.softeg.slartus.forpdanotifyservice.favorites
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.SystemClock
import android.preference.PreferenceManager
import android.util.Log
import org.softeg.slartus.forpdaapi.FavTopic
import org.softeg.slartus.forpdaapi.ListInfo
import org.softeg.slartus.forpdaapi.TopicsApi
import org.softeg.slartus.forpdacommon.ExtPreferences
import org.softeg.slartus.forpdanotifyservice.BuildConfig
import org.softeg.slartus.forpdanotifyservice.NotifierBase
import org.softeg.slartus.hosthelper.HostHelper
import java.util.*
/**
* Created by slinkin on 26.08.13.
*/
class FavoritesNotifier(context: Context?) : NotifierBase(context) {
private var m_PinnedOnly = false
private fun readConfig() {
val preferences = PreferenceManager.getDefaultSharedPreferences(context)
m_PinnedOnly = preferences.getBoolean("FavoritesNotifier.service.pinned_only", false)
}
override fun checkUpdates() {
try {
Log.i(TAG, "checkFavorites.start")
if (!isUse(context)) return
loadCookiesPath() ?: return
// Log.d(LOG_TAG, "CookiesPath " + cookiesPath);
val unreadTopics = getUnreadTopics(TopicsApi.getFavTopics(ListInfo()))
val hasNewUnread = hasNewUnreadTopic(unreadTopics)
updateNotification(context, unreadTopics, hasNewUnread)
Log.i(TAG, "checkFavorites.end")
} catch (throwable: Throwable) {
Log.e(TAG, throwable.toString())
} finally {
// restartTaskStatic(context, true)
}
}
private fun getUnreadTopics(topics: ArrayList<FavTopic>) = topics
.filter { it.isNew && (!m_PinnedOnly || it.isPinned) }
.sortedByDescending { it.lastMessageDate }
private fun hasNewUnreadTopic(unreadTopics: List<FavTopic>): Boolean {
if (unreadTopics.isEmpty()) return false
val lastPostedTopic = unreadTopics.first()
val lastPostedTopicCalendar = GregorianCalendar()
lastPostedTopicCalendar.time = lastPostedTopic.lastMessageDate
val lastDateTime = loadLastDate(LAST_DATETIME_KEY)
if (lastDateTime == null || lastDateTime.before(lastPostedTopicCalendar)) {
saveLastDate(lastPostedTopicCalendar, LAST_DATETIME_KEY)
return true
}
// if (BuildConfig.DEBUG) {
// return true
// }
return false
}
fun saveTimeout(context: Context, timeOut: Float) {
saveTimeOut(context, timeOut, TIME_OUT_KEY)
}
override fun restartTask(context: Context) {
restartTaskStatic(context, false)
}
override fun cancel(context: Context) {
try {
val alarm = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager?
alarm?.cancel(getAlarmPendingIntent(context, 0))
} catch (ex: Throwable) {
Log.e(TAG, ex.toString())
}
}
private fun updateNotification(context: Context, unreadTopics: List<FavTopic>, hasNewUnread: Boolean) {
Log.i(TAG, "favotires sendNotify")
if (hasNewUnread) {
Log.i(TAG, "favotires notify!")
var message = "Избранное (" + unreadTopics.size + ")"
if (unreadTopics.size == 1) {
message = String.format("%s ответил в тему \"%s\", на которую вы подписаны",
unreadTopics.first().lastMessageAuthor, unreadTopics.first().title)
}
var url = "https://${HostHelper.host}/forum/index.php?autocom=favtopics"
if (unreadTopics.size == 1) url = "https://${HostHelper.host}/forum/index.php?showtopic=" + unreadTopics.first().id + "&view=getnewpost"
sendNotify(context, message, "Непрочитанные сообщения в темах", url, MY_NOTIFICATION_ID)
} else if (unreadTopics.isEmpty()) {
cancelNotification(context, MY_NOTIFICATION_ID)
}
}
companion object {
private val TAG = FavoritesNotifier::class.simpleName
const val TIME_OUT_KEY = "FavoritesNotifier.service.timeout"
private const val LAST_DATETIME_KEY = "FavoritesNotifier.service.lastdatetime"
@JvmStatic
fun isUse(context: Context?): Boolean {
return ExtPreferences.getBoolean(context, "FavoritesNotifier.service.use", false)
}
private const val REQUEST_CODE_START = 839264722
private fun getAlarmPendingIntent(context: Context, flag: Int): PendingIntent {
val receiverIntent = Intent(context, FavoritesAlarmReceiver::class.java)
.apply {
action = "FAVORITES_ALARM"
}
return PendingIntent.getBroadcast(context, REQUEST_CODE_START, receiverIntent, flag)
}
private fun restartTaskStatic(context: Context, useTimeOut: Boolean) {
val timeOut = loadTimeOut(context, TIME_OUT_KEY)
Log.i(TAG, "checkFavorites.TimeOut: $timeOut")
val pendingIntent = getAlarmPendingIntent(context, PendingIntent.FLAG_CANCEL_CURRENT)
val alarm = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager?
alarm?.cancel(pendingIntent)
val wakeUpTime = SystemClock.elapsedRealtime() + if (useTimeOut) (timeOut * 60000).toLong() else 0L
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
alarm?.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, wakeUpTime, pendingIntent)
} else {
alarm?.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, wakeUpTime, pendingIntent)
}
}
@JvmStatic
fun restartTask(context: Context, cookesPath: String, timeOut: Float) {
saveCookiesPath(context, cookesPath)
val notifier = FavoritesNotifier(context)
notifier.saveTimeout(context, timeOut)
notifier.restartTask(context)
}
@JvmStatic
fun cancelAlarm(context: Context) {
val notifier = FavoritesNotifier(context)
notifier.cancel(context)
}
private const val MY_NOTIFICATION_ID = 2
}
init {
readConfig()
}
} | apache-2.0 | 3d1315ebc62c49bd40191ed7882a4e22 | 38.748428 | 148 | 0.651211 | 4.412709 | false | false | false | false |
vimeo/vimeo-networking-java | models/src/main/java/com/vimeo/networking2/LiveStreamsQuota.kt | 1 | 580 | package com.vimeo.networking2
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import com.vimeo.networking2.annotations.Internal
/**
* Live Stream Quota DTO.
*
* @param maximum The maximum amount of streams that the user can create.
* @param remaining The amount of remaining live streams that the user can create this month.
*/
@Internal
@JsonClass(generateAdapter = true)
data class LiveStreamsQuota(
@Internal
@Json(name = "maximum")
val maximum: Int? = null,
@Internal
@Json(name = "remaining")
val remaining: Int? = null
)
| mit | 646538347bb942a36069a732199b76e9 | 22.2 | 93 | 0.725862 | 3.84106 | false | false | false | false |
AndroidX/androidx | room/room-compiler/src/test/kotlin/androidx/room/vo/FtsEntityTest.kt | 3 | 9686 | /*
* Copyright 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 androidx.room.vo
import androidx.room.parser.FtsVersion
import androidx.room.compiler.processing.XElement
import androidx.room.compiler.processing.XType
import androidx.room.compiler.processing.XTypeElement
import mockElementAndType
import org.hamcrest.CoreMatchers.`is`
import org.hamcrest.MatcherAssert.assertThat
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import org.mockito.Mockito.mock
@RunWith(JUnit4::class)
class FtsEntityTest {
@Test
fun createStatement() {
val primaryKeyField = createField("rowid")
val languageIdField = createField("lid")
val bodyField = createField("body")
val dontIndexMe1Field = createField("dontIndexMe1")
val dontIndexMe2Field = createField("dontIndexMe2")
val entity = FtsEntity(
element = mock(XTypeElement::class.java),
tableName = "Mail",
type = mock(XType::class.java),
fields = listOf(
primaryKeyField, bodyField, languageIdField, dontIndexMe1Field,
dontIndexMe2Field
),
embeddedFields = emptyList(),
primaryKey = PrimaryKey(
declaredIn = mock(XElement::class.java),
fields = Fields(primaryKeyField),
autoGenerateId = true
),
constructor = null,
shadowTableName = "Mail_context",
ftsVersion = FtsVersion.FTS4,
ftsOptions = FtsOptions(
tokenizer = androidx.room.FtsOptions.TOKENIZER_PORTER,
tokenizerArgs = emptyList(),
contentEntity = null,
languageIdColumnName = "lid",
matchInfo = androidx.room.FtsOptions.MatchInfo.FTS3,
notIndexedColumns = listOf("dontIndexMe1", "dontIndexMe2"),
prefixSizes = listOf(2, 4),
preferredOrder = androidx.room.FtsOptions.Order.DESC
)
)
assertThat(
entity.createTableQuery,
`is`(
"CREATE VIRTUAL TABLE IF NOT EXISTS `Mail` USING FTS4(" +
"`body` TEXT, " +
"`dontIndexMe1` TEXT, " +
"`dontIndexMe2` TEXT, " +
"tokenize=porter, " +
"languageid=`lid`, " +
"matchinfo=fts3, " +
"notindexed=`dontIndexMe1`, " +
"notindexed=`dontIndexMe2`, " +
"prefix=`2,4`, " +
"order=DESC" +
")"
)
)
}
@Test
fun createStatement_simpleTokenizer_withTokenizerArgs() {
val primaryKeyField = createField("rowid")
val bodyField = createField("body")
val entity = FtsEntity(
element = mock(XTypeElement::class.java),
tableName = "Mail",
type = mock(XType::class.java),
fields = listOf(primaryKeyField, bodyField),
embeddedFields = emptyList(),
primaryKey = PrimaryKey(
declaredIn = mock(XElement::class.java),
fields = Fields(primaryKeyField),
autoGenerateId = true
),
constructor = null,
shadowTableName = "Mail_context",
ftsVersion = FtsVersion.FTS4,
ftsOptions = FtsOptions(
tokenizer = androidx.room.FtsOptions.TOKENIZER_SIMPLE,
tokenizerArgs = listOf("tokenchars=.=", "separators=X"),
contentEntity = null,
languageIdColumnName = "",
matchInfo = androidx.room.FtsOptions.MatchInfo.FTS4,
notIndexedColumns = emptyList(),
prefixSizes = emptyList(),
preferredOrder = androidx.room.FtsOptions.Order.ASC
)
)
assertThat(
entity.createTableQuery,
`is`(
"CREATE VIRTUAL TABLE IF NOT EXISTS `Mail` USING FTS4(" +
"`body` TEXT, " +
"tokenize=simple `tokenchars=.=` `separators=X`" +
")"
)
)
}
@Test
fun createStatement_simpleTokenizer_noTokenizerArgs() {
val primaryKeyField = createField("rowid")
val bodyField = createField("body")
val entity = FtsEntity(
element = mock(XTypeElement::class.java),
tableName = "Mail",
type = mock(XType::class.java),
fields = listOf(primaryKeyField, bodyField),
embeddedFields = emptyList(),
primaryKey = PrimaryKey(
declaredIn = mock(XElement::class.java),
fields = Fields(primaryKeyField),
autoGenerateId = true
),
constructor = null,
shadowTableName = "Mail_context",
ftsVersion = FtsVersion.FTS4,
ftsOptions = FtsOptions(
tokenizer = androidx.room.FtsOptions.TOKENIZER_SIMPLE,
tokenizerArgs = emptyList(),
contentEntity = null,
languageIdColumnName = "",
matchInfo = androidx.room.FtsOptions.MatchInfo.FTS4,
notIndexedColumns = emptyList(),
prefixSizes = emptyList(),
preferredOrder = androidx.room.FtsOptions.Order.ASC
)
)
assertThat(
entity.createTableQuery,
`is`(
"CREATE VIRTUAL TABLE IF NOT EXISTS `Mail` USING FTS4(" +
"`body` TEXT" +
")"
)
)
}
@Test
fun createStatement_nonSimpleTokenizer_withTokenizerArgs() {
val primaryKeyField = createField("rowid")
val bodyField = createField("body")
val entity = FtsEntity(
element = mock(XTypeElement::class.java),
tableName = "Mail",
type = mock(XType::class.java),
fields = listOf(primaryKeyField, bodyField),
embeddedFields = emptyList(),
primaryKey = PrimaryKey(
declaredIn = mock(XElement::class.java),
fields = Fields(primaryKeyField),
autoGenerateId = true
),
constructor = null,
shadowTableName = "Mail_context",
ftsVersion = FtsVersion.FTS4,
ftsOptions = FtsOptions(
tokenizer = androidx.room.FtsOptions.TOKENIZER_PORTER,
tokenizerArgs = listOf("tokenchars=.=", "separators=X"),
contentEntity = null,
languageIdColumnName = "",
matchInfo = androidx.room.FtsOptions.MatchInfo.FTS4,
notIndexedColumns = emptyList(),
prefixSizes = emptyList(),
preferredOrder = androidx.room.FtsOptions.Order.ASC
)
)
assertThat(
entity.createTableQuery,
`is`(
"CREATE VIRTUAL TABLE IF NOT EXISTS `Mail` USING FTS4(" +
"`body` TEXT, " +
"tokenize=porter `tokenchars=.=` `separators=X`" +
")"
)
)
}
@Test
fun createStatement_nonSimpleTokenizer_noTokenizerArgs() {
val primaryKeyField = createField("rowid")
val bodyField = createField("body")
val entity = FtsEntity(
element = mock(XTypeElement::class.java),
tableName = "Mail",
type = mock(XType::class.java),
fields = listOf(primaryKeyField, bodyField),
embeddedFields = emptyList(),
primaryKey = PrimaryKey(
declaredIn = mock(XElement::class.java),
fields = Fields(primaryKeyField),
autoGenerateId = true
),
constructor = null,
shadowTableName = "Mail_context",
ftsVersion = FtsVersion.FTS4,
ftsOptions = FtsOptions(
tokenizer = androidx.room.FtsOptions.TOKENIZER_PORTER,
tokenizerArgs = emptyList(),
contentEntity = null,
languageIdColumnName = "",
matchInfo = androidx.room.FtsOptions.MatchInfo.FTS4,
notIndexedColumns = emptyList(),
prefixSizes = emptyList(),
preferredOrder = androidx.room.FtsOptions.Order.ASC
)
)
assertThat(
entity.createTableQuery,
`is`(
"CREATE VIRTUAL TABLE IF NOT EXISTS `Mail` USING FTS4(" +
"`body` TEXT, " +
"tokenize=porter" +
")"
)
)
}
fun createField(name: String): Field {
val (element, type) = mockElementAndType()
return Field(
element = element,
name = name,
type = type,
affinity = null,
collate = null,
columnName = name
)
}
} | apache-2.0 | c2a075a1301d381d8e6d64a82c3ed513 | 35.8327 | 79 | 0.541193 | 5.029076 | false | false | false | false |
jk1/youtrack-idea-plugin | src/main/kotlin/com/github/jk1/ytplugin/issues/actions/CreateIssueAction.kt | 1 | 2008 | package com.github.jk1.ytplugin.issues.actions
import com.github.jk1.ytplugin.ComponentAware
import com.github.jk1.ytplugin.rest.IssuesRestClient
import com.github.jk1.ytplugin.ui.YouTrackPluginIcons
import com.github.jk1.ytplugin.whenActive
import com.intellij.icons.AllIcons
import com.intellij.ide.BrowserUtil
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys.EDITOR
import com.intellij.openapi.project.DumbAware
import javax.swing.Icon
class EditorCreateIssueAction : CreateIssueAction(false, YouTrackPluginIcons.YOUTRACK)
class ToolWindowCreateIssueAction : CreateIssueAction(true, AllIcons.General.Add)
open class CreateIssueAction(val allowEmptyIssue: Boolean, icon: Icon) : AnAction(
"Create Issue",
"Create a new issue draft in YouTrack from the selected content",
icon
), DumbAware {
override fun actionPerformed(event: AnActionEvent) {
val text = getSelectedText(event)
event.whenActive { project ->
val repo = ComponentAware.of(project).taskManagerComponent.getAllConfiguredYouTrackRepositories().firstOrNull()
if (repo != null) {
val id = IssuesRestClient(repo).createDraft(text?.asCodeBlock() ?: "")
if (id != "") {
BrowserUtil.browse("${repo.url}/newIssue?draftId=$id")
}
}
}
}
private fun String.asCodeBlock() = "```\n$this\n```"
override fun update(event: AnActionEvent) {
val project = event.project ?: return
event.presentation.isVisible = (!getSelectedText(event).isNullOrBlank() || allowEmptyIssue) &&
ComponentAware.of(project).taskManagerComponent.getAllConfiguredYouTrackRepositories().isNotEmpty()
}
private fun getSelectedText(event: AnActionEvent): String? {
return EDITOR.getData(event.dataContext)?.caretModel?.currentCaret?.selectedText
}
} | apache-2.0 | a24319e3913b72d2dbbf1e9e214b7c85 | 40.854167 | 123 | 0.718625 | 4.574032 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/ide/intentions/RemoveDbgIntention.kt | 3 | 1913 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import org.rust.lang.core.psi.RsBinaryExpr
import org.rust.lang.core.psi.RsDotExpr
import org.rust.lang.core.psi.RsMacroCall
import org.rust.lang.core.psi.RsPsiFactory
import org.rust.lang.core.psi.ext.*
import kotlin.math.max
import kotlin.math.min
/**
* Removes the `dbg!` macro
*
* ```
* let a = dbg!(variable);
* ```
*
* to this:
*
* ```
* let a = variable;
* ```
*/
class RemoveDbgIntention : RsElementBaseIntentionAction<RsMacroCall>() {
override fun getText() = "Remove dbg!"
override fun getFamilyName() = text
override fun findApplicableContext(project: Project, editor: Editor, element: PsiElement): RsMacroCall? {
val macroCall = element.ancestorStrict<RsMacroCall>() ?: return null
if (macroCall.macroName != "dbg") {
return null
}
return macroCall
}
override fun invoke(project: Project, editor: Editor, ctx: RsMacroCall) {
val expr = ctx.exprMacroArgument?.expr ?: return
var cursorOffsetToExpr = max(0, editor.caretModel.offset - expr.startOffset)
val parent = ctx.parent.parent
val newExpr = if (expr is RsBinaryExpr && (parent is RsBinaryExpr || parent is RsDotExpr)) {
cursorOffsetToExpr += 1
ctx.replaceWithExpr(RsPsiFactory(project).createExpression("(${expr.text})"))
} else {
ctx.replaceWithExpr(expr)
}
PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(editor.document)
editor.caretModel.moveToOffset(min(newExpr.startOffset + cursorOffsetToExpr, newExpr.endOffset))
}
}
| mit | 63c253e175981345c27d8ab481d1dd29 | 31.423729 | 109 | 0.69472 | 4.140693 | false | false | false | false |
RSDT/Japp16 | app/src/main/java/nl/rsdt/japp/application/activities/LoginActivity.kt | 2 | 3337 | package nl.rsdt.japp.application.activities
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.os.Bundle
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import com.google.android.material.snackbar.Snackbar
import nl.rsdt.japp.R
import nl.rsdt.japp.jotial.auth.Authentication
import nl.rsdt.japp.jotial.data.structures.area348.UserInfo
import java.util.*
/**
* @author Dingenis Sieger Sinke
* @version 1.0
* @since 8-7-2016
* Description...
*/
class LoginActivity : Activity() {
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
val passwordLost = findViewById<TextView>(R.id.password_forgotten)
passwordLost.setOnClickListener {
val year = Calendar.getInstance().get(Calendar.YEAR)
val browser = Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.forget_password_url, year)))
startActivity(browser)
}
val button = findViewById<Button>(R.id.login)
button.setOnClickListener {
if (findViewById<EditText>(R.id.username).text.toString().isNotEmpty() && findViewById<EditText>(R.id.password).text.toString().isNotEmpty()) {
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager?
val focus = [email protected]
if (focus != null) {
imm?.hideSoftInputFromWindow(focus.windowToken, 0)
}
val authentication = Authentication.Builder()
.setUsername((findViewById<View>(R.id.username) as EditText).text.toString())
.setPassword((findViewById<View>(R.id.password) as EditText).text.toString())
.setCallback (object : Authentication.OnAuthenticationCompletedCallback{
override fun onAuthenticationCompleted(result: Authentication.AuthenticationResult) {
if (result.isSucceeded) {
UserInfo.collect()
val intent = Intent(this@LoginActivity, SplashActivity::class.java)
startActivity(intent)
finish()
} else {
Snackbar.make(findViewById(R.id.login_layout), result.message, Snackbar.LENGTH_LONG)
.setActionTextColor(Color.BLUE)
.show()
}
}
})
.create()
authentication.executeAsync()
} else {
Snackbar.make(findViewById(R.id.login_layout), getString(R.string.fill_all_fields), Snackbar.LENGTH_LONG)
.setActionTextColor(Color.BLUE)
.show()
}
}
}
companion object {
var TAG = "LoginActivity"
}
}
| apache-2.0 | f08a9ebb9f905581246c5c9565399703 | 39.204819 | 155 | 0.58166 | 5.255118 | false | false | false | false |
charleskorn/batect | app/src/unitTest/kotlin/batect/ui/text/TextRunSpec.kt | 1 | 14473 | /*
Copyright 2017-2020 Charles Korn.
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 batect.ui.text
import batect.testutils.equalTo
import batect.testutils.given
import batect.testutils.on
import batect.testutils.withMessage
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.throws
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
object TextRunSpec : Spek({
describe("a series of formatted text elements") {
describe("simplifying a series of text elements") {
given("an empty set of elements") {
val original = TextRun()
on("simplifying it") {
val simplified = original.simplify()
it("returns an empty set of elements") {
assertThat(simplified, equalTo(original))
}
}
}
given("a single text element") {
val original = TextRun("hello world")
on("simplifying it") {
val simplified = original.simplify()
it("returns that single text element") {
assertThat(simplified, equalTo(original))
}
}
}
given("two text elements with different bold formatting") {
val original = Text("Plain text") + Text.bold("Bold text")
on("simplifying it") {
val simplified = original.simplify()
it("returns those two elements") {
assertThat(simplified, equalTo(original))
}
}
}
given("two text elements with different colors") {
val original = Text.green("Green text") + Text.blue("Blue text")
on("simplifying it") {
val simplified = original.simplify()
it("returns those two elements") {
assertThat(simplified, equalTo(original))
}
}
}
given("two text elements with the same bold formatting") {
val original = Text.bold("First bold text") + Text.bold(" Second bold text")
on("simplifying it") {
val simplified = original.simplify()
it("returns a single combined element") {
assertThat(simplified, equalTo(TextRun(Text.bold("First bold text Second bold text"))))
}
}
}
given("two text elements with the same color") {
val original = Text.red("First red text") + Text.red(" Second red text")
on("simplifying it") {
val simplified = original.simplify()
it("returns a single combined element") {
assertThat(simplified, equalTo(TextRun(Text.red("First red text Second red text"))))
}
}
}
given("three text elements with the first two sharing the same formatting") {
val original = Text.red("First red text") + Text.red(" Second red text") + Text("Other text")
on("simplifying it") {
val simplified = original.simplify()
it("combines the first two elements and leaves the third as-is") {
assertThat(simplified, equalTo(TextRun(Text.red("First red text Second red text"), Text("Other text"))))
}
}
}
given("three text elements with the last two sharing the same formatting") {
val original = Text("Other text") + Text.red("First red text") + Text.red(" Second red text")
on("simplifying it") {
val simplified = original.simplify()
it("combines the last two elements and leaves the first as-is") {
assertThat(simplified, equalTo(TextRun(Text("Other text"), Text.red("First red text Second red text"))))
}
}
}
given("three text elements with all three sharing the same formatting") {
val original = Text.red("First red text") + Text.red(" Second red text") + Text.red(" Third red text")
on("simplifying it") {
val simplified = original.simplify()
it("returns a single combined element") {
assertThat(simplified, equalTo(TextRun(Text.red("First red text Second red text Third red text"))))
}
}
}
given("four text elements with the first two sharing the same formatting and the last two sharing a different set of formatting") {
val original = Text.red("First red text") + Text.red(" Second red text") + Text("First unformatted text") + Text(" Second unformatted text")
on("simplifying it") {
val simplified = original.simplify()
it("combines the first two elements and combines the last two elements") {
assertThat(simplified, equalTo(TextRun(Text.red("First red text Second red text"), Text("First unformatted text Second unformatted text"))))
}
}
}
}
describe("restricting text to a certain length") {
val length = 10
on("restricting text that is shorter than the width of the console") {
val text = TextRun("123456789")
it("returns all text") {
assertThat(text.limitToLength(length), equalTo(TextRun("123456789")))
}
}
on("restricting text that is equal to the width of the console") {
val text = TextRun("1234567890")
it("returns all text") {
assertThat(text.limitToLength(length), equalTo(TextRun("1234567890")))
}
}
on("restricting text made up of multiple segments that is equal to the width of the console") {
val text = Text("123456") + Text.red("7890")
it("returns all text") {
assertThat(text.limitToLength(length), equalTo(Text("123456") + Text.red("7890")))
}
}
on("restricting text that is longer than the width of the console") {
val text = TextRun("12345678901")
it("returns as much text as possible, replacing the last three characters with ellipsis") {
assertThat(text.limitToLength(length), equalTo(TextRun("1234567...")))
}
}
on("restricting text with multiple lines") {
val text = TextRun("12345678901\n")
it("throws an appropriate exception") {
assertThat({ text.limitToLength(length) }, throws<UnsupportedOperationException>(withMessage("Cannot restrict the length of text containing line breaks.")))
}
}
on("restricting text that is shorter than the width of the console but would contain more control characters than the width of the console") {
val text = TextRun(Text.red("abc123"))
it("returns all text, including the control characters") {
assertThat(text.limitToLength(length), equalTo(TextRun(Text.red("abc123"))))
}
}
on("restricting coloured text that is longer than the width of the console, with further coloured text afterwards") {
val text = Text.red("12345678901") + Text.white("white")
it("returns as much text as possible, replacing the last three characters with ellipsis, and does not include the redundant text element") {
assertThat(text.limitToLength(length), equalTo(TextRun(Text.red("1234567..."))))
}
}
on("restricting text where the colour would change for the first character of the ellipsis") {
val text = Text.red("abc1234") + Text.white("wwww")
it("returns the text, with the ellipsis taking the colour of the text it appears next to") {
assertThat(text.limitToLength(length), equalTo(TextRun(Text.red("abc1234..."))))
}
}
on("restricting text where the limit is the same as the length of the ellipsis") {
val text = TextRun(Text.red("This doesn't matter"))
it("returns just the ellipsis with the same formatting as the text") {
assertThat(text.limitToLength(3), equalTo(TextRun(Text.red("..."))))
}
}
on("restricting text where the limit is the less than the length of the ellipsis") {
val text = TextRun(Text.red("This doesn't matter"))
it("returns just the ellipsis with the same formatting as the text") {
assertThat(text.limitToLength(2), equalTo(TextRun(Text.red(".."))))
}
}
on("restricting text where the limit is zero") {
val text = TextRun(Text.red("This doesn't matter"))
it("returns an empty TextRun") {
assertThat(text.limitToLength(0), equalTo(TextRun()))
}
}
on("restricting an empty set of text") {
val text = TextRun()
it("returns an empty TextRun") {
assertThat(text.limitToLength(length), equalTo(TextRun()))
}
}
}
describe("splitting a single run by new line delimiters") {
given("the text run contains a single element") {
given("the element contains no new line characters") {
val text = TextRun("some text")
it("does not split the text") {
assertThat(text.lines, equalTo(listOf(TextRun("some text"))))
}
}
given("the element ends with a new line character") {
val text = TextRun("some text\n")
it("splits the text into two lines") {
assertThat(text.lines, equalTo(listOf(TextRun("some text"), TextRun())))
}
}
given("the element ends with multiple new line characters") {
val text = TextRun("some text\n\n")
it("returns two lines") {
assertThat(text.lines, equalTo(listOf(TextRun("some text"), TextRun(), TextRun())))
}
}
given("the element contains a single new line characters") {
val text = TextRun("line 1\nline 2")
it("splits the run into multiple parts") {
assertThat(text.lines, equalTo(listOf(TextRun("line 1"), TextRun("line 2"))))
}
}
given("the element contains multiple new line characters") {
val text = TextRun("line 1\nline 2\nline 3\nline 4")
it("splits the run into multiple parts") {
assertThat(text.lines, equalTo(listOf(TextRun("line 1"), TextRun("line 2"), TextRun("line 3"), TextRun("line 4"))))
}
}
given("the element contains multiple new line characters in a row") {
val text = TextRun("line 1\n\nline 2")
it("splits the run into multiple parts") {
assertThat(text.lines, equalTo(listOf(TextRun("line 1"), TextRun(), TextRun("line 2"))))
}
}
given("the element contains formatted text") {
val text = TextRun(Text.bold("some text"))
it("preserves the formatting of the text") {
assertThat(text.lines, equalTo(listOf(TextRun(Text.bold("some text")))))
}
}
}
given("the text run contains multiple elements") {
given("the elements do not contain any new line characters") {
val text = Text.bold("Hello ") + Text.red("world!")
it("returns a single line with both elements") {
assertThat(text.lines, equalTo(listOf(Text.bold("Hello ") + Text.red("world!"))))
}
}
given("there is a new line character at the end of one element") {
val text = Text.bold("Hello\n") + Text("world!")
it("returns two lines") {
assertThat(text.lines, equalTo(listOf(TextRun(Text.bold("Hello")), TextRun("world!"))))
}
}
given("there is a new line character in the middle of one element") {
val text = Text.bold("Hey\nHello ") + Text("world!")
it("returns two lines") {
assertThat(text.lines, equalTo(listOf(TextRun(Text.bold("Hey")), Text.bold("Hello ") + Text("world!"))))
}
}
given("there is one element that is just a new line character") {
val text = Text.bold("Hello") + Text("\n")
it("returns two lines") {
assertThat(text.lines, equalTo(listOf(TextRun(Text.bold("Hello")), TextRun())))
}
}
}
}
}
})
| apache-2.0 | 51b700f7263d7e147a4807dbcd991e4f | 40.82948 | 176 | 0.522697 | 5.264824 | false | false | false | false |
androidx/androidx | compose/material3/material3/src/commonMain/kotlin/androidx/compose/material3/Snackbar.kt | 3 | 18581 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.material3
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.paddingFromBaseline
import androidx.compose.foundation.layout.widthIn
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material3.tokens.SnackbarTokens
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.layout.AlignmentLine
import androidx.compose.ui.layout.FirstBaseline
import androidx.compose.ui.layout.LastBaseline
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.layout.layoutId
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.unit.dp
import kotlin.math.max
import kotlin.math.min
/**
* <a href="https://m3.material.io/components/snackbar/overview" class="external" target="_blank">Material Design snackbar</a>.
*
* Snackbars provide brief messages about app processes at the bottom of the screen.
*
* 
*
* Snackbars inform users of a process that an app has performed or will perform. They appear
* temporarily, towards the bottom of the screen. They shouldn’t interrupt the user experience,
* and they don’t require user input to disappear.
*
* A Snackbar can contain a single action. "Dismiss" or "cancel" actions are optional.
*
* Snackbars with an action should not timeout or self-dismiss until the user performs another
* action. Here, moving the keyboard focus indicator to navigate through interactive elements in a
* page is not considered an action.
*
* This component provides only the visuals of the Snackbar. If you need to show a Snackbar
* with defaults on the screen, use [SnackbarHostState.showSnackbar]:
*
* @sample androidx.compose.material3.samples.ScaffoldWithSimpleSnackbar
*
* If you want to customize appearance of the Snackbar, you can pass your own version as a child
* of the [SnackbarHost] to the [Scaffold]:
* @sample androidx.compose.material3.samples.ScaffoldWithCustomSnackbar
*
* @param modifier the [Modifier] to be applied to this snackbar
* @param action action / button component to add as an action to the snackbar. Consider using
* [ColorScheme.inversePrimary] as the color for the action, if you do not have a predefined color
* you wish to use instead.
* @param dismissAction action / button component to add as an additional close affordance action
* when a snackbar is non self-dismissive. Consider using [ColorScheme.inverseOnSurface] as the
* color for the action, if you do not have a predefined color you wish to use instead.
* @param actionOnNewLine whether or not action should be put on a separate line. Recommended for
* action with long action text.
* @param shape defines the shape of this snackbar's container
* @param containerColor the color used for the background of this snackbar. Use [Color.Transparent]
* to have no color.
* @param contentColor the preferred color for content inside this snackbar
* @param actionContentColor the preferred content color for the optional [action] inside this
* snackbar
* @param dismissActionContentColor the preferred content color for the optional [dismissAction]
* inside this snackbar
* @param content content to show information about a process that an app has performed or will
* perform
*/
@Composable
fun Snackbar(
modifier: Modifier = Modifier,
action: @Composable (() -> Unit)? = null,
dismissAction: @Composable (() -> Unit)? = null,
actionOnNewLine: Boolean = false,
shape: Shape = SnackbarDefaults.shape,
containerColor: Color = SnackbarDefaults.color,
contentColor: Color = SnackbarDefaults.contentColor,
actionContentColor: Color = SnackbarDefaults.actionContentColor,
dismissActionContentColor: Color = SnackbarDefaults.dismissActionContentColor,
content: @Composable () -> Unit
) {
Surface(
modifier = modifier,
shape = shape,
color = containerColor,
contentColor = contentColor,
shadowElevation = SnackbarTokens.ContainerElevation
) {
val textStyle = MaterialTheme.typography.fromToken(SnackbarTokens.SupportingTextFont)
val actionTextStyle = MaterialTheme.typography.fromToken(SnackbarTokens.ActionLabelTextFont)
CompositionLocalProvider(LocalTextStyle provides textStyle) {
when {
action == null -> OneRowSnackbar(
text = content,
action = null,
dismissAction = dismissAction,
actionTextStyle,
actionContentColor,
dismissActionContentColor
)
actionOnNewLine -> NewLineButtonSnackbar(
content,
action,
dismissAction,
actionTextStyle,
actionContentColor,
dismissActionContentColor
)
else -> OneRowSnackbar(
text = content,
action = action,
dismissAction = dismissAction,
actionTextStyle,
actionContentColor,
dismissActionContentColor
)
}
}
}
}
/**
* <a href="https://m3.material.io/components/snackbar/overview" class="external" target="_blank">Material Design snackbar</a>.
*
* Snackbars provide brief messages about app processes at the bottom of the screen.
*
* 
*
* Snackbars inform users of a process that an app has performed or will perform. They appear
* temporarily, towards the bottom of the screen. They shouldn’t interrupt the user experience,
* and they don’t require user input to disappear.
*
* A Snackbar can contain a single action. "Dismiss" or "cancel" actions are optional.
*
* Snackbars with an action should not timeout or self-dismiss until the user performs another
* action. Here, moving the keyboard focus indicator to navigate through interactive elements in a
* page is not considered an action.
*
* This version of snackbar is designed to work with [SnackbarData] provided by the
* [SnackbarHost], which is usually used inside of the [Scaffold].
*
* This components provides only the visuals of the Snackbar. If you need to show a Snackbar
* with defaults on the screen, use [SnackbarHostState.showSnackbar]:
*
* @sample androidx.compose.material3.samples.ScaffoldWithSimpleSnackbar
*
* If you want to customize appearance of the Snackbar, you can pass your own version as a child
* of the [SnackbarHost] to the [Scaffold]:
*
* @sample androidx.compose.material3.samples.ScaffoldWithCustomSnackbar
*
* When a [SnackbarData.visuals] sets the Snackbar's duration as [SnackbarDuration.Indefinite], it's
* recommended to display an additional close affordance action.
* See [SnackbarVisuals.withDismissAction]:
*
* @sample androidx.compose.material3.samples.ScaffoldWithIndefiniteSnackbar
*
* @param snackbarData data about the current snackbar showing via [SnackbarHostState]
* @param modifier the [Modifier] to be applied to this snackbar
* @param actionOnNewLine whether or not action should be put on a separate line. Recommended for
* action with long action text.
* @param shape defines the shape of this snackbar's container
* @param containerColor the color used for the background of this snackbar. Use [Color.Transparent]
* to have no color.
* @param contentColor the preferred color for content inside this snackbar
* @param actionColor the color of the snackbar's action
* @param actionContentColor the preferred content color for the optional action inside this
* snackbar. See [SnackbarVisuals.actionLabel].
* @param dismissActionContentColor the preferred content color for the optional dismiss action
* inside this snackbar. See [SnackbarVisuals.withDismissAction].
*/
@Composable
fun Snackbar(
snackbarData: SnackbarData,
modifier: Modifier = Modifier,
actionOnNewLine: Boolean = false,
shape: Shape = SnackbarDefaults.shape,
containerColor: Color = SnackbarDefaults.color,
contentColor: Color = SnackbarDefaults.contentColor,
actionColor: Color = SnackbarDefaults.actionColor,
actionContentColor: Color = SnackbarDefaults.actionContentColor,
dismissActionContentColor: Color = SnackbarDefaults.dismissActionContentColor,
) {
val actionLabel = snackbarData.visuals.actionLabel
val actionComposable: (@Composable () -> Unit)? = if (actionLabel != null) {
@Composable {
TextButton(
colors = ButtonDefaults.textButtonColors(contentColor = actionColor),
onClick = { snackbarData.performAction() },
content = { Text(actionLabel) }
)
}
} else {
null
}
val dismissActionComposable: (@Composable () -> Unit)? =
if (snackbarData.visuals.withDismissAction) {
@Composable {
IconButton(
onClick = { snackbarData.dismiss() },
content = {
Icon(
Icons.Filled.Close,
contentDescription = null, // TODO add "Dismiss Snackbar" to Strings.
)
}
)
}
} else {
null
}
Snackbar(
modifier = modifier.padding(12.dp),
action = actionComposable,
dismissAction = dismissActionComposable,
actionOnNewLine = actionOnNewLine,
shape = shape,
containerColor = containerColor,
contentColor = contentColor,
actionContentColor = actionContentColor,
dismissActionContentColor = dismissActionContentColor,
content = { Text(snackbarData.visuals.message) }
)
}
@Composable
private fun NewLineButtonSnackbar(
text: @Composable () -> Unit,
action: @Composable () -> Unit,
dismissAction: @Composable (() -> Unit)?,
actionTextStyle: TextStyle,
actionContentColor: Color,
dismissActionContentColor: Color
) {
Column(
modifier = Modifier
// Fill max width, up to ContainerMaxWidth.
.widthIn(max = ContainerMaxWidth)
.fillMaxWidth()
.padding(
start = HorizontalSpacing,
bottom = SeparateButtonExtraY
)
) {
Box(
Modifier.paddingFromBaseline(HeightToFirstLine, LongButtonVerticalOffset)
.padding(end = HorizontalSpacingButtonSide)
) { text() }
Box(
Modifier.align(Alignment.End)
.padding(end = if (dismissAction == null) HorizontalSpacingButtonSide else 0.dp)
) {
Row {
CompositionLocalProvider(
LocalContentColor provides actionContentColor,
LocalTextStyle provides actionTextStyle,
content = action
)
if (dismissAction != null) {
CompositionLocalProvider(
LocalContentColor provides dismissActionContentColor,
content = dismissAction
)
}
}
}
}
}
@Composable
private fun OneRowSnackbar(
text: @Composable () -> Unit,
action: @Composable (() -> Unit)?,
dismissAction: @Composable (() -> Unit)?,
actionTextStyle: TextStyle,
actionTextColor: Color,
dismissActionColor: Color
) {
val textTag = "text"
val actionTag = "action"
val dismissActionTag = "dismissAction"
Layout(
{
Box(Modifier.layoutId(textTag).padding(vertical = SnackbarVerticalPadding)) { text() }
if (action != null) {
Box(Modifier.layoutId(actionTag)) {
CompositionLocalProvider(
LocalContentColor provides actionTextColor,
LocalTextStyle provides actionTextStyle,
content = action
)
}
}
if (dismissAction != null) {
Box(Modifier.layoutId(dismissActionTag)) {
CompositionLocalProvider(
LocalContentColor provides dismissActionColor,
content = dismissAction
)
}
}
},
modifier = Modifier.padding(
start = HorizontalSpacing,
end = if (dismissAction == null) HorizontalSpacingButtonSide else 0.dp
)
) { measurables, constraints ->
val containerWidth = min(constraints.maxWidth, ContainerMaxWidth.roundToPx())
val actionButtonPlaceable =
measurables.firstOrNull { it.layoutId == actionTag }?.measure(constraints)
val dismissButtonPlaceable =
measurables.firstOrNull { it.layoutId == dismissActionTag }?.measure(constraints)
val actionButtonWidth = actionButtonPlaceable?.width ?: 0
val actionButtonHeight = actionButtonPlaceable?.height ?: 0
val dismissButtonWidth = dismissButtonPlaceable?.width ?: 0
val dismissButtonHeight = dismissButtonPlaceable?.height ?: 0
val extraSpacingWidth = if (dismissButtonWidth == 0) TextEndExtraSpacing.roundToPx() else 0
val textMaxWidth =
(containerWidth - actionButtonWidth - dismissButtonWidth - extraSpacingWidth)
.coerceAtLeast(constraints.minWidth)
val textPlaceable = measurables.first { it.layoutId == textTag }.measure(
constraints.copy(minHeight = 0, maxWidth = textMaxWidth)
)
val firstTextBaseline = textPlaceable[FirstBaseline]
require(firstTextBaseline != AlignmentLine.Unspecified) { "No baselines for text" }
val lastTextBaseline = textPlaceable[LastBaseline]
require(lastTextBaseline != AlignmentLine.Unspecified) { "No baselines for text" }
val isOneLine = firstTextBaseline == lastTextBaseline
val dismissButtonPlaceX = containerWidth - dismissButtonWidth
val actionButtonPlaceX = dismissButtonPlaceX - actionButtonWidth
val textPlaceY: Int
val containerHeight: Int
val actionButtonPlaceY: Int
if (isOneLine) {
val minContainerHeight = SnackbarTokens.SingleLineContainerHeight.roundToPx()
val contentHeight = max(actionButtonHeight, dismissButtonHeight)
containerHeight = max(minContainerHeight, contentHeight)
textPlaceY = (containerHeight - textPlaceable.height) / 2
actionButtonPlaceY = if (actionButtonPlaceable != null) {
actionButtonPlaceable[FirstBaseline].let {
if (it != AlignmentLine.Unspecified) {
textPlaceY + firstTextBaseline - it
} else {
0
}
}
} else {
0
}
} else {
val baselineOffset = HeightToFirstLine.roundToPx()
textPlaceY = baselineOffset - firstTextBaseline
val minContainerHeight = SnackbarTokens.TwoLinesContainerHeight.roundToPx()
val contentHeight = textPlaceY + textPlaceable.height
containerHeight = max(minContainerHeight, contentHeight)
actionButtonPlaceY = if (actionButtonPlaceable != null) {
(containerHeight - actionButtonPlaceable.height) / 2
} else {
0
}
}
val dismissButtonPlaceY = if (dismissButtonPlaceable != null) {
(containerHeight - dismissButtonPlaceable.height) / 2
} else {
0
}
layout(containerWidth, containerHeight) {
textPlaceable.placeRelative(0, textPlaceY)
dismissButtonPlaceable?.placeRelative(dismissButtonPlaceX, dismissButtonPlaceY)
actionButtonPlaceable?.placeRelative(actionButtonPlaceX, actionButtonPlaceY)
}
}
}
/**
* Contains the default values used for [Snackbar].
*/
object SnackbarDefaults {
/** Default shape of a snackbar. */
val shape: Shape @Composable get() = SnackbarTokens.ContainerShape.toShape()
/** Default color of a snackbar. */
val color: Color @Composable get() = SnackbarTokens.ContainerColor.toColor()
/** Default content color of a snackbar. */
val contentColor: Color @Composable get() = SnackbarTokens.SupportingTextColor.toColor()
/** Default action color of a snackbar. */
val actionColor: Color @Composable get() = SnackbarTokens.ActionLabelTextColor.toColor()
/** Default action content color of a snackbar. */
val actionContentColor: Color @Composable get() = SnackbarTokens.ActionLabelTextColor.toColor()
/** Default dismiss action content color of a snackbar. */
val dismissActionContentColor: Color @Composable get() = SnackbarTokens.IconColor.toColor()
}
private val ContainerMaxWidth = 600.dp
private val HeightToFirstLine = 30.dp
private val HorizontalSpacing = 16.dp
private val HorizontalSpacingButtonSide = 8.dp
private val SeparateButtonExtraY = 2.dp
private val SnackbarVerticalPadding = 6.dp
private val TextEndExtraSpacing = 8.dp
private val LongButtonVerticalOffset = 12.dp
| apache-2.0 | a4a3faaf76722e792bec83a69bf54a26 | 42.092807 | 127 | 0.673343 | 5.052503 | false | false | false | false |
EventFahrplan/EventFahrplan | app/src/test/java/nerd/tuxmobil/fahrplan/congress/repositories/AppRepositorySessionsTest.kt | 1 | 7768 | package nerd.tuxmobil.fahrplan.congress.repositories
import app.cash.turbine.test
import com.google.common.truth.Truth.assertThat
import info.metadude.android.eventfahrplan.commons.testing.MainDispatcherTestRule
import info.metadude.android.eventfahrplan.commons.testing.verifyInvokedOnce
import info.metadude.android.eventfahrplan.database.repositories.SessionsDatabaseRepository
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runTest
import nerd.tuxmobil.fahrplan.congress.TestExecutionContext
import nerd.tuxmobil.fahrplan.congress.dataconverters.toSessionsDatabaseModel
import nerd.tuxmobil.fahrplan.congress.models.Session
import org.junit.Assert.fail
import org.junit.Rule
import org.junit.Test
import org.mockito.kotlin.any
import org.mockito.kotlin.doReturn
import org.mockito.kotlin.mock
import org.mockito.kotlin.whenever
/**
* Test class to deal with sessions which interact with the [SessionsDatabaseRepository].
*/
@OptIn(ExperimentalCoroutinesApi::class)
class AppRepositorySessionsTest {
@get:Rule
val mainDispatcherTestRule = MainDispatcherTestRule()
private val sessionsDatabaseRepository = mock<SessionsDatabaseRepository>()
private val testableAppRepository: AppRepository
get() = with(AppRepository) {
initialize(
context = mock(),
logging = mock(),
executionContext = TestExecutionContext,
databaseScope = mock(),
networkScope = mock(),
okHttpClient = mock(),
alarmsDatabaseRepository = mock(),
highlightsDatabaseRepository = mock(),
sessionsDatabaseRepository = sessionsDatabaseRepository,
metaDatabaseRepository = mock(),
scheduleNetworkRepository = mock(),
engelsystemNetworkRepository = mock(),
sharedPreferencesRepository = mock(),
sessionsTransformer = mock()
)
return this
}
companion object {
private val SESSION_1001 = createSession("1001").apply {
changedIsCanceled = false
changedTitle = false
changedIsNew = false
}
private val SESSION_1002 = createSession("1002").apply {
changedIsCanceled = true
changedTitle = false
changedIsNew = false
}
private val SESSION_1003 = createSession("1003").apply {
changedIsCanceled = false
changedTitle = true
changedIsNew = false
}
private val SESSION_1004 = createSession("1004").apply {
changedIsCanceled = false
changedTitle = false
changedIsNew = true
}
private val SESSION_1005 = createSession("1005").apply {
changedIsCanceled = true
changedTitle = true
changedIsNew = true
}
private val SESSION_2001 = createSession("2001").apply {
highlight = false
changedIsCanceled = false
}
private val SESSION_2002 = createSession("2002").apply {
highlight = true
changedIsCanceled = false
}
private val SESSION_2003 = createSession("2003").apply {
highlight = true
changedIsCanceled = true
}
private val SESSION_2004 = createSession("2004").apply {
highlight = false
changedIsCanceled = true
}
private val SESSION_3001 = createSession("3001").apply {
changedIsCanceled = false
}
private val SESSION_3002 = createSession("3002").apply {
changedIsCanceled = true
}
private fun createSession(sessionId: String) = Session(sessionId).apply {
url = "" // only initialized for toSessionsDatabaseModel()
}
}
@Test
fun `loadChangedSessions passes through an empty list`() {
whenever(sessionsDatabaseRepository.querySessionsOrderedByDateUtc()) doReturn emptyList()
assertThat(testableAppRepository.loadChangedSessions()).isEmpty()
verifyInvokedOnce(sessionsDatabaseRepository).querySessionsOrderedByDateUtc()
}
@Test
fun `loadChangedSessions filters out sessions which are not changed`() {
val sessions = listOf(SESSION_1001, SESSION_1002, SESSION_1003, SESSION_1004, SESSION_1005)
whenever(sessionsDatabaseRepository.querySessionsOrderedByDateUtc()) doReturn sessions.toSessionsDatabaseModel()
val changedSessions = testableAppRepository.loadChangedSessions()
assertThat(changedSessions).containsExactly(SESSION_1002, SESSION_1003, SESSION_1004, SESSION_1005)
verifyInvokedOnce(sessionsDatabaseRepository).querySessionsOrderedByDateUtc()
}
@Test
fun `loadStarredSessions passes through an empty list`() = runTest {
whenever(sessionsDatabaseRepository.querySessionsOrderedByDateUtc()) doReturn emptyList()
testableAppRepository.starredSessions.test {
assertThat(awaitItem()).isEqualTo(emptyList<Session>())
}
verifyInvokedOnce(sessionsDatabaseRepository).querySessionsOrderedByDateUtc()
}
@Test
fun `loadStarredSessions filters out sessions which are not starred`() = runTest {
val sessions = listOf(SESSION_2001, SESSION_2002, SESSION_2003, SESSION_2004)
whenever(sessionsDatabaseRepository.querySessionsOrderedByDateUtc()) doReturn sessions.toSessionsDatabaseModel()
testableAppRepository.starredSessions.test {
assertThat(awaitItem()).containsExactly(SESSION_2002)
}
verifyInvokedOnce(sessionsDatabaseRepository).querySessionsOrderedByDateUtc()
}
@Test
fun `loadUncanceledSessionsForDayIndex passes through an empty list`() {
whenever(sessionsDatabaseRepository.querySessionsForDayIndexOrderedByDateUtc(any())) doReturn emptyList()
assertThat(testableAppRepository.loadUncanceledSessionsForDayIndex(0)).isEmpty()
verifyInvokedOnce(sessionsDatabaseRepository).querySessionsForDayIndexOrderedByDateUtc(any())
}
@Test
fun `loadUncanceledSessionsForDayIndex filters out sessions which are canceled`() {
val sessions = listOf(SESSION_3001, SESSION_3002)
whenever(sessionsDatabaseRepository.querySessionsForDayIndexOrderedByDateUtc(any())) doReturn sessions.toSessionsDatabaseModel()
val uncanceledSessions = testableAppRepository.loadUncanceledSessionsForDayIndex(0)
assertThat(uncanceledSessions).containsExactly(SESSION_3001)
verifyInvokedOnce(sessionsDatabaseRepository).querySessionsForDayIndexOrderedByDateUtc(any())
}
@Test
fun `loadEarliestSession fails when no session is present`() {
whenever(sessionsDatabaseRepository.querySessionsOrderedByDateUtc()) doReturn emptyList()
try {
testableAppRepository.loadEarliestSession()
fail("Expect a NoSuchElementException to be thrown.")
} catch (e: NoSuchElementException) {
assertThat(e.message).isEqualTo("List is empty.")
}
verifyInvokedOnce(sessionsDatabaseRepository).querySessionsOrderedByDateUtc()
}
@Test
fun `loadEarliestSession returns the first session of the first day`() {
val sessions = listOf(SESSION_1005, SESSION_1001)
whenever(sessionsDatabaseRepository.querySessionsOrderedByDateUtc()) doReturn sessions.toSessionsDatabaseModel()
assertThat(testableAppRepository.loadEarliestSession()).isEqualTo(SESSION_1005)
verifyInvokedOnce(sessionsDatabaseRepository).querySessionsOrderedByDateUtc()
}
}
| apache-2.0 | 0c7e80b55f467b25442b53bc2ac25fc9 | 39.884211 | 136 | 0.690911 | 5.58046 | false | true | false | false |
Etik-Tak/backend | src/main/kotlin/dk/etiktak/backend/security/TokenService.kt | 1 | 3334 | // Copyright (c) 2017, Daniel Andersen ([email protected])
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// 3. The name of the author may not be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package dk.etiktak.backend.security
import dk.etiktak.backend.model.user.Client
import dk.etiktak.backend.repository.user.ClientRepository
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.security.authentication.BadCredentialsException
import org.springframework.stereotype.Service
import java.util.*
@Service
open class TokenService @Autowired constructor(
private val clientRepository: ClientRepository) {
private val logger = LoggerFactory.getLogger(TokenService::class.java)
companion object {
val timeout: Long = 2 * 60 * 60 * 1000
}
@Scheduled(fixedRate = 2 * (1 * 60 * 60 * 1000))
fun generateNewEncryptor() {
TokenEncryptionCache.sharedInstance.generateNewEncryptor()
}
/**
* Generates a new token from the given client.
*
* @param client Client
* @return Token
*/
fun generateNewToken(client: Client): String {
return TokenEncryptionCache.sharedInstance.encryptToken(TokenCacheEntry(client.uuid, Date().time))
}
/**
* Finds the client from a given token, or null, if the token is invalid or outdated.
*
* @param token Token
* @return Client
*/
fun getClientFromToken(token: String): Client? {
val now = Date().time
val tokenCacheEntry = TokenEncryptionCache.sharedInstance.decryptToken(token)
if (now - tokenCacheEntry.creationTime!! <= timeout) {
return clientRepository.findByUuid(tokenCacheEntry.clientUuid!!) ?: throw BadCredentialsException("Invalid token")
} else {
throw BadCredentialsException("Token has timed out")
}
}
} | bsd-3-clause | 666a6548e6227e41e0d48b730f04ff39 | 41.21519 | 126 | 0.733353 | 4.735795 | false | false | false | false |
westnordost/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/ferry/AddFerryAccessPedestrian.kt | 1 | 1144 | package de.westnordost.streetcomplete.quests.ferry
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.osm.osmquest.OsmFilterQuestType
import de.westnordost.streetcomplete.data.osm.changes.StringMapChangesBuilder
import de.westnordost.streetcomplete.ktx.toYesNo
import de.westnordost.streetcomplete.quests.YesNoQuestAnswerFragment
class AddFerryAccessPedestrian : OsmFilterQuestType<Boolean>() {
override val elementFilter = "ways, relations with route = ferry and !foot"
override val commitMessage = "Specify ferry access for pedestrians"
override val wikiLink = "Tag:route=ferry"
override val icon = R.drawable.ic_quest_ferry_pedestrian
override val hasMarkersAtEnds = true
override fun getTitle(tags: Map<String, String>): Int =
if (tags.containsKey("name"))
R.string.quest_ferry_pedestrian_name_title
else
R.string.quest_ferry_pedestrian_title
override fun createForm() = YesNoQuestAnswerFragment()
override fun applyAnswerTo(answer: Boolean, changes: StringMapChangesBuilder) {
changes.add("foot", answer.toYesNo())
}
}
| gpl-3.0 | 97cf1459b3a44c5fa67ebc3a04468ae9 | 39.857143 | 83 | 0.761364 | 4.434109 | false | false | false | false |
HabitRPG/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/BaseFragment.kt | 1 | 3680 | package com.habitrpg.android.habitica.ui.fragments
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.viewbinding.ViewBinding
import com.habitrpg.android.habitica.HabiticaBaseApplication
import com.habitrpg.android.habitica.components.UserComponent
import com.habitrpg.android.habitica.data.TutorialRepository
import com.habitrpg.android.habitica.helpers.ExceptionHandler
import com.habitrpg.android.habitica.proxy.AnalyticsManager
import com.habitrpg.android.habitica.ui.activities.MainActivity
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.disposables.CompositeDisposable
import java.util.concurrent.TimeUnit
import javax.inject.Inject
abstract class BaseFragment<VB : ViewBinding> : Fragment() {
var isModal: Boolean = false
abstract var binding: VB?
@Inject
lateinit var tutorialRepository: TutorialRepository
@Inject
lateinit var analyticsManager: AnalyticsManager
var tutorialStepIdentifier: String? = null
protected var tutorialCanBeDeferred = true
var tutorialTexts: List<String> = ArrayList()
protected var compositeSubscription: CompositeDisposable = CompositeDisposable()
var shouldInitializeComponent = true
open val displayedClassName: String?
get() = this.javaClass.simpleName
fun initializeComponent() {
if (!shouldInitializeComponent) return
HabiticaBaseApplication.userComponent?.let {
injectFragment(it)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
initializeComponent()
super.onCreate(savedInstanceState)
}
abstract fun createBinding(inflater: LayoutInflater, container: ViewGroup?): VB
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
compositeSubscription = CompositeDisposable()
binding = createBinding(inflater, container)
return binding?.root
}
abstract fun injectFragment(component: UserComponent)
override fun onResume() {
super.onResume()
showTutorialIfNeeded()
}
private fun showTutorialIfNeeded() {
tutorialStepIdentifier?.let { identifier ->
compositeSubscription.add(
tutorialRepository.getTutorialStep(identifier)
.firstElement()
.delay(1, TimeUnit.SECONDS)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ step ->
if (step.isValid && step.isManaged && step.shouldDisplay) {
val mainActivity = activity as? MainActivity ?: return@subscribe
mainActivity.displayTutorialStep(step, tutorialTexts, tutorialCanBeDeferred)
}
},
ExceptionHandler.rx()
)
)
}
}
override fun onDestroyView() {
binding = null
if (!compositeSubscription.isDisposed) {
compositeSubscription.dispose()
}
super.onDestroyView()
}
override fun onDestroy() {
try {
tutorialRepository.close()
} catch (exception: UninitializedPropertyAccessException) { /* no-on */ }
super.onDestroy()
}
open fun addToBackStack(): Boolean = true
}
| gpl-3.0 | 6b9ee37041ce0448018cfdbf6413871f | 31.454545 | 108 | 0.644837 | 5.795276 | false | false | false | false |
google/zsldemo | app/src/main/java/com/hadrosaur/zsldemo/CameraParams.kt | 1 | 8374 | /*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hadrosaur.zsldemo
import android.graphics.ImageFormat
import android.hardware.camera2.*
import android.hardware.camera2.CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL
import android.media.Image
import android.media.ImageReader
import android.media.ImageWriter
import android.os.Handler
import android.os.HandlerThread
import android.util.Size
import androidx.appcompat.app.AppCompatActivity
import com.hadrosaur.zsldemo.CameraController.CameraDeviceStateCallback
import com.hadrosaur.zsldemo.CameraController.CaptureSessionCallback
import com.hadrosaur.zsldemo.MainActivity.Companion.Logd
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*
class CameraParams {
var id = "0"
var device: CameraDevice? = null
var characteristics: CameraCharacteristics? = null
var isOpen = false
var canReprocess = false
var cameraDeviceStateCallback: CameraDeviceStateCallback? = null
var captureSessionCallback: CaptureSessionCallback? = null
var backgroundThread: HandlerThread? = null
var backgroundHandler: Handler? = null
var previewBuilder: CaptureRequest.Builder? = null
var captureBuilder: CaptureRequest.Builder? = null
var recaptureBuilder: CaptureRequest.Builder? = null
var captureSession: CameraCaptureSession? = null
var previewTextureView: AutoFitTextureView? = null
var jpegImageReader: ImageReader? = null
var privateImageReader: ImageReader? = null
var recaptureImageWriter: ImageWriter? = null
var captureImageAvailableListener: CaptureImageAvailableListener? = null
var saveImageAvailableListener: SaveImageAvailableListener? = null
var minSize: Size = Size(0, 0)
var maxSize: Size = Size(0, 0)
var minJpegSize: Size = Size(0, 0)
var maxJpegSize: Size = Size(0, 0)
//For latency measurements
var captureStart: Long = 0
var captureEnd: Long = 0
var debugImage: Image? = null
var debugResult: TotalCaptureResult? = null
}
fun setupCameraParams(activity: MainActivity, params: CameraParams) {
val manager = activity.getSystemService(AppCompatActivity.CAMERA_SERVICE) as CameraManager
params.apply {
try {
//Default to the first camera, which will normally be "0" (Rear)
id = "0"
if (!manager.cameraIdList.contains("0")) {
//For devices with no rear camera, like many chromebooks, this will probably be "1" (Front)
//This program cannot handle devices with no camera
for (cameraId in manager.cameraIdList) {
id = cameraId
}
}
} catch (accessError: CameraAccessException) {
accessError.printStackTrace()
}
characteristics = manager.getCameraCharacteristics(id)
previewTextureView = activity.texture_foreground
previewTextureView?.surfaceTextureListener = TextureListener(activity, params, activity.texture_foreground)
captureImageAvailableListener = CaptureImageAvailableListener(activity, params)
saveImageAvailableListener = SaveImageAvailableListener(activity, params)
val cameraCapabilities = manager.getCameraCharacteristics(id).get(CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES)
for (capability in cameraCapabilities) {
when (capability) {
CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_PRIVATE_REPROCESSING -> canReprocess = true
}
}
Logd("Camera can reprocess: " + canReprocess)
Logd("Supported Hardware Level: " + characteristics?.get(INFO_SUPPORTED_HARDWARE_LEVEL))
//Get image capture sizes
val map = characteristics?.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP)
if (map != null) {
// Logd("Input formats: " + Arrays.toString(map.inputFormats))
// Logd("Output formats: " + Arrays.toString(map.outputFormats))
maxSize = Collections.max(
Arrays.asList(*map.getOutputSizes(ImageFormat.PRIVATE)),
CompareSizesByArea())
//Camera devices can only support up to 1920x1080 with PRIVATE and preview
// maxSize = chooseSmallEnoughSize(map.getOutputSizes(ImageFormat.PRIVATE), 1920, 1080)
minSize = Collections.min(
Arrays.asList(*map.getOutputSizes(ImageFormat.PRIVATE)),
CompareSizesByArea())
maxJpegSize = Collections.max(
Arrays.asList(*map.getOutputSizes(ImageFormat.JPEG)),
CompareSizesByArea())
minJpegSize = Collections.max(
Arrays.asList(*map.getOutputSizes(ImageFormat.JPEG)),
CompareSizesByArea())
// Logd("Max width: " + maxSize.width + " Max height: " + maxSize.height)
// Logd("Min width: " + minSize.width + " Min height: " + minSize.height)
/* for (size in map.getOutputSizes(ImageFormat.PRIVATE)) {
Logd("Supported size: " + size.width + "x" + size.height)
}
*/
setupImageReaders(activity, params)
} //if map != null
}
}
fun setupImageReaders(activity: MainActivity, params: CameraParams) {
with (params) {
params.jpegImageReader?.close()
params.privateImageReader?.close()
params.recaptureImageWriter?.close()
// jpegImageReader = ImageReader.newInstance(3264, 2448,
// ImageFormat.JPEG, /*maxImages*/CIRCULAR_BUFFER_SIZE + 1)
// privateImageReader = ImageReader.newInstance(3264, 2448,
// ImageFormat.PRIVATE, /*maxImages*/CIRCULAR_BUFFER_SIZE + 1)
jpegImageReader = ImageReader.newInstance(maxJpegSize.width, maxJpegSize.height,
ImageFormat.JPEG, /*maxImages*/CIRCULAR_BUFFER_SIZE + 1)
privateImageReader = ImageReader.newInstance(maxSize.width, maxSize.height,
ImageFormat.PRIVATE, /*maxImages*/CIRCULAR_BUFFER_SIZE + 1)
privateImageReader?.setOnImageAvailableListener(captureImageAvailableListener, backgroundHandler)
jpegImageReader?.setOnImageAvailableListener(saveImageAvailableListener, backgroundHandler)
//For some cameras, using the max preview size can conflict with big image captures
//We just uses the smallest preview size to avoid this situation
params.previewTextureView?.surfaceTexture?.setDefaultBufferSize(minSize.width, minSize.height)
params.previewTextureView?.setAspectRatio(minSize.width, minSize.height)
}
}
internal class CompareSizesByArea : Comparator<Size> {
override fun compare(lhs: Size, rhs: Size): Int {
// We cast here to ensure the multiplications won't overflow
return java.lang.Long.signum(lhs.width.toLong() * lhs.height - rhs.width.toLong() * rhs.height)
}
}
/**
* Given `choices` of `Size`s supported by a camera, chooses the largest one whose
* width and height are at less than the given max values
* @param choices The list of sizes that the camera supports for the intended output class
* @param width The maximum desired width
* @param height The maximum desired height
* @return The optimal `Size`, or an arbitrary one if none were big enough
*/
internal fun chooseSmallEnoughSize(choices: Array<Size>, width: Int, height: Int): Size {
val smallEnough = ArrayList<Size>()
for (option in choices) {
if (option.width <= width && option.height <= height) {
smallEnough.add(option)
}
}
// Pick the smallest of those, assuming we found any
if (smallEnough.size > 0) {
return Collections.max(smallEnough, CompareSizesByArea())
} else {
Logd("Couldn't find any suitable preview size")
return choices[0]
}
}
| apache-2.0 | 3c385bf8aa16b9831d535605c9aa3293 | 39.84878 | 127 | 0.693456 | 4.629077 | false | false | false | false |
hotmobmobile/hotmob-android-sdk | AndroidStudio/HotmobSDKShowcase/preloaddemo/src/main/java/com/hotmob/preloaddemo/SplashActivity.kt | 1 | 4216 | package com.hotmob.preloaddemo
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import androidx.lifecycle.ProcessLifecycleOwner
import com.hotmob.sdk.ad.*
import com.hotmob.sdk.module.reload.HotmobReloadManager
class SplashActivity : AppCompatActivity(), HotmobAdListener, HotmobAdDeepLinkListener,
LifecycleObserver {
private val interstitial = HotmobInterstitial("LaunchApp", "hotmob_android_google_ad", false)
private var selfLoadingComplete = false
private var interstitialDeepLink = ""
private var goToMainAfterResume = false
private var isAppActive = true
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_splash)
interstitial.listener = this
interstitial.deepLinkListener = this
ProcessLifecycleOwner.get().lifecycle.addObserver(this)
}
override fun onResume() {
super.onResume()
if (goToMainAfterResume) {
// For case of Interstitial already show before
changeToMainPage()
} else if (interstitial.adState == HotmobAdState.INIT) {
// Preload ad
interstitial.loadAd(this)
// demonstrate loading time
Handler(Looper.getMainLooper()).postDelayed({
selfLoadingComplete = true
shouldShowInterstitial()
}, 3000)
}
}
override fun onDestroy() {
ProcessLifecycleOwner.get().lifecycle.removeObserver(this)
super.onDestroy()
}
private fun shouldShowInterstitial() {
Log.d("Splash", "shouldShowInterstitial $selfLoadingComplete")
// Determine showing Ad or switching page
if (interstitial.adState == HotmobAdState.LOADED && selfLoadingComplete) {
interstitial.showAd(this)
} else if (interstitial.adState == HotmobAdState.NO_AD && selfLoadingComplete) {
changeToMainPage()
}
}
private fun changeToMainPage() {
Log.d("Splash", "changeToMainPage")
interstitial.listener = null
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
finish()
}
override fun onAdEvent(adEvent: HotmobAdEvent) {
Log.d("Splash", "on event $adEvent")
when (adEvent) {
HotmobAdEvent.LOADED -> {
shouldShowInterstitial()
}
HotmobAdEvent.NO_AD -> {
shouldShowInterstitial()
}
HotmobAdEvent.HIDE -> {
// delay 500ms to wait in case of deep link click or switching app by ad landing
// deep link event is fired right after hide event
Handler(Looper.getMainLooper()).postDelayed({
// Deep link action here
if (!interstitialDeepLink.isBlank())
Toast.makeText(this, "Deep link $interstitialDeepLink Received", Toast.LENGTH_SHORT).show()
// Check app active
if (isAppActive) {
// Safe to change page
changeToMainPage()
} else {
// Should not open new Activity when app is not active, wait for next resume app
goToMainAfterResume = true
}
}, 500)
}
else -> {}
}
}
override fun onDeepLink(deepLink: String) {
Log.d("Splash", "on deep link $deepLink")
interstitialDeepLink = deepLink
}
// Track App activity
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun onAppBackgrounded() {
Log.d("Splash", "App in background")
isAppActive = false
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun onAppForegrounded() {
Log.d("Splash", "App in foreground")
isAppActive = true
}
}
| mit | 7b3ce5fa30b7e9189d894eb6382372c9 | 33.842975 | 115 | 0.618121 | 5.001186 | false | false | false | false |
artspb/php-generator | src/main/kotlin/me/artspb/php/generator/PhpGenerator.kt | 1 | 1222 | package me.artspb.php.generator
import me.artspb.php.generator.model.compound.Php
import java.io.File
import java.util.*
fun dir(path: String, nodes: DirNode.() -> Unit): DirNode {
val dir = DirNode(path)
dir.nodes()
return dir
}
interface Node {
fun create(relativePath: String = "")
}
class FileNode(private val name: String, val php: () -> Php) : Node {
override fun create(relativePath: String) = File(relativePath + name).printWriter().use { out -> out.print(php().toString()) }
}
class DirNode(path: String) : Node {
private val path = if (path.endsWith('/') || path.endsWith('\\')) path else path + File.separator
private val children = ArrayDeque<Node>()
fun file(name: String, php: () -> Php) = createNode(FileNode(name, php), {})
fun dir(path: String, nodes: DirNode.() -> Unit) = createNode(DirNode(path), nodes)
private fun <E : Node> createNode(node: E, nodes: E.() -> Unit): E {
node.nodes()
children.add(node)
return node
}
override fun create(relativePath: String) {
File(relativePath + path).mkdirs()
while (children.isNotEmpty()) {
children.poll().create(relativePath + path)
}
}
}
| apache-2.0 | 8d0cf196b1ee34d55f9db4e3967121cf | 28.095238 | 130 | 0.630933 | 3.636905 | false | false | false | false |
andrewoma/kwery | core/src/main/kotlin/com/github/andrewoma/kwery/core/builder/QueryBuilder.kt | 1 | 4501 | package com.github.andrewoma.kwery.core.builder
import java.util.*
/*
* Copyright (c) 2016 Andrew O'Malley
*
* 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.
*/
/**
* QueryBuilder is a simple SQL query builder to ease building dynamic queries
* where clauses and parameters may be optional.
*
* It is not a type-safe builder, it simply allows fragments of an SQL statement
* to be added in any order and then builds the statement.
*
* The main feature is provides is allowing where clauses to be combined with
* an operator, taking care of cases where groups end up being empty.
*/
class QueryBuilder {
private val selects = LinkedHashSet<String>()
private val params = mutableMapOf<String, Any?>()
private var filters: Filter.Group = Filter.Group()
private var groupBy: String? = null
private var having: String? = null
private var orderBy: String? = null
fun select(table: String) {
selects.add(table)
}
fun parameter(name: String, value: Any?) {
params.put(name, value)
}
fun groupBy(groupBy: String) {
this.groupBy = groupBy
}
fun having(having: String) {
this.having = having
}
fun orderBy(orderBy: String) {
this.orderBy = orderBy
}
fun whereGroup(operator: String = "and", block: FilterBuilder.() -> Unit) {
require(filters.countLeaves() == 0) { "There must be only one root filters group" }
filters = Filter.Group(operator)
block(FilterBuilder(filters))
}
inner class FilterBuilder(private val group: Filter.Group) {
fun where(where: String) {
group.filters.add(Filter.Where(where))
}
fun whereGroup(operator: String = "and", block: FilterBuilder.() -> Unit) {
val inner = Filter.Group(operator)
group.filters.add(inner)
block(FilterBuilder(inner))
}
}
fun build(sb: StringBuilder = StringBuilder(), block: QueryBuilder.() -> Unit): Query {
block(this)
selects.joinTo(sb, "\n")
if (filters.countLeaves() != 0) {
sb.append("\nwhere ")
appendConditions(sb, filters, true)
}
groupBy?.run { sb.append("\ngroup by ").append(groupBy) }
having?.run { sb.append("\nhaving ").append(having) }
orderBy?.run { sb.append("\norder by ").append(orderBy) }
return Query(sb, params)
}
private fun appendConditions(sb: StringBuilder, conditions: Filter, root: Boolean) {
when (conditions) {
is Filter.Where -> sb.append(conditions.where)
is Filter.Group -> appendConditions(conditions, root, sb)
}
}
private fun appendConditions(conditions: Filter.Group, root: Boolean, sb: StringBuilder) {
val filtered = conditions.filters.filter { it.countLeaves() != 0 }
when (filtered.size) {
0 -> Unit
1 -> appendConditions(sb, filtered.first(), false)
else -> {
if (!root) sb.append("\n(")
for ((i, condition) in filtered.withIndex()) {
appendConditions(sb, condition, false)
if (i != filtered.indices.last) sb.append(" ${conditions.operator} ")
}
if (!root) sb.append(")")
}
}
}
}
fun query(sb: StringBuilder = StringBuilder(), block: QueryBuilder.() -> Unit): Query {
return QueryBuilder().build(sb, block)
}
| mit | 9a6dc2fb8887b651933b313878dea1a0 | 35.008 | 94 | 0.641857 | 4.357212 | false | false | false | false |
NerdNumber9/TachiyomiEH | app/src/main/java/eu/kanade/tachiyomi/data/download/DownloadService.kt | 1 | 5985 | package eu.kanade.tachiyomi.data.download
import android.app.Notification
import android.app.Service
import android.content.Context
import android.content.Intent
import android.net.NetworkInfo.State.CONNECTED
import android.net.NetworkInfo.State.DISCONNECTED
import android.os.Build
import android.os.IBinder
import android.os.PowerManager
import android.support.v4.app.NotificationCompat
import com.github.pwittchen.reactivenetwork.library.Connectivity
import com.github.pwittchen.reactivenetwork.library.ReactiveNetwork
import com.jakewharton.rxrelay.BehaviorRelay
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.notification.Notifications
import eu.kanade.tachiyomi.data.preference.PreferencesHelper
import eu.kanade.tachiyomi.util.connectivityManager
import eu.kanade.tachiyomi.util.plusAssign
import eu.kanade.tachiyomi.util.powerManager
import eu.kanade.tachiyomi.util.toast
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import rx.subscriptions.CompositeSubscription
import uy.kohesive.injekt.injectLazy
/**
* This service is used to manage the downloader. The system can decide to stop the service, in
* which case the downloader is also stopped. It's also stopped while there's no network available.
* While the downloader is running, a wake lock will be held.
*/
class DownloadService : Service() {
companion object {
/**
* Relay used to know when the service is running.
*/
val runningRelay: BehaviorRelay<Boolean> = BehaviorRelay.create(false)
/**
* Starts this service.
*
* @param context the application context.
*/
fun start(context: Context) {
val intent = Intent(context, DownloadService::class.java)
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
context.startService(intent)
} else {
context.startForegroundService(intent)
}
}
/**
* Stops this service.
*
* @param context the application context.
*/
fun stop(context: Context) {
context.stopService(Intent(context, DownloadService::class.java))
}
}
/**
* Download manager.
*/
private val downloadManager: DownloadManager by injectLazy()
/**
* Preferences helper.
*/
private val preferences: PreferencesHelper by injectLazy()
/**
* Wake lock to prevent the device to enter sleep mode.
*/
private val wakeLock by lazy {
powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "DownloadService:WakeLock")
}
/**
* Subscriptions to store while the service is running.
*/
private lateinit var subscriptions: CompositeSubscription
/**
* Called when the service is created.
*/
override fun onCreate() {
super.onCreate()
startForeground(Notifications.ID_DOWNLOAD_CHAPTER, getPlaceholderNotification())
runningRelay.call(true)
subscriptions = CompositeSubscription()
listenDownloaderState()
listenNetworkChanges()
}
/**
* Called when the service is destroyed.
*/
override fun onDestroy() {
runningRelay.call(false)
subscriptions.unsubscribe()
downloadManager.stopDownloads()
wakeLock.releaseIfNeeded()
super.onDestroy()
}
/**
* Not used.
*/
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
return Service.START_NOT_STICKY
}
/**
* Not used.
*/
override fun onBind(intent: Intent): IBinder? {
return null
}
/**
* Listens to network changes.
*
* @see onNetworkStateChanged
*/
private fun listenNetworkChanges() {
subscriptions += ReactiveNetwork.observeNetworkConnectivity(applicationContext)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ state -> onNetworkStateChanged(state)
}, { _ ->
toast(R.string.download_queue_error)
stopSelf()
})
}
/**
* Called when the network state changes.
*
* @param connectivity the new network state.
*/
private fun onNetworkStateChanged(connectivity: Connectivity) {
when (connectivity.state) {
CONNECTED -> {
if (preferences.downloadOnlyOverWifi() && connectivityManager.isActiveNetworkMetered) {
downloadManager.stopDownloads(getString(R.string.download_notifier_text_only_wifi))
} else {
val started = downloadManager.startDownloads()
if (!started) stopSelf()
}
}
DISCONNECTED -> {
downloadManager.stopDownloads(getString(R.string.download_notifier_no_network))
}
else -> { /* Do nothing */ }
}
}
/**
* Listens to downloader status. Enables or disables the wake lock depending on the status.
*/
private fun listenDownloaderState() {
subscriptions += downloadManager.runningRelay.subscribe { running ->
if (running)
wakeLock.acquireIfNeeded()
else
wakeLock.releaseIfNeeded()
}
}
/**
* Releases the wake lock if it's held.
*/
fun PowerManager.WakeLock.releaseIfNeeded() {
if (isHeld) release()
}
/**
* Acquires the wake lock if it's not held.
*/
fun PowerManager.WakeLock.acquireIfNeeded() {
if (!isHeld) acquire()
}
private fun getPlaceholderNotification(): Notification {
return NotificationCompat.Builder(this, Notifications.CHANNEL_DOWNLOADER)
.setContentTitle(getString(R.string.download_notifier_downloader_title))
.build()
}
}
| apache-2.0 | f448c578eaeb0eb3ebaa862170f8dba4 | 29.692308 | 103 | 0.636591 | 5.025189 | false | false | false | false |
anrelic/Anci-OSS | service/src/spec/kotlin/su/jfdev/anci/service/ServiceLoaderSpec.kt | 1 | 1376 | package su.jfdev.anci.service
import io.kotlintest.specs.*
abstract class ServiceLoaderSpec<T: Any>(val clazz: Class<T>, val loader: ServiceLoader): FreeSpec() {
init {
"should return provider by type of service" {
val service = loader[clazz]
assert(clazz.isInstance(service))
}
"when servicing by Class way" - {
"valid class" {
val count = loader[VALID].count()
count shouldBe 1
}
"invalid class" {
val count = loader[INVALID].count()
count shouldBe 0
}
"when clazz is incompatible" - {
"should skip him and try next" {
loader[Partially::class.java].count() shouldBe 1
}
}
}
"when servicing by String way" - {
"valid class name" {
val count = loader[VALID.canonicalName].count()
count shouldBe 1
}
"invalid class name" {
val count = loader[INVALID.canonicalName].count()
count shouldBe 1
}
}
}
val INVALID = Fail::class.java
val VALID = Successful::class.java
}
interface Successful
interface Fail
object AnyImplementation: Successful, Partially
interface Partially
object FailPart | mit | 234df3eaf9505a663deb44db8844d740 | 27.6875 | 102 | 0.534157 | 4.84507 | false | false | false | false |
exponentjs/exponent | packages/expo-splash-screen/android/src/main/java/expo/modules/splashscreen/SplashScreenViewController.kt | 2 | 3770 | package expo.modules.splashscreen
import android.app.Activity
import android.os.Handler
import android.view.View
import android.view.ViewGroup
import expo.modules.splashscreen.exceptions.NoContentViewException
import java.lang.ref.WeakReference
const val SEARCH_FOR_ROOT_VIEW_INTERVAL = 20L
open class SplashScreenViewController(
activity: Activity,
private val rootViewClass: Class<out ViewGroup>,
private val splashScreenView: View
) {
private val weakActivity = WeakReference(activity)
private val contentView: ViewGroup = activity.findViewById(android.R.id.content)
?: throw NoContentViewException()
private val handler = Handler()
private var autoHideEnabled = true
private var splashScreenShown = false
private var rootView: ViewGroup? = null
// region public lifecycle
open fun showSplashScreen(successCallback: () -> Unit = {}) {
weakActivity.get()?.runOnUiThread {
(splashScreenView.parent as? ViewGroup)?.removeView(splashScreenView)
contentView.addView(splashScreenView)
splashScreenShown = true
successCallback()
searchForRootView()
}
}
fun preventAutoHide(
successCallback: (hasEffect: Boolean) -> Unit,
failureCallback: (reason: String) -> Unit
) {
if (!autoHideEnabled || !splashScreenShown) {
return successCallback(false)
}
autoHideEnabled = false
successCallback(true)
}
open fun hideSplashScreen(
successCallback: (hasEffect: Boolean) -> Unit = {},
failureCallback: (reason: String) -> Unit = {}
) {
if (!splashScreenShown) {
return successCallback(false)
}
// activity SHOULD be present at this point - if it's not, it means that application is already dead
val activity = weakActivity.get()
if (activity == null || activity.isFinishing || activity.isDestroyed) {
return failureCallback("Cannot hide native splash screen on activity that is already destroyed (application is already closed).")
}
activity.runOnUiThread {
contentView.removeView(splashScreenView)
autoHideEnabled = true
splashScreenShown = false
successCallback(true)
}
}
// endregion
/**
* Searches for RootView that conforms to class given via [SplashScreen.show].
* If [rootView] is already found this method is noop.
*/
private fun searchForRootView() {
if (rootView != null) {
return
}
// RootView is successfully found in first check (nearly impossible for first call)
findRootView(contentView)?.let { return@searchForRootView handleRootView(it) }
handler.postDelayed({ searchForRootView() }, SEARCH_FOR_ROOT_VIEW_INTERVAL)
}
private fun findRootView(view: View): ViewGroup? {
if (rootViewClass.isInstance(view)) {
return view as ViewGroup
}
if (view != splashScreenView && view is ViewGroup) {
for (idx in 0 until view.childCount) {
findRootView(view.getChildAt(idx))?.let { return@findRootView it }
}
}
return null
}
private fun handleRootView(view: ViewGroup) {
rootView = view
if ((rootView?.childCount ?: 0) > 0) {
if (autoHideEnabled) {
hideSplashScreen()
}
}
view.setOnHierarchyChangeListener(object : ViewGroup.OnHierarchyChangeListener {
override fun onChildViewRemoved(parent: View, child: View) {
// TODO: ensure mechanism for detecting reloading view hierarchy works (reload button)
if (rootView?.childCount == 0) {
showSplashScreen()
}
}
override fun onChildViewAdded(parent: View, child: View) {
// react only to first child
if (rootView?.childCount == 1) {
if (autoHideEnabled) {
hideSplashScreen()
}
}
}
})
}
}
| bsd-3-clause | 014543bac1421738c8d59318817a87e8 | 29.16 | 135 | 0.683289 | 4.694894 | false | false | false | false |
myoffe/kotlin-koans | src/i_introduction/_4_Lambdas/Lambdas.kt | 1 | 701 | package i_introduction._4_Lambdas
import util.TODO
import util.doc4
fun example() {
val sum = { x: Int, y: Int -> x + y }
val square: (Int) -> Int = { x -> x * x }
sum(1, square(2)) == 5
}
fun todoTask4(collection: Collection<Int>): Nothing = TODO(
"""
Task 4.
Rewrite 'JavaCode4.task4()' in Kotlin using lambdas.
You can find the appropriate function to call on 'collection' through IntelliJ's code completion feature.
(Don't use the class 'Iterables').
""",
documentation = doc4(),
references = { JavaCode4().task4(collection) })
fun task4(collection: Collection<Int>): Boolean {
return collection.any { x -> x % 42 == 0 }
}
| mit | 4a3bc17c2b1e6cb95a1d655a9c180ee4 | 22.366667 | 113 | 0.610556 | 3.670157 | false | false | false | false |
PolymerLabs/arcs | java/arcs/sdk/android/storage/service/BoundService.kt | 1 | 4557 | package arcs.sdk.android.storage.service
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.IBinder
import android.os.IInterface
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlinx.atomicfu.atomic
import kotlinx.coroutines.CancellableContinuation
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.suspendCancellableCoroutine
/**
* This interface exists so that we can swap out normal Android service connection routines
* with, for example, a Robolectric variant.
*
* In the majority of cases, you should be able to use one of the two existing implementations:
* [DefaultBindHelper] and [TestBindHelper].
*/
interface BindHelper {
/** A context related to this [BindHelper]. Useful for creating [Intent], for example. */
val context: Context
/** The method signature for [Context.bindService]. */
fun bind(intent: Intent, connection: ServiceConnection, flags: Int): Boolean
/** The method signature for [Context.unindService]. */
fun unbind(connection: ServiceConnection)
}
/**
* The default [BindHelper] implementation that uses the standard Android [context.bindService]
* and [context.unbindService] methods.
*/
class DefaultBindHelper(
/** A [Context] that's capable of calling [bindService] and [unbindService] methods. */
override val context: Context
) : BindHelper {
override fun bind(intent: Intent, connection: ServiceConnection, flags: Int): Boolean {
return context.bindService(intent, connection, flags)
}
override fun unbind(connection: ServiceConnection) {
context.unbindService(connection)
}
}
/**
* This represents a currently-connected service that can be disconnected. Use the
* [BindHelper.bindForIntent] extension method on a bindHelper to get a new instance.
*
* If the provided scope is cancelled while the [BoundService] is still active, the instance will
* disconnect and will no longer work.
*/
class BoundService<T : IInterface> internal constructor(
val service: T,
private val bindHelper: BindHelper,
private val connection: ServiceConnection,
scope: CoroutineScope
) {
private val connected = atomic(true)
private val completionJob = Job(scope.coroutineContext[Job.Key]).also {
it.invokeOnCompletion {
disconnect()
}
}
/** Disconnect from the service. The [service] property can no longer be used. */
fun disconnect() {
if (connected.getAndSet(false)) {
bindHelper.unbind(connection)
if (!completionJob.isCompleted) {
completionJob.complete()
}
}
}
}
/**
* Use the [BindHelper] to create and return a new [BoundService] of type [T].
*
* The [asInterface] parameter is most likely one of these two options:
* * For local-only services, pass { it as T }
* * For AIDL services, pass `IMyInterface.Stub::asInterface`
*
* If the service connection fails, this method will throw an exception.
*
* @param intent the Intent describing the service to connect to
* @param asInterface a method to converter [IBinder] into your service interface type [T]
* @param onDisconnected an optional method that will be called if the service disconnects
*/
suspend fun <T : IInterface> BindHelper.bindForIntent(
intent: Intent,
scope: CoroutineScope,
asInterface: (IBinder) -> T,
onDisconnected: (() -> Unit) = {}
): BoundService<T> {
return suspendCancellableCoroutine { continuation ->
SuspendServiceConnection(this, scope, continuation, onDisconnected, asInterface).run {
val willConnect = bind(intent, this, Context.BIND_AUTO_CREATE)
if (!willConnect) {
continuation.resumeWithException(Exception("Won't connect"))
}
}
}
}
/**
* This helper wraps a continuation with a StorageService connection.
*/
private class SuspendServiceConnection<T : IInterface>(
private val bindHelper: BindHelper,
private val scope: CoroutineScope,
private val continuation: CancellableContinuation<BoundService<T>>,
private val onDisconnected: () -> Unit = {},
private val asInterface: (IBinder) -> T
) : ServiceConnection {
private lateinit var service: IBinder
@Suppress("UNCHECKED_CAST")
override fun onServiceConnected(name: ComponentName?, service: IBinder) {
this.service = service
continuation.resume(BoundService(asInterface(service), bindHelper, this, scope))
}
override fun onServiceDisconnected(name: ComponentName?) {
onDisconnected()
}
}
| bsd-3-clause | fc32e1a089d692c4f30ccf374c236f9c | 33.522727 | 97 | 0.743691 | 4.419981 | false | false | false | false |
PolymerLabs/arcs | java/arcs/android/labs/host/AndroidManifestHostRegistry.kt | 1 | 3888 | /*
* Copyright 2020 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
package arcs.android.labs.host
import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import androidx.annotation.VisibleForTesting
import arcs.core.host.ArcHost
import arcs.core.host.HostRegistry
import arcs.core.host.api.Particle
import arcs.sdk.android.labs.host.ArcHostHelper
import arcs.sdk.android.labs.host.IntentRegistryAdapter
import arcs.sdk.android.labs.host.toRegistryHost
import kotlinx.coroutines.TimeoutCancellationException
/**
* A [HostRegistry] that discovers available [ArcHost] services by using [PackageManager] to
* query Android [Service] declarations in AndroidManfiest which can respond to a specific [Intent]
* Stub [ArcHost] instances are created which communicate with the [Service] via [Intent]-based
* RPC.
*
* In AndroidManifest.xml a <service> will need to be declared as follows for auto-discovery:
* ```xml
* <service android:name=".MyService" android:exported="false">
* <intent-filter>
* <action android:name="arcs.android.host.ARCS_HOST" />
* </intent-filter>
* </service>
* ```
* These [ArcHost] implementations are [ExternalHost]s mostly assumed to have
* pre-registered particles. [ProdHost] will still find its [Particle] implementations
* via [ServiceLoaderHostRegistry]
*
* @property context An android application context
* @property sender A method used to deliver an [Intent] to a [Service]
*/
class AndroidManifestHostRegistry private constructor(
private val context: Context,
private val sender: (Intent) -> Unit
) : HostRegistry() {
private val serviceHosts = mutableListOf<IntentRegistryAdapter>()
private val arcHosts = mutableListOf<ArcHost>()
/** Discover all Android services which handle [ArcHost] operations. */
fun initialize(): AndroidManifestHostRegistry = apply {
serviceHosts.addAll(findHostsByManifest())
}
/**
* Inspects AndroidManifest.xml for any <service> tags with
* ```xml
* <intent-filter>
* <action android:name="arcs.android.host.ARC_HOST"/>
* </intent-filter>
* ```
*
* Constructs an [ArcHost] delegate that communicates via [Intent]s for each
* [Service] discovered.
*/
private fun findHostsByManifest(): List<IntentRegistryAdapter> =
context.packageManager.queryIntentServices(
Intent(ArcHostHelper.ACTION_HOST_INTENT),
PackageManager.MATCH_ALL
)
.filter { it.serviceInfo != null }
.map { it.serviceInfo.toRegistryHost(sender) }
override suspend fun availableArcHosts(): List<ArcHost> {
if (arcHosts.isEmpty()) {
arcHosts.addAll(serviceHosts.flatMap { registryHost ->
try {
registryHost.registeredHosts()
} catch (e: TimeoutCancellationException) {
emptyList<ArcHost>()
}
})
}
return arcHosts
}
override suspend fun registerHost(host: ArcHost) {
throw UnsupportedOperationException(
"Hosts cannot be registered directly, use registerService()"
)
}
override suspend fun unregisterHost(host: ArcHost) {
throw UnsupportedOperationException(
"Hosts cannot be unregistered directly, use unregisterService()"
)
}
companion object {
/** Auxiliary constructor with default sender. */
fun create(ctx: Context) =
AndroidManifestHostRegistry(ctx) { intent -> ctx.startService(intent) }.initialize()
/** Auxiliary constructor for testing. */
@VisibleForTesting
fun createForTest(ctx: Context, sender: (Intent) -> Unit) =
AndroidManifestHostRegistry(ctx, sender).initialize()
}
}
| bsd-3-clause | 0ebe9cf49c48beb5dbabb5549533d074 | 33.105263 | 99 | 0.723765 | 4.263158 | false | false | false | false |
Maccimo/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/roots/KotlinNonJvmSourceRootConverterProvider.kt | 2 | 10791 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.roots
import com.intellij.conversion.*
import com.intellij.conversion.impl.ConversionContextImpl
import com.intellij.openapi.roots.ExternalProjectSystemRegistry
import com.intellij.openapi.roots.OrderRootType
import com.intellij.openapi.roots.impl.libraries.ApplicationLibraryTable
import com.intellij.openapi.roots.impl.libraries.LibraryEx
import com.intellij.openapi.roots.libraries.Library
import com.intellij.openapi.roots.libraries.LibraryKindRegistry
import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar
import com.intellij.openapi.roots.libraries.PersistentLibraryKind
import com.intellij.openapi.vfs.JarFileSystem
import com.intellij.openapi.vfs.VirtualFile
import org.jdom.Element
import org.jetbrains.jps.model.JpsElement
import org.jetbrains.jps.model.JpsElementFactory
import org.jetbrains.jps.model.java.JavaResourceRootType
import org.jetbrains.jps.model.java.JavaSourceRootType
import org.jetbrains.jps.model.module.JpsModuleSourceRootType
import org.jetbrains.jps.model.module.JpsTypedModuleSourceRoot
import org.jetbrains.jps.model.serialization.facet.JpsFacetSerializer
import org.jetbrains.jps.model.serialization.module.JpsModuleRootModelSerializer.*
import org.jetbrains.kotlin.config.getFacetPlatformByConfigurationElement
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.base.platforms.JsStdlibDetectionUtil
import org.jetbrains.kotlin.idea.facet.KotlinFacetType
import org.jetbrains.kotlin.idea.framework.JavaRuntimeDetectionUtil
import org.jetbrains.kotlin.platform.CommonPlatforms
import org.jetbrains.kotlin.platform.TargetPlatform
import org.jetbrains.kotlin.platform.isCommon
import org.jetbrains.kotlin.platform.js.JsPlatforms
import org.jetbrains.kotlin.platform.jvm.JvmPlatforms
import org.jetbrains.kotlin.platform.jvm.isJvm
import org.jetbrains.kotlin.utils.PathUtil
import java.util.*
private val rootTypesToMigrate: List<JpsModuleSourceRootType<*>> = listOf(
JavaSourceRootType.SOURCE,
JavaSourceRootType.TEST_SOURCE,
JavaResourceRootType.RESOURCE,
JavaResourceRootType.TEST_RESOURCE
)
// TODO(dsavvinov): review how it behaves in HMPP environment
private val PLATFORM_TO_STDLIB_DETECTORS: Map<TargetPlatform, (Array<VirtualFile>) -> Boolean> = mapOf(
JvmPlatforms.unspecifiedJvmPlatform to { roots: Array<VirtualFile> ->
JavaRuntimeDetectionUtil.getRuntimeJar(roots.toList()) != null
},
JsPlatforms.defaultJsPlatform to { roots: Array<VirtualFile> ->
JsStdlibDetectionUtil.getJavaScriptStdLibJar(roots.toList()) != null
},
CommonPlatforms.defaultCommonPlatform to { roots: Array<VirtualFile> ->
roots.any { PathUtil.KOTLIN_STDLIB_COMMON_JAR_PATTERN.matcher(it.name).matches() }
}
)
internal class KotlinNonJvmSourceRootConverterProvider : ConverterProvider() {
sealed class LibInfo {
class ByXml(
private val element: Element,
private val conversionContext: ConversionContext,
private val moduleSettings: ModuleSettings
) : LibInfo() {
override val explicitKind: PersistentLibraryKind<*>?
get() = LibraryKindRegistry.getInstance().findKindById(element.getAttributeValue("type")) as? PersistentLibraryKind<*>
override fun getRoots(): Array<VirtualFile> {
val contextImpl = conversionContext as? ConversionContextImpl ?: return VirtualFile.EMPTY_ARRAY
val classRoots = contextImpl.getClassRootUrls(element, moduleSettings)
val jarFileSystem = JarFileSystem.getInstance()
return classRoots
.map {
if (it.startsWith(JarFileSystem.PROTOCOL_PREFIX)) {
jarFileSystem.findFileByPath(it.substring(JarFileSystem.PROTOCOL_PREFIX.length))
} else {
null
}
}
.filter(Objects::nonNull)
.toArray{ arrayOfNulls<VirtualFile>(it) }
}
}
class ByLibrary(private val library: Library) : LibInfo() {
override val explicitKind: PersistentLibraryKind<*>?
get() = (library as? LibraryEx)?.kind
override fun getRoots(): Array<VirtualFile> = library.getFiles(OrderRootType.CLASSES)
}
abstract val explicitKind: PersistentLibraryKind<*>?
abstract fun getRoots(): Array<VirtualFile>
val stdlibPlatform: TargetPlatform? by lazy {
val roots = getRoots()
for ((platform, detector) in PLATFORM_TO_STDLIB_DETECTORS) {
if (detector.invoke(roots)) {
return@lazy platform
}
}
return@lazy null
}
}
class ConverterImpl(private val context: ConversionContext) : ProjectConverter() {
private val projectLibrariesByName by lazy {
context.projectLibrariesSettings.projectLibraries.groupBy { it.getAttributeValue(NAME_ATTRIBUTE) }
}
private fun findGlobalLibrary(name: String) = ApplicationLibraryTable.getApplicationTable().getLibraryByName(name)
private fun findProjectLibrary(name: String) = projectLibrariesByName[name]?.firstOrNull()
private fun createLibInfo(orderEntryElement: Element, moduleSettings: ModuleSettings): LibInfo? {
return when (orderEntryElement.getAttributeValue("type")) {
MODULE_LIBRARY_TYPE -> {
orderEntryElement.getChild(LIBRARY_TAG)?.let { LibInfo.ByXml(it, context, moduleSettings) }
}
LIBRARY_TYPE -> {
val libraryName = orderEntryElement.getAttributeValue(NAME_ATTRIBUTE) ?: return null
when (orderEntryElement.getAttributeValue(LEVEL_ATTRIBUTE)) {
LibraryTablesRegistrar.PROJECT_LEVEL ->
findProjectLibrary(libraryName)?.let { LibInfo.ByXml(it, context, moduleSettings) }
LibraryTablesRegistrar.APPLICATION_LEVEL ->
findGlobalLibrary(libraryName)?.let { LibInfo.ByLibrary(it) }
else ->
null
}
}
else -> null
}
}
override fun createModuleFileConverter(): ConversionProcessor<ModuleSettings> {
return object : ConversionProcessor<ModuleSettings>() {
private fun ModuleSettings.detectPlatformByFacet(): TargetPlatform? {
return getFacetElement(KotlinFacetType.ID)
?.getChild(JpsFacetSerializer.CONFIGURATION_TAG)
?.getFacetPlatformByConfigurationElement()
}
private fun detectPlatformByDependencies(moduleSettings: ModuleSettings): TargetPlatform? {
var hasCommonStdlib = false
moduleSettings.orderEntries
.asSequence()
.mapNotNull { createLibInfo(it, moduleSettings) }
.forEach {
val stdlibPlatform = it.stdlibPlatform
if (stdlibPlatform != null) {
if (stdlibPlatform.isCommon()) {
hasCommonStdlib = true
} else {
return stdlibPlatform
}
}
}
return if (hasCommonStdlib) CommonPlatforms.defaultCommonPlatform else null
}
private fun ModuleSettings.detectPlatform(): TargetPlatform {
return detectPlatformByFacet()
?: detectPlatformByDependencies(this)
?: JvmPlatforms.unspecifiedJvmPlatform
}
private fun ModuleSettings.getSourceFolderElements(): List<Element> {
val rootManagerElement = getComponentElement(ModuleSettings.MODULE_ROOT_MANAGER_COMPONENT) ?: return emptyList()
return rootManagerElement
.getChildren(CONTENT_TAG)
.flatMap { it.getChildren(SOURCE_FOLDER_TAG) }
}
private fun ModuleSettings.isExternalModule(): Boolean {
return when {
rootElement.getAttributeValue(ExternalProjectSystemRegistry.EXTERNAL_SYSTEM_ID_KEY) != null -> true
rootElement.getAttributeValue(ExternalProjectSystemRegistry.IS_MAVEN_MODULE_KEY)?.toBoolean() ?: false -> true
else -> false
}
}
override fun isConversionNeeded(settings: ModuleSettings): Boolean {
if (settings.isExternalModule()) return false
val hasMigrationRoots = settings.getSourceFolderElements().any {
loadSourceRoot(it).rootType in rootTypesToMigrate
}
if (!hasMigrationRoots) {
return false
}
val targetPlatform = settings.detectPlatform()
return (!targetPlatform.isJvm())
}
override fun process(settings: ModuleSettings) {
for (sourceFolder in settings.getSourceFolderElements()) {
val contentRoot = sourceFolder.parent as? Element ?: continue
val oldSourceRoot = loadSourceRoot(sourceFolder)
val (newRootType, data) = oldSourceRoot.getMigratedSourceRootTypeWithProperties() ?: continue
val url = sourceFolder.getAttributeValue(URL_ATTRIBUTE)!!
@Suppress("UNCHECKED_CAST")
val newSourceRoot = JpsElementFactory.getInstance().createModuleSourceRoot(url, newRootType, data)
as? JpsTypedModuleSourceRoot<JpsElement> ?: continue
contentRoot.removeContent(sourceFolder)
saveSourceRoot(contentRoot, url, newSourceRoot)
}
}
}
}
}
override fun getConversionDescription() =
KotlinBundle.message("roots.description.text.update.source.roots.for.non.jvm.modules.in.kotlin.project")
override fun createConverter(context: ConversionContext) = ConverterImpl(context)
} | apache-2.0 | 0647f6089f33bf0ba7a5efd17d98ee6a | 46.964444 | 134 | 0.629135 | 5.839286 | false | false | false | false |
mdaniel/intellij-community | platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/ParentWithNullsMultipleImpl.kt | 1 | 9126 | package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.extractOneToManyChildren
import com.intellij.workspaceModel.storage.impl.updateOneToManyChildrenOfParent
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class ParentWithNullsMultipleImpl: ParentWithNullsMultiple, WorkspaceEntityBase() {
companion object {
internal val CHILDREN_CONNECTION_ID: ConnectionId = ConnectionId.create(ParentWithNullsMultiple::class.java, ChildWithNullsMultiple::class.java, ConnectionId.ConnectionType.ONE_TO_MANY, true)
val connections = listOf<ConnectionId>(
CHILDREN_CONNECTION_ID,
)
}
@JvmField var _parentData: String? = null
override val parentData: String
get() = _parentData!!
override val children: List<ChildWithNullsMultiple>
get() = snapshot.extractOneToManyChildren<ChildWithNullsMultiple>(CHILDREN_CONNECTION_ID, this)!!.toList()
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: ParentWithNullsMultipleData?): ModifiableWorkspaceEntityBase<ParentWithNullsMultiple>(), ParentWithNullsMultiple.Builder {
constructor(): this(ParentWithNullsMultipleData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity ParentWithNullsMultiple is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isParentDataInitialized()) {
error("Field ParentWithNullsMultiple#parentData should be initialized")
}
if (!getEntityData().isEntitySourceInitialized()) {
error("Field ParentWithNullsMultiple#entitySource should be initialized")
}
// Check initialization for collection with ref type
if (_diff != null) {
if (_diff.extractOneToManyChildren<WorkspaceEntityBase>(CHILDREN_CONNECTION_ID, this) == null) {
error("Field ParentWithNullsMultiple#children should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] == null) {
error("Field ParentWithNullsMultiple#children should be initialized")
}
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
override var parentData: String
get() = getEntityData().parentData
set(value) {
checkModificationAllowed()
getEntityData().parentData = value
changedProperty.add("parentData")
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
// List of non-abstract referenced types
var _children: List<ChildWithNullsMultiple>? = emptyList()
override var children: List<ChildWithNullsMultiple>
get() {
// Getter of the list of non-abstract referenced types
val _diff = diff
return if (_diff != null) {
_diff.extractOneToManyChildren<ChildWithNullsMultiple>(CHILDREN_CONNECTION_ID, this)!!.toList() + (this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] as? List<ChildWithNullsMultiple> ?: emptyList())
} else {
this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] as? List<ChildWithNullsMultiple> ?: emptyList()
}
}
set(value) {
// Setter of the list of non-abstract referenced types
checkModificationAllowed()
val _diff = diff
if (_diff != null) {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*> && (item_value as? ModifiableWorkspaceEntityBase<*>)?.diff == null) {
_diff.addEntity(item_value)
}
}
_diff.updateOneToManyChildrenOfParent(CHILDREN_CONNECTION_ID, this, value)
}
else {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*>) {
item_value.entityLinks[EntityLink(false, CHILDREN_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
}
this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] = value
}
changedProperty.add("children")
}
override fun getEntityData(): ParentWithNullsMultipleData = result ?: super.getEntityData() as ParentWithNullsMultipleData
override fun getEntityClass(): Class<ParentWithNullsMultiple> = ParentWithNullsMultiple::class.java
}
}
class ParentWithNullsMultipleData : WorkspaceEntityData<ParentWithNullsMultiple>() {
lateinit var parentData: String
fun isParentDataInitialized(): Boolean = ::parentData.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<ParentWithNullsMultiple> {
val modifiable = ParentWithNullsMultipleImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): ParentWithNullsMultiple {
val entity = ParentWithNullsMultipleImpl()
entity._parentData = parentData
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
return entity
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return ParentWithNullsMultiple::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as ParentWithNullsMultipleData
if (this.parentData != other.parentData) return false
if (this.entitySource != other.entitySource) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as ParentWithNullsMultipleData
if (this.parentData != other.parentData) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + parentData.hashCode()
return result
}
} | apache-2.0 | 698a2431fe7530227876ef5e3ba37227 | 40.866972 | 226 | 0.631821 | 6.199728 | false | false | false | false |
micolous/metrodroid | src/commonMain/kotlin/au/id/micolous/metrodroid/transit/kmt/KMTTrip.kt | 1 | 3132 | /*
* KMTTrip.kt
*
* Copyright 2018 Bondan Sumbodo <[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 au.id.micolous.metrodroid.transit.kmt
import au.id.micolous.metrodroid.card.felica.FelicaBlock
import au.id.micolous.metrodroid.multi.Localizer
import au.id.micolous.metrodroid.multi.Parcelize
import au.id.micolous.metrodroid.multi.R
import au.id.micolous.metrodroid.time.Timestamp
import au.id.micolous.metrodroid.transit.Station
import au.id.micolous.metrodroid.transit.TransitCurrency
import au.id.micolous.metrodroid.transit.Trip
import au.id.micolous.metrodroid.util.StationTableReader
@Parcelize
class KMTTrip (private val mProcessType: Int,
private val mSequenceNumber: Int,
override val startTimestamp: Timestamp?,
private val mTransactionAmount: Int,
private val mEndGateCode: Int): Trip() {
// Normally, only the end station is recorded. But top-ups only have a "starting" station.
override val startStation: Station?
get() = if (mProcessType == 0 || mProcessType == 2) {
getStation(mEndGateCode)
} else null
// "Ending station" doesn't make sense for Ticket Machines or Point-of-sale
override val endStation: Station?
get() = if (mProcessType == 0 || mProcessType == 2) {
null
} else getStation(mEndGateCode)
override val mode: Trip.Mode
get() = when (mProcessType) {
0 -> Trip.Mode.TICKET_MACHINE
1 -> Trip.Mode.TRAIN
2 -> Trip.Mode.POS
else -> Trip.Mode.OTHER
}
override val fare: TransitCurrency?
get() = if (mProcessType != 1) {
TransitCurrency.IDR(mTransactionAmount).negate()
} else TransitCurrency.IDR(mTransactionAmount)
override fun getAgencyName(isShort: Boolean) = Localizer.localizeFormatted(R.string.kmt_agency)
companion object {
fun parse(block: FelicaBlock): KMTTrip {
val data = block.data
return KMTTrip(
mProcessType = data[12].toInt() and 0xff,
mSequenceNumber = data.byteArrayToInt(13, 3),
startTimestamp = KMTTransitData.parseTimestamp(data),
mTransactionAmount = data.byteArrayToInt(4, 4),
mEndGateCode = data.byteArrayToInt(8, 2))
}
private const val KMT_STR = "kmt"
private fun getStation(code: Int) = StationTableReader.getStation(KMT_STR, code)
}
}
| gpl-3.0 | 0c27a1527994ec1e1b843336ed46f28f | 37.666667 | 99 | 0.670498 | 4.099476 | false | false | false | false |
android/play-billing-samples | PlayBillingCodelab/start/src/main/java/com/sample/subscriptionscodelab/ui/theme/Color.kt | 2 | 952 | /*
* Copyright 2022 Google, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sample.subscriptionscodelab.ui.theme
import androidx.compose.ui.graphics.Color
val Purple200 = Color(0xFFBB86FC)
val Purple500 = Color(0xFF6200EE)
val Purple700 = Color(0xFF3700B3)
val Teal200 = Color(0xFF03DAC5)
val Navy = Color(0xFF073042)
val Blue = Color(0xFF4285F4)
val LightBlue = Color(0xFFD7EFFE)
val Chartreuse = Color(0xFFEFF7CF)
| apache-2.0 | 8f4f7258500284e1baf26d517fbe01cb | 33 | 75 | 0.759454 | 3.474453 | false | false | false | false |
WhisperSystems/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/components/voice/VoiceNoteDraft.kt | 1 | 921 | package org.thoughtcrime.securesms.components.voice
import android.net.Uri
import org.thoughtcrime.securesms.database.DraftDatabase
import java.lang.IllegalArgumentException
private const val SIZE = "size"
class VoiceNoteDraft(
val uri: Uri,
val size: Long
) {
companion object {
@JvmStatic
fun fromDraft(draft: DraftDatabase.Draft): VoiceNoteDraft {
if (draft.type != DraftDatabase.Draft.VOICE_NOTE) {
throw IllegalArgumentException()
}
val draftUri = Uri.parse(draft.value)
val uri: Uri = draftUri.buildUpon().clearQuery().build()
val size: Long = draftUri.getQueryParameter("size")!!.toLong()
return VoiceNoteDraft(uri, size)
}
}
fun asDraft(): DraftDatabase.Draft {
val draftUri = uri.buildUpon().appendQueryParameter(SIZE, size.toString())
return DraftDatabase.Draft(DraftDatabase.Draft.VOICE_NOTE, draftUri.build().toString())
}
}
| gpl-3.0 | 559f3f80f3f1378f155c3825fdbcefb9 | 26.088235 | 91 | 0.714441 | 4.093333 | false | false | false | false |
iPoli/iPoli-android | app/src/main/java/io/ipoli/android/habit/usecase/CreateHabitHistoryItemsUseCase.kt | 1 | 4814 | package io.ipoli.android.habit.usecase
import io.ipoli.android.common.UseCase
import io.ipoli.android.common.datetime.DateUtils
import io.ipoli.android.common.datetime.datesBetween
import io.ipoli.android.habit.data.Habit
import io.ipoli.android.habit.usecase.CreateHabitHistoryItemsUseCase.HabitHistoryItem.State.*
import io.ipoli.android.quest.Color
import org.threeten.bp.LocalDate
/**
* Created by Polina Zhelyazkova <[email protected]>
* on 10/12/18.
*/
class CreateHabitHistoryItemsUseCase :
UseCase<CreateHabitHistoryItemsUseCase.Params, List<CreateHabitHistoryItemsUseCase.HabitHistoryItem>> {
override fun execute(parameters: Params): List<HabitHistoryItem> {
val habit = parameters.habit
val today = parameters.today
val createdAt = DateUtils.fromMillisLocalZone(habit.createdAt.toEpochMilli())
val firstCompletedDate = habit.history.toSortedMap().entries.firstOrNull {
it.value.completedCount > 0
}?.key
val firstDate = if (firstCompletedDate == null) createdAt else DateUtils.min(
createdAt,
firstCompletedDate
)
val completedIndexes = mutableListOf<Int>()
var index = 0
val items =
parameters.startDate.minusDays(1)
.datesBetween(parameters.endDate.plusDays(1)).map {
val isCompleted = habit.isCompletedForDate(it)
val isGood = habit.isGood
val state = when {
it > today || it < firstDate -> EMPTY
it == today && !habit.shouldBeDoneOn(it) && isGood && !isCompleted -> EMPTY
it == today && isGood && !isCompleted -> NOT_COMPLETED_TODAY
it == today && !isGood && isCompleted -> FAILED
isGood && isCompleted -> COMPLETED
!isGood && isCompleted -> FAILED
!habit.shouldBeDoneOn(it) -> EMPTY
isGood && !isCompleted -> FAILED
!isGood && !isCompleted -> COMPLETED
else -> EMPTY
}
if (state == COMPLETED) {
completedIndexes.add(index)
}
index++
HabitHistoryItem(
date = it,
isGood = habit.isGood,
completedCount = habit.completedCountForDate(it),
timesADay = habit.timesADay,
color = habit.color,
shouldBeDone = habit.days.contains(it.dayOfWeek),
state = state
)
}
val connectedIndexes = mutableListOf<Int>()
completedIndexes.forEachIndexed { i, completedIndex ->
if (i < completedIndexes.size - 1) {
val nextIndex = completedIndexes[i + 1]
val hasFailed =
items
.subList(completedIndex + 1, nextIndex)
.any { it.state == FAILED }
if (!hasFailed) {
connectedIndexes.addAll((completedIndex + 1) until nextIndex)
}
}
}
return items.mapIndexedNotNull { i, item ->
if (i == 0 || i == items.size - 1) null
else {
val isPreviousCompleted =
items[i - 1].state == COMPLETED || connectedIndexes.contains(i - 1)
val isNextCompleted =
items[i + 1].state == COMPLETED || connectedIndexes.contains(i + 1)
val shouldNotComplete = connectedIndexes.contains(i)
item.copy(
isPreviousCompleted = isPreviousCompleted || shouldNotComplete,
isNextCompleted = isNextCompleted || shouldNotComplete,
state = if (item.state == EMPTY
&& shouldNotComplete && item.date < today
) CONNECTED
else item.state
)
}
}
}
data class Params(
val habit: Habit,
val startDate: LocalDate,
val endDate: LocalDate,
val today: LocalDate = LocalDate.now()
)
data class HabitHistoryItem(
val date: LocalDate,
val state: State,
val isGood: Boolean,
val completedCount: Int,
val timesADay: Int,
val color: Color,
val shouldBeDone: Boolean,
val isPreviousCompleted: Boolean = false,
val isNextCompleted: Boolean = false
) {
enum class State {
FAILED, EMPTY, COMPLETED, NOT_COMPLETED_TODAY, CONNECTED
}
}
} | gpl-3.0 | b4f8249402cfd76555f7ecbe7ed4d523 | 36.038462 | 107 | 0.534067 | 5.360802 | false | false | false | false |
carltonwhitehead/crispy-fish | library/src/main/kotlin/org/coner/crispyfish/filetype/staging/StagingFilenames.kt | 1 | 420 | package org.coner.crispyfish.filetype.staging
import java.util.regex.Pattern
object StagingFilenames {
val ORIGINAL_FILE_DAY_1 = Pattern.compile(".*.st1$")
val ORIGINAL_FILE_DAY_2 = Pattern.compile(".*.st2$")
val ORIGINAL_FILE_DAY_1_EXTENSION = "st1"
val ORIGINAL_FILE_DAY_2_EXTENSION = "st2"
val ORIGINAL_FILE_EXTENSIONS = arrayOf(ORIGINAL_FILE_DAY_1_EXTENSION, ORIGINAL_FILE_DAY_2_EXTENSION)
}
| gpl-2.0 | ff3f6c961aec219a8ab488f6c905d68c | 31.307692 | 104 | 0.72381 | 3.28125 | false | false | false | false |
AsamK/TextSecure | app/src/main/java/org/thoughtcrime/securesms/avatar/AvatarPickerStorage.kt | 2 | 2077 | package org.thoughtcrime.securesms.avatar
import android.content.Context
import android.net.Uri
import android.webkit.MimeTypeMap
import org.thoughtcrime.securesms.database.SignalDatabase
import org.thoughtcrime.securesms.mediasend.Media
import org.thoughtcrime.securesms.mms.PartAuthority
import org.thoughtcrime.securesms.util.MediaUtil
import org.thoughtcrime.securesms.util.storage.FileStorage
import java.io.InputStream
object AvatarPickerStorage {
private const val DIRECTORY = "avatar_picker"
private const val FILENAME_BASE = "avatar"
@JvmStatic
fun read(context: Context, fileName: String) = FileStorage.read(context, DIRECTORY, fileName)
fun save(context: Context, media: Media): Uri {
val fileName = FileStorage.save(context, PartAuthority.getAttachmentStream(context, media.uri), DIRECTORY, FILENAME_BASE, MediaUtil.getExtension(context, media.uri) ?: "")
return PartAuthority.getAvatarPickerUri(fileName)
}
fun save(context: Context, inputStream: InputStream): Uri {
val fileName = FileStorage.save(context, inputStream, DIRECTORY, FILENAME_BASE, MimeTypeMap.getSingleton().getExtensionFromMimeType(MediaUtil.IMAGE_JPEG) ?: "")
return PartAuthority.getAvatarPickerUri(fileName)
}
@JvmStatic
fun cleanOrphans(context: Context) {
val avatarFiles = FileStorage.getAllFiles(context, DIRECTORY, FILENAME_BASE)
val database = SignalDatabase.avatarPicker
val photoAvatars = database
.getAllAvatars()
.filterIsInstance<Avatar.Photo>()
val inDatabaseFileNames = photoAvatars.map { PartAuthority.getAvatarPickerFilename(it.uri) }
val onDiskFileNames = avatarFiles.map { it.name }
val inDatabaseButNotOnDisk = inDatabaseFileNames - onDiskFileNames
val onDiskButNotInDatabase = onDiskFileNames - inDatabaseFileNames
avatarFiles
.filter { onDiskButNotInDatabase.contains(it.name) }
.forEach { it.delete() }
photoAvatars
.filter { inDatabaseButNotOnDisk.contains(PartAuthority.getAvatarPickerFilename(it.uri)) }
.forEach { database.deleteAvatar(it) }
}
}
| gpl-3.0 | 5aa3ac8d32a8d224faebeb35ee936f27 | 36.763636 | 175 | 0.774675 | 4.318087 | false | false | false | false |
ktorio/ktor | ktor-client/ktor-client-core/common/test/FormDslTest.kt | 1 | 1576 | import io.ktor.client.request.forms.*
import io.ktor.http.*
import kotlin.test.*
/*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
class FormDslTest {
@Test
fun testAppendDoesNotEscapeKeyAndFilenameIfNotNeeded() {
val data = formData {
append(
key = "file",
filename = "file.name"
) {}
}
assertEquals(data.first().headers.getAll(HttpHeaders.ContentDisposition)!![0], "form-data; name=file")
assertEquals(data.first().headers.getAll(HttpHeaders.ContentDisposition)!![1], "filename=file.name")
}
@Test
fun testAppendEscapeKeyAndFilenameIfNeeded() {
val data = formData {
append(
key = "file 1",
filename = "file 1.name"
) {}
}
assertEquals(data.first().headers.getAll(HttpHeaders.ContentDisposition)!![0], "form-data; name=\"file 1\"")
assertEquals(data.first().headers.getAll(HttpHeaders.ContentDisposition)!![1], "filename=\"file 1.name\"")
}
@Test
fun testAppendDoesNotAddDoubleQuotes() {
val data = formData {
append(
key = "\"file 1\"",
filename = "\"file 1.name\""
) {}
}
assertEquals("form-data; name=\"file 1\"", data.first().headers.getAll(HttpHeaders.ContentDisposition)!![0])
assertEquals("filename=\"file 1.name\"", data.first().headers.getAll(HttpHeaders.ContentDisposition)!![1])
}
}
| apache-2.0 | 0a7bebe8ef498c6f3313458130e0cc63 | 33.26087 | 118 | 0.590102 | 4.282609 | false | true | false | false |
google/accompanist | drawablepainter/src/main/java/com/google/accompanist/drawablepainter/DrawablePainter.kt | 1 | 6445 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.google.accompanist.drawablepainter
import android.graphics.drawable.Animatable
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.Drawable
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.view.View
import androidx.compose.runtime.Composable
import androidx.compose.runtime.RememberObserver
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.graphics.asAndroidColorFilter
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.graphics.drawscope.drawIntoCanvas
import androidx.compose.ui.graphics.nativeCanvas
import androidx.compose.ui.graphics.painter.BitmapPainter
import androidx.compose.ui.graphics.painter.ColorPainter
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.graphics.withSave
import androidx.compose.ui.unit.LayoutDirection
import kotlin.math.roundToInt
private val MAIN_HANDLER by lazy(LazyThreadSafetyMode.NONE) {
Handler(Looper.getMainLooper())
}
/**
* A [Painter] which draws an Android [Drawable] and supports [Animatable] drawables. Instances
* should be remembered to be able to start and stop [Animatable] animations.
*
* Instances are usually retrieved from [rememberDrawablePainter].
*/
class DrawablePainter(
val drawable: Drawable
) : Painter(), RememberObserver {
private var drawInvalidateTick by mutableStateOf(0)
private var drawableIntrinsicSize by mutableStateOf(drawable.intrinsicSize)
private val callback: Drawable.Callback by lazy {
object : Drawable.Callback {
override fun invalidateDrawable(d: Drawable) {
// Update the tick so that we get re-drawn
drawInvalidateTick++
// Update our intrinsic size too
drawableIntrinsicSize = drawable.intrinsicSize
}
override fun scheduleDrawable(d: Drawable, what: Runnable, time: Long) {
MAIN_HANDLER.postAtTime(what, time)
}
override fun unscheduleDrawable(d: Drawable, what: Runnable) {
MAIN_HANDLER.removeCallbacks(what)
}
}
}
init {
if (drawable.intrinsicWidth >= 0 && drawable.intrinsicHeight >= 0) {
// Update the drawable's bounds to match the intrinsic size
drawable.setBounds(0, 0, drawable.intrinsicWidth, drawable.intrinsicHeight)
}
}
override fun onRemembered() {
drawable.callback = callback
drawable.setVisible(true, true)
if (drawable is Animatable) drawable.start()
}
override fun onAbandoned() = onForgotten()
override fun onForgotten() {
if (drawable is Animatable) drawable.stop()
drawable.setVisible(false, false)
drawable.callback = null
}
override fun applyAlpha(alpha: Float): Boolean {
drawable.alpha = (alpha * 255).roundToInt().coerceIn(0, 255)
return true
}
override fun applyColorFilter(colorFilter: ColorFilter?): Boolean {
drawable.colorFilter = colorFilter?.asAndroidColorFilter()
return true
}
override fun applyLayoutDirection(layoutDirection: LayoutDirection): Boolean {
if (Build.VERSION.SDK_INT >= 23) {
return drawable.setLayoutDirection(
when (layoutDirection) {
LayoutDirection.Ltr -> View.LAYOUT_DIRECTION_LTR
LayoutDirection.Rtl -> View.LAYOUT_DIRECTION_RTL
}
)
}
return false
}
override val intrinsicSize: Size get() = drawableIntrinsicSize
override fun DrawScope.onDraw() {
drawIntoCanvas { canvas ->
// Reading this ensures that we invalidate when invalidateDrawable() is called
drawInvalidateTick
// Update the Drawable's bounds
drawable.setBounds(0, 0, size.width.roundToInt(), size.height.roundToInt())
canvas.withSave {
drawable.draw(canvas.nativeCanvas)
}
}
}
}
/**
* Remembers [Drawable] wrapped up as a [Painter]. This function attempts to un-wrap the
* drawable contents and use Compose primitives where possible.
*
* If the provided [drawable] is `null`, an empty no-op painter is returned.
*
* This function tries to dispatch lifecycle events to [drawable] as much as possible from
* within Compose.
*
* @sample com.google.accompanist.sample.drawablepainter.BasicSample
*/
@Composable
fun rememberDrawablePainter(drawable: Drawable?): Painter = remember(drawable) {
when (drawable) {
null -> EmptyPainter
is BitmapDrawable -> BitmapPainter(drawable.bitmap.asImageBitmap())
is ColorDrawable -> ColorPainter(Color(drawable.color))
// Since the DrawablePainter will be remembered and it implements RememberObserver, it
// will receive the necessary events
else -> DrawablePainter(drawable.mutate())
}
}
private val Drawable.intrinsicSize: Size
get() = when {
// Only return a finite size if the drawable has an intrinsic size
intrinsicWidth >= 0 && intrinsicHeight >= 0 -> {
Size(width = intrinsicWidth.toFloat(), height = intrinsicHeight.toFloat())
}
else -> Size.Unspecified
}
internal object EmptyPainter : Painter() {
override val intrinsicSize: Size get() = Size.Unspecified
override fun DrawScope.onDraw() {}
}
| apache-2.0 | 5f105e15e288c4f2ada318148e89fad8 | 35.207865 | 95 | 0.701474 | 4.756458 | false | false | false | false |
inorichi/mangafeed | app/src/main/java/eu/kanade/tachiyomi/widget/preference/SwitchPreferenceCategory.kt | 2 | 3453 | package eu.kanade.tachiyomi.widget.preference
import android.content.Context
import android.content.res.TypedArray
import android.util.AttributeSet
import android.view.View
import android.widget.Checkable
import android.widget.CompoundButton
import android.widget.TextView
import androidx.appcompat.widget.SwitchCompat
import androidx.preference.PreferenceCategory
import androidx.preference.PreferenceViewHolder
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.util.system.getResourceColor
class SwitchPreferenceCategory @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null
) :
PreferenceCategory(
context,
attrs,
R.attr.switchPreferenceCompatStyle
),
CompoundButton.OnCheckedChangeListener {
private var mChecked = false
private var mCheckedSet = false
override fun onBindViewHolder(holder: PreferenceViewHolder) {
super.onBindViewHolder(holder)
val titleView = holder.findViewById(android.R.id.title) as TextView
titleView.setTextColor(context.getResourceColor(R.attr.colorAccent))
syncSwitchView(holder)
}
private fun syncSwitchView(holder: PreferenceViewHolder) {
val switchView = holder.findViewById(R.id.switchWidget)
syncSwitchView(switchView)
}
private fun syncSwitchView(view: View) {
if (view is Checkable) {
val isChecked = view.isChecked
if (isChecked == mChecked) return
if (view is SwitchCompat) {
view.setOnCheckedChangeListener(null)
}
view.toggle()
if (view is SwitchCompat) {
view.setOnCheckedChangeListener(this)
}
}
}
override fun onCheckedChanged(buttonView: CompoundButton, isChecked: Boolean) {
if (!callChangeListener(isChecked)) {
buttonView.isChecked = !isChecked
} else {
setChecked(isChecked)
}
}
override fun onClick() {
super.onClick()
val newValue = !isChecked()
if (callChangeListener(newValue)) {
setChecked(newValue)
}
}
/**
* Sets the checked state and saves it to the [SharedPreferences].
*
* @param checked The checked state.
*/
fun setChecked(checked: Boolean) {
// Always persist/notify the first time; don't assume the field's default of false.
val changed = mChecked != checked
if (changed || !mCheckedSet) {
mChecked = checked
mCheckedSet = true
persistBoolean(checked)
if (changed) {
notifyDependencyChange(shouldDisableDependents())
notifyChanged()
}
}
}
/**
* Returns the checked state.
*
* @return The checked state.
*/
fun isChecked(): Boolean {
return mChecked
}
override fun isEnabled(): Boolean {
return true
}
override fun shouldDisableDependents(): Boolean {
return false
}
override fun onGetDefaultValue(a: TypedArray, index: Int): Any {
return a.getBoolean(index, false)
}
override fun onSetInitialValue(restoreValue: Boolean, defaultValue: Any?) {
setChecked(
if (restoreValue) {
getPersistedBoolean(mChecked)
} else {
defaultValue as Boolean
}
)
}
}
| apache-2.0 | e939c2975fe97ba52aae075eb218f236 | 26.404762 | 91 | 0.631335 | 5.077941 | false | false | false | false |
mezpahlan/jivecampaign | src/test/kotlin/co/uk/jiveelection/campaign/translator/InMemoryJiveTranslatorTest.kt | 1 | 44553 | package co.uk.jiveelection.campaign.translator
import co.uk.jiveelection.campaign.jive.Jive
import co.uk.jiveelection.campaign.output.twitter.TranslationEntity
import co.uk.jiveelection.campaign.translator.memory.InMemoryJiveTranslator
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.junit.MockitoJUnitRunner
import java.util.ArrayList
import org.mockito.Mockito.verify
/**
* Tests for InMemoryJiveTranslator.
*/
@RunWith(MockitoJUnitRunner::class)
class InMemoryJiveTranslatorTest {
@Mock
private lateinit var mockJive: Jive<*, *, *>
private lateinit var jiveTranslator: JiveTranslator
@Before
fun setUp() {
jiveTranslator = InMemoryJiveTranslator(mockJive)
}
@Test
fun should_not_overwrite_previous_translations() {
verifyTranslation("at the pub! yeah!", "at da damn pub. Right On! yeah. Right On!")
}
@Test
fun should_translate_file() {
verifyTranslation("aaa file aaa", "aaa stash aaa")
}
@Test
fun should_not_translate_profiled() {
verifyTranslation("profiled", "profiled")
}
@Test
fun should_translate_send() {
verifyTranslation("aaa send aaa", "aaa t'row aaa")
}
@Test
fun should_not_translate_godsend() {
verifyTranslation("godsend", "godsend")
}
@Test
fun should_translate_program() {
verifyTranslation("aaa program aaa", "aaa honky code aaa")
}
@Test
fun should_translate_programmming() {
verifyTranslation("programming", "programmin'")
}
@Test
fun should_translate_atlas() {
verifyTranslation("aaa atlas aaa", "aaa Isaac aaa")
}
@Test
fun should_not_translate_atlases() {
verifyTranslation("atlases", "atlases")
}
@Test
fun should_translate_unix() {
verifyTranslation("aaa unix aaa", "aaa slow mo-fo aaa")
}
@Test
fun should_translate_UNIX() {
verifyTranslation("aaa UNIX aaa", "aaa that slow mo-fo aaa")
}
@Test
fun should_translate_take() {
verifyTranslation("aaa take aaa", "aaa snatch aaa")
}
@Test
fun should_not_translate_partake() {
verifyTranslation("partake", "partake")
}
@Test
fun should_translate_mexican() {
verifyTranslation("aaa mexican aaa", "aaa wet-back aaa")
}
@Test
fun should_translate_mexicans() {
verifyTranslation("aaa mexicans aaa", "aaa wet-backs aaa")
}
@Test
fun should_translate_Mexican() {
verifyTranslation("aaa Mexican aaa", "aaa wet-back aaa")
}
@Test
fun should_translate_Mexicans() {
verifyTranslation("aaa Mexicans aaa", "aaa wet-backs aaa")
}
@Test
fun should_translate_italian() {
verifyTranslation("aaa italian aaa", "aaa greaser aaa")
}
@Test
fun should_translate_italians() {
verifyTranslation("aaa italians aaa", "aaa greasers aaa")
}
@Test
fun should_translate_Italian() {
verifyTranslation("aaa Italian aaa", "aaa greaser aaa")
}
@Test
fun should_translate_Italians() {
verifyTranslation("aaa Italians aaa", "aaa greasers aaa")
}
@Test
fun should_translate_takes() {
verifyTranslation("aaa takes aaa", "aaa snatch'd aaa")
}
@Test
fun should_not_translate_partakes() {
verifyTranslation("partakes", "partakes")
}
@Test
fun should_translate_dont() {
verifyTranslation("aaa don't aaa", "aaa duzn't aaa")
}
@Test
fun should_translate_translator() {
verifyTranslation("aaa translator aaa", "aaa jibe aaa")
}
@Test
fun should_translate_fool() {
verifyTranslation("aaa fool aaa", "aaa honkyfool aaa")
}
@Test
fun should_not_translate_foolishly() {
verifyTranslation("foolishly", "foolishly")
}
@Test
fun should_translate_modem() {
verifyTranslation("aaa modem aaa", "aaa doodad aaa")
}
@Test
fun should_translate_the_e_variation() {
verifyTranslation("aaa see the aaa", "aaa see da damn aaa")
}
@Test
fun should_translate_the_a_variation() {
verifyTranslation("aaa la the aaa", "aaa la da damn aaa")
}
@Test
fun should_translate_the_t_variation() {
verifyTranslation("aaa cat the aaa", "aaa cat da damn aaa")
}
@Test
fun should_translate_the_d_variation() {
verifyTranslation("aaa bad the aaa", "aaa bad da damn aaa")
}
@Test
fun should_translate_man() {
verifyTranslation("aaa man aaa", "aaa dude aaa")
}
@Test
fun should_not_translate_manipulated() {
verifyTranslation("manipulated", "manipulated")
}
@Test
fun should_translate_woman() {
verifyTranslation("chairwoman", "chairmama")
}
@Test
fun should_translate_girl() {
verifyTranslation("aaa girl aaa", "aaa goat aaa")
}
@Test
fun should_not_translate_girlfriends() {
verifyTranslation("girlfriends", "girlfriends")
}
@Test
fun should_translate_something() {
verifyTranslation("aaa something aaa", "aaa sump'n aaa")
}
@Test
fun should_translate_lie() {
verifyTranslation("lie", "honky jibe")
}
@Test
fun should_not_translate_alien() {
verifyTranslation("alien", "alien")
}
@Test
fun should_translate_full_stop_a_variation() {
verifyTranslation("aaa a. aaa", "aaa a. Sheeeiit. aaa")
}
@Test
fun should_translate_full_stop_b_variation() {
verifyTranslation("aaa b. aaa", "aaa b. Sheeeiit. aaa")
}
@Test
fun should_translate_full_stop_e_variation() {
verifyTranslation("aaa e. aaa", "aaa e. What it is, Mama! aaa")
}
@Test
fun should_translate_full_stop_f_variation() {
verifyTranslation("aaa f. aaa", "aaa f. What it is, Mama! aaa")
}
@Test
fun should_translate_full_stop_i_variation() {
verifyTranslation("aaa i. aaa", "aaa i. Ya' know? aaa")
}
@Test
fun should_translate_full_stop_j_variation() {
verifyTranslation("aaa j. aaa", "aaa j. Ya' know? aaa")
}
@Test
fun should_translate_full_stop_m_variation() {
verifyTranslation("aaa m. aaa", "aaa m. 'S coo', bro. aaa")
}
@Test
fun should_translate_full_stop_n_variation() {
verifyTranslation("aaa n. aaa", "aaa n. 'S coo', bro. aaa")
}
@Test
fun should_translate_full_stop_q_variation() {
verifyTranslation("aaa q. aaa", "aaa q. Ah be baaad... aaa")
}
@Test
fun should_translate_full_stop_r_variation() {
verifyTranslation("aaa r. aaa", "aaa r. Ah be baaad... aaa")
}
@Test
fun should_translate_full_stop_u_variation() {
verifyTranslation("aaa u. aaa", "aaa u. Man! aaa")
}
@Test
fun should_translate_full_stop_v_variation() {
verifyTranslation("aaa v. aaa", "aaa v. Man! aaa")
}
@Test
fun should_translate_full_stop_y_variation() {
verifyTranslation("aaa y. aaa", "aaa y. Slap mah fro! aaa")
}
@Test
fun should_translate_full_stop_z_variation() {
verifyTranslation("aaa z. aaa", "aaa z. Slap mah fro! aaa")
}
@Test
fun should_translate_Sure() {
verifyTranslation("aaa Sure aaa", "aaa Sho' nuff aaa")
}
@Test
fun should_translate_sure() {
verifyTranslation("aaa sure aaa", "aaa sho' nuff aaa")
}
@Test
fun should_not_translate_pressure() {
verifyTranslation("pressure", "pressure")
}
@Test
fun should_translate_get() {
verifyTranslation("getaway", "gitaway")
}
@Test
fun should_not_translate_forget() {
verifyTranslation("forget", "forget")
}
@Test
fun should_translate_will_have() {
verifyTranslation("aaa will have aaa", "aaa gots'ta aaa")
}
@Test
fun should_translate_will() {
verifyTranslation("aaa will aaa", "aaa gots'ta aaa")
}
@Test
fun should_translate_got_to() {
verifyTranslation("aaa got to aaa", "aaa gots'ta aaa")
}
@Test
fun should_translate_I_am() {
verifyTranslation("aaa I am aaa", "aaa I's gots'ta be aaa")
}
@Test
fun should_translate_am_not() {
verifyTranslation("aaa am not aaa", "aaa aint aaa")
}
@Test
fun should_translate_is_not() {
verifyTranslation("aaa is not aaa", "aaa aint aaa")
}
@Test
fun should_translate_are_not() {
verifyTranslation("aaa are not aaa", "aaa aint aaa")
}
@Test
fun should_translate_are_your() {
verifyTranslation("aaa are your aaa", "aaa is yo' aaa")
}
@Test
fun should_translate_are_you() {
verifyTranslation("aaa are you aaa", "aaa you is aaa")
}
@Test
fun should_translate_hat() {
verifyTranslation("aaa hat aaa", "aaa fedora aaa")
}
@Test
fun should_not_translate_hatred() {
verifyTranslation("hatred", "hatred")
}
@Test
fun should_translate_shoe() {
verifyTranslation("aaa shoe aaa", "aaa kicker aaa")
}
@Test
fun should_not_translate_shoebox() {
verifyTranslation("shoebox", "shoebox")
}
@Test
fun should_translate_havent() {
verifyTranslation("aaa haven't aaa", "aaa aint aaa")
}
@Test
fun should_translate_have_to() {
verifyTranslation("aaa have to aaa", "aaa gots'ta aaa")
}
@Test
fun should_translate_have() {
verifyTranslation("aaa have aaa", "aaa gots' aaa")
}
@Test
fun should_translate_has() {
verifyTranslation("aaa has aaa", "aaa gots'ta aaa")
}
@Test
fun should_translate_come_over() {
verifyTranslation("aaa come over aaa", "aaa mosey on down aaa")
}
@Test
fun should_translate_come() {
verifyTranslation("aaa come aaa", "aaa mosey on down aaa")
}
@Test
fun should_not_translate_outcome() {
verifyTranslation("outcome", "outcome")
}
@Test
fun should_translate_exclamation_mark() {
verifyTranslation("aaa! aaa", "aaa. Right On! aaa")
}
@Test
fun should_translate_buy() {
verifyTranslation("aaa buy aaa", "aaa steal aaa")
}
@Test
fun should_translate_buyer() {
verifyTranslation("buyer", "buya'")
}
@Test
fun should_translate_car() {
verifyTranslation("aaa car aaa", "aaa wheels aaa")
}
@Test
fun should_translate_carcus() {
verifyTranslation("carcus", "carcus")
}
@Test
fun should_translate_drive() {
verifyTranslation("aaa drive aaa", "aaa roll aaa")
}
@Test
fun should_translate_screwdriver() {
verifyTranslation("screwdriver", "screwdriva'")
}
@Test
fun should_translate_eat() {
verifyTranslation("aaa eat aaa", "aaa feed da bud aaa")
}
@Test
fun should_not_translate_conceat() {
verifyTranslation("concreat", "concreat")
}
@Test
fun should_translate_black() {
verifyTranslation("aaa black aaa", "aaa brother aaa")
}
@Test
fun should_not_translate_blackest() {
verifyTranslation("blackest", "blackest")
}
@Test
fun should_translate_negro() {
verifyTranslation("aaa negro aaa", "aaa brother aaa")
}
@Test
fun should_translate_white() {
verifyTranslation("aaa white aaa", "aaa honky aaa")
}
@Test
fun should_translate_whiter() {
verifyTranslation("whiter", "whita'")
}
@Test
fun should_translate_nigger() {
verifyTranslation("aaa nigger aaa", "aaa gentleman aaa")
}
@Test
fun should_translate_nice() {
verifyTranslation("aaa nice aaa", "aaa supa' fine aaa")
}
@Test
fun should_note_translate_niceties() {
verifyTranslation("niceties", "niceties")
}
@Test
fun should_translate_person() {
verifyTranslation("aaa person aaa", "aaa sucka' aaa")
}
@Test
fun should_not_translate_personalities() {
verifyTranslation("personalities", "personalities")
}
@Test
fun should_translate_persons() {
verifyTranslation("aaa persons aaa", "aaa sucka's aaa")
}
@Test
fun should_translate_thing() {
verifyTranslation("aaa thing aaa", "aaa wahtahmellun aaa")
}
@Test
fun should_not_translate_clothing() {
verifyTranslation("clothing", "clothing")
}
@Test
fun should_translate_home() {
verifyTranslation("aaa home aaa", "aaa crib aaa")
}
@Test
fun should_translate_whomever() {
verifyTranslation("whomever", "whomeva'")
}
@Test
fun should_translate_name() {
verifyTranslation("aaa name aaa", "aaa dojigger aaa")
}
@Test
fun should_not_translate_tournament() {
verifyTranslation("tournament", "tournament")
}
@Test
fun should_translate_path() {
verifyTranslation("aaa path aaa", "aaa alley aaa")
}
@Test
fun should_not_translate_sociopath() {
verifyTranslation("sociopath", "sociopath")
}
@Test
fun should_translate_computer() {
verifyTranslation("aaa computer aaa", "aaa clunker aaa")
}
@Test
fun should_translate_or() {
verifyTranslation("aaa or aaa", "aaa o' aaa")
}
@Test
fun should_not_translate_orange() {
verifyTranslation("orange", "orange")
}
@Test
fun should_translate_killed() {
verifyTranslation("aaa killed aaa", "aaa wasted aaa")
}
@Test
fun should_not_translate_skilled() {
verifyTranslation("skilled", "skilled")
}
@Test
fun should_translate_president() {
verifyTranslation("aaa president aaa", "aaa super-dude aaa")
}
@Test
fun should_not_translate_presidential() {
verifyTranslation("presidential", "presidential")
}
@Test
fun should_translate_prime_minister() {
verifyTranslation("aaa prime minister aaa", "aaa super honcho aaa")
}
@Test
fun should_not_translate_prime_ministerial() {
verifyTranslation("prime ministerial", "prime ministerial")
}
@Test
fun should_translate_injured() {
verifyTranslation("aaa injured aaa", "aaa hosed aaa")
}
@Test
fun should_not_translate_reinjured() {
verifyTranslation("reinjured", "reinjured")
}
@Test
fun should_translate_government() {
verifyTranslation("aaa government aaa", "aaa guv'ment aaa")
}
@Test
fun should_translate_knew() {
verifyTranslation("misknew", "misknew")
}
@Test
fun should_not_translate_misknew() {
verifyTranslation("misknew", "misknew")
}
@Test
fun should_translate_Because() {
verifyTranslation("aaa Because aaa", "aaa B'cuz aaa")
}
@Test
fun should_translate_because() {
verifyTranslation("aaa because aaa", "aaa b'cuz aaa")
}
@Test
fun should_translate_Your() {
verifyTranslation("Yourself", "Yo'self")
}
@Test
fun should_translate_your() {
verifyTranslation("yourself", "yo'self")
}
@Test
fun should_translate_four() {
verifyTranslation("fourteen", "foeteen")
}
@Test
fun should_translate_got() {
verifyTranslation("aaa got aaa", "aaa gots aaa")
}
@Test
fun should_not_translate_gothic() {
verifyTranslation("gothic", "gothic")
}
@Test
fun should_translate_arent() {
verifyTranslation("aaa aren't aaa", "aaa ain't aaa")
}
@Test
fun should_translate_young() {
verifyTranslation("aaa young aaa", "aaa yung aaa")
}
@Test
fun should_translate_youngster() {
verifyTranslation("youngster", "yungsta'")
}
@Test
fun should_translate_you() {
verifyTranslation("aaa you aaa", "aaa ya' aaa")
}
@Test
fun should_translate_You() {
verifyTranslation("aaa You aaa", "aaa You's aaa")
}
@Test
fun should_translate_first() {
verifyTranslation("firstly", "fustly")
}
@Test
fun should_translate_police() {
verifyTranslation("aaa police aaa", "aaa honky pigs aaa")
}
@Test
fun should_not_translate_policed() {
verifyTranslation("policed", "policed")
}
@Test
fun should_translate_string() {
verifyTranslation("aaa string aaa", "aaa chittlin' aaa")
}
@Test
fun should_not_translate_hamstring() {
verifyTranslation("hamstring", "hamstring")
}
@Test
fun should_translate_read() {
verifyTranslation("aaa read aaa", "aaa eyeball aaa")
}
@Test
fun should_not_translate_readiness() {
verifyTranslation("readiness", "readiness")
}
@Test
fun should_translate_write() {
verifyTranslation("aaa write aaa", "aaa scribble aaa")
}
@Test
fun should_translate_th() {
verifyTranslation("that", "dat")
}
@Test
fun should_translate_Th() {
verifyTranslation("That", "Dat")
}
@Test
fun should_translate_ing() {
verifyTranslation("winning", "winnin'")
}
@Test
fun should_translate_a() {
verifyTranslation("aaa a aaa", "aaa some aaa")
}
@Test
fun should_not_translate_aweseome() {
verifyTranslation("awesome", "awesome")
}
@Test
fun should_translate_to() {
verifyTranslation("to town", "t'town")
}
@Test
fun should_not_translate_too() {
verifyTranslation("too", "too")
}
@Test
fun should_translate_tion() {
verifyTranslation("election", "elecshun")
}
@Test
fun should_translate_almost() {
verifyTranslation("aaa almost aaa", "aaa mos' aaa")
}
@Test
fun should_translate_from() {
verifyTranslation("aaa from aaa", "aaa fum aaa")
}
@Test
fun should_not_translate_wherefrom() {
verifyTranslation("wherefrom", "wherefrom")
}
@Test
fun should_translate_Youre() {
verifyTranslation("aaa You're aaa", "aaa Youse aaa")
}
@Test
fun should_translate_youre() {
verifyTranslation("aaa you're aaa", "aaa youse aaa")
}
@Test
fun should_translate_alright() {
verifyTranslation("aaa alright aaa", "aaa coo' aaa")
}
@Test
fun should_translate_okay() {
verifyTranslation("aaa okay aaa", "aaa coo' aaa")
}
@Test
fun should_translate_er() {
verifyTranslation("winter", "winta'")
}
@Test
fun should_not_translate_error() {
verifyTranslation("error", "error")
}
@Test
fun should_translate_known() {
verifyTranslation("aaa known aaa", "aaa knode aaa")
}
@Test
fun should_translate_want() {
verifyTranslation("aaa want aaa", "aaa wants' aaa")
}
@Test
fun should_translate_beat() {
verifyTranslation("aaa beat aaa", "aaa whup' aaa")
}
@Test
fun should_translate_beating() {
verifyTranslation("aaa beat aaa", "aaa whup' aaa")
verifyTranslation("beating", "beatin'")
}
@Test
fun should_translate_exp() {
verifyTranslation("explain", "'splain")
}
@Test
fun should_translate_exs() {
verifyTranslation("exsert", "'sert")
}
@Test
fun should_translate_exc() {
verifyTranslation("exclaim", "'slaim")
}
@Test
fun should_translate_ex() {
verifyTranslation("extra", "'estra")
}
@Test
fun should_translate_like() {
verifyTranslation("aaa like aaa", "aaa likes aaa")
}
@Test
fun should_not_translate_likes() {
verifyTranslation("likes", "likes")
}
@Test
fun should_translate_did() {
verifyTranslation("aaa did aaa", "aaa dun did aaa")
}
@Test
fun should_not_translate_candid() {
verifyTranslation("candid", "candid")
}
@Test
fun should_translate_kind_of() {
verifyTranslation("aaa kind of aaa", "aaa kind'a aaa")
}
@Test
fun should_translate_mankind_offered() {
verifyTranslation("mankind offered", "mankind offered")
}
@Test
fun should_translate_women() {
verifyTranslation("aaa women aaa", "aaa honky chicks aaa")
}
@Test
fun should_not_translate_anchorwomen() {
verifyTranslation("anchorwomen", "anchorwomen")
}
@Test
fun should_translate_men() {
verifyTranslation("aaa men aaa", "aaa dudes aaa")
}
@Test
fun should_translate_dead() {
verifyTranslation("aaa dead aaa", "aaa wasted aaa")
}
@Test
fun should_not_translate_deadliest() {
verifyTranslation("deadliest", "deadliest")
}
@Test
fun should_translate_good() {
verifyTranslation("aaa good aaa", "aaa baaaad aaa")
}
@Test
fun should_not_translate_goodbye() {
verifyTranslation("goodbye", "goodbye")
}
@Test
fun should_translate_open() {
verifyTranslation("aaa open aaa", "aaa jimmey aaa")
}
@Test
fun should_translate_opened() {
verifyTranslation("opened", "jimmey'd")
}
@Test
fun should_not_translate_unopened() {
verifyTranslation("unopened", "unopened")
}
@Test
fun should_translate_very() {
verifyTranslation("aaa very aaa", "aaa real aaa")
}
@Test
fun should_not_translate_avery() {
verifyTranslation("avery", "avery")
}
@Test
fun should_translate_per() {
verifyTranslation("aaa per aaa", "aaa puh' aaa")
}
@Test
fun should_not_translate_copper() {
verifyTranslation("copper", "copper")
}
@Test
fun should_translate_oar() {
verifyTranslation("aaa oar aaa", "aaa o' aaa")
}
@Test
fun should_not_translate_soar() {
verifyTranslation("soar", "soar")
}
@Test
fun should_translate_can() {
verifyTranslation("aaa can aaa", "aaa kin aaa")
}
@Test
fun should_not_translate_uncanny() {
verifyTranslation("uncanny", "uncanny")
}
@Test
fun should_translate_just() {
verifyTranslation("aaa just aaa", "aaa plum aaa")
}
@Test
fun should_not_translate_adjust() {
verifyTranslation("adjust", "adjust")
}
@Test
fun should_translate_Detroit() {
verifyTranslation("aaa Detroit aaa", "aaa Mo-town aaa")
}
@Test
fun should_translate_detroit() {
verifyTranslation("aaa detroit aaa", "aaa Mo-town aaa")
}
@Test
fun should_translate_believe() {
verifyTranslation("aaa believe aaa", "aaa recon' aaa")
}
@Test
fun should_translate_Indianapolis() {
verifyTranslation("aaa Indianapolis aaa", "aaa Nap-town aaa")
}
@Test
fun should_translate_indianapolis() {
verifyTranslation("aaa indianapolis aaa", "aaa Nap-town aaa")
}
@Test
fun should_translate_Jack() {
verifyTranslation("aaa Jack aaa", "aaa Buckwheat aaa")
}
@Test
fun should_not_translate_Jackal() {
verifyTranslation("Jackal", "Jackal")
}
@Test
fun should_translate_jack() {
verifyTranslation("aaa jack aaa", "aaa Buckwheat aaa")
}
@Test
fun should_not_translate_jackal() {
verifyTranslation("jackal", "jackal")
}
@Test
fun should_translate_Bob() {
verifyTranslation("aaa Bob aaa", "aaa Liva' Lips aaa")
}
@Test
fun should_nottranslate_Bobby() {
verifyTranslation("Bobby", "Bobby")
}
@Test
fun should_translate_bob() {
verifyTranslation("aaa bob aaa", "aaa Liva' Lips aaa")
}
@Test
fun should_nottranslate_bobby() {
verifyTranslation("bobby", "bobby")
}
@Test
fun should_translate_Phil() {
verifyTranslation("aaa Phil aaa", "aaa dat fine soul aaa")
}
@Test
fun should_translate_Phillip() {
verifyTranslation("Phillip", "Phillip")
}
@Test
fun should_translate_phil() {
verifyTranslation("aaa phil aaa", "aaa dat fine soul aaa")
}
@Test
fun should_translate_phillip() {
verifyTranslation("phillip", "phillip")
}
@Test
fun should_translate_Mark() {
verifyTranslation("aaa Mark aaa", "aaa Amos aaa")
}
@Test
fun should_translate_mark() {
verifyTranslation("aaa mark aaa", "aaa Amos aaa")
}
@Test
fun should_translate_Robert() {
verifyTranslation("Roberto", "Roberto")
}
@Test
fun should_not_translate_Roberto() {
verifyTranslation("Roberto", "Roberto")
}
@Test
fun should_translate_robert() {
verifyTranslation("aaa robert aaa", "aaa Leroy aaa")
}
@Test
fun should_not_translate_roberto() {
verifyTranslation("roberto", "roberto")
}
@Test
fun should_translate_Sandy() {
verifyTranslation("aaa Sandy aaa", "aaa dat fine femahnaine ladee aaa")
}
@Test
fun should_translate_sandy() {
verifyTranslation("aaa sandy aaa", "aaa dat fine femahnaine ladee aaa")
}
@Test
fun should_translate_John() {
verifyTranslation("aaa John aaa", "aaa Raz'tus aaa")
}
@Test
fun should_not_translate_Johnny() {
verifyTranslation("Johnny", "Johnny")
}
@Test
fun should_translate_john() {
verifyTranslation("aaa john aaa", "aaa Raz'tus aaa")
}
@Test
fun should_not_translate_johnny() {
verifyTranslation("johnny", "johnny")
}
@Test
fun should_translate_Paul() {
verifyTranslation("aaa Paul aaa", "aaa Fuh'rina aaa")
}
@Test
fun should_not_translate_Paula() {
verifyTranslation("Paula", "Paula")
}
@Test
fun should_translate_paul() {
verifyTranslation("aaa paul aaa", "aaa Fuh'rina aaa")
}
@Test
fun should_not_translate_paula() {
verifyTranslation("paula", "paula")
}
@Test
fun should_translate_Reagan() {
verifyTranslation("aaa Reagan aaa", "aaa Kingfish aaa")
}
@Test
fun should_translate_Reaganomics() {
verifyTranslation("Reaganomics", "Reaganomics")
}
@Test
fun should_translate_reagan() {
verifyTranslation("aaa reagan aaa", "aaa Kingfish aaa")
}
@Test
fun should_not_translate_reaganomics() {
verifyTranslation("reaganomics", "reaganomics")
}
@Test
fun should_translate_David() {
verifyTranslation("aaa David aaa", "aaa Issac aaa")
}
@Test
fun should_translate_david() {
verifyTranslation("aaa david aaa", "aaa Issac aaa")
}
@Test
fun should_translate_Ronald() {
verifyTranslation("aaa Ronald aaa", "aaa Rolo aaa")
}
@Test
fun should_translate_ronald() {
verifyTranslation("aaa ronald aaa", "aaa Rolo aaa")
}
@Test
fun should_translate_Jim() {
verifyTranslation("aaa Jim aaa", "aaa Bo-Jangles aaa")
}
@Test
fun should_not_translate_Jimmy() {
verifyTranslation("Jimmy", "Jimmy")
}
@Test
fun should_translate_jim() {
verifyTranslation("aaa jim aaa", "aaa Bo-Jangles aaa")
}
@Test
fun should_not_translate_jimmy() {
verifyTranslation("jimmy", "jimmy")
}
@Test
fun should_translate_Mary() {
verifyTranslation("aaa Mary aaa", "aaa Snow Flake aaa")
}
@Test
fun should_not_translate_Maryanne() {
verifyTranslation("Maryanne", "Maryanne")
}
@Test
fun should_translate_mary() {
verifyTranslation("aaa mary aaa", "aaa Snow Flake aaa")
}
@Test
fun should_not_translate_maryanne() {
verifyTranslation("maryanne", "maryanne")
}
@Test
fun should_translate_Larry() {
verifyTranslation("aaa Larry aaa", "aaa Remus aaa")
}
@Test
fun should_translate_larry() {
verifyTranslation("aaa larry aaa", "aaa Remus aaa")
}
@Test
fun should_translate_Mohammed() {
verifyTranslation("aaa Mohammed aaa", "aaa Home Boy aaa")
}
@Test
fun should_translate_mohammed() {
verifyTranslation("aaa mohammed aaa", "aaa Home Boy aaa")
}
@Test
fun should_translate_Pope() {
verifyTranslation("aaa Pope aaa", "aaa wiz' aaa")
}
@Test
fun should_translate_pope() {
verifyTranslation("aaa pope aaa", "aaa wiz' aaa")
}
@Test
fun should_translate_Pontiff() {
verifyTranslation("aaa Pontiff aaa", "aaa wiz' aaa")
}
@Test
fun should_translate_pontiff() {
verifyTranslation("aaa pontiff aaa", "aaa wiz' aaa")
}
@Test
fun should_translate_Pravda() {
verifyTranslation("aaa Pravda aaa", "aaa dat commie rag aaa")
}
@Test
fun should_translate_pravda() {
verifyTranslation("aaa pravda aaa", "aaa dat commie rag aaa")
}
@Test
fun should_translate_broken() {
verifyTranslation("aaa broken aaa", "aaa bugger'd aaa")
}
@Test
fun should_not_translate_unbrokenny() {
verifyTranslation("unbrokenny", "unbrokenny")
}
@Test
fun should_translate_strange() {
verifyTranslation("unstrangeny", "unstrangeny")
}
@Test
fun should_not_translate_unstrangeny() {
verifyTranslation("unstrangeny", "unstrangeny")
}
@Test
fun should_translate_dance() {
verifyTranslation("aaa dance aaa", "aaa boogy aaa")
}
@Test
fun should_not_translate_undanceny() {
verifyTranslation("undanceny", "undanceny")
}
@Test
fun should_translate_house() {
verifyTranslation("aaa house aaa", "aaa crib aaa")
}
@Test
fun should_translate_ask() {
verifyTranslation("aaa ask aaa", "aaa ax' aaa")
}
@Test
fun should_not_translate_unaskny() {
verifyTranslation("unaskny", "unaskny")
}
@Test
fun should_translate_so() {
verifyTranslation("aaa so aaa", "aaa so's aaa")
}
@Test
fun should_not_translate_unsony() {
verifyTranslation("unsony", "unsony")
}
@Test
fun should_translate_head() {
verifyTranslation("aaa head aaa", "aaa 'haid aaa")
}
@Test
fun should_not_translate_unheadny() {
verifyTranslation("unheadny", "unheadny")
}
@Test
fun should_translate_boss() {
verifyTranslation("aaa boss aaa", "aaa main man aaa")
}
@Test
fun should_not_translate_unbossny() {
verifyTranslation("unbossny", "unbossny")
}
@Test
fun should_translate_wife() {
verifyTranslation("aaa wife aaa", "aaa mama aaa")
}
@Test
fun should_not_translate_unwifeny() {
verifyTranslation("unwifeny", "unwifeny")
}
@Test
fun should_translate_people() {
verifyTranslation("aaa people aaa", "aaa sucka's aaa")
}
@Test
fun should_not_translate_unpeopleny() {
verifyTranslation("unpeopleny", "unpeopleny")
}
@Test
fun should_translate_money() {
verifyTranslation("aaa money aaa", "aaa bre'd aaa")
}
@Test
fun should_not_translate_unmoneyny() {
verifyTranslation("unmoneyny", "unmoneyny")
}
@Test
fun should_translate_a_colon() {
verifyTranslation("a:", "a, dig dis:")
}
@Test
fun should_translate_b_colon() {
verifyTranslation("b:", "b, dig dis:")
}
@Test
fun should_translate_c_colon() {
verifyTranslation("c:", "c, dig dis:")
}
@Test
fun should_translate_d_colon() {
verifyTranslation("d:", "d, dig dis:")
}
@Test
fun should_translate_e_colon() {
verifyTranslation("e:", "e, dig dis:")
}
@Test
fun should_translate_f_colon() {
verifyTranslation("f:", "f, dig dis:")
}
@Test
fun should_translate_g_colon() {
verifyTranslation("g:", "g, dig dis:")
}
@Test
fun should_translate_h_colon() {
verifyTranslation("h:", "h, dig dis:")
}
@Test
fun should_translate_i_colon() {
verifyTranslation("i:", "i, dig dis:")
}
@Test
fun should_translate_j_colon() {
verifyTranslation("j:", "j, dig dis:")
}
@Test
fun should_translate_k_colon() {
verifyTranslation("k:", "k, dig dis:")
}
@Test
fun should_translate_l_colon() {
verifyTranslation("l:", "l, dig dis:")
}
@Test
fun should_translate_m_colon() {
verifyTranslation("m:", "m, dig dis:")
}
@Test
fun should_translate_n_colon() {
verifyTranslation("n:", "n, dig dis:")
}
@Test
fun should_translate_o_colon() {
verifyTranslation("o:", "o, dig dis:")
}
@Test
fun should_translate_p_colon() {
verifyTranslation("http:", "http:")
}
@Test
fun should_translate_q_colon() {
verifyTranslation("q:", "q, dig dis:")
}
@Test
fun should_translate_r_colon() {
verifyTranslation("r:", "r, dig dis:")
}
@Test
fun should_translate_s_colon() {
verifyTranslation("https:", "https:")
}
@Test
fun should_translate_t_colon() {
verifyTranslation("t:", "t, dig dis:")
}
@Test
fun should_translate_u_colon() {
verifyTranslation("u:", "u, dig dis:")
}
@Test
fun should_translate_v_colon() {
verifyTranslation("v:", "v, dig dis:")
}
@Test
fun should_translate_w_colon() {
verifyTranslation("w:", "w, dig dis:")
}
@Test
fun should_translate_x_colon() {
verifyTranslation("x:", "x, dig dis:")
}
@Test
fun should_translate_y_colon() {
verifyTranslation("y:", "y, dig dis:")
}
@Test
fun should_translate_z_colon() {
verifyTranslation("z:", "z, dig dis:")
}
@Test
fun should_translate_amateur() {
verifyTranslation("aaa amateur aaa", "aaa begina' aaa")
}
@Test
fun should_not_translate_unamateurny() {
verifyTranslation("unamateurny", "unamateurny")
}
@Test
fun should_translate_radio() {
verifyTranslation("aaa radio aaa", "aaa transista' aaa")
}
@Test
fun should_not_translate_unradiony() {
verifyTranslation("unradiony", "unradiony")
}
@Test
fun should_translate_of() {
verifyTranslation("aaa of aaa", "aaa uh' aaa")
}
@Test
fun should_not_translate_unofny() {
verifyTranslation("unofny", "unofny")
}
@Test
fun should_translate_what() {
verifyTranslation("aaa what aaa", "aaa whut aaa")
}
@Test
fun should_not_translate_unwhatny() {
verifyTranslation("unwhatny", "unwhatny")
}
@Test
fun should_translate_does() {
verifyTranslation("aaa does aaa", "aaa duz aaa")
}
@Test
fun should_not_translate_undoesny() {
verifyTranslation("undoesny", "undoesny")
}
@Test
fun should_translate_was() {
verifyTranslation("aaa was aaa", "aaa wuz aaa")
}
@Test
fun should_not_translate_unwasny() {
verifyTranslation("unwasny", "unwasny")
}
@Test
fun should_translate_were() {
verifyTranslation("aaa were aaa", "aaa wuz aaa")
}
@Test
fun should_not_translate_unwereny() {
verifyTranslation("unwereny", "unwereny")
}
@Test
fun should_translate_understand() {
verifyTranslation("aaa understand aaa", "aaa dig it aaa")
}
@Test
fun should_not_translate_ununderstandny() {
verifyTranslation("ununderstandny", "ununderstandny")
}
@Test
fun should_translate_understand_it() {
verifyTranslation("aaa understand it aaa", "aaa dig it aaa")
}
@Test
fun should_not_translate_ununderstand_itny() {
verifyTranslation("ununderstand itny", "ununderstand itny")
}
@Test
fun should_translate_my() {
verifyTranslation("aaa my aaa", "aaa mah aaa")
}
@Test
fun should_not_translate_unmyny() {
verifyTranslation("unmyny", "unmyny")
}
@Test
fun should_translate_I() {
verifyTranslation("aaa I aaa", "aaa ah' aaa")
}
@Test
fun should_not_translate_unIny() {
verifyTranslation("unIny", "unIny")
}
@Test
fun should_translate_meta() {
verifyTranslation("aaa meta aaa", "aaa meta-fuckin' aaa")
}
@Test
fun should_not_translate_unmetany() {
verifyTranslation("unmetany", "unmetany")
}
@Test
fun should_translate_hair() {
verifyTranslation("aaa hair aaa", "aaa fro aaa")
}
@Test
fun should_not_translate_unhairny() {
verifyTranslation("unhairny", "unhairny")
}
@Test
fun should_translate_talk() {
verifyTranslation("aaa talk aaa", "aaa rap aaa")
}
@Test
fun should_not_translate_untalkny() {
verifyTranslation("untalkny", "untalkny")
}
@Test
fun should_translate_music() {
verifyTranslation("aaa music aaa", "aaa beat aaa")
}
@Test
fun should_not_translate_unmusicny() {
verifyTranslation("unmusicny", "unmusicny")
}
@Test
fun should_translate_basket() {
verifyTranslation("aaa basket aaa", "aaa hoop aaa")
}
@Test
fun should_not_translate_unbasketny() {
verifyTranslation("unbasketny", "unbasketny")
}
@Test
fun should_translate_football() {
verifyTranslation("aaa football aaa", "aaa ball aaa")
}
@Test
fun should_ntot_translate_unfootballny() {
verifyTranslation("unfootballny", "unfootballny")
}
@Test
fun should_translate_friend() {
verifyTranslation("aaa friend aaa", "aaa homey aaa")
}
@Test
fun should_not_translate_unfriendny() {
verifyTranslation("unfriendny", "unfriendny")
}
@Test
fun should_translate_school() {
verifyTranslation("aaa school aaa", "aaa farm aaa")
}
@Test
fun should_not_translate_unschoolny() {
verifyTranslation("unschoolny", "unschoolny")
}
@Test
fun should_translate_my_boss() {
verifyTranslation("aaa my boss aaa", "aaa The Man aaa")
}
@Test
fun should_not_translate_unmy_bossny() {
verifyTranslation("unmy bossny", "unmy bossny")
}
@Test
fun should_translate_want_to() {
verifyTranslation("aaa want to aaa", "aaa wanna aaa")
}
@Test
fun should_not_translate_unwant_tony() {
verifyTranslation("unwant tony", "unwant tony")
}
@Test
fun should_translate_wants_to() {
verifyTranslation("aaa wants to aaa", "aaa be hankerin' aftah aaa")
}
@Test
fun should_not_translate_unwants_tony() {
verifyTranslation("unwants tony", "unwants tony")
}
@Test
fun should_translate_Well() {
verifyTranslation("aaa Well aaa", "aaa Sheeit aaa")
}
@Test
fun should_not_translate_unWellny() {
verifyTranslation("unWellny", "unWellny")
}
@Test
fun should_translate_well() {
verifyTranslation("aaa well aaa", "aaa sheeit aaa")
}
@Test
fun should_not_translate_unwellny() {
verifyTranslation("unwellny", "unwellny")
}
@Test
fun should_translate_big() {
verifyTranslation("aaa big aaa", "aaa big-ass aaa")
}
@Test
fun should_not_translate_unbigny() {
verifyTranslation("unbigny", "unbigny")
}
@Test
fun should_translate_bad() {
verifyTranslation("aaa bad aaa", "aaa bad-ass aaa")
}
@Test
fun should_not_translate_unbadny() {
verifyTranslation("unbadny", "unbadny")
}
@Test
fun should_translate_small() {
verifyTranslation("aaa small aaa", "aaa little-ass aaa")
}
@Test
fun should_not_translate_unsmallny() {
verifyTranslation("unsmallny", "unsmallny")
}
@Test
fun should_translate_sort_of() {
verifyTranslation("aaa sort of aaa", "aaa radical aaa")
}
@Test
fun should_not_translate_unsort_ofny() {
verifyTranslation("unsort ofny", "unsort ofny")
}
@Test
fun should_translate_is() {
verifyTranslation("aaa is aaa", "aaa be aaa")
}
@Test
fun should_not_translate_unisny() {
verifyTranslation("unisny", "unisny")
}
@Test
fun should_translate_water() {
verifyTranslation("aaa water aaa", "aaa booze aaa")
}
@Test
fun should_not_translate_unwaterny() {
verifyTranslation("unwaterny", "unwaterny")
}
@Test
fun should_translate_book() {
verifyTranslation("aaa book aaa", "aaa scribblin' aaa")
}
@Test
fun should_not_translate_unbookny() {
verifyTranslation("unbookny", "unbookny")
}
@Test
fun should_translate_magazine() {
verifyTranslation("aaa magazine aaa", "aaa issue of GQ aaa")
}
@Test
fun should_not_translate_unmagazineny() {
verifyTranslation("unmagazineny", "unmagazineny")
}
@Test
fun should_translate_paper() {
verifyTranslation("aaa paper aaa", "aaa sheet aaa")
}
@Test
fun should_not_translate_unpaperny() {
verifyTranslation("unpaperny", "unpaperny")
}
@Test
fun should_translate_up() {
verifyTranslation("aaa up aaa", "aaa down aaa")
}
@Test
fun should_not_translate_unupny() {
verifyTranslation("unupny", "unupny")
}
@Test
fun should_translate_down() {
verifyTranslation("aaa down aaa", "aaa waaay down aaa")
}
@Test
fun should_not_translate_undownny() {
verifyTranslation("undownny", "undownny")
}
@Test
fun should_translate_Hi() {
verifyTranslation("aaa Hi aaa", "aaa 'Sup, dude aaa")
}
@Test
fun should_not_translate_unHiny() {
verifyTranslation("unHiny", "unHiny")
}
@Test
fun should_translate_VAX() {
verifyTranslation("aaa VAX aaa", "aaa Pink Cadillac aaa")
}
@Test
fun should_not_translate_unVAXy() {
verifyTranslation("aaa unVAXy aaa", "aaa unVAXy aaa")
}
@Test
fun should_translate_statusWithEntities() {
// Given
val statusText = "RT @AndrewDunn10 .@CheerfulPodcast is a remarkably fun #podcast. Worth a listen if you're interested in progressive politics and trying to make the world a little better."
val translated = "RT @AndrewDunn10 .@CheerfulPodcast be some remarkably fun #podcast. Word some listen if youse interested in progressive politics and tryin' t'make da damn world some little better. Ah be baaad..."
val translationEntity0 = TranslationEntity.translate(0, 3, "RT ")
val translationEntity1 = TranslationEntity.verbatim(3, 16, "@AndrewDunn10")
val translationEntity2 = TranslationEntity.translate(16, 18, " .")
val translationEntity3 = TranslationEntity.verbatim(18, 34, "@CheerfulPodcast")
val translationEntity4 = TranslationEntity.translate(34, 55, " is a remarkably fun ")
val translationEntity5 = TranslationEntity.verbatim(55, 63, "#podcast")
val translationEntity6 = TranslationEntity.translate(63, 170, ". Worth a listen if you're interested in progressive politics and trying to make the world a little better.")
val entitiesList = ArrayList<TranslationEntity>(7)
entitiesList.add(translationEntity0)
entitiesList.add(translationEntity1)
entitiesList.add(translationEntity2)
entitiesList.add(translationEntity3)
entitiesList.add(translationEntity4)
entitiesList.add(translationEntity5)
entitiesList.add(translationEntity6)
// When
jiveTranslator.translate(entitiesList)
// Then
verify<Jive<*, *, *>>(mockJive).onTranslationComplete(translated)
}
private fun verifyTranslation(text: String, translation: String) {
// Given
val translationEntity = TranslationEntity.translate(0, text.length, text)
val entityList = ArrayList<TranslationEntity>(1)
entityList.add(translationEntity)
// When
jiveTranslator.translate(entityList)
// Then
verify<Jive<*, *, *>>(mockJive).onTranslationComplete(translation)
}
}
| mit | b093c995c735695491e04cf3a27fe929 | 22.001033 | 222 | 0.597984 | 3.738295 | false | true | false | false |
cascheberg/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/database/ChatColorsDatabase.kt | 1 | 4793 | package org.thoughtcrime.securesms.database
import android.content.ContentValues
import android.content.Context
import android.database.Cursor
import org.thoughtcrime.securesms.conversation.colors.ChatColors
import org.thoughtcrime.securesms.database.helpers.SQLCipherOpenHelper
import org.thoughtcrime.securesms.database.model.databaseprotos.ChatColor
import org.thoughtcrime.securesms.dependencies.ApplicationDependencies
import org.thoughtcrime.securesms.keyvalue.SignalStore
import org.thoughtcrime.securesms.util.CursorUtil
import org.thoughtcrime.securesms.util.SqlUtil
class ChatColorsDatabase(context: Context, databaseHelper: SQLCipherOpenHelper) : Database(context, databaseHelper) {
companion object {
private const val TABLE_NAME = "chat_colors"
private const val ID = "_id"
private const val CHAT_COLORS = "chat_colors"
@JvmField
val CREATE_TABLE = """
CREATE TABLE $TABLE_NAME (
$ID INTEGER PRIMARY KEY AUTOINCREMENT,
$CHAT_COLORS BLOB
)
""".trimIndent()
}
fun getById(chatColorsId: ChatColors.Id): ChatColors {
val db = databaseHelper.readableDatabase
val projection = arrayOf(ID, CHAT_COLORS)
val args = SqlUtil.buildArgs(chatColorsId.longValue)
db.query(TABLE_NAME, projection, ID_WHERE, args, null, null, null)?.use {
if (it.moveToFirst()) {
return it.getChatColors()
}
}
throw IllegalArgumentException("Could not locate chat color $chatColorsId")
}
fun saveChatColors(chatColors: ChatColors): ChatColors {
return when (chatColors.id) {
is ChatColors.Id.Auto -> throw AssertionError("Saving 'auto' does not make sense")
is ChatColors.Id.BuiltIn -> chatColors
is ChatColors.Id.NotSet -> insertChatColors(chatColors)
is ChatColors.Id.Custom -> updateChatColors(chatColors)
}
}
fun getSavedChatColors(): List<ChatColors> {
val db = databaseHelper.readableDatabase
val projection = arrayOf(ID, CHAT_COLORS)
val result = mutableListOf<ChatColors>()
db.query(TABLE_NAME, projection, null, null, null, null, null)?.use {
while (it.moveToNext()) {
result.add(it.getChatColors())
}
}
return result
}
private fun insertChatColors(chatColors: ChatColors): ChatColors {
if (chatColors.id != ChatColors.Id.NotSet) {
throw IllegalArgumentException("Bad chat colors to insert.")
}
val db: SQLiteDatabase = databaseHelper.writableDatabase
val values = ContentValues(1).apply {
put(CHAT_COLORS, chatColors.serialize().toByteArray())
}
val rowId = db.insert(TABLE_NAME, null, values)
if (rowId == -1L) {
throw IllegalStateException("Failed to insert ChatColor into database")
}
notifyListeners()
return chatColors.withId(ChatColors.Id.forLongValue(rowId))
}
private fun updateChatColors(chatColors: ChatColors): ChatColors {
if (chatColors.id == ChatColors.Id.NotSet || chatColors.id == ChatColors.Id.BuiltIn) {
throw IllegalArgumentException("Bad chat colors to update.")
}
val db: SQLiteDatabase = databaseHelper.writableDatabase
val values = ContentValues(1).apply {
put(CHAT_COLORS, chatColors.serialize().toByteArray())
}
val rowsUpdated = db.update(TABLE_NAME, values, ID_WHERE, SqlUtil.buildArgs(chatColors.id.longValue))
if (rowsUpdated < 1) {
throw IllegalStateException("Failed to update ChatColor in database")
}
if (SignalStore.chatColorsValues().chatColors?.id == chatColors.id) {
SignalStore.chatColorsValues().chatColors = chatColors
}
val recipientDatabase = DatabaseFactory.getRecipientDatabase(context)
recipientDatabase.onUpdatedChatColors(chatColors)
notifyListeners()
return chatColors
}
fun deleteChatColors(chatColors: ChatColors) {
if (chatColors.id == ChatColors.Id.NotSet || chatColors.id == ChatColors.Id.BuiltIn) {
throw IllegalArgumentException("Cannot delete this chat color")
}
val db: SQLiteDatabase = databaseHelper.writableDatabase
db.delete(TABLE_NAME, ID_WHERE, SqlUtil.buildArgs(chatColors.id.longValue))
if (SignalStore.chatColorsValues().chatColors?.id == chatColors.id) {
SignalStore.chatColorsValues().chatColors = null
}
val recipientDatabase = DatabaseFactory.getRecipientDatabase(context)
recipientDatabase.onDeletedChatColors(chatColors)
notifyListeners()
}
private fun notifyListeners() {
ApplicationDependencies.getDatabaseObserver().notifyChatColorsListeners()
}
private fun Cursor.getId(): Long = CursorUtil.requireLong(this, ID)
private fun Cursor.getChatColors(): ChatColors = ChatColors.forChatColor(
ChatColors.Id.forLongValue(getId()),
ChatColor.parseFrom(CursorUtil.requireBlob(this, CHAT_COLORS))
)
}
| gpl-3.0 | 4df1b304d49949efab8c4f7fb84f04e9 | 33.482014 | 117 | 0.728562 | 4.421587 | false | false | false | false |
mdanielwork/intellij-community | platform/script-debugger/backend/src/rpc/CommandSenderBase.kt | 4 | 1356 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.rpc
import org.jetbrains.concurrency.AsyncPromise
import org.jetbrains.concurrency.Promise
import org.jetbrains.concurrency.catchError
import org.jetbrains.jsonProtocol.Request
abstract class CommandSenderBase<SUCCESS_RESPONSE> {
protected abstract fun <RESULT> doSend(message: Request<RESULT>, callback: RequestPromise<SUCCESS_RESPONSE, RESULT>)
fun <RESULT : Any?> send(message: Request<RESULT>): Promise<RESULT> {
val callback = RequestPromise<SUCCESS_RESPONSE, RESULT>(message.methodName)
doSend(message, callback)
return callback
}
}
class RequestPromise<SUCCESS_RESPONSE, RESULT : Any?>(private val methodName: String?) : AsyncPromise<RESULT>(), RequestCallback<SUCCESS_RESPONSE> {
override fun onSuccess(response: SUCCESS_RESPONSE?, resultReader: ResultReader<SUCCESS_RESPONSE>?) {
catchError {
val r: Any?
if (resultReader == null || response == null) {
r = response
}
else if (methodName == null) {
r = null
}
else {
r = resultReader.readResult(methodName, response)
}
UnsafeSetResult.setResult(this, r)
}
}
override fun onError(error: Throwable) {
setError(error)
}
} | apache-2.0 | f99fbd81c11b32730312dbac6cc24005 | 32.925 | 148 | 0.714602 | 4.250784 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.