repo_name
stringlengths
7
81
path
stringlengths
6
242
copies
stringclasses
53 values
size
stringlengths
2
6
content
stringlengths
73
737k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
5.44
99.8
line_max
int64
15
977
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.93
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
google/intellij-community
plugins/kotlin/base/util/src/org/jetbrains/kotlin/idea/base/util/caching/WorkspaceEntityChangeListener.kt
1
2799
// 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.base.util.caching import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.roots.libraries.Library import com.intellij.workspaceModel.ide.WorkspaceModelChangeListener import com.intellij.workspaceModel.storage.EntityChange import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.VersionedStorageChange import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.bridgeEntities.api.LibraryEntity import com.intellij.workspaceModel.storage.bridgeEntities.api.ModuleEntity abstract class WorkspaceEntityChangeListener<Entity : WorkspaceEntity, Value : Any>( protected val project: Project, private val afterChangeApplied: Boolean = true ) : WorkspaceModelChangeListener { protected abstract val entityClass: Class<Entity> protected abstract fun map(storage: EntityStorage, entity: Entity): Value? protected abstract fun entitiesChanged(outdated: List<Value>) final override fun beforeChanged(event: VersionedStorageChange) { if (!afterChangeApplied) { handleEvent(event) } } final override fun changed(event: VersionedStorageChange) { if (afterChangeApplied) { handleEvent(event) } } private fun handleEvent(event: VersionedStorageChange) { val storageBefore = event.storageBefore val changes = event.getChanges(entityClass).ifEmpty { return } val outdatedEntities: List<Value> = changes.asSequence() .mapNotNull(EntityChange<Entity>::oldEntity) .mapNotNull { map(storageBefore, it) } .toList() if (outdatedEntities.isNotEmpty()) { entitiesChanged(outdatedEntities) } } } abstract class ModuleEntityChangeListener(project: Project, afterChangeApplied: Boolean = true) : WorkspaceEntityChangeListener<ModuleEntity, Module>(project, afterChangeApplied) { override val entityClass: Class<ModuleEntity> get() = ModuleEntity::class.java override fun map(storage: EntityStorage, entity: ModuleEntity): Module? = storage.findModuleByEntityWithHack(entity, project) } abstract class LibraryEntityChangeListener(project: Project, afterChangeApplied: Boolean = true) : WorkspaceEntityChangeListener<LibraryEntity, Library>(project, afterChangeApplied) { override val entityClass: Class<LibraryEntity> get() = LibraryEntity::class.java override fun map(storage: EntityStorage, entity: LibraryEntity): Library? = storage.findLibraryByEntityWithHack(entity, project) }
apache-2.0
dacaa25d44a13ab0ba4ba063c7db5b64
41.424242
183
0.757056
5.212291
false
false
false
false
google/intellij-community
plugins/kotlin/j2k/post-processing/src/org/jetbrains/kotlin/idea/j2k/post/processing/inference/nullability/NullabilityBoundTypeEnhancer.kt
2
5491
// 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.j2k.post.processing.inference.nullability import javaslang.control.Option import org.jetbrains.kotlin.descriptors.ConstructorDescriptor import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.intentions.branchedTransformations.isNullExpression import org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.* import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.idea.resolve.ResolutionFacade import org.jetbrains.kotlin.idea.resolve.dataFlowValueFactory import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.util.getType import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowInfo import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowValue import org.jetbrains.kotlin.resolve.calls.smartcasts.Nullability import org.jetbrains.kotlin.resolve.jvm.checkers.mustNotBeNull import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.isNullable private fun <T> Option<T>.getOrNull(): T? = getOrElse(null as T?) class NullabilityBoundTypeEnhancer(private val resolutionFacade: ResolutionFacade) : BoundTypeEnhancer() { override fun enhance( expression: KtExpression, boundType: BoundType, inferenceContext: InferenceContext ): BoundType = when { expression.isNullExpression() -> WithForcedStateBoundType(boundType, State.UPPER) expression is KtCallExpression -> enhanceCallExpression(expression, boundType, inferenceContext) expression is KtQualifiedExpression && expression.selectorExpression is KtCallExpression -> enhanceCallExpression(expression.selectorExpression as KtCallExpression, boundType, inferenceContext) expression is KtNameReferenceExpression -> boundType.enhanceWith(expression.smartCastEnhancement()) expression is KtLambdaExpression -> WithForcedStateBoundType(boundType, State.LOWER) else -> boundType } private fun enhanceCallExpression( expression: KtCallExpression, boundType: BoundType, inferenceContext: InferenceContext ): BoundType { if (expression.resolveToCall(resolutionFacade)?.candidateDescriptor is ConstructorDescriptor) { return WithForcedStateBoundType(boundType, State.LOWER) } val resolved = expression.calleeExpression?.mainReference?.resolve() ?: return boundType if (inferenceContext.isInConversionScope(resolved)) return boundType return boundType.enhanceWith(expression.getExternallyAnnotatedForcedState()) } override fun enhanceKotlinType( type: KotlinType, boundType: BoundType, allowLowerEnhancement: Boolean, inferenceContext: InferenceContext ): BoundType { if (type.arguments.size != boundType.typeParameters.size) return boundType val inner = BoundTypeImpl( boundType.label, boundType.typeParameters.zip(type.arguments) { typeParameter, typeArgument -> TypeParameter( enhanceKotlinType( typeArgument.type, typeParameter.boundType, allowLowerEnhancement, inferenceContext ), typeParameter.variance ) } ) val enhancement = when { type.isMarkedNullable -> State.UPPER allowLowerEnhancement -> State.LOWER else -> null } return inner.enhanceWith(enhancement) } private fun KtReferenceExpression.smartCastEnhancement() = analyzeExpressionUponTheTypeInfo { dataFlowValue, dataFlowInfo, _ -> if (dataFlowInfo.completeNullabilityInfo.get(dataFlowValue)?.getOrNull() == Nullability.NOT_NULL) State.LOWER else null } private inline fun KtExpression.analyzeExpressionUponTheTypeInfo(analyzer: (DataFlowValue, DataFlowInfo, KotlinType) -> State?): State? { val bindingContext = analyze(resolutionFacade) val type = getType(bindingContext) ?: return null val dataFlowValue = resolutionFacade.dataFlowValueFactory .createDataFlowValue(this, type, bindingContext, resolutionFacade.moduleDescriptor) val dataFlowInfo = bindingContext[BindingContext.EXPRESSION_TYPE_INFO, this]?.dataFlowInfo ?: return null return analyzer(dataFlowValue, dataFlowInfo, type) } private fun KtExpression.getExternallyAnnotatedForcedState() = analyzeExpressionUponTheTypeInfo { dataFlowValue, dataFlowInfo, type -> if (!type.isNullable()) return@analyzeExpressionUponTheTypeInfo State.LOWER when { dataFlowInfo.completeNullabilityInfo.get(dataFlowValue)?.getOrNull() == Nullability.NOT_NULL -> State.LOWER type.isExternallyAnnotatedNotNull(dataFlowInfo, dataFlowValue) -> State.LOWER else -> null } } private fun KotlinType.isExternallyAnnotatedNotNull(dataFlowInfo: DataFlowInfo, dataFlowValue: DataFlowValue): Boolean = mustNotBeNull()?.isFromJava == true && dataFlowInfo.getStableNullability(dataFlowValue).canBeNull() }
apache-2.0
d7468c49c2cfb089d1465d980eb7cb86
47.60177
158
0.728465
5.737722
false
false
false
false
Werb/MoreType
app/src/main/java/com/werb/moretype/multi/MultiRegisterActivity.kt
1
6432
package com.werb.moretype.multi import android.Manifest import android.app.Activity import android.content.Intent import android.os.Bundle import android.text.TextUtils import android.view.View import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import com.werb.library.MoreAdapter import com.werb.library.link.MultiLink import com.werb.library.link.RegisterItem import com.werb.moretype.R import com.werb.moretype.TitleViewHolder import com.werb.moretype.Utils import com.werb.moretype.data.DataServer import com.werb.permissionschecker.PermissionChecker import com.werb.pickphotoview.PickPhotoView import com.werb.pickphotoview.util.PickConfig import kotlinx.android.synthetic.main.activity_multi_register.* import kotlinx.android.synthetic.main.widget_view_message_input.* /** * Created by wanbo on 2017/7/14. */ class MultiRegisterActivity : AppCompatActivity() { val PERMISSIONS = arrayOf(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE) private var permissionChecker: PermissionChecker? = null private val adapter = MoreAdapter() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_multi_register) // permission check permissionChecker = PermissionChecker(this) toolbar.setNavigationIcon(R.mipmap.ic_close_white_24dp) toolbar.setNavigationOnClickListener { finish() } multi_register_list.layoutManager = LinearLayoutManager(this) adapter.apply { register(RegisterItem(R.layout.item_view_title, TitleViewHolder::class.java)) multiRegister(object : MultiLink<Message>() { override fun link(data: Message): RegisterItem { return if (data.me){ RegisterItem(R.layout.item_view_multi_message_out, MessageOutViewHolder::class.java) }else { RegisterItem(R.layout.item_view_multi_message_in, MessageInViewHolder::class.java) } } }) attachTo(multi_register_list) } adapter.loadData(DataServer.getMultiRegisterData()) input_edit.setOnFocusChangeListener { view, hasFocus -> run { if (hasFocus) { view.postDelayed({ multi_register_list.smoothScrollToPosition(adapter.itemCount -1) }, 250) } } } layout_send.setOnClickListener(sendClick) input_image_layout.setOnClickListener(imageClick) } private val sendClick = View.OnClickListener { if (!TextUtils.isEmpty(input_edit.text.toString())) { adapter.loadData(buildSendMessageText()) input_edit.setText("") multi_register_list.smoothScrollToPosition(adapter.itemCount) it.postDelayed({ adapter.loadData(buildInMessageText()) multi_register_list.smoothScrollToPosition(adapter.itemCount) }, 200) } } private val imageClick = View.OnClickListener { permissionChecker?.let { if (it.isLackPermissions(PERMISSIONS)) { it.requestPermissions() } else { pickPhoto() } } } private fun pickPhoto() { PickPhotoView.Builder(this@MultiRegisterActivity) .setPickPhotoSize(1) .setShowCamera(true) .setSpanCount(4) .setLightStatusBar(true) .setStatusBarColor(R.color.colorTextLight) .setToolbarColor(R.color.colorTextLight) .setToolbarTextColor(R.color.colorAccent) .setSelectIconColor(R.color.colorPrimary) .setShowGif(false) .start() } private fun buildSendMessageText(): Message { return Message( "", "text", true, input_edit.text.toString(), "", "", "", "", false ) } private fun buildInMessageText(): Message { return Message( "https://avatars5.githubusercontent.com/u/12763277?v=4&s=460", "text", false, "收到你的消息", "", "", "", "", false ) } private fun buildSendMessageImage(url: String, size: ImageSize): Message { return Message( "", "image", true, input_edit.text.toString(), url, "", size.width.toString(), size.height.toString(), false ) } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) { permissionChecker?.let { when (requestCode) { PermissionChecker.PERMISSION_REQUEST_CODE -> { if (it.hasAllPermissionsGranted(grantResults)) { pickPhoto() } } else -> { it.showDialog() } } } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (resultCode == 0) { return } if (data == null) { return } if (requestCode == PickConfig.PICK_PHOTO_DATA) { val selectPaths = data.getSerializableExtra(PickConfig.INTENT_IMG_LIST_SELECT) as ArrayList<*> // do something u want val path = selectPaths[0] as String val imageSize = Utils.readImageSize(path) imageSize?.let { adapter.loadData(buildSendMessageImage(path, imageSize)) multi_register_list.smoothScrollToPosition(adapter.itemCount) } } } companion object { fun startActivity(activity: Activity){ activity.startActivity(Intent(activity, MultiRegisterActivity::class.java)) } } }
apache-2.0
107bb4ccff4e4893ba1da2db27da55d7
32.097938
115
0.574299
5.111465
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/jvm-debugger/test/test/org/jetbrains/kotlin/idea/debugger/test/mock/SmartMockReferenceType.kt
1
9253
// 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.debugger.test.mock import com.sun.jdi.* import org.jetbrains.kotlin.backend.common.output.OutputFile import org.jetbrains.kotlin.backend.common.output.OutputFileCollection import org.jetbrains.org.objectweb.asm.ClassReader import org.jetbrains.org.objectweb.asm.Opcodes import org.jetbrains.org.objectweb.asm.tree.ClassNode import org.jetbrains.org.objectweb.asm.tree.LineNumberNode import org.jetbrains.org.objectweb.asm.tree.MethodNode class SmartMockReferenceTypeContext(outputFiles: List<OutputFile>) { constructor(outputFiles: OutputFileCollection) : this(outputFiles.asList()) val virtualMachine = MockVirtualMachine() val classes = outputFiles .filter { it.relativePath.endsWith(".class") } .map { it.readClass() } private val referenceTypes: List<ReferenceType> by lazy { classes.map { SmartMockReferenceType(it, this) } } val referenceTypesByName by lazy { referenceTypes.map { Pair(it.name(), it) }.toMap() } } private fun OutputFile.readClass(): ClassNode { val classNode = ClassNode() ClassReader(asByteArray()).accept(classNode, ClassReader.EXPAND_FRAMES) return classNode } class SmartMockReferenceType(val classNode: ClassNode, private val context: SmartMockReferenceTypeContext) : ReferenceType { override fun instances(maxInstances: Long) = emptyList<ObjectReference>() override fun isPublic() = (classNode.access and Opcodes.ACC_PUBLIC) != 0 override fun classLoader() = null override fun sourceName(): String? = classNode.sourceFile override fun defaultStratum() = "Java" override fun isStatic() = (classNode.access and Opcodes.ACC_STATIC) != 0 override fun modifiers() = classNode.access override fun isProtected() = (classNode.access and Opcodes.ACC_PROTECTED) != 0 override fun isFinal() = (classNode.access and Opcodes.ACC_FINAL) != 0 override fun allLineLocations() = methodsCached.flatMap { it.allLineLocations() } override fun genericSignature(): String? = classNode.signature override fun isAbstract() = (classNode.access and Opcodes.ACC_ABSTRACT) != 0 override fun isPrepared() = true override fun name() = classNode.name.replace('/', '.') override fun isInitialized() = true override fun sourcePaths(stratum: String) = listOf(classNode.sourceFile) override fun failedToInitialize() = false override fun virtualMachine() = context.virtualMachine override fun isPrivate() = (classNode.access and Opcodes.ACC_PRIVATE) != 0 override fun signature(): String? = classNode.signature override fun sourceNames(stratum: String) = listOf(classNode.sourceFile) override fun availableStrata() = emptyList<String>() private val methodsCached by lazy { classNode.methods.map { MockMethod(it, this) } } override fun methods() = methodsCached override fun nestedTypes(): List<ReferenceType> { val fromInnerClasses = classNode.innerClasses .filter { it.outerName == classNode.name } .mapNotNull { context.classes.find { c -> it.name == c.name } } val fromOuterClasses = context.classes.filter { it.outerClass == classNode.name } return (fromInnerClasses + fromOuterClasses).distinctBy { it.name }.map { SmartMockReferenceType(it, context) } } override fun isPackagePrivate(): Boolean { return ((classNode.access and Opcodes.ACC_PUBLIC) == 0 && (classNode.access and Opcodes.ACC_PROTECTED) == 0 && (classNode.access and Opcodes.ACC_PRIVATE) == 0) } override fun isVerified() = true override fun fields() = TODO() override fun allFields() = TODO() override fun fieldByName(fieldName: String) = TODO() override fun getValue(p0: Field?) = TODO() override fun visibleFields() = TODO() override fun allLineLocations(stratum: String, sourceName: String) = TODO() override fun majorVersion() = TODO() override fun constantPoolCount() = TODO() override fun constantPool() = TODO() override fun compareTo(other: ReferenceType?) = TODO() override fun sourceDebugExtension() = TODO() override fun visibleMethods() = TODO() override fun locationsOfLine(lineNumber: Int) = TODO() override fun locationsOfLine(stratum: String, sourceName: String, lineNumber: Int) = TODO() override fun getValues(p0: List<Field>?) = TODO() override fun minorVersion() = TODO() override fun classObject() = TODO() override fun methodsByName(p0: String?) = TODO() override fun methodsByName(p0: String?, p1: String?) = TODO() override fun allMethods() = TODO() override fun equals(other: Any?): Boolean { if (this === other) return true if (other?.javaClass != javaClass) return false other as SmartMockReferenceType return classNode.name == other.classNode.name } override fun hashCode(): Int { return classNode.name.hashCode() } class MockMethod(private val methodNode: MethodNode, val containingClass: SmartMockReferenceType) : Method { override fun virtualMachine() = containingClass.context.virtualMachine override fun modifiers() = methodNode.access override fun isStaticInitializer() = methodNode.name == "<clinit>" override fun isPublic() = (methodNode.access and Opcodes.ACC_PUBLIC) != 0 override fun isNative() = (methodNode.access and Opcodes.ACC_NATIVE) != 0 override fun isStatic() = (methodNode.access and Opcodes.ACC_STATIC) != 0 override fun isBridge() = (methodNode.access and Opcodes.ACC_BRIDGE) != 0 override fun isProtected() = (methodNode.access and Opcodes.ACC_PROTECTED) != 0 override fun isFinal() = (methodNode.access and Opcodes.ACC_FINAL) != 0 override fun isAbstract() = (methodNode.access and Opcodes.ACC_ABSTRACT) != 0 override fun isSynthetic() = (methodNode.access and Opcodes.ACC_SYNTHETIC) != 0 override fun isConstructor() = methodNode.name == "<init>" override fun isPrivate() = (methodNode.access and Opcodes.ACC_PRIVATE) != 0 override fun isPackagePrivate(): Boolean { return ((methodNode.access and Opcodes.ACC_PUBLIC) == 0 && (methodNode.access and Opcodes.ACC_PROTECTED) == 0 && (methodNode.access and Opcodes.ACC_PRIVATE) == 0) } override fun declaringType() = containingClass override fun name(): String? = methodNode.name override fun signature(): String? = methodNode.signature override fun location(): Location? { val instructionList = methodNode.instructions ?: return null var current = instructionList.first while (current != null) { if (current is LineNumberNode) { return MockLocation(this, current.line) } current = current.next } return null } override fun allLineLocations(): List<Location> { val instructionList = methodNode.instructions ?: return emptyList() var current = instructionList.first val locations = mutableListOf<Location>() while (current != null) { if (current is LineNumberNode) { locations += MockLocation(this, current.line) } current = current.next } return locations } override fun argumentTypeNames() = TODO() override fun arguments() = TODO() override fun allLineLocations(p0: String?, p1: String?) = TODO() override fun genericSignature() = TODO() override fun returnType() = TODO() override fun compareTo(other: Method?) = TODO() override fun isObsolete() = false override fun variablesByName(p0: String?) = TODO() override fun argumentTypes() = TODO() override fun locationOfCodeIndex(p0: Long) = TODO() override fun bytecodes() = TODO() override fun returnTypeName() = TODO() override fun locationsOfLine(p0: Int) = TODO() override fun locationsOfLine(p0: String?, p1: String?, p2: Int) = TODO() override fun variables() = TODO() override fun isVarArgs() = TODO() override fun isSynchronized() = TODO() } private class MockLocation(val method: MockMethod, val line: Int) : Location { override fun virtualMachine() = method.containingClass.context.virtualMachine override fun sourceName() = method.containingClass.sourceName() override fun lineNumber() = line override fun sourcePath() = sourceName() override fun declaringType() = method.containingClass override fun method() = method override fun sourceName(stratum: String) = TODO() override fun codeIndex() = TODO() override fun lineNumber(stratum: String) = TODO() override fun sourcePath(stratum: String) = TODO() override fun compareTo(other: Location?) = TODO() } }
apache-2.0
6639ef03ad2367b5d238125512d85684
44.581281
158
0.669729
4.796786
false
false
false
false
apollographql/apollo-android
tests/integration-tests/src/commonTest/kotlin/test/CacheResolverTest.kt
1
1607
package test import com.apollographql.apollo3.ApolloClient import com.apollographql.apollo3.annotations.ApolloExperimental import com.apollographql.apollo3.api.CompiledField import com.apollographql.apollo3.api.Executable import com.apollographql.apollo3.cache.normalized.ApolloStore import com.apollographql.apollo3.cache.normalized.api.CacheResolver import com.apollographql.apollo3.cache.normalized.api.DefaultCacheResolver import com.apollographql.apollo3.cache.normalized.api.MemoryCacheFactory import com.apollographql.apollo3.cache.normalized.store import com.apollographql.apollo3.integration.normalizer.HeroNameQuery import com.apollographql.apollo3.testing.runTest import kotlin.test.Test import kotlin.test.assertEquals @OptIn(ApolloExperimental::class) class CacheResolverTest { @Test fun cacheResolverCanResolveQuery() = runTest { val resolver = object : CacheResolver { override fun resolveField(field: CompiledField, variables: Executable.Variables, parent: Map<String, Any?>, parentId: String): Any? { return when (field.name) { "hero" -> mapOf("name" to "Luke") else -> DefaultCacheResolver.resolveField(field, variables, parent, parentId) } } } val apolloClient = ApolloClient.Builder().serverUrl(serverUrl = "") .store( ApolloStore( normalizedCacheFactory = MemoryCacheFactory(), cacheResolver = resolver ) ) .build() val response = apolloClient.query(HeroNameQuery()).execute() assertEquals("Luke", response.data?.hero?.name) } }
mit
1e582c768f529e752276f65e71e48b6c
37.285714
139
0.742377
4.657971
false
true
false
false
stupacki/MultiFunctions
multi-functions/src/main/kotlin/io/multifunctions/MultiForEachIndexed.kt
1
3166
package io.multifunctions import io.multifunctions.models.Hepta import io.multifunctions.models.Hexa import io.multifunctions.models.Penta import io.multifunctions.models.Quad /** * Performs the given [action] on each element, providing sequential index with the element. * @param [action] function that takes the index of an element and the element itself * and performs the desired action on the element. */ public inline infix fun <A, B> Iterable<Pair<A?, B?>>.forEachIndexed(action: (Int, A?, B?) -> Unit) = forEachIndexed { index, (first, second) -> action(index, first, second) } /** * Performs the given [action] on each element, providing sequential index with the element. * @param [action] function that takes the index of an element and the element itself * and performs the desired action on the element. */ public inline infix fun <A, B, C> Iterable<Triple<A?, B?, C?>>.forEachIndexed(action: (Int, A?, B?, C?) -> Unit) = forEachIndexed { index, (first, second, third) -> action(index, first, second, third) } /** * Performs the given [action] on each element, providing sequential index with the element. * @param [action] function that takes the index of an element and the element itself * and performs the desired action on the element. */ public inline infix fun <A, B, C, D> Iterable<Quad<A?, B?, C?, D?>>.forEachIndexed(action: (Int, A?, B?, C?, D?) -> Unit) = forEachIndexed { index, (first, second, third, fourth) -> action(index, first, second, third, fourth) } /** * Performs the given [action] on each element, providing sequential index with the element. * @param [action] function that takes the index of an element and the element itself * and performs the desired action on the element. */ public inline infix fun <A, B, C, D, E> Iterable<Penta<A?, B?, C?, D?, E?>>.forEachIndexed(action: (Int, A?, B?, C?, D?, E?) -> Unit) = forEachIndexed { index, (first, second, third, fourth, fifth) -> action(index, first, second, third, fourth, fifth) } /** * Performs the given [action] on each element, providing sequential index with the element. * @param [action] function that takes the index of an element and the element itself * and performs the desired action on the element. */ public inline infix fun <A, B, C, D, E, F> Iterable<Hexa<A?, B?, C?, D?, E?, F?>>.forEachIndexed( action: (Int, A?, B?, C?, D?, E?, F?) -> Unit ) = forEachIndexed { index, (first, second, third, fourth, fifth, sixth) -> action(index, first, second, third, fourth, fifth, sixth) } /** * Performs the given [action] on each element, providing sequential index with the element. * @param [action] function that takes the index of an element and the element itself * and performs the desired action on the element. */ public inline infix fun <A, B, C, D, E, F, G> Iterable<Hepta<A?, B?, C?, D?, E?, F?, G?>>.forEachIndexed( action: (Int, A?, B?, C?, D?, E?, F?, G?) -> Unit ) = forEachIndexed { index, (first, second, third, fourth, fifth, sixth, seventh) -> action(index, first, second, third, fourth, fifth, sixth, seventh) }
apache-2.0
cfbf16bc062116495b23929ab27ef9f2
44.228571
135
0.674037
3.724706
false
false
false
false
vhromada/Catalog
core/src/main/kotlin/com/github/vhromada/catalog/controller/CheatController.kt
1
4095
package com.github.vhromada.catalog.controller import com.github.vhromada.catalog.entity.ChangeCheatRequest import com.github.vhromada.catalog.entity.Cheat import com.github.vhromada.catalog.facade.CheatFacade import org.springframework.http.HttpStatus import org.springframework.web.bind.annotation.DeleteMapping import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.PutMapping import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.ResponseStatus import org.springframework.web.bind.annotation.RestController /** * A class represents controller for cheats. * * @author Vladimir Hromada */ @RestController("cheatController") @RequestMapping("rest/games/{gameUuid}/cheats") class CheatController( /** * Facade for cheats */ private val facade: CheatFacade ) { /** * Returns cheat for game's UUID. * <br></br> * Validation errors: * * * Game doesn't exist in data storage * * @param gameUuid game's UUID * @return cheat for game's UUID */ @GetMapping fun find(@PathVariable("gameUuid") gameUuid: String): Cheat { return facade.find(game = gameUuid) } /** * Returns cheat. * <br></br> * Validation errors: * * * Game doesn't exist in data storage * * Cheat doesn't exist in data storage * * @param gameUuid game's UUID * @param cheatUuid cheat's UUID * @return cheat */ @GetMapping("{cheatUuid}") fun get( @PathVariable("gameUuid") gameUuid: String, @PathVariable("cheatUuid") cheatUuid: String ): Cheat { return facade.get(game = gameUuid, uuid = cheatUuid) } /** * Adds cheat. * <br></br> * Validation errors: * * * Cheat's data are null * * Cheat's data contain null value * * Action is null * * Action is empty string * * Description is null * * Description is empty string * * Game has already cheat in data storage * * Game doesn't exist in data storage * * @param gameUuid game's UUID * @param request request for changing game * @return add cheat */ @PutMapping @ResponseStatus(HttpStatus.CREATED) @Suppress("GrazieInspection") fun add( @PathVariable("gameUuid") gameUuid: String, @RequestBody request: ChangeCheatRequest ): Cheat { return facade.add(game = gameUuid, request = request) } /** * Updates cheat. * <br></br> * Validation errors: * * * Cheat's data are null * * Cheat's data contain null value * * Action is null * * Action is empty string * * Description is null * * Description is empty string * * Game doesn't exist in data storage * * Cheat doesn't exist in data storage * * @param gameUuid game's UUID * @param gameUuid cheat's UUID * @param request request for changing game * @return updated cheat */ @PostMapping("{cheatUuid}") fun update( @PathVariable("gameUuid") gameUuid: String, @PathVariable("cheatUuid") cheatUuid: String, @RequestBody request: ChangeCheatRequest ): Cheat { return facade.update(game = gameUuid, uuid = cheatUuid, request = request) } /** * Removes cheat. * <br></br> * Validation errors: * * * Game doesn't exist in data storage * * Cheat doesn't exist in data storage * * @param gameUuid game's UUID * @param gameUuid cheat's UUID */ @DeleteMapping("{cheatUuid}") @ResponseStatus(HttpStatus.NO_CONTENT) fun remove( @PathVariable("gameUuid") gameUuid: String, @PathVariable("cheatUuid") cheatUuid: String ) { facade.remove(game = gameUuid, uuid = cheatUuid) } }
mit
351faa184df2b416bcfa44c3b8d5da4c
27.838028
82
0.643223
4.337924
false
false
false
false
mikepenz/Android-Iconics
iconics-views/src/main/java/com/mikepenz/iconics/internal/CheckableIconBundle.kt
1
1387
/* * Copyright (c) 2019 Mike Penz * * 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.mikepenz.iconics.internal import android.content.Context import android.graphics.drawable.StateListDrawable import com.mikepenz.iconics.IconicsDrawable import com.mikepenz.iconics.utils.IconicsUtils /** * @author pa.gulko zTrap (07.07.2017) */ internal class CheckableIconBundle { var animateChanges: Boolean = false var checkedIcon: IconicsDrawable? = null var uncheckedIcon: IconicsDrawable? = null fun createIcons(ctx: Context) { checkedIcon = IconicsDrawable(ctx) uncheckedIcon = IconicsDrawable(ctx) } fun createStates(ctx: Context): StateListDrawable { return IconicsUtils.getCheckableIconStateList( ctx, uncheckedIcon, checkedIcon, animateChanges ) } }
apache-2.0
62d8bcaafedbebad6e994290d616ce95
29.822222
75
0.71305
4.403175
false
false
false
false
tiarebalbi/okhttp
okhttp/src/main/kotlin/okhttp3/internal/Util.kt
1
19646
/* * Copyright (C) 2012 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. */ @file:JvmName("Util") package okhttp3.internal import java.io.Closeable import java.io.FileNotFoundException import java.io.IOException import java.io.InterruptedIOException import java.net.InetSocketAddress import java.net.ServerSocket import java.net.Socket import java.net.SocketTimeoutException import java.nio.charset.Charset import java.nio.charset.StandardCharsets.UTF_16BE import java.nio.charset.StandardCharsets.UTF_16LE import java.nio.charset.StandardCharsets.UTF_8 import java.util.Collections import java.util.Comparator import java.util.LinkedHashMap import java.util.Locale import java.util.TimeZone import java.util.concurrent.ThreadFactory import java.util.concurrent.TimeUnit import kotlin.text.Charsets.UTF_32BE import kotlin.text.Charsets.UTF_32LE import okhttp3.EventListener import okhttp3.Headers import okhttp3.Headers.Companion.headersOf import okhttp3.HttpUrl import okhttp3.OkHttp import okhttp3.OkHttpClient import okhttp3.RequestBody.Companion.toRequestBody import okhttp3.Response import okhttp3.ResponseBody.Companion.toResponseBody import okhttp3.internal.http2.Header import okio.Buffer import okio.BufferedSink import okio.BufferedSource import okio.ByteString.Companion.decodeHex import okio.ExperimentalFileSystem import okio.FileSystem import okio.Options import okio.Path import okio.Source @JvmField val EMPTY_BYTE_ARRAY = ByteArray(0) @JvmField val EMPTY_HEADERS = headersOf() @JvmField val EMPTY_RESPONSE = EMPTY_BYTE_ARRAY.toResponseBody() @JvmField val EMPTY_REQUEST = EMPTY_BYTE_ARRAY.toRequestBody() /** Byte order marks. */ private val UNICODE_BOMS = Options.of( "efbbbf".decodeHex(), // UTF-8 "feff".decodeHex(), // UTF-16BE "fffe".decodeHex(), // UTF-16LE "0000ffff".decodeHex(), // UTF-32BE "ffff0000".decodeHex() // UTF-32LE ) /** GMT and UTC are equivalent for our purposes. */ @JvmField val UTC = TimeZone.getTimeZone("GMT")!! /** * Quick and dirty pattern to differentiate IP addresses from hostnames. This is an approximation * of Android's private InetAddress#isNumeric API. * * This matches IPv6 addresses as a hex string containing at least one colon, and possibly * including dots after the first colon. It matches IPv4 addresses as strings containing only * decimal digits and dots. This pattern matches strings like "a:.23" and "54" that are neither IP * addresses nor hostnames; they will be verified as IP addresses (which is a more strict * verification). */ private val VERIFY_AS_IP_ADDRESS = "([0-9a-fA-F]*:[0-9a-fA-F:.]*)|([\\d.]+)".toRegex() fun checkOffsetAndCount(arrayLength: Long, offset: Long, count: Long) { if (offset or count < 0L || offset > arrayLength || arrayLength - offset < count) { throw ArrayIndexOutOfBoundsException() } } fun threadFactory( name: String, daemon: Boolean ): ThreadFactory = ThreadFactory { runnable -> Thread(runnable, name).apply { isDaemon = daemon } } /** * Returns an array containing only elements found in this array and also in [other]. The returned * elements are in the same order as in this. */ fun Array<String>.intersect( other: Array<String>, comparator: Comparator<in String> ): Array<String> { val result = mutableListOf<String>() for (a in this) { for (b in other) { if (comparator.compare(a, b) == 0) { result.add(a) break } } } return result.toTypedArray() } /** * Returns true if there is an element in this array that is also in [other]. This method terminates * if any intersection is found. The sizes of both arguments are assumed to be so small, and the * likelihood of an intersection so great, that it is not worth the CPU cost of sorting or the * memory cost of hashing. */ fun Array<String>.hasIntersection( other: Array<String>?, comparator: Comparator<in String> ): Boolean { if (isEmpty() || other == null || other.isEmpty()) { return false } for (a in this) { for (b in other) { if (comparator.compare(a, b) == 0) { return true } } } return false } fun HttpUrl.toHostHeader(includeDefaultPort: Boolean = false): String { val host = if (":" in host) { "[$host]" } else { host } return if (includeDefaultPort || port != HttpUrl.defaultPort(scheme)) { "$host:$port" } else { host } } fun Array<String>.indexOf(value: String, comparator: Comparator<String>): Int = indexOfFirst { comparator.compare(it, value) == 0 } @Suppress("UNCHECKED_CAST") fun Array<String>.concat(value: String): Array<String> { val result = copyOf(size + 1) result[result.lastIndex] = value return result as Array<String> } /** * Increments [startIndex] until this string is not ASCII whitespace. Stops at [endIndex]. */ fun String.indexOfFirstNonAsciiWhitespace(startIndex: Int = 0, endIndex: Int = length): Int { for (i in startIndex until endIndex) { when (this[i]) { '\t', '\n', '\u000C', '\r', ' ' -> Unit else -> return i } } return endIndex } /** * Decrements [endIndex] until `input[endIndex - 1]` is not ASCII whitespace. Stops at [startIndex]. */ fun String.indexOfLastNonAsciiWhitespace(startIndex: Int = 0, endIndex: Int = length): Int { for (i in endIndex - 1 downTo startIndex) { when (this[i]) { '\t', '\n', '\u000C', '\r', ' ' -> Unit else -> return i + 1 } } return startIndex } /** Equivalent to `string.substring(startIndex, endIndex).trim()`. */ fun String.trimSubstring(startIndex: Int = 0, endIndex: Int = length): String { val start = indexOfFirstNonAsciiWhitespace(startIndex, endIndex) val end = indexOfLastNonAsciiWhitespace(start, endIndex) return substring(start, end) } /** * Returns the index of the first character in this string that contains a character in * [delimiters]. Returns endIndex if there is no such character. */ fun String.delimiterOffset(delimiters: String, startIndex: Int = 0, endIndex: Int = length): Int { for (i in startIndex until endIndex) { if (this[i] in delimiters) return i } return endIndex } /** * Returns the index of the first character in this string that is [delimiter]. Returns [endIndex] * if there is no such character. */ fun String.delimiterOffset(delimiter: Char, startIndex: Int = 0, endIndex: Int = length): Int { for (i in startIndex until endIndex) { if (this[i] == delimiter) return i } return endIndex } /** * Returns the index of the first character in this string that is either a control character (like * `\u0000` or `\n`) or a non-ASCII character. Returns -1 if this string has no such characters. */ fun String.indexOfControlOrNonAscii(): Int { for (i in 0 until length) { val c = this[i] if (c <= '\u001f' || c >= '\u007f') { return i } } return -1 } /** Returns true if this string is not a host name and might be an IP address. */ fun String.canParseAsIpAddress(): Boolean { return VERIFY_AS_IP_ADDRESS.matches(this) } /** Returns true if we should void putting this this header in an exception or toString(). */ fun isSensitiveHeader(name: String): Boolean { return name.equals("Authorization", ignoreCase = true) || name.equals("Cookie", ignoreCase = true) || name.equals("Proxy-Authorization", ignoreCase = true) || name.equals("Set-Cookie", ignoreCase = true) } /** Returns a [Locale.US] formatted [String]. */ fun format(format: String, vararg args: Any): String { return String.format(Locale.US, format, *args) } @Throws(IOException::class) fun BufferedSource.readBomAsCharset(default: Charset): Charset { return when (select(UNICODE_BOMS)) { 0 -> UTF_8 1 -> UTF_16BE 2 -> UTF_16LE 3 -> UTF_32BE 4 -> UTF_32LE -1 -> default else -> throw AssertionError() } } fun checkDuration(name: String, duration: Long, unit: TimeUnit?): Int { check(duration >= 0L) { "$name < 0" } check(unit != null) { "unit == null" } val millis = unit.toMillis(duration) require(millis <= Integer.MAX_VALUE) { "$name too large." } require(millis != 0L || duration <= 0L) { "$name too small." } return millis.toInt() } fun Char.parseHexDigit(): Int = when (this) { in '0'..'9' -> this - '0' in 'a'..'f' -> this - 'a' + 10 in 'A'..'F' -> this - 'A' + 10 else -> -1 } fun List<Header>.toHeaders(): Headers { val builder = Headers.Builder() for ((name, value) in this) { builder.addLenient(name.utf8(), value.utf8()) } return builder.build() } fun Headers.toHeaderList(): List<Header> = (0 until size).map { Header(name(it), value(it)) } /** Returns true if an HTTP request for this URL and [other] can reuse a connection. */ fun HttpUrl.canReuseConnectionFor(other: HttpUrl): Boolean = host == other.host && port == other.port && scheme == other.scheme fun EventListener.asFactory() = EventListener.Factory { this } infix fun Byte.and(mask: Int): Int = toInt() and mask infix fun Short.and(mask: Int): Int = toInt() and mask infix fun Int.and(mask: Long): Long = toLong() and mask @Throws(IOException::class) fun BufferedSink.writeMedium(medium: Int) { writeByte(medium.ushr(16) and 0xff) writeByte(medium.ushr(8) and 0xff) writeByte(medium and 0xff) } @Throws(IOException::class) fun BufferedSource.readMedium(): Int { return (readByte() and 0xff shl 16 or (readByte() and 0xff shl 8) or (readByte() and 0xff)) } /** * Reads until this is exhausted or the deadline has been reached. This is careful to not extend the * deadline if one exists already. */ @Throws(IOException::class) fun Source.skipAll(duration: Int, timeUnit: TimeUnit): Boolean { val nowNs = System.nanoTime() val originalDurationNs = if (timeout().hasDeadline()) { timeout().deadlineNanoTime() - nowNs } else { Long.MAX_VALUE } timeout().deadlineNanoTime(nowNs + minOf(originalDurationNs, timeUnit.toNanos(duration.toLong()))) return try { val skipBuffer = Buffer() while (read(skipBuffer, 8192) != -1L) { skipBuffer.clear() } true // Success! The source has been exhausted. } catch (_: InterruptedIOException) { false // We ran out of time before exhausting the source. } finally { if (originalDurationNs == Long.MAX_VALUE) { timeout().clearDeadline() } else { timeout().deadlineNanoTime(nowNs + originalDurationNs) } } } /** * Attempts to exhaust this, returning true if successful. This is useful when reading a complete * source is helpful, such as when doing so completes a cache body or frees a socket connection for * reuse. */ fun Source.discard(timeout: Int, timeUnit: TimeUnit): Boolean = try { this.skipAll(timeout, timeUnit) } catch (_: IOException) { false } fun Socket.peerName(): String { val address = remoteSocketAddress return if (address is InetSocketAddress) address.hostName else address.toString() } /** * Returns true if new reads and writes should be attempted on this. * * Unfortunately Java's networking APIs don't offer a good health check, so we go on our own by * attempting to read with a short timeout. If the fails immediately we know the socket is * unhealthy. * * @param source the source used to read bytes from the socket. */ fun Socket.isHealthy(source: BufferedSource): Boolean { return try { val readTimeout = soTimeout try { soTimeout = 1 !source.exhausted() } finally { soTimeout = readTimeout } } catch (_: SocketTimeoutException) { true // Read timed out; socket is good. } catch (_: IOException) { false // Couldn't read; socket is closed. } } /** Run [block] until it either throws an [IOException] or completes. */ inline fun ignoreIoExceptions(block: () -> Unit) { try { block() } catch (_: IOException) { } } inline fun threadName(name: String, block: () -> Unit) { val currentThread = Thread.currentThread() val oldName = currentThread.name currentThread.name = name try { block() } finally { currentThread.name = oldName } } fun Buffer.skipAll(b: Byte): Int { var count = 0 while (!exhausted() && this[0] == b) { count++ readByte() } return count } /** * Returns the index of the next non-whitespace character in this. Result is undefined if input * contains newline characters. */ fun String.indexOfNonWhitespace(startIndex: Int = 0): Int { for (i in startIndex until length) { val c = this[i] if (c != ' ' && c != '\t') { return i } } return length } /** Returns the Content-Length as reported by the response headers. */ fun Response.headersContentLength(): Long { return headers["Content-Length"]?.toLongOrDefault(-1L) ?: -1L } fun String.toLongOrDefault(defaultValue: Long): Long { return try { toLong() } catch (_: NumberFormatException) { defaultValue } } /** * Returns this as a non-negative integer, or 0 if it is negative, or [Int.MAX_VALUE] if it is too * large, or [defaultValue] if it cannot be parsed. */ fun String?.toNonNegativeInt(defaultValue: Int): Int { try { val value = this?.toLong() ?: return defaultValue return when { value > Int.MAX_VALUE -> Int.MAX_VALUE value < 0 -> 0 else -> value.toInt() } } catch (_: NumberFormatException) { return defaultValue } } /** Returns an immutable copy of this. */ fun <T> List<T>.toImmutableList(): List<T> { return Collections.unmodifiableList(toMutableList()) } /** Returns an immutable list containing [elements]. */ @SafeVarargs fun <T> immutableListOf(vararg elements: T): List<T> { return Collections.unmodifiableList(listOf(*elements.clone())) } /** Returns an immutable copy of this. */ fun <K, V> Map<K, V>.toImmutableMap(): Map<K, V> { return if (isEmpty()) { emptyMap() } else { Collections.unmodifiableMap(LinkedHashMap(this)) } } /** Closes this, ignoring any checked exceptions. */ fun Closeable.closeQuietly() { try { close() } catch (rethrown: RuntimeException) { throw rethrown } catch (_: Exception) { } } /** Closes this, ignoring any checked exceptions. */ fun Socket.closeQuietly() { try { close() } catch (e: AssertionError) { throw e } catch (rethrown: RuntimeException) { if (rethrown.message == "bio == null") { // Conscrypt in Android 10 and 11 may throw closing an SSLSocket. This is safe to ignore. // https://issuetracker.google.com/issues/177450597 return } throw rethrown } catch (_: Exception) { } } /** Closes this, ignoring any checked exceptions. */ fun ServerSocket.closeQuietly() { try { close() } catch (rethrown: RuntimeException) { throw rethrown } catch (_: Exception) { } } /** * Returns true if file streams can be manipulated independently of their paths. This is typically * true for systems like Mac, Unix, and Linux that use inodes in their file system interface. It is * typically false on Windows. * * If this returns false we won't permit simultaneous reads and writes. When writes commit we need * to delete the previous snapshots, and that won't succeed if the file is open. (We do permit * multiple simultaneous reads.) * * @param file a file in the directory to check. This file shouldn't already exist! */ @OptIn(ExperimentalFileSystem::class) fun FileSystem.isCivilized(file: Path): Boolean { sink(file).use { try { delete(file) return true } catch (_: IOException) { } } delete(file) return false } /** Delete file we expect but don't require to exist. */ @OptIn(ExperimentalFileSystem::class) fun FileSystem.deleteIfExists(path: Path) { try { delete(path) } catch (fnfe: FileNotFoundException) { return } } /** * Tolerant delete, try to clear as many files as possible even after a failure. */ @OptIn(ExperimentalFileSystem::class) fun FileSystem.deleteContents(directory: Path) { var exception: IOException? = null val files = try { list(directory) } catch (fnfe: FileNotFoundException) { return } for (file in files) { try { if (metadata(file).isDirectory) { deleteContents(file) } delete(file) } catch (ioe: IOException) { if (exception == null) { exception = ioe } } } if (exception != null) { throw exception } } fun Long.toHexString(): String = java.lang.Long.toHexString(this) fun Int.toHexString(): String = Integer.toHexString(this) @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN", "NOTHING_TO_INLINE") inline fun Any.wait() = (this as Object).wait() @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN", "NOTHING_TO_INLINE") inline fun Any.notify() = (this as Object).notify() @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN", "NOTHING_TO_INLINE") inline fun Any.notifyAll() = (this as Object).notifyAll() fun <T> readFieldOrNull(instance: Any, fieldType: Class<T>, fieldName: String): T? { var c: Class<*> = instance.javaClass while (c != Any::class.java) { try { val field = c.getDeclaredField(fieldName) field.isAccessible = true val value = field.get(instance) return if (!fieldType.isInstance(value)) null else fieldType.cast(value) } catch (_: NoSuchFieldException) { } c = c.superclass } // Didn't find the field we wanted. As a last gasp attempt, // try to find the value on a delegate. if (fieldName != "delegate") { val delegate = readFieldOrNull(instance, Any::class.java, "delegate") if (delegate != null) return readFieldOrNull(delegate, fieldType, fieldName) } return null } internal fun <E> MutableList<E>.addIfAbsent(element: E) { if (!contains(element)) add(element) } @JvmField val assertionsEnabled = OkHttpClient::class.java.desiredAssertionStatus() /** * Returns the string "OkHttp" unless the library has been shaded for inclusion in another library, * or obfuscated with tools like R8 or ProGuard. In such cases it'll return a longer string like * "com.example.shaded.okhttp3.OkHttp". In large applications it's possible to have multiple OkHttp * instances; this makes it clear which is which. */ @JvmField internal val okHttpName = OkHttpClient::class.java.name.removePrefix("okhttp3.").removeSuffix("Client") @Suppress("NOTHING_TO_INLINE") inline fun Any.assertThreadHoldsLock() { if (assertionsEnabled && !Thread.holdsLock(this)) { throw AssertionError("Thread ${Thread.currentThread().name} MUST hold lock on $this") } } @Suppress("NOTHING_TO_INLINE") inline fun Any.assertThreadDoesntHoldLock() { if (assertionsEnabled && Thread.holdsLock(this)) { throw AssertionError("Thread ${Thread.currentThread().name} MUST NOT hold lock on $this") } } fun Exception.withSuppressed(suppressed: List<Exception>): Throwable = apply { for (e in suppressed) addSuppressed(e) } inline fun <T> Iterable<T>.filterList(predicate: T.() -> Boolean): List<T> { var result: List<T> = emptyList() for (i in this) { if (predicate(i)) { if (result.isEmpty()) result = mutableListOf() (result as MutableList<T>).add(i) } } return result } const val userAgent = "okhttp/${OkHttp.VERSION}"
apache-2.0
5a2a0593612d36c32b4b850bf43f60cd
28.019202
100
0.688232
3.816239
false
false
false
false
Kotlin/kotlinx.coroutines
reactive/kotlinx-coroutines-rx3/src/RxAwait.kt
1
11956
/* * Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.coroutines.rx3 import io.reactivex.rxjava3.core.* import io.reactivex.rxjava3.disposables.Disposable import kotlinx.coroutines.CancellableContinuation import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Job import kotlinx.coroutines.suspendCancellableCoroutine import kotlin.coroutines.* // ------------------------ CompletableSource ------------------------ /** * Awaits for completion of this completable without blocking the thread. * Returns `Unit`, or throws the corresponding exception if this completable produces an error. * * This suspending function is cancellable. If the [Job] of the invoking coroutine is cancelled or completed while this * suspending function is suspended, this function immediately resumes with [CancellationException] and disposes of its * subscription. */ public suspend fun CompletableSource.await(): Unit = suspendCancellableCoroutine { cont -> subscribe(object : CompletableObserver { override fun onSubscribe(d: Disposable) { cont.disposeOnCancellation(d) } override fun onComplete() { cont.resume(Unit) } override fun onError(e: Throwable) { cont.resumeWithException(e) } }) } // ------------------------ MaybeSource ------------------------ /** * Awaits for completion of the [MaybeSource] without blocking the thread. * Returns the resulting value, or `null` if no value is produced, or throws the corresponding exception if this * [MaybeSource] produces an error. * * This suspending function is cancellable. * If the [Job] of the current coroutine is cancelled or completed while this suspending function is waiting, this * function immediately resumes with [CancellationException] and disposes of its subscription. */ @Suppress("UNCHECKED_CAST") public suspend fun <T> MaybeSource<T>.awaitSingleOrNull(): T? = suspendCancellableCoroutine { cont -> subscribe(object : MaybeObserver<T> { override fun onSubscribe(d: Disposable) { cont.disposeOnCancellation(d) } override fun onComplete() { cont.resume(null) } override fun onSuccess(t: T) { cont.resume(t) } override fun onError(error: Throwable) { cont.resumeWithException(error) } }) } /** * Awaits for completion of the [MaybeSource] without blocking the thread. * Returns the resulting value, or throws if either no value is produced or this [MaybeSource] produces an error. * * This suspending function is cancellable. * If the [Job] of the current coroutine is cancelled or completed while this suspending function is waiting, this * function immediately resumes with [CancellationException] and disposes of its subscription. * * @throws NoSuchElementException if no elements were produced by this [MaybeSource]. */ public suspend fun <T> MaybeSource<T>.awaitSingle(): T = awaitSingleOrNull() ?: throw NoSuchElementException() /** * Awaits for completion of the maybe without blocking a thread. * Returns the resulting value, null if no value was produced or throws the corresponding exception if this * maybe had produced error. * * This suspending function is cancellable. * If the [Job] of the current coroutine is cancelled or completed while this suspending function is waiting, this function * immediately resumes with [CancellationException]. * * ### Deprecation * * Deprecated in favor of [awaitSingleOrNull] in order to reflect that `null` can be returned to denote the absence of * a value, as opposed to throwing in such case. * * @suppress */ @Deprecated( message = "Deprecated in favor of awaitSingleOrNull()", level = DeprecationLevel.ERROR, replaceWith = ReplaceWith("this.awaitSingleOrNull()") ) // Warning since 1.5, error in 1.6, hidden in 1.7 public suspend fun <T> MaybeSource<T>.await(): T? = awaitSingleOrNull() /** * Awaits for completion of the maybe without blocking a thread. * Returns the resulting value, [default] if no value was produced or throws the corresponding exception if this * maybe had produced error. * * This suspending function is cancellable. * If the [Job] of the current coroutine is cancelled or completed while this suspending function is waiting, this function * immediately resumes with [CancellationException]. * * ### Deprecation * * Deprecated in favor of [awaitSingleOrNull] for naming consistency (see the deprecation of [MaybeSource.await] for * details). * * @suppress */ @Deprecated( message = "Deprecated in favor of awaitSingleOrNull()", level = DeprecationLevel.ERROR, replaceWith = ReplaceWith("this.awaitSingleOrNull() ?: default") ) // Warning since 1.5, error in 1.6, hidden in 1.7 public suspend fun <T> MaybeSource<T>.awaitOrDefault(default: T): T = awaitSingleOrNull() ?: default // ------------------------ SingleSource ------------------------ /** * Awaits for completion of the single value response without blocking the thread. * Returns the resulting value, or throws the corresponding exception if this response produces an error. * * This suspending function is cancellable. * If the [Job] of the current coroutine is cancelled or completed while the suspending function is waiting, this * function immediately disposes of its subscription and resumes with [CancellationException]. */ public suspend fun <T> SingleSource<T>.await(): T = suspendCancellableCoroutine { cont -> subscribe(object : SingleObserver<T> { override fun onSubscribe(d: Disposable) { cont.disposeOnCancellation(d) } override fun onSuccess(t: T) { cont.resume(t) } override fun onError(error: Throwable) { cont.resumeWithException(error) } }) } // ------------------------ ObservableSource ------------------------ /** * Awaits the first value from the given [Observable] without blocking the thread and returns the resulting value, or, * if the observable has produced an error, throws the corresponding exception. * * This suspending function is cancellable. * If the [Job] of the current coroutine is cancelled or completed while the suspending function is waiting, this * function immediately disposes of its subscription and resumes with [CancellationException]. * * @throws NoSuchElementException if the observable does not emit any value */ public suspend fun <T> ObservableSource<T>.awaitFirst(): T = awaitOne(Mode.FIRST) /** * Awaits the first value from the given [Observable], or returns the [default] value if none is emitted, without * blocking the thread, and returns the resulting value, or, if this observable has produced an error, throws the * corresponding exception. * * This suspending function is cancellable. * If the [Job] of the current coroutine is cancelled or completed while the suspending function is waiting, this * function immediately disposes of its subscription and resumes with [CancellationException]. */ public suspend fun <T> ObservableSource<T>.awaitFirstOrDefault(default: T): T = awaitOne(Mode.FIRST_OR_DEFAULT, default) /** * Awaits the first value from the given [Observable], or returns `null` if none is emitted, without blocking the * thread, and returns the resulting value, or, if this observable has produced an error, throws the corresponding * exception. * * This suspending function is cancellable. * If the [Job] of the current coroutine is cancelled or completed while the suspending function is waiting, this * function immediately disposes of its subscription and resumes with [CancellationException]. */ public suspend fun <T> ObservableSource<T>.awaitFirstOrNull(): T? = awaitOne(Mode.FIRST_OR_DEFAULT) /** * Awaits the first value from the given [Observable], or calls [defaultValue] to get a value if none is emitted, * without blocking the thread, and returns the resulting value, or, if this observable has produced an error, throws * the corresponding exception. * * This suspending function is cancellable. * If the [Job] of the current coroutine is cancelled or completed while the suspending function is waiting, this * function immediately disposes of its subscription and resumes with [CancellationException]. */ public suspend fun <T> ObservableSource<T>.awaitFirstOrElse(defaultValue: () -> T): T = awaitOne(Mode.FIRST_OR_DEFAULT) ?: defaultValue() /** * Awaits the last value from the given [Observable] without blocking the thread and * returns the resulting value, or, if this observable has produced an error, throws the corresponding exception. * * This suspending function is cancellable. * If the [Job] of the current coroutine is cancelled or completed while the suspending function is waiting, this * function immediately disposes of its subscription and resumes with [CancellationException]. * * @throws NoSuchElementException if the observable does not emit any value */ public suspend fun <T> ObservableSource<T>.awaitLast(): T = awaitOne(Mode.LAST) /** * Awaits the single value from the given observable without blocking the thread and returns the resulting value, or, * if this observable has produced an error, throws the corresponding exception. * * This suspending function is cancellable. * If the [Job] of the current coroutine is cancelled or completed while the suspending function is waiting, this * function immediately disposes of its subscription and resumes with [CancellationException]. * * @throws NoSuchElementException if the observable does not emit any value * @throws IllegalArgumentException if the observable emits more than one value */ public suspend fun <T> ObservableSource<T>.awaitSingle(): T = awaitOne(Mode.SINGLE) // ------------------------ private ------------------------ internal fun CancellableContinuation<*>.disposeOnCancellation(d: Disposable) = invokeOnCancellation { d.dispose() } private enum class Mode(val s: String) { FIRST("awaitFirst"), FIRST_OR_DEFAULT("awaitFirstOrDefault"), LAST("awaitLast"), SINGLE("awaitSingle"); override fun toString(): String = s } private suspend fun <T> ObservableSource<T>.awaitOne( mode: Mode, default: T? = null ): T = suspendCancellableCoroutine { cont -> subscribe(object : Observer<T> { private lateinit var subscription: Disposable private var value: T? = null private var seenValue = false override fun onSubscribe(sub: Disposable) { subscription = sub cont.invokeOnCancellation { sub.dispose() } } override fun onNext(t: T) { when (mode) { Mode.FIRST, Mode.FIRST_OR_DEFAULT -> { if (!seenValue) { seenValue = true cont.resume(t) subscription.dispose() } } Mode.LAST, Mode.SINGLE -> { if (mode == Mode.SINGLE && seenValue) { if (cont.isActive) cont.resumeWithException(IllegalArgumentException("More than one onNext value for $mode")) subscription.dispose() } else { value = t seenValue = true } } } } @Suppress("UNCHECKED_CAST") override fun onComplete() { if (seenValue) { if (cont.isActive) cont.resume(value as T) return } when { mode == Mode.FIRST_OR_DEFAULT -> { cont.resume(default as T) } cont.isActive -> { cont.resumeWithException(NoSuchElementException("No value received via onNext for $mode")) } } } override fun onError(e: Throwable) { cont.resumeWithException(e) } }) }
apache-2.0
35e68aa6e12dbd92dfdb2884f80a557a
42.794872
123
0.693794
4.92219
false
false
false
false
Kotlin/kotlinx.coroutines
kotlinx-coroutines-core/jvm/test/flow/FlatMapStressTest.kt
1
3159
/* * Copyright 2016-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.coroutines.flow import kotlinx.coroutines.* import kotlinx.coroutines.flow.internal.* import kotlinx.coroutines.scheduling.* import org.junit.Assume.* import org.junit.Test import java.util.concurrent.atomic.* import kotlin.test.* class FlatMapStressTest : TestBase() { private val iterations = 2000 * stressTestMultiplier private val expectedSum = iterations.toLong() * (iterations + 1) / 2 @Test fun testConcurrencyLevel() = runTest { withContext(Dispatchers.Default) { testConcurrencyLevel(2) } } @Test fun testConcurrencyLevel2() = runTest { withContext(Dispatchers.Default) { testConcurrencyLevel(3) } } @Test fun testBufferSize() = runTest { val bufferSize = 5 withContext(Dispatchers.Default) { val inFlightElements = AtomicLong(0L) var result = 0L (1..iterations step 4).asFlow().flatMapMerge { value -> unsafeFlow { repeat(4) { emit(value + it) inFlightElements.incrementAndGet() } } }.buffer(bufferSize).collect { value -> val inFlight = inFlightElements.get() assertTrue(inFlight <= bufferSize + 1, "Expected less in flight elements than ${bufferSize + 1}, but had $inFlight") inFlightElements.decrementAndGet() result += value } assertEquals(0, inFlightElements.get()) assertEquals(expectedSum, result) } } @Test fun testDelivery() = runTest { withContext(Dispatchers.Default) { val result = (1L..iterations step 4).asFlow().flatMapMerge { value -> unsafeFlow { repeat(4) { emit(value + it) } } }.longSum() assertEquals(expectedSum, result) } } @Test fun testIndependentShortBursts() = runTest { withContext(Dispatchers.Default) { repeat(iterations) { val result = (1L..4L).asFlow().flatMapMerge { value -> unsafeFlow { emit(value) emit(value) } }.longSum() assertEquals(20, result) } } } private suspend fun testConcurrencyLevel(maxConcurrency: Int) { assumeTrue(maxConcurrency <= CORE_POOL_SIZE) val concurrency = AtomicLong() val result = (1L..iterations).asFlow().flatMapMerge(concurrency = maxConcurrency) { value -> unsafeFlow { val current = concurrency.incrementAndGet() assertTrue(current in 1..maxConcurrency) emit(value) concurrency.decrementAndGet() } }.longSum() assertEquals(0, concurrency.get()) assertEquals(expectedSum, result) } }
apache-2.0
6bf816d1be6cad426c504311e4578f8b
29.970588
102
0.549541
5.170213
false
true
false
false
code-helix/slatekit
src/apps/kotlin/slatekit-examples/src/main/kotlin/slatekit/examples/Example_DateTime.kt
1
4510
/** * <slate_header> * author: Kishore Reddy * url: www.github.com/code-helix/slatekit * copyright: 2016 Kishore Reddy * license: www.github.com/code-helix/slatekit/blob/master/LICENSE.md * desc: A tool-kit, utility library and server-backend * usage: Please refer to license on github for more info. * </slate_header> */ package slatekit.examples //<doc:import_required> import slatekit.common.DateTime import slatekit.common.DateTimes //</doc:import_required> //<doc:import_examples> import slatekit.results.Try import slatekit.results.Success //import java.time.ZoneId import org.threeten.bp.* import slatekit.common.ext.* //</doc:import_examples> class Example_DateTime : Command("datetime") { override fun execute(request: CommandRequest) : Try<Any> { //<doc:examples> // // NOTE: // When working with new Java 8 Date/Time, which is a significant // improvement over the older mutable Java Date/Time models, // there is still some "cognitive overhead" ( IMHO ) in mentally // managing the different LocalDateTime, ZonedDateTime and conversion // to and from local/zoned functionality // // DESIGN: // This DateTime is a unified DateTime for both LocalDateTime and ZonedDateime // that wraps uses a ZonedDateTime internally ( defaulted to local timezone ) // and is used for representing a DateTime for either Local and/or other Zones. // This makes the Java 8 datetime/zones a bit simpler & concise while // essentially adding syntactic sugar using Kotlin operators and extension methods // // IMPORTANT: // This does NOT change the functionality of the Java 8 classes at all. // It is simply "syntactic sugar" for using the classes. // Case 1. Get datetime now, either locally, at utc and other zones // These will return a DateTime that wraps a ZonedDateTime. println( DateTime.now() ) println( DateTimes.nowUtc() ) println( DateTimes.nowAt("America/New_York")) println( DateTimes.nowAt("Europe/Athens")) println( DateTimes.nowAt(ZoneId.of("Europe/Athens"))) // Case 2: Build datetime explicitly println( DateTimes.of(2017, 7, 10)) println( DateTimes.of(2017, 7, 10, 11, 30, 0)) println( DateTimes.of(2017, 7, 10, 11, 30, 0, 0)) println( DateTime.of(2017, 7, 10, 11, 30, 0, 0, ZoneId.of("America/New_York"))) // Case 3. Get datetime fields val dt = DateTime.now() println( "year : " + dt.year ) println( "month : " + dt.month ) println( "day : " + dt.dayOfMonth) println( "hour : " + dt.hour ) println( "mins : " + dt.minute ) println( "secs : " + dt.second ) println( "nano : " + dt.nano ) println( "zone : " + dt.zone.id ) // Case 4: Conversion from now( local ) to utc, specific zone, // LocalDate, LocalTime, and LocalDateTime val now = DateTime.now() println( now.date() ) println( now.time() ) println( now.local() ) println( now.atUtc() ) println( now.atUtcLocal() ) println( now.atZone("Europe/Athens") ) // Case 5: Idiomatic use of Kotlin operators and extension methods // This uses the extensions from slatekit.common.ext.IntExtensions val later = DateTime.now() + 3.minutes println( DateTime.now() + 3.days ) println( DateTime.now() - 3.minutes ) println( DateTime.now() - 3.months ) // Case 6. Add time ( just like Java 8 ) val dt1 = DateTime.now() println( dt1.plusYears (1).toString() ) println( dt1.plusMonths (1).toString() ) println( dt1.plusDays (1).toString() ) println( dt1.plusHours (1).toString() ) println( dt1.plusMinutes(1).toString() ) println( dt1.plusSeconds(1).toString() ) // Case 7. Compare println( dt1 > dt1.plusYears (1) ) println( dt1 >= dt1.plusMonths (1) ) println( dt1 >= dt1.plusDays (1) ) println( dt1 < dt1.plusHours (1) ) println( dt1 <= dt1.plusMinutes(1) ) println( dt1 <= dt1.plusSeconds(1) ) // Case 8. Get duration (hours,mins,seconds) or period(days,months,years) println( dt1.plusSeconds(2).durationFrom( dt1 ) ) println( dt1.plusMinutes(2).durationFrom( dt1 ) ) println( dt1.plusHours(2).durationFrom( dt1 ) ) println( dt1.plusDays(2).periodFrom( dt1 ) ) println( dt1.plusMonths(2).periodFrom( dt1 ) ) println( dt1.plusYears(2).periodFrom( dt1 ) ) //</doc:examples> return Success("") } }
apache-2.0
ec6869cc15f16a682432e4cb94622ecd
33.166667
86
0.647007
3.642973
false
false
false
false
rodm/teamcity-gradle-init-scripts-plugin
agent/src/main/kotlin/com/github/rodm/teamcity/gradle/scripts/agent/GradleInitScriptsFeature.kt
1
3957
/* * Copyright 2017 Rod MacKenzie. * * 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.github.rodm.teamcity.gradle.scripts.agent import com.github.rodm.teamcity.gradle.scripts.GradleInitScriptsPlugin.FEATURE_TYPE import com.github.rodm.teamcity.gradle.scripts.GradleInitScriptsPlugin.INIT_SCRIPT_CONTENT import com.github.rodm.teamcity.gradle.scripts.GradleInitScriptsPlugin.INIT_SCRIPT_CONTENT_PARAMETER import com.github.rodm.teamcity.gradle.scripts.GradleInitScriptsPlugin.INIT_SCRIPT_NAME import com.github.rodm.teamcity.gradle.scripts.GradleInitScriptsPlugin.INIT_SCRIPT_NAME_PARAMETER import jetbrains.buildServer.agent.* import jetbrains.buildServer.log.Loggers.AGENT_CATEGORY import jetbrains.buildServer.util.EventDispatcher import jetbrains.buildServer.util.FileUtil import org.apache.log4j.Logger import java.io.File import java.io.IOException import java.lang.RuntimeException open class GradleInitScriptsFeature(eventDispatcher: EventDispatcher<AgentLifeCycleListener>) : AgentLifeCycleAdapter() { private val LOG = Logger.getLogger(AGENT_CATEGORY + ".GradleInitScriptsFeature") private val GRADLE_CMD_PARAMS = "ui.gradleRunner.additional.gradle.cmd.params" private val initScriptFiles = mutableListOf<File>() init { eventDispatcher.addListener(this) } override fun beforeRunnerStart(runner: BuildRunnerContext) { val runnerParameters = runner.runnerParameters val initScriptName = runnerParameters[INIT_SCRIPT_NAME_PARAMETER] if (initScriptName != null) { addInitScriptParameters(runner, initScriptName, runnerParameters[INIT_SCRIPT_CONTENT_PARAMETER]) } if (hasGradleInitScriptFeature(runner)) { addInitScriptParameters(runner, runnerParameters[INIT_SCRIPT_NAME], runnerParameters[INIT_SCRIPT_CONTENT]) } } private fun addInitScriptParameters(runner: BuildRunnerContext, name: String?, content: String?) { if (name != null) { if (content == null) { throw RuntimeException("Runner is configured to use init script '$name', but no content was found. Please check runner settings.") } try { val initScriptFile = FileUtil.createTempFile(getBuildTempDirectory(runner), "init_", ".gradle", true) if (initScriptFile != null) { FileUtil.writeFile(initScriptFile, content, "UTF-8") initScriptFiles.add(initScriptFile) val params = runner.runnerParameters.getOrDefault(GRADLE_CMD_PARAMS, "") val initScriptParams = "--init-script " + initScriptFile.absolutePath runner.addRunnerParameter(GRADLE_CMD_PARAMS, initScriptParams + " " + params) } } catch (e: IOException) { LOG.info("Failed to write init script: " + e.message) } } } override fun runnerFinished(runner: BuildRunnerContext, status: BuildFinishedStatus) { initScriptFiles.forEach { file -> FileUtil.delete(file) } initScriptFiles.clear() } open fun hasGradleInitScriptFeature(context: BuildRunnerContext) : Boolean { return !context.build.getBuildFeaturesOfType(FEATURE_TYPE).isEmpty() } open fun getBuildTempDirectory(context: BuildRunnerContext) : File { return context.build.getBuildTempDirectory() } }
apache-2.0
6eb557707fc182e758ed1af13ff92fd2
41.548387
146
0.710387
4.699525
false
false
false
false
code-helix/slatekit
src/lib/kotlin/slatekit-data/src/main/kotlin/slatekit/data/sql/Types.kt
1
3872
package slatekit.data.syntax import slatekit.common.Types import slatekit.common.data.DataType import slatekit.common.data.DataTypeMap /** * Maps the DataTypes * Java types to MySql * https://dev.mysql.com/doc/connector-j/5.1/en/connector-j-reference-type-conversions.html */ open class Types { /** * BOOL */ open val boolType = DataTypeMap(DataType.DTBool, "BIT", Types.JBoolClass) /** * STRINGS */ open val charType = DataTypeMap(DataType.DTChar, "CHAR", Types.JCharClass) open val stringType = DataTypeMap(DataType.DTString, "NVARCHAR", Types.JStringClass) open val textType = DataTypeMap(DataType.DTText, "TEXT", Types.JStringClass) /** * UUID */ open val uuidType = DataTypeMap(DataType.DTUUID, "NVARCHAR", Types.JStringClass) open val ulidType = DataTypeMap(DataType.DTULID, "NVARCHAR", Types.JStringClass) open val upidType = DataTypeMap(DataType.DTUPID, "NVARCHAR", Types.JStringClass) /** * NUMBERS * https://dev.mysql.com/doc/refman/8.0/en/integer-types.html * Type Storage (Bytes) Minimum Value Signed Minimum Value Unsigned Maximum Value Signed Maximum Value Unsigned * TINYINT 1 -128 0 127 255 * SMALLINT 2 -32768 0 32767 65535 * MEDIUMINT 3 -8388608 0 8388607 16777215 * INT 4 -2147483648 0 2147483647 4294967295 * BIGINT 8 -263 0 263-1 264-1 */ open val shortType = DataTypeMap(DataType.DTShort, "SMALLINT", Types.JShortClass) open val intType = DataTypeMap(DataType.DTInt, "INTEGER", Types.JIntClass) open val longType = DataTypeMap(DataType.DTLong, "BIGINT", Types.JLongClass) open val floatType = DataTypeMap(DataType.DTFloat, "FLOAT", Types.JFloatClass) open val doubleType = DataTypeMap(DataType.DTDouble, "DOUBLE", Types.JDoubleClass) //open val decimalType = DataTypeMap(DataType.DbDecimal, "DECIMAL", Types.JDecimalClass) /** * DATES / TIMES */ open val localdateType = DataTypeMap(DataType.DTLocalDate, "DATE", Types.JLocalDateClass) open val localtimeType = DataTypeMap(DataType.DTLocalTime, "TIME", Types.JLocalTimeClass) open val localDateTimeType = DataTypeMap(DataType.DTLocalDateTime, "DATETIME", Types.JLocalDateTimeClass) open val zonedDateTimeType = DataTypeMap(DataType.DTZonedDateTime, "DATETIME", Types.JZonedDateTimeClass) open val dateTimeType = DataTypeMap(DataType.DTDateTime, "DATETIME", Types.JDateTimeClass) open val instantType = DataTypeMap(DataType.DTInstant, "INSTANT", Types.JInstantClass) open val lookup = mapOf( boolType.metaType to boolType, charType.metaType to charType, stringType.metaType to stringType, textType.metaType to textType, uuidType.metaType to uuidType, shortType.metaType to shortType, intType.metaType to intType, longType.metaType to longType, floatType.metaType to floatType, doubleType.metaType to doubleType, //decimalType.metaType to decimalType, localdateType.metaType to localdateType, localtimeType.metaType to localtimeType, localDateTimeType.metaType to localDateTimeType, zonedDateTimeType.metaType to zonedDateTimeType, dateTimeType.metaType to dateTimeType, instantType.metaType to instantType, uuidType.metaType to uuidType, ulidType.metaType to ulidType, upidType.metaType to upidType ) }
apache-2.0
9bef21d8b12084da3d18b6318d209aed
45.095238
121
0.635331
4.533958
false
false
false
false
moko256/twicalico
app/src/main/java/com/github/moko256/twitlatte/TrendsActivity.kt
1
2855
/* * Copyright 2015-2019 The twitlatte authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.moko256.twitlatte import android.os.Bundle import android.view.Menu import android.view.View import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.SearchView import com.github.moko256.latte.client.twitter.CLIENT_TYPE_TWITTER /** * Created by moko256 on 2017/07/05. * * @author moko256 */ class TrendsActivity : AppCompatActivity(), BaseListFragment.GetViewForSnackBar { public override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) supportActionBar?.let { it.title = intent.getStringExtra("query") it.setDisplayHomeAsUpEnabled(true) it.setHomeAsUpIndicator(R.drawable.ic_back_white_24dp) } if (savedInstanceState == null && getClient()?.accessToken?.clientType == CLIENT_TYPE_TWITTER) { supportFragmentManager .beginTransaction() .add(android.R.id.content, TrendsFragment()) .commit() } } override fun getViewForSnackBar(): View { return findViewById(android.R.id.content) } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.activity_search_toolbar, menu) val searchMenu = menu.findItem(R.id.action_search) val searchView = searchMenu.actionView as SearchView searchMenu.expandActionView() searchView.onActionViewExpanded() searchView.clearFocus() searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextSubmit(searchWord: String): Boolean { searchView.clearFocus() searchView.setQuery("", false) startActivity(SearchResultActivity.getIntent(this@TrendsActivity, searchWord)) return false } override fun onQueryTextChange(newText: String): Boolean { return false } }) searchView.setOnCloseListener { finish() false } return super.onCreateOptionsMenu(menu) } override fun onSupportNavigateUp(): Boolean { finish() return true } }
apache-2.0
45bd0ea056261ef1137972c5fea1f35d
32.209302
104
0.6662
5.017575
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/jvmStatic/closure.kt
2
926
// TODO: muted automatically, investigate should it be ran for JS or not // IGNORE_BACKEND: JS, NATIVE // WITH_RUNTIME object A { val b: String = "OK" @JvmStatic val c: String = "OK" @JvmStatic fun test1() : String { return {b}() } @JvmStatic fun test2() : String { return {test1()}() } fun test3(): String { return {"1".test5()}() } @JvmStatic fun test4(): String { return {"1".test5()}() } @JvmStatic fun String.test5() : String { return {this + b}() } fun test6(): String { return {c}() } } fun box(): String { if (A.test1() != "OK") return "fail 1" if (A.test2() != "OK") return "fail 2" if (A.test3() != "1OK") return "fail 3" if (A.test4() != "1OK") return "fail 4" if (with(A) {"1".test5()} != "1OK") return "fail 5" if (A.test6() != "OK") return "fail 6" return "OK" }
apache-2.0
fb8feae0c291975cb75f4d5e25baa1ff
17.156863
72
0.5054
3.182131
false
true
false
false
vimeo/vimeo-networking-java
models/src/main/java/com/vimeo/networking2/GroupFollowInteraction.kt
1
1191
@file:JvmName("GroupFollowInteractionUtils") package com.vimeo.networking2 import com.squareup.moshi.Json import com.squareup.moshi.JsonClass import com.vimeo.networking2.common.UpdatableInteraction import com.vimeo.networking2.enums.FollowType import com.vimeo.networking2.enums.asEnum import java.util.Date /** * Follow a group interaction. * * @param rawType Whether the authenticated user is a moderator or subscriber. See [GroupFollowInteraction.type]. * @param title The user's title, or the null value if not applicable. */ @JsonClass(generateAdapter = true) data class GroupFollowInteraction( @Json(name = "added") override val added: Boolean? = null, @Json(name = "added_time") override val addedTime: Date? = null, @Json(name = "options") override val options: List<String>? = null, @Json(name = "uri") override val uri: String? = null, @Json(name = "type") val rawType: String? = null, @Json(name = "title") val title: String? = null ) : UpdatableInteraction /** * @see GroupFollowInteraction.rawType * @see FollowType */ val GroupFollowInteraction.type: FollowType get() = rawType.asEnum(FollowType.UNKNOWN)
mit
b489709e18d19fce42182aef8abb39fb
24.891304
113
0.721243
3.792994
false
false
false
false
Nunnery/MythicDrops
src/main/kotlin/com/tealcube/minecraft/bukkit/mythicdrops/api/choices/WeightedChoice.kt
1
3169
/* * This file is part of MythicDrops, licensed under the MIT License. * * Copyright (C) 2019 Richard Harrah * * Permission is hereby granted, free of charge, * to any person obtaining a copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS * OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.tealcube.minecraft.bukkit.mythicdrops.api.choices import com.tealcube.minecraft.bukkit.mythicdrops.api.weight.Weighted import com.tealcube.minecraft.bukkit.mythicdrops.safeRandom import io.pixeloutlaw.minecraft.spigot.mythicdrops.isZero /** * Simple utility for making weighted choices. */ class WeightedChoice<T : Weighted> : Choice<T>() { companion object { /** * Constructs a [WeightedChoice] for the given [option]. * * @param option Option(s) for choice. * @return constructed choice */ @JvmStatic fun <T : Weighted> between(vararg option: T): WeightedChoice<T> = between(option.asIterable()) /** * Constructs a [WeightedChoice] for the given [options]. * * @param option Option(s) for choice. * @return constructed choice */ @JvmStatic fun <T : Weighted> between(options: Iterable<T>): WeightedChoice<T> = WeightedChoice<T>().also { it.addOptions(options) } } override fun choose(): T? { return choose { true } } /** * Chooses one of the available options and returns it based on weight. * * @param block Extra block to execute to determine if option is selectable * @return chosen option or null if one cannot be chosen */ fun choose(block: (T) -> Boolean): T? { val selectableOptions = options.filter(block).filter { !it.weight.isZero() } val totalWeight: Double = selectableOptions.fold(0.0) { sum, element -> sum + element.weight } val chosenWeight = (0.0..totalWeight).safeRandom() val shuffledOptions = selectableOptions.shuffled() var currentWeight = 0.0 for (option in shuffledOptions) { currentWeight += option.weight if (currentWeight >= chosenWeight) { return option } } return null } }
mit
f11dfc01a999b5e65148ea299f793f5f
37.646341
105
0.667087
4.527143
false
false
false
false
exponent/exponent
android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/host/exp/exponent/modules/api/components/gesturehandler/react/RNGestureHandlerStateChangeEvent.kt
2
2241
package abi44_0_0.host.exp.exponent.modules.api.components.gesturehandler.react import androidx.core.util.Pools import abi44_0_0.com.facebook.react.bridge.Arguments import abi44_0_0.com.facebook.react.bridge.WritableMap import abi44_0_0.com.facebook.react.uimanager.events.Event import abi44_0_0.com.facebook.react.uimanager.events.RCTEventEmitter import abi44_0_0.host.exp.exponent.modules.api.components.gesturehandler.GestureHandler class RNGestureHandlerStateChangeEvent private constructor() : Event<RNGestureHandlerStateChangeEvent>() { private var extraData: WritableMap? = null private fun <T : GestureHandler<T>> init( handler: T, newState: Int, oldState: Int, dataExtractor: RNGestureHandlerEventDataExtractor<T>?, ) { super.init(handler.view!!.id) extraData = createEventData(handler, dataExtractor, newState, oldState) } override fun onDispose() { extraData = null EVENTS_POOL.release(this) } override fun getEventName() = EVENT_NAME // TODO: coalescing override fun canCoalesce() = false // TODO: coalescing override fun getCoalescingKey(): Short = 0 override fun dispatch(rctEventEmitter: RCTEventEmitter) { rctEventEmitter.receiveEvent(viewTag, EVENT_NAME, extraData) } companion object { const val EVENT_NAME = "onGestureHandlerStateChange" private const val TOUCH_EVENTS_POOL_SIZE = 7 // magic private val EVENTS_POOL = Pools.SynchronizedPool<RNGestureHandlerStateChangeEvent>(TOUCH_EVENTS_POOL_SIZE) fun <T : GestureHandler<T>> obtain( handler: T, newState: Int, oldState: Int, dataExtractor: RNGestureHandlerEventDataExtractor<T>?, ): RNGestureHandlerStateChangeEvent = (EVENTS_POOL.acquire() ?: RNGestureHandlerStateChangeEvent()).apply { init(handler, newState, oldState, dataExtractor) } fun <T : GestureHandler<T>> createEventData( handler: T, dataExtractor: RNGestureHandlerEventDataExtractor<T>?, newState: Int, oldState: Int, ): WritableMap = Arguments.createMap().apply { dataExtractor?.extractEventData(handler, this) putInt("handlerTag", handler.tag) putInt("state", newState) putInt("oldState", oldState) } } }
bsd-3-clause
d787155fa2f4e16e1a8e903a6f56d868
32.954545
110
0.728693
4.368421
false
false
false
false
smmribeiro/intellij-community
plugins/markdown/core/src/org/intellij/plugins/markdown/ui/preview/jcef/HtmlExporter.kt
1
3992
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.intellij.plugins.markdown.ui.preview.jcef import com.intellij.openapi.project.Project import com.intellij.openapi.util.io.FileUtil import com.intellij.util.Base64 import com.intellij.util.io.HttpRequests import org.intellij.plugins.markdown.MarkdownBundle import org.intellij.plugins.markdown.MarkdownNotifier import org.jsoup.Jsoup import org.jsoup.nodes.Element import org.jsoup.select.Elements import java.io.File import java.io.IOException data class HtmlResourceSavingSettings(val isSaved: Boolean, val resourceDir: String) class HtmlExporter(htmlSource: String, private val savingSettings: HtmlResourceSavingSettings, private val project: Project, private val targetFile: File) { private val document = Jsoup.parse(htmlSource) fun export() { with(document.head()) { getElementsByTag("script").remove() getElementsByTag("meta").remove() appendInlineStylesContent(select("link[rel=\"stylesheet\"]")) } val images = document.body().getElementsByTag("img") if (savingSettings.isSaved) { saveImages(images) } else { inlineImagesContent(images) } targetFile.writeText(document.html()) } private fun appendInlineStylesContent(styles: Elements) { val inlinedStyles = styles.mapNotNull { val content = getStyleContent(it) ?: return@mapNotNull null Element("style").text(content) } styles.remove() inlinedStyles.forEach { if (it.hasText()) { document.head().appendChild(it) } } } private fun getStyleContent(linkElement: Element): String? { val url = linkElement.attr("href") ?: return null return try { HttpRequests.request(url).readString() } catch (exception: IOException) { val name = File(url).name MarkdownNotifier.showWarningNotification(project, MarkdownBundle.message("markdown.export.style.not.found.msg", name)) null } } private fun inlineImagesContent(images: Elements) { images.forEach { val imgSrc = getImgUriWithProtocol(it.attr("src")) val content = getResource(imgSrc) if (content != null && imgSrc.isNotEmpty()) { it.attr("src", encodeImage(imgSrc, content)) } } } private fun encodeImage(url: String, bytes: ByteArray): String { val extension = FileUtil.getExtension(url, "png") val contentType = if (extension == "svg") "svg+xml" else extension return "data:image/$contentType;base64, ${Base64.encode(bytes)}" } private fun saveImages(images: Elements) { images.forEach { val imgSrc = it.attr("src") val imgUri = getImgUriWithProtocol(imgSrc) val content = getResource(imgUri) if (content != null && imgSrc.isNotEmpty()) { val savedImgFile = getSavedImageFile(savingSettings.resourceDir, imgSrc) FileUtil.createIfDoesntExist(savedImgFile) savedImgFile.writeBytes(content) val relativeImgPath = getRelativeImagePath(savingSettings.resourceDir) it.attr("src", FileUtil.join(relativeImgPath, File(imgSrc).name)) } } } private fun getImgUriWithProtocol(imgSrc: String): String { return if (imgSrc.startsWith("file:")) imgSrc else File(imgSrc).toURI().toString() } private fun getResource(url: String): ByteArray? = try { HttpRequests.request(url).readBytes(null) } catch (exception: IOException) { val name = File(url).name MarkdownNotifier.showWarningNotification(project, MarkdownBundle.message("markdown.export.images.not.found.msg", name)) null } private fun getSavedImageFile(resDir: String, imgUrl: String) = File(FileUtil.join(resDir, File(imgUrl).name)) private fun getRelativeImagePath(resDir: String) = FileUtil.getRelativePath(targetFile.parentFile, File(resDir)) }
apache-2.0
d6bd33a1f93c094b33aec766729b551c
31.721311
140
0.697395
4.233298
false
false
false
false
smmribeiro/intellij-community
plugins/github/src/org/jetbrains/plugins/github/pullrequest/action/GHPRUpdateTimelineAction.kt
12
1135
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.pullrequest.action import com.intellij.icons.AllIcons import com.intellij.ide.actions.RefreshAction import com.intellij.openapi.actionSystem.AnActionEvent import org.jetbrains.plugins.github.i18n.GithubBundle class GHPRUpdateTimelineAction : RefreshAction({ GithubBundle.message("pull.request.timeline.refresh.action") }, { GithubBundle.message("pull.request.timeline.refresh.action.description") }, AllIcons.Actions.Refresh) { override fun update(e: AnActionEvent) { val dataProvider = e.getData(GHPRActionKeys.PULL_REQUEST_DATA_PROVIDER) e.presentation.isEnabled = dataProvider?.timelineLoader != null } override fun actionPerformed(e: AnActionEvent) { val dataProvider = e.getRequiredData(GHPRActionKeys.PULL_REQUEST_DATA_PROVIDER) dataProvider.detailsData.reloadDetails() if (dataProvider.timelineLoader?.loadMore(true) != null) dataProvider.reviewData.resetReviewThreads() } }
apache-2.0
9af4f0367e89e47bc2eeb7b489df6197
44.44
140
0.767401
4.416342
false
false
false
false
jotomo/AndroidAPS
app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopSuspend.kt
1
2653
package info.nightscout.androidaps.plugins.general.automation.actions import android.widget.LinearLayout import androidx.annotation.DrawableRes import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.data.PumpEnactResult import info.nightscout.androidaps.events.EventRefreshOverview import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.general.automation.elements.InputDuration import info.nightscout.androidaps.plugins.general.automation.elements.LabelWithElement import info.nightscout.androidaps.plugins.general.automation.elements.LayoutBuilder import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.utils.JsonHelper import info.nightscout.androidaps.utils.resources.ResourceHelper import org.json.JSONObject import javax.inject.Inject class ActionLoopSuspend(injector: HasAndroidInjector) : Action(injector) { @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var loopPlugin: LoopPlugin @Inject lateinit var rxBus: RxBusWrapper var minutes = InputDuration(injector, 0, InputDuration.TimeUnit.MINUTES) override fun friendlyName(): Int = R.string.suspendloop override fun shortDescription(): String = resourceHelper.gs(R.string.suspendloopforXmin, minutes.getMinutes()) @DrawableRes override fun icon(): Int = R.drawable.ic_pause_circle_outline_24dp override fun doAction(callback: Callback) { if (!loopPlugin.isSuspended) { loopPlugin.suspendLoop(minutes.getMinutes()) rxBus.send(EventRefreshOverview("ActionLoopSuspend")) callback.result(PumpEnactResult(injector).success(true).comment(R.string.ok))?.run() } else { callback.result(PumpEnactResult(injector).success(true).comment(R.string.alreadysuspended))?.run() } } override fun toJSON(): String { val data = JSONObject().put("minutes", minutes.getMinutes()) return JSONObject() .put("type", this.javaClass.name) .put("data", data) .toString() } override fun fromJSON(data: String): Action { val o = JSONObject(data) minutes.setMinutes(JsonHelper.safeGetInt(o, "minutes")) return this } override fun hasDialog(): Boolean = true override fun generateDialog(root: LinearLayout) { LayoutBuilder() .add(LabelWithElement(injector, resourceHelper.gs(R.string.careportal_newnstreatment_duration_min_label), "", minutes)) .build(root) } }
agpl-3.0
5339bd72562dd7d3b193154cb3cc0f9a
41.806452
131
0.746702
4.638112
false
false
false
false
QuixomTech/DeviceInfo
app/src/main/java/com/quixom/apps/deviceinfo/fragments/CameraFragment.kt
1
25053
package com.quixom.apps.deviceinfo.fragments import android.Manifest import android.annotation.SuppressLint import android.annotation.TargetApi import android.content.Context import android.content.pm.PackageManager import android.graphics.Camera import android.graphics.ImageFormat import android.hardware.camera2.CameraCharacteristics import android.hardware.camera2.CameraManager import android.hardware.camera2.params.StreamConfigurationMap import android.os.Build import android.os.Bundle import android.support.annotation.RequiresApi import android.support.v4.app.ActivityCompat import android.support.v4.content.ContextCompat import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.util.Range import android.util.Rational import android.util.Size import android.view.* import android.widget.* import com.quixom.apps.deviceinfo.R import com.quixom.apps.deviceinfo.adapters.CameraAdapter import com.quixom.apps.deviceinfo.models.FeaturesHW import com.quixom.apps.deviceinfo.utilities.KeyUtil import java.lang.StringBuilder import java.util.* class CameraFragment : BaseFragment(), View.OnClickListener { @RequiresApi(Build.VERSION_CODES.M) @TargetApi(Build.VERSION_CODES.LOLLIPOP) override fun onClick(view: View?) { when (view) { tvRearCamera -> { checkCameraPermission("1") tabSelector(tvRearCamera!!, tvFrontCamera!!) } tvFrontCamera -> { checkCameraPermission("0") tabSelector(tvFrontCamera!!, tvRearCamera!!) } } } var ivMenu: ImageView? = null var ivBack: ImageView? = null var tvTitle: TextView? = null var tvCameraFeature: TextView? = null var tvRearCamera: TextView? = null var tvFrontCamera: TextView? = null var textAreaScroller: ScrollView? = null var llParentCamera: LinearLayout? = null private var rvCameraFeatures: RecyclerView? = null var camera: Camera? = null private var cameraManager: CameraManager? = null @TargetApi(Build.VERSION_CODES.LOLLIPOP) override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { // val view = inflater.inflate(R.layout.fragment_camera, container, false) val contextThemeWrapper = ContextThemeWrapper(activity, R.style.CameraTheme) val localInflater = inflater.cloneInContext(contextThemeWrapper) val view = localInflater.inflate(R.layout.fragment_camera, container, false) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { val window = activity!!.window window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) window.statusBarColor = resources.getColor(R.color.dark_green_blue) window.navigationBarColor = resources.getColor(R.color.dark_green_blue) } ivMenu = view.findViewById(R.id.iv_menu) ivBack = view.findViewById(R.id.iv_back) tvTitle = view.findViewById(R.id.tv_title) tvCameraFeature = view.findViewById(R.id.tv_camera_feature) tvRearCamera = view.findViewById(R.id.tv_rear_camera) tvFrontCamera = view.findViewById(R.id.tv_front_camera) textAreaScroller = view.findViewById(R.id.textAreaScroller) llParentCamera = view.findViewById(R.id.ll_parent_camera) rvCameraFeatures = view.findViewById(R.id.rv_Camera_Features) cameraManager = mActivity.getSystemService(Context.CAMERA_SERVICE) as CameraManager? camera = Camera() return view } @RequiresApi(Build.VERSION_CODES.M) @TargetApi(Build.VERSION_CODES.LOLLIPOP) override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) initToolbar() tvRearCamera?.setOnClickListener(this) tvFrontCamera?.setOnClickListener(this) if (cameraManager?.cameraIdList?.size!! >= 2) { llParentCamera?.visibility = View.VISIBLE } else { llParentCamera?.visibility = View.GONE } rvCameraFeatures?.layoutManager = LinearLayoutManager(mActivity) rvCameraFeatures?.hasFixedSize() checkCameraPermission("1") } override fun onHiddenChanged(hidden: Boolean) { super.onHiddenChanged(hidden) if (!hidden && isAdded) { initToolbar() } } private fun initToolbar() { ivMenu?.visibility = View.VISIBLE ivBack?.visibility = View.GONE tvTitle?.text = mResources.getString(R.string.camera) ivMenu?.setOnClickListener { mActivity.openDrawer() } } @RequiresApi(Build.VERSION_CODES.M) @TargetApi(Build.VERSION_CODES.LOLLIPOP) /** * this method will show permission pop up messages to user. */ private fun checkCameraPermission(ids: String) { if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { val hasWriteCameraPermission = mActivity.checkSelfPermission(Manifest.permission.CAMERA) if (hasWriteCameraPermission != PackageManager.PERMISSION_GRANTED) { requestPermissions(arrayOf(Manifest.permission.CAMERA), KeyUtil.KEY_CAMERA_CODE) } else { fetchCameraCharacteristics(cameraManager!!, ids) } } else { fetchCameraCharacteristics(cameraManager!!, ids) } } @TargetApi(Build.VERSION_CODES.LOLLIPOP) override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) when (requestCode) { KeyUtil.KEY_CAMERA_CODE -> if (permissions.isNotEmpty()) { if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { // Permission Granted fetchCameraCharacteristics(cameraManager!!, "1") } else if (grantResults[0] == PackageManager.PERMISSION_DENIED) { // Should we show an explanation? if (ActivityCompat.shouldShowRequestPermissionRationale(mActivity, Manifest.permission.GET_ACCOUNTS)) { //Show permission explanation dialog... Toast.makeText(mActivity, "Need to grant account Permission", Toast.LENGTH_LONG).show() } } } else -> super.onRequestPermissionsResult(requestCode, permissions, grantResults) } } private fun tabSelector(textview1: TextView, textview2: TextView) { /*** Set text color */ textview1.setTextColor(ContextCompat.getColor(mActivity, R.color.font_white)) textview2.setTextColor(ContextCompat.getColor(mActivity, R.color.orange)) /*** Background color */ textview1.setBackgroundColor(ContextCompat.getColor(mActivity, R.color.orange)) textview2.setBackgroundColor(ContextCompat.getColor(mActivity, R.color.font_white)) /*** Set background drawable */ textview1.setBackgroundResource(R.drawable.rectangle_fill) textview2.setBackgroundResource(R.drawable.rectangle_unfill) } @TargetApi(Build.VERSION_CODES.LOLLIPOP) private fun fetchCameraCharacteristics(cameraManager: CameraManager, ids: String) { val lists = ArrayList<FeaturesHW>() val sb = StringBuilder() val characteristics = cameraManager.getCameraCharacteristics(ids) for (key in characteristics.keys) { sb.append(key.name).append("=").append(getCharacteristicsValue(key, characteristics)).append("\n\n") val keyNm = key.name.split(".") if (getCharacteristicsValue(key, characteristics) != "") { if (key.name.split(".").size == 4) { lists.add(FeaturesHW(keyNm[3], getCharacteristicsValue(key, characteristics))) } else { lists.add(FeaturesHW(keyNm[2], getCharacteristicsValue(key, characteristics))) } } } val adapter = CameraAdapter(lists, mActivity) //now adding the adapter to RecyclerView rvCameraFeatures?.adapter = adapter } @SuppressLint("NewApi") @Suppress("UNCHECKED_CAST") private fun <T> getCharacteristicsValue(key: CameraCharacteristics.Key<T>, characteristics: CameraCharacteristics): String { val values = mutableListOf<String>() if (CameraCharacteristics.COLOR_CORRECTION_AVAILABLE_ABERRATION_MODES == key) { val modes = characteristics.get(key) as IntArray modes.forEach { when (it) { CameraCharacteristics.COLOR_CORRECTION_ABERRATION_MODE_OFF -> values.add("Off") CameraCharacteristics.COLOR_CORRECTION_ABERRATION_MODE_FAST -> values.add("Fast") CameraCharacteristics.COLOR_CORRECTION_ABERRATION_MODE_HIGH_QUALITY -> values.add("High Quality") } } } else if (CameraCharacteristics.CONTROL_AE_AVAILABLE_ANTIBANDING_MODES == key) { val modes = characteristics.get(key) as IntArray modes.forEach { when (it) { CameraCharacteristics.CONTROL_AE_ANTIBANDING_MODE_OFF -> values.add("Off") CameraCharacteristics.CONTROL_AE_ANTIBANDING_MODE_AUTO -> values.add("Auto") CameraCharacteristics.CONTROL_AE_ANTIBANDING_MODE_50HZ -> values.add("50Hz") CameraCharacteristics.CONTROL_AE_ANTIBANDING_MODE_60HZ -> values.add("60Hz") } } } else if (CameraCharacteristics.CONTROL_AE_AVAILABLE_MODES == key) { val modes = characteristics.get(key) as IntArray modes.forEach { when (it) { CameraCharacteristics.CONTROL_AE_MODE_OFF -> values.add("Off") CameraCharacteristics.CONTROL_AE_MODE_ON -> values.add("On") CameraCharacteristics.CONTROL_AE_MODE_ON_ALWAYS_FLASH -> values.add("Always Flash") CameraCharacteristics.CONTROL_AE_MODE_ON_AUTO_FLASH -> values.add("Auto Flash") CameraCharacteristics.CONTROL_AE_MODE_ON_AUTO_FLASH_REDEYE -> values.add("Auto Flash Redeye") } } } else if (CameraCharacteristics.CONTROL_AE_AVAILABLE_TARGET_FPS_RANGES == key) { val ranges = characteristics.get(key) as Array<Range<Int>> ranges.forEach { values.add(getRangeValue(it)) } } else if (CameraCharacteristics.CONTROL_AE_COMPENSATION_RANGE == key) { val range = characteristics.get(key) as Range<Int> values.add(getRangeValue(range)) } else if (CameraCharacteristics.CONTROL_AE_COMPENSATION_STEP == key) { val step = characteristics.get(key) as Rational values.add(step.toString()) }/* else if (CameraCharacteristics.CONTROL_AE_LOCK_AVAILABLE == key) { // TODO requires >23 val available = characteristics.get(key) values.add(available.toString()) } */ else if (CameraCharacteristics.CONTROL_AF_AVAILABLE_MODES == key) { val modes = characteristics.get(key) as IntArray modes.forEach { when (it) { CameraCharacteristics.CONTROL_AF_MODE_OFF -> values.add("Off") CameraCharacteristics.CONTROL_AF_MODE_AUTO -> values.add("Auto") CameraCharacteristics.CONTROL_AF_MODE_EDOF -> values.add("EDOF") CameraCharacteristics.CONTROL_AF_MODE_MACRO -> values.add("Macro") CameraCharacteristics.CONTROL_AF_MODE_CONTINUOUS_PICTURE -> values.add("Continous Picture") CameraCharacteristics.CONTROL_AF_MODE_CONTINUOUS_VIDEO -> values.add("Continous Video") } } } else if (CameraCharacteristics.CONTROL_AVAILABLE_EFFECTS == key) { val effects = characteristics.get(key) as IntArray effects.forEach { values.add(when (it) { CameraCharacteristics.CONTROL_EFFECT_MODE_OFF -> "Off" CameraCharacteristics.CONTROL_EFFECT_MODE_AQUA -> "Aqua" CameraCharacteristics.CONTROL_EFFECT_MODE_BLACKBOARD -> "Blackboard" CameraCharacteristics.CONTROL_EFFECT_MODE_MONO -> "Mono" CameraCharacteristics.CONTROL_EFFECT_MODE_NEGATIVE -> "Negative" CameraCharacteristics.CONTROL_EFFECT_MODE_POSTERIZE -> "Posterize" CameraCharacteristics.CONTROL_EFFECT_MODE_SEPIA -> "Sepia" CameraCharacteristics.CONTROL_EFFECT_MODE_SOLARIZE -> "Solarize" CameraCharacteristics.CONTROL_EFFECT_MODE_WHITEBOARD -> "Whiteboard" else -> { "Unkownn ${it}" } }) } } /*else if (CameraCharacteristics.CONTROL_AVAILABLE_MODES == key) { val modes = characteristics.get(key) as IntArray modes.forEach { values.add(when (it) { CameraCharacteristics.CONTROL_MODE_OFF -> "Off" CameraCharacteristics.CONTROL_MODE_OFF_KEEP_STATE -> "Off Keep State" CameraCharacteristics.CONTROL_MODE_AUTO -> "Auto" CameraCharacteristics.CONTROL_MODE_USE_SCENE_MODE -> "Use Scene Mode" else -> { "Unkownn ${it}" } }) } }*/ else if (CameraCharacteristics.CONTROL_AVAILABLE_SCENE_MODES == key) { val modes = characteristics.get(key) as IntArray modes.forEach { values.add(when (it) { CameraCharacteristics.CONTROL_SCENE_MODE_DISABLED -> "Disabled" CameraCharacteristics.CONTROL_SCENE_MODE_ACTION -> "Action" CameraCharacteristics.CONTROL_SCENE_MODE_BARCODE -> "Barcode" CameraCharacteristics.CONTROL_SCENE_MODE_BEACH -> "Beach" CameraCharacteristics.CONTROL_SCENE_MODE_CANDLELIGHT -> "Candlelight" CameraCharacteristics.CONTROL_SCENE_MODE_FACE_PRIORITY -> "Face Priority" CameraCharacteristics.CONTROL_SCENE_MODE_FIREWORKS -> "Fireworks" CameraCharacteristics.CONTROL_SCENE_MODE_HDR -> "HDR" CameraCharacteristics.CONTROL_SCENE_MODE_LANDSCAPE -> "Landscape" CameraCharacteristics.CONTROL_SCENE_MODE_NIGHT -> "Night" CameraCharacteristics.CONTROL_SCENE_MODE_NIGHT_PORTRAIT -> "Night Portrait" CameraCharacteristics.CONTROL_SCENE_MODE_PARTY -> "Party" CameraCharacteristics.CONTROL_SCENE_MODE_PORTRAIT -> "Portrait" CameraCharacteristics.CONTROL_SCENE_MODE_SNOW -> "Snow" CameraCharacteristics.CONTROL_SCENE_MODE_SPORTS -> "Sports" CameraCharacteristics.CONTROL_SCENE_MODE_STEADYPHOTO -> "Steady Photo" CameraCharacteristics.CONTROL_SCENE_MODE_SUNSET -> "Sunset" CameraCharacteristics.CONTROL_SCENE_MODE_THEATRE -> "Theatre" CameraCharacteristics.CONTROL_SCENE_MODE_HIGH_SPEED_VIDEO -> "High Speed Video" else -> { "Unkownn ${it}" } }) } } else if (CameraCharacteristics.CONTROL_AVAILABLE_VIDEO_STABILIZATION_MODES == key) { val modes = characteristics.get(key) as IntArray modes.forEach { values.add(when (it) { CameraCharacteristics.CONTROL_VIDEO_STABILIZATION_MODE_ON -> "On" CameraCharacteristics.CONTROL_VIDEO_STABILIZATION_MODE_OFF -> "Off" else -> { "Unkownn ${it}" } }) } } else if (CameraCharacteristics.CONTROL_AWB_AVAILABLE_MODES == key) { } /*else if (CameraCharacteristics.CONTROL_AWB_LOCK_AVAILABLE == key) { } */ else if (CameraCharacteristics.CONTROL_MAX_REGIONS_AE == key) { } else if (CameraCharacteristics.CONTROL_MAX_REGIONS_AF == key) { } else if (CameraCharacteristics.CONTROL_MAX_REGIONS_AWB == key) { } /*else if (CameraCharacteristics.CONTROL_POST_RAW_SENSITIVITY_BOOST_RANGE == key) { } else if (CameraCharacteristics.DEPTH_DEPTH_IS_EXCLUSIVE == key) { }*/ else if (CameraCharacteristics.EDGE_AVAILABLE_EDGE_MODES == key) { } else if (CameraCharacteristics.FLASH_INFO_AVAILABLE == key) { } else if (CameraCharacteristics.HOT_PIXEL_AVAILABLE_HOT_PIXEL_MODES == key) { } else if (CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL == key) { } else if (CameraCharacteristics.JPEG_AVAILABLE_THUMBNAIL_SIZES == key) { } else if (CameraCharacteristics.LENS_FACING == key) { val facing = characteristics.get(key) values.add( when (facing) { CameraCharacteristics.LENS_FACING_BACK -> "Back" CameraCharacteristics.LENS_FACING_FRONT -> "Front" CameraCharacteristics.LENS_FACING_EXTERNAL -> "External" else -> "Unkown" } ) } else if (CameraCharacteristics.LENS_INFO_AVAILABLE_APERTURES == key) { } else if (CameraCharacteristics.LENS_INFO_AVAILABLE_FILTER_DENSITIES == key) { } else if (CameraCharacteristics.LENS_INFO_AVAILABLE_FOCAL_LENGTHS == key) { } else if (CameraCharacteristics.LENS_INFO_AVAILABLE_OPTICAL_STABILIZATION == key) { } else if (CameraCharacteristics.LENS_INFO_FOCUS_DISTANCE_CALIBRATION == key) { } else if (CameraCharacteristics.LENS_INFO_HYPERFOCAL_DISTANCE == key) { } else if (CameraCharacteristics.LENS_INFO_MINIMUM_FOCUS_DISTANCE == key) { }/* else if (CameraCharacteristics.LENS_INTRINSIC_CALIBRATION == key) { } else if (CameraCharacteristics.LENS_POSE_ROTATION == key) { } /**/else if (CameraCharacteristics.LENS_POSE_TRANSLATION == key) { } /**/else if (CameraCharacteristics.LENS_RADIAL_DISTORTION == key) { }*//* else if (CameraCharacteristics.NOISE_REDUCTION_AVAILABLE_NOISE_REDUCTION_MODES == key) { } *//*else if (CameraCharacteristics.REPROCESS_MAX_CAPTURE_STALL == key) { } */ else if (CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES == key) { } else if (CameraCharacteristics.REQUEST_MAX_NUM_INPUT_STREAMS == key) { } else if (CameraCharacteristics.REQUEST_MAX_NUM_OUTPUT_PROC == key) { } else if (CameraCharacteristics.REQUEST_MAX_NUM_OUTPUT_PROC_STALLING == key) { } else if (CameraCharacteristics.REQUEST_MAX_NUM_OUTPUT_RAW == key) { } else if (CameraCharacteristics.REQUEST_PARTIAL_RESULT_COUNT == key) { } else if (CameraCharacteristics.REQUEST_PIPELINE_MAX_DEPTH == key) { } else if (CameraCharacteristics.SCALER_AVAILABLE_MAX_DIGITAL_ZOOM == key) { } else if (CameraCharacteristics.SCALER_CROPPING_TYPE == key) { } else if (CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP == key) { val map = characteristics.get(key) as StreamConfigurationMap val outputFormats = map.outputFormats outputFormats.forEach { values.add(printOutputFormat(it, map)) } } else if (CameraCharacteristics.SENSOR_AVAILABLE_TEST_PATTERN_MODES == key) { } else if (CameraCharacteristics.SENSOR_BLACK_LEVEL_PATTERN == key) { } else if (CameraCharacteristics.SENSOR_CALIBRATION_TRANSFORM1 == key) { } else if (CameraCharacteristics.SENSOR_CALIBRATION_TRANSFORM2 == key) { } else if (CameraCharacteristics.SENSOR_COLOR_TRANSFORM1 == key) { } else if (CameraCharacteristics.SENSOR_COLOR_TRANSFORM2 == key) { } else if (CameraCharacteristics.SENSOR_FORWARD_MATRIX1 == key) { } else if (CameraCharacteristics.SENSOR_FORWARD_MATRIX2 == key) { } else if (CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE == key) { } else if (CameraCharacteristics.SENSOR_INFO_COLOR_FILTER_ARRANGEMENT == key) { } else if (CameraCharacteristics.SENSOR_INFO_EXPOSURE_TIME_RANGE == key) { } /*else if (CameraCharacteristics.SENSOR_INFO_LENS_SHADING_APPLIED == key) { } */ else if (CameraCharacteristics.SENSOR_INFO_MAX_FRAME_DURATION == key) { } else if (CameraCharacteristics.SENSOR_INFO_PHYSICAL_SIZE == key) { } else if (CameraCharacteristics.SENSOR_INFO_PIXEL_ARRAY_SIZE == key) { } /*else if (CameraCharacteristics.SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE == key) { }*/ else if (CameraCharacteristics.SENSOR_INFO_SENSITIVITY_RANGE == key) { } else if (CameraCharacteristics.SENSOR_INFO_TIMESTAMP_SOURCE == key) { } else if (CameraCharacteristics.SENSOR_INFO_WHITE_LEVEL == key) { } else if (CameraCharacteristics.SENSOR_MAX_ANALOG_SENSITIVITY == key) { } /*else if (CameraCharacteristics.SENSOR_OPTICAL_BLACK_REGIONS == key) { }*/ else if (CameraCharacteristics.SENSOR_ORIENTATION == key) { val orientation = characteristics.get(key) as Int values.add(orientation.toString()) } else if (CameraCharacteristics.SENSOR_REFERENCE_ILLUMINANT1 == key) { } else if (CameraCharacteristics.SENSOR_REFERENCE_ILLUMINANT2 == key) { }/* else if (CameraCharacteristics.SHADING_AVAILABLE_MODES == key) { }*/ else if (CameraCharacteristics.STATISTICS_INFO_AVAILABLE_FACE_DETECT_MODES == key) { } else if (CameraCharacteristics.STATISTICS_INFO_AVAILABLE_HOT_PIXEL_MAP_MODES == key) { }/* else if (CameraCharacteristics.STATISTICS_INFO_AVAILABLE_LENS_SHADING_MAP_MODES == key) { }*/ else if (CameraCharacteristics.SYNC_MAX_LATENCY == key) { } else if (CameraCharacteristics.TONEMAP_AVAILABLE_TONE_MAP_MODES == key) { } else if (CameraCharacteristics.TONEMAP_MAX_CURVE_POINTS == key) { } values.sort() return if (values.isEmpty()) "" else join(", ", values) } @TargetApi(Build.VERSION_CODES.LOLLIPOP) private fun printOutputFormat(outputFormat: Int, map: StreamConfigurationMap): String { val formatName = getImageFormat(outputFormat) val outputSizes = map.getOutputSizes(outputFormat); val outputSizeValues = mutableListOf<String>() outputSizes.forEach { val mp = getMegaPixel(it) outputSizeValues.add("${it.width}x${it.height} (${mp}MP)") } val sizesString = join(", ", outputSizeValues) return "\n$formatName -> [$sizesString]" } @TargetApi(Build.VERSION_CODES.LOLLIPOP) private fun getMegaPixel(size: Size): String { val mp = (size.width * size.height) / 1000000f return String.format("%.1f", mp) } private fun getImageFormat(format: Int): String { return when (format) { ImageFormat.DEPTH16 -> "DEPTH16" ImageFormat.DEPTH_POINT_CLOUD -> "DEPTH_POINT_CLOUD" ImageFormat.FLEX_RGBA_8888 -> "FLEX_RGBA_8888" ImageFormat.FLEX_RGB_888 -> "FLEX_RGB_888" ImageFormat.JPEG -> "JPEG" ImageFormat.NV16 -> "NV16" ImageFormat.NV21 -> "NV21" ImageFormat.PRIVATE -> "PRIVATE" ImageFormat.RAW10 -> "RAW10" ImageFormat.RAW12 -> "RAW12" ImageFormat.RAW_PRIVATE -> "RAW_PRIVATE" ImageFormat.RAW_SENSOR -> "RAW_SENSOR" ImageFormat.RGB_565 -> "RGB_565" ImageFormat.YUV_420_888 -> "YUV_420_888" ImageFormat.YUV_422_888 -> "YUV_422_888" ImageFormat.YUV_444_888 -> "YUV_444_888" ImageFormat.YUY2 -> "YUY2" ImageFormat.YV12 -> "YV12" else -> "Unkown" } } @TargetApi(Build.VERSION_CODES.LOLLIPOP) private fun <T : Comparable<T>> getRangeValue(range: Range<T>): String { return "[${range.lower},${range.upper}]" } fun <T> join(delimiter: String, elements: Collection<T>?): String { if (null == elements || elements.isEmpty()) { return "" } val sb = StringBuilder() val iter = elements.iterator() while (iter.hasNext()) { val element = iter.next() sb.append(element.toString()) if (iter.hasNext()) { sb.append(delimiter) } } return sb.toString() } }
apache-2.0
5f6f80d692ec0df53ae0f597fc88dd9e
43.341593
128
0.62735
4.762022
false
false
false
false
anitawoodruff/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/models/SetupCustomization.kt
1
3988
package com.habitrpg.android.habitica.models class SetupCustomization { var key: String = "" var drawableId: Int? = null var colorId: Int? = null var text: String = "" var path: String = "" var category: String = "" var subcategory: String = "" companion object { fun createSize(key: String, drawableId: Int, text: String): SetupCustomization { val customization = SetupCustomization() customization.key = key customization.drawableId = drawableId customization.text = text customization.path = "size" customization.category = "body" customization.subcategory = "size" return customization } fun createShirt(key: String, drawableId: Int): SetupCustomization { val customization = SetupCustomization() customization.key = key customization.drawableId = drawableId customization.path = "shirt" customization.category = "body" customization.subcategory = "shirt" return customization } fun createSkin(key: String, colorId: Int?): SetupCustomization { val customization = SetupCustomization() customization.key = key customization.colorId = colorId customization.path = "skin" customization.category = "skin" return customization } fun createHairColor(key: String, colorId: Int?): SetupCustomization { val customization = SetupCustomization() customization.key = key customization.colorId = colorId customization.path = "hair.color" customization.category = "hair" customization.subcategory = "color" return customization } fun createHairBangs(key: String, drawableId: Int?): SetupCustomization { val customization = SetupCustomization() customization.key = key customization.drawableId = drawableId customization.path = "hair.bangs" customization.category = "hair" customization.subcategory = "bangs" return customization } fun createHairPonytail(key: String, drawableId: Int?): SetupCustomization { val customization = SetupCustomization() customization.key = key customization.drawableId = drawableId customization.path = "hair.base" customization.category = "hair" customization.subcategory = "base" return customization } fun createGlasses(key: String, drawableId: Int?): SetupCustomization { val customization = SetupCustomization() customization.key = key customization.drawableId = drawableId customization.path = "glasses" customization.category = "extras" customization.subcategory = "glasses" return customization } fun createFlower(key: String, drawableId: Int?): SetupCustomization { val customization = SetupCustomization() customization.key = key customization.drawableId = drawableId customization.path = "hair.flower" customization.category = "extras" customization.subcategory = "flower" return customization } fun createWheelchair(key: String, drawableId: Int?): SetupCustomization { val customization = SetupCustomization() customization.key = key customization.drawableId = drawableId customization.path = "chair" customization.category = "extras" customization.subcategory = "wheelchair" return customization } } }
gpl-3.0
68ea80218c8513db20c207bc7d82742a
35.622642
88
0.586008
6.12596
false
false
false
false
cout970/Modeler
src/main/kotlin/com/cout970/reactive/dsl/Util.kt
1
2155
package com.cout970.reactive.dsl import com.cout970.reactive.core.RBuilder import com.cout970.reactive.core.Renderer import com.cout970.reactive.nodes.ComponentBuilder import com.cout970.reactive.nodes.comp import org.liquidengine.legui.component.Component import org.liquidengine.legui.event.Event import org.liquidengine.legui.listener.EventListener import org.liquidengine.legui.listener.ListenerMap /** * This function converts all the children of this component to RNodes so they are not ignored/removed by * the reconciliation algorithm */ fun <T : Component> ComponentBuilder<T>.childrenAsNodes() { this.component.childComponents.forEach { comp(it) { if (!it.isEmpty) { childrenAsNodes() } } } } /** * This stores a function in a component, this function will be called after the component is mounted in * the component tree. * * The order of execution of this function is the following: * - The parent function gets called if exist * - Then for every child, it's function is called if exists, this follows the childComponents order in the parent */ fun RBuilder.postMount(func: Component.() -> Unit) { val oldDeferred = this.deferred this.deferred = { val oldFunc = it.metadata[Renderer.METADATA_POST_MOUNT] // Preserve the old postMount val finalFunc = if (oldFunc != null) { val comb: Component.() -> Unit = { (oldFunc as? (Component.() -> Unit))?.invoke(this) func() } comb } else { func } it.metadata[Renderer.METADATA_POST_MOUNT] = finalFunc oldDeferred?.invoke(it) } } /** * Given a key, finds a child of this component with it or returns null */ fun Component.child(key: String): Component? { return childComponents.find { it.metadata[Renderer.METADATA_KEY] == key } } fun <E : Event<*>> ListenerMap.replaceListener(eventClass: Class<E>, listener: EventListener<E>) { getListeners<E>(eventClass).firstOrNull()?.let { removeListener(eventClass, it) } getListeners<E>(eventClass).add(listener) }
gpl-3.0
fe9fe5ec9b3358f772319469de4c89ab
30.246377
114
0.676102
4.112595
false
false
false
false
idea4bsd/idea4bsd
platform/script-debugger/debugger-ui/src/CallFrameView.kt
21
4112
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.debugger.frame import com.intellij.icons.AllIcons import com.intellij.ui.ColoredTextContainer import com.intellij.ui.SimpleTextAttributes import com.intellij.xdebugger.evaluation.XDebuggerEvaluator import com.intellij.xdebugger.frame.XCompositeNode import com.intellij.xdebugger.frame.XStackFrame import org.jetbrains.concurrency.Promise import org.jetbrains.debugger.* // isInLibraryContent call could be costly, so we compute it only once (our customizePresentation called on each repaint) class CallFrameView @JvmOverloads constructor(val callFrame: CallFrame, override val viewSupport: DebuggerViewSupport, val script: Script? = null, sourceInfo: SourceInfo? = null, isInLibraryContent: Boolean? = null, override val vm: Vm? = null) : XStackFrame(), VariableContext { private val sourceInfo = sourceInfo ?: viewSupport.getSourceInfo(script, callFrame) private val isInLibraryContent: Boolean = isInLibraryContent ?: (this.sourceInfo != null && viewSupport.isInLibraryContent(this.sourceInfo, script)) private var evaluator: XDebuggerEvaluator? = null override fun getEqualityObject() = callFrame.equalityObject override fun computeChildren(node: XCompositeNode) { node.setAlreadySorted(true) createAndAddScopeList(node, callFrame.variableScopes, this, callFrame) } override val evaluateContext: EvaluateContext get() = callFrame.evaluateContext override fun watchableAsEvaluationExpression() = true override val memberFilter: Promise<MemberFilter> get() = viewSupport.getMemberFilter(this) fun getMemberFilter(scope: Scope) = createVariableContext(scope, this, callFrame).memberFilter override fun getEvaluator(): XDebuggerEvaluator? { if (evaluator == null) { evaluator = viewSupport.createFrameEvaluator(this) } return evaluator } override fun getSourcePosition() = sourceInfo override fun customizePresentation(component: ColoredTextContainer) { if (sourceInfo == null) { val scriptName = if (script == null) "unknown" else script.url.trimParameters().toDecodedForm() val line = callFrame.line component.append(if (line == -1) scriptName else "$scriptName:$line", SimpleTextAttributes.ERROR_ATTRIBUTES) return } val fileName = sourceInfo.file.name val line = sourceInfo.line + 1 val textAttributes = if (isInLibraryContent || callFrame.isFromAsyncStack) SimpleTextAttributes.GRAYED_ATTRIBUTES else SimpleTextAttributes.REGULAR_ATTRIBUTES val functionName = sourceInfo.functionName if (functionName == null || (functionName.isEmpty() && callFrame.hasOnlyGlobalScope)) { if (fileName.startsWith("index.")) { sourceInfo.file.parent?.let { component.append("${it.name}/", textAttributes) } } component.append("$fileName:$line", textAttributes) } else { if (functionName.isEmpty()) { component.append("anonymous", if (isInLibraryContent) SimpleTextAttributes.GRAYED_ITALIC_ATTRIBUTES else SimpleTextAttributes.REGULAR_ITALIC_ATTRIBUTES) } else { component.append(functionName, textAttributes) } component.append("(), $fileName:$line", textAttributes) } component.setIcon(AllIcons.Debugger.StackFrame) } }
apache-2.0
64e0e5ccc4092b29f793e91e3b7d94cb
40.13
160
0.70501
5.178841
false
false
false
false
sewerk/Bill-Calculator
app/src/test/java/pl/srw/billcalculator/form/FormPreviousReadingsVMTest.kt
1
4181
package pl.srw.billcalculator.form import android.arch.core.executor.testing.InstantTaskExecutorRule import android.arch.lifecycle.MutableLiveData import android.arch.lifecycle.Observer import com.nhaarman.mockito_kotlin.* import io.reactivex.Single import junitparams.JUnitParamsRunner import junitparams.Parameters import org.junit.Rule import org.junit.Test import org.junit.rules.TestRule import org.junit.runner.RunWith import pl.srw.billcalculator.RxJavaBaseTest import pl.srw.billcalculator.data.bill.ReadingsRepo import pl.srw.billcalculator.data.settings.prices.EnergyTariff import pl.srw.billcalculator.data.settings.prices.PricesRepo import pl.srw.billcalculator.type.Provider @RunWith(JUnitParamsRunner::class) class FormPreviousReadingsVMTest : RxJavaBaseTest() { @get:Rule val rule: TestRule = InstantTaskExecutorRule() val readings = intArrayOf(1, 2, 3) val readingsRepo: ReadingsRepo = mock { on { getPreviousReadingsFor(any()) } doReturn Single.just(readings) } val tariffLiveData = MutableLiveData<EnergyTariff>() val pricesRepo: PricesRepo = mock { on { tariffPge } doReturn tariffLiveData on { tariffTauron } doReturn tariffLiveData } val testObserver: Observer<IntArray> = mock() lateinit var sut: FormPreviousReadingsVM @Test @Parameters("PGNIG", "PGE", "TAURON") fun `fetches single previous readings for PGNIG or G11 tariff`(provider: Provider) { setTariff(EnergyTariff.G11) init(provider) sut.singlePrevReadings.observeForever(testObserver) verify(testObserver).onChanged(readings) } @Test @Parameters("PGNIG", "PGE", "TAURON") fun `does not fetch double previous readings for PGNIG or G11 tariff`(provider: Provider) { setTariff(EnergyTariff.G11) init(provider) sut.dayPrevReadings.observeForever(testObserver) sut.nightPrevReadings.observeForever(testObserver) verify(testObserver, never()).onChanged(readings) } @Test @Parameters("PGE", "TAURON") fun `fetches double previous readings for G12 tariff`(provider: Provider) { setTariff(EnergyTariff.G12) init(provider) sut.dayPrevReadings.observeForever(testObserver) sut.nightPrevReadings.observeForever(testObserver) verify(testObserver, times(2)).onChanged(readings) } @Test @Parameters("PGE", "TAURON") fun `does not fetch single previous readings for G12 tariff`(provider: Provider) { setTariff(EnergyTariff.G12) init(provider) sut.singlePrevReadings.observeForever(testObserver) verify(testObserver, never()).onChanged(readings) } @Test @Parameters("PGE", "TAURON") fun `fetch previous readings when tariff changes`(provider: Provider) { setTariff(EnergyTariff.G11) init(provider) sut.dayPrevReadings.observeForever(testObserver) sut.nightPrevReadings.observeForever(testObserver) clearInvocations(testObserver, readingsRepo) setTariff(EnergyTariff.G12) verify(readingsRepo, times(2)).getPreviousReadingsFor(any()) verify(testObserver, times(2)).onChanged(readings) } @Test @Parameters("PGE", "TAURON") fun `does not re-fetch previous readings but notifies cached value, when view re-attached`(provider: Provider) { setTariff(EnergyTariff.G11) init(provider) sut.singlePrevReadings.observeForever(testObserver) clearInvocations(readingsRepo) val afterReAttachObserver: Observer<IntArray> = mock() sut.singlePrevReadings.observeForever(afterReAttachObserver) verify(readingsRepo, never()).getPreviousReadingsFor(any()) verify(afterReAttachObserver).onChanged(readings) } private fun setTariff(tariff: EnergyTariff) { tariffLiveData.value = tariff waitToFinish() // tariff change after observing trigger prev reading fetch } private fun init(provider: Provider) { sut = FormPreviousReadingsVM(provider, readingsRepo, pricesRepo) waitToFinish() // constructor is triggering prev readings fetch } }
mit
5c05ef18f6210b451f9c2b19b87b4754
32.99187
116
0.719923
4.579409
false
true
false
false
siosio/intellij-community
plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/conversions/LiteralConversion.kt
1
5390
// 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.nj2k.conversions import org.jetbrains.annotations.NonNls import org.jetbrains.kotlin.nj2k.NewJ2kConverterContext import org.jetbrains.kotlin.nj2k.tree.* import java.math.BigInteger class LiteralConversion(context: NewJ2kConverterContext) : RecursiveApplicableConversionBase(context) { override fun applyToElement(element: JKTreeElement): JKTreeElement { if (element !is JKLiteralExpression) return recurse(element) val convertedElement = try { element.apply { convertLiteral() } } catch (_: NumberFormatException) { createTodoCall(cannotConvertLiteralMessage(element)) } return recurse(convertedElement) } private fun createTodoCall(@NonNls message: String): JKCallExpressionImpl { val todoMethodSymbol = symbolProvider.provideMethodSymbol("kotlin.TODO") val todoMessageArgument = JKArgumentImpl(JKLiteralExpression("\"$message\"", JKLiteralExpression.LiteralType.STRING)) return JKCallExpressionImpl(todoMethodSymbol, JKArgumentList(todoMessageArgument)) } private fun cannotConvertLiteralMessage(element: JKLiteralExpression): String { val literalType = element.type.toString().toLowerCase() val literalValue = element.literal return "Could not convert $literalType literal '$literalValue' to Kotlin" } private fun JKLiteralExpression.convertLiteral() { literal = when (type) { JKLiteralExpression.LiteralType.DOUBLE -> toDoubleLiteral() JKLiteralExpression.LiteralType.FLOAT -> toFloatLiteral() JKLiteralExpression.LiteralType.LONG -> toLongLiteral() JKLiteralExpression.LiteralType.INT -> toIntLiteral() JKLiteralExpression.LiteralType.CHAR -> convertCharLiteral() JKLiteralExpression.LiteralType.STRING -> toStringLiteral() else -> return } } private fun JKLiteralExpression.toDoubleLiteral() = literal.cleanFloatAndDoubleLiterals().let { text -> if (!text.contains(".") && !text.contains("e", true)) "$text." else text }.let { text -> if (text.endsWith(".")) "${text}0" else text } private fun JKLiteralExpression.toFloatLiteral() = literal.cleanFloatAndDoubleLiterals().let { text -> if (!text.endsWith("f")) "${text}f" else text } private fun JKLiteralExpression.toStringLiteral() = literal.replace("""((?:\\)*)\\([0-3]?[0-7]{1,2})""".toRegex()) { matchResult -> val leadingBackslashes = matchResult.groupValues[1] if (leadingBackslashes.length % 2 == 0) String.format("%s\\u%04x", leadingBackslashes, Integer.parseInt(matchResult.groupValues[2], 8)) else matchResult.value }.replace("""(?<!\\)\$([A-Za-z]+|\{)""".toRegex(), "\\\\$0") private fun JKLiteralExpression.convertCharLiteral() = literal.replace("""\\([0-3]?[0-7]{1,2})""".toRegex()) { String.format("\\u%04x", Integer.parseInt(it.groupValues[1], 8)) } private fun JKLiteralExpression.toIntLiteral() = literal .cleanIntAndLongLiterals() .convertHexLiteral(isLongLiteral = false) .convertBinaryLiteral(isLongLiteral = false) .convertOctalLiteral(isLongLiteral = false) private fun JKLiteralExpression.toLongLiteral() = literal .cleanIntAndLongLiterals() .convertHexLiteral(isLongLiteral = true) .convertBinaryLiteral(isLongLiteral = true) .convertOctalLiteral(isLongLiteral = true) + "L" private fun String.convertHexLiteral(isLongLiteral: Boolean): String { if (!startsWith("0x", ignoreCase = true)) return this val value = BigInteger(drop(2), 16) return when { isLongLiteral && value.bitLength() > 63 -> "-0x${value.toLong().toString(16).substring(1)}" !isLongLiteral && value.bitLength() > 31 -> "-0x${value.toInt().toString(16).substring(1)}" else -> this } } private fun String.convertBinaryLiteral(isLongLiteral: Boolean): String { if (!startsWith("0b", ignoreCase = true)) return this val value = BigInteger(drop(2), 2) return if (isLongLiteral) value.toLong().toString(10) else value.toInt().toString() } private fun String.convertOctalLiteral(isLongLiteral: Boolean): String { if (!startsWith("0") || length == 1 || get(1).toLowerCase() == 'x') return this val value = BigInteger(drop(1), 8) return if (isLongLiteral) value.toLong().toString(10) else value.toInt().toString(10) } private fun String.cleanFloatAndDoubleLiterals() = replace("L", "", ignoreCase = true) .replace("d", "", ignoreCase = true) .replace(".e", "e", ignoreCase = true) .replace(".f", "", ignoreCase = true) .replace("f", "", ignoreCase = true) .replace("_", "") private fun String.cleanIntAndLongLiterals() = replace("l", "", ignoreCase = true) .replace("_", "") }
apache-2.0
3cb37d848ceeecb9c576cd18cbd8d529
39.833333
158
0.633581
4.795374
false
false
false
false
JetBrains/kotlin-native
runtime/src/main/kotlin/kotlin/Array.kt
2
3011
/* * Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE file. */ package kotlin import kotlin.native.internal.ExportForCompiler import kotlin.native.internal.ExportTypeInfo import kotlin.native.internal.PointsTo /** * Represents an array. Array instances can be created using the constructor, [arrayOf], [arrayOfNulls] and [emptyArray] * standard library functions. * See [Kotlin language documentation](https://kotlinlang.org/docs/reference/basic-types.html#arrays) * for more information on arrays. */ @ExportTypeInfo("theArrayTypeInfo") public final class Array<T> { /** * Creates a new array with the specified [size], where each element is calculated by calling the specified * [init] function. * * The function [init] is called for each array element sequentially starting from the first one. * It should return the value for an array element given its index. */ @Suppress("TYPE_PARAMETER_AS_REIFIED") public constructor(size: Int, init: (Int) -> T): this(size) { var index = 0 while (index < size) { this[index] = init(index) index++ } } @PublishedApi @ExportForCompiler internal constructor(@Suppress("UNUSED_PARAMETER") size: Int) {} /** * Returns the number of elements in the array. */ public val size: Int get() = getArrayLength() /** * Returns the array element at the specified [index]. This method can be called using the * index operator. * ``` * value = arr[index] * ``` * * If the [index] is out of bounds of this array, throws an [IndexOutOfBoundsException]. */ @SymbolName("Kotlin_Array_get") @PointsTo(0x000, 0x000, 0x002) // ret -> this.intestines external public operator fun get(index: Int): T /** * Sets the array element at the specified [index] to the specified [value]. This method can * be called using the index operator. * ``` * arr[index] = value * ``` * * If the [index] is out of bounds of this array, throws an [IndexOutOfBoundsException]. */ @SymbolName("Kotlin_Array_set") @PointsTo(0x300, 0x000, 0x000) // this.intestines -> value external public operator fun set(index: Int, value: T): Unit /** * Creates an [Iterator] for iterating over the elements of the array. */ public operator fun iterator(): kotlin.collections.Iterator<T> { return IteratorImpl(this) } @SymbolName("Kotlin_Array_getArrayLength") external private fun getArrayLength(): Int } private class IteratorImpl<T>(val collection: Array<T>) : Iterator<T> { var index : Int = 0 public override fun next(): T { if (!hasNext()) throw NoSuchElementException("$index") return collection[index++] } public override operator fun hasNext(): Boolean { return index < collection.size } }
apache-2.0
0f5e79f48a4c6595a86ff649e72960bc
30.694737
120
0.653936
4.246827
false
false
false
false
jwren/intellij-community
plugins/kotlin/tests-common/test/org/jetbrains/kotlin/idea/checkers/CompilerTestLanguageVersionSettings.kt
1
7263
// 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.checkers import org.jetbrains.kotlin.config.* import org.jetbrains.kotlin.idea.compiler.configuration.KotlinPluginLayout import org.jetbrains.kotlin.idea.test.Directives import org.jetbrains.kotlin.idea.test.KotlinTestUtils import org.junit.Assert import java.util.regex.Pattern const val LANGUAGE_DIRECTIVE = "LANGUAGE" const val API_VERSION_DIRECTIVE = "API_VERSION" const val USE_EXPERIMENTAL_DIRECTIVE = "USE_EXPERIMENTAL" const val IGNORE_DATA_FLOW_IN_ASSERT_DIRECTIVE = "IGNORE_DATA_FLOW_IN_ASSERT" const val JVM_DEFAULT_MODE = "JVM_DEFAULT_MODE" const val SKIP_METADATA_VERSION_CHECK = "SKIP_METADATA_VERSION_CHECK" const val ALLOW_RESULT_RETURN_TYPE = "ALLOW_RESULT_RETURN_TYPE" const val INHERIT_MULTIFILE_PARTS = "INHERIT_MULTIFILE_PARTS" const val SANITIZE_PARENTHESES = "SANITIZE_PARENTHESES" const val CONSTRAINT_SYSTEM_FOR_OVERLOAD_RESOLUTION = "CONSTRAINT_SYSTEM_FOR_OVERLOAD_RESOLUTION" const val ENABLE_JVM_PREVIEW = "ENABLE_JVM_PREVIEW" data class CompilerTestLanguageVersionSettings( private val initialLanguageFeatures: Map<LanguageFeature, LanguageFeature.State>, override val apiVersion: ApiVersion, override val languageVersion: LanguageVersion, val analysisFlags: Map<AnalysisFlag<*>, Any?> = emptyMap() ) : LanguageVersionSettings { val extraLanguageFeatures = specificFeaturesForTests() + initialLanguageFeatures private val delegate = LanguageVersionSettingsImpl(languageVersion, apiVersion, emptyMap(), extraLanguageFeatures) override fun getFeatureSupport(feature: LanguageFeature): LanguageFeature.State = extraLanguageFeatures[feature] ?: delegate.getFeatureSupport(feature) override fun isPreRelease(): Boolean = false @Suppress("UNCHECKED_CAST") override fun <T> getFlag(flag: AnalysisFlag<T>): T = analysisFlags[flag] as T? ?: flag.defaultValue } private fun specificFeaturesForTests(): Map<LanguageFeature, LanguageFeature.State> { return if (System.getProperty("kotlin.ni") == "true") mapOf(LanguageFeature.NewInference to LanguageFeature.State.ENABLED) else emptyMap() } fun parseLanguageVersionSettingsOrDefault(directiveMap: Directives): CompilerTestLanguageVersionSettings = parseLanguageVersionSettings(directiveMap) ?: defaultLanguageVersionSettings() fun parseLanguageVersionSettings(directives: Directives): CompilerTestLanguageVersionSettings? { val apiVersionString = directives[API_VERSION_DIRECTIVE] val languageFeaturesString = directives[LANGUAGE_DIRECTIVE] val analysisFlags = listOfNotNull( analysisFlag(AnalysisFlags.optIn, directives[USE_EXPERIMENTAL_DIRECTIVE]?.split(' ')), analysisFlag(JvmAnalysisFlags.jvmDefaultMode, directives[JVM_DEFAULT_MODE]?.let { JvmDefaultMode.fromStringOrNull(it) }), analysisFlag(AnalysisFlags.ignoreDataFlowInAssert, if (IGNORE_DATA_FLOW_IN_ASSERT_DIRECTIVE in directives) true else null), analysisFlag(AnalysisFlags.skipMetadataVersionCheck, if (SKIP_METADATA_VERSION_CHECK in directives) true else null), analysisFlag(AnalysisFlags.allowResultReturnType, if (ALLOW_RESULT_RETURN_TYPE in directives) true else null), analysisFlag(JvmAnalysisFlags.inheritMultifileParts, if (INHERIT_MULTIFILE_PARTS in directives) true else null), analysisFlag(JvmAnalysisFlags.sanitizeParentheses, if (SANITIZE_PARENTHESES in directives) true else null), analysisFlag(JvmAnalysisFlags.enableJvmPreview, if (ENABLE_JVM_PREVIEW in directives) true else null), analysisFlag(AnalysisFlags.constraintSystemForOverloadResolution, directives[CONSTRAINT_SYSTEM_FOR_OVERLOAD_RESOLUTION]?.let { ConstraintSystemForOverloadResolutionMode.valueOf(it) }), analysisFlag(AnalysisFlags.explicitApiVersion, if (apiVersionString != null) true else null) ) if (apiVersionString == null && languageFeaturesString == null && analysisFlags.isEmpty()) { return null } val apiVersion = when (apiVersionString) { null -> KotlinPluginLayout.instance.standaloneCompilerVersion.apiVersion "LATEST" -> ApiVersion.LATEST else -> ApiVersion.parse(apiVersionString) ?: error("Unknown API version: $apiVersionString") } val languageVersion = maxOf( KotlinPluginLayout.instance.standaloneCompilerVersion.languageVersion, LanguageVersion.fromVersionString(apiVersion.versionString)!! ) val languageFeatures = languageFeaturesString?.let(::collectLanguageFeatureMap).orEmpty() return CompilerTestLanguageVersionSettings(languageFeatures, apiVersion, languageVersion, mapOf(*analysisFlags.toTypedArray())) } fun defaultLanguageVersionSettings(): CompilerTestLanguageVersionSettings { val bundledKotlinVersion = KotlinPluginLayout.instance.standaloneCompilerVersion return CompilerTestLanguageVersionSettings( initialLanguageFeatures = emptyMap(), bundledKotlinVersion.apiVersion, bundledKotlinVersion.languageVersion ) } fun languageVersionSettingsFromText(fileTexts: List<String>): LanguageVersionSettings { val allDirectives = Directives() for (fileText in fileTexts) { KotlinTestUtils.parseDirectives(fileText, allDirectives) } return parseLanguageVersionSettingsOrDefault(allDirectives) } @Suppress("INVISIBLE_MEMBER", "INVISIBLE_REFERENCE", "HIDDEN") private fun <T : Any> analysisFlag(flag: AnalysisFlag<T>, value: @kotlin.internal.NoInfer T?): Pair<AnalysisFlag<T>, T>? = value?.let(flag::to) private val languagePattern = Pattern.compile("(\\+|-|warn:)(\\w+)\\s*") private fun collectLanguageFeatureMap(directives: String): Map<LanguageFeature, LanguageFeature.State> { val matcher = languagePattern.matcher(directives) if (!matcher.find()) { Assert.fail( "Wrong syntax in the '// !$LANGUAGE_DIRECTIVE: ...' directive:\n" + "found: '$directives'\n" + "Must be '((+|-|warn:)LanguageFeatureName)+'\n" + "where '+' means 'enable', '-' means 'disable', 'warn:' means 'enable with warning'\n" + "and language feature names are names of enum entries in LanguageFeature enum class" ) } val values = HashMap<LanguageFeature, LanguageFeature.State>() do { val mode = when (matcher.group(1)) { "+" -> LanguageFeature.State.ENABLED "-" -> LanguageFeature.State.DISABLED "warn:" -> LanguageFeature.State.ENABLED_WITH_WARNING else -> error("Unknown mode for language feature: ${matcher.group(1)}") } val name = matcher.group(2) val feature = LanguageFeature.fromString(name) ?: throw AssertionError( "Language feature not found, please check spelling: $name\n" + "Known features:\n ${LanguageFeature.values().joinToString("\n ")}" ) if (values.put(feature, mode) != null) { Assert.fail("Duplicate entry for the language feature: $name") } } while (matcher.find()) return values }
apache-2.0
68fe44d8f5d71f7e1266c42c40ee5528
48.408163
158
0.733857
4.87777
false
true
false
false
androidx/androidx
compose/material/material/icons/generator/src/main/kotlin/androidx/compose/material/icons/generator/IconParser.kt
3
4913
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.material.icons.generator import androidx.compose.material.icons.generator.vector.FillType import androidx.compose.material.icons.generator.vector.PathParser import androidx.compose.material.icons.generator.vector.Vector import androidx.compose.material.icons.generator.vector.VectorNode import org.xmlpull.v1.XmlPullParser import org.xmlpull.v1.XmlPullParser.END_DOCUMENT import org.xmlpull.v1.XmlPullParser.END_TAG import org.xmlpull.v1.XmlPullParser.START_TAG import org.xmlpull.v1.XmlPullParserException import org.xmlpull.v1.XmlPullParserFactory /** * Parser that converts [icon]s into [Vector]s */ class IconParser(private val icon: Icon) { /** * @return a [Vector] representing the provided [icon]. */ fun parse(): Vector { val parser = XmlPullParserFactory.newInstance().newPullParser().apply { setInput(icon.fileContent.byteInputStream(), null) seekToStartTag() } check(parser.name == "vector") { "The start tag must be <vector>!" } parser.next() val nodes = mutableListOf<VectorNode>() var currentGroup: VectorNode.Group? = null while (!parser.isAtEnd()) { when (parser.eventType) { START_TAG -> { when (parser.name) { PATH -> { val pathData = parser.getAttributeValue( null, PATH_DATA ) val fillAlpha = parser.getValueAsFloat(FILL_ALPHA) val strokeAlpha = parser.getValueAsFloat(STROKE_ALPHA) val fillType = when (parser.getAttributeValue(null, FILL_TYPE)) { // evenOdd and nonZero are the only supported values here, where // nonZero is the default if no values are defined. EVEN_ODD -> FillType.EvenOdd else -> FillType.NonZero } val path = VectorNode.Path( strokeAlpha = strokeAlpha ?: 1f, fillAlpha = fillAlpha ?: 1f, fillType = fillType, nodes = PathParser.parsePathString(pathData) ) if (currentGroup != null) { currentGroup.paths.add(path) } else { nodes.add(path) } } // Material icons are simple and don't have nested groups, so this can be simple GROUP -> { val group = VectorNode.Group() currentGroup = group nodes.add(group) } CLIP_PATH -> { /* TODO: b/147418351 - parse clipping paths */ } } } } parser.next() } return Vector(nodes) } } /** * @return the float value for the attribute [name], or null if it couldn't be found */ private fun XmlPullParser.getValueAsFloat(name: String) = getAttributeValue(null, name)?.toFloatOrNull() private fun XmlPullParser.seekToStartTag(): XmlPullParser { var type = next() while (type != START_TAG && type != END_DOCUMENT) { // Empty loop type = next() } if (type != START_TAG) { throw XmlPullParserException("No start tag found") } return this } private fun XmlPullParser.isAtEnd() = eventType == END_DOCUMENT || (depth < 1 && eventType == END_TAG) // XML tag names private const val CLIP_PATH = "clip-path" private const val GROUP = "group" private const val PATH = "path" // XML attribute names private const val PATH_DATA = "android:pathData" private const val FILL_ALPHA = "android:fillAlpha" private const val STROKE_ALPHA = "android:strokeAlpha" private const val FILL_TYPE = "android:fillType" // XML attribute values private const val EVEN_ODD = "evenOdd"
apache-2.0
385be7830fa39a026f1a3de41f6a1e36
36.219697
104
0.562182
4.997965
false
false
false
false
androidx/androidx
wear/compose/integration-tests/demos/src/androidTest/java/androidx/wear/compose/integration/demos/test/DemoTest.kt
3
7303
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.wear.compose.integration.demos.test import androidx.compose.ui.test.ExperimentalTestApi import androidx.compose.ui.test.SemanticsNodeInteractionCollection import androidx.compose.ui.test.hasClickAction import androidx.compose.ui.test.hasScrollToNodeAction import androidx.compose.ui.test.hasText import androidx.compose.ui.test.isDialog import androidx.compose.ui.test.junit4.createAndroidComposeRule import androidx.compose.ui.test.performClick import androidx.compose.ui.test.performScrollToNode import androidx.test.espresso.Espresso import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.FlakyTest import androidx.test.filters.LargeTest import androidx.wear.compose.integration.demos.Demo import androidx.wear.compose.integration.demos.DemoActivity import androidx.wear.compose.integration.demos.DemoCategory import androidx.wear.compose.integration.demos.WearComposeDemos import com.google.common.truth.Truth.assertThat import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith private val ignoredDemos = listOf<String>( // Not ignoring any of them \o/ ) @LargeTest @RunWith(AndroidJUnit4::class) @OptIn(ExperimentalTestApi::class) class DemoTest { // We need to provide the recompose factory first to use new clock. @get:Rule val rule = createAndroidComposeRule<DemoActivity>() @FlakyTest(bugId = 259724403) @Test fun navigateThroughAllDemos() { // Compose integration-tests are split into batches due to size, // but that's overkill until we have a decent population of tests. navigateThroughAllDemos(AllButIgnoredDemos) } private fun navigateThroughAllDemos(root: DemoCategory, fastForwardClock: Boolean = false) { // Keep track of each demo we visit. val visitedDemos = mutableListOf<Demo>() // Visit all demos. root.visitDemos( visitedDemos = visitedDemos, path = listOf(root), fastForwardClock = fastForwardClock ) // Ensure that we visited all the demos we expected to, in the order we expected to. assertThat(visitedDemos).isEqualTo(root.allDemos()) } /** * DFS traversal of each demo in a [DemoCategory] using [Demo.visit] * * @param path The path of categories that leads to this demo */ private fun DemoCategory.visitDemos( visitedDemos: MutableList<Demo>, path: List<DemoCategory>, fastForwardClock: Boolean ) { demos.forEach { demo -> visitedDemos.add(demo) demo.visit(visitedDemos, path, fastForwardClock) } } /** * Visits a [Demo], and then navigates back up to the [DemoCategory] it was inside. * * If this [Demo] is a [DemoCategory], this will visit sub-[Demo]s first before continuing * in the current category. * * @param path The path of categories that leads to this demo */ private fun Demo.visit( visitedDemos: MutableList<Demo>, path: List<DemoCategory>, fastForwardClock: Boolean ) { if (fastForwardClock) { // Skip through the enter animation of the list screen fastForwardClock() } rule.onNode(hasScrollToNodeAction()) .performScrollToNode(hasText(title) and hasClickAction()) rule.onNode(hasText(title) and hasClickAction()).performClick() if (this is DemoCategory) { visitDemos(visitedDemos, path + this, fastForwardClock) } if (fastForwardClock) { // Skip through the enter animation of the visited demo fastForwardClock() } rule.waitForIdle() while (rule.onAllNodes(isDialog()).isNotEmpty()) { Espresso.pressBack() rule.waitForIdle() } clearFocusFromDemo() rule.waitForIdle() Espresso.pressBack() rule.waitForIdle() if (fastForwardClock) { // Pump press back fastForwardClock(2000) } } private fun fastForwardClock(millis: Long = 5000) { rule.waitForIdle() rule.mainClock.advanceTimeBy(millis) } private fun SemanticsNodeInteractionCollection.isNotEmpty(): Boolean { return fetchSemanticsNodes(atLeastOneRootRequired = false).isNotEmpty() } private fun clearFocusFromDemo() { with(rule.activity) { if (hostView.hasFocus()) { if (hostView.isFocused) { // One of the Compose components has focus. focusManager.clearFocus(force = true) } else { // A child view has focus. (View interop scenario). // We could also use hostViewGroup.focusedChild?.clearFocus(), but the // interop views might end up being focused if one of them is marked as // focusedByDefault. So we clear focus by requesting focus on the owner. rule.runOnUiThread { hostView.requestFocus() } } } } } } private val AllButIgnoredDemos = WearComposeDemos.filter { path, demo -> demo.navigationTitle(path) !in ignoredDemos } private fun Demo.navigationTitle(path: List<DemoCategory>): String { return path.plus(this).navigationTitle } private val List<Demo>.navigationTitle: String get() = if (size == 1) first().title else drop(1).joinToString(" > ") /** * Trims the tree of [Demo]s represented by this [DemoCategory] by cutting all leave demos for * which the [predicate] returns `false` and recursively removing all empty categories as a result. */ private fun DemoCategory.filter( path: List<DemoCategory> = emptyList(), predicate: (path: List<DemoCategory>, demo: Demo) -> Boolean ): DemoCategory { val newPath = path + this return DemoCategory( title, demos.mapNotNull { when (it) { is DemoCategory -> { it.filter(newPath, predicate).let { if (it.demos.isEmpty()) null else it } } else -> { if (predicate(newPath, it)) it else null } } } ) } /** * Flattened recursive DFS [List] of every demo in [this]. */ fun DemoCategory.allDemos(): List<Demo> { val allDemos = mutableListOf<Demo>() fun DemoCategory.addAllDemos() { demos.forEach { demo -> allDemos += demo if (demo is DemoCategory) { demo.addAllDemos() } } } addAllDemos() return allDemos }
apache-2.0
4a4f676a76e1ea34d50638dee5257197
32.347032
99
0.650828
4.666454
false
true
false
false
GunoH/intellij-community
plugins/kotlin/features-trainer/src/org/jetbrains/kotlin/training/ift/lesson/basic/KotlinSelectLesson.kt
4
1213
// 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.training.ift.lesson.basic import training.dsl.LessonSample import training.dsl.parseLessonSample import training.learn.lesson.general.NewSelectLesson class KotlinSelectLesson : NewSelectLesson() { override val selectArgument = "\"$selectString\"" override val selectCall = """someMethod("$firstString", $selectArgument, "$thirdString")""" override val numberOfSelectsForWholeCall = 2 override val sample: LessonSample = parseLessonSample(""" abstract class Scratch { abstract fun someMethod(string1: String, string2: String, string3: String) fun exampleMethod(condition: Boolean) { <select id=1>if (condition) { System.err.println("$beginString") $selectCall System.err.println("$endString") }</select> } } """.trimIndent()) override val selectIf = sample.getPosition(1).selection!!.let { sample.text.substring(it.first, it.second) } }
apache-2.0
cac93af936ec2695f65c3bb640a60fb7
40.862069
158
0.659522
4.738281
false
false
false
false
GunoH/intellij-community
plugins/kotlin/base/analysis/src/org/jetbrains/kotlin/idea/search/ideaExtensions/internalSearchUtils.kt
1
1888
/* * Copyright 2010-2022 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.search.ideaExtensions import com.intellij.psi.PsiClass import com.intellij.psi.PsiMethod import com.intellij.psi.PsiNamedElement import com.intellij.psi.search.searches.ClassInheritorsSearch import com.intellij.psi.search.searches.OverridingMethodsSearch import com.intellij.util.Processor import org.jetbrains.kotlin.asJava.classes.KtLightClass import org.jetbrains.kotlin.asJava.elements.KtLightMethod import org.jetbrains.kotlin.idea.search.KotlinSearchUsagesSupport import com.intellij.openapi.application.runReadAction fun findOverridingMethodsInKotlin( parentClass: PsiClass, baseElement: PsiNamedElement, parameters: OverridingMethodsSearch.SearchParameters, consumer: Processor<in PsiMethod>, ): Boolean = ClassInheritorsSearch.search(parentClass, parameters.scope, true).forEach(Processor { inheritor: PsiClass -> val found = runReadAction { findOverridingMethod(inheritor, baseElement) } found == null || (consumer.process(found) && parameters.isCheckDeep) }) private fun findOverridingMethod(inheritor: PsiClass, baseElement: PsiNamedElement): PsiMethod? { // Leave Java classes search to JavaOverridingMethodsSearcher if (inheritor !is KtLightClass) return null val name = baseElement.name val methodsByName = inheritor.findMethodsByName(name, false) for (lightMethodCandidate in methodsByName) { val kotlinOrigin = (lightMethodCandidate as? KtLightMethod)?.kotlinOrigin ?: continue if (KotlinSearchUsagesSupport.getInstance(inheritor.project).isCallableOverride(kotlinOrigin, baseElement)) { return lightMethodCandidate } } return null }
apache-2.0
028f1437b021b50a7418e09ec20cfba0
41.931818
121
0.790254
4.955381
false
false
false
false
GunoH/intellij-community
plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/quickfix/fixes/ImportQuickFix.kt
5
10935
// 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.quickfix.fixes import com.intellij.codeInsight.daemon.DaemonCodeAnalyzerSettings import com.intellij.codeInsight.daemon.QuickFixBundle import com.intellij.codeInsight.daemon.impl.ShowAutoImportPass import com.intellij.codeInsight.hint.HintManager import com.intellij.codeInsight.hint.QuestionAction import com.intellij.codeInspection.HintAction import com.intellij.lang.jvm.JvmModifier import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.ui.popup.JBPopup import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.psi.* import com.intellij.psi.util.PsiModificationTracker import com.intellij.psi.util.parentsOfType import org.jetbrains.kotlin.analysis.api.KtAnalysisSession import org.jetbrains.kotlin.analysis.api.fir.diagnostics.KtFirDiagnostic import org.jetbrains.kotlin.analysis.api.fir.utils.addImportToFile import org.jetbrains.kotlin.analysis.api.symbols.KtCallableSymbol import org.jetbrains.kotlin.analysis.api.symbols.KtNamedClassOrObjectSymbol import org.jetbrains.kotlin.analysis.api.symbols.KtSymbol import org.jetbrains.kotlin.analysis.api.symbols.markers.KtSymbolWithVisibility import org.jetbrains.kotlin.idea.base.analysis.api.utils.KtSymbolFromIndexProvider import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.codeinsight.api.applicators.fixes.diagnosticFixFactory import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.QuickFixActionBase import org.jetbrains.kotlin.idea.util.application.executeWriteCommand import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.KtPsiUtil.isSelectorInQualified import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject import org.jetbrains.kotlin.psi.psiUtil.unwrapNullability internal class ImportQuickFix( element: KtElement, private val importCandidates: List<FqName> ) : QuickFixActionBase<KtElement>(element), HintAction { init { require(importCandidates.isNotEmpty()) } override fun getText(): String = KotlinBundle.message("fix.import") override fun getFamilyName(): String = KotlinBundle.message("fix.import") override fun invoke(project: Project, editor: Editor, file: PsiFile) { if (file !is KtFile) return createAddImportAction(project, editor, file).execute() } private fun createAddImportAction(project: Project, editor: Editor, file: KtFile): QuestionAction { return ImportQuestionAction(project, editor, file, importCandidates) } override fun showHint(editor: Editor): Boolean { val element = element ?: return false if ( ApplicationManager.getApplication().isHeadlessEnvironment || HintManager.getInstance().hasShownHintsThatWillHideByOtherHint(true) ) { return false } val file = element.containingKtFile val project = file.project val elementRange = element.textRange val autoImportHintText = KotlinBundle.message("fix.import.question", importCandidates.first().asString()) HintManager.getInstance().showQuestionHint( editor, autoImportHintText, elementRange.startOffset, elementRange.endOffset, createAddImportAction(project, editor, file) ) return true } override fun fixSilently(editor: Editor): Boolean { val element = element ?: return false val file = element.containingKtFile if (!DaemonCodeAnalyzerSettings.getInstance().isImportHintEnabled) return false if (!ShowAutoImportPass.isAddUnambiguousImportsOnTheFlyEnabled(file)) return false val project = file.project val addImportAction = createAddImportAction(project, editor, file) if (importCandidates.size == 1) { addImportAction.execute() return true } else { return false } } private val modificationCountOnCreate: Long = PsiModificationTracker.getInstance(element.project).modificationCount /** * This is a safe-guard against showing hint after the quickfix have been applied. * * Inspired by the org.jetbrains.kotlin.idea.quickfix.ImportFixBase.isOutdated */ private fun isOutdated(project: Project): Boolean { return modificationCountOnCreate != PsiModificationTracker.getInstance(project).modificationCount } override fun isAvailableImpl(project: Project, editor: Editor?, file: PsiFile): Boolean { return super.isAvailableImpl(project, editor, file) && !isOutdated(project) } private class ImportQuestionAction( private val project: Project, private val editor: Editor, private val file: KtFile, private val importCandidates: List<FqName> ) : QuestionAction { init { require(importCandidates.isNotEmpty()) } override fun execute(): Boolean { when (importCandidates.size) { 1 -> { addImport(importCandidates.single()) return true } 0 -> { return false } else -> { if (ApplicationManager.getApplication().isUnitTestMode) return false createImportSelectorPopup().showInBestPositionFor(editor) return true } } } private fun createImportSelectorPopup(): JBPopup { return JBPopupFactory.getInstance() .createPopupChooserBuilder(importCandidates) .setTitle(KotlinBundle.message("action.add.import.chooser.title")) .setItemChosenCallback { selectedValue: FqName -> addImport(selectedValue) } .createPopup() } private fun addImport(nameToImport: FqName) { project.executeWriteCommand(QuickFixBundle.message("add.import")) { addImportToFile(project, file, nameToImport) } } } internal companion object { val FACTORY = diagnosticFixFactory(KtFirDiagnostic.UnresolvedReference::class) { diagnostic -> val element = diagnostic.psi val project = element.project val indexProvider = KtSymbolFromIndexProvider(project) val quickFix = when (element) { is KtTypeReference -> createImportTypeFix(indexProvider, element) is KtNameReferenceExpression -> createImportNameFix(indexProvider, element) else -> null } listOfNotNull(quickFix) } private fun KtAnalysisSession.createImportNameFix( indexProvider: KtSymbolFromIndexProvider, element: KtNameReferenceExpression ): ImportQuickFix? { if (isSelectorInQualified(element)) return null val firFile = element.containingKtFile.getFileSymbol() val unresolvedName = element.getReferencedNameAsName() val isVisible: (KtSymbol) -> Boolean = { it !is KtSymbolWithVisibility || isVisible(it, firFile, null, element) } val callableCandidates = collectCallableCandidates(indexProvider, unresolvedName, isVisible) val typeCandidates = collectTypesCandidates(indexProvider, unresolvedName, isVisible) val importCandidates = (callableCandidates + typeCandidates).distinct() if (importCandidates.isEmpty()) return null return ImportQuickFix(element, importCandidates) } private fun KtAnalysisSession.createImportTypeFix( indexProvider: KtSymbolFromIndexProvider, element: KtTypeReference ): ImportQuickFix? { val firFile = element.containingKtFile.getFileSymbol() val unresolvedName = element.typeName ?: return null val isVisible: (KtNamedClassOrObjectSymbol) -> Boolean = { isVisible(it, firFile, null, element) } val acceptableClasses = collectTypesCandidates(indexProvider, unresolvedName, isVisible).distinct() if (acceptableClasses.isEmpty()) return null return ImportQuickFix(element, acceptableClasses) } private fun KtAnalysisSession.collectCallableCandidates( indexProvider: KtSymbolFromIndexProvider, unresolvedName: Name, isVisible: (KtCallableSymbol) -> Boolean ): List<FqName> { val callablesCandidates = indexProvider.getKotlinCallableSymbolsByName(unresolvedName) { it.canBeImported() } + indexProvider.getJavaCallableSymbolsByName(unresolvedName) { it.canBeImported() } return callablesCandidates .filter(isVisible) .mapNotNull { it.callableIdIfNonLocal?.asSingleFqName() } .toList() } private fun KtAnalysisSession.collectTypesCandidates( indexProvider: KtSymbolFromIndexProvider, unresolvedName: Name, isVisible: (KtNamedClassOrObjectSymbol) -> Boolean ): List<FqName> { val classesCandidates = indexProvider.getKotlinClassesByName(unresolvedName) { it.canBeImported() } + indexProvider.getJavaClassesByName(unresolvedName) { it.canBeImported() } return classesCandidates .filter(isVisible) .mapNotNull { it.classIdIfNonLocal?.asSingleFqName() } .toList() } } } private fun PsiMember.canBeImported(): Boolean { return when (this) { is PsiClass -> qualifiedName != null && (containingClass == null || hasModifier(JvmModifier.STATIC)) is PsiField, is PsiMethod -> hasModifier(JvmModifier.STATIC) && containingClass?.qualifiedName != null else -> false } } private fun KtDeclaration.canBeImported(): Boolean { return when (this) { is KtProperty -> isTopLevel || containingClassOrObject is KtObjectDeclaration is KtNamedFunction -> isTopLevel || containingClassOrObject is KtObjectDeclaration is KtClassOrObject -> getClassId() != null && parentsOfType<KtClassOrObject>(withSelf = true).none { it.hasModifier(KtTokens.INNER_KEYWORD) } else -> false } } private val KtTypeReference.typeName: Name? get() { val userType = typeElement?.unwrapNullability() as? KtUserType return userType?.referencedName?.let(Name::identifier) }
apache-2.0
56cd8be402adde2576dcf5871c81e85c
39.058608
131
0.682579
5.564885
false
false
false
false
feelfreelinux/WykopMobilny
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/widgets/link/related/RelatedWidget.kt
1
5035
package io.github.feelfreelinux.wykopmobilny.ui.widgets.link.related import android.content.Context import android.util.AttributeSet import android.util.TypedValue import android.view.View import androidx.core.app.ShareCompat import androidx.core.content.ContextCompat import io.github.feelfreelinux.wykopmobilny.R import io.github.feelfreelinux.wykopmobilny.models.dataclass.Related import io.github.feelfreelinux.wykopmobilny.ui.dialogs.showExceptionDialog import io.github.feelfreelinux.wykopmobilny.ui.modules.profile.ProfileActivity import io.github.feelfreelinux.wykopmobilny.utils.api.getGroupColor import io.github.feelfreelinux.wykopmobilny.utils.getActivityContext import io.github.feelfreelinux.wykopmobilny.utils.isVisible import io.github.feelfreelinux.wykopmobilny.utils.usermanager.UserManagerApi import kotlinx.android.synthetic.main.link_related_layout.view.* class RelatedWidget(context: Context, attrs: AttributeSet) : androidx.cardview.widget.CardView(context, attrs), RelatedWidgetView { init { View.inflate(context, R.layout.link_related_layout, this) isClickable = true isFocusable = true val typedValue = TypedValue() getActivityContext()!!.theme?.resolveAttribute(R.attr.itemBackgroundColorStatelist, typedValue, true) setBackgroundResource(typedValue.resourceId) } val url: String get() = relatedItem.url private lateinit var presenter: RelatedWidgetPresenter private lateinit var relatedItem: Related fun setRelatedData(related: Related, userManagerApi: UserManagerApi, relatedWidgetPresenter: RelatedWidgetPresenter) { relatedItem = related presenter = relatedWidgetPresenter title.text = related.title urlTextView.text = related.url presenter.subscribe(this) presenter.relatedId = relatedItem.id setOnClickListener { presenter.handleLink(related.url) } shareTextView.setOnClickListener { shareUrl() } setVoteCount(related.voteCount) authorHeaderView.isVisible = related.author != null userNameTextView.isVisible = related.author != null related.author?.apply { userNameTextView.text = nick userNameTextView.setOnClickListener { openProfile() } authorHeaderView.setOnClickListener { openProfile() } authorHeaderView.setAuthor(this) userNameTextView.setTextColor(context.getGroupColor(group)) } setupButtons() plusButton.setup(userManagerApi) minusButton.setup(userManagerApi) } private fun openProfile() { val context = getActivityContext()!! context.startActivity(ProfileActivity.createIntent(context, relatedItem.author!!.nick)) } private fun setupButtons() { when (relatedItem.userVote) { 1 -> { plusButton.isButtonSelected = true plusButton.isEnabled = false minusButton.isButtonSelected = false minusButton.isEnabled = true minusButton.voteListener = { presenter.voteDown() } } 0 -> { plusButton.isButtonSelected = false plusButton.isEnabled = true plusButton.voteListener = { presenter.voteUp() } minusButton.isButtonSelected = false minusButton.isEnabled = true minusButton.voteListener = { presenter.voteDown() } } -1 -> { minusButton.isButtonSelected = true minusButton.isEnabled = false plusButton.isButtonSelected = false plusButton.isEnabled = true plusButton.voteListener = { presenter.voteUp() } } } } override fun markUnvoted() { relatedItem.userVote = -1 setupButtons() } override fun markVoted() { relatedItem.userVote = 1 setupButtons() } override fun setVoteCount(voteCount: Int) { relatedItem.voteCount = voteCount voteCountTextView.text = if (relatedItem.voteCount > 0) "+${relatedItem.voteCount}" else "${relatedItem.voteCount}" if (relatedItem.voteCount > 0) { voteCountTextView.setTextColor(ContextCompat.getColor(context, R.color.plusPressedColor)) } else if (relatedItem.voteCount < 0) { voteCountTextView.setTextColor(ContextCompat.getColor(context, R.color.minusPressedColor)) } } override fun showErrorDialog(e: Throwable) = context.showExceptionDialog(e) private fun shareUrl() { ShareCompat.IntentBuilder .from(getActivityContext()!!) .setType("text/plain") .setChooserTitle(R.string.share) .setText(url) .startChooser() } }
mit
fb2fdcbb34f5581bcdbf8186bb0579e7
35.492754
123
0.649652
5.437365
false
false
false
false
GunoH/intellij-community
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/SecondSampleEntityImpl.kt
2
6287
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.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.UsedClassesCollector import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList import com.intellij.workspaceModel.storage.url.VirtualFileUrl import java.util.* import java.util.UUID import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Child @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class SecondSampleEntityImpl(val dataSource: SecondSampleEntityData) : SecondSampleEntity, WorkspaceEntityBase() { companion object { val connections = listOf<ConnectionId>( ) } override val intProperty: Int get() = dataSource.intProperty override val entitySource: EntitySource get() = dataSource.entitySource override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(result: SecondSampleEntityData?) : ModifiableWorkspaceEntityBase<SecondSampleEntity, SecondSampleEntityData>( result), SecondSampleEntity.Builder { constructor() : this(SecondSampleEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity SecondSampleEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // After adding entity data to the builder, we need to unbind it and move the control over entity data to builder // Builder may switch to snapshot at any moment and lock entity data to modification this.currentEntityData = null // 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().isEntitySourceInitialized()) { error("Field WorkspaceEntity#entitySource should be initialized") } } override fun connectionIdList(): List<ConnectionId> { return connections } // Relabeling code, move information from dataSource to this builder override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) { dataSource as SecondSampleEntity if (this.entitySource != dataSource.entitySource) this.entitySource = dataSource.entitySource if (this.intProperty != dataSource.intProperty) this.intProperty = dataSource.intProperty if (parents != null) { } } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData(true).entitySource = value changedProperty.add("entitySource") } override var intProperty: Int get() = getEntityData().intProperty set(value) { checkModificationAllowed() getEntityData(true).intProperty = value changedProperty.add("intProperty") } override fun getEntityClass(): Class<SecondSampleEntity> = SecondSampleEntity::class.java } } class SecondSampleEntityData : WorkspaceEntityData<SecondSampleEntity>() { var intProperty: Int = 0 override fun wrapAsModifiable(diff: MutableEntityStorage): WorkspaceEntity.Builder<SecondSampleEntity> { val modifiable = SecondSampleEntityImpl.Builder(null) modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() return modifiable } override fun createEntity(snapshot: EntityStorage): SecondSampleEntity { return getCached(snapshot) { val entity = SecondSampleEntityImpl(this) entity.snapshot = snapshot entity.id = createEntityId() entity } } override fun getEntityInterface(): Class<out WorkspaceEntity> { return SecondSampleEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity { return SecondSampleEntity(intProperty, entitySource) { } } override fun getRequiredParents(): List<Class<out WorkspaceEntity>> { val res = mutableListOf<Class<out WorkspaceEntity>>() return res } override fun equals(other: Any?): Boolean { if (other == null) return false if (this.javaClass != other.javaClass) return false other as SecondSampleEntityData if (this.entitySource != other.entitySource) return false if (this.intProperty != other.intProperty) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this.javaClass != other.javaClass) return false other as SecondSampleEntityData if (this.intProperty != other.intProperty) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + intProperty.hashCode() return result } override fun hashCodeIgnoringEntitySource(): Int { var result = javaClass.hashCode() result = 31 * result + intProperty.hashCode() return result } override fun collectClassUsagesData(collector: UsedClassesCollector) { collector.sameForAllEntities = true } }
apache-2.0
00497536f71aa5a3631190798343e8d8
31.744792
125
0.741053
5.424504
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/uast/uast-kotlin/tests/testData/PropertyWithAnnotation.kt
3
204
annotation class TestAnnotation @TestAnnotation val prop1: Int = 0 @get:TestAnnotation val prop2: Int get() = 0 @set:TestAnnotation var prop3: Int = 0 get() = 0 set(value) { field = value }
apache-2.0
adc6d016b9ca3655f095aba7b35097d8
14.769231
32
0.676471
3.290323
false
true
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/structuralsearch/callExpression/constrNamedArgsCall.kt
4
324
class A(val b: Boolean, val c: Int, val d: Int) fun d() { println(<warning descr="SSR">A(true, 0, 1)</warning>) println(<warning descr="SSR">A(b = true, c = 0, d = 1)</warning>) println(<warning descr="SSR">A(c = 0, b = true, d = 1)</warning>) println(<warning descr="SSR">A(true, d = 1, c = 0)</warning>) }
apache-2.0
856bceff1325935bee4d172ddffac296
39.625
69
0.57716
2.842105
false
false
false
false
smmribeiro/intellij-community
platform/credential-store/src/keePass/masterKey.kt
9
5605
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.credentialStore.keePass import com.intellij.credentialStore.* import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream import com.intellij.util.io.delete import com.intellij.util.io.readBytes import com.intellij.util.io.safeOutputStream import org.yaml.snakeyaml.composer.Composer import org.yaml.snakeyaml.nodes.* import org.yaml.snakeyaml.parser.ParserImpl import org.yaml.snakeyaml.reader.StreamReader import org.yaml.snakeyaml.resolver.Resolver import java.nio.file.NoSuchFileException import java.nio.file.Path import java.util.* internal const val MASTER_KEY_FILE_NAME = "c.pwd" private const val OLD_MASTER_PASSWORD_FILE_NAME = "pdb.pwd" class MasterKey(value: ByteArray, // is password auto-generated, used to force set master password if database file location changed val isAutoGenerated: Boolean, val encryptionSpec: EncryptionSpec) { var value: ByteArray? = value /** * Clear byte array to avoid sensitive data in memory */ fun clear() { value?.fill(0) value = null } } class MasterKeyFileStorage(val passwordFile: Path) { fun load(): ByteArray? { var data: ByteArray var isOld = false try { data = passwordFile.readBytes() } catch (e: NoSuchFileException) { try { data = passwordFile.parent.resolve(OLD_MASTER_PASSWORD_FILE_NAME).readBytes() } catch (e: NoSuchFileException) { return null } isOld = true } try { val decrypted: ByteArray if (isOld) { decrypted = createBuiltInOrCrypt32EncryptionSupport(SystemInfo.isWindows).decrypt(data) data.fill(0) } else { decrypted = decryptMasterKey(data) ?: return null } data.fill(0) return decrypted } catch (e: Exception) { LOG.warn("Cannot decrypt master key, file content:\n${if (isOld) Base64.getEncoder().encodeToString(data) else data.toString(Charsets.UTF_8)}", e) return null } } private fun decryptMasterKey(data: ByteArray): ByteArray? { var encryptionType: EncryptionType? = null var value: ByteArray? = null for (node in createMasterKeyReader(data)) { val keyNode = node.keyNode val valueNode = node.valueNode if (keyNode is ScalarNode && valueNode is ScalarNode) { val propertyValue = valueNode.value ?: continue when (keyNode.value) { "encryption" -> encryptionType = EncryptionType.valueOf(propertyValue.toUpperCase()) "value" -> value = Base64.getDecoder().decode(propertyValue) } } } if (encryptionType == null) { LOG.error("encryption type not specified in $passwordFile, default one will be used (file content:\n${data.toString(Charsets.UTF_8)})") encryptionType = getDefaultEncryptionType() } if (value == null) { LOG.error("password not specified in $passwordFile, automatically generated will be used (file content:\n${data.toString(Charsets.UTF_8)})") return null } // PGP key id is not stored in master key file because PGP encoded data already contains recipient id and no need to explicitly specify it, // so, this EncryptionSupport MUST be used only for decryption since pgpKeyId is set to null. return createEncryptionSupport(EncryptionSpec(encryptionType, pgpKeyId = null)).decrypt(value) } // passed key will be cleared fun save(key: MasterKey?) { if (key == null) { passwordFile.delete() return } val encodedValue = Base64.getEncoder().encode(createEncryptionSupport(key.encryptionSpec).encrypt(key.value!!)) key.clear() val out = BufferExposingByteArrayOutputStream() val encryptionType = key.encryptionSpec.type out.writer().use { it.append("encryption: ").append(encryptionType.name).append('\n') it.append("isAutoGenerated: ").append(key.isAutoGenerated.toString()).append('\n') it.append("value: !!binary ") } passwordFile.safeOutputStream().use { it.write(out.internalBuffer, 0, out.size()) it.write(encodedValue) encodedValue.fill(0) } } private fun readMasterKeyIsAutoGeneratedMetadata(data: ByteArray): Boolean { var isAutoGenerated = true for (node in createMasterKeyReader(data)) { val keyNode = node.keyNode val valueNode = node.valueNode if (keyNode is ScalarNode && valueNode is ScalarNode) { val propertyValue = valueNode.value ?: continue when (keyNode.value) { "isAutoGenerated" -> isAutoGenerated = propertyValue.toBoolean() || propertyValue == "yes" } } } return isAutoGenerated } fun isAutoGenerated(): Boolean { try { return readMasterKeyIsAutoGeneratedMetadata(passwordFile.readBytes()) } catch (e: NoSuchFileException) { // true because on save will be generated return true } } } private fun createMasterKeyReader(data: ByteArray): List<NodeTuple> { val composer = Composer(ParserImpl(StreamReader(data.inputStream().reader())), object : Resolver() { override fun resolve(kind: NodeId, value: String?, implicit: Boolean): Tag { return when (kind) { NodeId.scalar -> Tag.STR else -> super.resolve(kind, value, implicit) } } }) return (composer.singleNode as? MappingNode)?.value ?: emptyList() }
apache-2.0
ee02452b5a6b5ed494ff0cd57c168d99
33.598765
152
0.67975
4.409913
false
false
false
false
gatling/gatling
src/docs/content/reference/current/http/protocol/code/HttpProtocolSampleKotlin.kt
1
7694
/* * Copyright 2011-2021 GatlingCorp (https://gatling.io) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import io.gatling.javaapi.core.CoreDsl.* import io.gatling.javaapi.core.Simulation import io.gatling.javaapi.http.HttpDsl.* import org.apache.commons.codec.digest.DigestUtils import java.util.* import javax.net.ssl.KeyManagerFactory class HttpProtocolSampleKotlin: Simulation() { init { //#bootstrapping val httpProtocol = http.baseUrl("https://gatling.io") val scn = scenario("Scenario") // etc... setUp(scn.injectOpen(atOnceUsers(1)).protocols(httpProtocol)) //#bootstrapping } init { //#baseUrl val httpProtocol = http.baseUrl("https://gatling.io") val scn = scenario("Scenario") // will make a request to "https://gatling.io/docs" .exec( http("Relative").get("/docs/") ) // will make a request to "https://github.com/gatling/gatling" .exec( http("Absolute").get("https://github.com/gatling/gatling") ) setUp(scn.injectOpen(atOnceUsers(1)).protocols(httpProtocol)) //#baseUrl } init { //#baseUrls http.baseUrls( "https://gatling.io", "https://github.com" ) //#baseUrls //#warmUp // change the warm up URL to https://www.google.com http.warmUp("https://www.google.com") // disable warm up http.disableWarmUp() //#warmUp //#maxConnectionsPerHost http.maxConnectionsPerHost(10) //#maxConnectionsPerHost //#shareConnections http.shareConnections() //#shareConnections //#enableHttp2 http.enableHttp2() //#enableHttp2 //#http2PriorKnowledge http .enableHttp2() .http2PriorKnowledge( mapOf( "www.google.com" to true, "gatling.io" to false ) ) //#http2PriorKnowledge //#dns-async // use hosts' configured DNS servers on Linux and MacOS // use Google's DNS servers on Windows http.asyncNameResolution() // force DNS servers http.asyncNameResolution("8.8.8.8") // instead of having a global DNS resolver // have each virtual user to have its own (hence own cache, own UDP requests) // only effective with asyncNameResolution http .asyncNameResolution() .perUserNameResolution() //#dns-async //#hostNameAliases http .hostNameAliases(mapOf("gatling.io" to listOf("192.168.0.1", "192.168.0.2"))) //#hostNameAliases //#virtualHost // with a static value http.virtualHost("virtualHost") // with a Gatling EL string http.virtualHost("#{virtualHost}") // with a function http.virtualHost { session -> session.getString("virtualHost") } //#virtualHost //#localAddress http.localAddress("localAddress") http.localAddresses("localAddress1", "localAddress2") // automatically discover all bindable local addresses http.useAllLocalAddresses() // automatically discover all bindable local addresses // matching one of the Java Regex patterns http.useAllLocalAddressesMatching("pattern1", "pattern2") //#localAddress //#perUserKeyManagerFactory http.perUserKeyManagerFactory { userId -> null as KeyManagerFactory? } //#perUserKeyManagerFactory //#disableAutoReferer http.disableAutoReferer() //#disableAutoReferer //#disableCaching http.disableCaching() //#disableCaching //#disableUrlEncoding http.disableUrlEncoding() //#disableUrlEncoding //#silentUri // make all requests whose url matches the provided Java Regex pattern silent http.silentUri("https://myCDN/.*") // make all resource requests silent http.silentResources() //#silentUri //#headers http // with a static header value .header("foo", "bar") // with a Gatling EL string header value .header("foo", "#{headerValue}") // with a function value .header("foo") { session -> session.getString("headerValue") } .headers(mapOf("foo" to "bar")) //#headers //#headers-built-ins // all those also accept a Gatling EL string or a function parameter http .acceptHeader("value") .acceptCharsetHeader("value") .acceptEncodingHeader("value") .acceptLanguageHeader("value") .authorizationHeader("value") .connectionHeader("value") .contentTypeHeader("value") .doNotTrackHeader("value") .originHeader("value") .userAgentHeader("value") .upgradeInsecureRequestsHeader("value") //#headers-built-ins //#sign http.sign { request -> // import org.apache.commons.codec.digest.DigestUtils val md5 = DigestUtils.md5Hex(request.body.bytes) request.headers.add("X-MD5", md5) } // or with access to the Session http.sign { request, session -> } //#sign //#sign-oauth1 // with static values http.signWithOAuth1( "consumerKey", "clientSharedSecret", "token", "tokenSecret" ) // with functions http.signWithOAuth1( { session -> session.getString("consumerKey") }, { session -> session.getString("clientSharedSecret") }, { session -> session.getString("token") } ) { session -> session.getString("tokenSecret") } //#sign-oauth1 //#authorization // with static values http.basicAuth("username", "password") // with Gatling El strings http.basicAuth("#{username}", "#{password}") // with functions http.basicAuth({ session -> session.getString("username") }) { session -> session.getString("password") } // with static values http.digestAuth("username", "password") // with Gatling El strings http.digestAuth("#{username}", "#{password}") // with functions http.digestAuth({ session -> session.getString("username") }) { session -> session.getString("password") } //#authorization //#disableFollowRedirect http.disableFollowRedirect() //#disableFollowRedirect //#redirectNamingStrategy http.redirectNamingStrategy { uri, originalRequestName, redirectCount -> "redirectedRequestName" } //#redirectNamingStrategy //#transformResponse http.transformResponse { response, session -> response } //#transformResponse //#inferHtmlResources // fetch only resources matching one of the patterns in the allow list http.inferHtmlResources(AllowList("pattern1", "pattern2")) // fetch all resources except those matching one of the patterns in the deny list http.inferHtmlResources(DenyList("pattern1", "pattern2")) // fetch only resources matching one of the patterns in the allow list // but not matching one of the patterns in the deny list http.inferHtmlResources(AllowList("pattern1", "pattern2"), DenyList("pattern3", "pattern4")) //#inferHtmlResources //#nameInferredHtmlResources // (default): name requests after the resource's url tail (after last `/`) http.nameInferredHtmlResourcesAfterUrlTail() // name requests after the resource's path http.nameInferredHtmlResourcesAfterPath() // name requests after the resource's absolute url http.nameInferredHtmlResourcesAfterAbsoluteUrl() // name requests after the resource's relative url http.nameInferredHtmlResourcesAfterRelativeUrl() // name requests after the resource's last path element http.nameInferredHtmlResourcesAfterLastPathElement() // name requests with a custom strategy http.nameInferredHtmlResources { uri -> "name" } //#nameInferredHtmlResources //#proxy http.proxy( Proxy("myHttpProxyHost", 8080) .httpsPort(8143) .credentials("myUsername", "myPassword") ) http.proxy( Proxy("mySocks4ProxyHost", 8080) .socks4() ) http.proxy( Proxy("mySocks5ProxyHost", 8080) .httpsPort(8143) .socks5() ) //#proxy //#noProxyFor http .proxy(Proxy("myProxyHost", 8080)) .noProxyFor("www.github.com", "gatling.io") //#noProxyFor } }
apache-2.0
ec3c998c12216b2c6c936e26a46da9a5
25.349315
106
0.741487
3.86245
false
false
false
false
leesocrates/remind
mvvmdemo/src/main/java/com/lee/socrates/mvvmdemo/bluetooth/BluetoothViewModel.kt
1
9672
package com.lee.socrates.mvvmdemo.bluetooth import android.Manifest import android.app.Activity import android.databinding.ObservableField import android.view.View import android.bluetooth.BluetoothAdapter import android.bluetooth.BluetoothManager import android.content.Context import android.bluetooth.BluetoothDevice import android.util.Log import java.util.* import android.bluetooth.BluetoothGattCharacteristic import android.bluetooth.BluetoothGatt import android.content.Intent import android.bluetooth.BluetoothGattDescriptor import android.bluetooth.BluetoothGattService import android.bluetooth.BluetoothGattCallback import android.content.pm.PackageManager import android.os.Build import android.support.v4.app.ActivityCompat import android.text.TextUtils import kotlin.experimental.and import android.support.v4.app.ActivityCompat.startActivityForResult import android.support.v4.content.ContextCompat /** * Created by lee on 2018/3/20. */ public class BluetoothViewModel { private val TAG = this.javaClass.simpleName private val bleAdapter: BluetoothAdapter? = BluetoothAdapter.getDefaultAdapter() val info = ObservableField<String>() private lateinit var mContext: Context private var bleGatt: BluetoothGatt? = null private var bleScanCallback: BluetoothAdapter.LeScanCallback? = null private lateinit var mNavigator: BlueToothNavigator fun init(context: Context, navigator: BlueToothNavigator) { mContext = context mNavigator = navigator } fun handleActivityResult(requestCode: Int, resultCode: Int) { if (requestCode == BlueToothActivity.REQUEST_ENABLE_BT) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { mNavigator.requestLocationPermission() return } } startScan() } } fun handleRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) { if (requestCode == BlueToothActivity.MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION) { if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { startScan() } } } fun startSearch(view: View) { Log.e(TAG, "startSearch ...") // 检测蓝牙 if (!check()) { if (bleAdapter != null && !bleAdapter.isEnabled) { mNavigator.requestOpenBlueTooth() } return } startScan() } private fun startScan() { bleScanCallback = BleScanCallback() // 回调接口 bleAdapter != null && bleAdapter.startLeScan(bleScanCallback) // var pairedDevices: Set<BluetoothDevice>? = bleAdapter?.bondedDevices // if(pairedDevices!=null && pairedDevices.isNotEmpty()){ // for (device in pairedDevices) { // Log.e(TAG, "found device name : " + device.name + " address : " + device.address) // } // } } private fun check(): Boolean { return null != bleAdapter && bleAdapter.isEnabled && !bleAdapter.isDiscovering } // 实现扫描回调接口 private inner class BleScanCallback : BluetoothAdapter.LeScanCallback { // 扫描到新设备时,会回调该接口。可以将新设备显示在ui中,看具体需求 override fun onLeScan(device: BluetoothDevice, rssi: Int, scanRecord: ByteArray) { if (device.name!=null && device.name.isNotEmpty()) { Log.e(TAG, "found device name : " + device.name + " address : " + device.address) } else{ Log.e(TAG, "found device name : " + device.name + " address : " + device.address) bleAdapter?.stopLeScan(bleScanCallback) } } } // 连接蓝牙设备,device为之前扫描得到的 fun connect(device: BluetoothDevice) { if (!check()) return // 检测蓝牙 bleAdapter?.stopLeScan(bleScanCallback) if (bleGatt != null && bleGatt!!.connect()) { // 已经连接了其他设备 // 如果是先前连接的设备,则不做处理 if (TextUtils.equals(device.address, bleGatt?.device?.address)) { return } else { // 否则断开连接 bleGatt?.close() } } // 连接设备,第二个参数为是否自动连接,第三个为回调函数 bleGatt = device.connectGatt(mContext, false, BleGattCallback()) } // 实现连接回调接口[关键] private inner class BleGattCallback : BluetoothGattCallback() { // 连接状态改变(连接成功或失败)时回调该接口 override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) { if (newState == BluetoothGatt.STATE_CONNECTED) { // 连接成功 connectSuccess() gatt.discoverServices() // 则去搜索设备的服务(Service)和服务对应Characteristic } else { // 连接失败 connectFail() } } // 发现设备的服务(Service)回调,需要在这里处理订阅事件。 override fun onServicesDiscovered(gatt: BluetoothGatt, status: Int) { if (status == BluetoothGatt.GATT_SUCCESS) { // 成功订阅 var services = gatt.services // 获得设备所有的服务 var characteristics = ArrayList<BluetoothGattCharacteristic>() var descriptors = ArrayList<BluetoothGattDescriptor>() // 依次遍历每个服务获得相应的Characteristic集合 // 之后遍历Characteristic获得相应的Descriptor集合 for (service in services) { Log.e(TAG, "-- service uuid : " + service.uuid.toString() + " --") for (characteristic in service.characteristics) { Log.e(TAG, "characteristic uuid : " + characteristic.uuid) characteristics.add(characteristic) // String READ_UUID = "6e400003-b5a3-f393-e0a9-e50e24dcca9e"; // 判断当前的Characteristic是否想要订阅的,这个要依据各自蓝牙模块的协议而定 if (characteristic.uuid.toString() == "sdfadasfadfdfafdafdfadfa") { // 依据协议订阅相关信息,否则接收不到数据 bleGatt?.setCharacteristicNotification(characteristic, true) // 大坑,适配某些手机!!!比如小米... bleGatt?.readCharacteristic(characteristic) for (descriptor in characteristic.descriptors) { descriptor.value = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE bleGatt?.writeDescriptor(descriptor) } } for (descriptor in characteristic.descriptors) { Log.e(TAG, "descriptor uuid : " + characteristic.uuid) descriptors.add(descriptor) } } } discoverServiceSuccess() } else { discoverServiceFail() } } // 发送消息结果回调 override fun onCharacteristicWrite(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic, status: Int) { val intent: Intent if (BluetoothGatt.GATT_SUCCESS == status) { // 发送成功 sendMessageSuccess() } else { // 发送失败 sendMessageFail() } } // 当订阅的Characteristic接收到消息时回调 override fun onCharacteristicChanged(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic) { // 数据为 characteristic.getValue()) Log.e(TAG, "onCharacteristicChanged: " + Arrays.toString(characteristic.value)) } } private fun connectSuccess() { } private fun connectFail() { } private fun discoverServiceSuccess() { } private fun discoverServiceFail() { } private fun sendMessageSuccess() { } private fun sendMessageFail() { } // byte转十六进制字符串 fun bytes2HexString(bytes: ByteArray): String { var ret = "" for (item in bytes) { var hex = Integer.toHexString((item and 0xFF.toByte()).toInt()) if (hex.length == 1) { hex = '0' + hex } ret += hex.toUpperCase(Locale.CHINA) } return ret } // 将16进制的字符串转换为字节数组 fun getHexBytes(message: String): ByteArray { val len = message.length / 2 val chars = message.toCharArray() val hexStr = arrayOfNulls<String>(len) val bytes = ByteArray(len) var i = 0 var j = 0 while (j < len) { hexStr[j] = "" + chars[i] + chars[i + 1] bytes[j] = Integer.parseInt(hexStr[j], 16).toByte() i += 2 j++ } return bytes } }
gpl-3.0
f708f7f0d9d5738ea20ff334f08eda53
35.319838
114
0.578595
4.693878
false
false
false
false
Suomaa/androidLearning
NavigationDrawer/app/src/main/java/fi/lasicaine/navigationdrawer/MainActivity.kt
1
3143
package fi.lasicaine.navigationdrawer import android.os.Bundle import com.google.android.material.floatingactionbutton.FloatingActionButton import com.google.android.material.snackbar.Snackbar import androidx.core.view.GravityCompat import androidx.appcompat.app.ActionBarDrawerToggle import android.view.MenuItem import androidx.drawerlayout.widget.DrawerLayout import com.google.android.material.navigation.NavigationView import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import android.view.Menu class MainActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val toolbar: Toolbar = findViewById(R.id.toolbar) setSupportActionBar(toolbar) val fab: FloatingActionButton = findViewById(R.id.fab) fab.setOnClickListener { view -> Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show() } val drawerLayout: DrawerLayout = findViewById(R.id.drawer_layout) val navView: NavigationView = findViewById(R.id.nav_view) val toggle = ActionBarDrawerToggle( this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close ) drawerLayout.addDrawerListener(toggle) toggle.syncState() navView.setNavigationItemSelectedListener(this) } override fun onBackPressed() { val drawerLayout: DrawerLayout = findViewById(R.id.drawer_layout) if (drawerLayout.isDrawerOpen(GravityCompat.START)) { drawerLayout.closeDrawer(GravityCompat.START) } else { super.onBackPressed() } } override fun onCreateOptionsMenu(menu: Menu): Boolean { // Inflate the menu; this adds items to the action bar if it is present. menuInflater.inflate(R.menu.main, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. return when (item.itemId) { R.id.action_settings -> true else -> super.onOptionsItemSelected(item) } } override fun onNavigationItemSelected(item: MenuItem): Boolean { // Handle navigation view item clicks here. when (item.itemId) { R.id.nav_home -> { // Handle the camera action } R.id.nav_gallery -> { } R.id.nav_slideshow -> { } R.id.nav_tools -> { } R.id.nav_share -> { } R.id.nav_send -> { } } val drawerLayout: DrawerLayout = findViewById(R.id.drawer_layout) drawerLayout.closeDrawer(GravityCompat.START) return true } }
apache-2.0
aa02122a28d311853c23880c2fb3dadc
33.538462
106
0.658606
4.910938
false
false
false
false
softappeal/yass
kotlin/yass/main/ch/softappeal/yass/remote/MethodMapper.kt
1
2739
package ch.softappeal.yass.remote import ch.softappeal.yass.* import java.lang.reflect.* @MustBeDocumented @Retention @Target(AnnotationTarget.FUNCTION) annotation class OneWay val Method.isOneWay: Boolean get() = isAnnotationPresent(OneWay::class.java) data class MethodMapping(val method: Method, val id: Int, val oneWay: Boolean = method.isOneWay) { init { if (oneWay) { check(method.returnType === Void.TYPE) { "OneWay method '$method' must return void" } check(method.exceptionTypes.isEmpty()) { "OneWay method '$method' must not throw exceptions" } } } } interface MethodMapper { @Throws(Exception::class) fun map(id: Int): MethodMapping @Throws(Exception::class) fun map(method: Method): MethodMapping } typealias MethodMapperFactory = (contract: Class<*>) -> MethodMapper fun MethodMapperFactory.mappings(contract: Class<*>): Sequence<MethodMapping> { val methodMapper = this(contract) return contract.methods.asSequence() .map(methodMapper::map) .sortedBy(MethodMapping::id) } val SimpleMethodMapperFactory: MethodMapperFactory = { contract -> val mappings = mutableListOf<MethodMapping>() val name2mapping = mutableMapOf<String, MethodMapping>() for (method in contract.methods.sortedBy(Method::getName)) { val mapping = MethodMapping(method, mappings.size) val oldMapping = name2mapping.put(method.name, mapping) check(oldMapping == null) { "methods '$method' and '${oldMapping!!.method}' in contract '$contract' are overloaded" } mappings.add(mapping) } object : MethodMapper { override fun map(id: Int) = if (id in 0 until mappings.size) mappings[id] else error("unexpected method id $id for contract '$contract'") override fun map(method: Method) = checkNotNull(name2mapping[method.name]) { "unexpected method '$method' for contract '$contract'" } } } val TaggedMethodMapperFactory: MethodMapperFactory = { contract -> val id2mapping = mutableMapOf<Int, MethodMapping>() for (method in contract.methods) { val id = tag(method) val oldMapping = id2mapping.put(id, MethodMapping(method, id)) check(oldMapping == null) { "tag $id used for methods '$method' and '${oldMapping!!.method}' in contract '$contract'" } } object : MethodMapper { override fun map(id: Int) = checkNotNull(id2mapping[id]) { "unexpected method id $id for contract '$contract'" } override fun map(method: Method) = checkNotNull(id2mapping[tag(method)]) { "unexpected method '$method' for contract '$contract'" } } }
bsd-3-clause
7b00046b924df0b22b85b26c7a54db3f
34.571429
110
0.663016
4.239938
false
false
false
false
breadwallet/breadwallet-android
app/src/main/java/com/platform/jsbridge/WalletJs.kt
1
22576
/** * BreadWallet * * Created by Ahsan Butt <[email protected]> on 1/15/20. * Copyright (c) 2019 breadwallet LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.platform.jsbridge import android.content.Context import android.security.keystore.UserNotAuthenticatedException import android.webkit.JavascriptInterface import com.breadwallet.BuildConfig import com.breadwallet.R import com.breadwallet.app.Buy import com.breadwallet.app.ConversionTracker import com.breadwallet.app.Trade import com.breadwallet.breadbox.BreadBox import com.breadwallet.breadbox.TransferSpeed import com.breadwallet.breadbox.addressFor import com.breadwallet.breadbox.baseUnit import com.breadwallet.breadbox.containsCurrency import com.breadwallet.breadbox.currencyId import com.breadwallet.breadbox.defaultUnit import com.breadwallet.breadbox.estimateFee import com.breadwallet.breadbox.estimateMaximum import com.breadwallet.breadbox.feeForSpeed import com.breadwallet.breadbox.findCurrency import com.breadwallet.breadbox.hashString import com.breadwallet.breadbox.isBitcoin import com.breadwallet.breadbox.isNative import com.breadwallet.breadbox.toBigDecimal import com.breadwallet.breadbox.toSanitizedString import com.breadwallet.crypto.Address import com.breadwallet.crypto.AddressScheme import com.breadwallet.crypto.Amount import com.breadwallet.crypto.Transfer import com.breadwallet.crypto.TransferAttribute import com.breadwallet.crypto.TransferFeeBasis import com.breadwallet.crypto.TransferState import com.breadwallet.crypto.Wallet import com.breadwallet.crypto.errors.FeeEstimationError import com.breadwallet.logger.logDebug import com.breadwallet.logger.logError import com.breadwallet.model.TokenItem import com.breadwallet.repository.RatesRepository import com.breadwallet.tools.manager.BRSharedPrefs import com.breadwallet.tools.security.BrdUserManager import com.breadwallet.tools.util.EventUtils import com.breadwallet.tools.util.TokenUtil import com.breadwallet.ui.send.TransferField import com.platform.ConfirmTransactionMessage import com.platform.PlatformTransactionBus import com.platform.TransactionResultMessage import com.breadwallet.platform.entities.TxMetaDataValue import com.breadwallet.platform.interfaces.AccountMetaDataProvider import com.platform.util.getStringOrNull import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.onStart import kotlinx.coroutines.flow.transform import org.json.JSONArray import org.json.JSONException import org.json.JSONObject import java.math.BigDecimal import java.util.Currency import java.util.Locale class WalletJs( private val promise: NativePromiseFactory, private val context: Context, private val metaDataProvider: AccountMetaDataProvider, private val breadBox: BreadBox, private val ratesRepository: RatesRepository, private val userManager: BrdUserManager, private val conversionTracker: ConversionTracker ) : JsApi { companion object { private const val KEY_BTC_DENOMINATION_DIGITS = "btc_denomination_digits" private const val KEY_LOCAL_CURRENCY_CODE = "local_currency_code" private const val KEY_LOCAL_CURRENCY_PRECISION = "local_currency_precision" private const val KEY_LOCAL_CURRENCY_SYMBOL = "local_currency_symbol" private const val KEY_APP_PLATFORM = "app_platform" private const val KEY_APP_VERSION = "app_version" private const val KEY_CURRENCY = "currency" private const val KEY_ADDRESS = "address" private const val KEY_CURRENCIES = "currencies" private const val KEY_ID = "id" private const val KEY_TICKER = "ticker" private const val KEY_NAME = "name" private const val KEY_COLORS = "colors" private const val KEY_BALANCE = "balance" private const val KEY_FIAT_BALANCE = "fiatBalance" private const val KEY_EXCHANGE = "exchange" private const val KEY_NUMERATOR = "numerator" private const val KEY_DENOMINATOR = "denominator" private const val KEY_HASH = "hash" private const val KEY_TRANSMITTED = "transmitted" private const val APP_PLATFORM = "android" private const val ERR_EMPTY_CURRENCIES = "currencies_empty" private const val ERR_ESTIMATE_FEE = "estimate_fee" private const val ERR_INSUFFICIENT_BALANCE = "insufficient_balance" private const val ERR_SEND_TXN = "send_txn" private const val ERR_CURRENCY_NOT_SUPPORTED = "currency_not_supported" private const val DOLLAR_IN_CENTS = 100 private const val BASE_10 = 10 private const val FORMAT_DELIMITER = "?format=" private const val FORMAT_LEGACY = "legacy" private const val FORMAT_SEGWIT = "segwit" } @JavascriptInterface fun info() = promise.create { val system = checkNotNull(breadBox.getSystemUnsafe()) val btcWallet = system.wallets.first { it.currency.isBitcoin() } val preferredCode = BRSharedPrefs.getPreferredFiatIso() val fiatCurrency = Currency.getInstance(preferredCode) JSONObject().apply { put(KEY_BTC_DENOMINATION_DIGITS, btcWallet.defaultUnit.decimals) put(KEY_LOCAL_CURRENCY_CODE, fiatCurrency.currencyCode.toUpperCase()) put(KEY_LOCAL_CURRENCY_PRECISION, fiatCurrency.defaultFractionDigits) put(KEY_LOCAL_CURRENCY_SYMBOL, fiatCurrency.symbol) put(KEY_APP_PLATFORM, APP_PLATFORM) put(KEY_APP_VERSION, "${BuildConfig.VERSION_NAME}.${BuildConfig.BUILD_VERSION}") } } @JvmOverloads @JavascriptInterface fun event( name: String, attributes: String? = null ) = promise.create { if (attributes != null) { val json = JSONObject(attributes) val attr = mutableMapOf<String, String>() json.keys().forEach { attr[it] = json.getString(it) } EventUtils.pushEvent(name, attr) } else { EventUtils.pushEvent(name) } null } @JavascriptInterface fun addresses( currencyCodeQ: String ) = promise.create { var (currencyCode, format) = parseCurrencyCodeQuery(currencyCodeQ) val system = checkNotNull(breadBox.getSystemUnsafe()) val wallet = system.wallets.first { it.currency.code.equals(currencyCode, true) } val address = getAddress(wallet, format) JSONObject().apply { put(KEY_CURRENCY, currencyCode) put(KEY_ADDRESS, address) } } @Suppress("LongMethod", "ComplexMethod") @JavascriptInterface @JvmOverloads fun currencies(listAll: Boolean = false) = promise.create { val system = checkNotNull(breadBox.getSystemUnsafe()) val wallets = if (listAll) { TokenUtil.getTokenItems() .filter(TokenItem::isSupported) .map(TokenItem::currencyId) } else { checkNotNull(metaDataProvider.getEnabledWalletsUnsafe()) } val currenciesJSON = JSONArray() wallets.forEach { currencyId -> val wallet = system.wallets.firstOrNull { it.currencyId.equals(currencyId, true) } val tokenItem = TokenUtil.tokenForCurrencyId(currencyId) val currencyCode = wallet?.currency?.code?.toUpperCase() ?: tokenItem?.symbol if (currencyCode.isNullOrBlank()) return@forEach val json = JSONObject().apply { try { put(KEY_ID, currencyCode) put(KEY_TICKER, currencyCode) put(KEY_NAME, tokenItem?.name ?: wallet?.name) val colors = JSONArray().apply { put(TokenUtil.getTokenStartColor(currencyCode)) put(TokenUtil.getTokenEndColor(currencyCode)) } put(KEY_COLORS, colors) // Add balance info if wallet is available if (wallet != null) { val balance = JSONObject().apply { val numerator = wallet.balance.toStringWithBase(BASE_10, "") val denominator = Amount.create( "1", false, wallet.defaultUnit ).orNull()?.toStringWithBase(BASE_10, "") ?: Amount.create( 0, wallet.baseUnit ) put(KEY_CURRENCY, currencyCode) put(KEY_NUMERATOR, numerator) put(KEY_DENOMINATOR, denominator) } val fiatCurrency = BRSharedPrefs.getPreferredFiatIso() val fiatBalance = JSONObject().apply { val fiatAmount = ratesRepository.getFiatForCrypto( wallet.balance.toBigDecimal(), currencyCode, fiatCurrency )?.multiply(BigDecimal(DOLLAR_IN_CENTS)) ?: BigDecimal.ZERO put(KEY_CURRENCY, fiatCurrency) put(KEY_NUMERATOR, fiatAmount.toPlainString()) put(KEY_DENOMINATOR, DOLLAR_IN_CENTS.toString()) } val exchange = JSONObject().apply { val fiatPerUnit = ratesRepository.getFiatForCrypto( BigDecimal.ONE, currencyCode, fiatCurrency )?.multiply(BigDecimal(DOLLAR_IN_CENTS)) ?: BigDecimal.ZERO put(KEY_CURRENCY, fiatCurrency) put(KEY_NUMERATOR, fiatPerUnit.toPlainString()) put(KEY_DENOMINATOR, DOLLAR_IN_CENTS.toString()) } put(KEY_BALANCE, balance) put(KEY_FIAT_BALANCE, fiatBalance) put(KEY_EXCHANGE, exchange) } } catch (ex: JSONException) { logError("Failed to load currency data: $currencyCode") } } currenciesJSON.put(json) } if (currenciesJSON.length() == 0) throw IllegalStateException(ERR_EMPTY_CURRENCIES) JSONObject().put(KEY_CURRENCIES, currenciesJSON) } @JavascriptInterface fun transferAttrsFor(currency: String, addressString: String) = promise.createForArray { val wallet = breadBox.wallet(currency).first() val address = wallet.addressFor(addressString) val attrs = address?.run(wallet::getTransferAttributesFor) ?: wallet.transferAttributes val jsonAttrs = attrs.map { attr -> JSONObject().apply { put("key", attr.key) put("required", attr.isRequired) put("value", attr.value.orNull()) } } JSONArray(jsonAttrs) } @JvmOverloads @JavascriptInterface fun transaction( toAddress: String, description: String, amountStr: String, currency: String, transferAttrsString: String = "[]" ) = promise.create { val system = checkNotNull(breadBox.getSystemUnsafe()) val wallet = system.wallets.first { it.currency.code.equals(currency, true) } val amountJSON = JSONObject(amountStr) val numerator = amountJSON.getString(KEY_NUMERATOR).toDouble() val denominator = amountJSON.getString(KEY_DENOMINATOR).toDouble() val amount = Amount.create((numerator / denominator), wallet.unit) val address = checkNotNull(wallet.addressFor(toAddress)) { "Invalid address ($toAddress)" } val transferAttrs = wallet.getTransferAttributesFor(address) val transferAttrsInput = JSONArray(transferAttrsString).run { List(length(), ::getJSONObject) } transferAttrs.forEach { attribute -> val key = attribute.key.toLowerCase(Locale.ROOT) val attrJson = transferAttrsInput.firstOrNull { attr -> attr.getStringOrNull("key").equals(key, true) } attribute.setValue(attrJson?.getStringOrNull("value")) val error = wallet.validateTransferAttribute(attribute).orNull() require(error == null) { "Invalid attribute key=${attribute.key} value=${attribute.value.orNull()} error=${error?.name}" } } val feeBasis = checkNotNull(estimateFee(wallet, address, amount)) { ERR_ESTIMATE_FEE } val fee = feeBasis.fee.toBigDecimal() val totalCost = if (feeBasis.currency.code == wallet.currency.code) { amount.toBigDecimal() + fee } else { amount.toBigDecimal() } val balance = wallet.balance.toBigDecimal() check(!amount.isZero && totalCost <= balance) { ERR_INSUFFICIENT_BALANCE } val transaction = checkNotNull( sendTransaction( wallet, address, amount, totalCost, feeBasis, transferAttrs ) ) { ERR_SEND_TXN } metaDataProvider.putTxMetaData( transaction, TxMetaDataValue(comment = description) ) conversionTracker.track(Trade(currency, transaction.hashString())) JSONObject().apply { put(KEY_HASH, transaction.hashString()) put(KEY_TRANSMITTED, true) } } @JavascriptInterface fun enableCurrency(currencyCode: String) = promise.create { val system = checkNotNull(breadBox.system().first()) val currencyId = TokenUtil.tokenForCode(currencyCode)?.currencyId.orEmpty() check(currencyId.isNotEmpty()) { ERR_CURRENCY_NOT_SUPPORTED } val network = system.networks.find { it.containsCurrency(currencyId) } when (network?.findCurrency(currencyId)?.isNative()) { null -> logError("No network or currency found for $currencyId.") false -> { val trackedWallets = breadBox.wallets().first() if (!trackedWallets.containsCurrency(network.currency.uids)) { logDebug("Adding native wallet ${network.currency.uids} for $currencyId.") metaDataProvider.enableWallet(network.currency.uids) } } } metaDataProvider.enableWallet(currencyId) // Suspend until the wallet exists, i.e. an address is available. val wallet = breadBox.wallet(currencyCode).first() JSONObject().apply { put(KEY_CURRENCY, currencyCode) put(KEY_ADDRESS, getAddress(wallet, FORMAT_LEGACY)) if (wallet.currency.isBitcoin()) { put("${KEY_ADDRESS}_${FORMAT_SEGWIT}", getAddress(wallet, FORMAT_SEGWIT)) } } } @JavascriptInterface fun maxlimit( toAddress: String, currency: String ) = promise.create { val system = checkNotNull(breadBox.getSystemUnsafe()) val wallet = system.wallets.first { it.currency.code.equals(currency, true) } val address = checkNotNull(wallet.addressFor(toAddress)) val limitMaxAmount = wallet.estimateMaximum(address, wallet.feeForSpeed(TransferSpeed.Priority(currency))) checkNotNull(limitMaxAmount) val numerator = limitMaxAmount.convert(wallet.baseUnit).orNull() ?.toStringWithBase(BASE_10, "") ?: "0" val denominator = Amount.create("1", false, wallet.baseUnit).orNull() ?.toStringWithBase(BASE_10, "") ?: Amount.create(0, wallet.baseUnit).toStringWithBase(BASE_10, "") JSONObject().apply { put(KEY_NUMERATOR, numerator) put(KEY_DENOMINATOR, denominator) } } @JavascriptInterface fun trackBuy( currencyCode: String, amount: String ) = promise.createForUnit { conversionTracker.track(Buy(currencyCode, amount.toDouble(), System.currentTimeMillis())) } private suspend fun estimateFee( wallet: Wallet, address: Address?, amount: Amount ): TransferFeeBasis? { if (address == null || wallet.containsAddress(address)) { return null } try { return wallet.estimateFee( address, amount, wallet.feeForSpeed(TransferSpeed.Priority(wallet.currency.code)) ) } catch (e: FeeEstimationError) { logError("Failed get fee estimate", e) } catch (e: IllegalStateException) { logError("Failed get fee estimate", e) } return null } @Suppress("LongMethod") private suspend fun sendTransaction( wallet: Wallet, address: Address, amount: Amount, totalCost: BigDecimal, feeBasis: TransferFeeBasis, transferAttributes: Set<TransferAttribute> ): Transfer? { val fiatCode = BRSharedPrefs.getPreferredFiatIso() val fiatAmount = ratesRepository.getFiatForCrypto( amount.toBigDecimal(), wallet.currency.code, fiatCode ) ?: BigDecimal.ZERO val fiatTotalCost = ratesRepository.getFiatForCrypto( totalCost, wallet.currency.code, fiatCode ) ?: BigDecimal.ZERO val fiatNetworkFee = ratesRepository.getFiatForCrypto( feeBasis.fee.toBigDecimal(), wallet.currency.code, fiatCode ) ?: BigDecimal.ZERO val transferFields = transferAttributes.map { attribute -> TransferField( attribute.key, attribute.isRequired, false, attribute.value.orNull() ) } val result = PlatformTransactionBus.results().onStart { PlatformTransactionBus.sendMessage( ConfirmTransactionMessage( wallet.currency.code, fiatCode, feeBasis.currency.code, address.toSanitizedString(), TransferSpeed.Priority(wallet.currency.code), amount.toBigDecimal(), fiatAmount, fiatTotalCost, fiatNetworkFee, transferFields ) ) }.first() return when (result) { is TransactionResultMessage.TransactionCancelled -> throw IllegalStateException( context.getString(R.string.Platform_transaction_cancelled) ) is TransactionResultMessage.TransactionConfirmed -> { val phrase = try { checkNotNull(userManager.getPhrase()) } catch (ex: UserNotAuthenticatedException) { logError("Failed to get phrase.", ex) return null } val newTransfer = wallet.createTransfer(address, amount, feeBasis, transferAttributes).orNull() if (newTransfer == null) { logError("Failed to create transfer.") return null } wallet.walletManager.submit(newTransfer, phrase) breadBox.walletTransfer(wallet.currency.code, newTransfer.hashString()) .transform { transfer -> when (checkNotNull(transfer.state.type)) { TransferState.Type.INCLUDED, TransferState.Type.PENDING, TransferState.Type.SUBMITTED -> emit(transfer) TransferState.Type.DELETED, TransferState.Type.FAILED -> { logError("Failed to submit transfer ${transfer.state.failedError.orNull()}") emit(null) } // Ignore pre-submit states TransferState.Type.CREATED, TransferState.Type.SIGNED -> Unit } }.first() } } } private fun parseCurrencyCodeQuery(currencyCodeQuery: String) = when { currencyCodeQuery.contains(FORMAT_DELIMITER) -> { val parts = currencyCodeQuery.split(FORMAT_DELIMITER) parts[0] to parts[1] } else -> { currencyCodeQuery to "" } } private fun getAddress(wallet: Wallet, format: String) = when { wallet.currency.isBitcoin() -> { wallet.getTargetForScheme( when { format.equals(FORMAT_SEGWIT, true) -> AddressScheme.BTC_SEGWIT else -> AddressScheme.BTC_LEGACY } ).toString() } else -> wallet.target.toSanitizedString() } }
mit
985611e1f1e4ba93ab4977a61751b37b
38.886926
111
0.602853
5.246572
false
false
false
false
seventhroot/elysium
bukkit/rpk-professions-bukkit/src/main/kotlin/com/rpkit/professions/bukkit/listener/BlockBreakListener.kt
1
5463
/* * Copyright 2020 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.professions.bukkit.listener import com.rpkit.characters.bukkit.character.RPKCharacterProvider import com.rpkit.core.bukkit.util.addLore import com.rpkit.itemquality.bukkit.itemquality.RPKItemQuality import com.rpkit.players.bukkit.profile.RPKMinecraftProfileProvider import com.rpkit.professions.bukkit.RPKProfessionsBukkit import com.rpkit.professions.bukkit.profession.RPKCraftingAction import com.rpkit.professions.bukkit.profession.RPKProfessionProvider import org.bukkit.GameMode import org.bukkit.event.EventHandler import org.bukkit.event.Listener import org.bukkit.event.block.BlockBreakEvent import org.bukkit.inventory.ItemStack import kotlin.math.roundToInt import kotlin.random.Random class BlockBreakListener(private val plugin: RPKProfessionsBukkit): Listener { @EventHandler fun onBlockBreak(event: BlockBreakEvent) { val bukkitPlayer = event.player if (bukkitPlayer.gameMode == GameMode.CREATIVE || bukkitPlayer.gameMode == GameMode.SPECTATOR) return val minecraftProfileProvider = plugin.core.serviceManager.getServiceProvider(RPKMinecraftProfileProvider::class) val characterProvider = plugin.core.serviceManager.getServiceProvider(RPKCharacterProvider::class) val professionProvider = plugin.core.serviceManager.getServiceProvider(RPKProfessionProvider::class) val minecraftProfile = minecraftProfileProvider.getMinecraftProfile(bukkitPlayer) if (minecraftProfile == null) { event.isDropItems = false return } val character = characterProvider.getActiveCharacter(minecraftProfile) if (character == null) { event.isDropItems = false return } val professions = professionProvider.getProfessions(character) val professionLevels = professions .associateWith { profession -> professionProvider.getProfessionLevel(character, profession) } val itemsToDrop = mutableListOf<ItemStack>() for (item in event.block.getDrops(event.player.inventory.itemInMainHand)) { val material = item.type val amount = professionLevels.entries .map { (profession, level) -> profession.getAmountFor(RPKCraftingAction.MINE, material, level) } .max() ?: plugin.config.getDouble("default.mining.$material.amount", 1.0) val potentialQualities = professionLevels.entries .mapNotNull { (profession, level) -> profession.getQualityFor(RPKCraftingAction.MINE, material, level) } val quality = potentialQualities.maxBy(RPKItemQuality::durabilityModifier) if (quality != null) { item.addLore(quality.lore) } if (amount > 1) { item.amount = amount.roundToInt() itemsToDrop.add(item) } else if (amount < 1) { val random = Random.nextDouble() if (random <= amount) { item.amount = 1 itemsToDrop.add(item) } } else { itemsToDrop.add(item) } professions.forEach { profession -> val receivedExperience = plugin.config.getInt("professions.${profession.name}.experience.items.mining.$material", 0) * item.amount if (receivedExperience > 0) { professionProvider.setProfessionExperience(character, profession, professionProvider.getProfessionExperience(character, profession) + receivedExperience) val level = professionProvider.getProfessionLevel(character, profession) val experience = professionProvider.getProfessionExperience(character, profession) event.player.sendMessage(plugin.messages["mine-experience", mapOf( "profession" to profession.name, "level" to level.toString(), "received-experience" to receivedExperience.toString(), "experience" to (experience - profession.getExperienceNeededForLevel(level)).toString(), "next-level-experience" to (profession.getExperienceNeededForLevel(level + 1) - profession.getExperienceNeededForLevel(level)).toString(), "total-experience" to experience.toString(), "total-next-level-experience" to profession.getExperienceNeededForLevel(level + 1).toString(), "material" to material.toString().toLowerCase().replace('_', ' ') )]) } } } event.isDropItems = false for (item in itemsToDrop) { event.block.world.dropItemNaturally(event.block.location, item) } } }
apache-2.0
37ba506e7e82f759361a69ae3cc70783
50.54717
173
0.663189
5.361138
false
false
false
false
seventhroot/elysium
bukkit/rpk-players-bukkit/src/main/kotlin/com/rpkit/players/bukkit/database/table/RPKDiscordProfileTable.kt
1
6204
/* * Copyright 2020 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.players.bukkit.database.table import com.rpkit.chat.bukkit.discord.RPKDiscordProvider import com.rpkit.core.database.Database import com.rpkit.core.database.Table import com.rpkit.players.bukkit.RPKPlayersBukkit import com.rpkit.players.bukkit.database.jooq.rpkit.Tables.RPKIT_DISCORD_PROFILE import com.rpkit.players.bukkit.profile.* import net.dv8tion.jda.api.entities.User import org.ehcache.config.builders.CacheConfigurationBuilder import org.ehcache.config.builders.ResourcePoolsBuilder import org.jooq.impl.DSL.constraint import org.jooq.impl.SQLDataType.BIGINT import org.jooq.impl.SQLDataType.INTEGER class RPKDiscordProfileTable( database: Database, private val plugin: RPKPlayersBukkit ): Table<RPKDiscordProfile>(database, RPKDiscordProfile::class) { private val cache = if (plugin.config.getBoolean("caching.rpkit_discord_profile.id.enabled")) { database.cacheManager.createCache("rpk-players-bukkit.rpkit_discord_profile.id", CacheConfigurationBuilder.newCacheConfigurationBuilder(Int::class.javaObjectType, RPKDiscordProfile::class.java, ResourcePoolsBuilder.heap(plugin.config.getLong("caching.rpkit_discord_profile.id.size")))) } else { null } override fun create() { database.create .createTableIfNotExists(RPKIT_DISCORD_PROFILE) .column(RPKIT_DISCORD_PROFILE.ID, INTEGER.identity(true)) .column(RPKIT_DISCORD_PROFILE.PROFILE_ID, INTEGER) .column(RPKIT_DISCORD_PROFILE.DISCORD_ID, BIGINT) .constraints( constraint("pk_rpkit_discord_profile").primaryKey(RPKIT_DISCORD_PROFILE.ID) ) .execute() } override fun applyMigrations() { if (database.getTableVersion(this) == null) { database.setTableVersion(this, "1.8.0") } } override fun insert(entity: RPKDiscordProfile): Int { val profile = entity.profile database.create .insertInto( RPKIT_DISCORD_PROFILE, RPKIT_DISCORD_PROFILE.PROFILE_ID, RPKIT_DISCORD_PROFILE.DISCORD_ID ) .values( if (profile is RPKProfile) { profile.id } else { null }, entity.discordId ) .execute() val id = database.create.lastID().toInt() entity.id = id cache?.put(id, entity) return id } override fun update(entity: RPKDiscordProfile) { val profile = entity.profile database.create .update(RPKIT_DISCORD_PROFILE) .set( RPKIT_DISCORD_PROFILE.PROFILE_ID, if (profile is RPKProfile) { profile.id } else { null } ) .set(RPKIT_DISCORD_PROFILE.DISCORD_ID, entity.discordId) .where(RPKIT_DISCORD_PROFILE.ID.eq(entity.id)) .execute() cache?.put(entity.id, entity) } override fun get(id: Int): RPKDiscordProfile? { if (cache?.containsKey(id) == true) { return cache[id] } val result = database.create .select( RPKIT_DISCORD_PROFILE.PROFILE_ID, RPKIT_DISCORD_PROFILE.DISCORD_ID ) .from(RPKIT_DISCORD_PROFILE) .where(RPKIT_DISCORD_PROFILE.ID.eq(id)) .fetchOne() ?: return null val profileId = result[RPKIT_DISCORD_PROFILE.PROFILE_ID] val profileProvider = plugin.core.serviceManager.getServiceProvider(RPKProfileProvider::class) val discordProvider = plugin.core.serviceManager.getServiceProvider(RPKDiscordProvider::class) val profile = if (profileId != null) { profileProvider.getProfile(profileId) } else { null } ?: RPKThinProfileImpl(discordProvider.getUser(result[RPKIT_DISCORD_PROFILE.DISCORD_ID])?.name ?: "Unknown Discord user") val discordProfile = RPKDiscordProfileImpl( id, profile, result[RPKIT_DISCORD_PROFILE.DISCORD_ID] ) cache?.put(id, discordProfile) return discordProfile } fun get(user: User): RPKDiscordProfile? { val result = database.create .select(RPKIT_DISCORD_PROFILE.ID) .from(RPKIT_DISCORD_PROFILE) .where(RPKIT_DISCORD_PROFILE.DISCORD_ID.eq(user.idLong)) .fetchOne() ?: return null return get(result[RPKIT_DISCORD_PROFILE.ID]) } fun get(profile: RPKProfile): List<RPKDiscordProfile> { val results = database.create .select(RPKIT_DISCORD_PROFILE.PROFILE_ID) .from(RPKIT_DISCORD_PROFILE) .where(RPKIT_DISCORD_PROFILE.PROFILE_ID.eq(profile.id)) .fetch() return results.mapNotNull { result -> get(result[RPKIT_DISCORD_PROFILE.ID]) } } override fun delete(entity: RPKDiscordProfile) { database.create .deleteFrom(RPKIT_DISCORD_PROFILE) .where(RPKIT_DISCORD_PROFILE.ID.eq(entity.id)) .execute() cache?.remove(entity.id) } }
apache-2.0
5ff997f8281db42afd3dd691c6422157
37.302469
130
0.593972
4.76132
false
false
false
false
serorigundam/numeri3
app/src/main/kotlin/net/ketc/numeri/domain/model/Tweet.kt
1
780
package net.ketc.numeri.domain.model import net.ketc.numeri.domain.model.cache.Cacheable import net.ketc.numeri.domain.service.TwitterClient interface Tweet : Cacheable<Long> { val user: TwitterUser val createdAt: String val text: String val quotedTweet: Tweet? val retweetedTweet: Tweet? val source: String val favoriteCount: Int val retweetCount: Int val hashtags: List<String> val urlEntities: List<UrlEntity> val mediaEntities: List<MediaEntity> val userMentionEntities: List<UserMentionEntity> val inReplyToStatusId: Long } infix fun TwitterClient.isMyTweet(tweet: Tweet) = tweet.user.id == id infix fun Tweet.isMention(client: TwitterClient) = userMentionEntities.any { it.id == client.id } && retweetedTweet == null
mit
ce3f64ba01c1d4390f4439197fc5ad90
30.2
123
0.744872
3.861386
false
false
false
false
hishamMuneer/JsonParsingDemo
app/src/main/java/com/hisham/jsonparsingdemo/source/ManualParsing.kt
1
2708
package com.hisham.jsonparsingdemo.source import com.google.gson.Gson import com.hisham.jsonparsingdemo.model.Movie import com.hisham.jsonparsingdemo.model.MovieObject import java.io.BufferedInputStream import java.lang.Exception import java.net.URL import org.json.JSONObject class ManualParsing : MoviesApi { override suspend fun getMovies(): MovieObject { try { val url = URL("https://jsonparsingdemo-cec5b.firebaseapp.com/json/moviesDemoItem.json") val connection = url.openConnection() connection.connect() val inputStream = BufferedInputStream(url.openStream()) val bufferedReader = inputStream.bufferedReader() val stringBuffer = StringBuffer() for (line in bufferedReader.readLines()) { stringBuffer.append(line) } bufferedReader.close() // JSON parsing val json = stringBuffer.toString() return Gson().fromJson(json, MovieObject::class.java) // val topLevelObject = JSONObject(json) // val moviesArray = topLevelObject.getJSONArray("movies") // val movieObject = moviesArray.getJSONObject(0) // val movieName = movieObject.getString("movie") // val movieYear = movieObject.getInt("year") // return MovieObject(listOf(Movie(movieName.plus(" From manual parsing"), movieYear))) } catch (e: Exception) { return MovieObject(emptyList()) } } override suspend fun getMovie(): Movie { try { val url = URL("https://jsonparsingdemo-cec5b.firebaseapp.com/json/movie.json") val connection = url.openConnection() connection.connect() val inputStream = BufferedInputStream(url.openStream()) val bufferedReader = inputStream.bufferedReader() val stringBuffer = StringBuffer() for (line in bufferedReader.readLines()) { stringBuffer.append(line) } bufferedReader.close() // JSON parsing val json = stringBuffer.toString() return Gson().fromJson(json, Movie::class.java) // val topLevelObject = JSONObject(json) // val moviesArray = topLevelObject.getJSONArray("movies") // val movieObject = moviesArray.getJSONObject(0) // val movieName = movieObject.getString("movie") // val movieYear = movieObject.getInt("year") // return MovieObject(listOf(Movie(movieName.plus(" From manual parsing"), movieYear))) } catch (e: Exception) { return Movie("", -1, "") } } }
mit
4454f81139594805678b816afdf13f0c
35.12
99
0.616691
4.923636
false
false
false
false
wiryls/HomeworkCollectionOfMYLS
2017.AndroidApplicationDevelopment/ODES/app/src/main/java/com/myls/odes/request/QueryUser.kt
1
1433
package com.myls.odes.request import android.os.Bundle import android.os.Parcel import android.os.Parcelable /** * Created by myls on 12/2/17. */ object QueryUser { class Request : ArgumentsHolder, IRequest { constructor(username: String): super() { with(bundle) { putString("stuid", username) } } override val url: String get() = "https://api.mysspku.com/index.php/V1/MobileCourse/getDetail" override val query: Bundle get() = bundle override val method: String get() = "GET" override val response: Class<*> get() = Response::class.java private constructor(parcel: Parcel): super(parcel) companion object CREATOR : Parcelable.Creator<Request> { override fun createFromParcel(parcel: Parcel) = Request(parcel) override fun newArray(size: Int) = arrayOfNulls<Request>(size) } } data class Response(val errcode: Int, val data: Data) { data class Data ( val errmsg: String = "", var studentid: String = "", var name: String = "", var gender: String = "", var grade: String = "", var vcode: String = "", var room: String = "", var building: String = "", var location: String = "" ) } }
mit
3bd308caa3e8ff931911c383e8316753
27.098039
81
0.542917
4.450311
false
false
false
false
bvic23/storybook-intellij-plugin
src/org/bvic23/intellij/plugin/storybook/models/Story.kt
1
935
package org.bvic23.intellij.plugin.storybook.models import com.fasterxml.jackson.module.kotlin.readValue import org.bvic23.intellij.plugin.storybook.JacksonMapper import org.bvic23.intellij.plugin.storybook.firstLetters import org.bvic23.intellij.plugin.storybook.normalized import org.bvic23.intellij.plugin.storybook.similar data class Story(val kind: String, val story: String) { private val normalizedSearchString = (kind + " " + story).normalized private val firstLetters = (kind + " " + story).firstLetters fun toJSON() = JacksonMapper.mapper.writeValueAsString(this) fun toMessage() = StorySelectionMessage("setCurrentStory", listOf(this)).toJSON() fun similarTo(target: String) = normalizedSearchString.similar(target, 10) || firstLetters.similar(target, 3) companion object { fun fromJSON(string: String?) = if (string != null) JacksonMapper.mapper.readValue<Story>(string) else null } }
mit
7785684f50531c118fe52478a61641e9
48.263158
115
0.767914
4.065217
false
false
false
false
wizardofos/Protozoo
extra/exposed/src/main/kotlin/org/jetbrains/exposed/sql/IterableEx.kt
1
3108
package org.jetbrains.exposed.sql import java.lang.UnsupportedOperationException interface SizedIterable<out T>: Iterable<T> { fun limit(n: Int, offset: Int = 0): SizedIterable<T> fun count(): Int fun empty(): Boolean fun forUpdate(): SizedIterable<T> = this fun notForUpdate(): SizedIterable<T> = this } fun <T> emptySized() : SizedIterable<T> = EmptySizedIterable() class EmptySizedIterable<out T> : SizedIterable<T>, Iterator<T> { override fun count(): Int = 0 override fun limit(n: Int, offset: Int): SizedIterable<T> = this override fun empty(): Boolean = true operator override fun iterator(): Iterator<T> = this operator override fun next(): T { throw UnsupportedOperationException() } override fun hasNext(): Boolean = false } class SizedCollection<out T>(val delegate: Collection<T>): SizedIterable<T> { override fun limit(n: Int, offset: Int): SizedIterable<T> = SizedCollection(delegate.drop(offset).take(n)) operator override fun iterator() = delegate.iterator() override fun count() = delegate.size override fun empty() = delegate.isEmpty() } class LazySizedCollection<out T>(val delegate: SizedIterable<T>): SizedIterable<T> { private var _wrapper: List<T>? = null private var _size: Int? = null private var _empty: Boolean? = null val wrapper: List<T> get() { if (_wrapper == null) { _wrapper = delegate.toList() } return _wrapper!! } override fun limit(n: Int, offset: Int): SizedIterable<T> = delegate.limit(n, offset) operator override fun iterator() = wrapper.iterator() override fun count() = _wrapper?.size ?: _count() override fun empty() = _wrapper?.isEmpty() ?: _empty() override fun forUpdate(): SizedIterable<T> = delegate.forUpdate() override fun notForUpdate(): SizedIterable<T> = delegate.notForUpdate() private fun _count(): Int { if (_size == null) { _size = delegate.count() _empty = (_size == 0) } return _size!! } private fun _empty(): Boolean { if (_empty == null) { _empty = delegate.empty() if (_empty == true) _size = 0 } return _empty!! } } infix fun <T, R> SizedIterable<T>.mapLazy(f:(T)->R):SizedIterable<R> { val source = this return object : SizedIterable<R> { override fun limit(n: Int, offset: Int): SizedIterable<R> = source.limit(n, offset).mapLazy(f) override fun forUpdate(): SizedIterable<R> = source.forUpdate().mapLazy(f) override fun notForUpdate(): SizedIterable<R> = source.notForUpdate().mapLazy(f) override fun count(): Int = source.count() override fun empty(): Boolean = source.empty() operator override fun iterator(): Iterator<R> { val sourceIterator = source.iterator() return object: Iterator<R> { operator override fun next(): R = f(sourceIterator.next()) override fun hasNext(): Boolean = sourceIterator.hasNext() } } } }
mit
e6203fcddd42439fac01d1390fbe8b53
31.715789
110
0.623552
4.188679
false
false
false
false
HendraAnggrian/collapsingtoolbarlayout-subtitle
sample/src/com/example/subtitlecollapsingtoolbarlayout/MainActivity.kt
1
6235
package com.example.subtitlecollapsingtoolbarlayout import android.content.SharedPreferences import android.content.SharedPreferences.OnSharedPreferenceChangeListener import android.graphics.Color import android.graphics.drawable.ColorDrawable import android.os.Bundle import android.view.Gravity import android.view.Menu import android.view.MenuItem import android.view.View import androidx.annotation.ColorInt import androidx.annotation.Px import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.app.AppCompatDelegate import androidx.core.view.GravityCompat import com.google.android.material.appbar.SubtitleCollapsingToolbarLayout import com.hendraanggrian.auto.prefs.BindPreference import com.hendraanggrian.auto.prefs.PreferencesSaver import com.hendraanggrian.auto.prefs.Prefs import com.hendraanggrian.auto.prefs.android.AndroidPreferences import com.hendraanggrian.auto.prefs.android.preferences import com.jakewharton.processphoenix.ProcessPhoenix import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity(), OnSharedPreferenceChangeListener { @JvmField @BindPreference("theme") var theme2 = AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM @JvmField @BindPreference var showSubtitle = false @JvmField @BindPreference var statusBarScrim = Color.TRANSPARENT @JvmField @BindPreference var contentScrim = Color.TRANSPARENT @JvmField @BindPreference var marginLeft = 0 @JvmField @BindPreference var marginTop = 0 @JvmField @BindPreference var marginRight = 0 @JvmField @BindPreference var marginBottom = 0 @JvmField @BindPreference var collapsedTitleColor = Color.TRANSPARENT @JvmField @BindPreference var collapsedSubtitleColor = Color.TRANSPARENT @JvmField @BindPreference @ColorInt var expandedTitleColor = Color.TRANSPARENT @JvmField @BindPreference @ColorInt var expandedSubtitleColor = Color.TRANSPARENT private lateinit var prefs: AndroidPreferences private lateinit var saver: PreferencesSaver @Px private var marginScale = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setSupportActionBar(toolbar) supportFragmentManager .beginTransaction() .replace(R.id.container, MainFragment()) .commitNow() prefs = preferences marginScale = resources.getDimensionPixelSize(R.dimen.margin_scale) onSharedPreferenceChanged(prefs, "") } override fun onResume() { super.onResume() prefs.registerOnSharedPreferenceChangeListener(this) } override fun onPause() { super.onPause() prefs.unregisterOnSharedPreferenceChangeListener(this) } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.activity_main, menu) menu.findItem( when (theme2) { AppCompatDelegate.MODE_NIGHT_NO -> R.id.lightThemeItem AppCompatDelegate.MODE_NIGHT_YES -> R.id.darkThemeItem else -> R.id.defaultThemeItem } ).isChecked = true return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.defaultThemeItem, R.id.lightThemeItem, R.id.darkThemeItem -> { theme2 = when (item.itemId) { R.id.lightThemeItem -> AppCompatDelegate.MODE_NIGHT_NO R.id.darkThemeItem -> AppCompatDelegate.MODE_NIGHT_YES else -> AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM } saver.save() AppCompatDelegate.setDefaultNightMode(theme2) } R.id.resetItem -> { prefs.edit { clear() } ProcessPhoenix.triggerRebirth(this) } } return super.onOptionsItemSelected(item) } override fun onSharedPreferenceChanged(p: SharedPreferences, key: String) { saver = Prefs.bind(prefs, this) toolbarLayout.subtitle = if (showSubtitle) SubtitleCollapsingToolbarLayout::class.java.simpleName else null toolbarLayout.statusBarScrim = if (statusBarScrim.isConfigured()) ColorDrawable(statusBarScrim) else null toolbarLayout.contentScrim = if (contentScrim.isConfigured()) ColorDrawable(contentScrim) else null toolbarLayout.collapsedTitleGravity = prefs.getGravity("collapsedGravity", GravityCompat.START or Gravity.CENTER_VERTICAL) toolbarLayout.expandedTitleGravity = prefs.getGravity("expandedGravity", GravityCompat.START or Gravity.BOTTOM) if (marginLeft != 0) toolbarLayout.expandedTitleMarginStart = marginLeft * marginScale if (marginTop != 0) toolbarLayout.expandedTitleMarginTop = marginTop * marginScale if (marginRight != 0) toolbarLayout.expandedTitleMarginEnd = marginRight * marginScale if (marginBottom != 0) toolbarLayout.expandedTitleMarginBottom = marginBottom * marginScale collapsedTitleColor.ifConfigured { toolbarLayout.setCollapsedTitleTextColor(it) } collapsedSubtitleColor.ifConfigured { toolbarLayout.setCollapsedSubtitleTextColor(it) } expandedTitleColor.ifConfigured { toolbarLayout.setExpandedTitleTextColor(it) } expandedSubtitleColor.ifConfigured { toolbarLayout.setExpandedSubtitleTextColor(it) } } fun expand(view: View) = appbar.setExpanded(true) private companion object { fun SharedPreferences.getGravity(key: String, def: Int): Int { val iterator = getStringSet(key, emptySet())!!.iterator() var gravity: Int? = null while (iterator.hasNext()) { val next = iterator.next().toInt() gravity = when (gravity) { null -> next else -> gravity or next } } return gravity ?: def } fun @receiver:ColorInt Int.isConfigured(): Boolean = this != Color.TRANSPARENT fun @receiver:ColorInt Int.ifConfigured(action: (Int) -> Unit) { if (isConfigured()) action(this) } } }
apache-2.0
36917d4fcb116178e61b592c26102f52
43.542857
115
0.702967
5.306383
false
true
false
false
jonnyzzz/TeamCity.Node
common/src/main/java/com/jonnyzzz/teamcity/plugins/node/common/GulpBean.kt
1
1680
/* * Copyright 2013-2015 Eugene Petrenko * * 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.jonnyzzz.teamcity.plugins.node.common class GulpBean { val gulpConfigurationParameter: String = "gulp" val runTypeName: String = "jonnyzzz.gulp" val file: String = "jonnyzzz.gulp.file" val targets: String = "jonnyzzz.gulp.tasks" val commandLineParameterKey : String = "jonnyzzz.commandLine" val gulpMode : String = "jonnyzzz.gulp.mode" val gulpModeDefault : GulpExecutionMode = GulpExecutionMode.NPM val gulpModes : List<GulpExecutionMode> get() = arrayListOf(*GulpExecutionMode.values()) fun parseMode(text : String?) : GulpExecutionMode? = gulpModes.firstOrNull { text == it.value } ?: gulpModeDefault fun parseCommands(text: String?): Collection<String> { if (text == null) return listOf() else return text .lines() .map { it.trim() } .filterNot { it.isEmpty() } } } enum class GulpExecutionMode(val title : String, val value : String) { NPM("NPM package from project", "npm"), GLOBAL("System-wide gulp", "global"), }
apache-2.0
40b427040aee74b578802b4c9fdc8ef2
31.941176
75
0.682738
4.179104
false
false
false
false
Edward608/RxBinding
rxbinding-kotlin/src/main/kotlin/com/jakewharton/rxbinding2/widget/RxToolbar.kt
2
2282
@file:Suppress( names = "NOTHING_TO_INLINE" ) package com.jakewharton.rxbinding2.widget import android.view.MenuItem import android.widget.Toolbar import com.jakewharton.rxbinding2.internal.VoidToUnit import io.reactivex.Observable import io.reactivex.functions.Consumer import kotlin.Int import kotlin.Suppress import kotlin.Unit /** * Create an observable which emits the clicked item in `view`'s menu. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. */ inline fun Toolbar.itemClicks(): Observable<MenuItem> = RxToolbar.itemClicks(this) /** * Create an observable which emits on `view` navigation click events. The emitted value is * unspecified and should only be used as notification. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. * * *Warning:* The created observable uses [Toolbar.setNavigationOnClickListener] * to observe clicks. Only one observable can be used for a view at a time. */ inline fun Toolbar.navigationClicks(): Observable<Unit> = RxToolbar.navigationClicks(this).map(VoidToUnit) /** * An action which sets the title property of `view` with character sequences. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. */ inline fun Toolbar.title(): Consumer<in CharSequence?> = RxToolbar.title(this) /** * An action which sets the title property of `view` string resource IDs. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. */ inline fun Toolbar.titleRes(): Consumer<in Int> = RxToolbar.titleRes(this) /** * An action which sets the subtitle property of `view` with character sequences. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. */ inline fun Toolbar.subtitle(): Consumer<in CharSequence?> = RxToolbar.subtitle(this) /** * An action which sets the subtitle property of `view` string resource IDs. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. */ inline fun Toolbar.subtitleRes(): Consumer<in Int> = RxToolbar.subtitleRes(this)
apache-2.0
96085c271fd008334ae363a16108ca91
33.575758
106
0.753725
4.187156
false
false
false
false
ujpv/intellij-rust
src/main/kotlin/backcompat/ui/layout/layoutImpl.kt
1
1729
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package backcompat.ui.layout import java.awt.Container import javax.swing.ButtonGroup import javax.swing.JLabel // see com.intellij.uiDesigner.core.AbstractLayout.DEFAULT_HGAP and DEFAULT_VGAP // https://docs.google.com/document/d/1DKnLkO-7_onA7_NCw669aeMH5ltNvw-QMiQHnXu8k_Y/edit internal const val HORIZONTAL_GAP = 10 internal const val VERTICAL_GAP = 5 fun createLayoutBuilder() = LayoutBuilder(MigLayoutBuilder()) // cannot use the same approach as in case of Row because cannot access to `build` method in inlined `panel` method, // in any case Kotlin compiler does the same thing — // "When a protected member is accessed from an inline function, a public accessor method is created to provide an access to that protected member from the outside of the class where the function will be inlined to." // (https://youtrack.jetbrains.com/issue/KT-12215) interface LayoutBuilderImpl { fun newRow(label: JLabel? = null, buttonGroup: ButtonGroup? = null, separated: Boolean = false, indented: Boolean = false): Row fun build(container: Container, layoutConstraints: Array<out LCFlags>) fun noteRow(text: String) }
mit
ed480f9bba5f7711f3f8a7b4a7064e4e
42.175
216
0.766647
3.90724
false
false
false
false
square/kotlinpoet
interop/kotlinx-metadata/src/main/kotlin/com/squareup/kotlinpoet/metadata/KotlinPoetMetadata.kt
1
4279
/* * 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 * * 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:JvmName("KotlinPoetMetadata") @file:Suppress("unused") package com.squareup.kotlinpoet.metadata import javax.lang.model.element.TypeElement import kotlin.annotation.AnnotationTarget.CLASS import kotlin.annotation.AnnotationTarget.FUNCTION import kotlin.annotation.AnnotationTarget.PROPERTY import kotlin.reflect.KClass import kotlinx.metadata.KmClass import kotlinx.metadata.jvm.KotlinClassHeader import kotlinx.metadata.jvm.KotlinClassMetadata /** * Indicates that a given API is part of the experimental KotlinPoet metadata support. This exists * because kotlinx-metadata is not a stable API, and will remain in place until it is. */ @RequiresOptIn @Retention(AnnotationRetention.BINARY) @Target(CLASS, FUNCTION, PROPERTY) public annotation class KotlinPoetMetadataPreview /** @return a new [KmClass] representation of the Kotlin metadata for [this] class. */ @KotlinPoetMetadataPreview public fun KClass<*>.toKmClass(): KmClass = java.toKmClass() /** @return a new [KmClass] representation of the Kotlin metadata for [this] class. */ @KotlinPoetMetadataPreview public fun Class<*>.toKmClass(): KmClass = readMetadata(::getAnnotation).toKmClass() /** @return a new [KmClass] representation of the Kotlin metadata for [this] type. */ @KotlinPoetMetadataPreview public fun TypeElement.toKmClass(): KmClass = readMetadata(::getAnnotation).toKmClass() @KotlinPoetMetadataPreview public fun Metadata.toKmClass(): KmClass { return toKotlinClassMetadata<KotlinClassMetadata.Class>() .toKmClass() } @KotlinPoetMetadataPreview public inline fun <reified T : KotlinClassMetadata> Metadata.toKotlinClassMetadata(): T { val expectedType = T::class val metadata = readKotlinClassMetadata() return when (expectedType) { KotlinClassMetadata.Class::class -> { check(metadata is KotlinClassMetadata.Class) metadata as T } KotlinClassMetadata.FileFacade::class -> { check(metadata is KotlinClassMetadata.FileFacade) metadata as T } KotlinClassMetadata.SyntheticClass::class -> throw UnsupportedOperationException("SyntheticClass isn't supported yet!") KotlinClassMetadata.MultiFileClassFacade::class -> throw UnsupportedOperationException("MultiFileClassFacade isn't supported yet!") KotlinClassMetadata.MultiFileClassPart::class -> throw UnsupportedOperationException("MultiFileClassPart isn't supported yet!") KotlinClassMetadata.Unknown::class -> throw RuntimeException("Recorded unknown metadata type! $metadata") else -> TODO("Unrecognized KotlinClassMetadata type: $expectedType") } } /** * Returns the [KotlinClassMetadata] this represents. In general you should only use this function * when you don't know what the underlying [KotlinClassMetadata] subtype is, otherwise you should * use one of the more direct functions like [toKmClass]. */ @KotlinPoetMetadataPreview public fun Metadata.readKotlinClassMetadata(): KotlinClassMetadata { val metadata = KotlinClassMetadata.read(asClassHeader()) checkNotNull(metadata) { "Could not parse metadata! Try bumping kotlinpoet and/or kotlinx-metadata version." } return metadata } private inline fun readMetadata(lookup: ((Class<Metadata>) -> Metadata?)): Metadata { return checkNotNull(lookup.invoke(Metadata::class.java)) { "No Metadata annotation found! Must be Kotlin code built with the standard library on the classpath." } } private fun Metadata.asClassHeader(): KotlinClassHeader { return KotlinClassHeader( kind = kind, metadataVersion = metadataVersion, data1 = data1, data2 = data2, extraString = extraString, packageName = packageName, extraInt = extraInt, ) }
apache-2.0
1dc4d9aef81b85547fc52c2d5f6a55c5
37.205357
105
0.766534
4.829571
false
false
false
false
signed/intellij-community
platform/configuration-store-impl/testSrc/SchemeManagerTest.kt
1
14315
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.configurationStore import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.options.ExternalizableScheme import com.intellij.openapi.options.SchemeManagerFactory import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.text.StringUtil import com.intellij.testFramework.PlatformTestUtil import com.intellij.testFramework.ProjectRule import com.intellij.testFramework.TemporaryDirectory import com.intellij.testFramework.runInEdtAndWait import com.intellij.util.io.createDirectories import com.intellij.util.io.directoryStreamIfExists import com.intellij.util.io.readText import com.intellij.util.io.write import com.intellij.util.loadElement import com.intellij.util.toByteArray import com.intellij.util.xmlb.annotations.Tag import gnu.trove.THashMap import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.assertThatThrownBy import org.junit.ClassRule import org.junit.Rule import org.junit.Test import java.io.File import java.nio.file.Path import java.util.function.Function internal val FILE_SPEC = "REMOTE" /** * Functionality without stream provider covered, ICS has own test suite */ internal class SchemeManagerTest { companion object { @JvmField @ClassRule val projectRule = ProjectRule() } private val tempDirManager = TemporaryDirectory() @Rule fun getTemporaryFolder() = tempDirManager private var localBaseDir: Path? = null private var remoteBaseDir: Path? = null private fun getTestDataPath() = PlatformTestUtil.getCommunityPath().replace(File.separatorChar, '/') + "/platform/platform-tests/testData/options" @Test fun loadSchemes() { doLoadSaveTest("options1", "1->first;2->second") } @Test fun loadSimpleSchemes() { doLoadSaveTest("options", "1->1") } @Test fun deleteScheme() { val manager = createAndLoad("options1") manager.removeScheme("first") manager.save() checkSchemes("2->second") } @Test fun renameScheme() { val manager = createAndLoad("options1") val scheme = manager.findSchemeByName("first") assertThat(scheme).isNotNull() scheme!!.name = "renamed" manager.save() checkSchemes("2->second;renamed->renamed") } @Test fun testRenameScheme2() { val manager = createAndLoad("options1") val first = manager.findSchemeByName("first") assertThat(first).isNotNull() assert(first != null) first!!.name = "2" val second = manager.findSchemeByName("second") assertThat(second).isNotNull() assert(second != null) second!!.name = "1" manager.save() checkSchemes("1->1;2->2") } @Test fun testDeleteRenamedScheme() { val manager = createAndLoad("options1") val firstScheme = manager.findSchemeByName("first") assertThat(firstScheme).isNotNull() assert(firstScheme != null) firstScheme!!.name = "first_renamed" manager.save() checkSchemes(remoteBaseDir!!.resolve("REMOTE"), "first_renamed->first_renamed;2->second", true) checkSchemes(localBaseDir!!, "", false) firstScheme.name = "first_renamed2" manager.removeScheme(firstScheme) manager.save() checkSchemes(remoteBaseDir!!.resolve("REMOTE"), "2->second", true) checkSchemes(localBaseDir!!, "", false) } @Test fun testDeleteAndCreateSchemeWithTheSameName() { val manager = createAndLoad("options1") val firstScheme = manager.findSchemeByName("first") assertThat(firstScheme).isNotNull() manager.removeScheme(firstScheme!!) manager.addScheme(TestScheme("first")) manager.save() checkSchemes("2->second;first->first") } @Test fun testGenerateUniqueSchemeName() { val manager = createAndLoad("options1") val scheme = TestScheme("first") manager.addNewScheme(scheme, false) assertThat("first2").isEqualTo(scheme.name) } fun TestScheme.save(file: Path) { file.write(serialize().toByteArray()) } @Test fun `different extensions`() { val dir = tempDirManager.newPath() val scheme = TestScheme("local", "true") scheme.save(dir.resolve("1.icls")) TestScheme("local", "false").save(dir.resolve("1.xml")) class ATestSchemesProcessor : TestSchemesProcessor(), SchemeExtensionProvider { override val schemeExtension = ".icls" } val schemesManager = SchemeManagerImpl(FILE_SPEC, ATestSchemesProcessor(), null, dir) schemesManager.loadSchemes() assertThat(schemesManager.allSchemes).containsOnly(scheme) assertThat(dir.resolve("1.icls")).isRegularFile() assertThat(dir.resolve("1.xml")).isRegularFile() scheme.data = "newTrue" schemesManager.save() assertThat(dir.resolve("1.icls")).isRegularFile() assertThat(dir.resolve("1.xml")).doesNotExist() } @Test fun setSchemes() { val dir = tempDirManager.newPath() val schemeManager = createSchemeManager(dir) schemeManager.loadSchemes() assertThat(schemeManager.allSchemes).isEmpty() val scheme = TestScheme("s1") schemeManager.setSchemes(listOf(scheme)) val schemes = schemeManager.allSchemes assertThat(schemes).containsOnly(scheme) assertThat(dir.resolve("s1.xml")).doesNotExist() scheme.data = "newTrue" schemeManager.save() assertThat(dir.resolve("s1.xml")).isRegularFile() schemeManager.setSchemes(emptyList()) schemeManager.save() assertThat(dir).doesNotExist() } @Test fun `reload schemes`() { val dir = tempDirManager.newPath() val schemeManager = createSchemeManager(dir) schemeManager.loadSchemes() assertThat(schemeManager.allSchemes).isEmpty() val scheme = TestScheme("s1", "oldData") schemeManager.setSchemes(listOf(scheme)) assertThat(schemeManager.allSchemes).containsOnly(scheme) schemeManager.save() dir.resolve("s1.xml").write("""<scheme name="s1" data="newData" />""") schemeManager.reload() assertThat(schemeManager.allSchemes).containsOnly(TestScheme("s1", "newData")) } @Test fun `save only if scheme differs from bundled`() { val dir = tempDirManager.newPath() var schemeManager = createSchemeManager(dir) val bundledPath = "/com/intellij/configurationStore/bundledSchemes/default" schemeManager.loadBundledScheme(bundledPath, this) val customScheme = TestScheme("default") assertThat(schemeManager.allSchemes).containsOnly(customScheme) schemeManager.save() assertThat(dir).doesNotExist() schemeManager.save() schemeManager.setSchemes(listOf(customScheme)) assertThat(dir).doesNotExist() assertThat(schemeManager.allSchemes).containsOnly(customScheme) customScheme.data = "foo" schemeManager.save() assertThat(dir.resolve("default.xml")).isRegularFile() schemeManager = createSchemeManager(dir) schemeManager.loadBundledScheme(bundledPath, this) schemeManager.loadSchemes() assertThat(schemeManager.allSchemes).containsOnly(customScheme) } @Test fun `don't remove dir if no schemes but at least one non-hidden file exists`() { val dir = tempDirManager.newPath() val schemeManager = createSchemeManager(dir) val scheme = TestScheme("s1") schemeManager.setSchemes(listOf(scheme)) schemeManager.save() val schemeFile = dir.resolve("s1.xml") assertThat(schemeFile).isRegularFile() schemeManager.setSchemes(emptyList()) dir.resolve("empty").write(byteArrayOf()) schemeManager.save() assertThat(schemeFile).doesNotExist() assertThat(dir).isDirectory() } @Test fun `remove empty directory only if some file was deleted`() { val dir = tempDirManager.newPath() val schemeManager = createSchemeManager(dir) schemeManager.loadSchemes() dir.createDirectories() schemeManager.save() assertThat(dir).isDirectory() schemeManager.addScheme(TestScheme("test")) schemeManager.save() assertThat(dir).isDirectory() schemeManager.setSchemes(emptyList()) schemeManager.save() assertThat(dir).doesNotExist() } @Test fun rename() { val dir = tempDirManager.newPath() val schemeManager = createSchemeManager(dir) schemeManager.loadSchemes() assertThat(schemeManager.allSchemes).isEmpty() val scheme = TestScheme("s1") schemeManager.setSchemes(listOf(scheme)) val schemes = schemeManager.allSchemes assertThat(schemes).containsOnly(scheme) assertThat(dir.resolve("s1.xml")).doesNotExist() scheme.data = "newTrue" schemeManager.save() assertThat(dir.resolve("s1.xml")).isRegularFile() scheme.name = "s2" schemeManager.save() assertThat(dir.resolve("s1.xml")).doesNotExist() assertThat(dir.resolve("s2.xml")).isRegularFile() } @Test fun `rename A to B and B to A`() { val dir = tempDirManager.newPath() val schemeManager = createSchemeManager(dir) val a = TestScheme("a", "a") val b = TestScheme("b", "b") schemeManager.setSchemes(listOf(a, b)) schemeManager.save() assertThat(dir.resolve("a.xml")).isRegularFile() assertThat(dir.resolve("b.xml")).isRegularFile() a.name = "b" b.name = "a" schemeManager.save() assertThat(dir.resolve("a.xml").readText()).isEqualTo("""<scheme name="a" data="b" />""") assertThat(dir.resolve("b.xml").readText()).isEqualTo("""<scheme name="b" data="a" />""") } @Test fun `VFS - rename A to B and B to A`() { val dir = tempDirManager.newPath() val schemeManager = SchemeManagerImpl(FILE_SPEC, TestSchemesProcessor(), null, dir, messageBus = ApplicationManager.getApplication().messageBus) val a = TestScheme("a", "a") val b = TestScheme("b", "b") schemeManager.setSchemes(listOf(a, b)) runInEdtAndWait { schemeManager.save() } assertThat(dir.resolve("a.xml")).isRegularFile() assertThat(dir.resolve("b.xml")).isRegularFile() a.name = "b" b.name = "a" runInEdtAndWait { schemeManager.save() } assertThat(dir.resolve("a.xml").readText()).isEqualTo("""<scheme name="a" data="b" />""") assertThat(dir.resolve("b.xml").readText()).isEqualTo("""<scheme name="b" data="a" />""") } @Test fun `path must not contains ROOT_CONFIG macro`() { assertThatThrownBy({ SchemeManagerFactory.getInstance().create("\$ROOT_CONFIG$/foo", TestSchemesProcessor()) }).hasMessage("Path must not contains ROOT_CONFIG macro, corrected: foo") } @Test fun `path must be system-independent`() { assertThatThrownBy({ SchemeManagerFactory.getInstance().create("foo\\bar", TestSchemesProcessor())}).hasMessage("Path must be system-independent, use forward slash instead of backslash") } private fun createSchemeManager(dir: Path) = SchemeManagerImpl(FILE_SPEC, TestSchemesProcessor(), null, dir) private fun createAndLoad(testData: String): SchemeManagerImpl<TestScheme, TestScheme> { createTempFiles(testData) return createAndLoad() } private fun doLoadSaveTest(testData: String, expected: String, localExpected: String = "") { val schemesManager = createAndLoad(testData) schemesManager.save() checkSchemes(remoteBaseDir!!.resolve("REMOTE"), expected, true) checkSchemes(localBaseDir!!, localExpected, false) } private fun checkSchemes(expected: String) { checkSchemes(remoteBaseDir!!.resolve("REMOTE"), expected, true) checkSchemes(localBaseDir!!, "", false) } private fun createAndLoad(): SchemeManagerImpl<TestScheme, TestScheme> { val schemesManager = SchemeManagerImpl(FILE_SPEC, TestSchemesProcessor(), MockStreamProvider(remoteBaseDir!!), localBaseDir!!) schemesManager.loadSchemes() return schemesManager } private fun createTempFiles(testData: String) { val temp = tempDirManager.newPath() localBaseDir = temp.resolve("__local") remoteBaseDir = temp FileUtil.copyDir(File("${getTestDataPath()}/$testData"), temp.resolve("REMOTE").toFile()) } } private fun checkSchemes(baseDir: Path, expected: String, ignoreDeleted: Boolean) { val filesToScheme = StringUtil.split(expected, ";") val fileToSchemeMap = THashMap<String, String>() for (fileToScheme in filesToScheme) { val index = fileToScheme.indexOf("->") fileToSchemeMap.put(fileToScheme.substring(0, index), fileToScheme.substring(index + 2)) } baseDir.directoryStreamIfExists { for (file in it) { val fileName = FileUtil.getNameWithoutExtension(file.fileName.toString()) if ("--deleted" == fileName && ignoreDeleted) { assertThat(fileToSchemeMap).containsKey(fileName) } } } for (file in fileToSchemeMap.keys) { assertThat(baseDir.resolve("$file.xml")).isRegularFile() } baseDir.directoryStreamIfExists { for (file in it) { val scheme = loadElement(file).deserialize(TestScheme::class.java) assertThat(fileToSchemeMap.get(FileUtil.getNameWithoutExtension(file.fileName.toString()))).isEqualTo(scheme.name) } } } @Tag("scheme") data class TestScheme(@field:com.intellij.util.xmlb.annotations.Attribute @field:kotlin.jvm.JvmField var name: String = "", @field:com.intellij.util.xmlb.annotations.Attribute var data: String? = null) : ExternalizableScheme, SerializableScheme { override fun getName() = name override fun setName(value: String) { name = value } override fun writeScheme() = serialize() } open class TestSchemesProcessor : LazySchemeProcessor<TestScheme, TestScheme>() { override fun createScheme(dataHolder: SchemeDataHolder<TestScheme>, name: String, attributeProvider: Function<String, String?>, isBundled: Boolean): TestScheme { val scheme = dataHolder.read().deserialize(TestScheme::class.java) dataHolder.updateDigest(scheme) return scheme } }
apache-2.0
f0265e8928cb6e5f8eb52948b8705d62
31.243243
246
0.714356
4.602894
false
true
false
false
LorittaBot/Loritta
pudding/client/src/main/kotlin/net/perfectdreams/loritta/cinnamon/pudding/services/BovespaBrokerService.kt
1
12716
package net.perfectdreams.loritta.cinnamon.pudding.services import kotlinx.datetime.Clock import kotlinx.datetime.toJavaInstant import kotlinx.datetime.toKotlinInstant import mu.KotlinLogging import net.perfectdreams.loritta.common.utils.LorittaBovespaBrokerUtils import net.perfectdreams.loritta.cinnamon.pudding.Pudding import net.perfectdreams.loritta.cinnamon.pudding.data.BrokerTickerInformation import net.perfectdreams.loritta.cinnamon.pudding.data.UserId import net.perfectdreams.loritta.cinnamon.pudding.tables.BoughtStocks import net.perfectdreams.loritta.cinnamon.pudding.tables.Profiles import net.perfectdreams.loritta.cinnamon.pudding.tables.SonhosTransactionsLog import net.perfectdreams.loritta.cinnamon.pudding.tables.TickerPrices import net.perfectdreams.loritta.cinnamon.pudding.tables.transactions.BrokerSonhosTransactionsLog import net.perfectdreams.loritta.cinnamon.pudding.utils.exposed.selectFirstOrNull import org.jetbrains.exposed.sql.SqlExpressionBuilder import org.jetbrains.exposed.sql.and import org.jetbrains.exposed.sql.avg import org.jetbrains.exposed.sql.batchInsert import org.jetbrains.exposed.sql.count import org.jetbrains.exposed.sql.deleteWhere import org.jetbrains.exposed.sql.insert import org.jetbrains.exposed.sql.insertAndGetId import org.jetbrains.exposed.sql.select import org.jetbrains.exposed.sql.sum import org.jetbrains.exposed.sql.update import java.math.BigDecimal class BovespaBrokerService(private val pudding: Pudding) : Service(pudding) { companion object { private val logger = KotlinLogging.logger {} } /** * Gets all ticker informations in the database * * @return a list of all tickers */ suspend fun getAllTickers() = pudding.transaction { TickerPrices.select { TickerPrices.enabled eq true } .map { BrokerTickerInformation( it[TickerPrices.ticker].value, it[TickerPrices.status], it[TickerPrices.value], it[TickerPrices.dailyPriceVariation], it[TickerPrices.lastUpdatedAt].toKotlinInstant() ) } } /** * Gets ticker [tickerId] information in the database * * @return a list of all tickers */ suspend fun getTicker(tickerId: String) = getTickerOrNull(tickerId) ?: error("Ticker $tickerId is not present in the database!") /** * Gets ticker [tickerId] information in the database * * @return a list of all tickers */ suspend fun getTickerOrNull(tickerId: String) = pudding.transaction { TickerPrices.selectFirstOrNull { TickerPrices.ticker eq tickerId } ?.let { BrokerTickerInformation( it[TickerPrices.ticker].value, it[TickerPrices.status], it[TickerPrices.value], it[TickerPrices.dailyPriceVariation], it[TickerPrices.lastUpdatedAt].toKotlinInstant() ) } } /** * Gets all ticker informations in the database * * @return a list of all tickers */ suspend fun getUserBoughtStocks(userId: Long) = pudding.transaction { val stockCount = BoughtStocks.ticker.count() val sumPrice = BoughtStocks.price.sum() val averagePrice = BoughtStocks.price.avg() BoughtStocks .slice(BoughtStocks.ticker, stockCount, sumPrice, averagePrice) .select { BoughtStocks.user eq userId }.groupBy(BoughtStocks.ticker) .map { BrokerUserStockShares( it[BoughtStocks.ticker].value, it[stockCount], it[sumPrice]!!, it[averagePrice]!! ) } } /** * Buys [quantity] shares in the [tickerId] ticker in [userId]'s account * * @param userId the user ID that is buying the assets * @param tickerId the ticker's ID * @param quantity how many assets are going to be bought * @throws StaleTickerDataException if the data is stale and shouldn't be relied on * @throws TooManySharesException if the amount of stocks bought plus the user's current stock count will be more than [LorittaBovespaBrokerUtils.MAX_STOCK_SHARES_PER_USER] * @throws NotEnoughSonhosException if the user doesn't have enough sonhos to purchase the assets * @throws OutOfSessionException if the ticker isn't active */ suspend fun buyStockShares(userId: Long, tickerId: String, quantity: Long): BoughtSharesResponse { if (0 >= quantity) throw TransactionActionWithLessThanOneShareException() return pudding.transaction { val tickerInformation = getTicker(tickerId) val valueOfStock = LorittaBovespaBrokerUtils.convertToBuyingPrice(tickerInformation.value) checkIfTickerIsInactive(tickerInformation) checkIfTickerDataIsStale(tickerInformation) val userProfile = pudding.users.getUserProfile(UserId(userId)) ?: error("User does not have a profile!") val currentStockCount = BoughtStocks.select { BoughtStocks.user eq userProfile.id.value.toLong() }.count() if (quantity + currentStockCount > LorittaBovespaBrokerUtils.MAX_STOCK_SHARES_PER_USER) throw TooManySharesException(currentStockCount) val money = userProfile.money val howMuchValue = valueOfStock * quantity if (howMuchValue > money) throw NotEnoughSonhosException(money, howMuchValue) logger.info { "User $userId is trying to buy $quantity $tickerId for $howMuchValue" } val now = Clock.System.now() // By using shouldReturnGeneratedValues, the database won't need to synchronize on each insert // this increases insert performance A LOT and, because we don't need the IDs, it is very useful to make // stocks purchases be VERY fast BoughtStocks.batchInsert(0 until quantity, shouldReturnGeneratedValues = false) { this[BoughtStocks.user] = userId this[BoughtStocks.ticker] = tickerId this[BoughtStocks.price] = valueOfStock this[BoughtStocks.boughtAt] = now.toEpochMilliseconds() } Profiles.update({ Profiles.id eq userId }) { with(SqlExpressionBuilder) { it.update(Profiles.money, Profiles.money - howMuchValue) } } val timestampLogId = SonhosTransactionsLog.insertAndGetId { it[SonhosTransactionsLog.user] = userId it[SonhosTransactionsLog.timestamp] = now.toJavaInstant() } BrokerSonhosTransactionsLog.insert { it[BrokerSonhosTransactionsLog.timestampLog] = timestampLogId it[BrokerSonhosTransactionsLog.action] = LorittaBovespaBrokerUtils.BrokerSonhosTransactionsEntryAction.BOUGHT_SHARES it[BrokerSonhosTransactionsLog.ticker] = tickerId it[BrokerSonhosTransactionsLog.sonhos] = howMuchValue it[BrokerSonhosTransactionsLog.stockPrice] = tickerInformation.value it[BrokerSonhosTransactionsLog.stockQuantity] = quantity } logger.info { "User $userId bought $quantity $tickerId for $howMuchValue" } return@transaction BoughtSharesResponse( tickerId, quantity, howMuchValue ) } } /** * Sells [quantity] shares in the [tickerId] ticker from [userId]'s account * * @param userId the user ID that is selling the assets * @param tickerId the ticker's ID * @param quantity how many assets are going to be sold * @throws StaleTickerDataException if the data is stale and shouldn't be relied on * @throws NotEnoughSharesException if the [userId] doesn't have enough stocks to be sold * @throws OutOfSessionException if the ticker isn't active */ suspend fun sellStockShares(userId: Long, tickerId: String, quantity: Long): SoldSharesResponse { if (0 >= quantity) throw TransactionActionWithLessThanOneShareException() return pudding.transaction { val tickerInformation = getTicker(tickerId) checkIfTickerIsInactive(tickerInformation) checkIfTickerDataIsStale(tickerInformation) val selfStocks = BoughtStocks.select { BoughtStocks.user eq userId and (BoughtStocks.ticker eq tickerId) }.toList() // Proper exceptions if (quantity > selfStocks.size) throw NotEnoughSharesException(selfStocks.size) val stocksThatWillBeSold = selfStocks.take(quantity.toInt()) val sellingPrice = LorittaBovespaBrokerUtils.convertToSellingPrice(tickerInformation.value) val howMuchWillBePaidToTheUser = sellingPrice * quantity logger.info { "User $userId is trying to sell $quantity $tickerId for $howMuchWillBePaidToTheUser" } val userProfit = howMuchWillBePaidToTheUser - stocksThatWillBeSold.sumOf { it[BoughtStocks.price] } val now = Clock.System.now() // The reason we batch the stocks in multiple queries is due to this issue: // https://github.com/LorittaBot/Loritta/issues/2343 // https://stackoverflow.com/questions/49274390/postgresql-and-hibernate-java-io-ioexception-tried-to-send-an-out-of-range-inte stocksThatWillBeSold.chunked(32767).forEachIndexed { index, chunkedStocks -> BoughtStocks.deleteWhere { BoughtStocks.id inList chunkedStocks.map { it[BoughtStocks.id] } } } Profiles.update({ Profiles.id eq userId }) { with(SqlExpressionBuilder) { it.update(Profiles.money, Profiles.money + howMuchWillBePaidToTheUser) } } val timestampLogId = SonhosTransactionsLog.insertAndGetId { it[SonhosTransactionsLog.user] = userId it[SonhosTransactionsLog.timestamp] = now.toJavaInstant() } BrokerSonhosTransactionsLog.insert { it[BrokerSonhosTransactionsLog.timestampLog] = timestampLogId it[BrokerSonhosTransactionsLog.action] = LorittaBovespaBrokerUtils.BrokerSonhosTransactionsEntryAction.SOLD_SHARES it[BrokerSonhosTransactionsLog.ticker] = tickerId it[BrokerSonhosTransactionsLog.sonhos] = howMuchWillBePaidToTheUser it[BrokerSonhosTransactionsLog.stockPrice] = tickerInformation.value it[BrokerSonhosTransactionsLog.stockQuantity] = quantity } logger.info { "User $userId sold $quantity $tickerId for $howMuchWillBePaidToTheUser" } return@transaction SoldSharesResponse( tickerId, quantity, howMuchWillBePaidToTheUser, userProfit ) } } private fun checkIfTickerIsInactive(tickerInformation: BrokerTickerInformation) { if (!LorittaBovespaBrokerUtils.checkIfTickerIsActive(tickerInformation.status)) throw OutOfSessionException(tickerInformation.status) } private fun checkIfTickerDataIsStale(tickerInformation: BrokerTickerInformation) { if (LorittaBovespaBrokerUtils.checkIfTickerDataIsStale(tickerInformation.lastUpdatedAt)) throw StaleTickerDataException() } data class BrokerUserStockShares( val ticker: String, val count: Long, val sum: Long, val average: BigDecimal ) data class BoughtSharesResponse( val tickerId: String, val quantity: Long, val value: Long ) data class SoldSharesResponse( val tickerId: String, val quantity: Long, val earnings: Long, val profit: Long ) class NotEnoughSonhosException(val userSonhos: Long, val howMuch: Long) : RuntimeException() class OutOfSessionException(val currentSession: String) : RuntimeException() class TooManySharesException(val currentSharesCount: Long) : RuntimeException() class NotEnoughSharesException(val currentBoughtSharesCount: Int) : RuntimeException() class StaleTickerDataException : RuntimeException() class TransactionActionWithLessThanOneShareException : RuntimeException() }
agpl-3.0
347fb23d177c57bda7ad989218a62bd1
41.674497
178
0.664281
5.41798
false
false
false
false
MaibornWolff/codecharta
analysis/model/src/test/kotlin/de/maibornwolff/codecharta/model/NodeMatcher.kt
1
2015
package de.maibornwolff.codecharta.model import org.hamcrest.BaseMatcher import org.hamcrest.Description import org.hamcrest.Matcher object NodeMatcher { fun matchesNode(expectedNode: Node): Matcher<Node> { return object : BaseMatcher<Node>() { override fun describeTo(description: Description) { description.appendText("should be ").appendValue(expectedNode) } override fun matches(item: Any): Boolean { return match(item as Node, expectedNode) } } } fun match(n1: Node, n2: Node): Boolean { return n1.name == n2.name && n1.type == n2.type && linksMatch(n1, n2) && n1.attributes == n2.attributes && n1.children.size == n2.children.size && n1.children.indices .map { match(n1.children.toMutableList()[it], n2.children.toMutableList()[it]) } .fold(true) { x, y -> x && y } } private fun linksMatch(n1: Node, n2: Node) = n1.link == n2.link || (n1.link.isNullOrEmpty() && n2.link.isNullOrEmpty()) fun hasNodeAtPath(node: Node, path: Path): Matcher<Node> { return object : BaseMatcher<Node>() { private var nodeAtPath: Node? = null override fun describeTo(description: Description) { description.appendText("paths should contain ").appendValue(node).appendText(" at ").appendValue(path) } override fun matches(item: Any?): Boolean { nodeAtPath = (item as Node).getNodeBy(path) as Node return if (nodeAtPath == null) false else match(nodeAtPath!!, node) } override fun describeMismatch(item: Any, description: Description) { description.appendText("but was ").appendValue(nodeAtPath) description.appendText(", where paths to leaves were ").appendValue((item as MutableNode).pathsToLeaves) } } } }
bsd-3-clause
0511f5293db0a7dd548b93b9942ae390
35.636364
120
0.587593
4.41886
false
false
false
false
talent-bearers/Slimefusion
src/main/java/talent/bearers/slimefusion/common/block/BlockMoonshard.kt
1
3340
package talent.bearers.slimefusion.common.block import com.teamwizardry.librarianlib.common.base.block.BlockMod import net.minecraft.block.SoundType import net.minecraft.block.material.Material import net.minecraft.block.properties.PropertyEnum import net.minecraft.block.state.BlockStateContainer import net.minecraft.block.state.IBlockState import net.minecraft.entity.player.EntityPlayer import net.minecraft.item.ItemStack import net.minecraft.util.EnumFacing import net.minecraft.util.math.AxisAlignedBB import net.minecraft.util.math.BlockPos import net.minecraft.util.math.RayTraceResult import net.minecraft.world.IBlockAccess import net.minecraft.world.World import talent.bearers.slimefusion.common.core.EnumOreType import talent.bearers.slimefusion.common.items.ModItems import talent.bearers.slimefusion.common.lib.LibNames import java.util.* /** * @author WireSegal * Created at 5:13 PM on 12/29/16. */ class BlockMoonshard : BlockMod(LibNames.MOONSHARD, Material.IRON, *EnumOreType.getNamesFor(LibNames.MOONSHARD)) { companion object { val TYPE: PropertyEnum<EnumOreType> = PropertyEnum.create("ore", EnumOreType::class.java) val SIDE: PropertyEnum<EnumFacing> = PropertyEnum.create("side", EnumFacing::class.java, EnumFacing.UP, EnumFacing.DOWN) val AABB_DOWN = AxisAlignedBB(5.5 / 16, 0.0, 5.5 / 16, 10.5 / 16, 1.0 / 16, 10.5 / 16) val AABB_UP = AxisAlignedBB(5.5 / 16, 0.0, 5.5 / 16, 10.5 / 16, 1.0 / 16, 10.5 / 16) val RAND = Random() } init { setHardness(5.0F) setResistance(10.0F) soundType = SoundType.METAL } override fun canSilkHarvest(world: World?, pos: BlockPos?, state: IBlockState?, player: EntityPlayer?) = true override fun createStackedBlock(state: IBlockState) = ItemStack(this, 1, state.getValue(TYPE).ordinal) override fun isOpaqueCube(state: IBlockState) = false override fun isFullCube(state: IBlockState) = false override fun getPickBlock(state: IBlockState, target: RayTraceResult, world: World?, pos: BlockPos?, player: EntityPlayer?) = createStackedBlock(state) override fun getDrops(world: IBlockAccess, pos: BlockPos, state: IBlockState, fortune: Int): MutableList<ItemStack> { val type = state.getValue(TYPE) val totalDrops = Math.max(RAND.nextInt(fortune + 3) + 1, 1) val secondaryDrops = if (type.rareDrop != null) (RAND.nextDouble() * totalDrops * 0.5).toInt() else 0 val ret = mutableListOf<ItemStack>() for (i in 0 until (totalDrops - secondaryDrops)) ret.add(ItemStack(ModItems.CRYSTAL, 1, type.mainDrop.ordinal)) for (i in 0 until secondaryDrops) ret.add(ItemStack(ModItems.CRYSTAL, 1, type.rareDrop?.ordinal ?: 0)) return ret } override fun createBlockState() = BlockStateContainer(this, TYPE, SIDE) override fun getMetaFromState(state: IBlockState) = state.getValue(TYPE).ordinal or (state.getValue(SIDE).index shl 3) override fun getStateFromMeta(meta: Int) = defaultState .withProperty(TYPE, EnumOreType[meta and 7]) .withProperty(SIDE, EnumFacing.VALUES[(meta and 8) shr 3]) override fun getBoundingBox(state: IBlockState, source: IBlockAccess, pos: BlockPos) = if (state.getValue(SIDE) == EnumFacing.UP) AABB_UP else AABB_DOWN }
mit
8ad6e3835eb4bb037207e8db872a4e49
45.388889
128
0.72485
3.852364
false
false
false
false
appnexus/mobile-sdk-android
examples/kotlin/LazyLoadDemo/app/src/main/java/com/xandr/lazyloaddemo/adapter/AdViewRecyclerAdapter.kt
1
13741
package appnexus.com.appnexussdktestapp.adapter import android.annotation.SuppressLint import android.content.Context import android.graphics.Bitmap import android.net.Uri import android.os.Handler import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.* import androidx.recyclerview.widget.RecyclerView import com.appnexus.opensdk.AdView import com.appnexus.opensdk.BannerAdView import com.appnexus.opensdk.InterstitialAdView import com.appnexus.opensdk.NativeAdResponse import com.appnexus.opensdk.instreamvideo.Quartile import com.appnexus.opensdk.instreamvideo.VideoAd import com.appnexus.opensdk.instreamvideo.VideoAdPlaybackListener import com.appnexus.opensdk.utils.Clog import com.appnexus.opensdk.utils.ViewUtil import com.xandr.lazyloaddemo.R import kotlinx.android.synthetic.main.layout_ad_view.view.* import java.util.* class AdViewRecyclerAdapter(val items: ArrayList<Any?>, val context: Context) : RecyclerView.Adapter<AdViewRecyclerAdapter.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return ViewHolder( LayoutInflater.from(context).inflate( R.layout.layout_ad_view, parent, false ) ) } override fun getItemCount(): Int { return items.size } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val currentAd = items.get(position) if (currentAd is NativeAdResponse) { handleNativeResponse(currentAd, holder.layoutMain) } else if (currentAd is AdView) { if (currentAd is InterstitialAdView) { holder.layoutMain.setOnClickListener({ currentAd.show() }) } else { if (currentAd is BannerAdView) { if (currentAd.isLazyLoadEnabled && currentAd.getTag( R.string.button_tag ) == null ) { val btn = Button(context) btn.setText("Activate") btn.setOnClickListener { Clog.e("LAZYLOAD", "Webview Activated") currentAd.loadLazyAd() currentAd.setTag(R.string.button_tag, btn) } currentAd.setTag(R.string.button_tag, true) holder.layoutMain.addView(btn) } else { if (currentAd.getTag(R.string.button_tag) is Button && currentAd.isLazyLoadEnabled) { ViewUtil.removeChildFromParent(currentAd.getTag(R.string.button_tag) as Button) ViewUtil.removeChildFromParent(currentAd) holder.layoutMain.addView(currentAd) Clog.e("LAZYLOAD", "Banner Added to the parent view") currentAd.post({ Clog.e("WIDTH", "${currentAd.width}") Clog.e("HEIGHT", "${currentAd.height}") currentAd.invalidate() currentAd.visibility = View.VISIBLE }) } else { ViewUtil.removeChildFromParent(currentAd) holder.layoutMain.addView(currentAd) Clog.e("LAZYLOAD", "Banner Added to the parent view") currentAd.post({ Clog.e("WIDTH", "${currentAd.width}") Clog.e("HEIGHT", "${currentAd.height}") currentAd.invalidate() currentAd.visibility = View.VISIBLE }) } } } } } else if (currentAd is VideoAd) { handleVideoAd(currentAd, holder.layoutMain) } } class ViewHolder(view: View) : RecyclerView.ViewHolder(view) { // Holds the TextView that will add each animal to val layoutMain = view.layoutMain } private fun handleVideoAd(videoAd: VideoAd, layoutVideo: LinearLayout) { // Load and display a Video // Video Ad elements val instreamVideoLayout = LayoutInflater.from(context).inflate(R.layout.fragment_preview_instream, null) val playButon = instreamVideoLayout.findViewById(R.id.play_button) as ImageButton playButon.visibility = View.VISIBLE val videoPlayer = instreamVideoLayout.findViewById(R.id.video_player) as VideoView val baseContainer = instreamVideoLayout.findViewById(R.id.instream_container_Layout) as RelativeLayout layoutVideo.removeAllViews() layoutVideo.addView(baseContainer) baseContainer.layoutParams.height = 1000 baseContainer.layoutParams.width = RelativeLayout.LayoutParams.MATCH_PARENT videoPlayer.setVideoURI(Uri.parse("https://acdn.adnxs.com/mobile/video_test/content/Scenario.mp4")) val controller = MediaController(context) videoPlayer.setMediaController(controller) playButon.setOnClickListener { if (videoAd.isReady) { videoAd.playAd(baseContainer) } else { videoPlayer.start() } playButon.visibility = View.INVISIBLE } // Set PlayBack Listener. videoAd.videoPlaybackListener = object : VideoAdPlaybackListener { override fun onAdPlaying(videoAd: VideoAd) { Clog.d("VideoAd", "onAdPlaying::") } override fun onQuartile(view: VideoAd, quartile: Quartile) { Clog.d("VideoAd", "onQuartile::$quartile") } override fun onAdCompleted( view: VideoAd, playbackState: VideoAdPlaybackListener.PlaybackCompletionState ) { if (playbackState == VideoAdPlaybackListener.PlaybackCompletionState.COMPLETED) { Clog.d("VideoAd", "adCompleted::playbackState") } else if (playbackState == VideoAdPlaybackListener.PlaybackCompletionState.SKIPPED) { Clog.d("VideoAd", "adSkipped::") } videoPlayer.start() } override fun onAdMuted(view: VideoAd, isMute: Boolean) { Clog.d("VideoAd", "isAudioMute::$isMute") } override fun onAdClicked(adView: VideoAd) { Clog.d("VideoAd", "onAdClicked") } override fun onAdClicked(videoAd: VideoAd, clickUrl: String) { Clog.d("VideoAd", "onAdClicked::clickUrl$clickUrl") } } } private fun handleNativeResponse(response: NativeAdResponse, layoutNative: LinearLayout) { val builder = NativeAdBuilder(context) if (response.icon != null) builder.setIconView(response.icon) if (response.image != null) builder.setImageView(response.image) builder.setTitle(response.title) builder.setDescription(response.description) builder.setCallToAction(response.callToAction) builder.setSponsoredBy(response.sponsoredBy) if (response.adStarRating != null) { builder.setAdStartValue(response.adStarRating.value.toString() + "/" + response.adStarRating.scale.toString()) } // register all the views if (builder.container != null && builder.container!!.parent != null) (builder.container!!.parent as ViewGroup).removeAllViews() val nativeContainer = builder.container Handler().post { layoutNative.removeAllViews() layoutNative.addView(nativeContainer) } } internal inner class NativeAdBuilder @SuppressLint("NewApi") constructor(context: Context) { var container: RelativeLayout? = null var iconAndTitle: LinearLayout var customViewLayout: LinearLayout var imageView: ImageView var iconView: ImageView var title: TextView var description: TextView var callToAction: TextView var adStarRating: TextView var socialContext: TextView var sponsoredBy: TextView var customView = null // Any Mediated network requiring to render there own view for impression tracking would go in here. var views: LinkedList<View>? = null val allViews: LinkedList<View> get() { if (views == null) { views = LinkedList() views!!.add(imageView) views!!.add(iconView) views!!.add(title) views!!.add(description) views!!.add(callToAction) views!!.add(adStarRating) views!!.add(socialContext) views!!.add(sponsoredBy) } return views as LinkedList<View> } init { container = RelativeLayout(context) iconAndTitle = LinearLayout(context) iconAndTitle.id = View.generateViewId() iconAndTitle.orientation = LinearLayout.HORIZONTAL iconView = ImageView(context) iconAndTitle.addView(iconView) title = TextView(context) iconAndTitle.addView(title) container!!.addView(iconAndTitle) imageView = ImageView(context) imageView.id = View.generateViewId() val imageView_params = RelativeLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT ) imageView_params.addRule(RelativeLayout.BELOW, iconAndTitle.id) description = TextView(context) description.id = View.generateViewId() val description_params = RelativeLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT ) description_params.addRule(RelativeLayout.BELOW, imageView.id) callToAction = TextView(context) callToAction.id = View.generateViewId() val callToAction_params = RelativeLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT ) callToAction_params.addRule(RelativeLayout.BELOW, description.id) adStarRating = TextView(context) adStarRating.id = View.generateViewId() val adStarRating_params = RelativeLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT ) adStarRating_params.addRule(RelativeLayout.BELOW, callToAction.id) socialContext = TextView(context) socialContext.id = View.generateViewId() val socialContext_params = RelativeLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT ) socialContext_params.addRule(RelativeLayout.BELOW, adStarRating.id) sponsoredBy = TextView(context) sponsoredBy.id = View.generateViewId() val sponsoredBy_params = RelativeLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT ) sponsoredBy_params.addRule(RelativeLayout.BELOW, socialContext.id) customViewLayout = LinearLayout(context) customViewLayout.id = View.generateViewId() customViewLayout.orientation = LinearLayout.HORIZONTAL val customViewLayout_params = RelativeLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT ) customViewLayout_params.addRule(RelativeLayout.BELOW, sponsoredBy.id) container!!.addView(description, description_params) container!!.addView(imageView, imageView_params) container!!.addView(callToAction, callToAction_params) container!!.addView(adStarRating, adStarRating_params) container!!.addView(socialContext, socialContext_params) container!!.addView(sponsoredBy, sponsoredBy_params) container!!.addView(customViewLayout, customViewLayout_params) } fun setImageView(bitmap: Bitmap) { imageView.setImageBitmap(bitmap) } fun setIconView(bitmap: Bitmap) { iconView.setImageBitmap(bitmap) } fun setCustomView(customView: View) { this.customViewLayout.addView(customView) } fun setTitle(title: String) { this.title.text = title } fun setDescription(description: String) { this.description.text = description } fun setCallToAction(callToAction: String) { this.callToAction.text = callToAction } fun setSocialContext(socialContext: String) { this.socialContext.text = socialContext } fun setSponsoredBy(sponsoredBy: String) { this.sponsoredBy.text = sponsoredBy } fun setAdStartValue(value: String) { this.adStarRating.text = value } } }
apache-2.0
c8505709a487ec9cc88d7f032ef0ddf2
38.262857
122
0.592752
5.492006
false
false
false
false
christophpickl/gadsu
src/main/kotlin/at/cpickl/gadsu/client/view/renderer.kt
1
1584
package at.cpickl.gadsu.client.view import at.cpickl.gadsu.client.Client import at.cpickl.gadsu.view.ViewConstants import at.cpickl.gadsu.view.components.panels.GridPanel import at.cpickl.gadsu.view.swing.Pad import at.cpickl.gadsu.view.swing.opaque import java.awt.Component import java.awt.GridBagConstraints import javax.swing.JLabel import javax.swing.JList import javax.swing.ListCellRenderer //class ClientRenderer : DefaultListCellRenderer() { // // override fun getListCellRendererComponent(list: JList<*>?, value: Any?, index: Int, isSelected: Boolean, cellHasFocus: Boolean): Component { // val comp = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus) // (comp as JLabel).text = (value as Client?)?.fullName ?: "null" // return comp // } // //} class ClientRenderer : ListCellRenderer<Client> { override fun getListCellRendererComponent(list: JList<out Client>?, value: Client?, index: Int, isSelected: Boolean, cellHasFocus: Boolean): Component { val panel = GridPanel() panel.opaque() ViewConstants.Table.changeBackground(panel, cellHasFocus) with(panel.c) { fill = GridBagConstraints.VERTICAL anchor = GridBagConstraints.WEST weightx = 0.0 panel.add(JLabel(value?.picture?.toViewLilRepresentation())) gridx++ insets = Pad.LEFT fill = GridBagConstraints.BOTH weightx = 1.0 panel.add(JLabel(value?.preferredName ?: "null")) } return panel } }
apache-2.0
9f0ba11ff8116062ed2aa0f8ff75871e
32.702128
156
0.683712
4.4
false
false
false
false
danrien/projectBlue
projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/client/stored/library/items/files/download/GivenARequestForAStoredFile/ThatSucceeds/WhenDownloading.kt
2
2330
package com.lasthopesoftware.bluewater.client.stored.library.items.files.download.GivenARequestForAStoredFile.ThatSucceeds import com.lasthopesoftware.bluewater.client.browsing.items.media.files.ServiceFileUriQueryParamsProvider import com.lasthopesoftware.bluewater.client.browsing.library.repository.LibraryId import com.lasthopesoftware.bluewater.client.connection.FakeConnectionProvider import com.lasthopesoftware.bluewater.client.connection.FakeConnectionResponseTuple import com.lasthopesoftware.bluewater.client.connection.libraries.ProvideLibraryConnections import com.lasthopesoftware.bluewater.client.stored.library.items.files.download.StoredFileDownloader import com.lasthopesoftware.bluewater.client.stored.library.items.files.repository.StoredFile import com.lasthopesoftware.bluewater.shared.promises.extensions.FuturePromise import com.lasthopesoftware.bluewater.shared.promises.extensions.ProgressingPromise import org.apache.commons.io.IOUtils import org.assertj.core.api.Assertions import org.junit.BeforeClass import org.junit.Test import org.mockito.Mockito import java.io.ByteArrayOutputStream import java.io.IOException import java.io.InputStream import java.util.* class WhenDownloading { companion object { private val responseBytes by lazy { val bytes = ByteArray(400) Random().nextBytes(bytes) bytes } private var inputStream: InputStream? = null @BeforeClass @JvmStatic fun before() { val fakeConnectionProvider = FakeConnectionProvider() fakeConnectionProvider.mapResponse({ FakeConnectionResponseTuple( 200, responseBytes ) }) val libraryConnections = Mockito.mock( ProvideLibraryConnections::class.java ) Mockito.`when`(libraryConnections.promiseLibraryConnection(LibraryId(4))) .thenReturn(ProgressingPromise(fakeConnectionProvider)) val downloader = StoredFileDownloader(ServiceFileUriQueryParamsProvider(), libraryConnections) inputStream = FuturePromise( downloader.promiseDownload( LibraryId(4), StoredFile().setServiceId(4) ) ).get() } } @Test @Throws(IOException::class) fun thenTheInputStreamIsReturned() { val outputStream = ByteArrayOutputStream() IOUtils.copy(inputStream, outputStream) Assertions.assertThat(outputStream.toByteArray()).containsExactly(*responseBytes) } }
lgpl-3.0
56b7774c5414029a54a4bdc21ed99182
35.40625
122
0.81588
4.429658
false
false
false
false
hcoles/pitest
pitest-maven-verification/src/test/resources/pit-kotlin-multi-module/sub-module-1/src/main/kotlin/NamedArguments.kt
1
1166
package com.example.one fun main() { resizePane(newSize = 10, forceResize = true, noAnimation = false) // Swap the order of last two named arguments resizePane(newSize = 11, noAnimation = false, forceResize = true) // Named arguments can be passed in any order resizePane(forceResize = true, newSize = 12, noAnimation = false) // Mixing Named and Positional Arguments // Kotlin 1.3 would allow us to name only the arguments after the positional ones resizePane(20, true, noAnimation = false) // Using a positional argument in the middle of named arguments (supported from Kotlin 1.4.0) // resizePane(newSize = 20, true, noAnimation = false) // Only the last argument as a positional argument (supported from Kotlin 1.4.0) // resizePane(newSize = 30, forceResize = true, false) // Use a named argument in the middle of positional arguments (supported from Kotlin 1.4.0) // resizePane(40, forceResize = true, false) } fun resizePane(newSize: Int, forceResize: Boolean, noAnimation: Boolean) { println("The parameters are newSize = $newSize, forceResize = $forceResize, noAnimation = $noAnimation") }
apache-2.0
0e78b548314c4e04b2ebd271b95615b2
40.642857
108
0.713551
4.4
false
false
false
false
DevCharly/kotlin-ant-dsl
examples/src/demo.kt
1
2428
import com.devcharly.kotlin.ant.* import java.io.File fun main(args: Array<String>) { // make basedirs used below File("_files_").mkdirs() File("_fileset_").mkdirs() File("_zip_").mkdirs() demoEcho() demoProperty() demoFiles() demoFileset() demoZip() demoTar() demoJar() demoJava() } fun demoEcho() { Ant { echo("Hello World") echo { +"aa" +"bb" +"cc" } echo(level = EchoLevel.ERROR) { +""" 111 22 3 """ } } } fun demoProperty() { Ant { property("place", "World") echo("Hello ${p("place")}") } } fun demoFiles() { Ant(basedir = "_files_") { touch("file.txt") echo("content2\n", file = "file2.txt", append = true) copy("file.txt", todir = "dir", overwrite = true) copy("file2.txt", tofile = "dir/file2.txt") delete("file.txt") } } fun demoFileset() { Ant(basedir = "_fileset_", logLevel = LogLevel.VERBOSE) { mkdir("dir1") mkdir("dir2") touch("dir1/file1.java") touch("dir2/file2.java") touch("dir2/fileTest.java") copy(todir = "dir") { fileset("dir1") fileset("dir2") { include(name = "**/*.java") exclude(name = "**/*Test*") } } } } fun demoZip() { Ant(basedir = "_zip_") { echo("content1", file = "dir/file1.txt") echo("content2", file = "dir/file2.txt") zip("out1.zip", basedir = "dir") zip("out2.zip", basedir = "dir", includes = "file1.txt") zip("out3.zip") { fileset(dir = "dir", includes = "file2.txt") } zip("out4.zip") { zipfileset(dir = "dir", prefix = "pre-dir") } } } fun demoTar() { Ant(basedir = "_zip_", logLevel = LogLevel.VERBOSE) { tar("out1.tar") { tarfileset(dir = "dir", username = "user1", uid = 123, filemode = "600") } bzip2(src = "out1.tar", destfile = "out1.tar.bz2") gzip(src = "out1.tar", destfile = "out1.tar.gz") bunzip2(src = "out1.tar.bz2", dest = "out1b.tar") gunzip(src = "out1.tar.gz", dest = "out1g.tar") } } fun demoJar() { Ant(basedir = "_zip_") { jar(destfile = "out1.jar", basedir = "dir") { manifest { attribute("Main-Class", "com.myapp.Main") attribute("Class-Path", "common.jar") } service("javax.script.ScriptEngineFactory") { provider("org.acme.PinkyLanguage") provider("org.acme.BrainLanguage") } } } } fun demoJava() { Ant { java(classname="test.Main") { arg("-h") classpath { pathelement(location = "dist/test.jar") pathelement(path = p("java.class.path")) } } } }
apache-2.0
5ea68d40356446e70f57504f22022cc0
17.821705
75
0.58196
2.55042
false
false
false
false
ruuvi/Android_RuuvitagScanner
app/src/main/java/com/ruuvi/station/tag/domain/TagConverter.kt
1
1316
package com.ruuvi.station.tag.domain import android.content.Context import com.ruuvi.station.app.preferences.Preferences import com.ruuvi.station.database.tables.RuuviTagEntity import com.ruuvi.station.units.domain.UnitsConverter class TagConverter( private val context: Context, private val preferences: Preferences, private val unitsConverter: UnitsConverter ) { fun fromDatabase(entity: RuuviTagEntity): RuuviTag = RuuviTag( id = entity.id.orEmpty(), name = entity.name.orEmpty(), displayName = entity.name ?: entity.id.toString(), rssi = entity.rssi, temperature = entity.temperature, humidity = entity.humidity, pressure = entity.pressure, updatedAt = entity.updateAt, temperatureString = unitsConverter.getTemperatureString(entity.temperature), humidityString = unitsConverter.getHumidityString(entity.humidity, entity.temperature), pressureString = unitsConverter.getPressureString(entity.pressure), defaultBackground = entity.defaultBackground, userBackground = entity.userBackground, dataFormat = entity.dataFormat, connectable = entity.connectable, lastSync = entity.lastSync ) }
mit
0787a1b0ceae11f98ca466aafd60f681
38.909091
99
0.682371
4.892193
false
false
false
false
curiosityio/AndroidBoilerplate
androidboilerplate/src/main/java/com/curiosityio/androidboilerplate/util/ValidCheckUtil.kt
1
1459
package com.curiosityio.androidboilerplate.util import android.telephony.PhoneNumberUtils import android.util.Patterns open class ValidCheckUtil { companion object { fun isValidEmail(email: String?): Boolean { if (email == null) return false else return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches() } fun isValidPhoneNumber(number: String?): Boolean { if (number == null) return false else return PhoneNumberUtils.isGlobalPhoneNumber(number) } fun isValidURL(url: String?): Boolean { if (url == null) return false else return Patterns.WEB_URL.matcher(url).matches() } fun isValidFirstAndLastName(fullname: String): Boolean { // regex accepts any [1 or more none whitespace character(s)], [one space], [1 or more none whitespace character(s)] // (allows hyphens in names for example why allowing any non-whitespace char.) val splitFullName = fullname.trim { it <= ' ' }.split("\\S+[ ]\\S+".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() return splitFullName.size == 2 } fun getSplitFullName(fullname: String): Array<String>? { if (isValidFirstAndLastName(fullname)) { return fullname.trim { it <= ' ' }.split("\\S+[ ]\\S+".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() } return null } } }
mit
9a1d828f2736e8d1e7371422c3e803f5
37.394737
136
0.625771
4.573668
false
false
false
false
ReactiveCircus/FlowBinding
flowbinding-material/src/androidTest/java/reactivecircus/flowbinding/material/BottomSheetBehaviorStateChangedFlowTest.kt
1
2256
package reactivecircus.flowbinding.material import android.view.View import androidx.test.filters.LargeTest import com.google.android.material.bottomsheet.BottomSheetBehavior import com.google.common.truth.Truth.assertThat import org.junit.Test import reactivecircus.flowbinding.material.fixtures.MaterialFragment1 import reactivecircus.flowbinding.material.test.R import reactivecircus.flowbinding.testing.FlowRecorder import reactivecircus.flowbinding.testing.launchTest import reactivecircus.flowbinding.testing.recordWith @LargeTest class BottomSheetBehaviorStateChangedFlowTest { @Test fun bottomSheetStateChanges() { launchTest<MaterialFragment1> { val recorder = FlowRecorder<Int>(testScope) val bottomSheet = getViewById<View>(R.id.bottomSheetLayout) val behavior = BottomSheetBehavior.from(bottomSheet) bottomSheet.bottomSheetStateChanges().recordWith(recorder) recorder.assertNoMoreValues() behavior.state = BottomSheetBehavior.STATE_EXPANDED // STATE_DRAGGING state is not emitted for programmatic state change assertThat(recorder.takeValue()) .isEqualTo(BottomSheetBehavior.STATE_SETTLING) assertThat(recorder.takeValue()) .isEqualTo(BottomSheetBehavior.STATE_EXPANDED) behavior.state = BottomSheetBehavior.STATE_COLLAPSED // STATE_DRAGGING state is not emitted for programmatic state change assertThat(recorder.takeValue()) .isEqualTo(BottomSheetBehavior.STATE_SETTLING) assertThat(recorder.takeValue()) .isEqualTo(BottomSheetBehavior.STATE_COLLAPSED) behavior.state = BottomSheetBehavior.STATE_HIDDEN // STATE_DRAGGING state is not emitted for programmatic state change assertThat(recorder.takeValue()) .isEqualTo(BottomSheetBehavior.STATE_SETTLING) assertThat(recorder.takeValue()) .isEqualTo(BottomSheetBehavior.STATE_HIDDEN) cancelTestScope() recorder.clearValues() behavior.state = BottomSheetBehavior.STATE_EXPANDED recorder.assertNoMoreValues() } } }
apache-2.0
1edc4d585bcad2982e50567ef97e48eb
40.018182
80
0.708777
5.890339
false
true
false
false
mp911de/lettuce
src/main/kotlin/io/lettuce/core/sentinel/api/coroutines/RedisSentinelCoroutinesCommandsImpl.kt
1
3601
/* * Copyright 2020-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 io.lettuce.core.sentinel.api.coroutines import io.lettuce.core.ExperimentalLettuceCoroutinesApi import io.lettuce.core.KillArgs import io.lettuce.core.output.CommandOutput import io.lettuce.core.protocol.CommandArgs import io.lettuce.core.protocol.ProtocolKeyword import io.lettuce.core.sentinel.api.reactive.RedisSentinelReactiveCommands import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.toList import kotlinx.coroutines.reactive.asFlow import kotlinx.coroutines.reactive.awaitFirstOrNull import kotlinx.coroutines.reactive.awaitLast import java.net.SocketAddress /** * Coroutine executed commands (based on reactive commands) for Redis Sentinel. * * @param <K> Key type. * @param <V> Value type. * @author Mikhael Sokolov * @since 6.0 */ @ExperimentalLettuceCoroutinesApi internal class RedisSentinelCoroutinesCommandsImpl<K : Any, V : Any>(private val ops: RedisSentinelReactiveCommands<K, V>) : RedisSentinelCoroutinesCommands<K, V> { override suspend fun getMasterAddrByName(key: K): SocketAddress = ops.getMasterAddrByName(key).awaitLast() override suspend fun masters(): List<Map<K, V>> = ops.masters().asFlow().toList() override suspend fun master(key: K): Map<K, V> = ops.master(key).awaitLast() override suspend fun slaves(key: K): List<Map<K, V>> = ops.slaves(key).asFlow().toList() override suspend fun reset(key: K): Long = ops.reset(key).awaitLast() override suspend fun failover(key: K): String = ops.failover(key).awaitLast() override suspend fun monitor(key: K, ip: String, port: Int, quorum: Int): String = ops.monitor(key, ip, port, quorum).awaitLast() override suspend fun set(key: K, option: String, value: V): String = ops.set(key, option, value).awaitLast() override suspend fun remove(key: K): String = ops.remove(key).awaitLast() override suspend fun clientGetname(): K? = ops.clientGetname().awaitFirstOrNull() override suspend fun clientSetname(name: K): String = ops.clientSetname(name).awaitLast() override suspend fun clientKill(addr: String): String = ops.clientKill(addr).awaitLast() override suspend fun clientKill(killArgs: KillArgs): Long = ops.clientKill(killArgs).awaitLast() override suspend fun clientPause(timeout: Long): String = ops.clientPause(timeout).awaitLast() override suspend fun clientList(): String = ops.clientList().awaitLast() override suspend fun info(): String = ops.info().awaitLast() override suspend fun info(section: String): String = ops.info(section).awaitLast() override suspend fun ping(): String = ops.ping().awaitLast() override fun <T : Any> dispatch(type: ProtocolKeyword, output: CommandOutput<K, V, T>): Flow<T> = ops.dispatch<T>(type, output).asFlow() override fun <T : Any> dispatch(type: ProtocolKeyword, output: CommandOutput<K, V, T>, args: CommandArgs<K, V>): Flow<T> = ops.dispatch<T>(type, output, args).asFlow() override fun isOpen(): Boolean = ops.isOpen }
apache-2.0
1def200c6baa4717f6653380c805dc7f
40.872093
171
0.742016
3.965859
false
false
false
false
wireapp/wire-android
storage/src/main/kotlin/com/waz/zclient/storage/db/history/EditHistoryEntity.kt
1
450
package com.waz.zclient.storage.db.history import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey @Entity(tableName = "EditHistory") data class EditHistoryEntity( @PrimaryKey @ColumnInfo(name = "original_id") val originalId: String, @ColumnInfo(name = "updated_id", defaultValue = "") val updatedId: String, @ColumnInfo(name = "timestamp", defaultValue = "0") val timestamp: Int )
gpl-3.0
cc6437a701bd23585e125843c625f2bd
24
55
0.722222
3.982301
false
false
false
false
Constantinuous/Angus
infrastructure/src/main/kotlin/de/constantinuous/angus/parsing/impl/JdbcDatabaseParser.kt
1
1558
package de.constantinuous.angus.parsing.impl import de.constantinuous.angus.parsing.DatabaseParser import java.sql.Connection import java.sql.DriverManager import java.sql.SQLException /** * Created by RichardG on 09.10.2016. */ class JdbcDatabaseParser : DatabaseParser { override fun extractFoo(connectionString: String, user: String, password: String){ val conn = DriverManager.getConnection(connectionString, user, password) conn.catalog = "IOL_Dubai_P" val md = conn.metaData val numericFunctions = md.numericFunctions.split(",") val procedures = md.getProcedures(null, null, "%") val tables = md.getTables(null, null, "%", null) println("---- Procedures ----") while (procedures.next()) { println("Procedure: "+procedures.getString(3)) } println("---- Functions ----") for (function in numericFunctions) { println("Numeric Function: "+function) } println("---- Tables ----") while (tables.next()) { println("Table: "+tables.getString(3)) } } private fun getProcedureCode(connection: Connection, myViewName : String){ val query = "exec sp_helptext ?" val stmt = connection.prepareStatement(query) stmt.setString(1, myViewName) val rs = stmt.executeQuery() val b = StringBuilder() while (rs.next()) { b.append(rs.getString("Text")) } rs.close() stmt.close() println(b.toString()) } }
mit
6b9fe954c49073bcb531ba98cf2c5e42
31.479167
86
0.61104
4.351955
false
false
false
false
bachhuberdesign/deck-builder-gwent
app/src/main/java/com/bachhuberdesign/deckbuildergwent/features/cardviewer/CardViewerController.kt
1
13230
package com.bachhuberdesign.deckbuildergwent.features.cardviewer import android.graphics.Color import android.os.Bundle import android.support.v4.view.MenuItemCompat import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.support.v7.widget.SearchView import android.util.Log import android.view.* import com.afollestad.materialdialogs.MaterialDialog import com.bachhuberdesign.deckbuildergwent.MainActivity import com.bachhuberdesign.deckbuildergwent.R import com.bachhuberdesign.deckbuildergwent.features.deckbuild.Deck import com.bachhuberdesign.deckbuildergwent.features.deckbuild.DeckbuildController import com.bachhuberdesign.deckbuildergwent.features.shared.model.Card import com.bachhuberdesign.deckbuildergwent.features.shared.model.Lane import com.bachhuberdesign.deckbuildergwent.inject.module.ActivityModule import com.bachhuberdesign.deckbuildergwent.util.changehandler.SharedElementDelayingChangeHandler import com.bachhuberdesign.deckbuildergwent.util.getStringResourceByName import com.bachhuberdesign.deckbuildergwent.util.inflate import com.bluelinelabs.conductor.Controller import com.bluelinelabs.conductor.RouterTransaction import com.bluelinelabs.conductor.changehandler.FadeChangeHandler import com.bluelinelabs.conductor.changehandler.TransitionChangeHandlerCompat import com.google.gson.Gson import com.mikepenz.fastadapter.FastAdapter import com.mikepenz.fastadapter.commons.adapters.FastItemAdapter import com.mikepenz.fastadapter.helpers.ClickListenerHelper import com.mikepenz.fastadapter.listeners.ClickEventHook import com.mikepenz.fontawesome_typeface_library.FontAwesome import com.mikepenz.iconics.IconicsDrawable import kotlinx.android.synthetic.main.controller_cardviewer.view.* import javax.inject.Inject /** * @author Eric Bachhuber * @version 1.0.0 * @since 1.0.0 */ class CardViewerController : Controller, CardViewerMvpContract { constructor(filters: CardFilters) : super() { this.filters = filters } constructor(filters: CardFilters, deckId: Int) { this.filters = filters this.deckId = deckId } constructor(args: Bundle) : super() companion object { @JvmStatic val TAG: String = CardViewerController::class.java.name } @Inject lateinit var presenter: CardViewerPresenter @Inject lateinit var gson: Gson lateinit var recyclerView: RecyclerView lateinit var adapter: FastItemAdapter<CardItem> var currentSortMethod: Int = 0 var isSortAscending = true var isAddCardButtonClickable = true var filters: CardFilters? = null var deckId: Int = 0 override fun onCreateView(inflater: LayoutInflater, container: ViewGroup): View { val view = container.inflate(R.layout.controller_cardviewer) (activity as MainActivity).persistedComponent .activitySubcomponent(ActivityModule(activity!!)) .inject(this) if (filters == null) { filters = gson.fromJson(args.getString("filters"), CardFilters::class.java) } if (deckId == 0) { deckId = args.getInt("deckId", 0) } if (deckId > 0) { (activity as MainActivity).displayHomeAsUp(true) } else { activity?.title = "Card Database" } setHasOptionsMenu(true) initRecyclerView(view) return view } override fun onAttach(view: View) { Log.d(TAG, "onAttach()") super.onAttach(view) presenter.attach(this) // TODO: Take getCards() call off UI thread presenter.getCards(filters!!, deckId) } override fun onDetach(view: View) { Log.d(TAG, "onDetach()") super.onDetach(view) presenter.detach() } override fun onDestroyView(view: View) { (activity as MainActivity).displayHomeAsUp(false) super.onDestroyView(view) } override fun onSaveInstanceState(outState: Bundle) { outState.putString("filters", gson.toJson(filters)) outState.putInt("deckId", deckId) super.onSaveInstanceState(outState) } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.menu_card_viewer, menu) menu.findItem(R.id.menu_filter_cards).icon = IconicsDrawable(activity!!) .icon(FontAwesome.Icon.faw_sort_amount_desc) .color(Color.WHITE) .sizeDp(18) menu.findItem(R.id.menu_search_cards).icon = IconicsDrawable(activity!!) .icon(FontAwesome.Icon.faw_search) .color(Color.WHITE) .sizeDp(18) super.onCreateOptionsMenu(menu, inflater) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.menu_search_cards -> showSearchActionView(item) R.id.menu_filter_cards -> showSortingDialog() } return super.onOptionsItemSelected(item) } private fun showSortingDialog() { val items = arrayListOf(activity!!.getString(R.string.sort_name), activity!!.getString(R.string.sort_type), activity!!.getString(R.string.sort_scrap_cost), activity!!.getString(R.string.sort_faction), activity!!.getString(R.string.sort_lane)) MaterialDialog.Builder(activity!!) .title(R.string.sort_title) .items(items) .itemsCallbackSingleChoice(currentSortMethod, { dialog, view, which, text -> isSortAscending = dialog.isPromptCheckBoxChecked currentSortMethod = which when (which) { 0 -> adapter.itemAdapter.withComparator(CardItem.CardNameComparator(isSortAscending)) 1 -> adapter.itemAdapter.withComparator(CardItem.CardTypeComparator(isSortAscending)) 2 -> adapter.itemAdapter.withComparator(CardItem.CardScrapCostComparator(isSortAscending)) 3 -> adapter.itemAdapter.withComparator(CardItem.CardFactionComparator(isSortAscending)) 4 -> adapter.itemAdapter.withComparator(CardItem.CardLaneComparator(isSortAscending)) } true }) .positiveText(R.string.confirm) .negativeText(android.R.string.cancel) .checkBoxPromptRes(R.string.checkbox_sort_ascending, isSortAscending, null) .show() } private fun showSearchActionView(searchItem: MenuItem) { val searchView = searchItem.actionView as SearchView MenuItemCompat.expandActionView(searchItem) searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextChange(queryText: String): Boolean { Log.d(TAG, "onQueryTextChange(): $queryText") adapter.filter(queryText) return true } override fun onQueryTextSubmit(p0: String?): Boolean { // Adapter filtering already handled by onQueryTextChange() -- ignore return true } }) } private fun initRecyclerView(v: View) { adapter = FastItemAdapter() adapter.withOnClickListener({ view, adapter, item, position -> val imageTransitionName = "imageTransition${item.card.cardId}" val nameTransitionName = "nameTransition${item.card.cardId}" val transitionNames = java.util.ArrayList<String>() transitionNames.add(imageTransitionName) transitionNames.add(nameTransitionName) router.pushController(RouterTransaction.with(CardDetailController(item.card.cardId)) .tag(DeckbuildController.TAG) .pushChangeHandler(TransitionChangeHandlerCompat(SharedElementDelayingChangeHandler(transitionNames), FadeChangeHandler())) .popChangeHandler(TransitionChangeHandlerCompat(SharedElementDelayingChangeHandler(transitionNames), FadeChangeHandler()))) true }) adapter.withItemEvent(object : ClickEventHook<CardItem>() { override fun onBindMany(viewHolder: RecyclerView.ViewHolder): MutableList<View>? { if (viewHolder is CardItem.ViewHolder) { return ClickListenerHelper.toList(viewHolder.removeCardButton, viewHolder.addCardButton) } else { return super.onBindMany(viewHolder) } } override fun onClick(v: View, position: Int, adapter: FastAdapter<CardItem>, item: CardItem) { if (v.tag == "add") { // Check if clickable to prevent duplicate presenter calls if (isAddCardButtonClickable) { isAddCardButtonClickable = false presenter.checkCardAddable(item.card, deckId) } } else if (v.tag == "remove") { if (item.count > 0) { presenter.removeCardFromDeck(deckId, item.card) } } } }) adapter.withFilterPredicate({ item, constraint -> val cardNameCondensed: String = item.card.name.replace("[\\W]".toRegex(), "") val constraintCondensed: String = constraint.replace("[\\W]".toRegex(), "") val descriptionCondensed: String = item.card.description.replace("[\\W]".toRegex(), "") // Filter out any item that doesn't match card name or description constraints !(cardNameCondensed.contains(constraintCondensed, ignoreCase = true) || descriptionCondensed.contains(constraintCondensed, ignoreCase = true)) }) val layoutManager = LinearLayoutManager(activity) recyclerView = v.recycler_view recyclerView.setHasFixedSize(false) recyclerView.layoutManager = layoutManager recyclerView.adapter = adapter } private fun refreshFilters(filters: CardFilters) { presenter.getCards(filters, deckId) } override fun onDeckbuildModeCardsLoaded(cards: List<Card>, deck: Deck) { cards.forEach { card -> val cardItem = CardItem(card, true) cardItem.count = deck.cards.filter { it.cardId == card.cardId }.size adapter.add(cardItem) } } override fun handleBack(): Boolean { return super.handleBack() } override fun onCardChecked(card: Card, isCardAddable: Boolean) { if (isCardAddable) { presenter.addCardToDeck(deckId, card) } isAddCardButtonClickable = true } override fun updateCount(card: Card, itemRemoved: Boolean) { Log.d(TAG, "updateCount()") val item = adapter.adapterItems.find { it.card.cardId == card.cardId } val position = adapter.adapterItems.indexOf(item) if (itemRemoved) { adapter.adapterItems.find { it.card.cardId == card.cardId }!!.count -= 1 } else { adapter.adapterItems.find { it.card.cardId == card.cardId }!!.count += 1 } adapter.notifyAdapterItemChanged(position) } override fun showLaneSelection(lanesToDisplay: List<Int>, card: Card) { val laneNames: MutableList<String> = ArrayList() lanesToDisplay.forEach { laneInt -> laneNames.add(activity!!.getStringResourceByName(Lane.ID_TO_KEY.apply(laneInt))) } MaterialDialog.Builder(activity!!) .title("Choose A Lane To Display This Card.") .items(laneNames) .itemsCallbackSingleChoice(0, { dialog, view, which, text -> when (text) { activity!!.getStringResourceByName(Lane.ID_TO_KEY.apply(Lane.EVENT)) -> card.selectedLane = Lane.EVENT activity!!.getStringResourceByName(Lane.ID_TO_KEY.apply(Lane.MELEE)) -> card.selectedLane = Lane.MELEE activity!!.getStringResourceByName(Lane.ID_TO_KEY.apply(Lane.RANGED)) -> card.selectedLane = Lane.RANGED activity!!.getStringResourceByName(Lane.ID_TO_KEY.apply(Lane.SIEGE)) -> card.selectedLane = Lane.SIEGE else -> { throw UnsupportedOperationException("Selected lane does not match Event/Melee/Ranged/Siege. Lane text: $text") } } presenter.addCardToDeck(deckId, card) isAddCardButtonClickable = true true }) .cancelListener { dialog -> isAddCardButtonClickable = true } .positiveText(android.R.string.ok) .show() } override fun onViewModeCardsLoaded(cards: List<Card>) { cards.forEach { card -> val cardItem = CardItem(card, false) adapter.add(cardItem) } } override fun onListFiltered(filteredCards: List<Card>) { Log.d(TAG, "onListFiltered()") } }
apache-2.0
4e56d0e86e4ff723ebf1c1133761c67a
38.492537
143
0.641799
5.078695
false
false
false
false
AerisG222/maw_photos_android
MaWPhotos/src/main/java/us/mikeandwan/photos/authorization/AuthAuthenticator.kt
1
2221
package us.mikeandwan.photos.authorization import kotlinx.coroutines.runBlocking import net.openid.appauth.AuthorizationException import net.openid.appauth.AuthorizationService import okhttp3.Authenticator import okhttp3.Request import okhttp3.Response import okhttp3.Route import timber.log.Timber import java.io.IOException import kotlin.coroutines.resume import kotlin.coroutines.suspendCoroutine @Suppress("UNUSED_ANONYMOUS_PARAMETER") class AuthAuthenticator( private val _authService: AuthorizationService, private val _authStateManager: AuthStateManager ) : Authenticator { @Synchronized @Throws(IOException::class) override fun authenticate(route: Route?, response: Response): Request? { val authState = _authStateManager.current var request: Request? = null Timber.d("Starting Authenticator.authenticate") runBlocking { suspendCoroutine<Unit> { continuation -> authState.performActionWithFreshTokens(_authService) { accessToken: String?, idToken: String?, ex: AuthorizationException? -> when { ex != null -> { Timber.e("Failed to authorize = %s", ex.message) request = null continuation.resume(Unit) } accessToken == null -> { Timber.e("Failed to authorize, received null access token") request = null // Give up, we've already failed to authenticate. continuation.resume(Unit) } else -> { Timber.i("authenticate: obtained access token") request = response.request.newBuilder() .header("Authorization", String.format("Bearer %s", accessToken)) .build() continuation.resume(Unit) } } } } } return request } }
mit
f5e3af58010917dbe7a2fa54024fa8e9
36.661017
97
0.542999
6.101648
false
false
false
false
SixCan/SixTomato
app/src/main/java/ca/six/tomato/view/OnRvItemClickListener.kt
1
2061
package ca.six.tomato.view import android.app.Service import android.os.Vibrator import android.support.v4.view.GestureDetectorCompat import android.support.v7.widget.RecyclerView import android.view.GestureDetector import android.view.MotionEvent /** * Created by songzhw on 2016-06-09. */ abstract class OnRvItemClickListener(private val rv: RecyclerView) : RecyclerView.OnItemTouchListener { private val gestureDetector: GestureDetectorCompat private val vibrator: Vibrator init { gestureDetector = GestureDetectorCompat(rv.context, RvGestureListener()) vibrator = rv.context.getSystemService(Service.VIBRATOR_SERVICE) as Vibrator } private inner class RvGestureListener : GestureDetector.SimpleOnGestureListener() { override fun onLongPress(e: MotionEvent) { // vibrate vibrator.vibrate(70) val child = rv.findChildViewUnder(e.x, e.y) if (child != null) { val vh = rv.getChildViewHolder(child) onLongClick(vh) } } override fun onSingleTapUp(e: MotionEvent): Boolean { val child = rv.findChildViewUnder(e.x, e.y) if (child != null) { val vh = rv.getChildViewHolder(child) onItemClick(vh) } return true //@return true if the event is consumed, else false } } // ========================= OnItemTouchListener ================================= override fun onInterceptTouchEvent(rv: RecyclerView, e: MotionEvent): Boolean { gestureDetector.onTouchEvent(e) return false } override fun onTouchEvent(rv: RecyclerView, e: MotionEvent) { gestureDetector.onTouchEvent(e) } override fun onRequestDisallowInterceptTouchEvent(disallowIntercept: Boolean) { } // ========================= abstract methods ================================= abstract fun onLongClick(vh: RecyclerView.ViewHolder) abstract fun onItemClick(vh: RecyclerView.ViewHolder) }
gpl-3.0
4f55ca04b7f5c06d5bd59eac22f0424e
32.241935
103
0.633188
5.165414
false
false
false
false
laurencegw/jenjin
jenjin-core/src/main/kotlin/com/binarymonks/jj/core/specs/physics/LightSpec.kt
1
497
package com.binarymonks.jj.core.specs.physics import com.badlogic.gdx.graphics.Color import com.binarymonks.jj.core.properties.PropOverride abstract class LightSpec { var name: String? = null var rays: Int = 100 var color: PropOverride<Color> = PropOverride(Color(0.3f, 0.3f, 0.3f, 1f)) var reach: Float = 2f var collisionGroup :CollisionGroupSpec = CollisionGroupSpecExplicit() } class PointLightSpec:LightSpec() { var offsetX: Float = 0f var offsetY: Float = 0f }
apache-2.0
e2d0d24ff6f6cf11680b6c00b16a2edc
26.666667
78
0.730382
3.451389
false
false
false
false
fan123199/V2ex-simple
app/src/main/java/im/fdx/v2ex/utils/TimeUtil.kt
1
4356
package im.fdx.v2ex.utils import android.text.format.DateUtils import com.elvishew.xlog.XLog import im.fdx.v2ex.MyApp import im.fdx.v2ex.R import im.fdx.v2ex.utils.extensions.getNum import java.text.ParseException import java.text.SimpleDateFormat import java.util.* /** * Created by a708 on 15-9-9. * 获取相对时间 */ object TimeUtil { /** * @param created 若等-1 (目前设定),则为没有回复。 * * * @return */ fun getRelativeTime(created: Long): String { if (created <= 0) { return "" } val c = created * 1000 val now = System.currentTimeMillis() val difference = now - c val text = if (difference >= 0 && difference <= DateUtils.MINUTE_IN_MILLIS) MyApp.get().getString(R.string.just_now) else DateUtils.getRelativeTimeSpanString( c, now, DateUtils.MINUTE_IN_MILLIS, DateUtils.FORMAT_ABBREV_RELATIVE) return text.toString() } fun getAbsoluteTime(created: String): String { val createdNum = created.toLongOrNull() ?: return "" val obj = 1000 * createdNum val format1 = SimpleDateFormat("yyyy/MM/dd", Locale.US) format1.timeZone = TimeZone.getTimeZone("GMT+8:00") return format1.format(obj) } /** * 遗憾的是只能通过这样得到一个不准确的时间。 * 坑爹的char,让我卡了好久 * 算出绝对时间是为了保存如缓存,不然可以直接用得到的时间展示。 * @param timeStr 两个点中间的字符串,包括空格 * * * @return long value */ fun toUtcTime(timeStr: String): Long { var theTime = timeStr theTime = theTime.trim() // String theTime = time.replace("&nbsp", ""); // 44 分钟前用 iPhone 发布 // · 1 小时 34 分钟前 · 775 次点击 // · 100 天前 · 775 次点击 // 1992.02.03 12:22:22 +0800 // 2017-09-26 22:27:57 PM // 刚刚 //其中可能出现一些奇怪的字符,你可能以为是空格。 var created = System.currentTimeMillis() / 1000 // ms -> second val second = theTime.indexOf("秒") val hour = theTime.indexOf("小时") val minute = theTime.indexOf("分钟") val day = theTime.indexOf("天") val now = theTime.indexOf("刚刚") try { when { // theTime.isEmpty() -> return System.currentTimeMillis()/1000 second != -1 -> return created hour != -1 -> created -= theTime.substring(0, hour).getNum().toLong() * 60 * 60 + theTime.substring(hour + 2, minute).getNum().toLong() * 60 day != -1 -> created -= theTime.substring(0, day).getNum().toLong() * 60 * 60 * 24 minute != -1 -> created -= theTime.substring(0, minute).getNum().toLong() * 60 now != -1 -> return created else -> { val sdf = SimpleDateFormat("yyyy-MM-dd hh:mm:ss +08:00", Locale.getDefault()) val date = sdf.parse(theTime.trim()) created = date?.time?.div(1000) ?: 0 } } } catch (e1: NumberFormatException) { XLog.tag("TimeUtil").e("NumberFormatException error: $theTime, $timeStr") } catch (e2: StringIndexOutOfBoundsException) { XLog.tag("TimeUtil").e(" StringIndexOutOfBoundsException error: $theTime, $timeStr") } catch (e2: ParseException) { try { val ccc = SimpleDateFormat("yyyy-MM-dd hh:mm:ss a", Locale.US) val date = ccc.parse(theTime.trim()) created = date?.time?.div(1000) ?: 0 } catch (ignore: ParseException) { try { val ccc = SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss", Locale.US) val date = ccc.parse(theTime.trim()) created = date?.time?.div(1000) ?: 0 } catch (ignre:ParseException){ XLog.tag("TimeUtil").e("time str parse error: $theTime") } } } return created } }
apache-2.0
2af053a5830e15c7a5500f334d44a7f5
33.067227
98
0.528614
3.913127
false
false
false
false
rock3r/detekt
detekt-rules/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/naming/NamingConventionCustomPatternTest.kt
1
6202
package io.gitlab.arturbosch.detekt.rules.naming import io.gitlab.arturbosch.detekt.test.TestConfig import io.gitlab.arturbosch.detekt.test.compileAndLint import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.assertThatExceptionOfType import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe import java.util.regex.PatternSyntaxException class NamingConventionCustomPatternTest : Spek({ val configCustomRules = object : TestConfig() { override fun subConfig(key: String): TestConfig = this @Suppress("UNCHECKED_CAST") override fun <T : Any> valueOrDefault(key: String, default: T): T = when (key) { FunctionNaming.FUNCTION_PATTERN -> "^`.+`$" as T ClassNaming.CLASS_PATTERN -> "^aBbD$" as T VariableNaming.VARIABLE_PATTERN -> "^123var$" as T TopLevelPropertyNaming.CONSTANT_PATTERN -> "^lowerCaseConst$" as T EnumNaming.ENUM_PATTERN -> "^(enum1)|(enum2)$" as T PackageNaming.PACKAGE_PATTERN -> "^(package_1)$" as T FunctionMaxLength.MAXIMUM_FUNCTION_NAME_LENGTH -> 50 as T else -> default } } val testConfig = object : TestConfig() { override fun subConfig(key: String): TestConfig = when (key) { FunctionNaming::class.simpleName -> configCustomRules FunctionMaxLength::class.simpleName -> configCustomRules ClassNaming::class.simpleName -> configCustomRules VariableNaming::class.simpleName -> configCustomRules TopLevelPropertyNaming::class.simpleName -> configCustomRules EnumNaming::class.simpleName -> configCustomRules PackageNaming::class.simpleName -> configCustomRules else -> this } override fun <T : Any> valueOrDefault(key: String, default: T): T = default } val excludeClassPatternVariableRegexCode = """ class Bar { val MYVar = 3 } object Foo { val MYVar = 3 }""" val excludeClassPatternFunctionRegexCode = """ class Bar { fun MYFun() {} } object Foo { fun MYFun() {} }""" describe("NamingRules rule") { it("should use custom name for method and class") { val rule = NamingRules(testConfig) assertThat(rule.compileAndLint(""" class aBbD{ fun `name with back ticks`(){ val `123var` = "" } companion object { const val lowerCaseConst = "" } } """)).isEmpty() } it("should use custom name for constant") { val rule = NamingRules(testConfig) assertThat(rule.compileAndLint(""" class aBbD{ companion object { const val lowerCaseConst = "" } } """)).isEmpty() } it("should use custom name for enum") { val rule = NamingRules(testConfig) assertThat(rule.compileAndLint(""" class aBbD{ enum class aBbD { enum1, enum2 } } """)).isEmpty() } it("should use custom name for package") { val rule = NamingRules(testConfig) assertThat(rule.compileAndLint("package package_1")).isEmpty() } it("shouldExcludeClassesFromVariableNaming") { val code = """ class Bar { val MYVar = 3 } object Foo { val MYVar = 3 }""" val config = TestConfig(mapOf(VariableNaming.EXCLUDE_CLASS_PATTERN to "Foo|Bar")) assertThat(VariableNaming(config).compileAndLint(code)).isEmpty() } it("shouldNotFailWithInvalidRegexWhenDisabledVariableNaming") { val configValues = mapOf( "active" to "false", VariableNaming.EXCLUDE_CLASS_PATTERN to "*Foo" ) val config = TestConfig(configValues) assertThat(VariableNaming(config).compileAndLint(excludeClassPatternVariableRegexCode)).isEmpty() } it("shouldFailWithInvalidRegexVariableNaming") { val config = TestConfig(mapOf(VariableNaming.EXCLUDE_CLASS_PATTERN to "*Foo")) assertThatExceptionOfType(PatternSyntaxException::class.java).isThrownBy { VariableNaming(config).compileAndLint(excludeClassPatternVariableRegexCode) } } it("shouldExcludeClassesFromFunctionNaming") { val code = """ class Bar { fun MYFun() {} } object Foo { fun MYFun() {} }""" val config = TestConfig(mapOf(FunctionNaming.EXCLUDE_CLASS_PATTERN to "Foo|Bar")) assertThat(FunctionNaming(config).compileAndLint(code)).isEmpty() } it("shouldNotFailWithInvalidRegexWhenDisabledFunctionNaming") { val configRules = mapOf( "active" to "false", FunctionNaming.EXCLUDE_CLASS_PATTERN to "*Foo" ) val config = TestConfig(configRules) assertThat(FunctionNaming(config).compileAndLint(excludeClassPatternFunctionRegexCode)).isEmpty() } it("shouldFailWithInvalidRegexFunctionNaming") { val config = TestConfig(mapOf(FunctionNaming.EXCLUDE_CLASS_PATTERN to "*Foo")) assertThatExceptionOfType(PatternSyntaxException::class.java).isThrownBy { FunctionNaming(config).compileAndLint(excludeClassPatternFunctionRegexCode) } } } })
apache-2.0
356b3b5fb5ee6d0c657ba162582914ce
36.361446
109
0.54692
5.796262
false
true
false
false
sealedtx/coursework-db-kotlin
app/src/main/java/coursework/kiulian/com/freerealestate/view/custom/RoundedDrawable.kt
1
2815
package coursework.kiulian.com.freerealestate.view.custom import android.graphics.* import android.graphics.drawable.Drawable /** * Created by User on 10.11.2016. */ class RoundedDrawable(var bitmap: Bitmap, cornerRadius: Int, private val margin: Int, type: Type) : Drawable() { private val cornerRadius: Float = cornerRadius.toFloat() private var mRect = RectF() private val bitmapShader: BitmapShader private val paint: Paint private var mType = Type.fitXY enum class Type { center, fitXY, centerCrop } init { mType = type bitmapShader = BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP) paint = Paint() paint.isAntiAlias = true paint.shader = bitmapShader } override fun onBoundsChange(bounds: Rect) { super.onBoundsChange(bounds) mRect.set(margin.toFloat(), margin.toFloat(), (bounds.width() - margin).toFloat(), (bounds.height() - margin).toFloat()) val shaderMatrix = Matrix() val width = bounds.width() val height = bounds.height() when (mType) { Type.centerCrop -> { var scale = width * 1.0f / bitmap.width if (scale * bitmap.height < height) { scale = height * 1.0f / bitmap.height } val outWidth = Math.round(scale * bitmap.width) val outHeight = Math.round(scale * bitmap.height) shaderMatrix.postScale(scale, scale) var left = 0 var top = 0 if (outWidth == width) { top = (outHeight - height) * -1 / 2 } else { left = (outWidth - width) * -1 / 2 } shaderMatrix.postTranslate(left.toFloat(), top.toFloat()) } Type.fitXY -> { val wScale = width * 1.0f / bitmap.width val hScale = height * 1.0f / bitmap.height shaderMatrix.postScale(wScale, hScale) } Type.center -> { val moveleft: Int val movetop: Int moveleft = (width - bitmap.width) / 2 movetop = (height - bitmap.height) / 2 shaderMatrix.postTranslate(moveleft.toFloat(), movetop.toFloat()) } } bitmapShader.setLocalMatrix(shaderMatrix) } override fun draw(canvas: Canvas) { canvas.drawRoundRect(mRect, cornerRadius, cornerRadius, paint) } override fun getOpacity(): Int { return PixelFormat.TRANSLUCENT } override fun setAlpha(alpha: Int) { paint.alpha = alpha } override fun setColorFilter(cf: ColorFilter?) { paint.colorFilter = cf } }
bsd-2-clause
c2bdd3152291c8351ce51d2385304eb3
28.642105
128
0.557016
4.637562
false
false
false
false
binaryfoo/emv-bertlv
src/main/java/io/github/binaryfoo/decoders/ResponseFormat1Decoder.kt
1
2199
package io.github.binaryfoo.decoders import io.github.binaryfoo.DecodedData import io.github.binaryfoo.Decoder import io.github.binaryfoo.EmvTags import io.github.binaryfoo.decoders.apdu.APDUCommand import io.github.binaryfoo.tlv.Tag class ResponseFormat1Decoder : Decoder { override fun decode(input: String, startIndexInBytes: Int, session: DecodeSession): List<DecodedData> { if (session.currentCommand == APDUCommand.GetProcessingOptions) { val aip = input.substring(0, 4) val afl = input.substring(4) return listOf( decode(EmvTags.APPLICATION_INTERCHANGE_PROFILE, aip, startIndexInBytes, 2, session), decode(EmvTags.AFL, afl, startIndexInBytes + 2, (input.length - 4) / 2, session)) } if (session.currentCommand == APDUCommand.GenerateAC) { val cid = input.substring(0, 2) val atc = input.substring(2, 6) val applicationCryptogram = input.substring(6, 22) val issuerApplicationData = input.substring(22) return listOf( decode(EmvTags.CRYPTOGRAM_INFORMATION_DATA, cid, startIndexInBytes, 1, session), decode(EmvTags.APPLICATION_TRANSACTION_COUNTER, atc, startIndexInBytes + 1, 2, session), decode(EmvTags.APPLICATION_CRYPTOGRAM, applicationCryptogram, startIndexInBytes + 3, 8, session), decode(EmvTags.ISSUER_APPLICATION_DATA, issuerApplicationData, startIndexInBytes + 11, (input.length - 22) / 2, session)) } if (session.currentCommand == APDUCommand.InternalAuthenticate) { // 9F4B is only used for Format 2 responses to Internal authenticate session.signedDynamicAppData = input } return listOf() } private fun decode(tag: Tag, value: String, startIndexInBytes: Int, length: Int, decodeSession: DecodeSession): DecodedData { val tagMetaData = decodeSession.tagMetaData!! val children = tagMetaData.get(tag).decoder.decode(value, startIndexInBytes, decodeSession) return DecodedData.withTag(tag, tagMetaData, tagMetaData.get(tag).decodePrimitiveTlvValue(value), startIndexInBytes, startIndexInBytes + length, children) } override fun validate(input: String?): String? = null override fun getMaxLength(): Int = 0 }
mit
147dcfb3135fb9ad80e5d5d2a38146fe
47.866667
158
0.73306
4.294922
false
false
false
false
youkai-app/Youkai
app/src/main/kotlin/app/youkai/MainActivity.kt
1
1896
package app.youkai import android.content.Context import android.content.Intent import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.support.v7.widget.Toolbar import android.view.Menu import android.view.MenuItem import app.youkai.data.local.Credentials import app.youkai.data.models.ext.MediaType import app.youkai.ui.feature.login.LoginActivity import app.youkai.ui.feature.media.MediaActivity import app.youkai.ui.feature.settings.SettingsActivity import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setSupportActionBar(toolbar as Toolbar) if (!Credentials.isAuthenticated) { startActivity(LoginActivity.getLaunchIntent(this)) finish() } // SNK Manga = 14916 // SNK Anime = 7442 // Bakemonogatari = 3919 // Hanamonogatari = 8032 // Development code. TODO: Remove go.setOnClickListener { val id = mediaId.text.toString() val type = MediaType.fromString(mediaType.text.toString()) startActivity(MediaActivity.getLaunchIntent(this, id, type)) } } companion object { fun getLaunchIntent(context: Context) = Intent(context, MainActivity::class.java) } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.activity_main, menu) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) { R.id.settings -> { startActivity(SettingsActivity.getLaunchIntent(this)) true } else -> { super.onOptionsItemSelected(item) } } }
gpl-3.0
abc570962b482bf453807a98df200522
30.6
89
0.685654
4.568675
false
false
false
false
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/server/data/value/LanternCollectionValue.kt
1
4193
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.data.value import org.lanternpowered.api.util.collections.containsAll import org.lanternpowered.api.util.uncheckedCast import org.spongepowered.api.data.Key import org.spongepowered.api.data.value.CollectionValue import org.spongepowered.api.data.value.Value import java.util.function.Function import java.util.function.Predicate abstract class LanternCollectionValue<E, C : MutableCollection<E>> protected constructor( key: Key<out Value<C>>, value: C ) : LanternValue<C>(key, value), CollectionValue<E, C> { override fun size() = this.value.size override fun isEmpty() = this.value.isEmpty() override fun contains(element: E) = element in this.value override fun containsAll(iterable: Iterable<E>) = this.value.containsAll(iterable) override fun getAll(): C = CopyHelper.copy(this.value) override fun iterator() = get().iterator() abstract class Mutable<E, C : MutableCollection<E>, M : CollectionValue.Mutable<E, C, M, I>, I : CollectionValue.Immutable<E, C, I, M>> protected constructor(key: Key<out Value<C>>, value: C) : LanternCollectionValue<E, C>(key, value), CollectionValue.Mutable<E, C, M, I> { private inline fun also(fn: () -> Unit) = apply { fn() }.uncheckedCast<M>() override fun add(element: E) = also { this.value.add(element) } override fun addAll(elements: Iterable<E>) = also { this.value.addAll(elements) } override fun remove(element: E) = also { this.value.remove(element) } override fun removeAll(elements: Iterable<E>) = also { this.value.removeAll(elements) } override fun removeAll(predicate: Predicate<E>) = also { this.value.removeIf(predicate) } override fun set(value: C) = also { this.value = value } override fun transform(function: Function<C, C>) = set(function.apply(get())) } abstract class Immutable<E, C : MutableCollection<E>, I : CollectionValue.Immutable<E, C, I, M>, M : CollectionValue.Mutable<E, C, M, I>> protected constructor(key: Key<out Value<C>>, value: C) : LanternCollectionValue<E, C>(key, value), CollectionValue.Immutable<E, C, I, M> { override fun get(): C = CopyHelper.copy(super.get()) override fun withElement(element: E): I { val collection = get() return if (collection.add(element)) withValue(collection) else uncheckedCast() } override fun withAll(elements: Iterable<E>): I { var change = false val collection = get() for (element in elements) { change = collection.add(element) || change } return if (change) withValue(collection) else uncheckedCast() } override fun without(element: E): I { if (element !in this) { return uncheckedCast() } val collection = get() collection.remove(element) return withValue(collection) } override fun withoutAll(elements: Iterable<E>): I { val collection = get() return if (collection.removeAll(elements)) withValue(collection) else uncheckedCast() } override fun withoutAll(predicate: Predicate<E>): I { val collection = get() return if (collection.removeIf(predicate)) withValue(collection) else uncheckedCast() } override fun with(value: C) = withValue(CopyHelper.copy(value)) /** * Constructs a new [LanternCollectionValue.Immutable] * without copying the actual value. * * @param value The value element * @return The new immutable value */ protected abstract fun withValue(value: C): I override fun transform(function: Function<C, C>) = with(function.apply(get())) } }
mit
bfd13485b82957326e999173daa2e4c6
37.824074
151
0.646554
4.23108
false
false
false
false
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/server/network/vanilla/packet/handler/play/ClientSettingsHandler.kt
1
1820
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.network.vanilla.packet.handler.play import org.lanternpowered.api.cause.causeOf import org.lanternpowered.api.event.EventManager import org.lanternpowered.server.event.LanternEventFactory import org.lanternpowered.server.data.key.LanternKeys import org.lanternpowered.server.network.NetworkContext import org.lanternpowered.server.network.packet.PacketHandler import org.lanternpowered.server.network.vanilla.packet.type.play.ClientSettingsPacket import org.lanternpowered.server.registry.type.data.SkinPartRegistry import org.lanternpowered.api.data.Keys object ClientSettingsHandler : PacketHandler<ClientSettingsPacket> { override fun handle(ctx: NetworkContext, packet: ClientSettingsPacket) { val player = ctx.session.player val cause = causeOf(player) val skinParts = SkinPartRegistry.fromBitPattern(packet.skinPartsBitPattern) val event = LanternEventFactory.createPlayerChangeClientSettingsEvent( cause, packet.chatVisibility, skinParts, packet.locale, player, packet.enableColors, packet.viewDistance) EventManager.post(event) player.locale = event.locale player.viewDistance = event.viewDistance player.chatVisibility = event.chatVisibility player.isChatColorsEnabled = packet.enableColors player.offer(LanternKeys.DISPLAYED_SKIN_PARTS, event.displayedSkinParts) player.offer(Keys.DOMINANT_HAND, packet.dominantHand) } }
mit
c090a7c704391ff1604a5e7a36239dd9
44.5
86
0.768681
4.364508
false
false
false
false
kazhida/surroundcalc
src/com/abplus/surroundcalc/DoodleActivity.kt
1
8850
package com.abplus.surroundcalc import android.app.Activity import android.app.ActionBar import com.abplus.surroundcalc.models.Drawing import com.abplus.surroundcalc.utls.Preferences import com.abplus.surroundcalc.models.Drawing.KeyColor import android.view.Menu import android.view.MenuItem import android.app.FragmentTransaction import android.os.Bundle import android.widget.PopupWindow import android.view.Gravity import android.view.ViewGroup import android.view.WindowManager import android.view.View import android.view.WindowManager.LayoutParams import com.abplus.surroundcalc.models.Region import com.abplus.surroundcalc.models.ValueLabel import android.widget.TextView import android.graphics.Rect import android.util.Log import android.widget.PopupMenu import android.graphics.Point import android.widget.RelativeLayout import android.graphics.PointF import com.google.ads.AdView import com.google.ads.AdSize import android.widget.FrameLayout import com.google.ads.AdRequest import com.google.ads.InterstitialAd import com.google.ads.AdListener import com.google.ads.Ad import android.os.Handler import com.abplus.surroundcalc.exporters.ActionSender import com.abplus.surroundcalc.utls.Purchases import com.abplus.surroundcalc.billing.BillingHelper import android.app.AlertDialog import android.content.DialogInterface import android.content.Intent import com.abplus.surroundcalc.billing.BillingHelper.Result import android.widget.Toast /** * Created by kazhida on 2014/01/02. */ class DoodleActivity : Activity() { var purchases: Purchases? = null var adView: AdView? = null var interstitial: InterstitialAd? = null val sku_basic: String get() = getString(R.string.sku_basic) protected override fun onCreate(savedInstanceState: Bundle?) : Unit { super.onCreate(savedInstanceState) setContentView(R.layout.main_activity) purchases = Purchases(this) adView = AdView(this, AdSize.BANNER, getString(R.string.banner_unit_id)) val params = RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT) adView!!.setLayoutParams(params) val frame = (findViewById(R.id.ad_frame) as FrameLayout?) frame?.addView(adView!!) interstitial = InterstitialAd(this, getString(R.string.interstitial_unit_id)) interstitial?.loadAd(AdRequest()); interstitial?.setAdListener(object: AdListener{ override fun onReceiveAd(p0: Ad?) { Log.d("surroundcalc", "Received") } override fun onFailedToReceiveAd(p0: Ad?, p1: AdRequest.ErrorCode?) { Log.d("surroundcalc", "Failed") } override fun onPresentScreen(p0: Ad?) { Log.d("surroundcalc", "PresentScreen") } override fun onDismissScreen(p0: Ad?) { Log.d("surroundcalc", "DismissScreen") interstitial?.loadAd(AdRequest()) } override fun onLeaveApplication(p0: Ad?) { Log.d("surroundcalc", "LeaveApplication") } }); val actionBar = getActionBar()!! addTab(actionBar, Drawing.KeyColor.BLUE, true) addTab(actionBar, Drawing.KeyColor.GREEN, false) addTab(actionBar, Drawing.KeyColor.RED, false) addTab(actionBar, Drawing.KeyColor.YELLOW, false) actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS) } protected override fun onActivityResult(requestCode : Int, resultCode : Int, data : Intent?) : Unit { if (! purchases!!.billingHelper.handleActivityResult(requestCode, resultCode, data)) { super.onActivityResult(requestCode, resultCode, data) } } protected override fun onResume() { super.onResume() adView?.loadAd(AdRequest()) val keyColor = Preferences(this).currentColor if (keyColor != null) { val actionBar = getActionBar()!! val tab = actionBar.getTabAt(keyColor.ordinal()); actionBar.selectTab(tab) } if (purchases!!.isPurchased(sku_basic)){ findViewById(R.id.ad_frame)?.setVisibility(View.GONE) } purchases!!.checkState(sku_basic, object : BillingHelper.QueryInventoryFinishedListener { override fun onQueryInventoryFinished(result: BillingHelper.Result?, inventory: BillingHelper.Inventory?) { if (result!!.isSuccess()) { if (inventory!!.hasPurchase(sku_basic)) { findViewById(R.id.ad_frame)?.setVisibility(View.GONE) } else { findViewById(R.id.ad_frame)?.setVisibility(View.VISIBLE) } } else { findViewById(R.id.ad_frame)?.setVisibility(View.VISIBLE) showErrorToast(R.string.err_inventory) } } }) } public override fun onPause() { super.onPause() adView?.stopLoading() } public override fun onDestroy() { adView?.destroy() purchases?.billingHelper?.dispose() super.onDestroy() } public override fun onCreateOptionsMenu(menu : Menu?) : Boolean { val inflater = getMenuInflater() inflater.inflate(R.menu.actions, menu) return super.onCreateOptionsMenu(menu) } public override fun onOptionsItemSelected(item : MenuItem?) : Boolean { return when (item?.getItemId()) { R.id.action_clear_drawing -> { doodleView.clear() true } R.id.action_content_undo -> { doodleView.undo() true } R.id.action_social_share -> { if (purchases!!.isPurchased(sku_basic)) { ActionSender().startActivity(this, doodleView.createBitmap()) } else { val builder = AlertDialog.Builder(this) builder.setTitle(R.string.upgrade_title) builder.setMessage(R.string.upgrade_message) builder.setPositiveButton(R.string.upgrade) {(dialog: DialogInterface, which: Int) -> purchases!!.purchase(this, getString(R.string.sku_basic), object : Runnable { override fun run() { findViewById(R.id.ad_frame)?.setVisibility(View.GONE) } }) } builder.setNegativeButton(R.string.close, null) builder.setCancelable(true) builder.create().show() } true } else -> super.onOptionsItemSelected(item) } } private val doodleView: DoodleView get() { val fragment = getFragmentManager().findFragmentById(R.id.fragment_container) as DoodleFragment return fragment.mainView } private fun showErrorToast(msgId: Int) { Toast.makeText(this, msgId, Toast.LENGTH_SHORT).show() } private fun addTab(actionBar : ActionBar, keyColor : Drawing.KeyColor, selected : Boolean) : Unit { val tab = actionBar.newTab() val resId = when (keyColor) { Drawing.KeyColor.BLUE -> { R.string.blue } Drawing.KeyColor.GREEN -> { R.string.green } Drawing.KeyColor.RED -> { R.string.red } Drawing.KeyColor.YELLOW -> { R.string.yellow } } tab.setText(resId) tab.setTabListener(TabListener(getString(resId), keyColor)) actionBar.addTab(tab, selected) } private fun setKeyColor(keyColor: Drawing.KeyColor) { Preferences(this).currentColor = keyColor } private inner class TabListener(val tag: String, val keyColor: Drawing.KeyColor): ActionBar.TabListener { var fragment: DoodleFragment? = null override fun onTabSelected(tab: ActionBar.Tab?, ft: FragmentTransaction?) { if (fragment == null) { fragment = DoodleFragment(keyColor) ft?.add(R.id.fragment_container, fragment!!, tag) } else { ft?.attach(fragment) } setKeyColor(keyColor) if (! purchases!!.isPurchased(sku_basic)) { interstitial?.show() } } override fun onTabUnselected(tab: ActionBar.Tab?, ft: FragmentTransaction?) { if (fragment != null) { ft?.detach(fragment) } } override fun onTabReselected(tab: ActionBar.Tab?, ft: FragmentTransaction?) {} } }
bsd-2-clause
50f3a78f97092c9e2cfbb834c16d8080
34.834008
122
0.613672
4.820261
false
false
false
false
Mauin/detekt
detekt-rules/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/naming/NamingRulesSpec.kt
1
1802
package io.gitlab.arturbosch.detekt.rules.naming import io.gitlab.arturbosch.detekt.test.lint import org.assertj.core.api.Assertions.assertThat import org.jetbrains.spek.api.dsl.describe import org.jetbrains.spek.api.dsl.it import org.jetbrains.spek.subject.SubjectSpek class NamingRulesSpec : SubjectSpek<NamingRules>({ subject { NamingRules() } describe("properties in classes") { it("should detect all positive cases") { val code = """ class C(val CONST_PARAMETER: String, private val PRIVATE_CONST_PARAMETER: Int) { private val _FIELD = 5 val FIELD get() = _field val camel_Case_Property = 5 const val MY_CONST = 7 const val MYCONST = 7 fun doStuff(FUN_PARAMETER: String) {} } """ val findings = subject.lint(code) assertThat(findings).hasSize(8) } it("checks all negative cases") { val code = """ class C(val constParameter: String, private val privateConstParameter: Int) { private val _field = 5 val field get() = _field val camelCaseProperty = 5 const val myConst = 7 data class D(val i: Int, val j: Int) fun doStuff() { val (_, holyGrail) = D(5, 4) emptyMap<String, String>().forEach { _, v -> println(v) } } val doable: (Int) -> Unit = { _ -> Unit } fun doStuff(funParameter: String) {} } """ val findings = subject.lint(code) assertThat(findings).isEmpty() } } describe("naming like in constants is allowed for destructuring and lambdas") { it("should not detect any") { val code = """ data class D(val i: Int, val j: Int) fun doStuff() { val (_, HOLY_GRAIL) = D(5, 4) emptyMap<String, String>().forEach { _, V -> println(v) } } """ val findings = subject.lint(code) assertThat(findings).isEmpty() } } })
apache-2.0
985abfcb27fe5b2b50b16fed653a3c6e
26.723077
84
0.640954
3.36194
false
false
false
false
sys1yagi/mastodon4j
mastodon4j/src/main/java/com/sys1yagi/mastodon4j/MastodonRequest.kt
1
1906
package com.sys1yagi.mastodon4j import com.google.gson.JsonParser import com.sys1yagi.mastodon4j.api.exception.Mastodon4jRequestException import com.sys1yagi.mastodon4j.extension.toPageable import okhttp3.Response import java.lang.Exception open class MastodonRequest<T>( private val executor: () -> Response, private val mapper: (String) -> Any ) { interface Action1<T> { fun invoke(arg: T) } private var action: (String) -> Unit = {} private var isPageable: Boolean = false internal fun toPageable() = apply { isPageable = true } @JvmSynthetic fun doOnJson(action: (String) -> Unit) = apply { this.action = action } fun doOnJson(action: Action1<String>) = apply { this.action = { action.invoke(it) } } @Suppress("UNCHECKED_CAST") @Throws(Mastodon4jRequestException::class) fun execute(): T { val response = executor() if (response.isSuccessful) { try { val body = response.body().string() val element = JsonParser().parse(body) if (element.isJsonObject) { action(body) return mapper(body) as T } else { val list = arrayListOf<Any>() element.asJsonArray.forEach { val json = it.toString() action(json) list.add(mapper(json)) } if (isPageable) { return list.toPageable(response) as T } else { return list as T } } } catch (e: Exception) { throw Mastodon4jRequestException(e) } } else { throw Mastodon4jRequestException(response) } } }
mit
869c901853ae8145ff99e12d9a41ba6a
28.338462
71
0.52256
4.729529
false
false
false
false
AoEiuV020/PaNovel
app/src/main/java/cc/aoeiuv020/panovel/find/qidiantu/list/QidiantuListAdapter.kt
1
5109
package cc.aoeiuv020.panovel.find.qidiantu.list import android.annotation.SuppressLint import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import cc.aoeiuv020.base.jar.ioExecutorService import cc.aoeiuv020.panovel.R import cc.aoeiuv020.panovel.data.DataManager import cc.aoeiuv020.panovel.report.Reporter import cc.aoeiuv020.panovel.util.noCover import cc.aoeiuv020.regex.pick import com.bumptech.glide.Glide import com.bumptech.glide.request.RequestOptions import org.jetbrains.anko.doAsync import org.jetbrains.anko.uiThread class QidiantuListAdapter : RecyclerView.Adapter<QidiantuListAdapter.ViewHolder>() { private val data = mutableListOf<Item>() private var onItemClickListener: OnItemClickListener? = null @SuppressLint("NotifyDataSetChanged") fun setData(data: List<Item>) { this.data.clear() this.data.addAll(data) notifyDataSetChanged() } fun setOnItemClickListener(listener: OnItemClickListener) { this.onItemClickListener = listener } override fun getItemCount(): Int { return data.count() } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return ViewHolder( LayoutInflater.from(parent.context) .inflate(R.layout.item_qidiantu_list, parent, false) ) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val item = data[position] holder.itemView.setOnClickListener { onItemClickListener?.onItemClick(item) } holder.bind(item) } class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { private val ivImage: ImageView = itemView.findViewById(R.id.ivImage) private val tvName: TextView = itemView.findViewById(R.id.tvName) private val tvAuthor: TextView = itemView.findViewById(R.id.tvAuthor) private val tvDate: TextView = itemView.findViewById(R.id.tvDate) private val tvType: TextView = itemView.findViewById(R.id.tvType) private val tvWords: TextView = itemView.findViewById(R.id.tvWords) private val tvRatio: TextView = itemView.findViewById(R.id.tvRatio) @SuppressLint("SetTextI18n") fun bind(item: Item) { showImage(item) tvName.text = item.name tvAuthor.text = item.author + " • " + item.level tvDate.text = item.dateAdded tvType.text = item.type tvWords.text = item.words val ratio = if (item.collection.isBlank() && item.firstOrder.isBlank()) { item.ratio } else { "${item.collection}/${item.firstOrder}= ${item.ratio}" } tvRatio.text = ratio } private fun showImage(item: Item) { ivImage.setTag(R.id.tag_image_item, item) val ctx = ivImage.context if (!item.image.isNullOrBlank()) { Glide.with(ctx.applicationContext) .load(item.image) .apply(RequestOptions().apply { placeholder(R.mipmap.no_cover) error(R.mipmap.no_cover) }) .into(ivImage) return } val url = item.url val name = item.name ivImage.setImageResource(R.mipmap.no_cover) ivImage.context.doAsync({ e -> val message = "刷新小说《${name}》失败," Reporter.post(message, e) }, ioExecutorService) { val bookId = url.pick("http.*/info/(\\d*)").first() val site = "起点中文" val novelManager = DataManager.query(site, item.author, item.name, bookId) novelManager.requestDetail(false) val imageUrl = novelManager.novel.image item.image = imageUrl item.name = novelManager.novel.name uiThread { ctx -> val tag = ivImage.getTag(R.id.tag_image_item) if (tag != item) { return@uiThread } tvName.text = item.name if (imageUrl == noCover) { ivImage.setImageResource(R.mipmap.no_cover) } else { Glide.with(ctx.applicationContext) .load(novelManager.getImage(imageUrl)) .apply(RequestOptions().apply { placeholder(R.mipmap.no_cover) error(R.mipmap.no_cover) }) .into(ivImage) } } } ivImage.setImageResource(R.mipmap.no_cover) } } interface OnItemClickListener { fun onItemClick(item: Item) } }
gpl-3.0
d5a2cb4779c02e5f267b71bd424b684e
36.644444
90
0.580594
4.766417
false
false
false
false
jonalmeida/focus-android
app/src/main/java/org/mozilla/focus/menu/context/WebContextMenu.kt
1
12261
/* -*- Mode: Java; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: nil; -*- * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.focus.menu.context import android.app.Activity import android.app.Dialog import android.content.ClipData import android.content.ClipboardManager import android.content.Context import android.content.Intent import android.content.pm.ActivityInfo import android.content.pm.PackageManager import android.content.pm.ResolveInfo import android.graphics.Color import android.graphics.drawable.ColorDrawable import android.net.Uri import android.os.Environment import android.preference.PreferenceManager import com.google.android.material.internal.NavigationMenuView import com.google.android.material.navigation.NavigationView import androidx.appcompat.app.AlertDialog import android.text.Html import android.view.LayoutInflater import android.view.View import android.widget.TextView import mozilla.components.browser.session.Session import org.mozilla.focus.R import org.mozilla.focus.activity.MainActivity import org.mozilla.focus.open.OpenWithFragment import org.mozilla.focus.ext.components import org.mozilla.focus.telemetry.TelemetryWrapper import org.mozilla.focus.telemetry.TelemetryWrapper.BrowserContextMenuValue import org.mozilla.focus.utils.Browsers import org.mozilla.focus.utils.Settings import org.mozilla.focus.utils.UrlUtils import org.mozilla.focus.utils.ViewUtils import org.mozilla.focus.utils.asFragmentActivity import org.mozilla.focus.web.Download import org.mozilla.focus.web.IWebView /** * The context menu shown when long pressing a URL or an image inside the WebView. */ object WebContextMenu { private fun createTitleView(context: Context, title: String): View { val titleView = LayoutInflater.from(context).inflate(R.layout.context_menu_title, null) as TextView titleView.text = title return titleView } @Suppress("ComplexMethod") fun show( context: Context, callback: IWebView.Callback, hitTarget: IWebView.HitTarget, session: Session ) { if (!(hitTarget.isLink || hitTarget.isImage)) { // We don't support any other classes yet: throw IllegalStateException("WebContextMenu can only handle long-press on images and/or links.") } TelemetryWrapper.openWebContextMenuEvent() val builder = AlertDialog.Builder(context) builder.setCustomTitle(when { hitTarget.isLink -> createTitleView(context, hitTarget.linkURL) hitTarget.isImage -> createTitleView(context, hitTarget.imageURL) else -> throw IllegalStateException("Unhandled long press target type") }) val view = LayoutInflater.from(context).inflate(R.layout.context_menu, null) builder.setView(view) builder.setOnCancelListener { // What type of element was long-pressed val value: BrowserContextMenuValue = if (hitTarget.isImage && hitTarget.isLink) { BrowserContextMenuValue.ImageWithLink } else if (hitTarget.isImage) { BrowserContextMenuValue.Image } else { BrowserContextMenuValue.Link } // This even is only sent when the back button is pressed, or when a user // taps outside of the dialog: TelemetryWrapper.cancelWebContextMenuEvent(value) } val dialog = builder.create() dialog.window!!.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT)) val menu = view.findViewById<View>(R.id.context_menu) as NavigationView menu.elevation = 0f val navigationMenuView = menu.getChildAt(0) as? NavigationMenuView if (navigationMenuView != null) { navigationMenuView.isVerticalScrollBarEnabled = false } setupMenuForHitTarget(dialog, menu, callback, hitTarget, context, session) val warningView = view.findViewById<View>(R.id.warning) as TextView if (hitTarget.isImage) { menu.setBackgroundResource(R.drawable.no_corners_context_menu_navigation_view_background) @Suppress("DEPRECATION") warningView.text = Html.fromHtml( context.getString(R.string.contextmenu_image_warning, context.getString(R.string.app_name)) ) } else { warningView.visibility = View.GONE } dialog.show() } private fun getAppDataForLink(context: Context, url: String): Array<ActivityInfo>? { val intent = Intent(Intent.ACTION_VIEW) intent.data = Uri.parse(url) val browsers = Browsers(context, url) val resolveInfos: List<ResolveInfo> = context.packageManager .queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY) .filter { !browsers.installedBrowsers.contains(it.activityInfo) && it.activityInfo.packageName != context.packageName } return if (resolveInfos.isEmpty()) null else resolveInfos.map { it.activityInfo }.toTypedArray() } /** * Set up the correct menu contents. Note: this method can only be called once the Dialog * has already been created - we need the dialog in order to be able to dismiss it in the * menu callbacks. */ @Suppress("ComplexMethod", "LongParameterList") private fun setupMenuForHitTarget( dialog: Dialog, navigationView: NavigationView, callback: IWebView.Callback, hitTarget: IWebView.HitTarget, context: Context, session: Session ) = with(navigationView) { val appLinkData = if (hitTarget.linkURL != null) getAppDataForLink(context, hitTarget.linkURL) else null inflateMenu(R.menu.menu_browser_context) menu.findItem(R.id.menu_open_with_app).isVisible = appLinkData != null menu.findItem(R.id.menu_new_tab).isVisible = hitTarget.isLink && !session.isCustomTabSession() menu.findItem(R.id.menu_open_in_focus).title = resources.getString( R.string.menu_open_with_default_browser2, resources.getString(R.string.app_name) ) menu.findItem(R.id.menu_open_in_focus).isVisible = hitTarget.isLink && session.isCustomTabSession() menu.findItem(R.id.menu_link_share).isVisible = hitTarget.isLink menu.findItem(R.id.menu_link_copy).isVisible = hitTarget.isLink menu.findItem(R.id.menu_image_share).isVisible = hitTarget.isImage menu.findItem(R.id.menu_image_copy).isVisible = hitTarget.isImage menu.findItem(R.id.menu_image_save).isVisible = hitTarget.isImage && UrlUtils.isHttpOrHttps(hitTarget.imageURL) setNavigationItemSelectedListener { item -> dialog.dismiss() when (item.itemId) { R.id.menu_open_with_app -> { val fragment = OpenWithFragment.newInstance(appLinkData!!, hitTarget.linkURL, null) fragment.show( context.asFragmentActivity()!!.supportFragmentManager, OpenWithFragment.FRAGMENT_TAG ) true } R.id.menu_open_in_focus -> { // Open selected link in Focus and navigate there val newSession = Session(hitTarget.linkURL, source = Session.Source.MENU) context.components.sessionManager.add(newSession, selected = true) val intent = Intent(context, MainActivity::class.java) intent.action = Intent.ACTION_MAIN intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP context.startActivity(intent) TelemetryWrapper.openLinkInFullBrowserFromCustomTabEvent() true } R.id.menu_new_tab -> { val newSession = Session(hitTarget.linkURL, source = Session.Source.MENU) context.components.sessionManager.add( newSession, selected = Settings.getInstance(context).shouldOpenNewTabs() ) if (!Settings.getInstance(context).shouldOpenNewTabs()) { // Show Snackbar to allow users to switch to tab they just opened val snackbar = ViewUtils.getBrandedSnackbar( (context as Activity).findViewById(android.R.id.content), R.string.new_tab_opened_snackbar) snackbar.setAction(R.string.open_new_tab_snackbar) { context.components.sessionManager.select(newSession) } snackbar.show() } TelemetryWrapper.openLinkInNewTabEvent() PreferenceManager.getDefaultSharedPreferences(context).edit() .putBoolean( context.getString(R.string.has_opened_new_tab), true ).apply() true } R.id.menu_link_share -> { TelemetryWrapper.shareLinkEvent() val shareIntent = Intent(Intent.ACTION_SEND) shareIntent.type = "text/plain" shareIntent.putExtra(Intent.EXTRA_TEXT, hitTarget.linkURL) dialog.context.startActivity( Intent.createChooser( shareIntent, dialog.context.getString(R.string.share_dialog_title) ) ) true } R.id.menu_image_share -> { TelemetryWrapper.shareImageEvent() val shareIntent = Intent(Intent.ACTION_SEND) shareIntent.type = "text/plain" shareIntent.putExtra(Intent.EXTRA_TEXT, hitTarget.imageURL) dialog.context.startActivity( Intent.createChooser( shareIntent, dialog.context.getString(R.string.share_dialog_title) ) ) true } R.id.menu_image_save -> { val download = Download(hitTarget.imageURL, null, null, null, -1, Environment.DIRECTORY_PICTURES, null) callback.onDownloadStart(download) TelemetryWrapper.saveImageEvent() true } R.id.menu_link_copy, R.id.menu_image_copy -> { val clipboard = dialog.context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager val uri: Uri = when { item.itemId == R.id.menu_link_copy -> { TelemetryWrapper.copyLinkEvent() Uri.parse(hitTarget.linkURL) } item.itemId == R.id.menu_image_copy -> { TelemetryWrapper.copyImageEvent() Uri.parse(hitTarget.imageURL) } else -> throw IllegalStateException("Unknown hitTarget type - cannot copy to clipboard") } val clip = ClipData.newUri(dialog.context.contentResolver, "URI", uri) clipboard.primaryClip = clip true } else -> throw IllegalArgumentException("Unhandled menu item id=" + item.itemId) } } } }
mpl-2.0
b2e37b2b6170af0446862e6b2ccb0207
42.633452
116
0.593589
5.143037
false
false
false
false
adrianfaciu/flowdock-teamcity-plugin
flowdock-teamcity-plugin-server/src/main/kotlin/com/adrianfaciu/teamcity/flowdockPlugin/notifications/FlowdockNotification.kt
1
700
package com.adrianfaciu.teamcity.flowdockPlugin.notifications /** * Notification object that will be serialized and sent to Flowdock */ class FlowdockNotification { var author: NotificationAuthor? = null var external_thread_id: String? = null var title: String? = null var event: String? = null var thread: NotificationThread? = null var thread_id: String? = null var body: String? = null var flow_token: String? = null override fun toString(): String { return "[author = $author, body = $body, external_thread_id = $external_thread_id, title = $title, event = $event, thread = $thread, thread_id = $thread_id, flow_token = $flow_token]" } }
mit
9106d9da8dff73f9a5f1c8ed49cc26f4
25.961538
191
0.674286
3.977273
false
false
false
false
jereksel/LibreSubstratum
app/src/main/kotlin/com/jereksel/libresubstratum/domain/usecases/CleanUnusedOverlays.kt
1
2379
/* * Copyright (C) 2018 Andrzej Ressel ([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 <https://www.gnu.org/licenses/>. */ package com.jereksel.libresubstratum.domain.usecases import android.os.Looper import com.google.common.util.concurrent.MoreExecutors import com.jereksel.libresubstratum.domain.IPackageManager import com.jereksel.libresubstratum.domain.InvalidOverlayService import com.jereksel.libresubstratum.domain.LoggedOverlayService import com.jereksel.libresubstratum.domain.OverlayService import com.jereksel.libresubstratum.extensions.getLogger import java.util.concurrent.Executors class CleanUnusedOverlays( val packageManager: IPackageManager, val overlayManager: OverlayService ): ICleanUnusedOverlays { val log = getLogger() val executor = MoreExecutors.listeningDecorator(Executors.newSingleThreadExecutor()) override fun clean() = executor.submit { if (overlayManager is InvalidOverlayService || (overlayManager as? LoggedOverlayService)?.overlayService is InvalidOverlayService) { return@submit } log.debug("Cleaning overlays") val overlays = packageManager.getInstalledOverlays() for (overlay in overlays) { val overlayId = overlay.overlayId val themeAppId = overlay.sourceThemeId val targetAppId = overlay.targetId if (!packageManager.isPackageInstalled(themeAppId) || !packageManager.isPackageInstalled(targetAppId)) { try { log.debug("Removing overlay: $overlayId") overlayManager.uninstallApk(overlayId).get() } catch (e: Exception) { log.error("Cannot remove $overlayId", e) } } } } }
mit
dcda037c5ea3ac30378f12bb40321b2c
34.522388
140
0.708701
4.95625
false
false
false
false
iovation/launchkey-android-whitelabel-sdk
demo-app/app/src/kotlinApp/java/com/launchkey/android/authenticator/demo/ui/fragment/security/SecurityService.kt
2
5953
/* * Copyright (c) 2016. LaunchKey, Inc. All rights reserved. */ package com.launchkey.android.authenticator.demo.ui.fragment.security import android.os.Handler import android.os.Looper import com.launchkey.android.authenticator.sdk.core.auth_method_management.* import com.launchkey.android.authenticator.sdk.core.auth_method_management.LocationsManager.GetStoredLocationsCallback import com.launchkey.android.authenticator.sdk.core.auth_method_management.WearablesManager.GetStoredWearablesCallback import com.launchkey.android.authenticator.sdk.core.authentication_management.AuthenticatorManager import java.util.* import java.util.concurrent.ConcurrentHashMap /** * Class that allows White Label * implementers to get current * information on the security * aspect of the White Label * SDK. */ class SecurityService private constructor() { private val statusListenerIntegerMap: MutableMap<SecurityStatusListener, Int> = ConcurrentHashMap() private fun getUpdatedStatus(listener: SecurityStatusListener) { val pinEnabled = AuthenticatorManager.instance.config.isMethodAllowed(AuthMethod.PIN_CODE) && AuthMethodManagerFactory.getPINCodeManager().isPINCodeSet val circleEnabled = AuthenticatorManager.instance.config.isMethodAllowed(AuthMethod.CIRCLE_CODE) && AuthMethodManagerFactory.getCircleCodeManager().isCircleCodeSet val fingerprintEnabled = AuthenticatorManager.instance.config.isMethodAllowed(AuthMethod.BIOMETRIC) && AuthMethodManagerFactory.getBiometricManager().isBiometricSet val list: MutableList<SecurityFactor> = ArrayList() if (pinEnabled) { list.add(SecurityFactorImpl(AuthMethod.PIN_CODE, AuthMethodType.KNOWLEDGE)) } if (circleEnabled) { list.add(SecurityFactorImpl(AuthMethod.CIRCLE_CODE, AuthMethodType.KNOWLEDGE)) } if (fingerprintEnabled) { list.add(SecurityFactorImpl(AuthMethod.BIOMETRIC, AuthMethodType.INHERENCE)) } statusListenerIntegerMap[listener] = 0 if (AuthenticatorManager.instance.config.isMethodAllowed(AuthMethod.LOCATIONS)) { AuthMethodManagerFactory.getLocationsManager().getStoredLocations(object : GetStoredLocationsCallback { override fun onGetSuccess(locations: List<LocationsManager.StoredLocation>) { val locationsEnabled = !locations.isEmpty() if (locationsEnabled) { var locationsActive = false for (location in locations) { if (location.isActive) { locationsActive = true break } } list.add(SecurityFactorImpl(AuthMethod.LOCATIONS, AuthMethodType.INHERENCE, locationsActive)) } val i = statusListenerIntegerMap[listener]!! statusListenerIntegerMap[listener] = i + 1 notifyListenerIfDone(listener, list) } override fun onGetFailure(e: Exception) { val i = statusListenerIntegerMap[listener]!! statusListenerIntegerMap[listener] = i + 1 notifyListenerIfDone(listener, list) } }) } else { notifyListenerIfDone(listener, list) } if (AuthenticatorManager.instance.config.isMethodAllowed(AuthMethod.LOCATIONS)) { AuthMethodManagerFactory.getWearablesManager().getStoredWearables(object : GetStoredWearablesCallback { override fun onGetSuccess(wearablesFactor: List<WearablesManager.Wearable>) { val wearablesEnabled = !wearablesFactor.isEmpty() if (wearablesEnabled) { var wearablesActive = false for (wearableFactor in wearablesFactor) { if (wearableFactor.isActive) { wearablesActive = true break } } list.add(SecurityFactorImpl(AuthMethod.WEARABLES, AuthMethodType.POSSESSION, wearablesActive)) } val i = statusListenerIntegerMap[listener]!! statusListenerIntegerMap[listener] = i + 1 notifyListenerIfDone(listener, list) } override fun onGetFailure(exception: Exception) { val i = statusListenerIntegerMap[listener]!! statusListenerIntegerMap[listener] = i + 1 notifyListenerIfDone(listener, list) } }) } else { notifyListenerIfDone(listener, list) } } fun getStatus(listener: SecurityStatusListener?) { if (listener == null || statusListenerIntegerMap.containsKey(listener)) { return } getStatusAsyncInternal(listener) } private fun getStatusAsyncInternal(l: SecurityStatusListener) { val r = Runnable { getUpdatedStatus(l) } val t = Thread(r) t.start() } private fun notifyListenerIfDone(securityStatusListener: SecurityStatusListener, securityFactors: List<SecurityFactor>) { if (statusListenerIntegerMap[securityStatusListener] == 2) { statusListenerIntegerMap.remove(securityStatusListener) val uiHandler = Handler(Looper.getMainLooper()) uiHandler.post { securityStatusListener.onSecurityStatusUpdate(securityFactors) } } } interface SecurityStatusListener { fun onSecurityStatusUpdate(list: List<SecurityFactor>) } companion object { /** * @return the single instance. */ val instance = SecurityService() } }
mit
54b2a26bf6a201166de58e6a253bd201
45.155039
172
0.63279
5.830558
false
false
false
false
drakeet/MultiType
library/src/main/kotlin/com/drakeet/multitype/ClassLinkerBridge.kt
1
1450
/* * Copyright (c) 2016-present. Drakeet Xu * * 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.drakeet.multitype /** * @author Drakeet Xu */ internal class ClassLinkerBridge<T> private constructor( private val javaClassLinker: JavaClassLinker<T>, private val delegates: Array<ItemViewDelegate<T, *>> ) : Linker<T> { override fun index(position: Int, item: T): Int { val indexedClass = javaClassLinker.index(position, item) val index = delegates.indexOfFirst { it.javaClass == indexedClass } if (index != -1) return index throw IndexOutOfBoundsException( "The delegates'(${delegates.contentToString()}) you registered do not contain this ${indexedClass.name}." ) } companion object { fun <T> toLinker( javaClassLinker: JavaClassLinker<T>, delegates: Array<ItemViewDelegate<T, *>> ): Linker<T> { return ClassLinkerBridge(javaClassLinker, delegates) } } }
apache-2.0
fcfcb3f3f5b7835311c0321df063ec22
31.954545
111
0.711724
4.142857
false
false
false
false
langara/MyIntent
myintent/src/main/java/pl/mareklangiewicz/myintent/MIStartFragment.kt
1
8688
package pl.mareklangiewicz.myintent import android.app.SearchManager import android.content.Context import android.os.Bundle import android.text.Editable import android.text.TextWatcher import android.view.LayoutInflater import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import androidx.appcompat.widget.SearchView import kotlinx.android.synthetic.main.mi_log_fragment.mi_lf_et_command import kotlinx.android.synthetic.main.mi_log_fragment.mi_lf_iv_play_stop import kotlinx.android.synthetic.main.mi_log_fragment.mi_lf_pb_countdown import kotlinx.android.synthetic.main.mi_log_fragment.mi_lf_rv_log import pl.mareklangiewicz.myactivities.MyActivity import pl.mareklangiewicz.myfragments.MyFragment import pl.mareklangiewicz.myintent.PlayStopButton.State.HIDDEN import pl.mareklangiewicz.myintent.PlayStopButton.State.PLAY import pl.mareklangiewicz.myintent.PlayStopButton.State.STOP import pl.mareklangiewicz.myutils.* import pl.mareklangiewicz.upue.* class MIStartFragment : MyFragment(), PlayStopButton.Listener, Countdown.Listener { var mSearchItem: MenuItem? = null private val adapter = MyMDAndroLogAdapter(log.history) private val tocancel = Lst<Pushee<Cancel>>() lateinit var mPSButton: PlayStopButton lateinit var mCountdown: Countdown var onResumePlayCmd = "" private val updateButtonsRunnable = Runnable { updateFAB() updatePS() } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { super.onCreateView(inflater, container, savedInstanceState) //just for logging setHasOptionsMenu(true) return inflater.inflate(R.layout.mi_log_fragment, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) manager?.name = BuildConfig.NAME_PREFIX + getString(R.string.mi_start) mCountdown = Countdown(mi_lf_pb_countdown) mCountdown.listener = this mPSButton = PlayStopButton(mi_lf_iv_play_stop) mPSButton.listener = this mi_lf_rv_log.adapter = adapter val ctl1 = log.history.changes { adapter.notifyDataSetChanged() } tocancel.add(ctl1) adapter.notifyDataSetChanged() // to make sure we are up to date //TODO SOMEDAY: some nice simple header with fragment title manager?.lnav?.menuId = R.menu.mi_log_local updateCheckedItem() manager?.fab?.setImageResource(R.drawable.mi_ic_mic_white_24dp) manager?.fab?.setOnClickListener { if(isViewAvailable) { mCountdown.cancel() mi_lf_et_command.setText("") (activity as MyActivity).execute("start custom action listen") } } mi_lf_et_command.addTextChangedListener(object : TextWatcher { override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) { } override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { } override fun afterTextChanged(s: Editable) { updatePS() } }) arguments?.getString("play")?.let { onResumePlayCmd = it } val ctl2 = manager!!.lnav!!.items { when (it) { R.id.mi_ll_i_error -> log.history.level = MyLogLevel.ERROR R.id.mi_ll_i_warning -> log.history.level = MyLogLevel.WARN R.id.mi_ll_i_info -> log.history.level = MyLogLevel.INFO R.id.mi_ll_i_debug -> log.history.level = MyLogLevel.DEBUG R.id.mi_ll_i_verbose -> log.history.level = MyLogLevel.VERBOSE R.id.mi_clear_log_history -> log.history.clr() } } tocancel.add(ctl2) } override fun onResume() { super.onResume() if(onResumePlayCmd.isNotEmpty()) play(onResumePlayCmd) onResumePlayCmd = "" lazyUpdateButtons() } override fun onStop() { mCountdown.cancel() super.onStop() } override fun onDestroyView() { view?.removeCallbacks(updateButtonsRunnable) mSearchItem = null mPSButton.listener = null mPSButton.state = HIDDEN manager?.fab?.setOnClickListener(null) manager?.fab?.hide() manager?.lnav?.menuId = -1 mCountdown.cancel() mCountdown.listener = null tocancel.forEach { it(Cancel) } tocancel.clr() mi_lf_rv_log.adapter = null super.onDestroyView() } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.mi_log_options, menu) mSearchItem = menu.findItem(R.id.action_search) val sview = mSearchItem?.actionView as SearchView val manager = activity!!.getSystemService(Context.SEARCH_SERVICE) as SearchManager sview.setSearchableInfo(manager.getSearchableInfo(activity!!.componentName)) sview.setIconifiedByDefault(true) } private fun updateCheckedItem() { val id = when (log.history.level) { MyLogLevel.ERROR, MyLogLevel.ASSERT -> R.id.mi_ll_i_error MyLogLevel.WARN -> R.id.mi_ll_i_warning MyLogLevel.INFO -> R.id.mi_ll_i_info MyLogLevel.DEBUG -> R.id.mi_ll_i_debug MyLogLevel.VERBOSE -> R.id.mi_ll_i_verbose } manager?.lnav?.setCheckedItem(id, false) } override fun onDrawerSlide(drawerView: View, slideOffset: Float) { if (slideOffset == 0f) { lazyUpdateButtons() } else { manager?.fab?.hide() mPSButton.state = HIDDEN } } override fun onDrawerClosed(drawerView: View) { lazyUpdateButtons() } private val isSomethingOnOurFragment: Boolean get() = view !== null && ( manager?.lnav?.overlaps(view) ?: false || manager?.gnav?.overlaps(view) ?: false ) private fun updateFAB() { if (isSomethingOnOurFragment) manager?.fab?.hide() else manager?.fab?.show() } private fun lazyUpdateButtons() { if (!isViewAvailable) { log.d("View is not available.") return } view?.removeCallbacks(updateButtonsRunnable) view?.postDelayed(updateButtonsRunnable, 300) } private fun updatePS() { if (!isViewAvailable) { log.v("UI not ready.") return } if (isSomethingOnOurFragment) mPSButton.state = HIDDEN else mPSButton.state = if (mCountdown.isRunning) STOP else PLAY if(mCountdown.isRunning) mi_lf_et_command.isFocusable = false // it also sets isFocusableInTouchMode property to false else mi_lf_et_command.isFocusableInTouchMode = true // it also sets isFocusable property to true } /** * Starts counting to start given command. * It will start the command if user doesn't press stop fast enough. * If no command is given it will try to get command from EditText */ fun play(cmd: String = "") { if(!isViewAvailable) { onResumePlayCmd = cmd // if it is empty - nothing is scheduled. return } if(!cmd.isEmpty()) mi_lf_et_command.setText(cmd) val acmd = if(!cmd.isEmpty()) cmd else mi_lf_et_command.text.toString() if (acmd.isEmpty()) { log.e("No command provided.") lazyUpdateButtons() return } mSearchItem?.collapseActionView() mCountdown.start(acmd) } override fun onPlayStopClicked(oldState: PlayStopButton.State, newState: PlayStopButton.State) { when (oldState) { PLAY -> play() STOP -> mCountdown.cancel() HIDDEN -> log.d("Clicked on hidden button. ignoring..") } } override fun onCountdownStarted(cmd: String?) { activity?.hideKeyboard() updatePS() } override fun onCountdownFinished(cmd: String?) { if (cmd == null) { log.d("onCountdownFinished(null)") return } log.w(cmd) try { (activity as MyActivity).execute(cmd) MIContract.CmdRecent.insert(activity!!, cmd) mi_lf_et_command.setText("") } catch (e: RuntimeException) { log.e(e.message, "ML", e) } updatePS() } override fun onCountdownCancelled(cmd: String?) = updatePS() }
apache-2.0
8f4b195e0ff62a1778d6b275c936f6bb
30.708029
117
0.629489
4.459959
false
false
false
false
soywiz/korge
@old/korge-spriter/src/commonMain/kotlin/com/soywiz/korge/ext/spriter/com/brashmonkey/spriter/Animation.kt
1
7585
package com.soywiz.korge.ext.spriter.com.brashmonkey.spriter import com.soywiz.korge.ext.spriter.com.brashmonkey.spriter.Mainline.Key import com.soywiz.korge.ext.spriter.com.brashmonkey.spriter.Mainline.Key.BoneRef import com.soywiz.korge.ext.spriter.com.brashmonkey.spriter.Mainline.Key.ObjectRef import com.soywiz.korge.ext.spriter.com.brashmonkey.spriter.Timeline.Key.Bone import com.soywiz.korge.ext.spriter.com.brashmonkey.spriter.Timeline.Key.Object /** * Represents an animation of a Spriter SCML file. * An animation holds [Timeline]s and a [Mainline] to animate objects. * Furthermore it holds an [.id], a [.length], a [.name] and whether it is [.looping] or not. * @author Trixt0r */ @Suppress("MemberVisibilityCanBePrivate") open class Animation( val mainline: Mainline, val id: Int, val name: String, val length: Int, val looping: Boolean, timelines: Int ) { companion object { val DUMMY = Animation(Mainline.DUMMY, 0, "", 0, false, 0) } private val timelines: Array<Timeline> = Array(timelines) { Timeline.DUMMY } private var timelinePointer = 0 private val nameToTimeline: HashMap<String, Timeline> = HashMap() open var currentKey: Key = Key.DUMMY var tweenedKeys: Array<Timeline.Key> = emptyArray() var unmappedTweenedKeys: Array<Timeline.Key> = emptyArray() private var prepared: Boolean = false /** * Returns a [Timeline] with the given index. * @param index the index of the timeline * * * @return the timeline with the given index * * * @throws IndexOutOfBoundsException if the index is out of range */ fun getTimeline(index: Int): Timeline { return this.timelines[index] } /** * Returns a [Timeline] with the given name. * @param name the name of the time line * * * @return the time line with the given name or null if no time line exists with the given name. */ fun getTimeline(name: String): Timeline? { return this.nameToTimeline[name] } fun addTimeline(timeline: Timeline) { this.timelines[timelinePointer++] = timeline this.nameToTimeline[timeline.name] = timeline } /** * Returns the number of time lines this animation holds. * @return the number of time lines */ fun timelines(): Int { return timelines.size } override fun toString(): String { var toReturn = "" + this::class + "|[id: " + id + ", " + name + ", duration: " + length + ", is looping: " + looping toReturn += "Mainline:\n" toReturn += mainline toReturn += "Timelines\n" for (timeline in this.timelines) toReturn += timeline toReturn += "]" return toReturn } /** * Updates the bone and object structure with the given time to the given root bone. * @param time The time which has to be between 0 and [.length] to work properly. * * * @param root The root bone which is not allowed to be null. The whole animation runs relative to the root bone. */ open fun update(time: Int, root: Bone?) { if (!this.prepared) throw SpriterException("This animation is not ready yet to animate itself. Please call prepare()!") if (root == null) throw SpriterException("The root can not be null! Set a root bone to apply this animation relative to the root bone.") this.currentKey = mainline.getKeyBeforeTime(time) for (timelineKey in this.unmappedTweenedKeys) timelineKey.active = false for (ref in currentKey.boneRefs) this.update(ref, root, time) for (ref in currentKey.objectRefs) this.update(ref, root, time) } protected open fun update(ref: BoneRef, root: Bone, time: Int) { val isObject = ref is ObjectRef //Get the timelines, the refs pointing to val timeline = getTimeline(ref.timeline) val key = timeline.getKey(ref.key) var nextKey: Timeline.Key = timeline.getKey((ref.key + 1) % timeline.keys.size) val currentTime = key.time var nextTime = nextKey.time if (nextTime < currentTime) { if (!looping) nextKey = key else nextTime = length } //Normalize the time var t = (time - currentTime).toFloat() / (nextTime - currentTime).toFloat() if (t.isNaN() || t.isInfinite()) t = 1f if (currentKey.time > currentTime) { var tMid = (currentKey.time - currentTime).toFloat() / (nextTime - currentTime).toFloat() if (tMid.isNaN() || tMid.isInfinite()) tMid = 0f t = (time - currentKey.time).toFloat() / (nextTime - currentKey.time).toFloat() if (t.isNaN() || t.isInfinite()) t = 1f t = currentKey.curve.tween(tMid, 1f, t) } else t = currentKey.curve.tween(0f, 1f, t) //Tween bone/object val bone1 = key.`object`() val bone2 = nextKey.`object`() val tweenTarget = this.tweenedKeys[ref.timeline].`object`() if (isObject) this.tweenObject(bone1, bone2, tweenTarget, t, key.curve, key.spin) else this.tweenBone(bone1 as Bone, bone2 as Bone, tweenTarget as Bone, t, key.curve, key.spin) this.unmappedTweenedKeys[ref.timeline].active = true this.unmapTimelineObject( ref.timeline, isObject, if (ref.parent != null) this.unmappedTweenedKeys[ref.parent.timeline].`object`() else root ) } fun unmapTimelineObject(timeline: Int, isObject: Boolean, root: Bone) { val tweenTarget = this.tweenedKeys[timeline].`object`() val mapTarget = this.unmappedTweenedKeys[timeline].`object`() if (isObject) mapTarget.set(tweenTarget) else (mapTarget as Bone).set(tweenTarget as Bone) mapTarget.unmap(root) } protected fun tweenBone(bone1: Bone, bone2: Bone, target: Bone, t: Float, curve: Curve, spin: Int) { target._angle = curve.tweenAngle(bone1._angle, bone2._angle, t, spin) curve.tweenPoint(bone1.position, bone2.position, t, target.position) curve.tweenPoint(bone1.scale, bone2.scale, t, target.scale) curve.tweenPoint(bone1.pivot, bone2.pivot, t, target.pivot) } protected fun tweenObject(object1: Object, object2: Object, target: Object, t: Float, curve: Curve, spin: Int) { this.tweenBone(object1, object2, target, t, curve, spin) target.alpha = curve.tweenAngle(object1.alpha, object2.alpha, t) target.ref.set(object1.ref) } fun getSimilarTimeline(t: Timeline): Timeline? { var found: Timeline? = getTimeline(t.name) if (found == null && t.id < this.timelines()) found = this.getTimeline(t.id) return found } /*Timeline getSimilarTimeline(BoneRef ref, Collection<Timeline> coveredTimelines){ if(ref.parent == null) return null; for(BoneRef boneRef: this.currentKey.objectRefs){ Timeline t = this.getTimeline(boneRef.timeline); if(boneRef.parent != null && boneRef.parent.id == ref.parent.id && !coveredTimelines.contains(t)) return t; } return null; } Timeline getSimilarTimeline(ObjectRef ref, Collection<Timeline> coveredTimelines){ if(ref.parent == null) return null; for(ObjectRef objRef: this.currentKey.objectRefs){ Timeline t = this.getTimeline(objRef.timeline); if(objRef.parent != null && objRef.parent.id == ref.parent.id && !coveredTimelines.contains(t)) return t; } return null; }*/ /** * Prepares this animation to set this animation in any time state. * This method has to be called before [.update]. */ fun prepare() { if (this.prepared) return this.tweenedKeys = Array(timelines.size) { Timeline.Key.DUMMY } this.unmappedTweenedKeys = Array(timelines.size) { Timeline.Key.DUMMY } for (i in this.tweenedKeys.indices) { this.tweenedKeys[i] = Timeline.Key(i) this.unmappedTweenedKeys[i] = Timeline.Key(i) this.tweenedKeys[i].setObject(Object(Point(0f, 0f))) this.unmappedTweenedKeys[i].setObject(Object(Point(0f, 0f))) } if (mainline.keys.isNotEmpty()) currentKey = mainline.getKey(0) this.prepared = true } }
apache-2.0
420acd3c322b96271c89beb9983c4f21
35.291866
138
0.706394
3.416667
false
false
false
false
yukuku/androidbible
Alkitab/src/main/java/yuku/alkitab/base/util/LabelColorUtil.kt
1
2325
package yuku.alkitab.base.util import android.graphics.Color import android.graphics.drawable.GradientDrawable import android.graphics.drawable.StateListDrawable import android.widget.TextView import androidx.core.graphics.ColorUtils import yuku.alkitab.model.Label object LabelColorUtil { @JvmStatic fun encodeBackground(colorRgb_background: Int): String { val sb = StringBuilder(10) sb.append('b') // 'b': background color val h = Integer.toHexString(colorRgb_background) for (x in h.length until 6) { sb.append('0') } sb.append(h) return sb.toString() } /** * @return colorRgb (without alpha) or -1 if can't decode */ @JvmStatic fun decodeBackground(backgroundColor: String?): Int { if (backgroundColor == null || backgroundColor.isEmpty()) return -1 return if (backgroundColor.length >= 7 && backgroundColor[0] == 'b') { // 'b': background color Integer.parseInt(backgroundColor.substring(1, 7), 16) } else { -1 } } @JvmStatic fun getForegroundBasedOnBackground(colorRgb: Int): Int { val hsl = floatArrayOf(0f, 0f, 0f) ColorUtils.RGBToHSL(Color.red(colorRgb), Color.green(colorRgb), Color.blue(colorRgb), hsl) if (hsl[2] > 0.5f) { hsl[2] -= 0.44f } else { hsl[2] += 0.44f } return ColorUtils.HSLToColor(hsl) and 0xffffff } @JvmStatic fun apply(label: Label, view: TextView): Int { var bgColorRgb = decodeBackground(label.backgroundColor) if (bgColorRgb == -1) { bgColorRgb = 0x212121 // default color Grey 900 } var grad: GradientDrawable? = null val bg = view.background if (bg is GradientDrawable) { grad = bg } else if (bg is StateListDrawable) { val current = bg.current if (current is GradientDrawable) { grad = current } } if (grad != null) { grad.setColor(0xff000000.toInt() or bgColorRgb) val labelColor = 0xff000000.toInt() or getForegroundBasedOnBackground(bgColorRgb) view.setTextColor(labelColor) return labelColor } return 0 } }
apache-2.0
019036c78f3603283e3ea1b57ec82ec1
29.592105
103
0.596989
4.337687
false
false
false
false
shlusiak/Freebloks-Android
app/src/main/java/de/saschahlusiak/freebloks/game/PlayerDetailFragment.kt
1
5390
package de.saschahlusiak.freebloks.game import android.graphics.Color import android.os.Bundle import android.view.View import android.view.WindowInsets import androidx.cardview.widget.CardView import androidx.core.view.isVisible import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import de.saschahlusiak.freebloks.R import de.saschahlusiak.freebloks.databinding.PlayerDetailFragmentBinding import de.saschahlusiak.freebloks.model.Game import de.saschahlusiak.freebloks.model.colorOf import de.saschahlusiak.freebloks.utils.viewBinding /** * The current player sheet at the bottom of the screen. * * Observes [FreebloksActivityViewModel.playerToShowInSheet]. There are several cases: * * - Not connected * "Not connected" * * - Game in not started * "No player" * * - Game is running * If the board is not rotated, the current player. * If the board is rotated, the rotated player. * If the current player is a local player, show number of turns. * If current player is remote player, show spinner. * * - Game is finished * The board is rotating. At any time the status is showing the currently shown player and their left stones. * */ class PlayerDetailFragment : Fragment(R.layout.player_detail_fragment) { private val viewModel by lazy { ViewModelProvider(requireActivity()).get(FreebloksActivityViewModel::class.java) } private val binding by viewBinding(PlayerDetailFragmentBinding::bind) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { val cardView = view as CardView view.setOnApplyWindowInsetsListener { _: View, insets: WindowInsets -> cardView.setContentPadding(insets.systemWindowInsetLeft, 0, insets.systemWindowInsetRight, insets.systemWindowInsetBottom) insets } viewModel.playerToShowInSheet.observe(viewLifecycleOwner) { updateViews(it) } viewModel.inProgress.observe(viewLifecycleOwner) { inProgressChanged(it) } } private fun inProgressChanged(inProgress: Boolean) { binding.movesLeft.isVisible = !inProgress binding.progressBar.isVisible = inProgress } private fun updateViews(data: SheetPlayer) = with(binding) { val client = viewModel.client val background = root currentPlayer.clearAnimation() // the intro trumps everything if (viewModel.intro != null) { background.setCardBackgroundColor(Color.rgb(64, 64, 80)) currentPlayer.setText(R.string.touch_to_skip) points.visibility = View.GONE movesLeft.text = "" return } // if not connected, show that if (client == null || !client.isConnected()) { background.setCardBackgroundColor(Color.rgb(64, 64, 80)) currentPlayer.setText(R.string.not_connected) points.visibility = View.GONE movesLeft.text = "" return } // no current player if (data.player < 0) { background.setCardBackgroundColor(Color.rgb(64, 64, 80)) currentPlayer.setText(R.string.no_player) points.visibility = View.GONE movesLeft.text = "" return } val game: Game = client.game val board = game.board // is it "your turn", like, in general? val isYourTurn = client.game.isLocalPlayer() val playerColor = game.gameMode.colorOf(data.player) val playerName = viewModel.getPlayerName(data.player) val p = board.getPlayer(data.player) background.setCardBackgroundColor(resources.getColor(playerColor.backgroundColorId)) points.visibility = View.VISIBLE points.text = resources.getQuantityString(R.plurals.number_of_points, p.totalPoints, p.totalPoints) if (client.game.isFinished) { currentPlayer.text = "[$playerName]" movesLeft.text = resources.getQuantityString(R.plurals.number_of_stones_left, p.stonesLeft, p.stonesLeft) return } movesLeft.text = resources.getQuantityString(R.plurals.player_status_moves, p.numberOfPossibleTurns, p.numberOfPossibleTurns) // we are showing "home" if (!data.isRotated) { if (isYourTurn) { currentPlayer.text = getString(R.string.your_turn, playerName) } else { currentPlayer.text = getString(R.string.waiting_for_color, playerName) } } else { if (p.numberOfPossibleTurns <= 0) currentPlayer.text = "[${getString(R.string.color_is_out_of_moves, playerName)}]" else { currentPlayer.text = playerName } } } private fun startAnimation() { // FIXME: animation of current player /* final Animation a = new TranslateAnimation(0, 8, 0, 0); a.setInterpolator(new CycleInterpolator(2)); a.setDuration(500); Runnable r = new Runnable() { @Override public void run() { if (view == null) return; boolean local = false; View t = findViewById(R.id.currentPlayer); t.postDelayed(this, 5000); if (client != null && client.game != null) local = client.game.isLocalPlayer(); if (!local) return; t.startAnimation(a); } }; findViewById(R.id.currentPlayer).postDelayed(r, 1000); */ } }
gpl-2.0
01d2095c2daa856760eea1dc4332999d
33.33758
134
0.66679
4.443528
false
false
false
false
panpf/sketch
sketch/src/androidTest/java/com/github/panpf/sketch/test/decode/internal/ExifOrientationHelperTest.kt
1
45782
/* * Copyright (C) 2022 panpf <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.panpf.sketch.test.decode.internal import android.graphics.BitmapFactory import android.graphics.Rect import androidx.exifinterface.media.ExifInterface import androidx.test.ext.junit.runners.AndroidJUnit4 import com.github.panpf.sketch.cache.internal.LruBitmapPool import com.github.panpf.sketch.datasource.AssetDataSource import com.github.panpf.sketch.datasource.FileDataSource import com.github.panpf.sketch.datasource.ResourceDataSource import com.github.panpf.sketch.decode.internal.ExifOrientationHelper import com.github.panpf.sketch.decode.internal.exifOrientationName import com.github.panpf.sketch.decode.internal.readExifOrientation import com.github.panpf.sketch.decode.internal.readExifOrientationWithMimeType import com.github.panpf.sketch.fetch.newAssetUri import com.github.panpf.sketch.fetch.newResourceUri import com.github.panpf.sketch.request.LoadRequest import com.github.panpf.sketch.resize.Resize import com.github.panpf.sketch.resize.Scale.CENTER_CROP import com.github.panpf.sketch.resize.Scale.END_CROP import com.github.panpf.sketch.resize.Scale.FILL import com.github.panpf.sketch.resize.Scale.START_CROP import com.github.panpf.sketch.test.R import com.github.panpf.sketch.test.utils.ExifOrientationTestFileHelper import com.github.panpf.sketch.test.utils.cornerA import com.github.panpf.sketch.test.utils.cornerB import com.github.panpf.sketch.test.utils.cornerC import com.github.panpf.sketch.test.utils.cornerD import com.github.panpf.sketch.test.utils.corners import com.github.panpf.sketch.test.utils.getTestContext import com.github.panpf.sketch.test.utils.getTestContextAndNewSketch import com.github.panpf.sketch.util.Size import org.junit.Assert import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class ExifOrientationHelperTest { @Test fun testConstructor() { ExifOrientationHelper(ExifInterface.ORIENTATION_UNDEFINED).apply { Assert.assertEquals(ExifInterface.ORIENTATION_UNDEFINED, exifOrientation) } ExifOrientationHelper(ExifInterface.ORIENTATION_ROTATE_270).apply { Assert.assertEquals(ExifInterface.ORIENTATION_ROTATE_270, exifOrientation) } } @Test fun testReadExifOrientation() { val (context, sketch) = getTestContextAndNewSketch() Assert.assertEquals( ExifInterface.ORIENTATION_NORMAL, AssetDataSource( sketch, LoadRequest(context, newAssetUri("sample.jpeg")), "sample.jpeg" ).readExifOrientation() ) Assert.assertEquals( ExifInterface.ORIENTATION_UNDEFINED, AssetDataSource( sketch, LoadRequest(context, newAssetUri("sample.webp")), "sample.webp" ).readExifOrientation() ) ExifOrientationTestFileHelper(context, "exif_origin_clock_hor.jpeg").files().forEach { Assert.assertEquals( it.exifOrientation, FileDataSource( sketch, LoadRequest(context, it.file.path), it.file ).readExifOrientation() ) } Assert.assertEquals( ExifInterface.ORIENTATION_UNDEFINED, ResourceDataSource( sketch, LoadRequest(context, newResourceUri(R.xml.network_security_config)), packageName = context.packageName, context.resources, R.xml.network_security_config ).readExifOrientation() ) } @Test fun testReadExifOrientationWithMimeType() { val (context, sketch) = getTestContextAndNewSketch() Assert.assertEquals( ExifInterface.ORIENTATION_NORMAL, AssetDataSource( sketch, LoadRequest(context, newAssetUri("sample.jpeg")), "sample.jpeg" ).readExifOrientationWithMimeType("image/jpeg") ) Assert.assertEquals( ExifInterface.ORIENTATION_UNDEFINED, AssetDataSource( sketch, LoadRequest(context, newAssetUri("sample.jpeg")), "sample.jpeg" ).readExifOrientationWithMimeType("image/bmp") ) Assert.assertEquals( ExifInterface.ORIENTATION_UNDEFINED, AssetDataSource( sketch, LoadRequest(context, newAssetUri("sample.webp")), "sample.webp" ).readExifOrientationWithMimeType("image/webp") ) ExifOrientationTestFileHelper(context, "exif_origin_clock_hor.jpeg").files().forEach { Assert.assertEquals( it.exifOrientation, FileDataSource(sketch, LoadRequest(context, it.file.path), it.file) .readExifOrientationWithMimeType("image/jpeg") ) Assert.assertEquals( ExifInterface.ORIENTATION_UNDEFINED, FileDataSource(sketch, LoadRequest(context, it.file.path), it.file) .readExifOrientationWithMimeType("image/bmp") ) } Assert.assertEquals( ExifInterface.ORIENTATION_UNDEFINED, ResourceDataSource( sketch, LoadRequest(context, newResourceUri(R.xml.network_security_config)), packageName = context.packageName, context.resources, R.xml.network_security_config ).readExifOrientationWithMimeType("image/jpeg") ) } @Test fun testExifOrientationName() { Assert.assertEquals("ROTATE_90", exifOrientationName(ExifInterface.ORIENTATION_ROTATE_90)) Assert.assertEquals("TRANSPOSE", exifOrientationName(ExifInterface.ORIENTATION_TRANSPOSE)) Assert.assertEquals("ROTATE_180", exifOrientationName(ExifInterface.ORIENTATION_ROTATE_180)) Assert.assertEquals( "FLIP_VERTICAL", exifOrientationName(ExifInterface.ORIENTATION_FLIP_VERTICAL) ) Assert.assertEquals("ROTATE_270", exifOrientationName(ExifInterface.ORIENTATION_ROTATE_270)) Assert.assertEquals("TRANSVERSE", exifOrientationName(ExifInterface.ORIENTATION_TRANSVERSE)) Assert.assertEquals( "FLIP_HORIZONTAL", exifOrientationName(ExifInterface.ORIENTATION_FLIP_HORIZONTAL) ) Assert.assertEquals("UNDEFINED", exifOrientationName(ExifInterface.ORIENTATION_UNDEFINED)) Assert.assertEquals("NORMAL", exifOrientationName(ExifInterface.ORIENTATION_NORMAL)) Assert.assertEquals("-1", exifOrientationName(-1)) Assert.assertEquals("100", exifOrientationName(100)) } @Test fun testIsFlipped() { Assert.assertFalse(ExifOrientationHelper(ExifInterface.ORIENTATION_ROTATE_90).isFlipped) Assert.assertTrue(ExifOrientationHelper(ExifInterface.ORIENTATION_TRANSPOSE).isFlipped) Assert.assertFalse(ExifOrientationHelper(ExifInterface.ORIENTATION_ROTATE_180).isFlipped) Assert.assertTrue(ExifOrientationHelper(ExifInterface.ORIENTATION_FLIP_VERTICAL).isFlipped) Assert.assertFalse(ExifOrientationHelper(ExifInterface.ORIENTATION_ROTATE_270).isFlipped) Assert.assertTrue(ExifOrientationHelper(ExifInterface.ORIENTATION_TRANSVERSE).isFlipped) Assert.assertTrue(ExifOrientationHelper(ExifInterface.ORIENTATION_FLIP_HORIZONTAL).isFlipped) Assert.assertFalse(ExifOrientationHelper(ExifInterface.ORIENTATION_UNDEFINED).isFlipped) Assert.assertFalse(ExifOrientationHelper(ExifInterface.ORIENTATION_NORMAL).isFlipped) Assert.assertFalse(ExifOrientationHelper(-1).isFlipped) Assert.assertFalse(ExifOrientationHelper(100).isFlipped) } @Test fun testRotationDegrees() { Assert.assertEquals( 90, ExifOrientationHelper(ExifInterface.ORIENTATION_ROTATE_90).rotationDegrees ) Assert.assertEquals( 270, ExifOrientationHelper(ExifInterface.ORIENTATION_TRANSPOSE).rotationDegrees ) Assert.assertEquals( 180, ExifOrientationHelper(ExifInterface.ORIENTATION_ROTATE_180).rotationDegrees ) Assert.assertEquals( 180, ExifOrientationHelper(ExifInterface.ORIENTATION_FLIP_VERTICAL).rotationDegrees ) Assert.assertEquals( 270, ExifOrientationHelper(ExifInterface.ORIENTATION_ROTATE_270).rotationDegrees ) Assert.assertEquals( 90, ExifOrientationHelper(ExifInterface.ORIENTATION_TRANSVERSE).rotationDegrees ) Assert.assertEquals( 0, ExifOrientationHelper(ExifInterface.ORIENTATION_FLIP_HORIZONTAL).rotationDegrees ) Assert.assertEquals( 0, ExifOrientationHelper(ExifInterface.ORIENTATION_UNDEFINED).rotationDegrees ) Assert.assertEquals( 0, ExifOrientationHelper(ExifInterface.ORIENTATION_NORMAL).rotationDegrees ) Assert.assertEquals(0, ExifOrientationHelper(-1).rotationDegrees) Assert.assertEquals(0, ExifOrientationHelper(100).rotationDegrees) } @Test fun testApplyToBitmap() { val context = getTestContext() val bitmapPool = LruBitmapPool(44124124) val inBitmap = context.assets.open("sample.jpeg").use { BitmapFactory.decodeStream(it) } Assert.assertTrue( inBitmap.cornerA != inBitmap.cornerB && inBitmap.cornerA != inBitmap.cornerC && inBitmap.cornerA != inBitmap.cornerD ) ExifOrientationHelper(ExifInterface.ORIENTATION_ROTATE_90) .applyToBitmap(inBitmap, bitmapPool, false)!!.let { outBitmap -> Assert.assertEquals( inBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), outBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), inBitmap.corners { listOf(cornerD, cornerA, cornerB, cornerC) }.toString(), ) } ExifOrientationHelper(ExifInterface.ORIENTATION_TRANSVERSE) .applyToBitmap(inBitmap, bitmapPool, false)!!.let { outBitmap -> // Flip horizontally and apply ORIENTATION_ROTATE_90 Assert.assertEquals( inBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), outBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), inBitmap.corners { listOf(cornerC, cornerB, cornerA, cornerD) }.toString(), ) } ExifOrientationHelper(ExifInterface.ORIENTATION_ROTATE_180) .applyToBitmap(inBitmap, bitmapPool, false)!!.let { outBitmap -> Assert.assertEquals( inBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), outBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), inBitmap.corners { listOf(cornerC, cornerD, cornerA, cornerB) }.toString(), ) } ExifOrientationHelper(ExifInterface.ORIENTATION_FLIP_VERTICAL) .applyToBitmap(inBitmap, bitmapPool, false)!!.let { outBitmap -> // Flip horizontally and apply ORIENTATION_ROTATE_180 Assert.assertEquals( inBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), outBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), inBitmap.corners { listOf(cornerD, cornerC, cornerB, cornerA) }.toString(), ) } ExifOrientationHelper(ExifInterface.ORIENTATION_ROTATE_270) .applyToBitmap(inBitmap, bitmapPool, false)!!.let { outBitmap -> Assert.assertEquals( inBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), outBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), inBitmap.corners { listOf(cornerB, cornerC, cornerD, cornerA) }.toString(), ) } ExifOrientationHelper(ExifInterface.ORIENTATION_TRANSPOSE) .applyToBitmap(inBitmap, bitmapPool, false)!!.let { outBitmap -> // Flip horizontally and apply ORIENTATION_ROTATE_270 Assert.assertEquals( inBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), outBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), inBitmap.corners { listOf(cornerA, cornerD, cornerC, cornerB) }.toString(), ) } ExifOrientationHelper(ExifInterface.ORIENTATION_FLIP_HORIZONTAL) .applyToBitmap(inBitmap, bitmapPool, false)!!.let { outBitmap -> Assert.assertEquals( inBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), outBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), inBitmap.corners { listOf(cornerB, cornerA, cornerD, cornerC) }.toString(), ) } Assert.assertNull( ExifOrientationHelper(ExifInterface.ORIENTATION_UNDEFINED).applyToBitmap( inBitmap, bitmapPool, false ) ) Assert.assertNull( ExifOrientationHelper(ExifInterface.ORIENTATION_NORMAL).applyToBitmap( inBitmap, bitmapPool, false ) ) Assert.assertNull( ExifOrientationHelper(-1).applyToBitmap(inBitmap, bitmapPool, false) ) Assert.assertNull( ExifOrientationHelper(100).applyToBitmap(inBitmap, bitmapPool, false) ) } @Test fun testAddToBitmap() { val context = getTestContext() val bitmapPool = LruBitmapPool(44124124) val inBitmap = context.assets.open("sample.jpeg").use { BitmapFactory.decodeStream(it) } Assert.assertTrue( inBitmap.cornerA != inBitmap.cornerB && inBitmap.cornerA != inBitmap.cornerC && inBitmap.cornerA != inBitmap.cornerD ) ExifOrientationHelper(ExifInterface.ORIENTATION_ROTATE_90) .addToBitmap(inBitmap, bitmapPool, false)!!.let { outBitmap -> Assert.assertEquals( inBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), outBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), inBitmap.corners { listOf(cornerB, cornerC, cornerD, cornerA) }.toString(), ) } ExifOrientationHelper(ExifInterface.ORIENTATION_TRANSVERSE) .addToBitmap(inBitmap, bitmapPool, false)!!.let { outBitmap -> // Flip horizontally based on ORIENTATION_ROTATE_90 Assert.assertEquals( inBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), outBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), inBitmap.corners { listOf(cornerC, cornerB, cornerA, cornerD) }.toString(), ) } ExifOrientationHelper(ExifInterface.ORIENTATION_ROTATE_180) .addToBitmap(inBitmap, bitmapPool, false)!!.let { outBitmap -> Assert.assertEquals( inBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), outBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), inBitmap.corners { listOf(cornerC, cornerD, cornerA, cornerB) }.toString(), ) } ExifOrientationHelper(ExifInterface.ORIENTATION_FLIP_VERTICAL) .addToBitmap(inBitmap, bitmapPool, false)!!.let { outBitmap -> // Flip horizontally based on ORIENTATION_ROTATE_180 Assert.assertEquals( inBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), outBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), inBitmap.corners { listOf(cornerD, cornerC, cornerB, cornerA) }.toString(), ) } ExifOrientationHelper(ExifInterface.ORIENTATION_ROTATE_270) .addToBitmap(inBitmap, bitmapPool, false)!!.let { outBitmap -> Assert.assertEquals( inBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), outBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), inBitmap.corners { listOf(cornerD, cornerA, cornerB, cornerC) }.toString(), ) } ExifOrientationHelper(ExifInterface.ORIENTATION_TRANSPOSE) .addToBitmap(inBitmap, bitmapPool, false)!!.let { outBitmap -> // Flip horizontally based on ORIENTATION_ROTATE_270 Assert.assertEquals( inBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), outBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), inBitmap.corners { listOf(cornerA, cornerD, cornerC, cornerB) }.toString(), ) } ExifOrientationHelper(ExifInterface.ORIENTATION_FLIP_HORIZONTAL) .addToBitmap(inBitmap, bitmapPool, false)!!.let { outBitmap -> Assert.assertEquals( inBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), outBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), inBitmap.corners { listOf(cornerB, cornerA, cornerD, cornerC) }.toString(), ) } Assert.assertNull( ExifOrientationHelper(ExifInterface.ORIENTATION_UNDEFINED) .addToBitmap(inBitmap, bitmapPool, false) ) Assert.assertNull( ExifOrientationHelper(ExifInterface.ORIENTATION_NORMAL) .addToBitmap(inBitmap, bitmapPool, false) ) Assert.assertNull( ExifOrientationHelper(-1).addToBitmap(inBitmap, bitmapPool, false) ) Assert.assertNull( ExifOrientationHelper(100).addToBitmap(inBitmap, bitmapPool, false) ) } @Test fun testAddAndApplyToBitmap() { val context = getTestContext() val bitmapPool = LruBitmapPool(44124124) val inBitmap = context.assets.open("sample.jpeg").use { BitmapFactory.decodeStream(it) } Assert.assertTrue( inBitmap.cornerA != inBitmap.cornerB && inBitmap.cornerA != inBitmap.cornerC && inBitmap.cornerA != inBitmap.cornerD ) ExifOrientationHelper(ExifInterface.ORIENTATION_ROTATE_90).applyToBitmap( ExifOrientationHelper(ExifInterface.ORIENTATION_ROTATE_90) .addToBitmap(inBitmap, bitmapPool, false)!!, bitmapPool, false )!!.let { outBitmap -> Assert.assertEquals( inBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), outBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), inBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), ) } ExifOrientationHelper(ExifInterface.ORIENTATION_TRANSVERSE).applyToBitmap( ExifOrientationHelper(ExifInterface.ORIENTATION_TRANSVERSE) .addToBitmap(inBitmap, bitmapPool, false)!!, bitmapPool, false )!!.let { outBitmap -> Assert.assertEquals( inBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), outBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), inBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), ) } ExifOrientationHelper(ExifInterface.ORIENTATION_ROTATE_180).applyToBitmap( ExifOrientationHelper(ExifInterface.ORIENTATION_ROTATE_180) .addToBitmap(inBitmap, bitmapPool, false)!!, bitmapPool, false )!!.let { outBitmap -> Assert.assertEquals( inBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), outBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), inBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), ) } ExifOrientationHelper(ExifInterface.ORIENTATION_FLIP_VERTICAL).applyToBitmap( ExifOrientationHelper(ExifInterface.ORIENTATION_FLIP_VERTICAL) .addToBitmap(inBitmap, bitmapPool, false)!!, bitmapPool, false )!!.let { outBitmap -> Assert.assertEquals( inBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), outBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), inBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), ) } ExifOrientationHelper(ExifInterface.ORIENTATION_ROTATE_270).applyToBitmap( ExifOrientationHelper(ExifInterface.ORIENTATION_ROTATE_270) .addToBitmap(inBitmap, bitmapPool, false)!!, bitmapPool, false )!!.let { outBitmap -> Assert.assertEquals( inBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), outBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), inBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), ) } ExifOrientationHelper(ExifInterface.ORIENTATION_TRANSPOSE).applyToBitmap( ExifOrientationHelper(ExifInterface.ORIENTATION_TRANSPOSE) .addToBitmap(inBitmap, bitmapPool, false)!!, bitmapPool, false )!!.let { outBitmap -> Assert.assertEquals( inBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), outBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), inBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), ) } ExifOrientationHelper(ExifInterface.ORIENTATION_FLIP_HORIZONTAL).applyToBitmap( ExifOrientationHelper(ExifInterface.ORIENTATION_FLIP_HORIZONTAL) .addToBitmap(inBitmap, bitmapPool, false)!!, bitmapPool, false )!!.let { outBitmap -> Assert.assertEquals( inBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), outBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), inBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), ) } } @Test fun testApplyToSize() { Assert.assertEquals( Size(50, 100), ExifOrientationHelper(ExifInterface.ORIENTATION_ROTATE_90) .applyToSize(Size(100, 50)) ) Assert.assertEquals( Size(50, 100), ExifOrientationHelper(ExifInterface.ORIENTATION_TRANSVERSE) .applyToSize(Size(100, 50)) ) Assert.assertEquals( Size(100, 50), ExifOrientationHelper(ExifInterface.ORIENTATION_ROTATE_180) .applyToSize(Size(100, 50)) ) Assert.assertEquals( Size(100, 50), ExifOrientationHelper(ExifInterface.ORIENTATION_FLIP_VERTICAL) .applyToSize(Size(100, 50)) ) Assert.assertEquals( Size(50, 100), ExifOrientationHelper(ExifInterface.ORIENTATION_ROTATE_270) .applyToSize(Size(100, 50)) ) Assert.assertEquals( Size(50, 100), ExifOrientationHelper(ExifInterface.ORIENTATION_TRANSPOSE) .applyToSize(Size(100, 50)) ) Assert.assertEquals( Size(100, 50), ExifOrientationHelper(ExifInterface.ORIENTATION_UNDEFINED) .applyToSize(Size(100, 50)) ) Assert.assertEquals( Size(100, 50), ExifOrientationHelper(ExifInterface.ORIENTATION_NORMAL) .applyToSize(Size(100, 50)) ) Assert.assertEquals( Size(100, 50), ExifOrientationHelper(ExifInterface.ORIENTATION_FLIP_HORIZONTAL) .applyToSize(Size(100, 50)) ) Assert.assertEquals( Size(100, 50), ExifOrientationHelper(-1).applyToSize(Size(100, 50)) ) Assert.assertEquals( Size(100, 50), ExifOrientationHelper(100).applyToSize(Size(100, 50)) ) } @Test fun testAddToSize() { ExifOrientationHelper(ExifInterface.ORIENTATION_ROTATE_90).apply { Assert.assertEquals(Size(50, 100), addToSize(Size(100, 50))) } ExifOrientationHelper(ExifInterface.ORIENTATION_TRANSVERSE).apply { Assert.assertEquals(Size(50, 100), addToSize(Size(100, 50))) } ExifOrientationHelper(ExifInterface.ORIENTATION_ROTATE_180).apply { Assert.assertEquals(Size(100, 50), addToSize(Size(100, 50))) } ExifOrientationHelper(ExifInterface.ORIENTATION_FLIP_VERTICAL).apply { Assert.assertEquals(Size(100, 50), addToSize(Size(100, 50))) } ExifOrientationHelper(ExifInterface.ORIENTATION_ROTATE_270).apply { Assert.assertEquals(Size(50, 100), addToSize(Size(100, 50))) } ExifOrientationHelper(ExifInterface.ORIENTATION_TRANSPOSE).apply { Assert.assertEquals(Size(50, 100), addToSize(Size(100, 50))) } ExifOrientationHelper(ExifInterface.ORIENTATION_UNDEFINED).apply { Assert.assertEquals(Size(100, 50), addToSize(Size(100, 50))) } ExifOrientationHelper(ExifInterface.ORIENTATION_NORMAL).apply { Assert.assertEquals(Size(100, 50), addToSize(Size(100, 50))) } ExifOrientationHelper(ExifInterface.ORIENTATION_FLIP_HORIZONTAL).apply { Assert.assertEquals(Size(100, 50), addToSize(Size(100, 50))) } ExifOrientationHelper(-1).apply { Assert.assertEquals(Size(100, 50), addToSize(Size(100, 50))) } ExifOrientationHelper(100).apply { Assert.assertEquals(Size(100, 50), addToSize(Size(100, 50))) } } @Test fun testAddToResize() { ExifOrientationHelper(ExifInterface.ORIENTATION_ROTATE_90).apply { Assert.assertEquals(Resize(5, 10), addToResize(Resize(10, 5), Size(100, 50))) Assert.assertEquals( Resize(5, 10, END_CROP), addToResize(Resize(10, 5, START_CROP), Size(100, 50)) ) Assert.assertEquals( Resize(5, 10, CENTER_CROP), addToResize(Resize(10, 5, CENTER_CROP), Size(100, 50)) ) Assert.assertEquals( Resize(5, 10, START_CROP), addToResize(Resize(10, 5, END_CROP), Size(100, 50)) ) Assert.assertEquals( Resize(5, 10, FILL), addToResize(Resize(10, 5, FILL), Size(100, 50)) ) Assert.assertEquals( Resize(5, 10, START_CROP), addToResize(Resize(10, 5, START_CROP), Size(50, 100)) ) Assert.assertEquals( Resize(5, 10, CENTER_CROP), addToResize(Resize(10, 5, CENTER_CROP), Size(50, 100)) ) Assert.assertEquals( Resize(5, 10, END_CROP), addToResize(Resize(10, 5, END_CROP), Size(50, 100)) ) Assert.assertEquals( Resize(5, 10, FILL), addToResize(Resize(10, 5, FILL), Size(50, 100)) ) } ExifOrientationHelper(ExifInterface.ORIENTATION_TRANSVERSE).apply { Assert.assertEquals(Resize(5, 10), addToResize(Resize(10, 5), Size(100, 50))) Assert.assertEquals( Resize(5, 10, END_CROP), addToResize(Resize(10, 5, START_CROP), Size(100, 50)) ) Assert.assertEquals( Resize(5, 10, CENTER_CROP), addToResize(Resize(10, 5, CENTER_CROP), Size(100, 50)) ) Assert.assertEquals( Resize(5, 10, START_CROP), addToResize(Resize(10, 5, END_CROP), Size(100, 50)) ) Assert.assertEquals( Resize(5, 10, FILL), addToResize(Resize(10, 5, FILL), Size(100, 50)) ) Assert.assertEquals( Resize(5, 10, END_CROP), addToResize(Resize(10, 5, START_CROP), Size(50, 100)) ) Assert.assertEquals( Resize(5, 10, CENTER_CROP), addToResize(Resize(10, 5, CENTER_CROP), Size(50, 100)) ) Assert.assertEquals( Resize(5, 10, START_CROP), addToResize(Resize(10, 5, END_CROP), Size(50, 100)) ) Assert.assertEquals( Resize(5, 10, FILL), addToResize(Resize(10, 5, FILL), Size(50, 100)) ) } ExifOrientationHelper(ExifInterface.ORIENTATION_ROTATE_180).apply { Assert.assertEquals(Resize(10, 5), addToResize(Resize(10, 5), Size(100, 50))) Assert.assertEquals( Resize(10, 5, END_CROP), addToResize(Resize(10, 5, START_CROP), Size(100, 50)) ) Assert.assertEquals( Resize(10, 5, CENTER_CROP), addToResize(Resize(10, 5, CENTER_CROP), Size(100, 50)) ) Assert.assertEquals( Resize(10, 5, START_CROP), addToResize(Resize(10, 5, END_CROP), Size(100, 50)) ) Assert.assertEquals( Resize(10, 5, FILL), addToResize(Resize(10, 5, FILL), Size(100, 50)) ) Assert.assertEquals( Resize(10, 5, END_CROP), addToResize(Resize(10, 5, START_CROP), Size(50, 100)) ) Assert.assertEquals( Resize(10, 5, CENTER_CROP), addToResize(Resize(10, 5, CENTER_CROP), Size(50, 100)) ) Assert.assertEquals( Resize(10, 5, START_CROP), addToResize(Resize(10, 5, END_CROP), Size(50, 100)) ) Assert.assertEquals( Resize(10, 5, FILL), addToResize(Resize(10, 5, FILL), Size(50, 100)) ) } ExifOrientationHelper(ExifInterface.ORIENTATION_FLIP_VERTICAL).apply { Assert.assertEquals(Resize(10, 5), addToResize(Resize(10, 5), Size(100, 50))) Assert.assertEquals( Resize(10, 5, START_CROP), addToResize(Resize(10, 5, START_CROP), Size(100, 50)) ) Assert.assertEquals( Resize(10, 5, CENTER_CROP), addToResize(Resize(10, 5, CENTER_CROP), Size(100, 50)) ) Assert.assertEquals( Resize(10, 5, END_CROP), addToResize(Resize(10, 5, END_CROP), Size(100, 50)) ) Assert.assertEquals( Resize(10, 5, FILL), addToResize(Resize(10, 5, FILL), Size(100, 50)) ) Assert.assertEquals( Resize(10, 5, END_CROP), addToResize(Resize(10, 5, START_CROP), Size(50, 100)) ) Assert.assertEquals( Resize(10, 5, CENTER_CROP), addToResize(Resize(10, 5, CENTER_CROP), Size(50, 100)) ) Assert.assertEquals( Resize(10, 5, START_CROP), addToResize(Resize(10, 5, END_CROP), Size(50, 100)) ) Assert.assertEquals( Resize(10, 5, FILL), addToResize(Resize(10, 5, FILL), Size(50, 100)) ) } ExifOrientationHelper(ExifInterface.ORIENTATION_ROTATE_270).apply { Assert.assertEquals(Resize(5, 10), addToResize(Resize(10, 5), Size(100, 50))) Assert.assertEquals( Resize(5, 10, START_CROP), addToResize(Resize(10, 5, START_CROP), Size(100, 50)) ) Assert.assertEquals( Resize(5, 10, CENTER_CROP), addToResize(Resize(10, 5, CENTER_CROP), Size(100, 50)) ) Assert.assertEquals( Resize(5, 10, END_CROP), addToResize(Resize(10, 5, END_CROP), Size(100, 50)) ) Assert.assertEquals( Resize(5, 10, FILL), addToResize(Resize(10, 5, FILL), Size(100, 50)) ) Assert.assertEquals( Resize(5, 10, END_CROP), addToResize(Resize(10, 5, START_CROP), Size(50, 100)) ) Assert.assertEquals( Resize(5, 10, CENTER_CROP), addToResize(Resize(10, 5, CENTER_CROP), Size(50, 100)) ) Assert.assertEquals( Resize(5, 10, START_CROP), addToResize(Resize(10, 5, END_CROP), Size(50, 100)) ) Assert.assertEquals( Resize(5, 10, FILL), addToResize(Resize(10, 5, FILL), Size(50, 100)) ) } ExifOrientationHelper(ExifInterface.ORIENTATION_TRANSPOSE).apply { Assert.assertEquals(Resize(5, 10), addToResize(Resize(10, 5), Size(100, 50))) Assert.assertEquals( Resize(5, 10, START_CROP), addToResize(Resize(10, 5, START_CROP), Size(100, 50)) ) Assert.assertEquals( Resize(5, 10, CENTER_CROP), addToResize(Resize(10, 5, CENTER_CROP), Size(100, 50)) ) Assert.assertEquals( Resize(5, 10, END_CROP), addToResize(Resize(10, 5, END_CROP), Size(100, 50)) ) Assert.assertEquals( Resize(5, 10, FILL), addToResize(Resize(10, 5, FILL), Size(100, 50)) ) Assert.assertEquals( Resize(5, 10, START_CROP), addToResize(Resize(10, 5, START_CROP), Size(50, 100)) ) Assert.assertEquals( Resize(5, 10, CENTER_CROP), addToResize(Resize(10, 5, CENTER_CROP), Size(50, 100)) ) Assert.assertEquals( Resize(5, 10, END_CROP), addToResize(Resize(10, 5, END_CROP), Size(50, 100)) ) Assert.assertEquals( Resize(5, 10, FILL), addToResize(Resize(10, 5, FILL), Size(50, 100)) ) } ExifOrientationHelper(ExifInterface.ORIENTATION_UNDEFINED).apply { Assert.assertEquals(Resize(10, 5), addToResize(Resize(10, 5), Size(100, 50))) Assert.assertEquals( Resize(10, 5, START_CROP), addToResize(Resize(10, 5, START_CROP), Size(100, 50)) ) Assert.assertEquals( Resize(10, 5, CENTER_CROP), addToResize(Resize(10, 5, CENTER_CROP), Size(100, 50)) ) Assert.assertEquals( Resize(10, 5, END_CROP), addToResize(Resize(10, 5, END_CROP), Size(100, 50)) ) Assert.assertEquals( Resize(10, 5, FILL), addToResize(Resize(10, 5, FILL), Size(100, 50)) ) Assert.assertEquals( Resize(10, 5, START_CROP), addToResize(Resize(10, 5, START_CROP), Size(50, 100)) ) Assert.assertEquals( Resize(10, 5, CENTER_CROP), addToResize(Resize(10, 5, CENTER_CROP), Size(50, 100)) ) Assert.assertEquals( Resize(10, 5, END_CROP), addToResize(Resize(10, 5, END_CROP), Size(50, 100)) ) Assert.assertEquals( Resize(10, 5, FILL), addToResize(Resize(10, 5, FILL), Size(50, 100)) ) } ExifOrientationHelper(ExifInterface.ORIENTATION_NORMAL).apply { Assert.assertEquals(Resize(10, 5), addToResize(Resize(10, 5), Size(100, 50))) Assert.assertEquals( Resize(10, 5, START_CROP), addToResize(Resize(10, 5, START_CROP), Size(100, 50)) ) Assert.assertEquals( Resize(10, 5, CENTER_CROP), addToResize(Resize(10, 5, CENTER_CROP), Size(100, 50)) ) Assert.assertEquals( Resize(10, 5, END_CROP), addToResize(Resize(10, 5, END_CROP), Size(100, 50)) ) Assert.assertEquals( Resize(10, 5, FILL), addToResize(Resize(10, 5, FILL), Size(100, 50)) ) Assert.assertEquals( Resize(10, 5, START_CROP), addToResize(Resize(10, 5, START_CROP), Size(50, 100)) ) Assert.assertEquals( Resize(10, 5, CENTER_CROP), addToResize(Resize(10, 5, CENTER_CROP), Size(50, 100)) ) Assert.assertEquals( Resize(10, 5, END_CROP), addToResize(Resize(10, 5, END_CROP), Size(50, 100)) ) Assert.assertEquals( Resize(10, 5, FILL), addToResize(Resize(10, 5, FILL), Size(50, 100)) ) } ExifOrientationHelper(ExifInterface.ORIENTATION_FLIP_HORIZONTAL).apply { Assert.assertEquals(Resize(10, 5), addToResize(Resize(10, 5), Size(100, 50))) Assert.assertEquals( Resize(10, 5, END_CROP), addToResize(Resize(10, 5, START_CROP), Size(100, 50)) ) Assert.assertEquals( Resize(10, 5, CENTER_CROP), addToResize(Resize(10, 5, CENTER_CROP), Size(100, 50)) ) Assert.assertEquals( Resize(10, 5, START_CROP), addToResize(Resize(10, 5, END_CROP), Size(100, 50)) ) Assert.assertEquals( Resize(10, 5, FILL), addToResize(Resize(10, 5, FILL), Size(100, 50)) ) Assert.assertEquals( Resize(10, 5, START_CROP), addToResize(Resize(10, 5, START_CROP), Size(50, 100)) ) Assert.assertEquals( Resize(10, 5, CENTER_CROP), addToResize(Resize(10, 5, CENTER_CROP), Size(50, 100)) ) Assert.assertEquals( Resize(10, 5, END_CROP), addToResize(Resize(10, 5, END_CROP), Size(50, 100)) ) Assert.assertEquals( Resize(10, 5, FILL), addToResize(Resize(10, 5, FILL), Size(50, 100)) ) } ExifOrientationHelper(-1).apply { Assert.assertEquals(Resize(10, 5), addToResize(Resize(10, 5), Size(100, 50))) Assert.assertEquals( Resize(10, 5, START_CROP), addToResize(Resize(10, 5, START_CROP), Size(100, 50)) ) Assert.assertEquals( Resize(10, 5, CENTER_CROP), addToResize(Resize(10, 5, CENTER_CROP), Size(100, 50)) ) Assert.assertEquals( Resize(10, 5, END_CROP), addToResize(Resize(10, 5, END_CROP), Size(100, 50)) ) Assert.assertEquals( Resize(10, 5, FILL), addToResize(Resize(10, 5, FILL), Size(100, 50)) ) Assert.assertEquals( Resize(10, 5, START_CROP), addToResize(Resize(10, 5, START_CROP), Size(50, 100)) ) Assert.assertEquals( Resize(10, 5, CENTER_CROP), addToResize(Resize(10, 5, CENTER_CROP), Size(50, 100)) ) Assert.assertEquals( Resize(10, 5, END_CROP), addToResize(Resize(10, 5, END_CROP), Size(50, 100)) ) Assert.assertEquals( Resize(10, 5, FILL), addToResize(Resize(10, 5, FILL), Size(50, 100)) ) } ExifOrientationHelper(10).apply { Assert.assertEquals(Resize(10, 5), addToResize(Resize(10, 5), Size(100, 50))) Assert.assertEquals( Resize(10, 5, START_CROP), addToResize(Resize(10, 5, START_CROP), Size(100, 50)) ) Assert.assertEquals( Resize(10, 5, CENTER_CROP), addToResize(Resize(10, 5, CENTER_CROP), Size(100, 50)) ) Assert.assertEquals( Resize(10, 5, END_CROP), addToResize(Resize(10, 5, END_CROP), Size(100, 50)) ) Assert.assertEquals( Resize(10, 5, FILL), addToResize(Resize(10, 5, FILL), Size(100, 50)) ) Assert.assertEquals( Resize(10, 5, START_CROP), addToResize(Resize(10, 5, START_CROP), Size(50, 100)) ) Assert.assertEquals( Resize(10, 5, CENTER_CROP), addToResize(Resize(10, 5, CENTER_CROP), Size(50, 100)) ) Assert.assertEquals( Resize(10, 5, END_CROP), addToResize(Resize(10, 5, END_CROP), Size(50, 100)) ) Assert.assertEquals( Resize(10, 5, FILL), addToResize(Resize(10, 5, FILL), Size(50, 100)) ) } } @Test fun testAddToRect() { Assert.assertEquals( Rect(10, 50, 30, 60), ExifOrientationHelper(ExifInterface.ORIENTATION_ROTATE_90) .addToRect(Rect(40, 10, 50, 30), Size(100, 50)) ) Assert.assertEquals( Rect(20, 50, 40, 60), ExifOrientationHelper(ExifInterface.ORIENTATION_TRANSVERSE) .addToRect(Rect(40, 10, 50, 30), Size(100, 50)) ) Assert.assertEquals( Rect(50, 20, 60, 40), ExifOrientationHelper(ExifInterface.ORIENTATION_ROTATE_180) .addToRect(Rect(40, 10, 50, 30), Size(100, 50)) ) Assert.assertEquals( Rect(40, 20, 50, 40), ExifOrientationHelper(ExifInterface.ORIENTATION_FLIP_VERTICAL) .addToRect(Rect(40, 10, 50, 30), Size(100, 50)) ) Assert.assertEquals( Rect(20, 40, 40, 50), ExifOrientationHelper(ExifInterface.ORIENTATION_ROTATE_270) .addToRect(Rect(40, 10, 50, 30), Size(100, 50)) ) Assert.assertEquals( Rect(10, 40, 30, 50), ExifOrientationHelper(ExifInterface.ORIENTATION_TRANSPOSE) .addToRect(Rect(40, 10, 50, 30), Size(100, 50)) ) Assert.assertEquals( Rect(50, 10, 60, 30), ExifOrientationHelper(ExifInterface.ORIENTATION_FLIP_HORIZONTAL) .addToRect(Rect(40, 10, 50, 30), Size(100, 50)) ) Assert.assertEquals( Rect(40, 10, 50, 30), ExifOrientationHelper(ExifInterface.ORIENTATION_UNDEFINED) .addToRect(Rect(40, 10, 50, 30), Size(100, 50)) ) Assert.assertEquals( Rect(40, 10, 50, 30), ExifOrientationHelper(ExifInterface.ORIENTATION_NORMAL) .addToRect(Rect(40, 10, 50, 30), Size(100, 50)) ) Assert.assertEquals( Rect(40, 10, 50, 30), ExifOrientationHelper(-1) .addToRect(Rect(40, 10, 50, 30), Size(100, 50)) ) Assert.assertEquals( Rect(40, 10, 50, 30), ExifOrientationHelper(100) .addToRect(Rect(40, 10, 50, 30), Size(100, 50)) ) } }
apache-2.0
09ac48e8bc4a2815b904bcd772432c24
42.478632
101
0.570923
4.985517
false
false
false
false
lare96/luna
plugins/world/player/skill/crafting/hideTanning/Hide.kt
1
1452
package world.player.skill.crafting.hideTanning /** * An enum representing all tannable hides. */ enum class Hide(val hide: Int, val tan: Int, val cost: Int, val displayName: String) { SOFT_LEATHER(hide = 1739, tan = 1741, cost = 2, displayName = "Soft leather"), HARD_LEATHER(hide = 1739, tan = 1743, cost = 3, displayName = "Hard leather"), SWAMP_SNAKESKIN(hide = 7801, tan = 6289, cost = 20, displayName = "Snakeskin"), SNAKESKIN(hide = 6287, tan = 6289, cost = 15, displayName = "Snakeskin"), GREEN_D_LEATHER(hide = 1753, tan = 1745, cost = 20, displayName = "Green d'hide"), BLUE_D_LEATHER(hide = 1751, tan = 2505, cost = 20, displayName = "Blue d'hide"), RED_D_LEATHER(hide = 1749, tan = 2507, cost = 20, displayName = "Red d'hide"), BLACK_D_LEATHER(hide = 1747, tan = 2509, cost = 20, displayName = "Black d'hide"); companion object { /** * Mappings of [Hide.tan] to [Hide]. */ val TAN_TO_HIDE = values().associateBy { it.tan } } }
mit
f752a7692771ac4d5969992c5014aa31
29.914894
86
0.437328
4.258065
false
false
false
false
salRoid/Filmy
app/src/main/java/tech/salroid/filmy/ui/activities/SettingsActivity.kt
1
4228
package tech.salroid.filmy.ui.activities import androidx.appcompat.app.AppCompatActivity import tech.salroid.filmy.R import android.os.Bundle import androidx.core.content.res.ResourcesCompat import androidx.preference.Preference.OnPreferenceChangeListener import androidx.preference.Preference.OnPreferenceClickListener import android.content.Intent import android.graphics.Color import android.view.MenuItem import androidx.preference.* import tech.salroid.filmy.databinding.ActivitySettingsBinding class SettingsActivity : AppCompatActivity() { private var nightMode = false private lateinit var binding: ActivitySettingsBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val sp = PreferenceManager.getDefaultSharedPreferences(this) nightMode = sp.getBoolean("dark", false) if (nightMode) setTheme(R.style.AppTheme_Base_Dark) else setTheme(R.style.AppTheme_Base) binding = ActivitySettingsBinding.inflate(layoutInflater) setContentView(binding.root) setSupportActionBar(binding.toolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) supportActionBar?.title = "" binding.logo.typeface = ResourcesCompat.getFont(this, R.font.rubik) if (nightMode) allThemeLogic() supportFragmentManager.beginTransaction().replace(R.id.container, FilmyPreferenceFragment()).commit() } private fun allThemeLogic() { binding.logo.setTextColor(Color.parseColor("#bdbdbd")) } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == android.R.id.home) { finish() } return super.onOptionsItemSelected(item) } class FilmyPreferenceFragment : PreferenceFragmentCompat() { private var imagePref: SwitchPreferenceCompat? = null private var darkPref: SwitchPreferenceCompat? = null override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { setPreferencesFromResource(R.xml.preference, rootKey) val myPreference = PreferenceManager.getDefaultSharedPreferences(requireContext()).edit() imagePref = findPreference("imagequality") as? SwitchPreferenceCompat imagePref?.onPreferenceChangeListener = OnPreferenceChangeListener { preference, o -> val quality: String val switchPreference = preference as SwitchPreferenceCompat quality = if (!switchPreference.isChecked) { "original" } else { "w1280" } myPreference.putString("image_quality", quality) myPreference.apply() true } darkPref = findPreference("dark") as? SwitchPreferenceCompat darkPref?.onPreferenceChangeListener = OnPreferenceChangeListener { _, _ -> recreateActivity() true } val license = findPreference("license") as? Preference license?.onPreferenceClickListener = OnPreferenceClickListener { startActivity(Intent(activity, License::class.java)) true } val share = findPreference("Share") as? Preference share?.onPreferenceClickListener = OnPreferenceClickListener { val appShareDetails = resources.getString(R.string.app_share_link) val myIntent = Intent(Intent.ACTION_SEND) myIntent.type = "text/plain" myIntent.putExtra( Intent.EXTRA_TEXT, "Check out this awesome movie app.\n*filmy*\n$appShareDetails" ) startActivity(Intent.createChooser(myIntent, "Share with")) true } val about = findPreference("About") as? Preference about?.onPreferenceClickListener = OnPreferenceClickListener { startActivity(Intent(activity, AboutActivity::class.java)) true } } private fun recreateActivity() { activity?.recreate() } } }
apache-2.0
3391c48e97b0fde625e507d92725a904
37.099099
109
0.650662
5.775956
false
false
false
false
AndroidX/androidx
compose/material3/material3/src/androidAndroidTest/kotlin/androidx/compose/material3/MaterialComponentsInsetSupportTest.kt
3
5351
/* * Copyright (C) 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 * * 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.PaddingValues import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.WindowInsetsSides import androidx.compose.foundation.layout.asPaddingValues import androidx.compose.foundation.layout.only import androidx.compose.foundation.layout.systemBars import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.LocalLayoutDirection import androidx.compose.ui.test.junit4.createAndroidComposeRule import androidx.compose.ui.unit.LayoutDirection import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.MediumTest import com.google.common.truth.Truth.assertThat import java.util.concurrent.TimeUnit import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @OptIn(ExperimentalMaterial3Api::class) @MediumTest @RunWith(AndroidJUnit4::class) class MaterialComponentsInsetSupportTest { @get:Rule val rule = createAndroidComposeRule<MaterialWindowInsetsActivity>() @Before fun setup() { rule.activity.createdLatch.await(1, TimeUnit.SECONDS) } @Test fun topAppBar_respectsInsetsDefault() { var contentPadding: WindowInsets? = null var expected: WindowInsets? = null rule.setContent { expected = WindowInsets.systemBars .only(WindowInsetsSides.Horizontal + WindowInsetsSides.Top) contentPadding = TopAppBarDefaults.windowInsets } rule.runOnIdle { assertThat(contentPadding).isEqualTo(expected) } } @Test fun bottomAppBar_respectsInsetsDefault() { var contentPadding: WindowInsets? = null var expected: WindowInsets? = null rule.setContent { expected = WindowInsets.systemBars .only(WindowInsetsSides.Horizontal + WindowInsetsSides.Bottom) contentPadding = BottomAppBarDefaults.windowInsets } rule.runOnIdle { // only checking bottom as bottom app bar has special optional padding on the sides assertThat(contentPadding).isEqualTo(expected) } } @Test fun drawerSheets_respectsInsetsDefault() { var contentPadding: WindowInsets? = null var expected: WindowInsets? = null rule.setContent { expected = WindowInsets.systemBars .only(WindowInsetsSides.Start + WindowInsetsSides.Vertical) contentPadding = DrawerDefaults.windowInsets } rule.runOnIdle { assertThat(contentPadding).isEqualTo(expected) } } @Test fun navigationBar_respectsInsetsDefault() { var contentPadding: WindowInsets? = null var expected: WindowInsets? = null rule.setContent { expected = WindowInsets.systemBars .only(WindowInsetsSides.Bottom + WindowInsetsSides.Horizontal) contentPadding = NavigationBarDefaults.windowInsets } rule.runOnIdle { assertThat(contentPadding).isEqualTo(expected) } } @Test fun NavRail_respectsInsetsDefault() { var contentPadding: WindowInsets? = null var expected: WindowInsets? = null rule.setContent { expected = WindowInsets.systemBars .only(WindowInsetsSides.Start + WindowInsetsSides.Vertical) contentPadding = NavigationRailDefaults.windowInsets } rule.runOnIdle { assertThat(contentPadding).isEqualTo(expected) } } @Test fun scaffold_providesInsets() { var contentPadding: PaddingValues? = null var expected: PaddingValues? = null var layoutDirection: LayoutDirection? = null rule.setContent { layoutDirection = LocalLayoutDirection.current expected = WindowInsets.systemBars .asPaddingValues(LocalDensity.current) Scaffold { paddingValues -> contentPadding = paddingValues } } rule.runOnIdle { assertThat(contentPadding?.calculateBottomPadding()) .isEqualTo(expected?.calculateBottomPadding()) assertThat(contentPadding?.calculateTopPadding()) .isEqualTo(expected?.calculateTopPadding()) assertThat(contentPadding?.calculateLeftPadding(layoutDirection!!)) .isEqualTo(expected?.calculateLeftPadding(layoutDirection!!)) assertThat(contentPadding?.calculateRightPadding(layoutDirection!!)) .isEqualTo(expected?.calculateRightPadding(layoutDirection!!)) } } }
apache-2.0
e01818d11bb4e3dd3fa7857df2534a1a
34.673333
95
0.686974
5.527893
false
true
false
false