repo_name
stringlengths
7
81
path
stringlengths
6
242
copies
stringclasses
55 values
size
stringlengths
2
6
content
stringlengths
55
737k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
5.44
99.8
line_max
int64
15
979
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.93
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
mdanielwork/intellij-community
plugins/java-decompiler/plugin/src/org/jetbrains/java/decompiler/IdeaDecompiler.kt
1
9908
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.java.decompiler import com.intellij.application.options.CodeStyle import com.intellij.execution.filters.LineNumbersMapping import com.intellij.ide.highlighter.JavaFileType import com.intellij.ide.plugins.PluginManagerCore import com.intellij.ide.util.PropertiesComponent import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ex.ApplicationManagerEx import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileEditor.FileEditorManagerListener import com.intellij.openapi.fileTypes.StdFileTypes import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.newvfs.RefreshQueue import com.intellij.openapi.vfs.newvfs.events.VFileContentChangeEvent import com.intellij.psi.PsiJavaModule import com.intellij.psi.PsiPackage import com.intellij.psi.compiled.ClassFileDecompilers import com.intellij.psi.impl.compiled.ClsFileImpl import com.intellij.ui.components.LegalNoticeDialog import com.intellij.util.ArrayUtil import com.intellij.util.containers.ContainerUtil import org.jetbrains.java.decompiler.main.decompiler.BaseDecompiler import org.jetbrains.java.decompiler.main.extern.IBytecodeProvider import org.jetbrains.java.decompiler.main.extern.IFernflowerPreferences import org.jetbrains.java.decompiler.main.extern.IResultSaver import java.io.File import java.io.IOException import java.util.* import java.util.concurrent.Callable import java.util.concurrent.Future import java.util.jar.Manifest class IdeaDecompiler : ClassFileDecompilers.Light() { companion object { const val BANNER: String = "//\n// Source code recreated from a .class file by IntelliJ IDEA\n// (powered by Fernflower decompiler)\n//\n\n" private const val LEGAL_NOTICE_KEY = "decompiler.legal.notice.accepted" private const val POSTPONE_EXIT_CODE = DialogWrapper.CANCEL_EXIT_CODE private const val DECLINE_EXIT_CODE = DialogWrapper.NEXT_USER_EXIT_CODE private fun getOptions(): Map<String, Any> { val options = CodeStyle.getDefaultSettings().getIndentOptions(JavaFileType.INSTANCE) val indent = StringUtil.repeat(" ", options.INDENT_SIZE) return mapOf( IFernflowerPreferences.HIDE_DEFAULT_CONSTRUCTOR to "0", IFernflowerPreferences.DECOMPILE_GENERIC_SIGNATURES to "1", IFernflowerPreferences.REMOVE_SYNTHETIC to "1", IFernflowerPreferences.REMOVE_BRIDGE to "1", IFernflowerPreferences.LITERALS_AS_IS to "1", IFernflowerPreferences.NEW_LINE_SEPARATOR to "1", IFernflowerPreferences.BANNER to BANNER, IFernflowerPreferences.MAX_PROCESSING_METHOD to 60, IFernflowerPreferences.INDENT_STRING to indent, IFernflowerPreferences.IGNORE_INVALID_BYTECODE to "1", IFernflowerPreferences.VERIFY_ANONYMOUS_CLASSES to "1", IFernflowerPreferences.UNIT_TEST_MODE to if (ApplicationManager.getApplication().isUnitTestMode) "1" else "0") } } private val myLogger = lazy { IdeaLogger() } private val myOptions = lazy { getOptions() } private val myFutures = ContainerUtil.newConcurrentMap<VirtualFile, Future<CharSequence>>() @Volatile private var myLegalNoticeAccepted = false init { myLegalNoticeAccepted = ApplicationManager.getApplication().isUnitTestMode || PropertiesComponent.getInstance().isValueSet(LEGAL_NOTICE_KEY) if (!myLegalNoticeAccepted) { intercept() } } private fun intercept() { val app = ApplicationManager.getApplication() val connection = app.messageBus.connect(app) connection.subscribe(FileEditorManagerListener.Before.FILE_EDITOR_MANAGER, object : FileEditorManagerListener.Before { override fun beforeFileOpened(source: FileEditorManager, file: VirtualFile) { if (!myLegalNoticeAccepted && file.fileType === StdFileTypes.CLASS && ClassFileDecompilers.find(file) === this@IdeaDecompiler) { myFutures[file] = app.executeOnPooledThread(Callable<CharSequence> { decompile(file) }) val title = IdeaDecompilerBundle.message("legal.notice.title", StringUtil.last(file.path, 40, true)) val message = IdeaDecompilerBundle.message("legal.notice.text") val result = LegalNoticeDialog.build(title, message) .withCancelText(IdeaDecompilerBundle.message("legal.notice.action.postpone")) .withCustomAction(IdeaDecompilerBundle.message("legal.notice.action.reject"), DECLINE_EXIT_CODE) .show() when (result) { DialogWrapper.OK_EXIT_CODE -> { PropertiesComponent.getInstance().setValue(LEGAL_NOTICE_KEY, true) myLegalNoticeAccepted = true app.invokeLater { RefreshQueue.getInstance().processSingleEvent( VFileContentChangeEvent(this@IdeaDecompiler, file, file.modificationStamp, -1, false)) } connection.disconnect() } DECLINE_EXIT_CODE -> { myFutures.remove(file)?.cancel(true) PluginManagerCore.disablePlugin("org.jetbrains.java.decompiler") ApplicationManagerEx.getApplicationEx().restart(true) } POSTPONE_EXIT_CODE -> { myFutures.remove(file)?.cancel(true) } } } } }) } override fun accepts(file: VirtualFile): Boolean = true override fun getText(file: VirtualFile): CharSequence = if (myLegalNoticeAccepted) myFutures.remove(file)?.get() ?: decompile(file) else ClsFileImpl.decompile(file) private fun decompile(file: VirtualFile): CharSequence { if (PsiPackage.PACKAGE_INFO_CLS_FILE == file.name || PsiJavaModule.MODULE_INFO_CLS_FILE == file.name) { return ClsFileImpl.decompile(file) } val indicator = ProgressManager.getInstance().progressIndicator if (indicator != null) { indicator.text = IdeaDecompilerBundle.message("decompiling.progress", file.name) } try { val mask = "${file.nameWithoutExtension}$" val files = mapOf(file.path to file) + file.parent.children.filter { it.nameWithoutExtension.startsWith(mask) && it.fileType === StdFileTypes.CLASS }.map { it.path to it } val options = HashMap(myOptions.value) if (Registry.`is`("decompiler.use.line.mapping")) { options[IFernflowerPreferences.BYTECODE_SOURCE_MAPPING] = "1" } if (Registry.`is`("decompiler.dump.original.lines")) { options[IFernflowerPreferences.DUMP_ORIGINAL_LINES] = "1" } val provider = MyBytecodeProvider(files) val saver = MyResultSaver() val decompiler = BaseDecompiler(provider, saver, options, myLogger.value) files.keys.forEach { path -> decompiler.addSource(File(path)) } decompiler.decompileContext() val mapping = saver.myMapping if (mapping != null) { file.putUserData(LineNumbersMapping.LINE_NUMBERS_MAPPING_KEY, ExactMatchLineNumbersMapping(mapping)) } return saver.myResult } catch (e: ProcessCanceledException) { throw e } catch (e: Exception) { if (e is IdeaLogger.InternalException && e.cause is IOException) { Logger.getInstance(IdeaDecompiler::class.java).warn(file.url, e) return ArrayUtil.EMPTY_CHAR_SEQUENCE } if (ApplicationManager.getApplication().isUnitTestMode) { throw AssertionError(file.url, e) } else { throw ClassFileDecompilers.Light.CannotDecompileException(e) } } } private class MyBytecodeProvider(private val files: Map<String, VirtualFile>) : IBytecodeProvider { override fun getBytecode(externalPath: String, internalPath: String?): ByteArray { val path = FileUtil.toSystemIndependentName(externalPath) val file = files[path] ?: throw AssertionError(path + " not in " + files.keys) return file.contentsToByteArray(false) } } private class MyResultSaver : IResultSaver { var myResult = "" var myMapping: IntArray? = null override fun saveClassFile(path: String, qualifiedName: String, entryName: String, content: String, mapping: IntArray?) { if (myResult.isEmpty()) { myResult = content myMapping = mapping } } override fun saveFolder(path: String) { } override fun copyFile(source: String, path: String, entryName: String) { } override fun createArchive(path: String, archiveName: String, manifest: Manifest) { } override fun saveDirEntry(path: String, archiveName: String, entryName: String) { } override fun copyEntry(source: String, path: String, archiveName: String, entry: String) { } override fun saveClassEntry(path: String, archiveName: String, qualifiedName: String, entryName: String, content: String) { } override fun closeArchive(path: String, archiveName: String) { } } private class ExactMatchLineNumbersMapping(private val mapping: IntArray) : LineNumbersMapping { @Suppress("LoopToCallChain") override fun bytecodeToSource(line: Int): Int { for (i in mapping.indices step 2) { if (mapping[i] == line) { return mapping[i + 1] } } return -1 } @Suppress("LoopToCallChain") override fun sourceToBytecode(line: Int): Int { for (i in mapping.indices step 2) { if (mapping[i + 1] == line) { return mapping[i] } } return -1 } } }
apache-2.0
5636ae7d44ee867d699942ae34b9dbef
40.634454
144
0.714877
4.555402
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/search/declarationsSearch/overridersSearch.kt
1
7684
// 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.search.declarationsSearch import com.intellij.psi.* import com.intellij.psi.search.SearchScope import com.intellij.psi.search.searches.AllOverridingMethodsSearch import com.intellij.psi.search.searches.DirectClassInheritorsSearch import com.intellij.psi.search.searches.FunctionalExpressionSearch import com.intellij.psi.search.searches.OverridingMethodsSearch import com.intellij.psi.util.MethodSignatureUtil import com.intellij.psi.util.PsiUtil import com.intellij.psi.util.TypeConversionUtil import com.intellij.util.EmptyQuery import com.intellij.util.MergeQuery import com.intellij.util.Processor import com.intellij.util.Query import org.jetbrains.kotlin.asJava.* import org.jetbrains.kotlin.asJava.classes.KtFakeLightClass import org.jetbrains.kotlin.asJava.classes.KtFakeLightMethod import org.jetbrains.kotlin.idea.base.util.allScope import org.jetbrains.kotlin.idea.base.util.excludeKotlinSources import org.jetbrains.kotlin.idea.search.KotlinSearchUsagesSupport.Companion.findDeepestSuperMethodsNoWrapping import org.jetbrains.kotlin.idea.search.KotlinSearchUsagesSupport.Companion.forEachKotlinOverride import org.jetbrains.kotlin.idea.search.KotlinSearchUsagesSupport.Companion.forEachOverridingMethod import org.jetbrains.kotlin.idea.search.KotlinSearchUsagesSupport.Companion.isOverridable import org.jetbrains.kotlin.idea.search.useScope import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject import java.util.* fun PsiElement.isOverridableElement(): Boolean = when (this) { is PsiMethod -> PsiUtil.canBeOverridden(this) is KtDeclaration -> isOverridable() else -> false } fun HierarchySearchRequest<*>.searchOverriders(): Query<PsiMethod> { val psiMethods = runReadAction { originalElement.toLightMethods() } if (psiMethods.isEmpty()) return EmptyQuery.getEmptyQuery() return psiMethods .map { psiMethod -> KotlinPsiMethodOverridersSearch.search(copy(psiMethod)) } .reduce { query1, query2 -> MergeQuery(query1, query2) } } object KotlinPsiMethodOverridersSearch : HierarchySearch<PsiMethod>(PsiMethodOverridingHierarchyTraverser) { fun searchDirectOverriders(psiMethod: PsiMethod): Iterable<PsiMethod> { fun PsiMethod.isAcceptable(inheritor: PsiClass, baseMethod: PsiMethod, baseClass: PsiClass): Boolean = when { hasModifierProperty(PsiModifier.STATIC) -> false baseMethod.hasModifierProperty(PsiModifier.PACKAGE_LOCAL) -> JavaPsiFacade.getInstance(project).arePackagesTheSame(baseClass, inheritor) else -> true } val psiClass = psiMethod.containingClass ?: return Collections.emptyList() val classToMethod = LinkedHashMap<PsiClass, PsiMethod>() val classTraverser = object : HierarchyTraverser<PsiClass> { override fun nextElements(current: PsiClass): Iterable<PsiClass> = DirectClassInheritorsSearch.search( current, current.project.allScope(), /* includeAnonymous = */ true ) override fun shouldDescend(element: PsiClass): Boolean = element.isInheritable() && !classToMethod.containsKey(element) } classTraverser.forEach(psiClass) { inheritor -> val substitutor = TypeConversionUtil.getSuperClassSubstitutor(psiClass, inheritor, PsiSubstitutor.EMPTY) val signature = psiMethod.getSignature(substitutor) val candidate = MethodSignatureUtil.findMethodBySuperSignature(inheritor, signature, false) if (candidate != null && candidate.isAcceptable(inheritor, psiMethod, psiClass)) { classToMethod[inheritor] = candidate } } return classToMethod.values } override fun isApplicable(request: HierarchySearchRequest<PsiMethod>): Boolean = runReadAction { request.originalElement.isOverridableElement() } override fun doSearchDirect(request: HierarchySearchRequest<PsiMethod>, consumer: Processor<in PsiMethod>) { searchDirectOverriders(request.originalElement).forEach { method -> consumer.process(method) } } } object PsiMethodOverridingHierarchyTraverser : HierarchyTraverser<PsiMethod> { override fun nextElements(current: PsiMethod): Iterable<PsiMethod> = KotlinPsiMethodOverridersSearch.searchDirectOverriders(current) override fun shouldDescend(element: PsiMethod): Boolean = PsiUtil.canBeOverridden(element) } fun PsiElement.toPossiblyFakeLightMethods(): List<PsiMethod> { if (this is PsiMethod) return listOf(this) val element = unwrapped ?: return emptyList() val lightMethods = element.toLightMethods() if (lightMethods.isNotEmpty()) return lightMethods return if (element is KtNamedDeclaration) listOfNotNull(KtFakeLightMethod.get(element)) else emptyList() } fun KtNamedDeclaration.forEachOverridingElement( scope: SearchScope = runReadAction { useScope() }, searchDeeply: Boolean = true, processor: (superMember: PsiElement, overridingMember: PsiElement) -> Boolean ): Boolean { val ktClass = runReadAction { containingClassOrObject as? KtClass } ?: return true toLightMethods().forEach { baseMethod -> if (!OverridingMethodsSearch.search(baseMethod, scope.excludeKotlinSources(project), searchDeeply).all { processor(baseMethod, it) }) { return false } } return forEachKotlinOverride(ktClass, listOf(this), scope, searchDeeply) { baseElement, overrider -> processor(baseElement, overrider) } } fun KtNamedDeclaration.hasOverridingElement(): Boolean { var hasUsage = false forEachOverridingElement(searchDeeply = false) { _, _ -> hasUsage = true false } return hasUsage } fun PsiMethod.forEachImplementation( scope: SearchScope = runReadAction { useScope() }, processor: (PsiElement) -> Boolean ): Boolean = forEachOverridingMethod(scope, processor) && FunctionalExpressionSearch.search( this, scope.excludeKotlinSources(project) ).forEach(Processor { processor(it) }) @Deprecated( "This method is obsolete and will be removed", ReplaceWith( "OverridersSearchUtilsKt.forEachOverridingMethod", "org.jetbrains.kotlin.idea.search.declarationsSearch.OverridersSearchUtilsKt" ), DeprecationLevel.ERROR ) @JvmName("forEachOverridingMethod") fun PsiMethod.forEachOverridingMethodCompat( scope: SearchScope = runReadAction { useScope() }, processor: (PsiMethod) -> Boolean ): Boolean = forEachOverridingMethod(scope, processor) fun PsiClass.forEachDeclaredMemberOverride(processor: (superMember: PsiElement, overridingMember: PsiElement) -> Boolean) { val scope = runReadAction { useScope() } if (this !is KtFakeLightClass) { AllOverridingMethodsSearch.search(this, scope.excludeKotlinSources(project)).all { processor(it.first, it.second) } } val ktClass = unwrapped as? KtClass ?: return val members = ktClass.declarations.filterIsInstance<KtNamedDeclaration>() + ktClass.primaryConstructorParameters.filter { it.hasValOrVar() } forEachKotlinOverride(ktClass, members, scope, searchDeeply = true, processor) } fun findDeepestSuperMethodsKotlinAware(method: PsiElement) = findDeepestSuperMethodsNoWrapping(method).mapNotNull { it.getRepresentativeLightMethod() }
apache-2.0
e7e5835abe06f39a808203c6aee833b5
43.421965
143
0.744794
5.129506
false
false
false
false
dahlstrom-g/intellij-community
plugins/gradle/java/src/service/resolve/GradleExtensionsContributor.kt
2
6229
// 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.plugins.gradle.service.resolve import com.intellij.icons.AllIcons import com.intellij.lang.properties.IProperty import com.intellij.lang.properties.psi.PropertiesFile import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ProjectFileIndex import com.intellij.openapi.vfs.VfsUtil import com.intellij.psi.* import com.intellij.psi.scope.PsiScopeProcessor import com.intellij.psi.util.InheritanceUtil import com.intellij.psi.util.PsiUtilCore import com.intellij.util.castSafelyTo import org.jetbrains.plugins.gradle.service.resolve.GradleCommonClassNames.GRADLE_API_PROJECT import org.jetbrains.plugins.gradle.settings.GradleExtensionsSettings import org.jetbrains.plugins.gradle.settings.GradleExtensionsSettings.GradleExtensionsData import org.jetbrains.plugins.gradle.settings.GradleLocalSettings import org.jetbrains.plugins.gradle.util.PROPERTIES_FILE_NAME import org.jetbrains.plugins.gradle.util.getGradleUserHomePropertiesPath import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrLightField import org.jetbrains.plugins.groovy.lang.resolve.NonCodeMembersContributor import org.jetbrains.plugins.groovy.lang.resolve.getName import org.jetbrains.plugins.groovy.lang.resolve.processors.inference.type import org.jetbrains.plugins.groovy.lang.resolve.shouldProcessProperties import java.nio.file.Path class GradleExtensionsContributor : NonCodeMembersContributor() { override fun getClassNames(): Collection<String> { return listOf(GradleCommonClassNames.GRADLE_API_EXTRA_PROPERTIES_EXTENSION, GRADLE_API_PROJECT) } override fun processDynamicElements(qualifierType: PsiType, aClass: PsiClass?, processor: PsiScopeProcessor, place: PsiElement, state: ResolveState) { if (qualifierType !is GradleProjectAwareType && !InheritanceUtil.isInheritor(qualifierType, GradleCommonClassNames.GRADLE_API_EXTRA_PROPERTIES_EXTENSION)) return if (!processor.shouldProcessProperties()) return val file = place.containingFile val data = getExtensionsFor(file) ?: return val name = processor.getName(state) val resolvedProperties = processPropertiesFromFile(aClass, processor, place, state) val properties = if (name == null) data.findAllProperties() else listOf(data.findProperty(name) ?: return) for (property in properties) { if (property.name in resolvedProperties) { continue } if (!processor.execute(GradleGroovyProperty(property, file), state)) { return } } } private fun processPropertiesFromFile(aClass: PsiClass?, processor: PsiScopeProcessor, place: PsiElement, state: ResolveState) : Set<String> { if (aClass == null) { return emptySet() } val factory = JavaPsiFacade.getInstance(place.project) val stringType = factory.findClass(CommonClassNames.JAVA_LANG_STRING, place.resolveScope)?.type() ?: return emptySet() val properties = gradlePropertiesStream(place) val name = processor.getName(state) val processedNames = mutableSetOf<String>() for (propertyFile in properties) { if (name == null) { for (property in propertyFile.properties) { if (property.name.contains(".")) { continue } processedNames.add(property.name) val newProperty = createGroovyProperty(aClass, property, stringType) processor.execute(newProperty, state) } } else { val property = propertyFile.findPropertyByKey(name) ?: continue val newProperty = createGroovyProperty(aClass, property, stringType) processor.execute(newProperty, state) return setOf(newProperty.name) } } return processedNames } companion object { private fun gradlePropertiesStream(place: PsiElement): Sequence<PropertiesFile> = sequence { val externalRootProjectPath = place.getRootGradleProjectPath() ?: return@sequence val userHomePropertiesFile = getGradleUserHomePropertiesPath()?.parent?.toString()?.getGradlePropertiesFile(place.project) if (userHomePropertiesFile != null) { yield(userHomePropertiesFile) } val projectRootPropertiesFile = externalRootProjectPath.getGradlePropertiesFile(place.project) if (projectRootPropertiesFile != null) { yield(projectRootPropertiesFile) } val localSettings = GradleLocalSettings.getInstance(place.project) val installationDirectoryPropertiesFile = localSettings.getGradleHome(externalRootProjectPath)?.getGradlePropertiesFile(place.project) if (installationDirectoryPropertiesFile != null) { yield(installationDirectoryPropertiesFile) } } private fun String.getGradlePropertiesFile(project: Project): PropertiesFile? { val file = VfsUtil.findFile(Path.of(this), false)?.findChild(PROPERTIES_FILE_NAME) return file?.let { PsiUtilCore.getPsiFile(project, it) }.castSafelyTo<PropertiesFile>() } private fun createGroovyProperty(aClass: PsiClass, property: IProperty, stringType: PsiClassType): GrLightField { val newProperty = GrLightField(aClass, property.name, stringType, property.psiElement) newProperty.setIcon(AllIcons.FileTypes.Properties) newProperty.originInfo = propertiesFileOriginInfo return newProperty } fun getExtensionsFor(psiElement: PsiElement): GradleExtensionsData? { val project = psiElement.project val virtualFile = psiElement.containingFile?.originalFile?.virtualFile ?: return null val module = ProjectFileIndex.getInstance(project).getModuleForFile(virtualFile) return GradleExtensionsSettings.getInstance(project).getExtensionsFor(module) } internal const val propertiesFileOriginInfo : String = "by gradle.properties" } }
apache-2.0
24a96a2020b3db0cad275056453c6938
44.801471
165
0.720661
5.130972
false
false
false
false
dkandalov/katas
kotlin/src/katas/kotlin/leetcode/regex_matching/v4/RegexMatching.kt
1
2038
package katas.kotlin.leetcode.regex_matching.v4 import datsok.shouldEqual import org.junit.jupiter.api.Test class RegexMatching { @Test fun `some examples`() { "".matchRegex("") shouldEqual true "a".matchRegex("a") shouldEqual true "ab".matchRegex("ab") shouldEqual true "a".matchRegex("b") shouldEqual false "ab".matchRegex("a") shouldEqual false "a".matchRegex(".") shouldEqual true "ab".matchRegex("..") shouldEqual true "ab".matchRegex("a.") shouldEqual true "ab".matchRegex(".b") shouldEqual true "abc".matchRegex("..") shouldEqual false "abc".matchRegex("b..") shouldEqual false "".matchRegex("a?") shouldEqual true "a".matchRegex("a?") shouldEqual true "b".matchRegex("a?") shouldEqual false "".matchRegex("a*") shouldEqual true "a".matchRegex("a*") shouldEqual true "aaa".matchRegex("a*") shouldEqual true "b".matchRegex("a*") shouldEqual false "abc".matchRegex(".*") shouldEqual true } } typealias Matcher = (String) -> List<String> fun char(c: Char): Matcher = { input -> if (input.firstOrNull() == c) listOf(input.drop(1)) else emptyList() } fun anyChar(): Matcher = { input -> if (input.isNotEmpty()) listOf(input.drop(1)) else emptyList() } fun zeroOrOne(matcher: Matcher): Matcher = { input -> listOf(input) + matcher(input) } fun zeroOrMore(matcher: Matcher): Matcher = { input -> listOf(input) + matcher(input).flatMap(zeroOrMore(matcher)) } private fun String.matchRegex(regex: String): Boolean { val matchers = regex.fold(emptyList<Matcher>()) { acc, c -> when (c) { '.' -> acc + anyChar() '?' -> acc.dropLast(1) + zeroOrOne(acc.last()) '*' -> acc.dropLast(1) + zeroOrMore(acc.last()) else -> acc + char(c) } } return matchers .fold(listOf(this)) { inputs, matcher -> inputs.flatMap(matcher) } .any { it.isEmpty() } }
unlicense
8c98a910b0a6b0daf73ec1959551d5c4
30.353846
72
0.595682
4.133874
false
false
false
false
airbnb/epoxy
epoxy-processor/src/main/java/com/airbnb/epoxy/processor/ModelViewProcessor.kt
1
29901
package com.airbnb.epoxy.processor import androidx.room.compiler.processing.XElement import androidx.room.compiler.processing.XExecutableElement import androidx.room.compiler.processing.XMethodElement import androidx.room.compiler.processing.XProcessingEnv import androidx.room.compiler.processing.XRoundEnv import androidx.room.compiler.processing.XTypeElement import androidx.room.compiler.processing.XVariableElement import com.airbnb.epoxy.AfterPropsSet import com.airbnb.epoxy.CallbackProp import com.airbnb.epoxy.ModelProp import com.airbnb.epoxy.ModelView import com.airbnb.epoxy.OnViewRecycled import com.airbnb.epoxy.OnVisibilityChanged import com.airbnb.epoxy.OnVisibilityStateChanged import com.airbnb.epoxy.TextProp import com.airbnb.epoxy.processor.Utils.validateFieldAccessibleViaGeneratedCode import com.google.devtools.ksp.processing.SymbolProcessor import com.google.devtools.ksp.processing.SymbolProcessorEnvironment import com.google.devtools.ksp.processing.SymbolProcessorProvider import com.squareup.javapoet.TypeName import net.ltgt.gradle.incap.IncrementalAnnotationProcessor import net.ltgt.gradle.incap.IncrementalAnnotationProcessorType import java.util.HashMap import java.util.HashSet import java.util.concurrent.ConcurrentHashMap import javax.tools.Diagnostic import kotlin.contracts.contract import kotlin.reflect.KClass class ModelViewProcessorProvider : SymbolProcessorProvider { override fun create(environment: SymbolProcessorEnvironment): SymbolProcessor { return ModelViewProcessor(environment) } } @IncrementalAnnotationProcessor(IncrementalAnnotationProcessorType.AGGREGATING) class ModelViewProcessor @JvmOverloads constructor( kspEnvironment: SymbolProcessorEnvironment? = null ) : BaseProcessorWithPackageConfigs(kspEnvironment) { override val usesPackageEpoxyConfig: Boolean = false override val usesModelViewConfig: Boolean = true private val modelClassMap = ConcurrentHashMap<XTypeElement, ModelViewInfo>() private val styleableModelsToWrite = mutableListOf<ModelViewInfo>() override fun additionalSupportedAnnotations(): List<KClass<*>> = listOf( ModelView::class, TextProp::class, CallbackProp::class ) override fun processRound( environment: XProcessingEnv, round: XRoundEnv, memoizer: Memoizer, timer: Timer, roundNumber: Int ): List<XElement> { super.processRound(environment, round, memoizer, timer, roundNumber) timer.markStepCompleted("package config processing") // We have a very common case of needing to wait for Paris styleables to be generated before // we can fully process our models and generate code. To support this we need to tell KSP to // defer symbols. However, this also causes KSP to reprocess the same annotations and create // duplicates if we try to save the previous models, and with KSP it is also not valid to use // symbols across rounds and that can cause errors. // Java AP on the other hand will not reprocess annotated elements so we need to hold on to // them across rounds. // To support this case in an efficient way in KSP we check for any Paris dependencies and // bail ASAP in that case to avoid reprocessing as much as possible. // Paris only ever generates code in the first round, so it should be safe to rely on this. val shouldDeferElementsIfHasParisDependency = isKsp() && roundNumber == 1 val elementsToDefer = processViewAnnotations(round, memoizer, shouldDeferElementsIfHasParisDependency) timer.markStepCompleted("process View Annotations") if (elementsToDefer.isNotEmpty()) { return elementsToDefer } // Avoid doing the work to look up the rest of the annotations in model view classes // if no new model view classes were found. if (modelClassMap.isNotEmpty()) { val classTypes = modelClassMap.keys.toList() processSetterAnnotations(classTypes, memoizer) timer.markStepCompleted("process setter Annotations") processResetAnnotations(classTypes, memoizer) timer.markStepCompleted("process reset Annotations") processVisibilityStateChangedAnnotations(classTypes, memoizer) processVisibilityChangedAnnotations(classTypes, memoizer) timer.markStepCompleted("process visibility Annotations") processAfterBindAnnotations(classTypes, memoizer) timer.markStepCompleted("process after bind Annotations") updateViewsForInheritedViewAnnotations(memoizer) timer.markStepCompleted("update For Inherited Annotations") // Group overloads after inheriting methods from super classes so those can be included in // the groups as well. groupOverloads() timer.markStepCompleted("group overloads") // Up until here our code generation has assumed that that all attributes in a group are // view attributes (and not attributes inherited from a base model class), so this should be // done after grouping attributes, and these attributes should not be grouped. // No code to bind these attributes is generated, as it is assumed that the original model // handles its own bind (also we can't know how to bind these). updatesViewsForInheritedBaseModelAttributes(memoizer) timer.markStepCompleted("updates for inherited Attributes") addStyleAttributes() timer.markStepCompleted("add style attributes") } // This may write previously generated models that were waiting for their style builder // to be generated. writeJava(environment, memoizer, timer) generatedModels.addAll(modelClassMap.values) modelClassMap.clear() if (roundNumber > 2 && styleableModelsToWrite.isNotEmpty()) { messager.printMessage( Diagnostic.Kind.ERROR, "Unable to find Paris generated code for styleable Epoxy models. Is Paris configured correctly?" ) } return emptyList() } private fun processViewAnnotations( round: XRoundEnv, memoizer: Memoizer, shouldDeferElementsIfHasParisDependency: Boolean ): List<XElement> { val modelViewElements = round.getElementsAnnotatedWith(ModelView::class) if (shouldDeferElementsIfHasParisDependency && modelViewElements.any { it.hasStyleableAnnotation() }) { return modelViewElements.toList() } modelViewElements .forEach("processViewAnnotations") { viewElement -> if (!validateViewElement(viewElement, memoizer)) { return@forEach } modelClassMap[viewElement] = ModelViewInfo( viewElement, environment, logger, configManager, resourceProcessor, memoizer ) } return emptyList() } private fun validateViewElement(viewElement: XElement, memoizer: Memoizer): Boolean { contract { returns(true) implies (viewElement is XTypeElement) } if (viewElement !is XTypeElement) { logger.logError( "${ModelView::class.simpleName} annotations can only be on a class", viewElement ) return false } if (viewElement.isPrivate()) { logger.logError( "${ModelView::class.simpleName} annotations must not be on private classes.", viewElement ) return false } // Nested classes must be static if (viewElement.enclosingTypeElement != null) { logger.logError( "Classes with ${ModelView::class.java} annotations cannot be nested.", viewElement ) return false } if (!viewElement.type.isSubTypeOf(memoizer.androidViewType)) { logger.logError( "Classes with ${ModelView::class.java} annotations must extend " + "android.view.View.", viewElement ) return false } return true } private fun processSetterAnnotations(classTypes: List<XTypeElement>, memoizer: Memoizer) { for (propAnnotation in modelPropAnnotations) { classTypes.getElementsAnnotatedWith(propAnnotation).mapNotNull { prop -> val enclosingElement = prop.enclosingTypeElement ?: return@mapNotNull null // Interfaces can use model property annotations freely, they will be processed if // and when implementors of that interface are processed. This is particularly // useful for Kotlin delegation where the model view class may not be overriding // the interface properties directly, and so doesn't have an opportunity to annotate // them with Epoxy model property annotations. if (enclosingElement.isInterface()) { return@mapNotNull null } val info = getModelInfoForPropElement(prop) if (info == null) { logger.logError( "${propAnnotation.simpleName} annotation can only be used in classes " + "annotated with ${ModelView::class.java.simpleName} " + "(${enclosingElement.name}#$prop)", prop ) return@mapNotNull null } // JvmOverloads is used on properties with default arguments, which we support. // However, the generated no arg version of the function will also have the // @ModelProp annotation so we need to ignore it when it is processed. // However, the JvmOverloads annotation is removed in the java class so we need // to manually look for a valid overload function. if (prop is XMethodElement && prop.parameters.isEmpty() && info.viewElement.findOverload( prop, 1 )?.hasAnyAnnotation(*modelPropAnnotationsArray) == true ) { return@mapNotNull null } if (!validatePropElement(prop, propAnnotation.java, memoizer)) { return@mapNotNull null } info.buildProp(prop) to info }.forEach { (viewProp, modelInfo) -> // This is done synchronously after the parallel prop building so that we // have all props in the order they are listed in the view. // This keeps a consistent ordering despite the parallel execution, which is necessary // for consistent generated code as well as consistent prop binding order (which // people are not supposed to rely on, but inevitably do, and we want to avoid breaking // that by changing the ordering). modelInfo.addAttribute(viewProp) } } } private fun groupOverloads() { modelClassMap.values.forEach { viewInfo -> val attributeGroups = HashMap<String, MutableList<AttributeInfo>>() // Track which groups are created manually by the user via a group annotation param. // We use this to check that more than one setter is in the group, since otherwise it // doesn't make sense to have a group and there is likely a typo we can catch for them val customGroups = HashSet<String>() for (attributeInfo in viewInfo.attributeInfo) { val setterInfo = attributeInfo as ViewAttributeInfo var groupKey = setterInfo.groupKey!! if (groupKey.isEmpty()) { // Default to using the method name as the group name, so method overloads are // grouped together by default groupKey = setterInfo.viewAttributeName } else { customGroups.add(groupKey) } attributeGroups .getOrPut(groupKey) { mutableListOf() } .add(attributeInfo) } for (customGroup in customGroups) { attributeGroups[customGroup]?.let { if (it.size == 1) { val attribute = it[0] as ViewAttributeInfo logger.logError( "Only one setter was included in the custom group " + "'$customGroup' at ${viewInfo.viewElement.name}#" + "${attribute.viewAttributeName}. Groups should have at " + "least 2 setters." ) } } } for ((groupKey, groupAttributes) in attributeGroups) { viewInfo.addAttributeGroup(groupKey, groupAttributes) } } } private fun validatePropElement( prop: XElement, propAnnotation: Class<out Annotation>, memoizer: Memoizer ): Boolean { return when (prop) { is XExecutableElement -> validateExecutableElement( prop, propAnnotation, 1, memoizer = memoizer ) is XVariableElement -> validateVariableElement(prop, propAnnotation) else -> { logger.logError( prop, "%s annotations can only be on a method or a field(element: %s)", propAnnotation, prop ) return false } } } private fun validateVariableElement( field: XVariableElement, annotationClass: Class<*> ): Boolean { return validateFieldAccessibleViaGeneratedCode( field, annotationClass, logger ) } private fun validateExecutableElement( element: XElement, annotationClass: Class<*>, paramCount: Int, checkTypeParameters: List<TypeName>? = null, memoizer: Memoizer ): Boolean { contract { returns(true) implies (element is XMethodElement) } if (element !is XMethodElement) { logger.logError( element, "%s annotations can only be on a method (element: %s)", annotationClass::class.java.simpleName, element ) return false } val parameters = element.parameters if (parameters.size != paramCount) { logger.logError( element, "Methods annotated with %s must have exactly %s parameter (method: %s)", annotationClass::class.java.simpleName, paramCount, element.name ) return false } checkTypeParameters?.let { expectedTypeParameters -> // Check also the parameter types var hasErrors = false parameters.forEachIndexed { i, parameter -> val typeName = parameter.type.typeNameWithWorkaround(memoizer) val expectedType = expectedTypeParameters[i] hasErrors = hasErrors || (typeName != expectedType.box() && typeName != expectedType.unbox()) } if (hasErrors) { logger.logError( element, "Methods annotated with %s must have parameter types %s, " + "found: %s (method: %s)", annotationClass::class.java.simpleName, expectedTypeParameters, parameters.map { it.type }, element.name ) } } if (element.isStatic() || element.isPrivate()) { logger.logError( element, "Methods annotated with %s cannot be private or static (method: %s)", annotationClass::class.java.simpleName, element.name ) return false } return true } private fun processResetAnnotations(classTypes: List<XTypeElement>, memoizer: Memoizer) { classTypes.getElementsAnnotatedWith(OnViewRecycled::class).mapNotNull { recycleMethod -> if (!validateResetElement(recycleMethod, memoizer)) { return@mapNotNull null } val info = getModelInfoForPropElement(recycleMethod) if (info == null) { logger.logError( "%s annotation can only be used in classes annotated with %s", OnViewRecycled::class.java, ModelView::class.java ) return@mapNotNull null } recycleMethod.expectName to info }.forEach { (methodName, modelInfo) -> // Do this after, synchronously, to preserve function ordering in the view. // If there are multiple functions with this annotation this allows them // to be called in predictable order from top to bottom of the class, which // some users may depend on. modelInfo.addOnRecycleMethod(methodName) } } private fun processVisibilityStateChangedAnnotations( classTypes: List<XTypeElement>, memoizer: Memoizer ) { classTypes.getElementsAnnotatedWith(OnVisibilityStateChanged::class) .mapNotNull { visibilityMethod -> if (!validateVisibilityStateChangedElement(visibilityMethod, memoizer)) { return@mapNotNull null } val info = getModelInfoForPropElement(visibilityMethod) if (info == null) { logger.logError( "%s annotation can only be used in classes annotated with %s", OnVisibilityStateChanged::class.java, ModelView::class.java ) return@mapNotNull null } visibilityMethod.expectName to info }.forEach { (methodName, modelInfo) -> // Do this after, synchronously, to preserve function ordering in the view. // If there are multiple functions with this annotation this allows them // to be called in predictable order from top to bottom of the class, which // some users may depend on. modelInfo.addOnVisibilityStateChangedMethod(methodName) } } private fun processVisibilityChangedAnnotations( classTypes: List<XTypeElement>, memoizer: Memoizer ) { classTypes.getElementsAnnotatedWith(OnVisibilityChanged::class).mapNotNull { visibilityMethod -> if (!validateVisibilityChangedElement(visibilityMethod, memoizer)) { return@mapNotNull null } val info = getModelInfoForPropElement(visibilityMethod) if (info == null) { logger.logError( visibilityMethod, "%s annotation can only be used in classes annotated with %s", OnVisibilityChanged::class.java, ModelView::class.java ) return@mapNotNull null } visibilityMethod.expectName to info }.forEach { (methodName, modelInfo) -> // Do this after, synchronously, to preserve function ordering in the view. // If there are multiple functions with this annotation this allows them // to be called in predictable order from top to bottom of the class, which // some users may depend on. modelInfo.addOnVisibilityChangedMethod(methodName) } } private fun processAfterBindAnnotations(classTypes: List<XTypeElement>, memoizer: Memoizer) { classTypes.getElementsAnnotatedWith(AfterPropsSet::class).mapNotNull { afterPropsMethod -> if (!validateAfterPropsMethod(afterPropsMethod, memoizer)) { return@mapNotNull null } val info = getModelInfoForPropElement(afterPropsMethod) if (info == null) { logger.logError( afterPropsMethod, "%s annotation can only be used in classes annotated with %s", AfterPropsSet::class.java, ModelView::class.java ) return@mapNotNull null } afterPropsMethod.expectName to info }.forEach { (methodName, modelInfo) -> // Do this after, synchronously, to preserve function ordering in the view. // If there are multiple functions with this annotation this allows them // to be called in predictable order from top to bottom of the class, which // some users may depend on. modelInfo.addAfterPropsSetMethod(methodName) } } private fun validateAfterPropsMethod(method: XElement, memoizer: Memoizer): Boolean { contract { returns(true) implies (method is XMethodElement) } return validateExecutableElement(method, AfterPropsSet::class.java, 0, memoizer = memoizer) } /** Include props and reset methods from super class views. */ private fun updateViewsForInheritedViewAnnotations(memoizer: Memoizer) { modelClassMap.values.forEach { view -> // We walk up the super class tree and look for any elements with epoxy annotations. // This approach lets us capture views that we've already processed as well as views // in other libraries that we wouldn't have otherwise processed. view.viewElement.iterateSuperClasses { superViewElement -> val annotationsOnViewSuperClass = memoizer.getAnnotationsOnViewSuperClass( superViewElement, logger, resourceProcessor ) val isSamePackage by lazy { annotationsOnViewSuperClass.viewPackageName == view.viewElement.packageName } fun forEachElementWithAnnotation( annotations: List<KClass<out Annotation>>, function: (Memoizer.ViewElement) -> Unit ) { annotationsOnViewSuperClass.annotatedElements .filterKeys { annotation -> annotation in annotations } .values .flatten() .filter { viewElement -> isSamePackage || !viewElement.isPackagePrivate } .forEach { function(it) } } forEachElementWithAnnotation(modelPropAnnotations) { // todo Include view interfaces for the super class in this model // 1. we should only do that if all methods in the super class are accessible to this (ie not package private and in a different package) // 2. We also need to handle the case the that super view is abstract - right now interfaces are not generated for abstract views // 3. If an abstract view only implements part of the interface it would mess up the way we check which methods count in the interface // We don't want the attribute from the super class replacing an attribute in the // subclass if the subclass overrides it, since the subclass definition could include // different annotation parameter settings, or we could end up with duplicates // If an annotated prop method has a default value it will also have @JvmOverloads // so java source in KAPT sees both a zero param and and 1 param method. We just // ignore the empty param version. if (it.element is XMethodElement && it.element.parameters.size != 1) { return@forEachElementWithAnnotation } view.addAttributeIfNotExists(it.attributeInfo.value) } forEachElementWithAnnotation(listOf(OnViewRecycled::class)) { view.addOnRecycleMethod(it.simpleName) } forEachElementWithAnnotation(listOf(OnVisibilityStateChanged::class)) { view.addOnVisibilityStateChangedMethod(it.simpleName) } forEachElementWithAnnotation(listOf(OnVisibilityChanged::class)) { view.addOnVisibilityChangedMethod(it.simpleName) } forEachElementWithAnnotation(listOf(AfterPropsSet::class)) { view.addAfterPropsSetMethod(it.simpleName) } } } } /** * If a view defines a base model that its generated model should extend we need to check if that * base model has [com.airbnb.epoxy.EpoxyAttribute] fields and include those in our model if * so. */ private fun updatesViewsForInheritedBaseModelAttributes(memoizer: Memoizer) { modelClassMap.values.forEach { modelViewInfo -> // Skip generated model super classes since it will already contain all of the functions // necessary for included attributes, and duplicating them is a waste. if (modelViewInfo.isSuperClassAlsoGenerated) return@forEach memoizer.getInheritedEpoxyAttributes( modelViewInfo.superClassElement.type, modelViewInfo.generatedName.packageName(), logger ).let { modelViewInfo.addAttributes(it) } } } private fun addStyleAttributes() { modelClassMap .values .filter("addStyleAttributes") { it.viewElement.hasStyleableAnnotation() } .also { styleableModelsToWrite.addAll(it) } } private fun validateResetElement(resetMethod: XElement, memoizer: Memoizer): Boolean { contract { returns(true) implies (resetMethod is XMethodElement) } return validateExecutableElement( resetMethod, OnViewRecycled::class.java, 0, memoizer = memoizer ) } private fun validateVisibilityStateChangedElement( visibilityMethod: XElement, memoizer: Memoizer ): Boolean { contract { returns(true) implies (visibilityMethod is XMethodElement) } return validateExecutableElement( visibilityMethod, OnVisibilityStateChanged::class.java, 1, checkTypeParameters = listOf(TypeName.INT), memoizer = memoizer ) } private fun validateVisibilityChangedElement(visibilityMethod: XElement, memoizer: Memoizer): Boolean { contract { returns(true) implies (visibilityMethod is XMethodElement) } return validateExecutableElement( visibilityMethod, OnVisibilityChanged::class.java, 4, checkTypeParameters = listOf(TypeName.FLOAT, TypeName.FLOAT, TypeName.INT, TypeName.INT), memoizer = memoizer ) } private fun writeJava(processingEnv: XProcessingEnv, memoizer: Memoizer, timer: Timer) { val modelsToWrite = modelClassMap.values.toMutableList() modelsToWrite.removeAll(styleableModelsToWrite) val hasStyleableModels = styleableModelsToWrite.isNotEmpty() styleableModelsToWrite.filter { tryAddStyleBuilderAttribute(it, processingEnv, memoizer) }.let { modelsToWrite.addAll(it) styleableModelsToWrite.removeAll(it) } if (hasStyleableModels) { timer.markStepCompleted("update models with Paris Styleable builder") } val modelWriter = createModelWriter(memoizer) ModelViewWriter(modelWriter, this) .writeModels(modelsToWrite, originatingConfigElements()) if (styleableModelsToWrite.isEmpty()) { // Make sure all models have been processed and written before we generate interface information modelWriter.writeFilesForViewInterfaces() } timer.markStepCompleted("write generated files") } private fun getModelInfoForPropElement(element: XElement): ModelViewInfo? = element.enclosingTypeElement?.let { modelClassMap[it] } companion object { val modelPropAnnotations: List<KClass<out Annotation>> = listOf( ModelProp::class, TextProp::class, CallbackProp::class ) val modelPropAnnotationsArray: Array<KClass<out Annotation>> = modelPropAnnotations.toTypedArray() val modelPropAnnotationSimpleNames: Set<String> = modelPropAnnotations.mapNotNull { it.simpleName }.toSet() } }
apache-2.0
f198bda03e3a74087c1f3fff33dc078d
40.586926
157
0.603191
5.962313
false
false
false
false
paplorinc/intellij-community
platform/configuration-store-impl/testSrc/CodeStyleTest.kt
1
5677
// 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.configurationStore import com.intellij.openapi.util.JDOMUtil import com.intellij.psi.codeStyle.CodeStyleSettings import com.intellij.psi.codeStyle.CodeStyleSettingsProvider import com.intellij.psi.codeStyle.CustomCodeStyleSettings import com.intellij.testFramework.DisposableRule import com.intellij.testFramework.PlatformTestUtil import com.intellij.testFramework.ProjectRule import com.intellij.testFramework.assertions.Assertions.assertThat import com.intellij.util.containers.ContainerUtil import org.jdom.Element import org.junit.ClassRule import org.junit.Rule import org.junit.Test internal class CodeStyleTest { companion object { @JvmField @ClassRule val projectRule = ProjectRule() } @JvmField @Rule val disposableRule = DisposableRule() @Test fun `do not remove unknown`() { val settings = CodeStyleSettings() val loaded = """ <code_scheme name="testSchemeName" version="${CodeStyleSettings.CURR_VERSION}"> <UnknownDoNotRemoveMe> <option name="ALIGN_OBJECT_PROPERTIES" value="2" /> </UnknownDoNotRemoveMe> <codeStyleSettings language="CoffeeScript"> <option name="KEEP_SIMPLE_METHODS_IN_ONE_LINE" value="true" /> </codeStyleSettings> <codeStyleSettings language="Gherkin"> <indentOptions> <option name="USE_TAB_CHARACTER" value="true" /> </indentOptions> </codeStyleSettings> <codeStyleSettings language="SQL"> <option name="KEEP_LINE_BREAKS" value="false" /> <option name="KEEP_BLANK_LINES_IN_CODE" value="10" /> </codeStyleSettings> </code_scheme>""".trimIndent() settings.readExternal(JDOMUtil.load(loaded)) val serialized = Element("code_scheme").setAttribute("name", "testSchemeName") settings.writeExternal(serialized) assertThat(serialized).isEqualTo(loaded) } @Test fun `do not duplicate known extra sections`() { val newProvider: CodeStyleSettingsProvider = object : CodeStyleSettingsProvider() { override fun createCustomSettings(settings: CodeStyleSettings?): CustomCodeStyleSettings { return object : CustomCodeStyleSettings("NewComponent", settings) { override fun getKnownTagNames(): List<String> { return ContainerUtil.concat(super.getKnownTagNames(), listOf("NewComponent-extra")) } override fun writeExternal(parentElement: Element?, parentSettings: CustomCodeStyleSettings) { super.writeExternal(parentElement, parentSettings) writeMain(parentElement) writeExtra(parentElement) } private fun writeMain(parentElement: Element?) { var extra = parentElement!!.getChild(tagName) if (extra == null) { extra = Element(tagName) parentElement.addContent(extra) } val option = Element("option") option.setAttribute("name", "MAIN") option.setAttribute("value", "3") extra.addContent(option) } private fun writeExtra(parentElement: Element?) { val extra = Element("NewComponent-extra") val option = Element("option") option.setAttribute("name", "EXTRA") option.setAttribute("value", "3") extra.addContent(option) parentElement!!.addContent(extra) } } } } PlatformTestUtil.maskExtensions(CodeStyleSettingsProvider.EXTENSION_POINT_NAME, listOf(newProvider), disposableRule.disposable) val settings = CodeStyleSettings() fun text(param: String): String { return """ <code_scheme name="testSchemeName" version="${CodeStyleSettings.CURR_VERSION}"> <NewComponent> <option name="MAIN" value="${param}" /> </NewComponent> <NewComponent-extra> <option name="EXTRA" value="${param}" /> </NewComponent-extra> <codeStyleSettings language="CoffeeScript"> <option name="KEEP_SIMPLE_METHODS_IN_ONE_LINE" value="true" /> </codeStyleSettings> <codeStyleSettings language="Gherkin"> <indentOptions> <option name="USE_TAB_CHARACTER" value="true" /> </indentOptions> </codeStyleSettings> <codeStyleSettings language="SQL"> <option name="KEEP_LINE_BREAKS" value="false" /> <option name="KEEP_BLANK_LINES_IN_CODE" value="10" /> </codeStyleSettings> </code_scheme>""".trimIndent() } settings.readExternal(JDOMUtil.load(text("2"))) val serialized = Element("code_scheme").setAttribute("name", "testSchemeName") settings.writeExternal(serialized) assertThat(serialized).isEqualTo(text("3")) } @Test fun `reset deprecations`() { val settings = CodeStyleSettings() val initial = """ <code_scheme name="testSchemeName" version="${CodeStyleSettings.CURR_VERSION}"> <option name="RIGHT_MARGIN" value="64" /> <option name="USE_FQ_CLASS_NAMES_IN_JAVADOC" value="false" /> </code_scheme>""".trimIndent() val expected = """ <code_scheme name="testSchemeName" version="${CodeStyleSettings.CURR_VERSION}"> <option name="RIGHT_MARGIN" value="64" /> </code_scheme>""".trimIndent() settings.readExternal(JDOMUtil.load(initial)) settings.resetDeprecatedFields() val serialized = Element("code_scheme").setAttribute("name", "testSchemeName") settings.writeExternal(serialized) assertThat(serialized).isEqualTo(expected) } }
apache-2.0
7b4d1aead52d527b96554f5ff57e9123
37.62585
140
0.670248
4.923677
false
true
false
false
DemonWav/MinecraftDevIntelliJ
src/main/kotlin/com/demonwav/mcdev/platform/mixin/folding/MixinFoldingSettings.kt
1
992
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2020 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mixin.folding import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage @State(name = "MixinFoldingSettings", storages = [Storage("minecraft_dev.xml")]) class MixinFoldingSettings : PersistentStateComponent<MixinFoldingSettings.State> { data class State( var foldTargetDescriptors: Boolean = true, var foldObjectCasts: Boolean = false ) private var state = State() override fun getState(): State = this.state override fun loadState(state: State) { this.state = state } companion object { val instance: MixinFoldingSettings get() = ServiceManager.getService(MixinFoldingSettings::class.java) } }
mit
3975cd504d50713b6a2f0a3c2298e650
25.105263
83
0.724798
4.550459
false
false
false
false
ssseasonnn/RxDownload
rxdownload4-recorder/src/main/java/zlc/season/rxdownload4/recorder/StatusConverter.kt
1
1287
package zlc.season.rxdownload4.recorder import androidx.room.TypeConverter import zlc.season.rxdownload4.manager.* class StatusConverter { companion object { const val NORMAL = 0 //never save const val STARTED = 1 const val DOWNLOADING = 2 const val PAUSED = 3 const val COMPLETED = 4 const val FAILED = 5 const val DELETED = 6 //never save const val PENDING = 7 //never save } @TypeConverter fun intToStatus(status: Int): Status { return when (status) { NORMAL -> Normal() PENDING -> Pending() STARTED -> Started() DOWNLOADING -> Downloading() PAUSED -> Paused() COMPLETED -> Completed() FAILED -> Failed() DELETED -> Deleted() else -> throw IllegalStateException("UNKNOWN STATE") } } @TypeConverter fun statusToInt(status: Status): Int { return when (status) { is Normal -> NORMAL is Pending -> PENDING is Started -> STARTED is Downloading -> DOWNLOADING is Paused -> PAUSED is Completed -> COMPLETED is Failed -> FAILED is Deleted -> DELETED } } }
apache-2.0
6f727bfdd2981f62d20bbe6cc8350fad
27
64
0.545455
5.384937
false
false
false
false
paplorinc/intellij-community
java/java-impl/src/com/intellij/lang/java/request/CreateExecutableFromJavaUsageRequest.kt
6
2702
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.lang.java.request import com.intellij.codeInsight.daemon.impl.quickfix.CreateMethodFromUsageFix.getTargetSubstitutor import com.intellij.lang.jvm.JvmModifier import com.intellij.lang.jvm.actions.* import com.intellij.openapi.components.service import com.intellij.psi.* import com.intellij.psi.PsiType.getJavaLangObject import com.intellij.psi.codeStyle.JavaCodeStyleManager import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.util.createSmartPointer import com.intellij.psi.util.parentOfType import com.intellij.refactoring.util.RefactoringUtil internal abstract class CreateExecutableFromJavaUsageRequest<out T : PsiCall>( call: T, private val modifiers: Collection<JvmModifier> ) : CreateExecutableRequest { private val psiManager = call.manager private val project = psiManager.project private val callPointer: SmartPsiElementPointer<T> = call.createSmartPointer(project) protected val call: T get() = callPointer.element ?: error("dead pointer") override fun isValid() = callPointer.element != null override fun getAnnotations() = emptyList<AnnotationRequest>() override fun getModifiers() = modifiers override fun getTargetSubstitutor() = PsiJvmSubstitutor(project, getTargetSubstitutor(call)) override fun getExpectedParameters(): List<ExpectedParameter> { val argumentList = call.argumentList ?: return emptyList() val scope = call.resolveScope val codeStyleManager: JavaCodeStyleManager = project.service() return argumentList.expressions.map { expression -> val type = getArgType(expression, scope) val names = codeStyleManager.suggestSemanticNames(expression) val expectedTypes = if (type == null) emptyList() else expectedTypes(type, ExpectedType.Kind.SUPERTYPE) expectedParameter(expectedTypes, names) } } override fun getParameters() = getParameters(expectedParameters, project) private fun getArgType(expression: PsiExpression, scope: GlobalSearchScope): PsiType? { val argType: PsiType? = RefactoringUtil.getTypeByExpression(expression) if (argType == null || PsiType.NULL == argType || LambdaUtil.notInferredType(argType)) { return getJavaLangObject(psiManager, scope) } else if (argType is PsiDisjunctionType) { return argType.leastUpperBound } else if (argType is PsiWildcardType) { return if (argType.isBounded) argType.bound else getJavaLangObject(psiManager, scope) } return argType } val context get() = call.parentOfType(PsiMethod::class, PsiClass::class) }
apache-2.0
5c6c91c36d1c18646c492a3475f47c8e
41.888889
140
0.776092
4.868468
false
false
false
false
google/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertTrimIndentToTrimMarginIntention.kt
1
2942
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.intentions import com.intellij.openapi.editor.Editor import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.KtCallExpression import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.KtStringTemplateExpression import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelector import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe class ConvertTrimIndentToTrimMarginIntention : SelfTargetingIntention<KtCallExpression>( KtCallExpression::class.java, KotlinBundle.lazyMessage("convert.to.trim.margin") ) { override fun isApplicableTo(element: KtCallExpression, caretOffset: Int): Boolean { val template = (element.getQualifiedExpressionForSelector()?.receiverExpression as? KtStringTemplateExpression) ?: return false if (!template.text.startsWith("\"\"\"")) return false val callee = element.calleeExpression ?: return false if (callee.text != "trimIndent" || callee.getCallableDescriptor()?.fqNameSafe != FqName("kotlin.text.trimIndent")) return false return template.isSurroundedByLineBreaksOrBlanks() } override fun applyTo(element: KtCallExpression, editor: Editor?) { val qualifiedExpression = element.getQualifiedExpressionForSelector() val template = (qualifiedExpression?.receiverExpression as? KtStringTemplateExpression) ?: return val indent = template.calculateIndent() val newTemplate = buildString { template.entries.forEach { entry -> val text = entry.text if (text.isLineBreakOrBlank()) { append(text) } else { append(indent) append("|") append(text.drop(indent.length)) } } } qualifiedExpression.replace(KtPsiFactory(element).createExpression("\"\"\"$newTemplate\"\"\".trimMargin()")) } companion object { fun KtStringTemplateExpression.isSurroundedByLineBreaksOrBlanks(): Boolean { val entries = entries return listOfNotNull(entries.firstOrNull(), entries.lastOrNull()).all { it.text.isLineBreakOrBlank() } } fun String.isLineBreakOrBlank(): Boolean = this == "\n" || this.isBlank() fun KtStringTemplateExpression.calculateIndent(): String = entries.asSequence().mapNotNull { stringTemplateEntry -> val text = stringTemplateEntry.text if (text.isLineBreakOrBlank()) null else text.takeWhile { it.isWhitespace() } }.minByOrNull { it.length } ?: "" } }
apache-2.0
dd754689f782a0a8735d7b5bae89faca
47.229508
135
0.691366
5.458256
false
false
false
false
jeantuffier/reminder
app/src/main/java/fr/jeantuffier/reminder/free/create/presentation/CreateTaskPresenter.kt
1
2531
package fr.jeantuffier.reminder.free.create.presentation import android.app.AlarmManager import android.app.PendingIntent import android.content.Context import fr.jeantuffier.reminder.free.common.dao.TaskDao import fr.jeantuffier.reminder.free.common.extension.getIntent import fr.jeantuffier.reminder.free.common.extension.withExtras import fr.jeantuffier.reminder.free.common.model.Priority import fr.jeantuffier.reminder.free.common.model.Task import fr.jeantuffier.reminder.free.common.service.DisplayNotificationService import io.reactivex.Single import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import java.util.* class CreateTaskPresenter( private val context: Context, private val view: CreateTaskContract.View, private val taskDao: TaskDao ) : CreateTaskContract.Presenter { override fun createTask(title: String, delay: Int, frequency: String, priorityForm: Int, time: Array<String>) { taskDao.getAll() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { tasks -> val priority = getPriority(priorityForm).getLevel() val createdAt = Calendar.getInstance().timeInMillis.toString() val task = Task(getNextTaskId(tasks), title, priority, delay, frequency, time[0], time[1], createdAt) saveTask(task) } } private fun getPriority(priorityForm: Int?): Priority { return when (priorityForm) { 0 -> Priority.LOW 1 -> Priority.MIDDLE else -> Priority.HIGH } } private fun getNextTaskId(tasks: List<Task>) = (tasks.map { it.id }.max() ?: 0) + 1 private fun saveTask(task: Task) { Single.fromCallable { taskDao.insert(task) } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { id -> view.notifyNewItem() registerAlarm(task) } } private fun registerAlarm(task: Task) { val triggerAt = System.currentTimeMillis() + task.getDelayInMs() val intent = DisplayNotificationService.getIntent(context, task) val pendingIntent = PendingIntent.getService(context, task.id, intent, 0) val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager alarmManager.setInexactRepeating(AlarmManager.RTC, triggerAt, task.getDelayInMs(), pendingIntent) } }
mit
a102315f56613b0a7d998720d489c578
38.546875
117
0.690241
4.652574
false
false
false
false
google/intellij-community
jvm/jvm-analysis-impl/src/com/intellij/codeInspection/AssertBetweenInconvertibleTypesInspection.kt
5
7202
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.codeInspection import com.intellij.analysis.JvmAnalysisBundle import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.CommonClassNames import com.intellij.psi.PsiElementVisitor import com.intellij.psi.PsiType import com.intellij.uast.UastHintedVisitorAdapter import com.siyeh.ig.callMatcher.CallMatcher import com.siyeh.ig.psiutils.InconvertibleTypesChecker import com.siyeh.ig.psiutils.InconvertibleTypesChecker.Convertible import com.siyeh.ig.psiutils.InconvertibleTypesChecker.LookForMutualSubclass import com.siyeh.ig.psiutils.TypeUtils import com.siyeh.ig.testFrameworks.UAssertHint import com.siyeh.ig.testFrameworks.UAssertHint.Companion.createAssertEqualsUHint import com.siyeh.ig.testFrameworks.UAssertHint.Companion.createAssertNotEqualsUHint import com.siyeh.ig.testFrameworks.UAssertHint.Companion.createAssertNotSameUHint import com.siyeh.ig.testFrameworks.UAssertHint.Companion.createAssertSameUHint import org.jetbrains.annotations.Nls import org.jetbrains.annotations.NonNls import org.jetbrains.annotations.NotNull import org.jetbrains.uast.* import org.jetbrains.uast.visitor.AbstractUastNonRecursiveVisitor class AssertBetweenInconvertibleTypesInspection : AbstractBaseUastLocalInspectionTool() { private val ASSERTJ_IS_EQUAL: CallMatcher = CallMatcher.instanceCall( "org.assertj.core.api.Assert", "isEqualTo", "isSameAs", "isNotEqualTo", "isNotSameAs") .parameterTypes(CommonClassNames.JAVA_LANG_OBJECT) private val ASSERTJ_DESCRIBED: CallMatcher = CallMatcher.instanceCall( "org.assertj.core.api.Descriptable", "describedAs", "as") private val ASSERTJ_ASSERT_THAT: CallMatcher = CallMatcher.staticCall( "org.assertj.core.api.Assertions", "assertThat").parameterCount(1) override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor = UastHintedVisitorAdapter.create( holder.file.language, AssertEqualsBetweenInconvertibleTypesVisitor(holder), arrayOf(UCallExpression::class.java), true) override fun getID(): String = "AssertBetweenInconvertibleTypes" inner class AssertEqualsBetweenInconvertibleTypesVisitor(private val holder: ProblemsHolder) : AbstractUastNonRecursiveVisitor() { override fun visitCallExpression(node: UCallExpression): Boolean { processAssertHint(createAssertEqualsUHint(node), node, holder) processAssertHint(createAssertNotEqualsUHint(node), node, holder) processAssertHint(createAssertSameUHint(node), node, holder) processAssertHint(createAssertNotSameUHint(node), node, holder) processAssertJ(node) return true } private fun processAssertHint(assertHint: UAssertHint?, expression: UCallExpression, holder : ProblemsHolder ) { if (assertHint == null) return val firstArgument = assertHint.firstArgument val secondArgument = assertHint.secondArgument val firstParameter = expression.getParameterForArgument(firstArgument) if (firstParameter == null || !TypeUtils.isJavaLangObject(firstParameter.type)) return val secondParameter = expression.getParameterForArgument(secondArgument) if (secondParameter == null || !TypeUtils.isJavaLangObject(secondParameter.type)) return checkConvertibleTypes(expression, firstArgument, secondArgument, holder) } private fun checkConvertibleTypes(expression: UCallExpression, firstArgument: UExpression, secondArgument: UExpression, holder : ProblemsHolder) { if (firstArgument.isNullLiteral() || secondArgument.isNullLiteral()) return val type1 = firstArgument.getExpressionType() ?: return val type2 = secondArgument.getExpressionType() ?: return val mismatch = InconvertibleTypesChecker.checkTypes(type1, type2, LookForMutualSubclass.IF_CHEAP) if (mismatch != null) { val name = expression.methodIdentifier?.sourcePsi ?: return val convertible = mismatch.isConvertible if (convertible == Convertible.CONVERTIBLE_MUTUAL_SUBCLASS_UNKNOWN) { holder.registerPossibleProblem(name) } else { val methodName = expression.methodName ?: return val highlightType = if (isAssertNotEqualsMethod(methodName)) ProblemHighlightType.WEAK_WARNING else ProblemHighlightType.GENERIC_ERROR_OR_WARNING val errorString = buildErrorString(methodName, mismatch.left, mismatch.right) holder.registerProblem(name, errorString, highlightType) } } } private fun getQualifier(call: UCallExpression) : UCallExpression? { val receiver = call.getParentOfType<UQualifiedReferenceExpression>()?.receiver if (receiver is UCallExpression) return receiver if (receiver is UQualifiedReferenceExpression) { val selector = receiver.selector if (selector is UCallExpression) return selector } return null } private fun processAssertJ(call: UCallExpression) { if (!ASSERTJ_IS_EQUAL.uCallMatches(call)) return var qualifier = getQualifier(call) if (qualifier == null) return val chain = qualifier.getOutermostQualified().getQualifiedChain() val lastDescribed = chain.lastOrNull { expr -> expr is UCallExpression && ASSERTJ_DESCRIBED.uCallMatches(expr) } if (lastDescribed != null) { qualifier = getQualifier(lastDescribed as UCallExpression) } if (qualifier == null || !ASSERTJ_ASSERT_THAT.uCallMatches(qualifier)) return val callValueArguments = call.valueArguments val qualValueArguments = qualifier.valueArguments if (callValueArguments.isEmpty() || qualValueArguments.isEmpty()) return checkConvertibleTypes(call, callValueArguments[0], qualValueArguments[0], holder) } } @Nls fun buildErrorString(methodName: @NotNull String, left: @NotNull PsiType, right: @NotNull PsiType): String { val comparedTypeText = left.presentableText val comparisonTypeText = right.presentableText if (isAssertNotEqualsMethod(methodName)) { return JvmAnalysisBundle.message("jvm.inspections.assertnotequals.between.inconvertible.types.problem.descriptor", comparedTypeText, comparisonTypeText) } return if (isAssertNotSameMethod(methodName)) { JvmAnalysisBundle.message("jvm.inspections.assertnotsame.between.inconvertible.types.problem.descriptor", comparedTypeText, comparisonTypeText) } else JvmAnalysisBundle.message("jvm.inspections.assertequals.between.inconvertible.types.problem.descriptor", StringUtil.escapeXmlEntities(comparedTypeText), StringUtil.escapeXmlEntities(comparisonTypeText)) } private fun isAssertNotEqualsMethod(methodName: @NonNls String): Boolean { return "assertNotEquals".equals(methodName) || "isNotEqualTo".equals(methodName) } private fun isAssertNotSameMethod(methodName: @NonNls String): Boolean { return "assertNotSame".equals(methodName) || "isNotSameAs".equals(methodName) } }
apache-2.0
603fc9b12d37fafa9679b6dd437b0af6
51.955882
149
0.756734
5.096957
false
false
false
false
google/intellij-community
plugins/github/src/org/jetbrains/plugins/github/pullrequest/GHPRStatisticsCollector.kt
1
4111
// 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.jetbrains.plugins.github.pullrequest import com.intellij.collaboration.async.disposingScope import com.intellij.collaboration.auth.createAccountsFlow import com.intellij.internal.statistic.eventLog.EventLogGroup import com.intellij.internal.statistic.eventLog.FeatureUsageData import com.intellij.internal.statistic.eventLog.events.EventFields import com.intellij.internal.statistic.eventLog.events.PrimitiveEventField import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector import com.intellij.openapi.Disposable import com.intellij.openapi.components.Service import com.intellij.openapi.components.service import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.project.Project import com.intellij.openapi.startup.StartupActivity import kotlinx.coroutines.future.await import kotlinx.coroutines.launch import org.jetbrains.plugins.github.api.GithubServerPath import org.jetbrains.plugins.github.api.data.GHEnterpriseServerMeta import org.jetbrains.plugins.github.api.data.GithubPullRequestMergeMethod import org.jetbrains.plugins.github.authentication.accounts.GHAccountManager import org.jetbrains.plugins.github.util.GHEnterpriseServerMetadataLoader object GHPRStatisticsCollector { private val COUNTERS_GROUP = EventLogGroup("vcs.github.pullrequest.counters", 2) class Counters : CounterUsagesCollector() { override fun getGroup() = COUNTERS_GROUP } private val TIMELINE_OPENED_EVENT = COUNTERS_GROUP.registerEvent("timeline.opened", EventFields.Int("count")) private val DIFF_OPENED_EVENT = COUNTERS_GROUP.registerEvent("diff.opened", EventFields.Int("count")) private val MERGED_EVENT = COUNTERS_GROUP.registerEvent("merged", EventFields.Enum<GithubPullRequestMergeMethod>("method") { it.name.toUpperCase() }) private val anonymizedId = object : PrimitiveEventField<String>() { override val name = "anonymized_id" override fun addData(fuData: FeatureUsageData, value: String) { fuData.addAnonymizedId(value) } override val validationRule: List<String> get() = listOf("{regexp#hash}") } private val SERVER_META_EVENT = COUNTERS_GROUP.registerEvent("server.meta.collected", anonymizedId, EventFields.Version) fun logTimelineOpened(project: Project) { val count = FileEditorManager.getInstance(project).openFiles.count { it is GHPRTimelineVirtualFile } TIMELINE_OPENED_EVENT.log(project, count) } fun logDiffOpened(project: Project) { val count = FileEditorManager.getInstance(project).openFiles.count { it is GHPRDiffVirtualFileBase || it is GHPRCombinedDiffPreviewVirtualFileBase } DIFF_OPENED_EVENT.log(project, count) } fun logMergedEvent(method: GithubPullRequestMergeMethod) { MERGED_EVENT.log(method) } fun logEnterpriseServerMeta(project: Project, server: GithubServerPath, meta: GHEnterpriseServerMeta) { SERVER_META_EVENT.log(project, server.toUrl(), meta.installedVersion) } } @Service private class GHServerVersionsCollector(private val project: Project) : Disposable { private val scope = disposingScope() init { val accountsFlow = project.service<GHAccountManager>().createAccountsFlow(this) scope.launch { accountsFlow.collect { for (account in it) { val server = account.server if (server.isGithubDotCom) continue try { val metadata = service<GHEnterpriseServerMetadataLoader>().loadMetadata(server).await() GHPRStatisticsCollector.logEnterpriseServerMeta(project, server, metadata) } catch (ignore: Exception) { } } } } } class Initializer : StartupActivity.Background { override fun runActivity(project: Project) { //init service to start version checks project.service<GHServerVersionsCollector>() } } override fun dispose() = Unit }
apache-2.0
68628fdefc3e85164479ab0abc721bcc
38.912621
140
0.75675
4.619101
false
false
false
false
RuneSuite/client
plugins/src/main/java/org/runestar/client/plugins/smoothanimations/Actor.kt
1
2233
package org.runestar.client.plugins.smoothanimations import org.runestar.client.raw.CLIENT import org.runestar.client.raw.access.XActor import org.runestar.client.raw.access.XModel import org.runestar.client.raw.access.XSeqType import org.runestar.client.raw.base.MethodEvent internal fun actorGetModelEnter(event: MethodEvent<out XActor, XModel>) { val actor = event.instance actor.movementFrame = packFrame(actor.movementFrame, actor.movementFrameCycle) actor.sequenceFrame = packFrame(actor.sequenceFrame, actor.sequenceFrameCycle) actor.spotAnimationFrame = packFrame(actor.spotAnimationFrame, actor.spotAnimationFrameCycle) } internal fun actorGetModelExit(event: MethodEvent<out XActor, XModel>) { val actor = event.instance actor.movementFrame = unpackFrame(actor.movementFrame) actor.sequenceFrame = unpackFrame(actor.sequenceFrame) actor.spotAnimationFrame = unpackFrame(actor.spotAnimationFrame) } internal fun animateSequenceEnter(event: MethodEvent<XSeqType, XModel>) { val frameArg = event.arguments[1] as Int val frame = frameArg and 0xFFFF event.arguments[1] = frame val seq = event.instance val nextFrame = frame + 1 val frameCycle = (frameArg xor Int.MIN_VALUE) shr 16 if (frameArg >= -1 || nextFrame > seq.frameIds.lastIndex || frameCycle == 0) return val frameId = seq.frameIds[frame] val frames = CLIENT.getAnimFrameset(frameId shr 16) ?: return val nextFrameId = seq.frameIds[nextFrame] val nextFrames = CLIENT.getAnimFrameset(nextFrameId shr 16) ?: return event.skipBody = true val model = event.arguments[0] as XModel val frameIdx = frameId and 0xFFFF val nextFrameIdx = nextFrameId and 0xFFFF val animatedModel = model.toSharedSequenceModel(!frames.hasAlphaTransform(frameIdx) && !nextFrames.hasAlphaTransform(nextFrameIdx)) animatedModel.animateInterpolated(frames.frames[frameIdx], nextFrames.frames[nextFrameIdx], frameCycle, seq.frameLengths[frame] + 1) event.returned = animatedModel } internal fun animateSequence2Enter(event: MethodEvent<XSeqType, XModel>) { event.arguments[1] = (event.arguments[1] as Int) and 0xFFFF event.arguments[3] = (event.arguments[3] as Int) and 0xFFFF }
mit
3478cec088d9fe3d4759a79faeb2e921
41.961538
136
0.766234
3.924429
false
false
false
false
square/okhttp
okhttp/src/nonJvmMain/kotlin/okhttp3/CacheControl.kt
3
2953
/* * Copyright (C) 2019 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package okhttp3 import kotlin.time.DurationUnit import okhttp3.internal.commonBuild import okhttp3.internal.commonForceCache import okhttp3.internal.commonForceNetwork import okhttp3.internal.commonImmutable import okhttp3.internal.commonMaxAge import okhttp3.internal.commonMaxStale import okhttp3.internal.commonMinFresh import okhttp3.internal.commonNoCache import okhttp3.internal.commonNoStore import okhttp3.internal.commonNoTransform import okhttp3.internal.commonOnlyIfCached import okhttp3.internal.commonParse import okhttp3.internal.commonToString actual class CacheControl internal actual constructor( actual val noCache: Boolean, actual val noStore: Boolean, actual val maxAgeSeconds: Int, actual val sMaxAgeSeconds: Int, actual val isPrivate: Boolean, actual val isPublic: Boolean, actual val mustRevalidate: Boolean, actual val maxStaleSeconds: Int, actual val minFreshSeconds: Int, actual val onlyIfCached: Boolean, actual val noTransform: Boolean, actual val immutable: Boolean, internal actual var headerValue: String? ) { actual override fun toString(): String = commonToString() actual class Builder { internal actual var noCache: Boolean = false internal actual var noStore: Boolean = false internal actual var maxAgeSeconds = -1 internal actual var maxStaleSeconds = -1 internal actual var minFreshSeconds = -1 internal actual var onlyIfCached: Boolean = false internal actual var noTransform: Boolean = false internal actual var immutable: Boolean = false actual fun noCache() = commonNoCache() actual fun noStore() = commonNoStore() actual fun onlyIfCached() = commonOnlyIfCached() actual fun noTransform() = commonNoTransform() actual fun immutable() = commonImmutable() actual fun maxAge(maxAge: Int, timeUnit: DurationUnit) = commonMaxAge(maxAge, timeUnit) actual fun maxStale(maxStale: Int, timeUnit: DurationUnit) = commonMaxStale(maxStale, timeUnit) actual fun minFresh(minFresh: Int, timeUnit: DurationUnit) = commonMinFresh(minFresh, timeUnit) actual fun build(): CacheControl = commonBuild() } actual companion object { actual val FORCE_NETWORK = commonForceNetwork() actual val FORCE_CACHE = commonForceCache() actual fun parse(headers: Headers): CacheControl = commonParse(headers) } }
apache-2.0
01b6e01f49831e07d71276dc874111a5
33.337209
99
0.767355
4.599688
false
false
false
false
youdonghai/intellij-community
platform/diff-impl/tests/com/intellij/diff/tools/fragmented/UnifiedFragmentBuilderTest.kt
1
2351
/* * 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.diff.tools.fragmented import com.intellij.diff.DiffTestCase import com.intellij.diff.comparison.ComparisonPolicy import com.intellij.diff.util.LineRange import com.intellij.diff.util.Side import com.intellij.openapi.editor.impl.DocumentImpl import com.intellij.openapi.progress.DumbProgressIndicator class UnifiedFragmentBuilderTest : DiffTestCase() { fun testEquals() { val document1 = DocumentImpl("A\nB\nC") val document2 = DocumentImpl("A\nB\nC") val fragments = MANAGER.compareLinesInner(document1.charsSequence, document2.charsSequence, ComparisonPolicy.DEFAULT, DumbProgressIndicator.INSTANCE) val builder = UnifiedFragmentBuilder(fragments, document1, document2, Side.LEFT) builder.exec() assertTrue(builder.isEqual) assertEquals(builder.text.toString(), "A\nB\nC\n") assertEmpty(builder.changedLines) assertEmpty(builder.blocks) } fun testWrongEndLineTypoBug() { val document1 = DocumentImpl("A\nB\nC\nD") val document2 = DocumentImpl("A\nD") val fragments = MANAGER.compareLinesInner(document1.charsSequence, document2.charsSequence, ComparisonPolicy.DEFAULT, DumbProgressIndicator.INSTANCE) val builder = UnifiedFragmentBuilder(fragments, document1, document2, Side.RIGHT) builder.exec() assertFalse(builder.isEqual) assertEquals(builder.text.toString(), "A\nB\nC\nD\n") assertEquals(builder.changedLines, listOf(LineRange(1, 3))) assertEquals(builder.blocks.size, 1) val block = builder.blocks[0] assertEquals(block.line1, 1) assertEquals(block.line2, 3) assertEquals(block.range1.start, 1) assertEquals(block.range1.end, 3) assertEquals(block.range2.start, 3) assertEquals(block.range2.end, 3) } }
apache-2.0
ae7b8421e0630225b184965d1d4c979d
36.31746
153
0.757125
4.074523
false
true
false
false
NeatoRobotics/neato-sdk-android
Neato-SDK/neato-sdk-android/src/main/java/com/neatorobotics/sdk/android/utils/RetryUtils.kt
1
1493
/* * Copyright (c) 2019. * Neato Robotics Inc. */ package com.neatorobotics.sdk.android.utils import android.util.Log import kotlinx.coroutines.delay const val TAG = "RetryUtils.kt" suspend fun <T> retryWithException( times: Int = Int.MAX_VALUE, initialDelay: Long = 100, maxDelay: Long = 3000, factor: Double = 2.0, block: suspend () -> T): T { var currentDelay = initialDelay repeat(times - 1) { try { return block() } catch (e: Exception) { Log.e(TAG, e.message?:"") // you can log an error here and/or make a more finer-grained // analysis of the cause to see if retry is needed } delay(currentDelay) currentDelay = (currentDelay * factor).toLong().coerceAtMost(maxDelay) } return block() // last attempt } suspend fun <T> retry( times: Int = Int.MAX_VALUE, initialDelay: Long = 100, maxDelay: Long = 3000, factor: Double = 2.0, block: suspend () -> T, exitBlock: (T) -> Boolean, default: T): T { var currentDelay = initialDelay repeat(times) { try { val result = block() if(exitBlock(result)) return result } catch (e: Exception) { // you can log an error here } delay(currentDelay) currentDelay = (currentDelay * factor).toLong().coerceAtMost(maxDelay) } return default // last attempt }
mit
1b553e21d6c193c175aa221a9bcd5787
25.678571
78
0.569993
4.024259
false
false
false
false
zpao/buck
test/com/facebook/buck/multitenant/service/MemorySharingIntSetTest.kt
1
8113
/* * Copyright (c) Facebook, Inc. and its affiliates. * * 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.facebook.buck.multitenant.service import io.vavr.collection.HashSet import org.junit.Assert.assertArrayEquals import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Test class MemorySharingIntSetTest { @Test @SuppressWarnings("MagicNumber") fun replaceSetWithNullWhenDeltasRemoveAllEntries() { val id = 1 val oldValues = uniqueSet(10, 20, 30) val info = DeltaDeriveInfo(id, oldValues, mutableListOf( remove(30), remove(10), remove(20) )) assertEquals( "Because the deltas remove all the entries, should map to null.", mapOf<Int, MemorySharingIntSet?>(id to null), aggregateDeltaDeriveInfos(listOf(info)) ) } @Test @SuppressWarnings("MagicNumber") fun addingToEmptyOldDepsCreatesUniqueSetWithProperlySortedValues() { val id = 1 val oldValues = null val info = DeltaDeriveInfo(id, oldValues, mutableListOf( add(60), add(10), add(80), add(50), add(20), add(30), add(90), add(40), add(70) )) val set = aggregateDeltaDeriveInfos(listOf(info)).getValue(id) assertArrayEquals( intArrayOf(10, 20, 30, 40, 50, 60, 70, 80, 90), asUniqueValues(set) ) } @Test(expected = IllegalStateException::class) @SuppressWarnings("MagicNumber") fun throwsIfRemoveSpecifiedToEmptyOldDeps() { val id = 1 val oldValues = null val info = DeltaDeriveInfo(id, oldValues, mutableListOf(remove(10))) aggregateDeltaDeriveInfos(listOf(info)) } @Test(expected = IllegalStateException::class) @SuppressWarnings("MagicNumber") fun throwsIfAddSpecifiedForIdAlreadyInOldDeps() { val id = 1 val oldValues = uniqueSet(10, 20, 30, 50, 60) val info = DeltaDeriveInfo(id, oldValues, mutableListOf(add(20))) aggregateDeltaDeriveInfos(listOf(info)) } @Test(expected = IllegalStateException::class) @SuppressWarnings("MagicNumber") fun throwsIfRemoveSpecifiedForIdNotInOldDeps() { val id = 1 val oldValues = uniqueSet(10, 20, 30, 50, 60) val info = DeltaDeriveInfo(id, oldValues, mutableListOf(remove(40))) aggregateDeltaDeriveInfos(listOf(info)) } @Test @SuppressWarnings("MagicNumber") fun addDeltasGreaterThanExistingValues() { val id = 1 val oldValues = uniqueSet(10, 20, 30) val info = DeltaDeriveInfo(id, oldValues, mutableListOf( add(60), add(40), add(50) )) val set = aggregateDeltaDeriveInfos(listOf(info)).getValue(id) assertArrayEquals( intArrayOf(10, 20, 30, 40, 50, 60), asUniqueValues(set) ) } @Test @SuppressWarnings("MagicNumber") fun addDeltasLessThanExistingValues() { val id = 1 val oldValues = uniqueSet(40, 50, 60) val info = DeltaDeriveInfo(id, oldValues, mutableListOf( add(20), add(10), add(30) )) val set = aggregateDeltaDeriveInfos(listOf(info)).getValue(id) assertArrayEquals( intArrayOf(10, 20, 30, 40, 50, 60), asUniqueValues(set) ) } @Test @SuppressWarnings("MagicNumber") fun crossOverPersistentSizeThreshold() { val id = 1 val values = IntArray(THRESHOLD_FOR_UNIQUE_VS_PERSISTENT - 1) { i -> i * 10 } val oldValues = MemorySharingIntSet.Unique(values) val info = DeltaDeriveInfo(id, oldValues, mutableListOf( remove(0), add(values.size * 10), add((values.size + 1) * 10) )) val set = aggregateDeltaDeriveInfos(listOf(info)).getValue(id) var expected = HashSet.empty<Int>() for (i in 1..THRESHOLD_FOR_UNIQUE_VS_PERSISTENT) { expected = expected.add(i * 10) } assertEquals(expected, asPersistentValues(set)) } @Test @SuppressWarnings("MagicNumber") fun fallUnderPersistentSizeThreshold() { val id = 1 var values = HashSet.empty<Int>() for (i in 0 until THRESHOLD_FOR_UNIQUE_VS_PERSISTENT) { values = values.add(i * 10) } val oldValues = MemorySharingIntSet.Persistent(values) val info = DeltaDeriveInfo(id, oldValues, mutableListOf( remove((values.size() - 1) * 10) )) val set = aggregateDeltaDeriveInfos(listOf(info)).getValue(id) val expected = IntArray(THRESHOLD_FOR_UNIQUE_VS_PERSISTENT - 1) { i -> i * 10 } assertArrayEquals(expected, asUniqueValues(set)) } @Test @SuppressWarnings("MagicNumber") fun modifyPersistentSetThatExceedsThreshold() { // oldIds will contain all even numbers. var oldKeys = HashSet.empty<Int>() // Ensure that both the old and new set exceed the size threshold. val maxId = THRESHOLD_FOR_UNIQUE_VS_PERSISTENT * 4 for (i in 0 until maxId step 2) { oldKeys = oldKeys.add(i) } val oldValues = MemorySharingIntSet.Persistent(oldKeys) // remove numbers divisible by 4 and add all odd numbers. val deltas = mutableListOf<SetDelta>() for (i in 0 until maxId step 4) { deltas.add(SetDelta.Remove(i)) } val numRemoves = deltas.size for (i in 1 until maxId step 2) { deltas.add(SetDelta.Add(i)) } val numAdds = deltas.size - numRemoves val id = maxId + 1 val info = DeltaDeriveInfo(id, oldValues, deltas) val set = aggregateDeltaDeriveInfos(listOf(info)).getValue(id) val expectedSize = oldKeys.size() + numAdds - numRemoves var expected = HashSet.empty<Int>() for (i in 0 until maxId) { if (i % 4 != 0) { expected = expected.add(i) } } assertEquals( "Sanity check expected set before comparing to observed value.", expectedSize, expected.size()) assertEquals(expected, asPersistentValues(set)) } @Test @SuppressWarnings("MagicNumber") fun contains() { val uniqueSet = uniqueSet(10, 20, 30, 40, 50, 60) assertTrue(uniqueSet.contains(40)) assertFalse(uniqueSet.contains(35)) val persistentSet = MemorySharingIntSet.Persistent(HashSet.ofAll(uniqueSet.values.toSet())) assertTrue(persistentSet.contains(40)) assertFalse(persistentSet.contains(35)) } } private fun uniqueSet(vararg ids: Int) = MemorySharingIntSet.Unique(ids.sortedArray()) private fun add(id: Int): SetDelta = SetDelta.Add(id) private fun remove(id: Int): SetDelta = SetDelta.Remove(id) private fun asUniqueValues(set: MemorySharingIntSet?): IntArray { @SuppressWarnings("UnsafeCast") val unique = set as MemorySharingIntSet.Unique return unique.values } private fun asPersistentValues(set: MemorySharingIntSet?): Iterable<Int> { @SuppressWarnings("UnsafeCast") val persistent = set as MemorySharingIntSet.Persistent return persistent.values }
apache-2.0
6a16013459d3852333a317653cd3c911
33.088235
99
0.61383
4.604427
false
true
false
false
leafclick/intellij-community
platform/execution-impl/src/com/intellij/execution/runners/ConsoleTitleGen.kt
1
1569
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.execution.runners import com.intellij.execution.ExecutionHelper import com.intellij.openapi.project.Project open class ConsoleTitleGen @JvmOverloads constructor(private val myProject: Project, private val consoleTitle: String, private val shouldAddNumberToTitle: Boolean = true) { fun makeTitle(): String { if (shouldAddNumberToTitle) { val activeConsoleNames = getActiveConsoles(consoleTitle) var max = -1 for (name in activeConsoleNames) { try { val numBegin = name.lastIndexOf("(") if (numBegin != -1) { val numString = name.substring(numBegin + 1, name.length - 1) val num = Integer.parseInt(numString) if (num > max) { max = num } } else { max = 0 } } catch (ignored: Exception) { //skip } } return when (max) { -1 -> consoleTitle else -> "$consoleTitle (${max + 1})" } } return consoleTitle } protected open fun getActiveConsoles(consoleTitle: String) = ExecutionHelper.collectConsolesByDisplayName(myProject) { dom -> dom.startsWith(consoleTitle) } .filter { it.processHandler?.isProcessTerminated == false } .map { it.displayName } }
apache-2.0
8520fd14aad4ea83305288dd8dfcd70e
31.6875
140
0.579987
4.827692
false
false
false
false
code-helix/slatekit
src/lib/kotlin/slatekit-utils/src/main/kotlin/slatekit/utils/templates/Subs.kt
1
2646
/** * <slate_header> * url: www.slatekit.com * git: www.github.com/code-helix/slatekit * org: www.codehelix.co * author: Kishore Reddy * copyright: 2016 CodeHelix Solutions Inc. * license: refer to website and/or github * about: A tool-kit, utility library and server-backend * mantra: Simplicity above all else * </slate_header> */ package slatekit.utils.templates import slatekit.common.DateTimes import slatekit.common.ext.toStringYYYYMMDD import slatekit.common.values.ListMap /** * Performs dynamic substitutions of variables in text. * Similar to interpolated strings, but at runtime. This allows for creating * @param items * @param setDefaults */ class Subs(items: List<Pair<String, (TemplatePart) -> String>>? = null, setDefaults: Boolean = true) { private val groups = ListMap(items ?: listOf()) init { // Add the default subs/variables if (setDefaults) { defaults() } // Add the custom variables items?.let { it -> it.forEach { entry -> groups.add(entry.first, entry.second) } } } /** * whether this contains a substitution with the given key * * @param key * @return */ fun contains(key: String): Boolean = groups.contains(key) /** * Size of the substitutions * @return */ val size: Int get() = groups.size /** * gets the value with the supplied key * * @param key * @return */ operator fun get(key: String): String = lookup(key) /** * gets the value with the supplied key * * @param key * @return */ fun lookup(key: String): String = if (!groups.contains(key)) { "" } else { val sub = groups[key] sub?.invoke(TemplatePart(key, TemplateConstants.TypeText, -1, -1)) ?: "" } private fun defaults() { // Default functions. groups.add("today" , { DateTimes.today().toStringYYYYMMDD() }) groups.add("yesterday", { DateTimes.today().plusDays(-1).toStringYYYYMMDD() }) groups.add("tomorrow" , { DateTimes.today().plusDays(1).toStringYYYYMMDD() }) groups.add("t" , { DateTimes.today().toStringYYYYMMDD() }) groups.add("t-1" , { DateTimes.today().plusDays(-1).toStringYYYYMMDD() }) groups.add("t+1" , { DateTimes.today().plusDays(1).toStringYYYYMMDD() }) groups.add("today+1" , { DateTimes.today().plusDays(1).toStringYYYYMMDD() }) groups.add("today-1" , { DateTimes.today().plusDays(-1).toStringYYYYMMDD() }) } }
apache-2.0
fb53e07eac9e70610df5224ed122eb55
28.076923
102
0.593726
4.058282
false
false
false
false
zdary/intellij-community
plugins/git4idea/src/git4idea/index/GitFileStatus.kt
4
2166
// 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 git4idea.index import com.intellij.openapi.vcs.FilePath import com.intellij.openapi.vcs.FileStatus import com.intellij.openapi.vfs.VirtualFile import git4idea.GitContentRevision data class GitFileStatus(val index: StatusCode, val workTree: StatusCode, val path: FilePath, val origPath: FilePath? = null) { constructor(root: VirtualFile, record: LightFileStatus.StatusRecord) : this(record.index, record.workTree, GitContentRevision.createPath(root, record.path), record.origPath?.let { GitContentRevision.createPath(root, it) }) fun isConflicted(): Boolean = isConflicted(index, workTree) fun isUntracked() = isUntracked(index) || isUntracked(workTree) fun isIgnored() = isIgnored(index) || isIgnored(workTree) fun isTracked() = !isIgnored(index) && !isUntracked(index) fun getStagedStatus(): FileStatus? = if (isIgnored(index) || isUntracked(index) || isConflicted()) null else getFileStatus(index) fun getUnStagedStatus(): FileStatus? = if (isIgnored(workTree) || isUntracked(workTree) || isConflicted()) null else getFileStatus(workTree) } fun untrackedStatus(filePath: FilePath) = GitFileStatus('?', '?', filePath, null) fun ignoredStatus(filePath: FilePath) = GitFileStatus('!', '!', filePath, null) fun notChangedStatus(filePath: FilePath) = GitFileStatus(' ', ' ', filePath, null) fun GitFileStatus.has(contentVersion: ContentVersion): Boolean { return when (contentVersion) { ContentVersion.HEAD -> isTracked() && !isAdded(index) && !isIntendedToBeAdded(index, workTree) ContentVersion.STAGED -> isTracked() && !isDeleted(index) ContentVersion.LOCAL -> !isDeleted(workTree) } } fun GitFileStatus.path(contentVersion: ContentVersion): FilePath { return when (contentVersion) { ContentVersion.HEAD -> origPath ?: path ContentVersion.STAGED -> if (isRenamed(index)) path else origPath ?: path ContentVersion.LOCAL -> path } } enum class ContentVersion { HEAD, STAGED, LOCAL }
apache-2.0
8c00039b7bc6c7e1b24afa0fd26fdca2
44.145833
155
0.724377
4.503119
false
false
false
false
exponent/exponent
packages/expo-updates/android/src/main/java/expo/modules/updates/manifest/LegacyUpdateManifest.kt
2
5284
package expo.modules.updates.manifest import android.net.Uri import android.util.Log import expo.modules.updates.UpdatesConfiguration import expo.modules.updates.UpdatesUtils import expo.modules.updates.db.entity.AssetEntity import expo.modules.updates.db.entity.UpdateEntity import expo.modules.updates.db.enums.UpdateStatus import expo.modules.updates.loader.EmbeddedLoader import expo.modules.manifests.core.LegacyManifest import org.json.JSONArray import org.json.JSONException import org.json.JSONObject import java.net.URI import java.text.ParseException import java.util.* class LegacyUpdateManifest private constructor( override val manifest: LegacyManifest, private val mManifestUrl: Uri, private val mId: UUID, private val mScopeKey: String, private val mCommitTime: Date, private val mRuntimeVersion: String, private val mBundleUrl: Uri, private val mAssets: JSONArray? ) : UpdateManifest { override val serverDefinedHeaders: JSONObject? = null override val manifestFilters: JSONObject? = null override val updateEntity: UpdateEntity by lazy { UpdateEntity(mId, mCommitTime, mRuntimeVersion, mScopeKey).apply { manifest = [email protected]() if (isDevelopmentMode) { status = UpdateStatus.DEVELOPMENT } } } override val assetEntityList: List<AssetEntity> by lazy { val assetList = mutableListOf<AssetEntity>() val bundleKey = manifest.getBundleKey() assetList.add( AssetEntity(bundleKey, "js").apply { url = mBundleUrl isLaunchAsset = true embeddedAssetFilename = EmbeddedLoader.BUNDLE_FILENAME } ) if (mAssets != null && mAssets.length() > 0) { for (i in 0 until mAssets.length()) { try { val bundledAsset = mAssets.getString(i) val extensionIndex = bundledAsset.lastIndexOf('.') val prefixLength = "asset_".length val hash = if (extensionIndex > 0) bundledAsset.substring( prefixLength, extensionIndex ) else bundledAsset.substring(prefixLength) val type = if (extensionIndex > 0) bundledAsset.substring(extensionIndex + 1) else "" assetList.add( AssetEntity(hash, type).apply { url = Uri.withAppendedPath(assetsUrlBase, hash) embeddedAssetFilename = bundledAsset } ) } catch (e: JSONException) { Log.e(TAG, "Could not read asset from manifest", e) } } } assetList } private val assetsUrlBase: Uri? by lazy { getAssetsUrlBase(mManifestUrl, manifest) } override val isDevelopmentMode: Boolean by lazy { manifest.isDevelopmentMode() } companion object { private val TAG = UpdateManifest::class.java.simpleName private const val EXPO_ASSETS_URL_BASE = "https://classic-assets.eascdn.net/~assets/" private val EXPO_DOMAINS = arrayOf("expo.io", "exp.host", "expo.test") @Throws(JSONException::class) fun fromLegacyManifest( manifest: LegacyManifest, configuration: UpdatesConfiguration ): LegacyUpdateManifest { val id: UUID val commitTime: Date if (manifest.isUsingDeveloperTool()) { // xdl doesn't always serve a releaseId, but we don't need one in dev mode id = UUID.randomUUID() commitTime = Date() } else { id = UUID.fromString(manifest.getReleaseId()) val commitTimeString = manifest.getCommitTime() commitTime = try { UpdatesUtils.parseDateString(commitTimeString) } catch (e: ParseException) { Log.e(TAG, "Could not parse commitTime", e) Date() } } val runtimeVersion = manifest.getRuntimeVersion() ?: manifest.getSDKVersion() ?: throw Exception("sdkVersion should not be null") val bundleUrl = Uri.parse(manifest.getBundleURL()) val bundledAssets = manifest.getBundledAssets() return LegacyUpdateManifest( manifest, configuration.updateUrl!!, id, configuration.scopeKey!!, commitTime, runtimeVersion, bundleUrl, bundledAssets ) } internal fun getAssetsUrlBase(manifestUrl: Uri, legacyManifest: LegacyManifest): Uri { val hostname = manifestUrl.host return if (hostname == null) { Uri.parse(EXPO_ASSETS_URL_BASE) } else { for (expoDomain in EXPO_DOMAINS) { if (hostname == expoDomain || hostname.endsWith(".$expoDomain")) { return Uri.parse(EXPO_ASSETS_URL_BASE) } } // assetUrlOverride may be an absolute or relative URL // if relative, we should resolve with respect to the manifest URL // java.net.URI's resolve method does this for us val assetsPathOrUrl = legacyManifest.getAssetUrlOverride() ?: "assets" try { val assetsURI = URI(assetsPathOrUrl) val manifestURI = URI(manifestUrl.toString()) Uri.parse(manifestURI.resolve(assetsURI).toString()) } catch (e: Exception) { Log.e(TAG, "Failed to parse assetUrlOverride, falling back to default asset path", e) manifestUrl.buildUpon().appendPath("assets").build() } } } } }
bsd-3-clause
e150a7dc81df0cf3b19297990793f19f
33.090323
135
0.664837
4.547332
false
false
false
false
exponent/exponent
android/expoview/src/main/java/host/exp/exponent/notifications/schedulers/CalendarSchedulerModel.kt
2
2918
package host.exp.exponent.notifications.schedulers import host.exp.exponent.notifications.helpers.ExpoCronDefinitionBuilder import host.exp.exponent.notifications.managers.SchedulersDatabase import host.exp.exponent.kernel.ExperienceKey import host.exp.exponent.notifications.managers.SchedulersManagerProxy import com.cronutils.parser.CronParser import com.cronutils.model.time.ExecutionTime import android.content.Intent import android.os.SystemClock import com.raizlabs.android.dbflow.annotation.Column import com.raizlabs.android.dbflow.annotation.PrimaryKey import com.raizlabs.android.dbflow.annotation.Table import com.raizlabs.android.dbflow.structure.BaseModel import org.joda.time.DateTime import org.json.JSONException import java.util.* @Table(database = SchedulersDatabase::class) class CalendarSchedulerModel : BaseModel(), SchedulerModel { @Column @PrimaryKey(autoincrement = true) var id = 0 @Column override var notificationId = 0 @Column(name = "experienceId") var experienceScopeKey: String? = null @Column var isRepeat = false @Column var serializedDetails: String? = null @Column var calendarData: String? = null override val idAsString: String get() = Integer.valueOf(id).toString() + this.javaClass.simpleName override val ownerExperienceKey: ExperienceKey get() = ExperienceKey(experienceScopeKey!!) override fun canBeRescheduled(): Boolean { return isRepeat } override fun saveAndGetId(): String { save() // get id from database val details = getDetailsMap() details!![SchedulersManagerProxy.SCHEDULER_ID] = idAsString setDetailsFromMap(details) save() return idAsString } override fun remove() { delete() } // elapsedTime override val nextAppearanceTime: Long get() { val cronDefinition = ExpoCronDefinitionBuilder.cronDefinition val parser = CronParser(cronDefinition) val cron = parser.parse(calendarData) val now = DateTime.now() val nextExecution = ExecutionTime.forCron(cron).nextExecution(now) val whenShouldAppear = nextExecution.toDate().time val bootTime = DateTime.now().toDate().time - SystemClock.elapsedRealtime() return whenShouldAppear - bootTime } override fun shouldBeTriggeredByAction(action: String?): Boolean { return triggeringActions.contains(action) } override fun getDetailsMap(): HashMap<String, Any>? { return try { HashMapSerializer.deserialize(serializedDetails) } catch (e: JSONException) { e.printStackTrace() null } } override fun setDetailsFromMap(detailsMap: HashMap<String, Any>) { serializedDetails = HashMapSerializer.serialize(detailsMap) } companion object { private val triggeringActions = listOf( null, Intent.ACTION_BOOT_COMPLETED, Intent.ACTION_REBOOT, Intent.ACTION_TIME_CHANGED, Intent.ACTION_TIMEZONE_CHANGED ) } }
bsd-3-clause
ae827c9d09644241132874419983ab0c
31.422222
81
0.750857
4.427921
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/compiler-plugins/scripting-ide-services/src/org/jetbrains/kotlin/scripting/ide_services/compiler/impl/IdeLikeReplCodeAnalyzer.kt
2
3409
// 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.scripting.ide_services.compiler.impl import org.jetbrains.kotlin.cli.jvm.compiler.CliBindingTrace import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment import org.jetbrains.kotlin.container.getService import org.jetbrains.kotlin.descriptors.ClassDescriptorWithResolutionScopes import org.jetbrains.kotlin.descriptors.ModuleDescriptor import org.jetbrains.kotlin.descriptors.PropertyDescriptor import org.jetbrains.kotlin.descriptors.ScriptDescriptor import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.tower.ImplicitsExtensionsResolutionFilter import org.jetbrains.kotlin.resolve.diagnostics.Diagnostics import org.jetbrains.kotlin.resolve.lazy.declarations.FileBasedDeclarationProviderFactory import org.jetbrains.kotlin.scripting.compiler.plugin.repl.ReplCodeAnalyzerBase import org.jetbrains.kotlin.scripting.definitions.ScriptPriorities class IdeLikeReplCodeAnalyzer( private val environment: KotlinCoreEnvironment, implicitsResolutionFilter: ImplicitsExtensionsResolutionFilter ) : ReplCodeAnalyzerBase(environment, CliBindingTrace(), implicitsResolutionFilter) { interface ReplLineAnalysisResultWithStateless : ReplLineAnalysisResult { // Result of stateless analyse, which may be used for reporting errors // without code generation data class Stateless( override val diagnostics: Diagnostics, val bindingContext: BindingContext, val resolutionFacade: KotlinResolutionFacadeForRepl, val moduleDescriptor: ModuleDescriptor, val resultProperty: PropertyDescriptor?, ) : ReplLineAnalysisResultWithStateless { override val scriptDescriptor: ClassDescriptorWithResolutionScopes? get() = null } } fun statelessAnalyzeWithImportedScripts( psiFile: KtFile, importedScripts: List<KtFile>, priority: Int ): ReplLineAnalysisResultWithStateless { topDownAnalysisContext.scripts.clear() trace.clearDiagnostics() psiFile.script!!.putUserData(ScriptPriorities.PRIORITY_KEY, priority) return doStatelessAnalyze(psiFile, importedScripts) } private fun doStatelessAnalyze(linePsi: KtFile, importedScripts: List<KtFile>): ReplLineAnalysisResultWithStateless { scriptDeclarationFactory.setDelegateFactory( FileBasedDeclarationProviderFactory(resolveSession.storageManager, listOf(linePsi) + importedScripts) ) replState.submitLine(linePsi) val context = runAnalyzer(linePsi, importedScripts) val resultPropertyDescriptor = (context.scripts[linePsi.script] as? ScriptDescriptor)?.resultValue val moduleDescriptor = container.getService(ModuleDescriptor::class.java) val resolutionFacade = KotlinResolutionFacadeForRepl(environment, container) val diagnostics = trace.bindingContext.diagnostics return ReplLineAnalysisResultWithStateless.Stateless( diagnostics, trace.bindingContext, resolutionFacade, moduleDescriptor, resultPropertyDescriptor, ) } }
apache-2.0
60e95f6b61f6cf761f6b5e3b83343ee6
44.453333
158
0.76474
5.588525
false
false
false
false
google/intellij-community
plugins/kotlin/base/fe10/code-insight/src/org/jetbrains/kotlin/idea/base/fe10/codeInsight/Fe10QuickFixProviderImpl.kt
5
4556
// 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.fe10.codeInsight import com.intellij.codeInsight.intention.IntentionAction import com.intellij.codeInspection.SuppressIntentionAction import com.intellij.openapi.diagnostic.Logger import com.intellij.util.containers.MultiMap import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.DiagnosticFactory import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.highlighter.AnnotationHostKind import org.jetbrains.kotlin.idea.highlighter.Fe10QuickFixProvider import org.jetbrains.kotlin.idea.quickfix.KotlinSuppressIntentionAction import org.jetbrains.kotlin.idea.quickfix.QuickFixes import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.types.KotlinType import java.lang.reflect.* import java.util.* class Fe10QuickFixProviderImpl : Fe10QuickFixProvider { override fun createQuickFixes(diagnostics: Collection<Diagnostic>): MultiMap<Diagnostic, IntentionAction> { val first = diagnostics.minByOrNull { it.toString() } val factory = diagnostics.first().getRealDiagnosticFactory() val actions = MultiMap<Diagnostic, IntentionAction>() val intentionActionsFactories = QuickFixes.getInstance().getActionFactories(factory) for (intentionActionsFactory in intentionActionsFactories) { val allProblemsActions = intentionActionsFactory.createActionsForAllProblems(diagnostics) if (allProblemsActions.isNotEmpty()) { actions.putValues(first, allProblemsActions) } else { for (diagnostic in diagnostics) { actions.putValues(diagnostic, intentionActionsFactory.createActions(diagnostic)) } } } for (diagnostic in diagnostics) { actions.putValues(diagnostic, QuickFixes.getInstance().getActions(diagnostic.factory)) } actions.values().forEach { NoDeclarationDescriptorsChecker.check(it::class.java) } return actions } override fun createSuppressFix(element: KtElement, suppressionKey: String, hostKind: AnnotationHostKind): SuppressIntentionAction { return KotlinSuppressIntentionAction(element, suppressionKey, hostKind) } private fun Diagnostic.getRealDiagnosticFactory(): DiagnosticFactory<*> { return when (factory) { Errors.PLUGIN_ERROR -> Errors.PLUGIN_ERROR.cast(this).a.factory Errors.PLUGIN_WARNING -> Errors.PLUGIN_WARNING.cast(this).a.factory Errors.PLUGIN_INFO -> Errors.PLUGIN_INFO.cast(this).a.factory else -> factory } } } private object NoDeclarationDescriptorsChecker { private val LOG = Logger.getInstance(NoDeclarationDescriptorsChecker::class.java) private val checkedQuickFixClasses = Collections.synchronizedSet(HashSet<Class<*>>()) fun check(quickFixClass: Class<*>) { if (!checkedQuickFixClasses.add(quickFixClass)) return for (field in quickFixClass.declaredFields) { checkType(field.genericType, field) } quickFixClass.superclass?.let { check(it) } } private fun checkType(type: Type, field: Field) { when (type) { is Class<*> -> { if (DeclarationDescriptor::class.java.isAssignableFrom(type) || KotlinType::class.java.isAssignableFrom(type)) { LOG.error( "QuickFix class ${field.declaringClass.name} contains field ${field.name} that holds ${type.simpleName}. " + "This leads to holding too much memory through this quick-fix instance. " + "Possible solution can be wrapping it using KotlinIntentionActionFactoryWithDelegate." ) } if (IntentionAction::class.java.isAssignableFrom(type)) { check(type) } } is GenericArrayType -> checkType(type.genericComponentType, field) is ParameterizedType -> { if (Collection::class.java.isAssignableFrom(type.rawType as Class<*>)) { type.actualTypeArguments.forEach { checkType(it, field) } } } is WildcardType -> type.upperBounds.forEach { checkType(it, field) } } } }
apache-2.0
122341764eb92db07b428c9dc4ec36a4
42.4
135
0.683275
5.142212
false
false
false
false
anitawoodruff/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/models/inventory/Quest.kt
1
1224
package com.habitrpg.android.habitica.models.inventory import com.habitrpg.android.habitica.models.members.Member import io.realm.RealmList import io.realm.RealmObject import io.realm.annotations.PrimaryKey open class Quest : RealmObject() { @PrimaryKey var id: String? = null set(value) { field = value progress?.id = value } var key: String = "" set(value) { field = value progress?.key = key } var active: Boolean = false var leader: String? = null var RSVPNeeded: Boolean = false var members: RealmList<QuestMember>? = null var progress: QuestProgress? = null var participants: RealmList<Member>? = null var rageStrikes: RealmList<QuestRageStrike>? = null var completed: String? = null fun hasRageStrikes(): Boolean { return rageStrikes?.isNotEmpty() ?: false } fun addRageStrike(rageStrike: QuestRageStrike) { if (rageStrikes == null) { rageStrikes = RealmList() } rageStrikes?.add(rageStrike) } val activeRageStrikeNumber: Int get() { return rageStrikes?.filter { it.wasHit }?.size ?: 0 } }
gpl-3.0
af91bd260cf654b3e222512441255c94
23.541667
59
0.617647
4.355872
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/intentions/UnfoldAssignmentToWhenIntention.kt
1
1794
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions.branchedTransformations.intentions import com.intellij.codeInsight.intention.LowPriorityAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.TextRange import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingRangeIntention import org.jetbrains.kotlin.idea.intentions.branchedTransformations.BranchedUnfoldingUtils import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtBinaryExpression import org.jetbrains.kotlin.psi.KtPsiUtil import org.jetbrains.kotlin.psi.KtWhenExpression import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.startOffset class UnfoldAssignmentToWhenIntention : SelfTargetingRangeIntention<KtBinaryExpression>( KtBinaryExpression::class.java, KotlinBundle.lazyMessage("replace.assignment.with.when.expression") ), LowPriorityAction { override fun applicabilityRange(element: KtBinaryExpression): TextRange? { if (element.operationToken !in KtTokens.ALL_ASSIGNMENTS) return null if (element.left == null) return null val right = element.right as? KtWhenExpression ?: return null if (!KtPsiUtil.checkWhenExpressionHasSingleElse(right)) return null if (right.entries.any { it.expression == null }) return null return TextRange(element.startOffset, right.whenKeyword.endOffset) } override fun applyTo(element: KtBinaryExpression, editor: Editor?) = BranchedUnfoldingUtils.unfoldAssignmentToWhen(element, editor) }
apache-2.0
461349eb72bca2c03559048ec3c3e66a
51.794118
158
0.80379
4.733509
false
false
false
false
idea4bsd/idea4bsd
platform/configuration-store-impl/src/ModuleStoreImpl.kt
4
2512
/* * 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.components.* import com.intellij.openapi.module.Module import java.io.File import java.nio.file.Paths private val MODULE_FILE_STORAGE_ANNOTATION = FileStorageAnnotation(StoragePathMacros.MODULE_FILE, false) private open class ModuleStoreImpl(module: Module, private val pathMacroManager: PathMacroManager) : ModuleStoreBase() { override val project = module.project override val storageManager = ModuleStateStorageManager(pathMacroManager.createTrackingSubstitutor(), module) override final fun getPathMacroManagerForDefaults() = pathMacroManager private class TestModuleStore(module: Module, pathMacroManager: PathMacroManager) : ModuleStoreImpl(module, pathMacroManager) { private var moduleComponentLoadPolicy: StateLoadPolicy? = null override fun setPath(path: String) { super.setPath(path) if (File(path).exists()) { moduleComponentLoadPolicy = StateLoadPolicy.LOAD } } override val loadPolicy: StateLoadPolicy get() = moduleComponentLoadPolicy ?: (project.stateStore as ComponentStoreImpl).loadPolicy } } // used in upsource abstract class ModuleStoreBase : ComponentStoreImpl() { override abstract val storageManager: StateStorageManagerImpl override final fun <T> getStorageSpecs(component: PersistentStateComponent<T>, stateSpec: State, operation: StateStorageOperation): Array<out Storage> { val storages = stateSpec.storages if (storages.isEmpty()) { return arrayOf(MODULE_FILE_STORAGE_ANNOTATION) } else { return super.getStorageSpecs(component, stateSpec, operation) } } override fun setPath(path: String) { if (!storageManager.addMacro(StoragePathMacros.MODULE_FILE, path)) { storageManager.getCachedFileStorages(listOf(StoragePathMacros.MODULE_FILE)).firstOrNull()?.setFile(null, Paths.get(path)) } } }
apache-2.0
5da0712c0753dbffa4abc49246213601
36.507463
154
0.761943
4.868217
false
true
false
false
jwren/intellij-community
plugins/kotlin/jvm-debugger/util/src/org/jetbrains/kotlin/idea/debugger/DebuggerUtils.kt
1
5144
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.debugger import com.intellij.debugger.impl.DebuggerUtilsImpl.getLocalVariableBorders import com.intellij.openapi.project.DumbService import com.intellij.openapi.project.Project import com.intellij.openapi.util.io.FileUtilRt import com.intellij.psi.search.GlobalSearchScope import com.sun.jdi.AbsentInformationException import com.sun.jdi.LocalVariable import com.sun.jdi.Location import org.jetbrains.annotations.TestOnly import org.jetbrains.kotlin.asJava.finder.JavaElementFinder import org.jetbrains.kotlin.idea.core.KotlinFileTypeFactoryUtils import org.jetbrains.kotlin.idea.project.platform import org.jetbrains.kotlin.idea.stubindex.KotlinSourceFilterScope import org.jetbrains.kotlin.idea.stubindex.PackageIndexUtil.findFilesWithExactPackage import org.jetbrains.kotlin.idea.stubindex.StaticFacadeIndexUtil import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.platform.isCommon import org.jetbrains.kotlin.platform.jvm.isJvm import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.resolve.jvm.JvmClassName import java.nio.file.Path import java.util.* object DebuggerUtils { @get:TestOnly var forceRanking = false private val IR_BACKEND_LAMBDA_REGEX = ".+\\\$lambda-\\d+".toRegex() fun findSourceFileForClassIncludeLibrarySources( project: Project, scope: GlobalSearchScope, className: JvmClassName, fileName: String, location: Location? = null ): KtFile? { return runReadAction { findSourceFileForClass( project, listOf(scope, KotlinSourceFilterScope.librarySources(GlobalSearchScope.allScope(project), project)), className, fileName, location ) } } fun findSourceFileForClass( project: Project, scopes: List<GlobalSearchScope>, className: JvmClassName, fileName: String, location: Location? ): KtFile? { if (!isKotlinSourceFile(fileName)) return null if (DumbService.getInstance(project).isDumb) return null val partFqName = className.fqNameForClassNameWithoutDollars for (scope in scopes) { val files = findFilesByNameInPackage(className, fileName, project, scope) .filter { it.platform.isJvm() || it.platform.isCommon() } if (files.isEmpty()) { continue } if (files.size == 1 && !forceRanking || location == null) { return files.first() } StaticFacadeIndexUtil.findFilesForFilePart(partFqName, scope, project) .singleOrNull { it.name == fileName } ?.let { return it } return FileRankingCalculatorForIde.findMostAppropriateSource(files, location) } return null } private fun findFilesByNameInPackage( className: JvmClassName, fileName: String, project: Project, searchScope: GlobalSearchScope ): List<KtFile> { val files = findFilesWithExactPackage(className.packageFqName, searchScope, project).filter { it.name == fileName } return files.sortedWith(JavaElementFinder.byClasspathComparator(searchScope)) } fun isKotlinSourceFile(fileName: String): Boolean { val extension = FileUtilRt.getExtension(fileName).lowercase(Locale.getDefault()) return extension in KotlinFileTypeFactoryUtils.KOTLIN_EXTENSIONS } fun String.trimIfMangledInBytecode(isMangledInBytecode: Boolean): String = if (isMangledInBytecode) getMethodNameWithoutMangling() else this private fun String.getMethodNameWithoutMangling() = substringBefore('-') fun isKotlinFakeLineNumber(location: Location): Boolean { // The compiler inserts a fake line number for single-line inline function calls with a // lambda parameter such as: // // 42.let { it + 1 } // // This is done so that a breakpoint can be set on the lambda and on the line even though // the lambda is on the same line. When stepping, we do not want to stop at such fake line // numbers. They cause us to step to line 1 of the current file. try { if (location.lineNumber("Kotlin") == 1 && location.sourceName("Kotlin") == "fake.kt" && Path.of(location.sourcePath("Kotlin")) == Path.of("kotlin/jvm/internal/FakeKt") ) { return true } } catch (ignored: AbsentInformationException) { } return false } fun String.isGeneratedIrBackendLambdaMethodName() = matches(IR_BACKEND_LAMBDA_REGEX) fun LocalVariable.getBorders(): ClosedRange<Location>? { val range = getLocalVariableBorders(this) ?: return null return range.from..range.to } }
apache-2.0
97e96545b633e2c9b69826f11f36d9b7
36.275362
158
0.67535
4.875829
false
false
false
false
jwren/intellij-community
plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/fir/inspections/diagnosticBased/HLUnusedVariableInspection.kt
3
2830
// 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.fir.inspections.diagnosticBased import org.jetbrains.kotlin.idea.quickfix.RemovePsiElementSimpleFix import com.intellij.codeInspection.ProblemHighlightType import org.jetbrains.kotlin.analysis.api.fir.diagnostics.KtFirDiagnostic import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.api.applicator.HLApplicator import org.jetbrains.kotlin.idea.api.applicator.HLApplicatorInput import org.jetbrains.kotlin.idea.api.applicator.applicator import org.jetbrains.kotlin.idea.fir.api.AbstractHLDiagnosticBasedInspection import org.jetbrains.kotlin.idea.fir.api.HLInputByDiagnosticProvider import org.jetbrains.kotlin.idea.fir.api.applicator.HLApplicabilityRange import org.jetbrains.kotlin.idea.fir.api.applicator.HLPresentation import org.jetbrains.kotlin.idea.fir.api.applicator.presentation import org.jetbrains.kotlin.idea.fir.api.inputByDiagnosticProvider import org.jetbrains.kotlin.idea.fir.applicators.ApplicabilityRanges import org.jetbrains.kotlin.idea.util.isExplicitTypeReferenceNeededForTypeInference import org.jetbrains.kotlin.psi.KtNamedDeclaration import org.jetbrains.kotlin.psi.KtProperty class HLUnusedVariableInspection : AbstractHLDiagnosticBasedInspection<KtNamedDeclaration, KtFirDiagnostic.UnusedVariable, HLApplicatorInput.Empty>( elementType = KtNamedDeclaration::class, diagnosticType = KtFirDiagnostic.UnusedVariable::class, ) { override val inputByDiagnosticProvider: HLInputByDiagnosticProvider<KtNamedDeclaration, KtFirDiagnostic.UnusedVariable, HLApplicatorInput.Empty> get() = inputByDiagnosticProvider { diagnostic -> val ktProperty = diagnostic.psi as? KtProperty ?: return@inputByDiagnosticProvider null if (ktProperty.isExplicitTypeReferenceNeededForTypeInference()) return@inputByDiagnosticProvider null HLApplicatorInput.Empty } override val presentation: HLPresentation<KtNamedDeclaration> get() = presentation { highlightType(ProblemHighlightType.LIKE_UNUSED_SYMBOL) } override val applicabilityRange: HLApplicabilityRange<KtNamedDeclaration> get() = ApplicabilityRanges.DECLARATION_NAME override val applicator: HLApplicator<KtNamedDeclaration, HLApplicatorInput.Empty> get() = applicator { familyName(KotlinBundle.message("remove.element")) actionName { psi, _ -> KotlinBundle.message("remove.variable.0", psi.name.toString()) } applyTo { psi, _ -> RemovePsiElementSimpleFix.RemoveVariableFactory.removeProperty(psi as KtProperty) } } }
apache-2.0
84f4831e79c1bee638af9afb11ac7725
55.62
158
0.783746
5.18315
false
false
false
false
androidx/androidx
compose/foundation/foundation/src/androidAndroidTest/kotlin/androidx/compose/foundation/ScrollableTest.kt
3
85880
/* * 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.foundation import androidx.compose.animation.core.DecayAnimationSpec import androidx.compose.animation.core.keyframes import androidx.compose.animation.core.tween import androidx.compose.animation.rememberSplineBasedDecay import androidx.compose.foundation.gestures.DefaultFlingBehavior import androidx.compose.foundation.gestures.FlingBehavior import androidx.compose.foundation.gestures.Orientation import androidx.compose.foundation.gestures.ScrollScope import androidx.compose.foundation.gestures.ScrollableDefaults import androidx.compose.foundation.gestures.ScrollableState import androidx.compose.foundation.gestures.animateScrollBy import androidx.compose.foundation.gestures.awaitFirstDown import androidx.compose.foundation.gestures.scrollable import androidx.compose.foundation.interaction.DragInteraction import androidx.compose.foundation.interaction.Interaction import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyListState import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.runtime.currentComposer import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.MotionDurationScale import androidx.compose.ui.focus.FocusDirection import androidx.compose.ui.focus.FocusManager import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.focus.onFocusChanged import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.input.consumeScrollContainerInfo import androidx.compose.ui.input.nestedscroll.NestedScrollConnection import androidx.compose.ui.input.nestedscroll.NestedScrollDispatcher import androidx.compose.ui.input.nestedscroll.NestedScrollSource import androidx.compose.ui.input.nestedscroll.nestedScroll import androidx.compose.ui.input.pointer.PointerInputScope import androidx.compose.ui.input.pointer.changedToUpIgnoreConsumed import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.input.pointer.util.VelocityTracker import androidx.compose.ui.materialize import androidx.compose.ui.platform.AbstractComposeView import androidx.compose.ui.platform.InspectableValue import androidx.compose.ui.platform.LocalFocusManager import androidx.compose.ui.platform.LocalViewConfiguration import androidx.compose.ui.platform.isDebugInspectorInfoEnabled import androidx.compose.ui.platform.testTag import androidx.compose.ui.test.ExperimentalTestApi import androidx.compose.ui.test.ScrollWheel import androidx.compose.ui.test.junit4.ComposeContentTestRule import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onNodeWithTag import androidx.compose.ui.test.onRoot import androidx.compose.ui.test.performMouseInput import androidx.compose.ui.test.performTouchInput import androidx.compose.ui.test.swipe import androidx.compose.ui.test.swipeDown import androidx.compose.ui.test.swipeLeft import androidx.compose.ui.test.swipeRight import androidx.compose.ui.test.swipeUp import androidx.compose.ui.test.swipeWithVelocity import androidx.compose.ui.unit.Velocity import androidx.compose.ui.unit.dp import androidx.compose.ui.util.fastForEach import androidx.test.espresso.Espresso.onView import androidx.test.espresso.action.CoordinatesProvider import androidx.test.espresso.action.GeneralLocation import androidx.test.espresso.action.GeneralSwipeAction import androidx.test.espresso.action.Press import androidx.test.espresso.action.Swipe import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.LargeTest import com.google.common.truth.Truth.assertThat import com.google.common.truth.Truth.assertWithMessage import kotlin.math.abs import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext import org.hamcrest.CoreMatchers.allOf import org.hamcrest.CoreMatchers.instanceOf import org.junit.After import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @LargeTest @RunWith(AndroidJUnit4::class) class ScrollableTest { @get:Rule val rule = createComposeRule() private val scrollableBoxTag = "scrollableBox" private lateinit var scope: CoroutineScope private fun ComposeContentTestRule.setContentAndGetScope(content: @Composable () -> Unit) { setContent { val actualScope = rememberCoroutineScope() SideEffect { scope = actualScope } content() } } @Before fun before() { isDebugInspectorInfoEnabled = true } @After fun after() { isDebugInspectorInfoEnabled = false } @Test fun scrollable_horizontalScroll() { var total = 0f val controller = ScrollableState( consumeScrollDelta = { total += it it } ) setScrollableContent { Modifier.scrollable( state = controller, orientation = Orientation.Horizontal ) } rule.onNodeWithTag(scrollableBoxTag).performTouchInput { this.swipe( start = this.center, end = Offset(this.center.x + 100f, this.center.y), durationMillis = 100 ) } val lastTotal = rule.runOnIdle { assertThat(total).isGreaterThan(0) total } rule.onNodeWithTag(scrollableBoxTag).performTouchInput { this.swipe( start = this.center, end = Offset(this.center.x, this.center.y + 100f), durationMillis = 100 ) } rule.runOnIdle { assertThat(total).isEqualTo(lastTotal) } rule.onNodeWithTag(scrollableBoxTag).performTouchInput { this.swipe( start = this.center, end = Offset(this.center.x - 100f, this.center.y), durationMillis = 100 ) } rule.runOnIdle { assertThat(total).isLessThan(0.01f) } } @OptIn(ExperimentalTestApi::class) @Test fun scrollable_horizontalScroll_mouseWheel() { var total = 0f val controller = ScrollableState( consumeScrollDelta = { total += it it } ) setScrollableContent { Modifier.scrollable( state = controller, orientation = Orientation.Horizontal ) } rule.onNodeWithTag(scrollableBoxTag).performMouseInput { this.scroll(-100f, ScrollWheel.Horizontal) } val lastTotal = rule.runOnIdle { assertThat(total).isGreaterThan(0) total } rule.onNodeWithTag(scrollableBoxTag).performMouseInput { this.scroll(-100f, ScrollWheel.Vertical) } rule.runOnIdle { assertThat(total).isEqualTo(lastTotal) } rule.onNodeWithTag(scrollableBoxTag).performMouseInput { this.scroll(100f, ScrollWheel.Horizontal) } rule.runOnIdle { assertThat(total).isLessThan(0.01f) } } @Test fun scrollable_horizontalScroll_reverse() { var total = 0f val controller = ScrollableState( consumeScrollDelta = { total += it it } ) setScrollableContent { Modifier.scrollable( reverseDirection = true, state = controller, orientation = Orientation.Horizontal ) } rule.onNodeWithTag(scrollableBoxTag).performTouchInput { this.swipe( start = this.center, end = Offset(this.center.x + 100f, this.center.y), durationMillis = 100 ) } val lastTotal = rule.runOnIdle { assertThat(total).isLessThan(0) total } rule.onNodeWithTag(scrollableBoxTag).performTouchInput { this.swipe( start = this.center, end = Offset(this.center.x, this.center.y + 100f), durationMillis = 100 ) } rule.runOnIdle { assertThat(total).isEqualTo(lastTotal) } rule.onNodeWithTag(scrollableBoxTag).performTouchInput { this.swipe( start = this.center, end = Offset(this.center.x - 100f, this.center.y), durationMillis = 100 ) } rule.runOnIdle { assertThat(total).isLessThan(0.01f) } } @OptIn(ExperimentalTestApi::class) @Test fun scrollable_horizontalScroll_reverse_mouseWheel() { var total = 0f val controller = ScrollableState( consumeScrollDelta = { total += it it } ) setScrollableContent { Modifier.scrollable( reverseDirection = true, state = controller, orientation = Orientation.Horizontal ) } rule.onNodeWithTag(scrollableBoxTag).performMouseInput { this.scroll(-100f, ScrollWheel.Horizontal) } val lastTotal = rule.runOnIdle { assertThat(total).isLessThan(0) total } rule.onNodeWithTag(scrollableBoxTag).performMouseInput { this.scroll(-100f, ScrollWheel.Vertical) } rule.runOnIdle { assertThat(total).isEqualTo(lastTotal) } rule.onNodeWithTag(scrollableBoxTag).performMouseInput { this.scroll(100f, ScrollWheel.Horizontal) } rule.runOnIdle { assertThat(total).isLessThan(0.01f) } } @Test fun scrollable_verticalScroll() { var total = 0f val controller = ScrollableState( consumeScrollDelta = { total += it it } ) setScrollableContent { Modifier.scrollable( state = controller, orientation = Orientation.Vertical ) } rule.onNodeWithTag(scrollableBoxTag).performTouchInput { this.swipe( start = this.center, end = Offset(this.center.x, this.center.y + 100f), durationMillis = 100 ) } val lastTotal = rule.runOnIdle { assertThat(total).isGreaterThan(0) total } rule.onNodeWithTag(scrollableBoxTag).performTouchInput { this.swipe( start = this.center, end = Offset(this.center.x + 100f, this.center.y), durationMillis = 100 ) } rule.runOnIdle { assertThat(total).isEqualTo(lastTotal) } rule.onNodeWithTag(scrollableBoxTag).performTouchInput { this.swipe( start = this.center, end = Offset(this.center.x, this.center.y - 100f), durationMillis = 100 ) } rule.runOnIdle { assertThat(total).isLessThan(0.01f) } } @OptIn(ExperimentalTestApi::class) @Test fun scrollable_verticalScroll_mouseWheel() { var total = 0f val controller = ScrollableState( consumeScrollDelta = { total += it it } ) setScrollableContent { Modifier.scrollable( state = controller, orientation = Orientation.Vertical ) } rule.onNodeWithTag(scrollableBoxTag).performMouseInput { this.scroll(-100f, ScrollWheel.Vertical) } val lastTotal = rule.runOnIdle { assertThat(total).isGreaterThan(0) total } rule.onNodeWithTag(scrollableBoxTag).performMouseInput { this.scroll(-100f, ScrollWheel.Horizontal) } rule.runOnIdle { assertThat(total).isEqualTo(lastTotal) } rule.onNodeWithTag(scrollableBoxTag).performMouseInput { this.scroll(100f, ScrollWheel.Vertical) } rule.runOnIdle { assertThat(total).isLessThan(0.01f) } } @Test fun scrollable_verticalScroll_reversed() { var total = 0f val controller = ScrollableState( consumeScrollDelta = { total += it it } ) setScrollableContent { Modifier.scrollable( reverseDirection = true, state = controller, orientation = Orientation.Vertical ) } rule.onNodeWithTag(scrollableBoxTag).performTouchInput { this.swipe( start = this.center, end = Offset(this.center.x, this.center.y + 100f), durationMillis = 100 ) } val lastTotal = rule.runOnIdle { assertThat(total).isLessThan(0) total } rule.onNodeWithTag(scrollableBoxTag).performTouchInput { this.swipe( start = this.center, end = Offset(this.center.x + 100f, this.center.y), durationMillis = 100 ) } rule.runOnIdle { assertThat(total).isEqualTo(lastTotal) } rule.onNodeWithTag(scrollableBoxTag).performTouchInput { this.swipe( start = this.center, end = Offset(this.center.x, this.center.y - 100f), durationMillis = 100 ) } rule.runOnIdle { assertThat(total).isLessThan(0.01f) } } @OptIn(ExperimentalTestApi::class) @Test fun scrollable_verticalScroll_reversed_mouseWheel() { var total = 0f val controller = ScrollableState( consumeScrollDelta = { total += it it } ) setScrollableContent { Modifier.scrollable( reverseDirection = true, state = controller, orientation = Orientation.Vertical ) } rule.onNodeWithTag(scrollableBoxTag).performMouseInput { this.scroll(-100f, ScrollWheel.Vertical) } val lastTotal = rule.runOnIdle { assertThat(total).isLessThan(0) total } rule.onNodeWithTag(scrollableBoxTag).performMouseInput { this.scroll(-100f, ScrollWheel.Horizontal) } rule.runOnIdle { assertThat(total).isEqualTo(lastTotal) } rule.onNodeWithTag(scrollableBoxTag).performMouseInput { this.scroll(100f, ScrollWheel.Vertical) } rule.runOnIdle { assertThat(total).isLessThan(0.01f) } } @Test fun scrollable_disabledWontCallLambda() { val enabled = mutableStateOf(true) var total = 0f val controller = ScrollableState( consumeScrollDelta = { total += it it } ) setScrollableContent { Modifier.scrollable( state = controller, orientation = Orientation.Horizontal, enabled = enabled.value ) } rule.onNodeWithTag(scrollableBoxTag).performTouchInput { this.swipe( start = this.center, end = Offset(this.center.x + 100f, this.center.y), durationMillis = 100 ) } val prevTotal = rule.runOnIdle { assertThat(total).isGreaterThan(0f) enabled.value = false total } rule.onNodeWithTag(scrollableBoxTag).performTouchInput { this.swipe( start = this.center, end = Offset(this.center.x + 100f, this.center.y), durationMillis = 100 ) } rule.runOnIdle { assertThat(total).isEqualTo(prevTotal) } } @Test fun scrollable_startWithoutSlop_ifFlinging() { rule.mainClock.autoAdvance = false var total = 0f val controller = ScrollableState( consumeScrollDelta = { total += it it } ) setScrollableContent { Modifier.scrollable( state = controller, orientation = Orientation.Horizontal ) } rule.onNodeWithTag(scrollableBoxTag).performTouchInput { swipeWithVelocity( start = this.center, end = Offset(this.center.x + 200f, this.center.y), durationMillis = 100, endVelocity = 4000f ) } assertThat(total).isGreaterThan(0f) val prev = total // pump frames twice to start fling animation rule.mainClock.advanceTimeByFrame() rule.mainClock.advanceTimeByFrame() val prevAfterSomeFling = total assertThat(prevAfterSomeFling).isGreaterThan(prev) // don't advance main clock anymore since we're in the middle of the fling. Now interrupt rule.onNodeWithTag(scrollableBoxTag).performTouchInput { down(this.center) moveBy(Offset(115f, 0f)) up() } val expected = prevAfterSomeFling + 115 assertThat(total).isEqualTo(expected) } @Test fun scrollable_blocksDownEvents_ifFlingingCaught() { rule.mainClock.autoAdvance = false var total = 0f val controller = ScrollableState( consumeScrollDelta = { total += it it } ) rule.setContent { Box { Box( contentAlignment = Alignment.Center, modifier = Modifier .size(300.dp) .scrollable( orientation = Orientation.Horizontal, state = controller ) ) { Box( modifier = Modifier .size(300.dp) .testTag(scrollableBoxTag) .clickable { assertWithMessage("Clickable shouldn't click when fling caught") .fail() } ) } } } rule.onNodeWithTag(scrollableBoxTag).performTouchInput { swipeWithVelocity( start = this.center, end = Offset(this.center.x + 200f, this.center.y), durationMillis = 100, endVelocity = 4000f ) } assertThat(total).isGreaterThan(0f) val prev = total // pump frames twice to start fling animation rule.mainClock.advanceTimeByFrame() rule.mainClock.advanceTimeByFrame() val prevAfterSomeFling = total assertThat(prevAfterSomeFling).isGreaterThan(prev) // don't advance main clock anymore since we're in the middle of the fling. Now interrupt rule.onNodeWithTag(scrollableBoxTag).performTouchInput { down(this.center) up() } // shouldn't assert in clickable lambda } @Test fun scrollable_snappingScrolling() { var total = 0f val controller = ScrollableState( consumeScrollDelta = { total += it it } ) setScrollableContent { Modifier.scrollable( orientation = Orientation.Vertical, state = controller ) } rule.waitForIdle() assertThat(total).isEqualTo(0f) scope.launch { controller.animateScrollBy(1000f) } rule.waitForIdle() assertThat(total).isWithin(0.001f).of(1000f) scope.launch { controller.animateScrollBy(-200f) } rule.waitForIdle() assertThat(total).isWithin(0.001f).of(800f) } @Test fun scrollable_explicitDisposal() { rule.mainClock.autoAdvance = false val emit = mutableStateOf(true) val expectEmission = mutableStateOf(true) var total = 0f val controller = ScrollableState( consumeScrollDelta = { assertWithMessage("Animating after dispose!").that(expectEmission.value).isTrue() total += it it } ) setScrollableContent { if (emit.value) { Modifier.scrollable( orientation = Orientation.Horizontal, state = controller ) } else { Modifier } } rule.onNodeWithTag(scrollableBoxTag).performTouchInput { this.swipeWithVelocity( start = this.center, end = Offset(this.center.x + 200f, this.center.y), durationMillis = 100, endVelocity = 4000f ) } assertThat(total).isGreaterThan(0f) // start the fling for a few frames rule.mainClock.advanceTimeByFrame() rule.mainClock.advanceTimeByFrame() // flip the emission rule.runOnUiThread { emit.value = false } // propagate the emit flip and record the value rule.mainClock.advanceTimeByFrame() val prevTotal = total // make sure we don't receive any deltas rule.runOnUiThread { expectEmission.value = false } // pump the clock until idle rule.mainClock.autoAdvance = true rule.waitForIdle() // still same and didn't fail in onScrollConsumptionRequested.. lambda assertThat(total).isEqualTo(prevTotal) } @Test fun scrollable_nestedDrag() { var innerDrag = 0f var outerDrag = 0f val outerState = ScrollableState( consumeScrollDelta = { outerDrag += it it } ) val innerState = ScrollableState( consumeScrollDelta = { innerDrag += it / 2 it / 2 } ) rule.setContentAndGetScope { Box { Box( contentAlignment = Alignment.Center, modifier = Modifier .size(300.dp) .scrollable( state = outerState, orientation = Orientation.Horizontal ) ) { Box( modifier = Modifier .testTag(scrollableBoxTag) .size(300.dp) .scrollable( state = innerState, orientation = Orientation.Horizontal ) ) } } } rule.onNodeWithTag(scrollableBoxTag).performTouchInput { this.swipeWithVelocity( start = this.center, end = Offset(this.center.x + 200f, this.center.y), durationMillis = 300, endVelocity = 0f ) } val lastEqualDrag = rule.runOnIdle { assertThat(innerDrag).isGreaterThan(0f) assertThat(outerDrag).isGreaterThan(0f) // we consumed half delta in child, so exactly half should go to the parent assertThat(outerDrag).isEqualTo(innerDrag) innerDrag } rule.runOnIdle { // values should be the same since no fling assertThat(innerDrag).isEqualTo(lastEqualDrag) assertThat(outerDrag).isEqualTo(lastEqualDrag) } } @OptIn(ExperimentalTestApi::class) @Test fun scrollable_nestedScroll_disabledForMouseWheel() { var innerDrag = 0f var outerDrag = 0f val outerState = ScrollableState( consumeScrollDelta = { outerDrag += it it } ) val innerState = ScrollableState( consumeScrollDelta = { innerDrag += it / 2 it / 2 } ) rule.setContentAndGetScope { Box { Box( contentAlignment = Alignment.Center, modifier = Modifier .size(300.dp) .scrollable( state = outerState, orientation = Orientation.Horizontal ) ) { Box( modifier = Modifier .testTag(scrollableBoxTag) .size(300.dp) .scrollable( state = innerState, orientation = Orientation.Horizontal ) ) } } } rule.onNodeWithTag(scrollableBoxTag).performMouseInput { this.scroll(-200f, ScrollWheel.Horizontal) } rule.runOnIdle { assertThat(innerDrag).isGreaterThan(0f) assertThat(outerDrag).isZero() innerDrag } } @Test fun scrollable_nestedFling() { var innerDrag = 0f var outerDrag = 0f val outerState = ScrollableState( consumeScrollDelta = { outerDrag += it it } ) val innerState = ScrollableState( consumeScrollDelta = { innerDrag += it / 2 it / 2 } ) rule.setContentAndGetScope { Box { Box( contentAlignment = Alignment.Center, modifier = Modifier .size(300.dp) .scrollable( state = outerState, orientation = Orientation.Horizontal ) ) { Box( modifier = Modifier .testTag(scrollableBoxTag) .size(300.dp) .scrollable( state = innerState, orientation = Orientation.Horizontal ) ) } } } // swipe again with velocity rule.onNodeWithTag(scrollableBoxTag).performTouchInput { this.swipe( start = this.center, end = Offset(this.center.x + 200f, this.center.y), durationMillis = 300 ) } assertThat(innerDrag).isGreaterThan(0f) assertThat(outerDrag).isGreaterThan(0f) // we consumed half delta in child, so exactly half should go to the parent assertThat(outerDrag).isEqualTo(innerDrag) val lastEqualDrag = innerDrag rule.runOnIdle { assertThat(innerDrag).isGreaterThan(lastEqualDrag) assertThat(outerDrag).isGreaterThan(lastEqualDrag) } } @Test fun scrollable_nestedScrollAbove_respectsPreConsumption() { var value = 0f var lastReceivedPreScrollAvailable = 0f val preConsumeFraction = 0.7f val controller = ScrollableState( consumeScrollDelta = { val expected = lastReceivedPreScrollAvailable * (1 - preConsumeFraction) assertThat(it - expected).isWithin(0.01f) value += it it } ) val preConsumingParent = object : NestedScrollConnection { override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset { lastReceivedPreScrollAvailable = available.x return available * preConsumeFraction } override suspend fun onPreFling(available: Velocity): Velocity { // consume all velocity return available } } rule.setContentAndGetScope { Box { Box( contentAlignment = Alignment.Center, modifier = Modifier .size(300.dp) .nestedScroll(preConsumingParent) ) { Box( modifier = Modifier .size(300.dp) .testTag(scrollableBoxTag) .scrollable( state = controller, orientation = Orientation.Horizontal ) ) } } } rule.onNodeWithTag(scrollableBoxTag).performTouchInput { this.swipe( start = this.center, end = Offset(this.center.x + 200f, this.center.y), durationMillis = 300 ) } val preFlingValue = rule.runOnIdle { value } rule.runOnIdle { // if scrollable respects pre-fling consumption, it should fling 0px since we // pre-consume all assertThat(preFlingValue).isEqualTo(value) } } @Test fun scrollable_nestedScrollAbove_proxiesPostCycles() { var value = 0f var expectedLeft = 0f val velocityFlung = 5000f val controller = ScrollableState( consumeScrollDelta = { val toConsume = it * 0.345f value += toConsume expectedLeft = it - toConsume toConsume } ) val parent = object : NestedScrollConnection { override fun onPostScroll( consumed: Offset, available: Offset, source: NestedScrollSource ): Offset { // we should get in post scroll as much as left in controller callback assertThat(available.x).isEqualTo(expectedLeft) return if (source == NestedScrollSource.Fling) Offset.Zero else available } override suspend fun onPostFling( consumed: Velocity, available: Velocity ): Velocity { val expected = velocityFlung - consumed.x assertThat(consumed.x).isLessThan(velocityFlung) assertThat(abs(available.x - expected)).isLessThan(0.1f) return available } } rule.setContentAndGetScope { Box { Box( contentAlignment = Alignment.Center, modifier = Modifier .size(300.dp) .nestedScroll(parent) ) { Box( modifier = Modifier .size(300.dp) .testTag(scrollableBoxTag) .scrollable( state = controller, orientation = Orientation.Horizontal ) ) } } } rule.onNodeWithTag(scrollableBoxTag).performTouchInput { this.swipeWithVelocity( start = this.center, end = Offset(this.center.x + 500f, this.center.y), durationMillis = 300, endVelocity = velocityFlung ) } // all assertions in callback above rule.waitForIdle() } @Test fun scrollable_nestedScrollAbove_reversed_proxiesPostCycles() { var value = 0f var expectedLeft = 0f val velocityFlung = 5000f val controller = ScrollableState( consumeScrollDelta = { val toConsume = it * 0.345f value += toConsume expectedLeft = it - toConsume toConsume } ) val parent = object : NestedScrollConnection { override fun onPostScroll( consumed: Offset, available: Offset, source: NestedScrollSource ): Offset { // we should get in post scroll as much as left in controller callback assertThat(available.x).isEqualTo(-expectedLeft) return if (source == NestedScrollSource.Fling) Offset.Zero else available } override suspend fun onPostFling( consumed: Velocity, available: Velocity ): Velocity { val expected = velocityFlung - consumed.x assertThat(consumed.x).isLessThan(velocityFlung) assertThat(abs(available.x - expected)).isLessThan(0.1f) return available } } rule.setContentAndGetScope { Box { Box( contentAlignment = Alignment.Center, modifier = Modifier .size(300.dp) .nestedScroll(parent) ) { Box( modifier = Modifier .size(300.dp) .testTag(scrollableBoxTag) .scrollable( state = controller, reverseDirection = true, orientation = Orientation.Horizontal ) ) } } } rule.onNodeWithTag(scrollableBoxTag).performTouchInput { this.swipeWithVelocity( start = this.center, end = Offset(this.center.x + 500f, this.center.y), durationMillis = 300, endVelocity = velocityFlung ) } // all assertions in callback above rule.waitForIdle() } @Test fun scrollable_nestedScrollBelow_listensDispatches() { var value = 0f var expectedConsumed = 0f val controller = ScrollableState( consumeScrollDelta = { expectedConsumed = it * 0.3f value += expectedConsumed expectedConsumed } ) val child = object : NestedScrollConnection {} val dispatcher = NestedScrollDispatcher() rule.setContentAndGetScope { Box { Box( modifier = Modifier .size(300.dp) .scrollable( state = controller, orientation = Orientation.Horizontal ) ) { Box( Modifier .size(200.dp) .testTag(scrollableBoxTag) .nestedScroll(child, dispatcher) ) } } } val lastValueBeforeFling = rule.runOnIdle { val preScrollConsumed = dispatcher .dispatchPreScroll(Offset(20f, 20f), NestedScrollSource.Drag) // scrollable is not interested in pre scroll assertThat(preScrollConsumed).isEqualTo(Offset.Zero) val consumed = dispatcher.dispatchPostScroll( Offset(20f, 20f), Offset(50f, 50f), NestedScrollSource.Drag ) assertThat(consumed.x - expectedConsumed).isWithin(0.001f) value } scope.launch { val preFlingConsumed = dispatcher.dispatchPreFling(Velocity(50f, 50f)) // scrollable won't participate in the pre fling assertThat(preFlingConsumed).isEqualTo(Velocity.Zero) } rule.waitForIdle() scope.launch { dispatcher.dispatchPostFling( Velocity(1000f, 1000f), Velocity(2000f, 2000f) ) } rule.runOnIdle { // catch that scrollable caught our post fling and flung assertThat(value).isGreaterThan(lastValueBeforeFling) } } @Test fun scrollable_nestedScroll_allowParentWhenDisabled() { var childValue = 0f var parentValue = 0f val childController = ScrollableState( consumeScrollDelta = { childValue += it it } ) val parentController = ScrollableState( consumeScrollDelta = { parentValue += it it } ) rule.setContentAndGetScope { Box { Box( modifier = Modifier .size(300.dp) .scrollable( state = parentController, orientation = Orientation.Horizontal ) ) { Box( Modifier .size(200.dp) .testTag(scrollableBoxTag) .scrollable( enabled = false, orientation = Orientation.Horizontal, state = childController ) ) } } } rule.runOnIdle { assertThat(parentValue).isEqualTo(0f) assertThat(childValue).isEqualTo(0f) } rule.onNodeWithTag(scrollableBoxTag) .performTouchInput { swipe(center, center.copy(x = center.x + 100f)) } rule.runOnIdle { assertThat(childValue).isEqualTo(0f) assertThat(parentValue).isGreaterThan(0f) } } @Test fun scrollable_nestedScroll_disabledConnectionNoOp() { var childValue = 0f var parentValue = 0f var selfValue = 0f val childController = ScrollableState( consumeScrollDelta = { childValue += it / 2 it / 2 } ) val middleController = ScrollableState( consumeScrollDelta = { selfValue += it / 2 it / 2 } ) val parentController = ScrollableState( consumeScrollDelta = { parentValue += it / 2 it / 2 } ) rule.setContentAndGetScope { Box { Box( modifier = Modifier .size(300.dp) .scrollable( state = parentController, orientation = Orientation.Horizontal ) ) { Box( Modifier .size(200.dp) .scrollable( enabled = false, orientation = Orientation.Horizontal, state = middleController ) ) { Box( Modifier .size(200.dp) .testTag(scrollableBoxTag) .scrollable( orientation = Orientation.Horizontal, state = childController ) ) } } } } rule.runOnIdle { assertThat(parentValue).isEqualTo(0f) assertThat(selfValue).isEqualTo(0f) assertThat(childValue).isEqualTo(0f) } rule.onNodeWithTag(scrollableBoxTag) .performTouchInput { swipe(center, center.copy(x = center.x + 100f)) } rule.runOnIdle { assertThat(childValue).isGreaterThan(0f) // disabled middle node doesn't consume assertThat(selfValue).isEqualTo(0f) // but allow nested scroll to propagate up correctly assertThat(parentValue).isGreaterThan(0f) } } @Test fun scrollable_bothOrientations_proxiesPostFling() { val velocityFlung = 5000f val outerState = ScrollableState(consumeScrollDelta = { 0f }) val innerState = ScrollableState(consumeScrollDelta = { 0f }) val innerFlingBehavior = object : FlingBehavior { override suspend fun ScrollScope.performFling(initialVelocity: Float): Float { return initialVelocity } } val parent = object : NestedScrollConnection { override suspend fun onPostFling( consumed: Velocity, available: Velocity ): Velocity { assertThat(consumed.x).isEqualTo(0f) assertThat(available.x).isWithin(0.1f).of(velocityFlung) return available } } rule.setContentAndGetScope { Box { Box( contentAlignment = Alignment.Center, modifier = Modifier .size(300.dp) .nestedScroll(parent) .scrollable( state = outerState, orientation = Orientation.Vertical ) ) { Box( modifier = Modifier .size(300.dp) .testTag(scrollableBoxTag) .scrollable( state = innerState, flingBehavior = innerFlingBehavior, orientation = Orientation.Horizontal ) ) } } } rule.onNodeWithTag(scrollableBoxTag).performTouchInput { this.swipeWithVelocity( start = this.center, end = Offset(this.center.x + 500f, this.center.y), durationMillis = 300, endVelocity = velocityFlung ) } // all assertions in callback above rule.waitForIdle() } @Test fun scrollable_interactionSource() { val interactionSource = MutableInteractionSource() var total = 0f val controller = ScrollableState( consumeScrollDelta = { total += it it } ) setScrollableContent { Modifier.scrollable( interactionSource = interactionSource, orientation = Orientation.Horizontal, state = controller ) } val interactions = mutableListOf<Interaction>() scope.launch { interactionSource.interactions.collect { interactions.add(it) } } rule.runOnIdle { assertThat(interactions).isEmpty() } rule.onNodeWithTag(scrollableBoxTag) .performTouchInput { down(Offset(visibleSize.width / 4f, visibleSize.height / 2f)) moveBy(Offset(visibleSize.width / 2f, 0f)) } rule.runOnIdle { assertThat(interactions).hasSize(1) assertThat(interactions.first()).isInstanceOf(DragInteraction.Start::class.java) } rule.onNodeWithTag(scrollableBoxTag) .performTouchInput { up() } rule.runOnIdle { assertThat(interactions).hasSize(2) assertThat(interactions.first()).isInstanceOf(DragInteraction.Start::class.java) assertThat(interactions[1]).isInstanceOf(DragInteraction.Stop::class.java) assertThat((interactions[1] as DragInteraction.Stop).start) .isEqualTo(interactions[0]) } } @Test fun scrollable_interactionSource_resetWhenDisposed() { val interactionSource = MutableInteractionSource() var emitScrollableBox by mutableStateOf(true) var total = 0f val controller = ScrollableState( consumeScrollDelta = { total += it it } ) rule.setContentAndGetScope { Box { if (emitScrollableBox) { Box( modifier = Modifier .testTag(scrollableBoxTag) .size(100.dp) .scrollable( interactionSource = interactionSource, orientation = Orientation.Horizontal, state = controller ) ) } } } val interactions = mutableListOf<Interaction>() scope.launch { interactionSource.interactions.collect { interactions.add(it) } } rule.runOnIdle { assertThat(interactions).isEmpty() } rule.onNodeWithTag(scrollableBoxTag) .performTouchInput { down(Offset(visibleSize.width / 4f, visibleSize.height / 2f)) moveBy(Offset(visibleSize.width / 2f, 0f)) } rule.runOnIdle { assertThat(interactions).hasSize(1) assertThat(interactions.first()).isInstanceOf(DragInteraction.Start::class.java) } // Dispose scrollable rule.runOnIdle { emitScrollableBox = false } rule.runOnIdle { assertThat(interactions).hasSize(2) assertThat(interactions.first()).isInstanceOf(DragInteraction.Start::class.java) assertThat(interactions[1]).isInstanceOf(DragInteraction.Cancel::class.java) assertThat((interactions[1] as DragInteraction.Cancel).start) .isEqualTo(interactions[0]) } } @Test fun scrollable_flingBehaviourCalled_whenVelocity0() { var total = 0f val controller = ScrollableState( consumeScrollDelta = { total += it it } ) var flingCalled = 0 var flingVelocity: Float = Float.MAX_VALUE val flingBehaviour = object : FlingBehavior { override suspend fun ScrollScope.performFling(initialVelocity: Float): Float { flingCalled++ flingVelocity = initialVelocity return 0f } } setScrollableContent { Modifier.scrollable( state = controller, flingBehavior = flingBehaviour, orientation = Orientation.Horizontal ) } rule.onNodeWithTag(scrollableBoxTag).performTouchInput { down(this.center) moveBy(Offset(115f, 0f)) up() } assertThat(flingCalled).isEqualTo(1) assertThat(flingVelocity).isLessThan(0.01f) assertThat(flingVelocity).isGreaterThan(-0.01f) } @Test fun scrollable_flingBehaviourCalled() { var total = 0f val controller = ScrollableState( consumeScrollDelta = { total += it it } ) var flingCalled = 0 var flingVelocity: Float = Float.MAX_VALUE val flingBehaviour = object : FlingBehavior { override suspend fun ScrollScope.performFling(initialVelocity: Float): Float { flingCalled++ flingVelocity = initialVelocity return 0f } } setScrollableContent { Modifier.scrollable( state = controller, flingBehavior = flingBehaviour, orientation = Orientation.Horizontal ) } rule.onNodeWithTag(scrollableBoxTag).performTouchInput { swipeWithVelocity( this.center, this.center + Offset(115f, 0f), endVelocity = 1000f ) } assertThat(flingCalled).isEqualTo(1) assertThat(flingVelocity).isWithin(5f).of(1000f) } @Test fun scrollable_flingBehaviourCalled_reversed() { var total = 0f val controller = ScrollableState( consumeScrollDelta = { total += it it } ) var flingCalled = 0 var flingVelocity: Float = Float.MAX_VALUE val flingBehaviour = object : FlingBehavior { override suspend fun ScrollScope.performFling(initialVelocity: Float): Float { flingCalled++ flingVelocity = initialVelocity return 0f } } setScrollableContent { Modifier.scrollable( state = controller, reverseDirection = true, flingBehavior = flingBehaviour, orientation = Orientation.Horizontal ) } rule.onNodeWithTag(scrollableBoxTag).performTouchInput { swipeWithVelocity( this.center, this.center + Offset(115f, 0f), endVelocity = 1000f ) } assertThat(flingCalled).isEqualTo(1) assertThat(flingVelocity).isWithin(5f).of(-1000f) } @Test fun scrollable_flingBehaviourCalled_correctScope() { var total = 0f var returned = 0f val controller = ScrollableState( consumeScrollDelta = { total += it it } ) val flingBehaviour = object : FlingBehavior { override suspend fun ScrollScope.performFling(initialVelocity: Float): Float { returned = scrollBy(123f) return 0f } } setScrollableContent { Modifier.scrollable( state = controller, flingBehavior = flingBehaviour, orientation = Orientation.Horizontal ) } rule.onNodeWithTag(scrollableBoxTag).performTouchInput { down(center) moveBy(Offset(x = 100f, y = 0f)) } val prevTotal = rule.runOnIdle { assertThat(total).isGreaterThan(0f) total } rule.onNodeWithTag(scrollableBoxTag).performTouchInput { up() } rule.runOnIdle { assertThat(total).isEqualTo(prevTotal + 123) assertThat(returned).isEqualTo(123f) } } @Test fun scrollable_flingBehaviourCalled_reversed_correctScope() { var total = 0f var returned = 0f val controller = ScrollableState( consumeScrollDelta = { total += it it } ) val flingBehaviour = object : FlingBehavior { override suspend fun ScrollScope.performFling(initialVelocity: Float): Float { returned = scrollBy(123f) return 0f } } setScrollableContent { Modifier.scrollable( state = controller, reverseDirection = true, flingBehavior = flingBehaviour, orientation = Orientation.Horizontal ) } rule.onNodeWithTag(scrollableBoxTag).performTouchInput { down(center) moveBy(Offset(x = 100f, y = 0f)) } val prevTotal = rule.runOnIdle { assertThat(total).isLessThan(0f) total } rule.onNodeWithTag(scrollableBoxTag).performTouchInput { up() } rule.runOnIdle { assertThat(total).isEqualTo(prevTotal + 123) assertThat(returned).isEqualTo(123f) } } @Test fun scrollable_setsModifierLocalScrollableContainer() { val controller = ScrollableState { it } var isOuterInVerticalScrollableContainer: Boolean? = null var isInnerInVerticalScrollableContainer: Boolean? = null var isOuterInHorizontalScrollableContainer: Boolean? = null var isInnerInHorizontalScrollableContainer: Boolean? = null rule.setContent { Box { Box( modifier = Modifier .testTag(scrollableBoxTag) .size(100.dp) .consumeScrollContainerInfo { isOuterInVerticalScrollableContainer = it?.canScrollVertically() isOuterInHorizontalScrollableContainer = it?.canScrollHorizontally() } .scrollable( state = controller, orientation = Orientation.Horizontal ) .consumeScrollContainerInfo { isInnerInHorizontalScrollableContainer = it?.canScrollHorizontally() isInnerInVerticalScrollableContainer = it?.canScrollVertically() } ) } } rule.runOnIdle { assertThat(isInnerInHorizontalScrollableContainer).isTrue() assertThat(isInnerInVerticalScrollableContainer).isFalse() assertThat(isOuterInVerticalScrollableContainer).isFalse() assertThat(isOuterInHorizontalScrollableContainer).isFalse() } } @Test fun scrollable_nested_setsModifierLocalScrollableContainer() { val horizontalController = ScrollableState { it } val verticalController = ScrollableState { it } var horizontalDrag: Boolean? = null var verticalDrag: Boolean? = null rule.setContent { Box( modifier = Modifier .size(100.dp) .scrollable( state = horizontalController, orientation = Orientation.Horizontal ) ) { Box( modifier = Modifier .size(100.dp) .scrollable( state = verticalController, orientation = Orientation.Vertical ) .consumeScrollContainerInfo { horizontalDrag = it?.canScrollHorizontally() verticalDrag = it?.canScrollVertically() }) } } rule.runOnIdle { assertThat(horizontalDrag).isTrue() assertThat(verticalDrag).isTrue() } } @Test fun scrollable_scrollByWorksWithRepeatableAnimations() { rule.mainClock.autoAdvance = false var total = 0f val controller = ScrollableState( consumeScrollDelta = { total += it it } ) rule.setContentAndGetScope { Box( modifier = Modifier .size(100.dp) .scrollable( state = controller, orientation = Orientation.Horizontal ) ) } rule.runOnIdle { scope.launch { controller.animateScrollBy( 100f, keyframes { durationMillis = 2500 // emulate a repeatable animation: 0f at 0 100f at 500 100f at 1000 0f at 1500 0f at 2000 100f at 2500 } ) } } rule.mainClock.advanceTimeBy(250) rule.runOnIdle { // in the middle of the first animation assertThat(total).isGreaterThan(0f) assertThat(total).isLessThan(100f) } rule.mainClock.advanceTimeBy(500) // 750 ms rule.runOnIdle { // first animation finished assertThat(total).isEqualTo(100) } rule.mainClock.advanceTimeBy(250) // 1250 ms rule.runOnIdle { // in the middle of the second animation assertThat(total).isGreaterThan(0f) assertThat(total).isLessThan(100f) } rule.mainClock.advanceTimeBy(500) // 1750 ms rule.runOnIdle { // second animation finished assertThat(total).isEqualTo(0) } rule.mainClock.advanceTimeBy(500) // 2250 ms rule.runOnIdle { // in the middle of the third animation assertThat(total).isGreaterThan(0f) assertThat(total).isLessThan(100f) } rule.mainClock.advanceTimeBy(500) // 2750 ms rule.runOnIdle { // third animation finished assertThat(total).isEqualTo(100) } } @Test fun scrollable_cancellingAnimateScrollUpdatesIsScrollInProgress() { rule.mainClock.autoAdvance = false var total = 0f val controller = ScrollableState( consumeScrollDelta = { total += it it } ) rule.setContentAndGetScope { Box( modifier = Modifier .size(100.dp) .scrollable( state = controller, orientation = Orientation.Horizontal ) ) } lateinit var animateJob: Job rule.runOnIdle { animateJob = scope.launch { controller.animateScrollBy( 100f, tween(1000) ) } } rule.mainClock.advanceTimeBy(500) rule.runOnIdle { assertThat(controller.isScrollInProgress).isTrue() } // Stop halfway through the animation animateJob.cancel() rule.runOnIdle { assertThat(controller.isScrollInProgress).isFalse() } } @Test fun scrollable_preemptingAnimateScrollUpdatesIsScrollInProgress() { rule.mainClock.autoAdvance = false var total = 0f val controller = ScrollableState( consumeScrollDelta = { total += it it } ) rule.setContentAndGetScope { Box( modifier = Modifier .size(100.dp) .scrollable( state = controller, orientation = Orientation.Horizontal ) ) } rule.runOnIdle { scope.launch { controller.animateScrollBy( 100f, tween(1000) ) } } rule.mainClock.advanceTimeBy(500) rule.runOnIdle { assertThat(total).isGreaterThan(0f) assertThat(total).isLessThan(100f) assertThat(controller.isScrollInProgress).isTrue() scope.launch { controller.animateScrollBy( -100f, tween(1000) ) } } rule.runOnIdle { assertThat(controller.isScrollInProgress).isTrue() } rule.mainClock.advanceTimeBy(1000) rule.mainClock.advanceTimeByFrame() rule.runOnIdle { assertThat(total).isGreaterThan(-75f) assertThat(total).isLessThan(0f) assertThat(controller.isScrollInProgress).isFalse() } } @Test fun scrollable_multiDirectionsShouldPropagateOrthogonalAxisToNextParentWithSameDirection() { var innerDelta = 0f var middleDelta = 0f var outerDelta = 0f val outerStateController = ScrollableState { outerDelta += it it } val middleController = ScrollableState { middleDelta += it it / 2 } val innerController = ScrollableState { innerDelta += it it / 2 } rule.setContentAndGetScope { Box( modifier = Modifier .testTag("outerScrollable") .size(300.dp) .scrollable( outerStateController, orientation = Orientation.Horizontal ) ) { Box( modifier = Modifier .testTag("middleScrollable") .size(300.dp) .scrollable( middleController, orientation = Orientation.Vertical ) ) { Box( modifier = Modifier .testTag("innerScrollable") .size(300.dp) .scrollable( innerController, orientation = Orientation.Horizontal ) ) } } } rule.onNodeWithTag("innerScrollable").performTouchInput { down(center) moveBy(Offset(100f, 0f)) up() } rule.runOnIdle { assertThat(innerDelta).isGreaterThan(0) assertThat(middleDelta).isEqualTo(0) assertThat(outerDelta).isEqualTo(innerDelta / 2f) } } @Test fun nestedScrollable_shouldImmediateScrollIfChildIsFlinging() { var innerDelta = 0f var middleDelta = 0f var outerDelta = 0f var touchSlop = 0f val outerStateController = ScrollableState { outerDelta += it 0f } val middleController = ScrollableState { middleDelta += it 0f } val innerController = ScrollableState { innerDelta += it it / 2f } rule.setContentAndGetScope { touchSlop = LocalViewConfiguration.current.touchSlop Box( modifier = Modifier .testTag("outerScrollable") .size(600.dp) .background(Color.Red) .scrollable( outerStateController, orientation = Orientation.Vertical ), contentAlignment = Alignment.BottomStart ) { Box( modifier = Modifier .testTag("middleScrollable") .size(300.dp) .background(Color.Blue) .scrollable( middleController, orientation = Orientation.Vertical ), contentAlignment = Alignment.BottomStart ) { Box( modifier = Modifier .testTag("innerScrollable") .size(50.dp) .background(Color.Yellow) .scrollable( innerController, orientation = Orientation.Vertical ) ) } } } rule.mainClock.autoAdvance = false rule.onNodeWithTag("innerScrollable").performTouchInput { swipeUp() } rule.mainClock.advanceTimeByFrame() rule.mainClock.advanceTimeByFrame() val previousOuter = outerDelta rule.onNodeWithTag("outerScrollable").performTouchInput { down(topCenter) // Move less than touch slop, should start immediately moveBy(Offset(0f, touchSlop / 2)) } rule.mainClock.autoAdvance = true rule.runOnIdle { assertThat(outerDelta).isEqualTo(previousOuter + touchSlop / 2) } } // b/179417109 Double checks that in a nested scroll cycle, the parent post scroll // consumption is taken into consideration. @Test fun dispatchScroll_shouldReturnConsumedDeltaInNestedScrollChain() { var consumedInner = 0f var consumedOuter = 0f var touchSlop = 0f var preScrollAvailable = Offset.Zero var consumedPostScroll = Offset.Zero var postScrollAvailable = Offset.Zero val outerStateController = ScrollableState { consumedOuter += it it } val innerController = ScrollableState { consumedInner += it / 2 it / 2 } val connection = object : NestedScrollConnection { override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset { preScrollAvailable += available return Offset.Zero } override fun onPostScroll( consumed: Offset, available: Offset, source: NestedScrollSource ): Offset { consumedPostScroll += consumed postScrollAvailable += available return Offset.Zero } } rule.setContent { touchSlop = LocalViewConfiguration.current.touchSlop Box(modifier = Modifier.nestedScroll(connection)) { Box( modifier = Modifier .testTag("outerScrollable") .size(300.dp) .scrollable( outerStateController, orientation = Orientation.Horizontal ) ) { Box( modifier = Modifier .testTag("innerScrollable") .size(300.dp) .scrollable( innerController, orientation = Orientation.Horizontal ) ) } } } val scrollDelta = 200f rule.onRoot().performTouchInput { down(center) moveBy(Offset(scrollDelta, 0f)) up() } rule.runOnIdle { assertThat(consumedInner).isGreaterThan(0) assertThat(consumedOuter).isGreaterThan(0) assertThat(touchSlop).isGreaterThan(0) assertThat(postScrollAvailable.x).isEqualTo(0f) assertThat(consumedPostScroll.x).isEqualTo(scrollDelta - touchSlop) assertThat(preScrollAvailable.x).isEqualTo(scrollDelta - touchSlop) assertThat(scrollDelta).isEqualTo(consumedInner + consumedOuter + touchSlop) } } @Test fun testInspectorValue() { val controller = ScrollableState( consumeScrollDelta = { it } ) rule.setContentAndGetScope { val modifier = Modifier.scrollable(controller, Orientation.Vertical) as InspectableValue assertThat(modifier.nameFallback).isEqualTo("scrollable") assertThat(modifier.valueOverride).isNull() assertThat(modifier.inspectableElements.map { it.name }.asIterable()).containsExactly( "orientation", "state", "overscrollEffect", "enabled", "reverseDirection", "flingBehavior", "interactionSource", ) } } @OptIn(ExperimentalFoundationApi::class) @Test fun producingEqualMaterializedModifierAfterRecomposition() { val state = ScrollableState { it } val counter = mutableStateOf(0) var materialized: Modifier? = null rule.setContent { counter.value // just to trigger recomposition materialized = currentComposer.materialize( Modifier.scrollable( state, Orientation.Vertical, NoOpOverscrollEffect ) ) } lateinit var first: Modifier rule.runOnIdle { first = requireNotNull(materialized) materialized = null counter.value++ } rule.runOnIdle { val second = requireNotNull(materialized) assertThat(first).isEqualTo(second) } } @Test fun focusStaysInScrollableEvenThoughThereIsACloserItemOutside() { lateinit var focusManager: FocusManager val initialFocus = FocusRequester() var nextItemIsFocused = false rule.setContent { focusManager = LocalFocusManager.current Column { Column( Modifier .size(10.dp) .verticalScroll(rememberScrollState()) ) { Box( Modifier .size(10.dp) .focusRequester(initialFocus) .focusable() ) Box(Modifier.size(10.dp)) Box( Modifier .size(10.dp) .onFocusChanged { nextItemIsFocused = it.isFocused } .focusable()) } Box( Modifier .size(10.dp) .focusable() ) } } rule.runOnIdle { initialFocus.requestFocus() } rule.runOnIdle { focusManager.moveFocus(FocusDirection.Down) } rule.runOnIdle { assertThat(nextItemIsFocused).isTrue() } } @Test fun verticalScrollable_assertVelocityCalculationIsSimilarInsideOutsideVelocityTracker() { // arrange val tracker = VelocityTracker() var velocity = Velocity.Zero val capturingScrollConnection = object : NestedScrollConnection { override suspend fun onPreFling(available: Velocity): Velocity { velocity += available return Velocity.Zero } } val controller = ScrollableState { _ -> 0f } setScrollableContent { Modifier .pointerInput(Unit) { savePointerInputEvents(tracker, this) } .nestedScroll(capturingScrollConnection) .scrollable(controller, Orientation.Vertical) } // act rule.onNodeWithTag(scrollableBoxTag).performTouchInput { swipeUp() } // assert rule.runOnIdle { val diff = abs((velocity - tracker.calculateVelocity()).y) assertThat(diff).isLessThan(VelocityTrackerCalculationThreshold) } tracker.resetTracking() velocity = Velocity.Zero // act rule.onNodeWithTag(scrollableBoxTag).performTouchInput { swipeDown() } // assert rule.runOnIdle { val diff = abs((velocity - tracker.calculateVelocity()).y) assertThat(diff).isLessThan(VelocityTrackerCalculationThreshold) } } @Test fun horizontalScrollable_assertVelocityCalculationIsSimilarInsideOutsideVelocityTracker() { // arrange val tracker = VelocityTracker() var velocity = Velocity.Zero val capturingScrollConnection = object : NestedScrollConnection { override suspend fun onPreFling(available: Velocity): Velocity { velocity += available return Velocity.Zero } } val controller = ScrollableState { _ -> 0f } setScrollableContent { Modifier .pointerInput(Unit) { savePointerInputEvents(tracker, this) } .nestedScroll(capturingScrollConnection) .scrollable(controller, Orientation.Horizontal) } // act rule.onNodeWithTag(scrollableBoxTag).performTouchInput { swipeLeft() } // assert rule.runOnIdle { val diff = abs((velocity - tracker.calculateVelocity()).x) assertThat(diff).isLessThan(VelocityTrackerCalculationThreshold) } tracker.resetTracking() velocity = Velocity.Zero // act rule.onNodeWithTag(scrollableBoxTag).performTouchInput { swipeRight() } // assert rule.runOnIdle { val diff = abs((velocity - tracker.calculateVelocity()).x) assertThat(diff).isLessThan(VelocityTrackerCalculationThreshold) } } @Test fun offsetsScrollable_velocityCalculationShouldConsiderLocalPositions() { // arrange var velocity = Velocity.Zero val fullScreen = mutableStateOf(false) lateinit var scrollState: LazyListState val capturingScrollConnection = object : NestedScrollConnection { override suspend fun onPreFling(available: Velocity): Velocity { velocity += available return Velocity.Zero } } rule.setContent { scrollState = rememberLazyListState() Column(modifier = Modifier.nestedScroll(capturingScrollConnection)) { if (!fullScreen.value) { Box( modifier = Modifier .fillMaxWidth() .background(Color.Black) .height(400.dp) ) } LazyColumn(state = scrollState) { items(100) { Box( modifier = Modifier .padding(10.dp) .background(Color.Red) .fillMaxWidth() .height(50.dp) ) } } } } // act // Register generated velocity with offset composeViewSwipeUp() rule.waitForIdle() val previousVelocity = velocity velocity = Velocity.Zero // Remove offset and restart scroll fullScreen.value = true rule.runOnIdle { runBlocking { scrollState.scrollToItem(0) } } rule.waitForIdle() // Register generated velocity without offset, should be larger as there was more // screen to cover. composeViewSwipeUp() // assert rule.runOnIdle { assertThat(abs(previousVelocity.y)).isNotEqualTo(abs(velocity.y)) } } @Test fun disableSystemAnimations_defaultFlingBehaviorShouldContinueToWork() { val controller = ScrollableState { 0f } var defaultFlingBehavior: DefaultFlingBehavior? = null setScrollableContent { defaultFlingBehavior = ScrollableDefaults.flingBehavior() as? DefaultFlingBehavior Modifier.scrollable( state = controller, orientation = Orientation.Horizontal, flingBehavior = defaultFlingBehavior ) } scope.launch { controller.scroll { defaultFlingBehavior?.let { with(it) { performFling(1000f) } } } } rule.runOnIdle { assertThat(defaultFlingBehavior?.lastAnimationCycleCount).isGreaterThan(1) } // Simulate turning of animation scope.launch { controller.scroll { withContext(TestScrollMotionDurationScale(0f)) { defaultFlingBehavior?.let { with(it) { performFling(1000f) } } } } } rule.runOnIdle { assertThat(defaultFlingBehavior?.lastAnimationCycleCount).isGreaterThan(1) } } @Test fun defaultFlingBehavior_useScrollMotionDurationScale() { val controller = ScrollableState { 0f } var defaultFlingBehavior: DefaultFlingBehavior? = null var switchMotionDurationScale by mutableStateOf(true) rule.setContentAndGetScope { val flingSpec: DecayAnimationSpec<Float> = rememberSplineBasedDecay() if (switchMotionDurationScale) { defaultFlingBehavior = DefaultFlingBehavior(flingSpec, TestScrollMotionDurationScale(1f)) Box( modifier = Modifier .testTag(scrollableBoxTag) .size(100.dp) .scrollable( state = controller, orientation = Orientation.Horizontal, flingBehavior = defaultFlingBehavior ) ) } else { defaultFlingBehavior = DefaultFlingBehavior(flingSpec, TestScrollMotionDurationScale(0f)) Box( modifier = Modifier .testTag(scrollableBoxTag) .size(100.dp) .scrollable( state = controller, orientation = Orientation.Horizontal, flingBehavior = defaultFlingBehavior ) ) } } scope.launch { controller.scroll { defaultFlingBehavior?.let { with(it) { performFling(1000f) } } } } rule.runOnIdle { assertThat(defaultFlingBehavior?.lastAnimationCycleCount).isGreaterThan(1) } switchMotionDurationScale = false rule.waitForIdle() scope.launch { controller.scroll { defaultFlingBehavior?.let { with(it) { performFling(1000f) } } } } rule.runOnIdle { assertThat(defaultFlingBehavior?.lastAnimationCycleCount).isEqualTo(1) } } private fun setScrollableContent(scrollableModifierFactory: @Composable () -> Modifier) { rule.setContentAndGetScope { Box { val scrollable = scrollableModifierFactory() Box( modifier = Modifier .testTag(scrollableBoxTag) .size(100.dp) .then(scrollable) ) } } } } @OptIn(ExperimentalFoundationApi::class) private val NoOpOverscrollEffect = object : OverscrollEffect { override fun consumePreScroll( scrollDelta: Offset, source: NestedScrollSource ): Offset = Offset.Zero override fun consumePostScroll( initialDragDelta: Offset, overscrollDelta: Offset, source: NestedScrollSource ) { } override suspend fun consumePreFling(velocity: Velocity): Velocity = Velocity.Zero override suspend fun consumePostFling(velocity: Velocity) {} override val isInProgress: Boolean get() = false override val effectModifier: Modifier get() = Modifier } // Very low tolerance on the difference internal val VelocityTrackerCalculationThreshold = 1 @OptIn(ExperimentalComposeUiApi::class) internal suspend fun savePointerInputEvents( tracker: VelocityTracker, pointerInputScope: PointerInputScope ) { with(pointerInputScope) { coroutineScope { awaitPointerEventScope { while (true) { var event = awaitFirstDown() tracker.addPosition(event.uptimeMillis, event.position) while (!event.changedToUpIgnoreConsumed()) { val currentEvent = awaitPointerEvent().changes .firstOrNull() if (currentEvent != null && !currentEvent.changedToUpIgnoreConsumed()) { currentEvent.historical.fastForEach { tracker.addPosition(it.uptimeMillis, it.position) } tracker.addPosition( currentEvent.uptimeMillis, currentEvent.position ) event = currentEvent } } } } } } } internal fun composeViewSwipeUp() { onView(allOf(instanceOf(AbstractComposeView::class.java))) .perform( espressoSwipe( GeneralLocation.BOTTOM_CENTER, GeneralLocation.CENTER ) ) } internal fun composeViewSwipeDown() { onView(allOf(instanceOf(AbstractComposeView::class.java))) .perform( espressoSwipe( GeneralLocation.CENTER, GeneralLocation.BOTTOM_CENTER ) ) } internal fun composeViewSwipeLeft() { onView(allOf(instanceOf(AbstractComposeView::class.java))) .perform( espressoSwipe( GeneralLocation.CENTER, GeneralLocation.CENTER_LEFT ) ) } internal fun composeViewSwipeRight() { onView(allOf(instanceOf(AbstractComposeView::class.java))) .perform( espressoSwipe( GeneralLocation.CENTER, GeneralLocation.CENTER_RIGHT ) ) } private fun espressoSwipe( start: CoordinatesProvider, end: CoordinatesProvider ): GeneralSwipeAction { return GeneralSwipeAction( Swipe.FAST, start, end, Press.FINGER ) } internal class TestScrollMotionDurationScale(override val scaleFactor: Float) : MotionDurationScale
apache-2.0
888231a8df95a099ba932a4dbe3ef489
31.298232
100
0.518712
6.129032
false
false
false
false
androidx/androidx
health/connect/connect-client/samples/src/main/java/androidx/health/connect/client/samples/AvailabilitySamples.kt
3
1794
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("UNUSED_VARIABLE") package androidx.health.connect.client.samples import android.content.Context import android.content.Intent import android.net.Uri import androidx.annotation.Sampled import androidx.health.connect.client.HealthConnectClient @Sampled suspend fun AvailabilityCheckSamples(context: Context, providerPackageName: String) { if (!HealthConnectClient.isApiSupported()) { return // early return as there is no viable integration } if (!HealthConnectClient.isProviderAvailable(context)) { // Optionally redirect to package installer to find a provider, for example: val uriString = "market://details?id=$providerPackageName&url=healthconnect%3A%2F%2Fonboarding" context.startActivity( Intent(Intent.ACTION_VIEW).apply { setPackage("com.android.vending") data = Uri.parse(uriString) putExtra("overlay", true) putExtra("callerId", context.packageName) } ) return } val healthConnectClient = HealthConnectClient.getOrCreate(context) // Issue operations with healthConnectClient }
apache-2.0
e2ebc8defa1360a15f3122916fdc490e
36.375
91
0.710702
4.6
false
false
false
false
GunoH/intellij-community
plugins/full-line/core/src/org/jetbrains/completion/full/line/language/formatters/PlainTextFormatter.kt
2
512
package org.jetbrains.completion.full.line.language.formatters import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import org.jetbrains.completion.full.line.language.ElementFormatter class PlainTextFormatter : ElementFormatter { override fun condition(element: PsiElement): Boolean = true override fun filter(element: PsiElement): Boolean? = element !is PsiFile && element.firstChild == null && element.text.isNotEmpty() override fun format(element: PsiElement): String = element.text }
apache-2.0
06b67cbd9eb575a59cf400939196a1e1
38.384615
133
0.798828
4.413793
false
false
false
false
PaleoCrafter/VanillaImmersion
src/main/kotlin/de/mineformers/vanillaimmersion/util/vectors.kt
1
5368
@file:JvmName("VectorExtensions") package de.mineformers.vanillaimmersion.util import net.minecraft.util.Rotation import net.minecraft.util.math.AxisAlignedBB import net.minecraft.util.math.BlockPos import net.minecraft.util.math.Vec3d import net.minecraft.util.math.Vec3i import javax.vecmath.AxisAngle4d import javax.vecmath.Matrix4d import javax.vecmath.Vector4d // Various extensions to do with Minecraft's vector types, should be all fairly self explanatory val AxisAlignedBB.min: Vec3d get() = Vec3d(this.minX, this.minY, this.minZ) val AxisAlignedBB.max: Vec3d get() = Vec3d(this.maxX, this.maxY, this.maxZ) fun Vec3d.partOf(box: AxisAlignedBB) = box.minX <= x && x <= box.maxX && box.minY <= y && y <= box.maxY && box.minZ <= z && z <= box.maxZ fun AxisAlignedBB.rotateX(rotation: Rotation) = rotate(Vec3d(1.0, .0, .0), rotation) fun AxisAlignedBB.rotateY(rotation: Rotation) = rotate(Vec3d(.0, 1.0, .0), rotation) fun AxisAlignedBB.rotateZ(rotation: Rotation) = rotate(Vec3d(.0, .0, 1.0), rotation) fun AxisAlignedBB.rotate(axis: Vec3d, rotation: Rotation): AxisAlignedBB { val angle = when (rotation) { Rotation.COUNTERCLOCKWISE_90 -> Math.PI / 2 Rotation.CLOCKWISE_90 -> -Math.PI / 2 Rotation.CLOCKWISE_180 -> -Math.PI else -> .0 } val offset = this.offset(-.5, -.5, -.5) val rotatedMin = offset.min.rotate(axis, angle) val rotatedMax = offset.max.rotate(axis, angle) return AxisAlignedBB(rotatedMin.x, rotatedMin.y, rotatedMin.z, rotatedMax.x, rotatedMax.y, rotatedMax.z).offset(.5, .5, .5) } val Vec3d.blockPos: BlockPos get() = BlockPos(this) fun Vec3d.rotateX(rotation: Rotation) = rotate(Vec3d(1.0, .0, .0), rotation) fun Vec3d.rotateY(rotation: Rotation) = rotate(Vec3d(.0, 1.0, .0), rotation) fun Vec3d.rotateZ(rotation: Rotation) = rotate(Vec3d(.0, .0, 1.0), rotation) fun Vec3d.rotate(axis: Vec3d, rotation: Rotation): Vec3d { val angle = when (rotation) { Rotation.COUNTERCLOCKWISE_90 -> Math.PI / 2 Rotation.CLOCKWISE_90 -> -Math.PI / 2 Rotation.CLOCKWISE_180 -> -Math.PI else -> .0 } return rotate(axis, angle) } fun Vec3d.rotate(axis: Vec3d, angle: Double): Vec3d { val matrix = Matrix4d() matrix.setIdentity() matrix.setRotation(AxisAngle4d(axis.x, axis.y, axis.z, angle)) val vec = Vector4d(x, y, z, 1.0) matrix.transform(vec) return Vec3d(vec.x, vec.y, vec.z) } val Rotation.inverse: Rotation get() = when (this) { Rotation.COUNTERCLOCKWISE_90 -> Rotation.CLOCKWISE_90 Rotation.CLOCKWISE_90 -> Rotation.COUNTERCLOCKWISE_90 else -> this } operator fun Vec3d.get(coord: Int) = when (coord) { 0 -> this.x 1 -> this.y else -> this.z } operator fun Vec3d.unaryPlus() = this operator fun Vec3d.unaryMinus() = Vec3d(-x, -y, -z) operator fun Vec3d.plus(b: Vec3d) = this.add(b) operator fun Vec3d.plus(b: Vec3i) = this.add(Vec3d(b)) operator fun Vec3d.minus(b: Vec3d) = this.subtract(b) operator fun Vec3d.minus(b: Vec3i) = this.subtract(Vec3d(b)) operator fun Byte.times(b: Vec3d) = b * this operator fun Short.times(b: Vec3d) = b * this operator fun Int.times(b: Vec3d) = b * this operator fun Long.times(b: Vec3d) = b * this operator fun Float.times(b: Vec3d) = b * this operator fun Double.times(b: Vec3d) = b * this operator fun Vec3d.times(b: Byte) = scale(b.toDouble()) operator fun Vec3d.times(b: Short) = scale(b.toDouble()) operator fun Vec3d.times(b: Int) = scale(b.toDouble()) operator fun Vec3d.times(b: Long) = scale(b.toDouble()) operator fun Vec3d.times(b: Float) = scale(b.toDouble()) operator fun Vec3d.times(b: Double) = scale(b) operator fun Vec3d.times(b: Vec3d) = Vec3d(x * b.x, y * b.y, z * b.z) operator fun Vec3d.times(b: Vec3i) = this * Vec3d(b) operator fun Vec3d.div(b: Byte) = scale(1 / b.toDouble()) operator fun Vec3d.div(b: Short) = scale(1 / b.toDouble()) operator fun Vec3d.div(b: Int) = scale(1 / b.toDouble()) operator fun Vec3d.div(b: Long) = scale(1 / b.toDouble()) operator fun Vec3d.div(b: Float) = scale(1 / b.toDouble()) operator fun Vec3d.div(b: Double) = scale(1 / b) operator fun Vec3d.div(b: Vec3d) = Vec3d(x / b.x, y / b.y, z / b.z) operator fun Vec3d.div(b: Vec3i) = this / Vec3d(b) val Vec3i.vec3d: Vec3d get() = Vec3d(this) operator fun BlockPos.plus(b: Vec3i) = this.add(b) operator fun BlockPos.minus(b: Vec3i) = this.subtract(b) operator fun Byte.times(b: BlockPos) = this.toInt() * b operator fun Short.times(b: BlockPos) = this.toInt() * b operator fun Int.times(b: BlockPos) = BlockPos(b.x * this, b.y * this, b.z * this) operator fun Long.times(b: BlockPos) = this.toInt() * b operator fun Float.times(b: BlockPos) = Vec3d(this.toDouble(), this.toDouble(), this.toDouble()) * b operator fun Double.times(b: BlockPos) = Vec3d(this, this, this) * b operator fun BlockPos.times(b: Byte) = b * this operator fun BlockPos.times(b: Short) = b * this operator fun BlockPos.times(b: Int) = b * this operator fun BlockPos.times(b: Long) = b * this operator fun BlockPos.times(b: Float) = b * this operator fun BlockPos.times(b: Double) = b * this operator fun BlockPos.times(b: Vec3i) = BlockPos(x * b.x, y * b.y, z * b.z) operator fun BlockPos.div(b: Vec3i) = BlockPos(x / b.x, y / b.y, z / b.z)
mit
85f7bd59fbf56eed6171a640f0e01496
27.553191
100
0.671386
2.834213
false
false
false
false
OnyxDevTools/onyx-database-parent
onyx-database/src/main/kotlin/com/onyx/interactors/scanner/impl/PartitionFullTableScanner.kt
1
4268
package com.onyx.interactors.scanner.impl import com.onyx.descriptor.EntityDescriptor import com.onyx.diskmap.DiskMap import com.onyx.diskmap.impl.base.skiplist.AbstractIterableSkipList import com.onyx.entity.SystemEntity import com.onyx.exception.OnyxException import com.onyx.extension.common.async import com.onyx.interactors.record.data.Reference import com.onyx.interactors.scanner.TableScanner import com.onyx.persistence.IManagedEntity import com.onyx.persistence.context.SchemaContext import com.onyx.persistence.manager.PersistenceManager import com.onyx.persistence.query.Query import com.onyx.persistence.query.QueryCriteria import com.onyx.persistence.query.QueryPartitionMode import com.onyx.extension.meetsCriteria import com.onyx.persistence.context.Contexts import java.util.concurrent.Future /** * Created by timothy.osborn on 1/3/15. * * * It can either scan the entire table or a subset of index values */ class PartitionFullTableScanner @Throws(OnyxException::class) constructor(criteria: QueryCriteria, classToScan: Class<*>, descriptor: EntityDescriptor, query: Query, context: SchemaContext, persistenceManager: PersistenceManager) : FullTableScanner(criteria, classToScan, descriptor, query, context, persistenceManager), TableScanner { private var systemEntity: SystemEntity = context.getSystemEntityByName(query.entityType!!.name)!! /** * Scan records with existing values * * @param records Existing values to check for criteria * @return Existing values that match the criteria * @throws OnyxException Cannot scan partition */ @Throws(OnyxException::class) private fun scanPartition(records: DiskMap<Any, IManagedEntity>, partitionId: Long): MutableSet<Reference> { val matching = HashSet<Reference>() val context = Contexts.get(contextId)!! @Suppress("UNCHECKED_CAST") records.entries.forEach { val entry = it as AbstractIterableSkipList<Any, IManagedEntity>.SkipListEntry<Any?, IManagedEntity> val reference = Reference(partitionId, entry.node?.position ?: 0) if(entry.node != null && query.meetsCriteria(entry.value!!, reference, context, descriptor)) { collector?.collect(reference, entry.value) if(collector == null) matching.add(reference) } } records.clearCache() return matching } /** * Full Table Scan * * @return References matching criteria * @throws OnyxException Cannot scan partition */ @Throws(OnyxException::class) override fun scan(): MutableSet<Reference> { val context = Contexts.get(contextId)!! if (query.partition === QueryPartitionMode.ALL) { val matching = HashSet<Reference>() val units = ArrayList<Future<Set<Reference>>>() systemEntity.partition!!.entries.forEach { units.add( async { val partitionDescriptor = context.getDescriptorForEntity(query.entityType, it.value) val dataFile = context.getDataFile(partitionDescriptor) val records = dataFile.getHashMap<DiskMap<Any, IManagedEntity>>(descriptor.identifier!!.type, partitionDescriptor.entityClass.name) scanPartition(records, it.index) } ) } units.forEach { val results = it.get() if(collector == null) matching += results } return matching } else { val partitionId = context.getPartitionWithValue(query.entityType!!, query.partition)?.index ?: 0L if(partitionId == 0L) // Partition does not exist, lets do a full scan of default partition return super.scan() val partitionDescriptor = context.getDescriptorForEntity(query.entityType, query.partition) val dataFile = context.getDataFile(partitionDescriptor) val records = dataFile.getHashMap<DiskMap<Any, IManagedEntity>>(descriptor.identifier!!.type, partitionDescriptor.entityClass.name) return scanPartition(records, partitionId) } } }
agpl-3.0
0b3b630044d7467e73f15b9ac806d86a
41.267327
335
0.679241
4.883295
false
false
false
false
smmribeiro/intellij-community
platform/object-serializer/src/BaseBeanBinding.kt
13
1865
// 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.serialization import java.lang.reflect.Constructor import kotlin.reflect.full.primaryConstructor import kotlin.reflect.jvm.isAccessible open class BaseBeanBinding(internal val beanClass: Class<*>) { // kotlin data class constructor is never cached, because we have (and it is good) very limited number of such classes @Volatile private var constructor: Constructor<*>? = null @Throws(SecurityException::class, NoSuchMethodException::class) fun resolveConstructor(): Constructor<*> { var constructor = constructor if (constructor != null) { return constructor } constructor = beanClass.getDeclaredConstructor() constructor.isAccessible = true this.constructor = constructor return constructor } fun newInstance(): Any { val constructor = try { resolveConstructor() } catch (e: SecurityException) { return beanClass.newInstance() } catch (e: NoSuchMethodException) { return createUsingKotlin(beanClass) } return constructor.newInstance() } override fun toString(): String { return "${javaClass.simpleName}(beanClass=$beanClass)" } } // ReflectionUtil uses another approach to do it - unreliable because located in util module, where Kotlin cannot be used. // Here we use Kotlin reflection and this approach is more reliable because we are prepared for future Kotlin versions. private fun createUsingKotlin(clazz: Class<*>): Any { // if cannot create data class val kClass = clazz.kotlin val kFunction = kClass.primaryConstructor ?: kClass.constructors.first() try { kFunction.isAccessible = true } catch (ignored: SecurityException) { } return kFunction.callBy(emptyMap()) }
apache-2.0
38ebdf0287d6ec4128ae275fe8a3fdad
32.321429
140
0.733512
4.869452
false
false
false
false
smmribeiro/intellij-community
plugins/git4idea/src/git4idea/config/GitExecutableSelectorPanel.kt
7
6402
// 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 git4idea.config import com.intellij.ide.impl.isTrusted import com.intellij.openapi.Disposable import com.intellij.openapi.application.ModalityState import com.intellij.openapi.application.invokeAndWaitIfNeeded import com.intellij.openapi.application.runInEdt import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.Task import com.intellij.openapi.progress.runBackgroundableTask import com.intellij.openapi.progress.util.BackgroundTaskUtil import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.changes.VcsDirtyScopeManager import com.intellij.ui.dsl.builder.Panel import com.intellij.ui.dsl.gridLayout.HorizontalAlign import com.intellij.util.application import com.intellij.util.ui.VcsExecutablePathSelector import git4idea.GitVcs import git4idea.i18n.GitBundle import org.jetbrains.annotations.CalledInAny internal class GitExecutableSelectorPanel(val project: Project, val disposable: Disposable) { companion object { fun Panel.createGitExecutableSelectorRow(project: Project, disposable: Disposable) { val panel = GitExecutableSelectorPanel(project, disposable) with(panel) { createRow() } } } private val applicationSettings get() = GitVcsApplicationSettings.getInstance() private val projectSettings get() = GitVcsSettings.getInstance(project) private val pathSelector = VcsExecutablePathSelector(GitVcs.DISPLAY_NAME.get(), disposable, GitExecutableHandler()) @Volatile private var versionCheckRequested = false init { application.messageBus.connect(disposable).subscribe(GitExecutableManager.TOPIC, GitExecutableListener { runInEdt(getModalityState()) { resetPathSelector() } }) BackgroundTaskUtil.executeOnPooledThread(disposable) { GitExecutableManager.getInstance().getDetectedExecutable(project, true) // detect executable if needed } } private fun Panel.createRow() = row { cell(pathSelector.mainPanel) .horizontalAlign(HorizontalAlign.FILL) .onReset { resetPathSelector() } .onIsModified { pathSelector.isModified( applicationSettings.savedPathToGit, projectSettings.pathToGit != null, projectSettings.pathToGit) } .onApply { val currentPath = pathSelector.currentPath if (pathSelector.isOverridden) { projectSettings.pathToGit = currentPath } else { applicationSettings.setPathToGit(currentPath) projectSettings.pathToGit = null } validateExecutableOnceAfterClose() VcsDirtyScopeManager.getInstance(project).markEverythingDirty() } } private fun resetPathSelector() { pathSelector.setAutoDetectedPath(GitExecutableManager.getInstance().getDetectedExecutable(project, false)) pathSelector.reset( applicationSettings.savedPathToGit, projectSettings.pathToGit != null, projectSettings.pathToGit) } private fun testGitExecutable(pathToGit: String) { val modalityState = getModalityState() val errorNotifier = InlineErrorNotifierFromSettings( GitExecutableInlineComponent(pathSelector.errorComponent, modalityState, null), modalityState, disposable ) if (!project.isDefault && !project.isTrusted()) { errorNotifier.showError(GitBundle.message("git.executable.validation.cant.run.in.safe.mode"), null) return } object : Task.Modal(project, GitBundle.message("git.executable.version.progress.title"), true) { private lateinit var gitVersion: GitVersion override fun run(indicator: ProgressIndicator) { val executableManager = GitExecutableManager.getInstance() val executable = executableManager.getExecutable(pathToGit) executableManager.dropVersionCache(executable) gitVersion = executableManager.identifyVersion(executable) } override fun onThrowable(error: Throwable) { val problemHandler = findGitExecutableProblemHandler(project) problemHandler.showError(error, errorNotifier) } override fun onSuccess() { if (gitVersion.isSupported) { errorNotifier.showMessage(GitBundle.message("git.executable.version.is", gitVersion.presentation)) } else { showUnsupportedVersionError(project, gitVersion, errorNotifier) } } }.queue() } /** * Special method to check executable after it has been changed through settings */ private fun validateExecutableOnceAfterClose() { if (versionCheckRequested) return versionCheckRequested = true runInEdt(ModalityState.NON_MODAL) { versionCheckRequested = false runBackgroundableTask(GitBundle.message("git.executable.version.progress.title"), project, true) { GitExecutableManager.getInstance().testGitExecutableVersionValid(project) } } } private fun getModalityState() = ModalityState.stateForComponent(pathSelector.mainPanel) private inner class InlineErrorNotifierFromSettings(inlineComponent: InlineComponent, private val modalityState: ModalityState, disposable: Disposable) : InlineErrorNotifier(inlineComponent, modalityState, disposable) { @CalledInAny override fun showError(text: String, description: String?, fixOption: ErrorNotifier.FixOption?) { if (fixOption is ErrorNotifier.FixOption.Configure) { super.showError(text, description, null) } else { super.showError(text, description, fixOption) } } override fun resetGitExecutable() { super.resetGitExecutable() GitExecutableManager.getInstance().getDetectedExecutable(project, true) // populate cache invokeAndWaitIfNeeded(modalityState) { resetPathSelector() } } } private inner class GitExecutableHandler : VcsExecutablePathSelector.ExecutableHandler { override fun patchExecutable(executable: String): String? { return GitExecutableDetector.patchExecutablePath(executable) } override fun testExecutable(executable: String) { testGitExecutable(executable) } } }
apache-2.0
2cb35e9e0dbfa71a0154ed9f708d9dcd
35.798851
158
0.729928
5.434635
false
false
false
false
smmribeiro/intellij-community
plugins/stats-collector/src/com/intellij/stats/completion/network/status/bean/AnalyticsPlatformSettingsDeserializer.kt
9
2017
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.stats.completion.network.status.bean import com.google.gson.* import com.intellij.lang.Language import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.util.Version import java.lang.reflect.Type object AnalyticsPlatformSettingsDeserializer { private val GSON by lazy { GsonBuilder() .registerTypeAdapter(Language::class.java, object : JsonDeserializer<Language> { override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): Language { if (!json.isJsonPrimitive) throw JsonSyntaxException("No string field \"language\"") val value = json.asString if (value == "ANY") return Language.ANY return Language.findLanguageByID(value) ?: throw JsonSyntaxException("No language with id: $value") } }) .registerTypeAdapter(Version::class.java, object : JsonDeserializer<Version> { override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): Version { if (!json.isJsonPrimitive) throw JsonSyntaxException("No string field for major version") val value = json.asString return Version.parseVersion(value) ?: throw JsonSyntaxException("Couldn't parse major version: $value") } }) .create() } private val LOG = logger<AnalyticsPlatformSettingsDeserializer>() fun deserialize(json: String): AnalyticsPlatformSettings? { try { return GSON.fromJson(json, AnalyticsPlatformSettings::class.java) } catch (e: JsonSyntaxException) { if (json.contains("Authentication", ignoreCase = true)) { LOG.warn("Could not get Analytics Platform settings due to authentication problems", e) } else { LOG.error("Could not parse Analytics Platform settings: $json", e) } return null } } }
apache-2.0
6c4f593abf3fd05d59c74f6754cd4a18
43.844444
140
0.708478
4.779621
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/refactoring/move/kotlin/moveTopLevelDeclarations/misc/protectedMembersInternalRefs/before/foo/test.kt
13
532
package foo open class Older { protected object ProtectedObject { val inProtectedObject = 0 } protected class ProtectedClass { val inProtectedClass = 0 } protected fun protectedFun() = 0 protected var protectedVar = 0 } class <caret>Younger : Older() { protected val v1: ProtectedObject = ProtectedObject val v2 = ProtectedObject.inProtectedObject protected val v3: ProtectedClass = ProtectedClass() val v4 = ProtectedClass().inProtectedClass val v5 = protectedFun() val v6 = protectedVar }
apache-2.0
a3f804ced9e37b711ff60f1ab5dd59dd
30.352941
66
0.727444
4.360656
false
false
false
false
80998062/Fank
presentation/src/main/java/com/sinyuk/fanfou/ui/colormatchtabs/menu/ArcMenu.kt
1
10117
/* * * * Apache License * * * * Copyright [2017] Sinyuk * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * */ package com.sinyuk.fanfou.ui.colormatchtabs.menu import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.animation.ValueAnimator import android.annotation.SuppressLint import android.content.Context import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.graphics.PorterDuff import android.os.Build import android.support.design.widget.FloatingActionButton import android.support.v4.content.ContextCompat import android.support.v4.view.animation.FastOutLinearInInterpolator import android.support.v4.view.animation.PathInterpolatorCompat import android.util.AttributeSet import android.view.Gravity import android.view.MotionEvent import android.view.animation.AnimationUtils import android.widget.FrameLayout import com.sinyuk.fanfou.R import com.sinyuk.fanfou.ui.colormatchtabs.listeners.OnArcMenuListener import com.sinyuk.fanfou.ui.colormatchtabs.model.CircleSubMenu import com.sinyuk.fanfou.ui.colormatchtabs.model.ColorTab import com.sinyuk.fanfou.ui.colormatchtabs.utils.getColor import com.sinyuk.fanfou.ui.colormatchtabs.utils.getDimen /** * Created by anna on 19.05.17. * */ class ArcMenu : FrameLayout { companion object { private const val MAX_ANGLE_FOR_MENU = 140.0 private const val START_MENU_ANGLE = -20.0 private const val CONTROL_X1 = 0.250f private const val CONTROL_Y1 = 0.270f private const val CONTROL_X2 = 0.190f private const val CONTROL_Y2 = 1.650f const val ANIMATION_DURATION = 200L } private lateinit var fab: FloatingActionButton private lateinit var fabLayoutParams: LayoutParams private lateinit var backgroundPaint: Paint private var isMenuOpen = false internal var listOfTabs: MutableList<ColorTab> = mutableListOf() private var circleSubMenu: MutableList<CircleSubMenu> = mutableListOf() private var currentRadius = 0f internal var menuToggleListener: MenuToggleListener? = null private var userMenuToggleListener: MenuToggleListener? = null private var arcMenuListener: OnArcMenuListener? = null private var isMenuAnimating: Boolean = false constructor(context: Context?) : this(context, null) constructor(context: Context?, attrs: AttributeSet?) : this(context, attrs, 0) constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { setBackgroundColor(Color.TRANSPARENT) initCanvas() initFab() } private fun initCanvas() { setWillNotDraw(false) backgroundPaint = Paint() backgroundPaint.flags = Paint.ANTI_ALIAS_FLAG } private fun initFab() { fab = FloatingActionButton(context) fabLayoutParams = LayoutParams(getDimen(R.dimen.fab_size), getDimen(R.dimen.fab_size)) fabLayoutParams.gravity = Gravity.CENTER_HORIZONTAL or Gravity.BOTTOM fab.useCompatPadding = true fab.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_rice)) super.addView(fab, 0, fabLayoutParams) fab.setOnClickListener { if (!isMenuAnimating) { drawMenu() } } } fun addMenuToggleListener(toggleListener: MenuToggleListener) { this.userMenuToggleListener = toggleListener } fun addOnClickListener(arcMenuClick: OnArcMenuListener) { this.arcMenuListener = arcMenuClick } @SuppressLint("SwitchIntDef") override fun onMeasure(widthMeasureSpec: Int, originHeightMeasureSpec: Int) { var heightMeasureSpec = originHeightMeasureSpec val heightLayout = (fab.height * 2) + calculateRadius() when (MeasureSpec.getMode(heightMeasureSpec)) { MeasureSpec.AT_MOST -> heightMeasureSpec = MeasureSpec.makeMeasureSpec( Math.min(heightLayout, MeasureSpec.getSize(heightMeasureSpec)), MeasureSpec.EXACTLY) MeasureSpec.UNSPECIFIED -> heightMeasureSpec = MeasureSpec.makeMeasureSpec(heightLayout, MeasureSpec.EXACTLY) } super.onMeasure(widthMeasureSpec, heightMeasureSpec) } var isLayoutParamNeedToSet = true override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) { super.onLayout(changed, left, top, right, bottom) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { if (isLayoutParamNeedToSet) { fab.layoutParams = fabLayoutParams isLayoutParamNeedToSet = false } } } private fun drawMenu() { if (isMenuOpen) { userMenuToggleListener?.onCloseMenu() menuToggleListener?.onCloseMenu() animateCloseMenu() fab.startAnimation(AnimationUtils.loadAnimation(context, R.anim.rotate_backward)) } else { userMenuToggleListener?.onOpenMenu() menuToggleListener?.onOpenMenu() animateOpenMenu() fab.startAnimation(AnimationUtils.loadAnimation(context, R.anim.rotate_forward)) } isMenuOpen = !isMenuOpen } override fun onDraw(canvas: Canvas?) { super.onDraw(canvas) if (currentRadius != 0f) { layoutChildrenArc(canvas) } } private fun layoutChildrenArc(canvas: Canvas?) { val eachAngle = calculateSubMenuAngle() var angleForChild = START_MENU_ANGLE listOfTabs.forEach { val childX = ((fab.x + (fab.width / 2).toFloat()) - (currentRadius * Math.cos(Math.toRadians(angleForChild))).toFloat()) val childY = ((fab.y + (fab.height / 2).toFloat()) + (currentRadius * Math.sin(Math.toRadians(angleForChild))).toFloat()) backgroundPaint.color = it.selectedColor canvas?.drawCircle(childX, childY, calculateCircleSize(), backgroundPaint) if (currentRadius >= (calculateRadius().toFloat() - (calculateRadius().toFloat() / 3)) && isMenuOpen) { animateDrawableAppears(childX, childY, it, canvas) } angleForChild -= eachAngle } } private fun calculateCircleSize() = (fab.height - fab.paddingTop) / 2f private fun animateOpenMenu() { ValueAnimator.ofFloat(0f, calculateRadius().toFloat()).apply { duration = ANIMATION_DURATION interpolator = PathInterpolatorCompat.create(CONTROL_X1, CONTROL_Y1, CONTROL_X2, CONTROL_Y2) addUpdateListener { currentRadius = animatedValue as Float invalidate() } addListener(animationListener) }.start() } private fun animateDrawableAppears(childX: Float, childY: Float, tab: ColorTab, canvas: Canvas?) { val left = childX.toInt() - ((tab.icon?.intrinsicWidth ?: 0) / 2) val top = childY.toInt() - ((tab.icon?.intrinsicHeight ?: 0) / 2) tab.icon?.setColorFilter(getColor(R.color.windowBackground), PorterDuff.Mode.SRC_ATOP) tab.icon?.setBounds(left, top, left + (tab.icon?.intrinsicWidth ?: 0), top + (tab.icon?.intrinsicHeight ?: 0)) tab.icon?.draw(canvas) } private fun animateCloseMenu() { ValueAnimator.ofFloat(calculateRadius().toFloat(), 0f).apply { duration = ANIMATION_DURATION interpolator = FastOutLinearInInterpolator() addUpdateListener { currentRadius = animatedValue as Float invalidate() } addListener(animationListener) }.start() } private fun calculateSubMenuAngle() = MAX_ANGLE_FOR_MENU / (listOfTabs.count() - 1).toDouble() private fun calculateRadius() = width / 3 private fun calculateSubMenu() { val eachAngle = MAX_ANGLE_FOR_MENU / (listOfTabs.count() - 1).toDouble() var angleForChild = START_MENU_ANGLE listOfTabs.forEach { val childX = ((fab.x + (fab.width / 2).toFloat()) - (calculateRadius() * Math.cos(Math.toRadians(angleForChild))).toFloat()) val childY = ((fab.y + (fab.height / 2).toFloat()) + (calculateRadius() * Math.sin(Math.toRadians(angleForChild))).toFloat()) circleSubMenu.add(CircleSubMenu(childX, childY, calculateCircleSize())) angleForChild -= eachAngle } } override fun onTouchEvent(event: MotionEvent?): Boolean { if (circleSubMenu.isEmpty()) { calculateSubMenu() } when (event?.action) { MotionEvent.ACTION_DOWN -> { if (isMenuOpen) { click(event.x, event.y) } } } return super.onTouchEvent(event) } private fun click(x: Float, y: Float) { circleSubMenu.forEachIndexed { index, circleSubMenu -> if ((circleSubMenu.x - circleSubMenu.radius) <= x && x <= (circleSubMenu.x + circleSubMenu.radius)) { if ((circleSubMenu.y - circleSubMenu.radius) <= y && y <= (circleSubMenu.y + circleSubMenu.radius)) { arcMenuListener?.onClick(index) } } } } private val animationListener = object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator?) { isMenuAnimating = false } override fun onAnimationStart(animation: Animator?) { isMenuAnimating = true } } }
mit
3d51ccf2c03bf37c5d3dc26287ef7721
38.217054
137
0.659484
4.634448
false
false
false
false
h0tk3y/better-parse
src/commonMain/kotlin/com/github/h0tk3y/betterParse/st/LiftToSyntaxTree.kt
1
9698
package com.github.h0tk3y.betterParse.st import com.github.h0tk3y.betterParse.combinators.* import com.github.h0tk3y.betterParse.grammar.Grammar import com.github.h0tk3y.betterParse.grammar.ParserReference import com.github.h0tk3y.betterParse.lexer.Token import com.github.h0tk3y.betterParse.lexer.TokenMatch import com.github.h0tk3y.betterParse.lexer.TokenMatchesSequence import com.github.h0tk3y.betterParse.parser.* import com.github.h0tk3y.betterParse.parser.ParsedValue /** Encloses custom logic for transforming a [Parser] to a parser of [SyntaxTree]. * A correct implementation overrides [liftToSyntaxTree] so that it calls `recurse` for the sub-parsers, if any, and * combines them into the parser that it returns. */ public interface LiftToSyntaxTreeTransformer { public interface DefaultTransformerReference { public fun <T> transform(parser: Parser<T>): Parser<SyntaxTree<T>> } public fun <T> liftToSyntaxTree(parser: Parser<T>, default: DefaultTransformerReference): Parser<SyntaxTree<T>> } /** Options for transforming a [Parser] to a parser of [SyntaxTree]. * @param retainSkipped - whether the [skip]ped parsers should be present in the syntax tree structure. * @param retainSeparators - whether the separators of [separated], [leftAssociative] and [rightAssociative] should be * present in the syntax tree structure. */ public data class LiftToSyntaxTreeOptions( val retainSkipped: Boolean = false, val retainSeparators: Boolean = true ) /** Converts a [Parser] of [T] to another that parses [SyntaxTree]. The resulting [SyntaxTree]s will have this parser * as [SyntaxTree.parser] and the result that this parser is stored in [SyntaxTree.item]. The [liftOptions] are * used to determine which parts of the syntax tree should be dropped. The [structureParsers] define the resulting * structure of the syntax tree: only the nodes having these parsers are retained (see: [SyntaxTree.flatten]), pass * empty set to retain all nodes. */ public fun <T> Parser<T>.liftToSyntaxTreeParser( liftOptions: LiftToSyntaxTreeOptions = LiftToSyntaxTreeOptions(), structureParsers: Set<Parser<*>>? = null, transformer: LiftToSyntaxTreeTransformer? = null ): Parser<SyntaxTree<T>> { val astParser = ParserToSyntaxTreeLifter(liftOptions, transformer).lift(this) return if (structureParsers == null) astParser else astParser.flattened(structureParsers) } /** Converts a [Grammar] so that its [Grammar.rootParser] parses a [SyntaxTree]. See: [liftToSyntaxTreeParser]. */ public fun <T> Grammar<T>.liftToSyntaxTreeGrammar( liftOptions: LiftToSyntaxTreeOptions = LiftToSyntaxTreeOptions(), structureParsers: Set<Parser<*>>? = declaredParsers, transformer: LiftToSyntaxTreeTransformer? = null ): Grammar<SyntaxTree<T>> = object : Grammar<SyntaxTree<T>>() { override val rootParser: Parser<SyntaxTree<T>> = [email protected] .liftToSyntaxTreeParser(liftOptions, structureParsers, transformer) override val tokens: List<Token> get() = [email protected] override val declaredParsers: Set<Parser<Any?>> = [email protected] } private class ParserToSyntaxTreeLifter( val liftOptions: LiftToSyntaxTreeOptions, val transformer: LiftToSyntaxTreeTransformer? ) { @Suppress("UNCHECKED_CAST") fun <T> lift(parser: Parser<T>): Parser<SyntaxTree<T>> { if (parser in parsersInStack) return referenceResultInStack(parser) as Parser<SyntaxTree<T>> parsersInStack += parser val result = when (parser) { is EmptyParser -> emptyASTParser() is Token -> liftTokenToAST(parser) is MapCombinator<*, *> -> liftMapCombinatorToAST(parser) is AndCombinator -> liftAndCombinatorToAST(parser) is OrCombinator -> liftOrCombinatorToAST(parser) is OptionalCombinator<*> -> liftOptionalCombinatorToAST(parser) is RepeatCombinator<*> -> liftRepeatCombinatorToAST(parser) is ParserReference<*> -> liftParserReferenceToAST(parser) is SeparatedCombinator<*, *> -> liftSeparatedCombinatorToAST(parser) else -> { transformer?.liftToSyntaxTree(parser, default) ?: throw IllegalArgumentException("Unexpected parser $this. Provide a custom transformer that can lift it.") } } as Parser<SyntaxTree<T>> resultMap[parser] = result parsersInStack -= parser return result } inner class DefaultTransformerReference : LiftToSyntaxTreeTransformer.DefaultTransformerReference { override fun <T> transform(parser: Parser<T>): Parser<SyntaxTree<T>> = lift(parser) } private val default = DefaultTransformerReference() private fun liftTokenToAST(token: Token): Parser<SyntaxTree<TokenMatch>> { return token.map { SyntaxTree(it, listOf(), token, it.offset until (it.offset + it.length)) } } private fun <T, R> liftMapCombinatorToAST(combinator: MapCombinator<T, R>): Parser<SyntaxTree<R>> { val liftedInner = lift(combinator.innerParser) return liftedInner.map { SyntaxTree(combinator.transform(it.item), listOf(it), combinator, it.range) } } private fun <T> liftOptionalCombinatorToAST(combinator: OptionalCombinator<T>): Parser<SyntaxTree<T?>> { return object: Parser<SyntaxTree<T?>> { override fun tryParse(tokens: TokenMatchesSequence, fromPosition: Int): ParseResult<SyntaxTree<T?>> { val result = optional(lift(combinator.parser)).tryParse(tokens, fromPosition) return when (result) { is ErrorResult -> result is Parsed -> { val inputPosition = tokens[fromPosition]?.offset ?: 0 val ast = SyntaxTree(result.value?.item, listOfNotNull(result.value), combinator, result.value?.range ?: inputPosition..inputPosition) ParsedValue(ast, result.nextPosition) } } } } } private fun <T> liftParserReferenceToAST(combinator: ParserReference<T>): Parser<SyntaxTree<T>> { return lift(combinator.parser) } private fun <T> liftAndCombinatorToAST(combinator: AndCombinator<T>): AndCombinator<SyntaxTree<T>> { val liftedConsumers = combinator.consumersImpl.map { when (it) { is Parser<*> -> lift(it) is SkipParser -> lift(it.innerParser) else -> throw IllegalArgumentException() } } return AndCombinator(liftedConsumers) { parsedItems -> val nonSkippedResults = combinator.nonSkippedIndices.map { parsedItems[it] } val originalResult = combinator.transform(nonSkippedResults.map { (it as SyntaxTree<*>).item }) val start = (parsedItems.first() as SyntaxTree<*>).range.first val end = ((parsedItems.lastOrNull { (it as SyntaxTree<*>).range.last != 0 }) as? SyntaxTree<*>)?.range?.last ?: 0 @Suppress("UNCHECKED_CAST") val children = if (liftOptions.retainSkipped) parsedItems as List<SyntaxTree<*>> else combinator.nonSkippedIndices.map { parsedItems[it] } as List<SyntaxTree<*>> return@AndCombinator SyntaxTree(originalResult, children, combinator, start..end) } } private fun <T> liftOrCombinatorToAST(combinator: OrCombinator<T>): Parser<SyntaxTree<T>> { val liftedParsers = combinator.parsers.map { lift(it) } return OrCombinator(liftedParsers).map { SyntaxTree(it.item, listOf(it), combinator, it.range) } } private fun <T> liftRepeatCombinatorToAST(combinator: RepeatCombinator<T>): Parser<SyntaxTree<List<T>>> { val liftedInner = lift(combinator.parser) return RepeatCombinator(liftedInner, combinator.atLeast, combinator.atMost).map { val start = it.firstOrNull()?.range?.start ?: 0 val end = it.lastOrNull { it.range.endInclusive != 0 }?.range?.endInclusive ?: 0 SyntaxTree(it.map { it.item }, it, combinator, start..end) } } private fun <T, S> liftSeparatedCombinatorToAST(combinator: SeparatedCombinator<T, S>): Parser<SyntaxTree<Separated<T, S>>> { val liftedTerm = lift(combinator.termParser) val liftedSeparator = lift(combinator.separatorParser) return SeparatedCombinator(liftedTerm, liftedSeparator, combinator.acceptZero).map { separated -> val item = Separated(separated.terms.map { it.item }, separated.separators.map { it.item }) val children = when { separated.terms.isEmpty() -> emptyList<SyntaxTree<*>>() liftOptions.retainSeparators -> listOf(separated.terms.first()) + (separated.separators zip separated.terms.drop(1)).flatMap { (s, t) -> listOf(s, t) } else -> separated.terms } val start = children.firstOrNull()?.range?.start ?: 0 val end = children.lastOrNull { it.range.last != 0 }?.range?.last ?: 0 SyntaxTree(item, children, combinator, start..end) } } private fun emptyASTParser() = EmptyParser.map { SyntaxTree(Unit, emptyList(), EmptyParser, 0..0) } private val resultMap = hashMapOf<Parser<*>, Parser<SyntaxTree<*>>>() private fun referenceResultInStack(parser: Parser<*>) = ParserReference { resultMap[parser]!! } private val parsersInStack = hashSetOf<Parser<*>>() }
apache-2.0
dc0e4bbbb151776d5954277e505632dc
48.994845
171
0.675088
4.660259
false
false
false
false
getsentry/raven-java
sentry/src/test/java/io/sentry/DuplicateEventDetectionEventProcessorTest.kt
1
3243
package io.sentry import io.sentry.exception.ExceptionMechanismException import io.sentry.protocol.Mechanism import java.lang.RuntimeException import kotlin.test.Test import kotlin.test.assertNotNull import kotlin.test.assertNull class DuplicateEventDetectionEventProcessorTest { class Fixture { fun getSut(enableDeduplication: Boolean? = null): DuplicateEventDetectionEventProcessor { val options = SentryOptions().apply { if (enableDeduplication != null) { this.setEnableDeduplication(enableDeduplication) } } return DuplicateEventDetectionEventProcessor(options) } } var fixture = Fixture() @Test fun `does not drop event if no previous event with same exception was processed`() { val processor = fixture.getSut() processor.process(SentryEvent(), null) val result = processor.process(SentryEvent(RuntimeException()), null) assertNotNull(result) } @Test fun `drops event with the same exception`() { val processor = fixture.getSut() val event = SentryEvent(RuntimeException()) processor.process(event, null) val result = processor.process(event, null) assertNull(result) } @Test fun `drops event with mechanism exception having an exception that has already been processed`() { val processor = fixture.getSut() val event = SentryEvent(RuntimeException()) processor.process(event, null) val result = processor.process(SentryEvent(ExceptionMechanismException(Mechanism(), event.throwable!!, Thread.currentThread())), null) assertNull(result) } @Test fun `drops event with exception that has already been processed with event with mechanism exception`() { val processor = fixture.getSut() val sentryEvent = SentryEvent(ExceptionMechanismException(Mechanism(), RuntimeException(), Thread.currentThread())) processor.process(sentryEvent, null) val result = processor.process(SentryEvent((sentryEvent.throwable as ExceptionMechanismException).throwable), null) assertNull(result) } @Test fun `drops event with the cause equal to exception in already processed event`() { val processor = fixture.getSut() val event = SentryEvent(RuntimeException()) processor.process(event, null) val result = processor.process(SentryEvent(RuntimeException(event.throwable)), null) assertNull(result) } @Test fun `drops event with any of the causes has been already processed`() { val processor = fixture.getSut() val event = SentryEvent(RuntimeException()) processor.process(event, null) val result = processor.process(SentryEvent(RuntimeException(RuntimeException(event.throwable))), null) assertNull(result) } @Test fun `does not deduplicate is deduplication is disabled`() { val processor = fixture.getSut(enableDeduplication = false) val event = SentryEvent(RuntimeException()) assertNotNull(processor.process(event, null)) assertNotNull(processor.process(event, null)) } }
bsd-3-clause
2f23ae5f2503ae8801fbe266bb85fe96
33.136842
142
0.682393
5.256078
false
true
false
false
EMResearch/EvoMaster
core/src/main/kotlin/org/evomaster/core/search/impact/impactinfocollection/value/DisruptiveGeneImpact.kt
1
3226
package org.evomaster.core.search.impact.impactinfocollection.value import org.evomaster.core.search.gene.optional.CustomMutationRateGene import org.evomaster.core.search.gene.Gene import org.evomaster.core.search.impact.impactinfocollection.* /** * created by manzh on 2019-09-09 */ class DisruptiveGeneImpact ( sharedImpactInfo: SharedImpactInfo, specificImpactInfo: SpecificImpactInfo, val geneImpact: GeneImpact ) : GeneImpact(sharedImpactInfo, specificImpactInfo){ constructor( id : String, geneImpact: GeneImpact ) : this( SharedImpactInfo(id), SpecificImpactInfo(), geneImpact ) constructor(id : String, gene: CustomMutationRateGene<*>) : this(id, geneImpact = ImpactUtils.createGeneImpact(gene.gene, id)) override fun copy(): DisruptiveGeneImpact { return DisruptiveGeneImpact( shared.copy(), specific.copy(), geneImpact = geneImpact.copy()) } override fun clone(): DisruptiveGeneImpact { return DisruptiveGeneImpact( shared, specific.copy(), geneImpact = geneImpact.clone()) } override fun validate(gene: Gene): Boolean = gene is CustomMutationRateGene<*> override fun countImpactWithMutatedGeneWithContext(gc: MutatedGeneWithContext, noImpactTargets : Set<Int>, impactTargets: Set<Int>, improvedTargets: Set<Int>, onlyManipulation: Boolean) { countImpactAndPerformance(noImpactTargets = noImpactTargets, impactTargets = impactTargets, improvedTargets = improvedTargets, onlyManipulation = onlyManipulation, num = gc.numOfMutatedGene) if (gc.previous == null && impactTargets.isNotEmpty()) return if (gc.current !is CustomMutationRateGene<*>){ throw IllegalStateException("gc.current (${gc.current::class.java.simpleName}) should be DisruptiveGene") } if (gc.previous != null && gc.previous !is CustomMutationRateGene<*>){ throw IllegalStateException("gc.previous (${gc.previous::class.java.simpleName}) should be DisruptiveGene") } val mutatedGeneWithContext = MutatedGeneWithContext( previous = if (gc.previous==null) null else (gc.previous as CustomMutationRateGene<*>).gene, current = gc.current.gene, numOfMutatedGene = gc.numOfMutatedGene ) geneImpact.countImpactWithMutatedGeneWithContext(mutatedGeneWithContext, noImpactTargets = noImpactTargets, impactTargets = impactTargets, improvedTargets = improvedTargets, onlyManipulation = onlyManipulation) } override fun flatViewInnerImpact(): Map<String, Impact> { return mutableMapOf("${getId()}-${geneImpact.getId()}" to geneImpact) .plus(geneImpact.flatViewInnerImpact().map { "${getId()}-${it.key}" to it.value }) } override fun innerImpacts(): List<Impact> { return listOf(geneImpact) } override fun syncImpact(previous: Gene?, current: Gene) { check(previous,current) geneImpact.syncImpact((previous as CustomMutationRateGene<*>).gene, (current as CustomMutationRateGene<*>).gene) } }
lgpl-3.0
0712baa6cc28f77f1f6e70ebf9c45fe9
40.909091
218
0.681029
5.36772
false
false
false
false
BlueBoxWare/LibGDXPlugin
src/main/kotlin/com/gmail/blueboxware/libgdxplugin/filetypes/skin/inspections/SkinBaseInspection.kt
1
1776
package com.gmail.blueboxware.libgdxplugin.filetypes.skin.inspections import com.gmail.blueboxware.libgdxplugin.filetypes.skin.psi.SkinElement import com.gmail.blueboxware.libgdxplugin.filetypes.skin.utils.* import com.intellij.codeInspection.LocalInspectionTool import com.intellij.codeInspection.SuppressQuickFix import com.intellij.openapi.application.ApplicationManager import com.intellij.psi.PsiElement /* * Copyright 2017 Blue Box Ware * * 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. */ abstract class SkinBaseInspection : LocalInspectionTool() { init { if (ApplicationManager.getApplication().isUnitTestMode) { assert(INSPECTION_NAMES.contains(id)) } } override fun getGroupPath() = arrayOf("libGDX", "Skin files") @Suppress("DialogTitleCapitalization") override fun getGroupDisplayName() = "libGDX" override fun isEnabledByDefault() = true override fun isSuppressedFor(element: PsiElement): Boolean = (element as? SkinElement)?.isSuppressed(id) ?: false override fun getBatchSuppressActions(element: PsiElement?): Array<SuppressQuickFix> = arrayOf( SuppressForPropertyFix(id), SuppressForObjectFix(id), SuppressForFileFix(id) ) }
apache-2.0
2a205999a64b4f1777f32c9313eb4a34
34.52
89
0.740428
4.761394
false
false
false
false
herolynx/bouncer
src/main/kotlin/com/herolynx/bouncer/monitoring/HealthService.kt
1
1161
package com.herolynx.bouncer.monitoring import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RestController import java.util.UUID @RestController class HealthService { private val id = UUID.randomUUID() private var healthy = true private var ready = true @GetMapping("/probe/health") fun health(): Boolean { return checkStatus(healthy, String.format("[%s] I'm sick!", id)) } @PostMapping("/probe/health") fun changeHealth(): String { healthy = !healthy return String.format("%s is now: %s", id, healthy) } @GetMapping("/probe/ready") fun ready(): Boolean { return checkStatus(ready, String.format("[%s] Dude, I'm busy - leave me alone!", id)) } @PostMapping("/probe/ready") fun changeReady(): String { ready = !ready return String.format("%s is now: %s", id, ready) } private fun checkStatus(s: Boolean, errMsg: String): Boolean { if (!s) { throw RuntimeException(errMsg) } return s } }
mit
4cc5153f3eeb72f978093a81aae45c4e
24.23913
93
0.640827
4.16129
false
false
false
false
Stargamers/FastHub
app/src/main/java/com/fastaccess/ui/modules/editor/EditorPresenter.kt
7
7972
package com.fastaccess.ui.modules.editor import com.fastaccess.data.dao.CommentRequestModel import com.fastaccess.data.dao.EditReviewCommentModel import com.fastaccess.data.dao.model.Comment import com.fastaccess.helper.BundleConstant import com.fastaccess.helper.BundleConstant.ExtraType.* import com.fastaccess.helper.InputHelper import com.fastaccess.provider.rest.RestProvider import com.fastaccess.ui.base.mvp.presenter.BasePresenter /** * Created by Kosh on 27 Nov 2016, 1:31 AM */ class EditorPresenter : BasePresenter<EditorMvp.View>(), EditorMvp.Presenter { override fun onEditGistComment(id: Long, savedText: CharSequence?, gistId: String) { if (!InputHelper.isEmpty(savedText)) { val requestModel = CommentRequestModel() requestModel.body = savedText!!.toString() makeRestCall<Comment>(RestProvider.getGistService(isEnterprise).editGistComment(gistId, id, requestModel), { comment -> sendToView { view -> view.onSendResultAndFinish(comment, false) } }, false) } } override fun onSubmitGistComment(savedText: CharSequence?, gistId: String) { if (!InputHelper.isEmpty(savedText)) { val requestModel = CommentRequestModel() requestModel.body = savedText!!.toString() makeRestCall<Comment>(RestProvider.getGistService(isEnterprise).createGistComment(gistId, requestModel), { comment -> sendToView { view -> view.onSendResultAndFinish(comment, true) } }, false) } } override fun onHandleSubmission(savedText: CharSequence?, @BundleConstant.ExtraType extraType: String?, itemId: String?, id: Long, login: String?, issueNumber: Int, sha: String?, reviewComment: EditReviewCommentModel?) { if (extraType == null) { throw NullPointerException("extraType is null") } when (extraType) { EDIT_GIST_COMMENT_EXTRA -> { if (itemId == null) { throw NullPointerException("itemId is null") } onEditGistComment(id, savedText, itemId) } NEW_GIST_COMMENT_EXTRA -> { if (itemId == null) { throw NullPointerException("itemId is null") } onSubmitGistComment(savedText, itemId) } FOR_RESULT_EXTRA -> sendToView({ it.onSendMarkDownResult() }) EDIT_ISSUE_COMMENT_EXTRA -> { if (itemId == null || login == null) { throw NullPointerException("itemId or login is null") } onEditIssueComment(savedText!!, itemId, id, login, issueNumber) } NEW_ISSUE_COMMENT_EXTRA -> { if (itemId == null || login == null) { throw NullPointerException("itemId or login is null") } onSubmitIssueComment(savedText!!, itemId, login, issueNumber) } NEW_COMMIT_COMMENT_EXTRA -> { if (itemId == null || login == null || sha == null) { throw NullPointerException("itemId or login is null") } onSubmitCommitComment(savedText!!, itemId, login, sha) } EDIT_COMMIT_COMMENT_EXTRA -> { if (itemId == null || login == null) { throw NullPointerException("itemId or login is null") } onEditCommitComment(savedText!!, itemId, login, id) } NEW_REVIEW_COMMENT_EXTRA -> { if (reviewComment == null || itemId == null || login == null || savedText == null) { throw NullPointerException("reviewComment null") } onSubmitReviewComment(reviewComment, savedText, itemId, login, issueNumber) } EDIT_REVIEW_COMMENT_EXTRA -> { if (reviewComment == null || itemId == null || login == null || savedText == null) { throw NullPointerException("reviewComment null") } onEditReviewComment(reviewComment, savedText, itemId, login, issueNumber, id) } } } private fun onEditReviewComment(reviewComment: EditReviewCommentModel, savedText: CharSequence, repoId: String, login: String, @Suppress("UNUSED_PARAMETER") issueNumber: Int, id: Long) { if (!InputHelper.isEmpty(savedText)) { val requestModel = CommentRequestModel() requestModel.body = savedText.toString() makeRestCall(RestProvider.getReviewService(isEnterprise).editComment(login, repoId, id, requestModel) .map { comment -> reviewComment.commentModel = comment reviewComment }, { comment -> sendToView { view -> view.onSendReviewResultAndFinish(comment, false) } }, false) } } private fun onSubmitReviewComment(reviewComment: EditReviewCommentModel, savedText: CharSequence, repoId: String, login: String, issueNumber: Int) { if (!InputHelper.isEmpty(savedText)) { val requestModel = CommentRequestModel() requestModel.body = savedText.toString() requestModel.inReplyTo = reviewComment.inReplyTo makeRestCall(RestProvider.getReviewService(isEnterprise).submitComment(login, repoId, issueNumber.toLong(), requestModel) .map { comment -> reviewComment.commentModel = comment reviewComment }, { comment -> sendToView { view -> view.onSendReviewResultAndFinish(comment, true) } }, false) } } override fun onSubmitIssueComment(savedText: CharSequence, itemId: String, login: String, issueNumber: Int) { if (!InputHelper.isEmpty(savedText)) { val requestModel = CommentRequestModel() requestModel.body = savedText.toString() makeRestCall<Comment>(RestProvider.getIssueService(isEnterprise).createIssueComment(login, itemId, issueNumber, requestModel) ) { comment -> sendToView { view -> view.onSendResultAndFinish(comment, true) } } } } override fun onEditIssueComment(savedText: CharSequence, itemId: String, id: Long, login: String, issueNumber: Int) { if (!InputHelper.isEmpty(savedText)) { val requestModel = CommentRequestModel() requestModel.body = savedText.toString() makeRestCall<Comment>(RestProvider.getIssueService(isEnterprise).editIssueComment(login, itemId, id, requestModel), { comment -> sendToView { view -> view.onSendResultAndFinish(comment, false) } }, false) } } override fun onSubmitCommitComment(savedText: CharSequence, itemId: String, login: String, sha: String) { if (!InputHelper.isEmpty(savedText)) { val requestModel = CommentRequestModel() requestModel.body = savedText.toString() makeRestCall<Comment>(RestProvider.getRepoService(isEnterprise).postCommitComment(login, itemId, sha, requestModel), { comment -> sendToView { view -> view.onSendResultAndFinish(comment, true) } }, false) } } override fun onEditCommitComment(savedText: CharSequence, itemId: String, login: String, id: Long) { if (!InputHelper.isEmpty(savedText)) { val requestModel = CommentRequestModel() requestModel.body = savedText.toString() makeRestCall<Comment>(RestProvider.getRepoService(isEnterprise).editCommitComment(login, itemId, id, requestModel), { comment -> sendToView { view -> view.onSendResultAndFinish(comment, false) } }, false) } } }
gpl-3.0
32beb9d4c828ec4fc76c1e0b29322f96
49.77707
137
0.605996
5.567039
false
false
false
false
fobo66/BookcrossingMobile
app/src/main/java/com/bookcrossing/mobile/modules/ApiModule.kt
1
1946
/* * Copyright 2020 Andrey Mukamolov * * 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.bookcrossing.mobile.modules import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.FirebaseDatabase import com.google.firebase.messaging.FirebaseMessaging import com.google.firebase.storage.FirebaseStorage import com.google.mlkit.vision.barcode.Barcode import com.google.mlkit.vision.barcode.BarcodeScannerOptions import com.google.mlkit.vision.barcode.BarcodeScanning import dagger.Module import dagger.Provides /** * Module to provide Firebase dependencies via Dagger * * Created by fobo66 on 15.11.2016. */ @Module class ApiModule { /** Firebase Realtime Database */ @Provides fun provideDatabase() = FirebaseDatabase.getInstance() /** Firebase Storage */ @Provides fun provideStorage() = FirebaseStorage.getInstance() /** Firebase Auth */ @Provides fun provideAuth() = FirebaseAuth.getInstance() /** Firebase Cloud Messaging */ @Provides fun provideFCM() = FirebaseMessaging.getInstance() /** MLKit barcode scanner options */ @Provides fun provideMlKitOptions() = BarcodeScannerOptions.Builder() .setBarcodeFormats( Barcode.FORMAT_QR_CODE ) .build() /** MLKit barcode scanner */ @Provides fun provideMlKitBarcodeDetector(options: BarcodeScannerOptions) = BarcodeScanning.getClient(options) }
apache-2.0
25a1b33dfa3269dca8ed74e3fa44a0f8
28.5
78
0.739979
4.334076
false
false
false
false
premnirmal/StockTicker
app/src/main/kotlin/com/github/premnirmal/ticker/network/data/Quote.kt
1
10568
package com.github.premnirmal.ticker.network.data import android.os.Parcelable import com.github.premnirmal.ticker.AppPreferences import kotlinx.android.parcel.Parcelize /** * Created by premnirmal on 3/30/17. */ @Parcelize data class Quote constructor( var symbol: String = "", var name: String = "", var lastTradePrice: Float = 0.toFloat(), var changeInPercent: Float = 0.toFloat(), var change: Float = 0.toFloat() ) : Parcelable, Comparable<Quote> { var isPostMarket: Boolean = false var stockExchange: String = "" var currencyCode: String = "" var annualDividendRate: Float = 0.toFloat() var annualDividendYield: Float = 0.toFloat() var position: Position? = null var properties: Properties? = null var region: String = "" var quoteType: String = "" var longName: String? = null var gmtOffSetMilliseconds: Long = 0 var dayHigh: Float? = null var dayLow: Float? = null var previousClose: Float = 0.0f var open: Float? = null var regularMarketVolume: Long? = null var trailingPE: Float? = 0.0f var marketState: String = "" var tradeable: Boolean = false var triggerable: Boolean = false var fiftyTwoWeekLowChange: Float? = 0.0f var fiftyTwoWeekLowChangePercent: Float? = 0.0f var fiftyTwoWeekHighChange: Float? = 0.0f var fiftyTwoWeekHighChangePercent: Float? = 0.0f var fiftyTwoWeekLow: Float? = 0.0f var fiftyTwoWeekHigh: Float? = 0.0f var dividendDate: Long? = null var earningsTimestamp: Long? = null var fiftyDayAverage: Float? = 0.0f var fiftyDayAverageChange: Float? = 0.0f var fiftyDayAverageChangePercent: Float? = 0.0f var twoHundredDayAverage: Float? = 0.0f var twoHundredDayAverageChange: Float? = 0.0f var twoHundredDayAverageChangePercent: Float? = 0.0f var marketCap: Long? = null val priceFormat: PriceFormat get() = currencyCodes[currencyCode]?.let { PriceFormat(currencyCode = currencyCode, symbol = it, prefix = prefixCurrencies[currencyCode] ?: true) } ?: PriceFormat(currencyCode, currencyCode) fun hasAlertAbove(): Boolean = this.properties != null && this.properties!!.alertAbove > 0.0f && this.properties!!.alertAbove < this.lastTradePrice fun hasAlertBelow(): Boolean = this.properties != null && this.properties!!.alertBelow > 0.0f && this.properties!!.alertBelow > this.lastTradePrice fun getAlertAbove(): Float = this.properties?.alertAbove ?: 0.0f fun getAlertBelow(): Float = this.properties?.alertBelow ?: 0.0f fun hasPositions(): Boolean = position?.holdings?.isNotEmpty() ?: false fun changeString(): String = AppPreferences.SELECTED_DECIMAL_FORMAT.format(change) fun changeStringWithSign(): String { val changeString = AppPreferences.SELECTED_DECIMAL_FORMAT.format(change) if (change >= 0) { return "+$changeString" } return changeString } fun changePercentString(): String = "${AppPreferences.DECIMAL_FORMAT_2DP.format(changeInPercent)}%" fun changePercentStringWithSign(): String { val changeString = "${AppPreferences.DECIMAL_FORMAT_2DP.format(changeInPercent)}%" if (changeInPercent >= 0) { return "+$changeString" } return changeString } fun dividendInfo(): String { return if (annualDividendRate <= 0f || annualDividendYield <= 0f) { "--" } else { AppPreferences.DECIMAL_FORMAT_2DP.format(annualDividendRate) } } private fun positionPrice(): Float = position?.averagePrice() ?: 0f private fun totalPositionShares(): Float = position?.totalShares() ?: 0f private fun totalPositionPrice(): Float = position?.totalPaidPrice() ?: 0f fun priceString(): String = AppPreferences.SELECTED_DECIMAL_FORMAT.format(lastTradePrice) fun averagePositionPrice(): String = AppPreferences.SELECTED_DECIMAL_FORMAT.format(positionPrice()) fun numSharesString(): String = AppPreferences.SELECTED_DECIMAL_FORMAT.format(totalPositionShares()) fun totalSpentString(): String = AppPreferences.SELECTED_DECIMAL_FORMAT.format(totalPositionPrice()) fun holdings(): Float = lastTradePrice * totalPositionShares() fun holdingsString(): String = AppPreferences.SELECTED_DECIMAL_FORMAT.format(holdings()) fun gainLoss(): Float = holdings() - totalPositionShares() * positionPrice() fun gainLossString(): String { val gainLoss = gainLoss() val gainLossString = AppPreferences.SELECTED_DECIMAL_FORMAT.format(gainLoss) if (gainLoss >= 0) { return "+$gainLossString" } return gainLossString } private fun gainLossPercent(): Float { if (totalPositionPrice() == 0f) return 0f return (gainLoss() / totalPositionPrice()) * 100f } fun gainLossPercentString(): String { val gainLossPercent = gainLossPercent() val gainLossString = "${AppPreferences.DECIMAL_FORMAT_2DP.format(gainLossPercent)}%" if (gainLossPercent >= 0) { return "+$gainLossString" } return gainLossString } fun dayChange(): Float = totalPositionShares() * change fun dayChangeString(): String { val dayChange = dayChange() val dayChangeString = AppPreferences.SELECTED_DECIMAL_FORMAT.format(dayChange) if (dayChange > 0) { return "+$dayChangeString" } return dayChangeString } fun newsQuery(): String { return "${if (symbol.contains(".")) symbol.substring(0, symbol.indexOf('.')) else symbol} ${name.split(" ").toMutableList().apply { removeAll(arrayOf("Inc.", "Corporation", "PLC", "ORD")) }.take(3).joinToString(" ")} stock" } val isMarketOpen: Boolean get() = "REGULAR" == marketState.uppercase() override operator fun compareTo(other: Quote): Int = other.changeInPercent.compareTo(changeInPercent) fun copyValues(data: Quote) { this.name = data.name this.lastTradePrice = data.lastTradePrice this.changeInPercent = data.changeInPercent this.change = data.change this.stockExchange = data.stockExchange this.currencyCode = data.currencyCode this.annualDividendRate = data.annualDividendRate this.annualDividendYield = data.annualDividendYield this.region = data.region this.quoteType = data.quoteType this.longName = data.longName this.gmtOffSetMilliseconds = data.gmtOffSetMilliseconds this.dayHigh = data.dayHigh this.dayLow = data.dayLow this.previousClose = data.previousClose this.open = data.open this.regularMarketVolume = data.regularMarketVolume this.trailingPE = data.trailingPE this.marketState = data.marketState this.tradeable = data.tradeable this.fiftyTwoWeekLowChange = data.fiftyTwoWeekLowChange this.fiftyTwoWeekLowChangePercent = data.fiftyTwoWeekLowChangePercent this.fiftyTwoWeekHighChange = data.fiftyTwoWeekHighChange this.fiftyTwoWeekHighChangePercent = data.fiftyTwoWeekHighChangePercent this.fiftyTwoWeekLow = data.fiftyTwoWeekLow this.fiftyTwoWeekHigh = data.fiftyTwoWeekHigh this.dividendDate = data.dividendDate this.earningsTimestamp = data.earningsTimestamp this.fiftyDayAverage = data.fiftyDayAverage this.fiftyDayAverageChange = data.fiftyDayAverageChange this.fiftyDayAverageChangePercent = data.fiftyDayAverageChangePercent this.twoHundredDayAverage = data.twoHundredDayAverage this.twoHundredDayAverageChange = data.twoHundredDayAverageChange this.twoHundredDayAverageChangePercent = data.twoHundredDayAverageChangePercent this.marketCap = data.marketCap } companion object { private val currencyCodes: Map<String, String> by lazy { mapOf( "USD" to "$", "CAD" to "$", "EUR" to "€", "AED" to "د.إ.‏", "AFN" to "؋", "ALL" to "Lek", "AMD" to "դր.", "ARS" to "$", "AUD" to "$", "AZN" to "ман.", "BAM" to "KM", "BDT" to "৳", "BGN" to "лв.", "BHD" to "د.ب.‏", "BIF" to "FBu", "BND" to "$", "BOB" to "Bs", "BRL" to "R$", "BWP" to "P", "BYN" to "руб.", "BZD" to "$", "CDF" to "FrCD", "CHF" to "CHF", "CLP" to "$", "CNY" to "CN¥", "COP" to "$", "CRC" to "₡", "CVE" to "CV$", "CZK" to "Kč", "DJF" to "Fdj", "DKK" to "kr", "DOP" to "RD$", "DZD" to "د.ج.‏", "EEK" to "kr", "EGP" to "ج.م.‏", "ERN" to "Nfk", "ETB" to "Br", "GBP" to "£", "GBp" to "p", "GEL" to "GEL", "GHS" to "GH₵", "GNF" to "FG", "GTQ" to "Q", "HKD" to "$", "HNL" to "L", "HRK" to "kn", "HUF" to "Ft", "IDR" to "Rp", "ILS" to "₪", "INR" to "₹", "IQD" to "د.ع.‏", "IRR" to "﷼", "ISK" to "kr", "JMD" to "$", "JOD" to "د.أ.‏", "JPY" to "¥", "KES" to "Ksh", "KHR" to "៛", "KMF" to "FC", "KRW" to "₩", "KWD" to "د.ك.‏", "KZT" to "тңг.", "LBP" to "ل.ل.‏", "LKR" to "SLRe", "LTL" to "Lt", "LVL" to "Ls", "LYD" to "د.ل.‏", "MAD" to "د.م.‏", "MDL" to "MDL", "MGA" to "MGA", "MKD" to "MKD", "MMK" to "K", "MOP" to "MOP$", "MUR" to "MURs", "MXN" to "$", "MYR" to "RM", "MZN" to "MTn", "NAD" to "N$", "NGN" to "₦", "NIO" to "C$", "NOK" to "kr", "NPR" to "नेरू", "NZD" to "$", "OMR" to "ر.ع.‏", "PAB" to "B/.", "PEN" to "S/.", "PHP" to "₱", "PKR" to "₨", "PLN" to "zł", "PYG" to "₲", "QAR" to "ر.ق.‏", "RON" to "RON", "RSD" to "дин.", "RUB" to "₽.", "RWF" to "FR", "SAR" to "ر.س.‏", "SDG" to "SDG", "SEK" to "kr", "SGD" to "$", "SOS" to "Ssh", "SYP" to "ل.س.‏", "THB" to "฿", "TND" to "د.ت.‏", "TOP" to "T$", "TRY" to "TL", "TTD" to "$", "TWD" to "NT$", "TZS" to "TSh", "UAH" to "₴", "UGX" to "USh", "UYU" to "$", "UZS" to "UZS", "VEF" to "Bs.F.", "VND" to "₫", "XAF" to "FCFA", "XOF" to "CFA", "YER" to "ر.ي.‏", "ZAR" to "R", "ZMK" to "ZK", "ZWL" to "ZWL$" ) } private val prefixCurrencies: Map<String, Boolean> by lazy { mapOf("GBp" to false) } } }
gpl-3.0
a4bca6465b20d828aafaadc85fc2fcb6
29.79646
227
0.604656
3.644902
false
false
false
false
arcao/Geocaching4Locus
app/src/main/java/com/arcao/geocaching4locus/App.kt
1
4883
@file:Suppress("DEPRECATION") package com.arcao.geocaching4locus import android.app.Application import android.webkit.CookieManager import androidx.annotation.WorkerThread import androidx.core.content.edit import androidx.core.content.pm.PackageInfoCompat import androidx.preference.PreferenceManager import com.arcao.feedback.feedbackModule import com.arcao.geocaching4locus.authentication.util.isPremium import com.arcao.geocaching4locus.base.constants.CrashlyticsConstants import com.arcao.geocaching4locus.base.constants.PrefConstants import com.arcao.geocaching4locus.base.util.AnalyticsManager import com.arcao.geocaching4locus.base.util.CrashlyticsTree import com.arcao.geocaching4locus.base.util.KoinTimberLogger import com.arcao.geocaching4locus.data.account.AccountManager import com.arcao.geocaching4locus.data.geocachingApiModule import com.google.firebase.crashlytics.FirebaseCrashlytics import locus.api.android.utils.LocusUtils import locus.api.locusMapApiModule import org.koin.android.ext.android.inject import org.koin.android.ext.koin.androidContext import org.koin.core.context.startKoin import timber.log.Timber import java.util.UUID class App : Application() { private val accountManager by inject<AccountManager>() private val analyticsManager by inject<AnalyticsManager>() private val deviceId: String by lazy { val pref = PreferenceManager.getDefaultSharedPreferences(this) var value = pref.getString(PrefConstants.DEVICE_ID, null) if (value.isNullOrEmpty()) { value = UUID.randomUUID().toString() pref.edit { putString(PrefConstants.DEVICE_ID, value) } } value } val version: String by lazy { try { packageManager.getPackageInfo(packageName, 0).versionName } catch (e: Exception) { Timber.e(e) "1.0" } } val versionCode: Long by lazy { try { PackageInfoCompat.getLongVersionCode(packageManager.getPackageInfo(packageName, 0)) } catch (e: Exception) { Timber.e(e) 0L } } val name: String by lazy { getString(applicationInfo.labelRes) } override fun onCreate() { super.onCreate() startKoin { androidContext(this@App) if (BuildConfig.DEBUG) { logger(KoinTimberLogger()) } modules(listOf(appModule, geocachingApiModule, locusMapApiModule, feedbackModule)) } prepareCrashlytics() analyticsManager.setPremiumMember(accountManager.isPremium) } private fun prepareCrashlytics() { // Set up Crashlytics, disabled for debug builds if (BuildConfig.DEBUG) { FirebaseCrashlytics.getInstance().setCrashlyticsCollectionEnabled(false) } val crashlytics = FirebaseCrashlytics.getInstance() Timber.plant(Timber.DebugTree()) Timber.plant(CrashlyticsTree(crashlytics)) crashlytics.setUserId(deviceId) crashlytics.setCustomKey(CrashlyticsConstants.PREMIUM_MEMBER, accountManager.isPremium) val lv = try { LocusUtils.getActiveVersion(this) } catch (t: Throwable) { Timber.e(t) null } crashlytics.setCustomKey(CrashlyticsConstants.LOCUS_VERSION, lv?.versionName.orEmpty()) crashlytics.setCustomKey(CrashlyticsConstants.LOCUS_PACKAGE, lv?.packageName.orEmpty()) } @WorkerThread fun clearGeocachingCookies() { // required to call flushCookie() // setCookie acts differently when trying to expire cookies between builds of Android that are using // Chromium HTTP stack and those that are not. Using both of these domains to ensure it works on both. clearCookiesForDomain("geocaching.com") clearCookiesForDomain(".geocaching.com") clearCookiesForDomain("https://geocaching.com") clearCookiesForDomain("https://.geocaching.com") flushCookie() } private fun flushCookie() { CookieManager.getInstance().flush() } companion object { private fun clearCookiesForDomain(domain: String) { val cookieManager = CookieManager.getInstance() val cookies = cookieManager.getCookie(domain) ?: return for (cookie in cookies.split(";").dropLastWhile { it.isEmpty() }.toTypedArray()) { val cookieParts = cookie.split("=").dropLastWhile { it.isEmpty() }.toTypedArray() if (cookieParts.isNotEmpty()) { val newCookie = cookieParts[0].trim(Character::isWhitespace) + "=;expires=Sat, 1 Jan 2000 00:00:01 UTC;" cookieManager.setCookie(domain, newCookie) } } } } }
gpl-3.0
c81d4ae3fd0a935b8f039b7567cfa9b2
32.217687
112
0.672537
4.917422
false
false
false
false
vincent-maximilian/slakoverflow
src/main/kotlin/jmailen/slakoverflow/stackoverflow/client.kt
1
2104
package jmailen.slakoverflow.stackoverflow import java.net.URI import jmailen.http.RestClient import jmailen.java.urlEncode import kotlin.collections.set import org.slf4j.LoggerFactory class StackOverflowClient(val stackAppKey: String? = null) { companion object { val logger = LoggerFactory.getLogger(StackOverflowClient::class.java) } fun siteInfo(): List<SiteInfo> { val call = ApiCall("/info", stackAppKey = stackAppKey) logger.info("siteInfo: ${call.url()}") return RestClient.get<SiteInfos>(call.url()).items } fun excerptSearch(freeText: String): List<SearchResultExcerpt> { val call = ApiCall("/search/excerpts", stackAppKey = stackAppKey).apply { params["order"] = "desc" params["sort"] = "relevance" params["q"] = freeText } logger.info("excerptSearch: ${call.url()}") return RestClient.get<SearchResults>(call.url()).items } fun answers(questionId: Int): List<Answer> { val call = ApiCall("/questions/$questionId/answers", stackAppKey = stackAppKey).apply { params["order"] = "desc" params["sort"] = "votes" } logger.info("answers: ${call.url()}") return RestClient.get<Answers>(call.url()).items } fun pageFor(questionId: Int) = QuestionPage(questionId) } class ApiCall(val path: String = "", site: String = ApiCall.STACKOVERFLOW_SITE, stackAppKey: String? = null) { companion object { const val API_ROOT = "https://api.stackexchange.com/2.2" const val STACKOVERFLOW_SITE = "stackoverflow" } var params = LinkedHashMap<String, String>() init { params.set("site", site) stackAppKey?.let { key -> params.set("key", key) } } fun url() = URI(API_ROOT + path + paramsString()).toURL().toString() private fun paramsString() = when (params.isEmpty()) { true -> "" false -> "?" + params.map { "${it.key.urlEncode()}=${it.value.urlEncode()}" }.joinToString("&") } }
mit
1f503300745cd92bbb8d60b7b3c48c8f
29.941176
110
0.610266
4.216433
false
false
false
false
CPRTeam/CCIP-Android
app/src/main/java/app/opass/ccip/ui/announcement/AnnouncementFragment.kt
1
3795
package app.opass.ccip.ui.announcement import android.app.Activity import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.LinearLayout import android.widget.Toast import androidx.core.view.updateLayoutParams import androidx.core.view.updatePadding import androidx.fragment.app.Fragment import androidx.recyclerview.widget.DefaultItemAnimator import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.swiperefreshlayout.widget.SwipeRefreshLayout import app.opass.ccip.R import app.opass.ccip.extension.asyncExecute import app.opass.ccip.extension.setOnApplyWindowInsetsListenerCompat import app.opass.ccip.network.CCIPClient import app.opass.ccip.util.PreferenceUtil import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.launch import kotlin.coroutines.CoroutineContext class AnnouncementFragment : Fragment(), CoroutineScope { companion object { private const val EXTRA_URL = "EXTRA_URL" fun newInstance(url: String): AnnouncementFragment = AnnouncementFragment().apply { arguments = Bundle().apply { putString(EXTRA_URL, url) } } } private lateinit var announcementView: RecyclerView private lateinit var announcementEmptyView: View private lateinit var swipeRefreshLayout: SwipeRefreshLayout private lateinit var mActivity: Activity private lateinit var mJob: Job override val coroutineContext: CoroutineContext get() = mJob + Dispatchers.Main private val baseUrl by lazy { requireArguments().getString(EXTRA_URL)!! } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { super.onCreateView(inflater, container, savedInstanceState) val view = inflater.inflate(R.layout.fragment_announcement, container, false) announcementView = view.findViewById(R.id.announcement) announcementEmptyView = view.findViewById(R.id.announcement_empty) swipeRefreshLayout = view.findViewById(R.id.swipeContainer) mActivity = requireActivity() mJob = Job() announcementView.layoutManager = LinearLayoutManager(mActivity) announcementView.itemAnimator = DefaultItemAnimator() announcementView.setOnApplyWindowInsetsListenerCompat { v, insets, insetsCompat -> v.updatePadding(bottom = insetsCompat.systemGestureInsets.bottom) insets } announcementEmptyView.setOnApplyWindowInsetsListenerCompat { v, insets, insetsCompat -> v.updateLayoutParams<LinearLayout.LayoutParams> { this.bottomMargin = insetsCompat.systemGestureInsets.bottom } insets } swipeRefreshLayout.isEnabled = false swipeRefreshLayout.post { swipeRefreshLayout.isRefreshing = true } launch { try { CCIPClient.withBaseUrl(baseUrl).announcement(PreferenceUtil.getToken(mActivity)).asyncExecute().run { if (isSuccessful && !body().isNullOrEmpty()) { announcementView.adapter = AnnouncementAdapter(mActivity, body()!!) } else { announcementEmptyView.visibility = View.VISIBLE } } } catch (t: Throwable) { Toast.makeText(mActivity, R.string.offline, Toast.LENGTH_LONG).show() } finally { swipeRefreshLayout.isRefreshing = false } } return view } override fun onDestroy() { super.onDestroy() mJob.cancel() } }
gpl-3.0
efa0f75abbe157fb73aeec26cb323bb0
39.37234
117
0.709091
5.436963
false
false
false
false
ujpv/intellij-rust
src/main/kotlin/org/rust/ide/formatter/impl/utils.kt
1
4590
package org.rust.ide.formatter.impl import com.intellij.lang.ASTNode import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiElement import com.intellij.psi.TokenType.WHITE_SPACE import com.intellij.psi.tree.IElementType import com.intellij.psi.tree.TokenSet import com.intellij.psi.tree.TokenSet.orSet import org.rust.lang.core.psi.* import org.rust.lang.core.psi.RustCompositeElementTypes.* import org.rust.lang.core.psi.RustTokenElementTypes.* import com.intellij.psi.tree.TokenSet.create as ts val KEYWORDS = ts(*IElementType.enumerate { it is RustKeywordTokenType }) val NO_SPACE_AROUND_OPS = ts(COLONCOLON, DOT, DOTDOT) val SPACE_AROUND_OPS = TokenSet.andNot(ALL_OPS, NO_SPACE_AROUND_OPS) val UNARY_OPS = ts(MINUS, MUL, EXCL, AND, ANDAND) val PARAMS_LIKE = ts(PARAMETERS, VARIADIC_PARAMETERS) val PAREN_DELIMITED_BLOCKS = orSet(PARAMS_LIKE, ts(PAREN_EXPR, TUPLE_EXPR, TUPLE_TYPE, ARG_LIST, FORMAT_MACRO_ARGS, TRY_MACRO_ARGS, PAT_TUP, TUPLE_FIELDS)) val PAREN_LISTS = orSet(PAREN_DELIMITED_BLOCKS, ts(PAT_ENUM)) val BRACK_DELIMITED_BLOCKS = ts(VEC_TYPE, ARRAY_EXPR, FORMAT_MACRO_ARGS, TRY_MACRO_ARGS) val BRACK_LISTS = orSet(BRACK_DELIMITED_BLOCKS, ts(INDEX_EXPR)) val BLOCK_LIKE = ts(BLOCK, BLOCK_FIELDS, STRUCT_EXPR_BODY, MATCH_BODY, ENUM_BODY) val BRACE_LISTS = ts(USE_GLOB_LIST, FORMAT_MACRO_ARGS, TRY_MACRO_ARGS) val BRACE_DELIMITED_BLOCKS = orSet(BLOCK_LIKE, BRACE_LISTS) val ANGLE_DELIMITED_BLOCKS = ts(GENERIC_PARAMS, GENERIC_ARGS, FOR_LIFETIMES) val ANGLE_LISTS = orSet(ANGLE_DELIMITED_BLOCKS, ts(QUAL_PATH_EXPR)) val ATTRS = ts(OUTER_ATTR, INNER_ATTR) val MOD_ITEMS = ts(FOREIGN_MOD_ITEM, MOD_ITEM) val DELIMITED_BLOCKS = orSet(BRACE_DELIMITED_BLOCKS, BRACK_DELIMITED_BLOCKS, PAREN_DELIMITED_BLOCKS, ANGLE_DELIMITED_BLOCKS) val FLAT_BRACE_BLOCKS = orSet(MOD_ITEMS, ts(PAT_STRUCT, TRAIT_ITEM, IMPL_ITEM)) val TYPES = ts(VEC_TYPE, PTR_TYPE, REF_TYPE, BARE_FN_TYPE, TUPLE_TYPE, PATH_TYPE, TYPE_WITH_BOUNDS_TYPE, FOR_IN_TYPE, WILDCARD_TYPE) val MACRO_ARGS = ts(MACRO_ARG, FORMAT_MACRO_ARGS, TRY_MACRO_ARGS, VEC_MACRO_ARGS) val FN_DECLS = ts(FN_ITEM, FOREIGN_FN_DECL, TRAIT_METHOD_MEMBER, IMPL_METHOD_MEMBER, BARE_FN_TYPE, LAMBDA_EXPR) val ONE_LINE_ITEMS = ts(USE_ITEM, CONST_ITEM, STATIC_ITEM, MOD_DECL_ITEM, EXTERN_CRATE_ITEM, TYPE_ITEM, INNER_ATTR) val PsiElement.isTopLevelItem: Boolean get() = (this is RustItemElement || this is RustAttrElement) && parent is RustMod val PsiElement.isStmtOrExpr: Boolean get() = this is RustStmtElement || this is RustExprElement val PsiElement.isBlockDelim: Boolean get() = node.isBlockDelim fun onSameLine(e1: PsiElement, e2: PsiElement): Boolean { val documentManager = PsiDocumentManager.getInstance(e1.project) val document = documentManager.getDocument(e1.containingFile) return if (document != null && document == documentManager.getDocument(e2.containingFile)) { document.getLineNumber(e1.textOffset) == document.getLineNumber(e2.textOffset) } else { false } } val ASTNode.isDelimitedBlock: Boolean get() = elementType in DELIMITED_BLOCKS val ASTNode.isFlatBraceBlock: Boolean get() = elementType in FLAT_BRACE_BLOCKS /** * A flat block is a Rust PSI element which does not denote separate PSI * element for its _block_ part (e.g. `{...}`), for example [MOD_ITEM]. */ val ASTNode.isFlatBlock: Boolean get() = isFlatBraceBlock || elementType == PAT_ENUM val ASTNode.isBlockDelim: Boolean get() = isBlockDelim(treeParent) fun ASTNode.isBlockDelim(parent: ASTNode?): Boolean { if (parent == null) return false val parentType = parent.elementType return when (elementType) { LBRACE, RBRACE -> parentType in BRACE_DELIMITED_BLOCKS || parent.isFlatBraceBlock LBRACK, RBRACK -> parentType in BRACK_LISTS LPAREN, RPAREN -> parentType in PAREN_LISTS || parentType == PAT_ENUM LT, GT -> parentType in ANGLE_LISTS OR -> parentType == PARAMETERS && parent.treeParent?.elementType == LAMBDA_EXPR else -> false } } fun ASTNode?.isWhitespaceOrEmpty() = this == null || textLength == 0 || elementType == WHITE_SPACE fun onSameLine(e1: ASTNode, e2: ASTNode): Boolean = onSameLine(e1.psi, e2.psi) fun ASTNode.treeNonWSPrev(): ASTNode? { var current = this.treePrev while (current?.elementType == WHITE_SPACE) { current = current?.treePrev } return current } fun ASTNode.treeNonWSNext(): ASTNode? { var current = this.treeNext while (current?.elementType == WHITE_SPACE) { current = current?.treeNext } return current }
mit
2d08698061d483ab7b8d85c9ab0fc324
37.571429
115
0.73159
3.574766
false
false
false
false
talent-bearers/Slimefusion
src/main/java/talent/bearers/slimefusion/common/block/base/BlockModLog.kt
1
4728
package talent.bearers.slimefusion.common.block.base import com.teamwizardry.librarianlib.common.base.block.BlockMod import net.minecraft.block.BlockLog 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.EntityLivingBase import net.minecraft.init.Items import net.minecraft.item.ItemStack import net.minecraft.item.crafting.FurnaceRecipes import net.minecraft.util.EnumFacing import net.minecraft.util.Rotation import net.minecraft.util.math.BlockPos import net.minecraft.world.IBlockAccess import net.minecraft.world.World import net.minecraftforge.oredict.OreDictionary /** * @author WireSegal * Created at 9:56 AM on 12/25/16. */ @Suppress("LeakingThis") open class BlockModLog(name: String, vararg variants: String) : BlockMod(name, Material.WOOD, *variants) { companion object { val AXIS: PropertyEnum<BlockLog.EnumAxis> = PropertyEnum.create("axis", BlockLog.EnumAxis::class.java) } init { blockHardness = 2.0f soundType = SoundType.WOOD if (itemForm != null) { for (variant in variants.indices) OreDictionary.registerOre("logWood", ItemStack(this, 1, variant)) FurnaceRecipes.instance().addSmeltingRecipeForBlock(this, ItemStack(Items.COAL, 1, 1), 0.15f) //todo crystalcoal } defaultState = defaultState.withProperty(AXIS, BlockLog.EnumAxis.Y) } override fun damageDropped(state: IBlockState): Int { return getMetaFromState(state) and 3 } override fun breakBlock(worldIn: World, pos: BlockPos, state: IBlockState) { val i = 4 val j = i + 1 if (worldIn.isAreaLoaded(pos.add(-j, -j, -j), pos.add(j, j, j))) { for (blockpos in BlockPos.getAllInBox(pos.add(-i, -i, -i), pos.add(i, i, i))) { val iblockstate = worldIn.getBlockState(blockpos) if (iblockstate.block.isLeaves(iblockstate, worldIn, blockpos)) { iblockstate.block.beginLeavesDecay(iblockstate, worldIn, blockpos) } } } } override fun getFlammability(world: IBlockAccess?, pos: BlockPos?, face: EnumFacing?) = 5 override fun getFireSpreadSpeed(world: IBlockAccess?, pos: BlockPos?, face: EnumFacing?) = 5 override fun onBlockPlaced(worldIn: World?, pos: BlockPos?, facing: EnumFacing, hitX: Float, hitY: Float, hitZ: Float, meta: Int, placer: EntityLivingBase?): IBlockState { return this.getStateFromMeta(meta).withProperty(AXIS, BlockLog.EnumAxis.fromFacingAxis(facing.axis)) } override fun withRotation(state: IBlockState, rot: Rotation): IBlockState { when (rot) { Rotation.COUNTERCLOCKWISE_90, Rotation.CLOCKWISE_90 -> { when (state.getValue(AXIS)) { BlockLog.EnumAxis.X -> return state.withProperty(AXIS, BlockLog.EnumAxis.Z) BlockLog.EnumAxis.Z -> return state.withProperty(AXIS, BlockLog.EnumAxis.X) else -> return state } } else -> return state } } override fun canSustainLeaves(state: IBlockState, world: IBlockAccess, pos: BlockPos): Boolean { return true } override fun isWood(world: IBlockAccess?, pos: BlockPos?): Boolean { return true } override fun rotateBlock(world: World, pos: BlockPos, axis: EnumFacing?): Boolean { val state = world.getBlockState(pos) world.setBlockState(pos, state.cycleProperty(AXIS)) return true } override fun getStateFromMeta(meta: Int): IBlockState { var axis = BlockLog.EnumAxis.Y val i = meta and 12 when (i) { 4 -> axis = BlockLog.EnumAxis.X 8 -> axis = BlockLog.EnumAxis.Z 12 -> axis = BlockLog.EnumAxis.NONE } return this.defaultState.withProperty(AXIS, axis) } override fun getMetaFromState(state: IBlockState): Int { var i = 0 when (state.getValue(AXIS)) { BlockLog.EnumAxis.X -> i = i or 4 BlockLog.EnumAxis.Z -> i = i or 8 BlockLog.EnumAxis.NONE -> i = i or 12 else -> i = i or 0 } return i } override fun createBlockState(): BlockStateContainer { return BlockStateContainer(this, AXIS) } override fun getHarvestTool(state: IBlockState?): String? { return "axe" } override fun isToolEffective(type: String?, state: IBlockState?): Boolean { return type == "axe" } }
mit
4c7e056e30741d16851e646e899950f7
34.283582
175
0.652496
4.309936
false
false
false
false
signed/intellij-community
platform/configuration-store-impl/src/ProjectStoreImpl.kt
1
18871
/* * 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.ide.highlighter.ProjectFileType import com.intellij.ide.highlighter.WorkspaceFileType import com.intellij.notification.Notifications import com.intellij.notification.NotificationsManager import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.invokeAndWaitIfNeed import com.intellij.openapi.application.runReadAction import com.intellij.openapi.components.* import com.intellij.openapi.components.StateStorage.SaveSession import com.intellij.openapi.components.impl.ServiceManagerImpl import com.intellij.openapi.components.impl.stores.IComponentStore import com.intellij.openapi.components.impl.stores.IProjectStore import com.intellij.openapi.components.impl.stores.StoreUtil import com.intellij.openapi.diagnostic.catchAndLog import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectCoreUtil import com.intellij.openapi.project.ex.ProjectNameProvider import com.intellij.openapi.project.impl.ProjectImpl import com.intellij.openapi.project.impl.ProjectManagerImpl.UnableToSaveProjectNotification import com.intellij.openapi.project.impl.ProjectStoreClassProvider import com.intellij.openapi.util.JDOMUtil import com.intellij.openapi.util.Pair import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.io.FileUtilRt import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.ReadonlyStatusHandler import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.PathUtilRt import com.intellij.util.SmartList import com.intellij.util.attribute import com.intellij.util.containers.computeOrNull import com.intellij.util.containers.forEachGuaranteed import com.intellij.util.containers.isNullOrEmpty import com.intellij.util.io.* import com.intellij.util.isEmpty import com.intellij.util.lang.CompoundRuntimeException import com.intellij.util.text.nullize import gnu.trove.THashSet import org.jdom.Element import java.io.File import java.io.IOException import java.nio.file.Path import java.nio.file.Paths const val PROJECT_FILE = "\$PROJECT_FILE$" const val PROJECT_CONFIG_DIR = "\$PROJECT_CONFIG_DIR$" val IProjectStore.nameFile: Path get() = Paths.get(directoryStorePath, ProjectImpl.NAME_FILE) internal val PROJECT_FILE_STORAGE_ANNOTATION = FileStorageAnnotation(PROJECT_FILE, false) internal val DEPRECATED_PROJECT_FILE_STORAGE_ANNOTATION = FileStorageAnnotation(PROJECT_FILE, true) abstract class ProjectStoreBase(override final val project: ProjectImpl) : ComponentStoreImpl(), IProjectStore { // protected setter used in upsource // Zelix KlassMaster - ERROR: Could not find method 'getScheme()' var scheme = StorageScheme.DEFAULT override final var loadPolicy = StateLoadPolicy.LOAD override final fun isOptimiseTestLoadSpeed() = loadPolicy != StateLoadPolicy.LOAD override final fun getStorageScheme() = scheme override abstract val storageManager: StateStorageManagerImpl protected val isDirectoryBased: Boolean get() = scheme == StorageScheme.DIRECTORY_BASED override final fun setOptimiseTestLoadSpeed(value: Boolean) { // we don't load default state in tests as app store does because // 1) we should not do it // 2) it was so before, so, we preserve old behavior (otherwise RunManager will load template run configurations) loadPolicy = if (value) StateLoadPolicy.NOT_LOAD else StateLoadPolicy.LOAD } override fun getProjectFilePath() = storageManager.expandMacro(PROJECT_FILE) override final fun getWorkspaceFilePath() = storageManager.expandMacro(StoragePathMacros.WORKSPACE_FILE) override final fun clearStorages() { storageManager.clearStorages() } override final fun loadProjectFromTemplate(defaultProject: Project) { defaultProject.save() val element = (defaultProject.stateStore as DefaultProjectStoreImpl).getStateCopy() ?: return LOG.catchAndLog { normalizeDefaultProjectElement(defaultProject, element, if (isDirectoryBased) Paths.get(storageManager.expandMacro(PROJECT_CONFIG_DIR)) else null) } (storageManager.getOrCreateStorage(PROJECT_FILE) as XmlElementStorage).setDefaultState(element) } override final fun getProjectBasePath(): String { if (isDirectoryBased) { val path = PathUtilRt.getParentPath(storageManager.expandMacro(PROJECT_CONFIG_DIR)) if (Registry.`is`("store.basedir.parent.detection", true) && PathUtilRt.getFileName(path).startsWith("${Project.DIRECTORY_STORE_FOLDER}.")) { return PathUtilRt.getParentPath(PathUtilRt.getParentPath(path)) } return path } else { return PathUtilRt.getParentPath(projectFilePath) } } // used in upsource protected fun setPath(filePath: String, refreshVfs: Boolean, useOldWorkspaceContentIfExists: Boolean) { val storageManager = storageManager val fs = LocalFileSystem.getInstance() if (FileUtilRt.extensionEquals(filePath, ProjectFileType.DEFAULT_EXTENSION)) { scheme = StorageScheme.DEFAULT storageManager.addMacro(PROJECT_FILE, filePath) val workspacePath = composeWsPath(filePath) storageManager.addMacro(StoragePathMacros.WORKSPACE_FILE, workspacePath) if (refreshVfs) { invokeAndWaitIfNeed { VfsUtil.markDirtyAndRefresh(false, true, false, fs.refreshAndFindFileByPath(filePath), fs.refreshAndFindFileByPath(workspacePath)) } } if (ApplicationManager.getApplication().isUnitTestMode) { // load state only if there are existing files isOptimiseTestLoadSpeed = !File(filePath).exists() } } else { scheme = StorageScheme.DIRECTORY_BASED // if useOldWorkspaceContentIfExists false, so, file path is expected to be correct (we must avoid file io operations) val isDir = !useOldWorkspaceContentIfExists || Paths.get(filePath).isDirectory() val configDir = "${(if (isDir) filePath else PathUtilRt.getParentPath(filePath))}/${Project.DIRECTORY_STORE_FOLDER}" storageManager.addMacro(PROJECT_CONFIG_DIR, configDir) storageManager.addMacro(PROJECT_FILE, "$configDir/misc.xml") storageManager.addMacro(StoragePathMacros.WORKSPACE_FILE, "$configDir/workspace.xml") if (!isDir) { val workspace = File(workspaceFilePath) if (!workspace.exists()) { useOldWorkspaceContent(filePath, workspace) } } if (ApplicationManager.getApplication().isUnitTestMode) { // load state only if there are existing files isOptimiseTestLoadSpeed = !Paths.get(filePath).exists() } if (refreshVfs) { invokeAndWaitIfNeed { VfsUtil.markDirtyAndRefresh(false, true, true, fs.refreshAndFindFileByPath(configDir)) } } } } override fun <T> getStorageSpecs(component: PersistentStateComponent<T>, stateSpec: State, operation: StateStorageOperation): List<Storage> { val storages = stateSpec.storages if (storages.isEmpty()) { return listOf(PROJECT_FILE_STORAGE_ANNOTATION) } if (isDirectoryBased) { var result: MutableList<Storage>? = null for (storage in storages) { @Suppress("DEPRECATION") if (storage.path != PROJECT_FILE) { if (result == null) { result = SmartList() } result.add(storage) } } if (result.isNullOrEmpty()) { return listOf(PROJECT_FILE_STORAGE_ANNOTATION) } else { result!!.sortWith(deprecatedComparator) // if we create project from default, component state written not to own storage file, but to project file, // we don't have time to fix it properly, so, ancient hack restored result.add(DEPRECATED_PROJECT_FILE_STORAGE_ANNOTATION) return result } } else { var result: MutableList<Storage>? = null // FlexIdeProjectLevelCompilerOptionsHolder, FlexProjectLevelCompilerOptionsHolderImpl and CustomBeanRegistry var hasOnlyDeprecatedStorages = true for (storage in storages) { @Suppress("DEPRECATION") if (storage.path == PROJECT_FILE || storage.path == StoragePathMacros.WORKSPACE_FILE) { if (result == null) { result = SmartList() } result.add(storage) if (!storage.deprecated) { hasOnlyDeprecatedStorages = false } } } if (result.isNullOrEmpty()) { return listOf(PROJECT_FILE_STORAGE_ANNOTATION) } else { if (hasOnlyDeprecatedStorages) { result!!.add(PROJECT_FILE_STORAGE_ANNOTATION) } result!!.sortWith(deprecatedComparator) return result } } } override fun isProjectFile(file: VirtualFile): Boolean { if (!file.isInLocalFileSystem || !ProjectCoreUtil.isProjectOrWorkspaceFile(file, file.fileType)) { return false } val filePath = file.path if (!isDirectoryBased) { return filePath == projectFilePath || filePath == workspaceFilePath } return FileUtil.isAncestor(PathUtilRt.getParentPath(projectFilePath), filePath, false) } override fun getDirectoryStorePath(ignoreProjectStorageScheme: Boolean) = if (!ignoreProjectStorageScheme && !isDirectoryBased) null else PathUtilRt.getParentPath(projectFilePath).nullize() override fun getDirectoryStoreFile() = directoryStorePath?.let { LocalFileSystem.getInstance().findFileByPath(it) } override fun getDirectoryStorePathOrBase() = PathUtilRt.getParentPath(projectFilePath) } private open class ProjectStoreImpl(project: ProjectImpl, private val pathMacroManager: PathMacroManager) : ProjectStoreBase(project) { private var lastSavedProjectName: String? = null init { assert(!project.isDefault) } override final fun getPathMacroManagerForDefaults() = pathMacroManager override val storageManager = ProjectStateStorageManager(pathMacroManager.createTrackingSubstitutor(), project) override fun setPath(filePath: String) { setPath(filePath, true, true) } override fun getProjectName(): String { if (!isDirectoryBased) { return PathUtilRt.getFileName(projectFilePath).removeSuffix(ProjectFileType.DOT_DEFAULT_EXTENSION) } val baseDir = projectBasePath val nameFile = nameFile if (nameFile.exists()) { LOG.catchAndLog { nameFile.inputStream().reader().useLines { it.firstOrNull { !it.isEmpty() }?.trim() }?.let { lastSavedProjectName = it return it } } } return ProjectNameProvider.EP_NAME.extensions.computeOrNull { LOG.catchAndLog { it.getName(project) } } ?: PathUtilRt.getFileName(baseDir).replace(":", "") } private fun saveProjectName() { if (!isDirectoryBased) { return } val currentProjectName = project.name if (lastSavedProjectName == currentProjectName) { return } lastSavedProjectName = currentProjectName val basePath = projectBasePath if (currentProjectName == PathUtilRt.getFileName(basePath)) { // name equals to base path name - just remove name nameFile.delete() } else { if (Paths.get(basePath).isDirectory()) { nameFile.write(currentProjectName.toByteArray()) } } } override fun doSave(saveSessions: List<SaveSession>, readonlyFiles: MutableList<Pair<SaveSession, VirtualFile>>, prevErrors: MutableList<Throwable>?): MutableList<Throwable>? { try { saveProjectName() } catch (e: Throwable) { LOG.error("Unable to store project name", e) } var errors = prevErrors beforeSave(readonlyFiles) errors = super.doSave(saveSessions, readonlyFiles, errors) val notifications = NotificationsManager.getNotificationsManager().getNotificationsOfType(UnableToSaveProjectNotification::class.java, project) if (readonlyFiles.isEmpty()) { for (notification in notifications) { notification.expire() } return errors } if (!notifications.isEmpty()) { throw IComponentStore.SaveCancelledException() } val status = runReadAction { ReadonlyStatusHandler.getInstance(project).ensureFilesWritable(*getFilesList(readonlyFiles)) } if (status.hasReadonlyFiles()) { dropUnableToSaveProjectNotification(project, status.readonlyFiles) throw IComponentStore.SaveCancelledException() } val oldList = readonlyFiles.toTypedArray() readonlyFiles.clear() for (entry in oldList) { errors = executeSave(entry.first, readonlyFiles, errors) } CompoundRuntimeException.throwIfNotEmpty(errors) if (!readonlyFiles.isEmpty()) { dropUnableToSaveProjectNotification(project, getFilesList(readonlyFiles)) throw IComponentStore.SaveCancelledException() } return errors } protected open fun beforeSave(readonlyFiles: List<Pair<SaveSession, VirtualFile>>) { } } private fun dropUnableToSaveProjectNotification(project: Project, readOnlyFiles: Array<VirtualFile>) { val notifications = NotificationsManager.getNotificationsManager().getNotificationsOfType(UnableToSaveProjectNotification::class.java, project) if (notifications.isEmpty()) { Notifications.Bus.notify(UnableToSaveProjectNotification(project, readOnlyFiles), project) } else { notifications[0].myFiles = readOnlyFiles } } private fun getFilesList(readonlyFiles: List<Pair<SaveSession, VirtualFile>>) = Array(readonlyFiles.size) { readonlyFiles[it].second } private class ProjectWithModulesStoreImpl(project: ProjectImpl, pathMacroManager: PathMacroManager) : ProjectStoreImpl(project, pathMacroManager) { override fun beforeSave(readonlyFiles: List<Pair<SaveSession, VirtualFile>>) { super.beforeSave(readonlyFiles) for (module in (ModuleManager.getInstance(project)?.modules ?: Module.EMPTY_ARRAY)) { module.stateStore.save(readonlyFiles) } } } // used in upsource class PlatformLangProjectStoreClassProvider : ProjectStoreClassProvider { override fun getProjectStoreClass(isDefaultProject: Boolean): Class<out IComponentStore> { return if (isDefaultProject) DefaultProjectStoreImpl::class.java else ProjectWithModulesStoreImpl::class.java } } private class PlatformProjectStoreClassProvider : ProjectStoreClassProvider { override fun getProjectStoreClass(isDefaultProject: Boolean): Class<out IComponentStore> { return if (isDefaultProject) DefaultProjectStoreImpl::class.java else ProjectStoreImpl::class.java } } private fun composeWsPath(filePath: String) = "${FileUtilRt.getNameWithoutExtension(filePath)}${WorkspaceFileType.DOT_DEFAULT_EXTENSION}" private fun useOldWorkspaceContent(filePath: String, ws: File) { val oldWs = File(composeWsPath(filePath)) if (!oldWs.exists()) { return } try { FileUtil.copyContent(oldWs, ws) } catch (e: IOException) { LOG.error(e) } } private fun removeWorkspaceComponentConfiguration(defaultProject: Project, element: Element) { val componentElements = element.getChildren("component") if (componentElements.isEmpty()) { return } val workspaceComponentNames = THashSet(listOf("GradleLocalSettings")) @Suppress("DEPRECATION") val projectComponents = defaultProject.getComponents(PersistentStateComponent::class.java) projectComponents.forEachGuaranteed { getNameIfWorkspaceStorage(it.javaClass)?.let { workspaceComponentNames.add(it) } } ServiceManagerImpl.processAllImplementationClasses(defaultProject as ProjectImpl) { aClass, pluginDescriptor -> getNameIfWorkspaceStorage(aClass)?.let { workspaceComponentNames.add(it) } true } val iterator = componentElements.iterator() for (componentElement in iterator) { val name = componentElement.getAttributeValue("name") ?: continue if (workspaceComponentNames.contains(name)) { iterator.remove() } } return } // public only to test fun normalizeDefaultProjectElement(defaultProject: Project, element: Element, projectConfigDir: Path?) { LOG.catchAndLog { removeWorkspaceComponentConfiguration(defaultProject, element) } if (projectConfigDir == null) { return } LOG.catchAndLog { val iterator = element.getChildren("component").iterator() for (component in iterator) { when (component.getAttributeValue("name")) { "InspectionProjectProfileManager" -> convertProfiles(component.getChildren("profile").iterator(), "InspectionProjectProfileManager", projectConfigDir.resolve("inspectionProfiles")) "CopyrightManager" -> { iterator.remove() val schemeDir = projectConfigDir.resolve("copyright") convertProfiles(component.getChildren("copyright").iterator(), "CopyrightManager", schemeDir) component.removeAttribute("name") if (!component.isEmpty()) { val wrapper = Element("component").attribute("name", "CopyrightManager") component.name = "settings" wrapper.addContent(component) JDOMUtil.write(wrapper, schemeDir.resolve("profiles_settings.xml").outputStream(), "\n") } } } } } } private fun convertProfiles(profileIterator: MutableIterator<Element>, componentName: String, schemeDir: Path) { for (profile in profileIterator) { val schemeName = profile.getChildren("option").find { it.getAttributeValue("name") == "myName" }?.getAttributeValue("value") ?: continue profileIterator.remove() val wrapper = Element("component").attribute("name", componentName) wrapper.addContent(profile) val path = schemeDir.resolve("${FileUtil.sanitizeFileName(schemeName, true)}.xml") JDOMUtil.write(wrapper, path.outputStream(), "\n") } } private fun getNameIfWorkspaceStorage(aClass: Class<*>): String? { val stateAnnotation = StoreUtil.getStateSpec(aClass) if (stateAnnotation == null || stateAnnotation.name.isNullOrEmpty()) { return null } val storage = stateAnnotation.storages.sortByDeprecated().firstOrNull() ?: return null return if (storage.path == StoragePathMacros.WORKSPACE_FILE) stateAnnotation.name else null }
apache-2.0
d1de14d50b6d058718c2d2b11c86004a
36.518887
191
0.73764
5.168721
false
false
false
false
googlecodelabs/odml-pathways
audio_classification/codelab2/android/starter/app/src/main/java/com/example/mysoundclassification/MainActivity.kt
2
3076
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.example.mysoundclassification import android.Manifest import android.os.Bundle import android.util.Log import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import org.tensorflow.lite.task.audio.classifier.AudioClassifier import java.util.* import kotlin.concurrent.scheduleAtFixedRate class MainActivity : AppCompatActivity() { var TAG = "MainActivity" // TODO 1: define your model name //var modelPath = "my_birds_model.tflite" var probabilityThreshold: Float = 0.3f lateinit var textView: TextView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val REQUEST_RECORD_AUDIO = 1337 requestPermissions(arrayOf(Manifest.permission.RECORD_AUDIO), REQUEST_RECORD_AUDIO) textView = findViewById<TextView>(R.id.output) val recorderSpecsTextView = findViewById<TextView>(R.id.textViewAudioRecorderSpecs) val classifier = AudioClassifier.createFromFile(this, modelPath) val tensor = classifier.createInputTensorAudio() val format = classifier.requiredTensorAudioFormat val recorderSpecs = "Number Of Channels: ${format.channels}\n" + "Sample Rate: ${format.sampleRate}" recorderSpecsTextView.text = recorderSpecs val record = classifier.createAudioRecord() record.startRecording() Timer().scheduleAtFixedRate(1, 500) { val numberOfSamples = tensor.load(record) val output = classifier.classify(tensor) // TODO 2: Check if it's a bird sound. //var filteredModelOutput = output[0].categories.filter { // it.label.contains("Bird") && it.score > probabilityThreshold //} // TODO 3: given there's a bird sound, which one is it? //if (filteredModelOutput.isNotEmpty()) { // Log.i("Yamnet", "bird sound detected!") // filteredModelOutput = output[1].categories.filter { // it.score > probabilityThreshold // } //} val outputStr = filteredModelOutput.sortedBy { -it.score } .joinToString(separator = "\n") { "${it.label} -> ${it.score} " } if (outputStr.isNotEmpty()) runOnUiThread { textView.text = outputStr } } } }
apache-2.0
427f72aba161f6b959483f23967c0b7f
34.367816
91
0.656372
4.63253
false
false
false
false
jiangkang/KTools
video/src/main/java/com/jiangkang/video/surfaceview/SnowSurfaceView.kt
1
2604
package com.jiangkang.video.surfaceview import android.content.Context import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.graphics.Path import android.util.AttributeSet import android.view.SurfaceHolder import android.view.SurfaceView import android.view.View import kotlin.math.cos import kotlin.math.sin import kotlin.random.Random open class SnowSurfaceView : SurfaceView, SurfaceHolder.Callback2, Runnable { private lateinit var mPaint: Paint private lateinit var mCanvas: Canvas private var canDraw = false constructor(context: Context) : super(context) { initViews(context) } constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) { initViews(context) } constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { initViews(context) } private fun initViews(context: Context) { holder.addCallback(this) focusable = View.FOCUSABLE keepScreenOn = true isFocusableInTouchMode = true mPaint = Paint().apply { color = Color.WHITE isAntiAlias = true strokeJoin = Paint.Join.ROUND strokeCap = Paint.Cap.ROUND style = Paint.Style.FILL_AND_STROKE strokeWidth = 2f } } override fun surfaceCreated(holder: SurfaceHolder) { canDraw = true Thread(this).start() } override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) { } override fun surfaceDestroyed(holder: SurfaceHolder) { canDraw = false } override fun surfaceRedrawNeeded(holder: SurfaceHolder) { } override fun run() { // while (canDraw) { drawContent() // } } private fun drawContent() { mCanvas = holder.lockCanvas() val r = 30 val c = (randomY() + randomX())/ 2 val path = Path().apply { moveTo(r + c, c) for (i in 1 until 15) { val a = 0.44879895f * i val b = r + r * (i %2) lineTo(c + b * cos(a),c + b * sin(a)) } } mCanvas.drawPath(path, mPaint) holder.unlockCanvasAndPost(mCanvas) } private fun randomX(): Float { return width * Random.nextFloat() } private fun randomY(): Float { return height * Random.nextFloat() } private fun randomRadius(): Float { return 10 * Random.nextFloat() } }
mit
5b3dcb94a8e1807c22d4e10fe4a0b4a6
23.575472
114
0.614823
4.458904
false
false
false
false
looker-open-source/sdk-codegen
kotlin/src/main/com/looker/rtl/Constants.kt
1
4255
/* * The MIT License (MIT) * * Copyright (c) 2019 Looker Data Sciences, Inc. * * 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. */ @file:JvmName("Constants") package com.looker.rtl import java.text.SimpleDateFormat import java.time.ZonedDateTime import java.time.format.DateTimeFormatter import java.util.* const val MATCH_CHARSET = ";.*charset=" const val MATCH_CHARSET_UTF8 = """$MATCH_CHARSET.*\butf-8\b""" const val MATCH_MODE_STRING = """(^application/.*(\bjson\b|\bxml\b|\bsql\b|\bgraphql\b|\bjavascript\b|\bx-www-form-urlencoded\b)|^text/|.*\+xml\b|$MATCH_CHARSET)""" const val MATCH_MODE_BINARY = """^image/|^audio/|^video/|^font/|^application/|^multipart/""" val StringMatch = Regex(MATCH_MODE_STRING, RegexOption.IGNORE_CASE) val BinaryMatch = Regex(MATCH_MODE_BINARY, RegexOption.IGNORE_CASE) const val DEFAULT_TIMEOUT = 120 const val DEFAULT_API_VERSION = "4.0" // Kotlin requires at least API 4.0 typealias Values = Map<String, Any?> class DelimArray<T>(val values: Array<T>, private val delimiter: String = ",") { override fun toString(): String { return values.joinToString(delimiter) } } typealias UriString = String typealias UrlString = String /* TODO The above won't work long term, so we'll need to implement something... class DelimArray<T> : Array<T>() { } */ fun isTrue(value: String?): Boolean { val low = unQuote(value?.toLowerCase()) return low == "true" || low == "1" || low == "t" || low == "y" || low == "yes" } fun isFalse(value: String?): Boolean { val low = unQuote(value?.toLowerCase()) return low == "false" || low == "0" || low == "f" || low == "n" || low == "no" } fun asBoolean(value: String?): Boolean? { if (isTrue(value)) return true if (isFalse(value)) return false return null } /** * strip quotes from the value if the same "quote" character is the start and end of the string */ fun unQuote(value: String?): String { if (value === null) return "" if (value.isBlank()) return "" val quote = value.substring(0, 1) if ("\"`'".contains(quote)) { if (value.endsWith(quote)) { // Strip matching characters return value.substring(1, value.length - 1) } } return value } enum class ResponseMode { String, Binary, Unknown } fun responseMode(contentType: String): ResponseMode { if (StringMatch.containsMatchIn(contentType)) return ResponseMode.String if (BinaryMatch.containsMatchIn(contentType)) return ResponseMode.Binary return ResponseMode.Unknown } internal fun ZonedDateTime(utcDateTime: String): ZonedDateTime { return ZonedDateTime.parse(utcDateTime, DateTimeFormatter.ISO_OFFSET_DATE_TIME) } internal fun Date(utcDateTime: String): Date { val utcFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") utcFormat.timeZone = TimeZone.getTimeZone("UTC") return utcFormat.parse(utcDateTime) } /** Loads environment variables into system properties */ fun loadEnvironment(): Map<String, String> { // TODO get dotenv working for .env file loading https://github.com/cdimascio/dotenv-kotlin val envMap = System.getenv() for ((key, value) in envMap) System.setProperty(key, value) return envMap }
mit
f92df1682b1f62a51d87f758c21b5992
33.314516
138
0.701998
3.83679
false
false
false
false
idanarye/nisui
cli/src/main/kotlin/nisui/cli/RunSubcommand.kt
1
1582
package nisui.cli import java.io.PrintStream import java.io.InputStream import org.slf4j.LoggerFactory import picocli.CommandLine import nisui.core.* import nisui.simple_reactor.ExperimentFailedException import nisui.simple_reactor.SimpleReactor @CommandLine.Command( name = "run", description = ["Run the data-points we have prepared, storing the results in the database."] ) public class RunSubcommand(val nisuiFactory: NisuiFactory) : SubCommand() { companion object { private val logger = LoggerFactory.getLogger(this.javaClass.declaringClass) } override fun getNames(): Array<String> = arrayOf("run") @CommandLine.Option(names = ["-t", "--threads"], required = false, description = ["Number of threads to use."]) var numThreads: Int = 0 override fun run(in_: InputStream?, out_: PrintStream) { run(out_, nisuiFactory.createResultsStorage()) } private fun <D, R> run(out_: PrintStream, storage: ResultsStorage<D, R>) { val experimentFunction = nisuiFactory.createExperimentFunction() val numThreads = if (numThreads == 0) { numThreads = Runtime.getRuntime().availableProcessors() logger.info("Running experiment in {} threads", numThreads) numThreads } else { this.numThreads } val reactor = SimpleReactor<D, R>(numThreads, storage, experimentFunction, { logger.error(it.message) }) try { reactor.run() } catch (e: InterruptedException) { logger.info("Inetrrupted") } } }
mit
e0336af050e5a4ca36d946a97b5e7bf9
31.285714
115
0.666877
4.468927
false
false
false
false
sensefly-sa/dynamodb-to-s3
src/main/kotlin/io/sensefly/dynamodbtos3/RestoreTable.kt
1
3575
package io.sensefly.dynamodbtos3 import com.amazonaws.services.dynamodbv2.AmazonDynamoDB import com.amazonaws.services.dynamodbv2.document.DynamoDB import com.amazonaws.services.dynamodbv2.model.* import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.module.kotlin.readValue import com.google.common.base.Stopwatch import com.google.common.util.concurrent.RateLimiter import io.sensefly.dynamodbtos3.reader.ReaderFactory import org.slf4j.LoggerFactory import org.springframework.stereotype.Component import java.net.URI import java.text.NumberFormat import javax.inject.Inject @Component class RestoreTable @Inject constructor( private val dynamoDB: DynamoDB, private val amazonDynamoDB: AmazonDynamoDB, private val objectMapper: ObjectMapper, private val readerFactory: ReaderFactory<*>) { companion object { const val DEFAULT_WRITE_PERCENTAGE = 0.5 private const val LOG_PROGRESS_FREQ = 5000 } private val log = LoggerFactory.getLogger(javaClass) fun restore(source: URI, tableName: String, writePercentage: Double = DEFAULT_WRITE_PERCENTAGE) { val stopwatch = Stopwatch.createStarted() val writeCapacity = readCapacity(tableName) val batchSize = minOf(writeCapacity, 25) val permitsPerSec = writeCapacity.toDouble() * writePercentage * 10 val rateLimiter = RateLimiter.create(permitsPerSec) log.info("Start {} restore from {} with {} rate ({} write capacity)", tableName, source, permitsPerSec, writeCapacity) val writeRequests = mutableListOf<WriteRequest>() var count = 0 readerFactory.get(source).use { reader -> reader.read().bufferedReader().use { var line: String? do { line = it.readLine() if (line != null) { count++ val item: Map<String, AttributeValue> = objectMapper.readValue(line) writeRequests.add(WriteRequest(PutRequest(item))) if (writeRequests.size == batchSize) { write(mapOf(tableName to writeRequests), rateLimiter) writeRequests.clear() } } if (count % LOG_PROGRESS_FREQ == 0) { log.info("Table {}: {} items written ({})", tableName, NumberFormat.getInstance().format(count), stopwatch) } } while (line != null) // insert remaining items if (writeRequests.isNotEmpty()) { write(mapOf(tableName to writeRequests), rateLimiter) } } } log.info("Restore {} table ({} items) completed in {}", tableName, NumberFormat.getInstance().format(count), stopwatch) } private fun write(writeRequests: Map<String, List<WriteRequest>>, rateLimiter: RateLimiter) { val request = BatchWriteItemRequest() .withReturnConsumedCapacity(ReturnConsumedCapacity.TOTAL) .withRequestItems(writeRequests) val result = amazonDynamoDB.batchWriteItem(request) val consumedCapacity = if (result.consumedCapacity == null) 100.0 else result.consumedCapacity[0].capacityUnits val consumed = Math.round(consumedCapacity * 10).toInt() val wait = rateLimiter.acquire(consumed) log.debug("consumed: {}, wait: {}, capacity: {}", consumed, wait, consumedCapacity) if (result.unprocessedItems.isNotEmpty()) { log.debug("Reprocess {} items", result.unprocessedItems.size) write(result.unprocessedItems, rateLimiter) } } private fun readCapacity(tableName: String): Int { return Math.toIntExact(dynamoDB.getTable(tableName).describe().provisionedThroughput.writeCapacityUnits) } }
bsd-3-clause
413cbf48550b5f829097899695fcc2f0
36.25
123
0.706573
4.508197
false
false
false
false
consp1racy/android-commons
commons/src/main/java/net/xpece/android/view/ViewFader.kt
1
2184
package net.xpece.android.view import android.support.annotation.RequiresApi import android.support.v4.view.ViewCompat import android.view.View import android.view.View.VISIBLE import android.view.animation.AccelerateInterpolator import android.view.animation.DecelerateInterpolator import java.util.* @RequiresApi(16) class ViewFader { companion object { private val HIDE_INTERPOLATOR = AccelerateInterpolator() private val SHOW_INTERPOLATOR = DecelerateInterpolator() private const val FADE_OUT_DURATION_MILLIS = 200L private const val FADE_IN_DURATION_MILLIS = 100L private const val SHOWING = 0 private const val HIDING = 1 } private val fadingViews = WeakHashMap<View, Int>() fun isFadingIn(view: View) = fadingViews[view] == SHOWING fun isFadingOut(view: View) = fadingViews[view] == HIDING fun fadeOut(view: View): Unit = view.run { if (visibility == VISIBLE && !isFadingOut(this)) { clearAnimation() if (ViewCompat.isLaidOut(this)) { animate() .alpha(0F) .setDuration(FADE_OUT_DURATION_MILLIS) .setInterpolator(HIDE_INTERPOLATOR) .withStartAction { fadingViews[this] = HIDING } .withEndAction { invisible(); fadingViews.remove(this) } .start() } else { invisible() alpha = 0F } } } fun fadeIn(view: View): Unit = view.run { if (visibility != VISIBLE && !isFadingIn(this)) { clearAnimation() if (ViewCompat.isLaidOut(this)) { animate() .alpha(1F) .setDuration(FADE_IN_DURATION_MILLIS) .setInterpolator(SHOW_INTERPOLATOR) .withStartAction { fadingViews[this] = SHOWING; visible() } .withEndAction { fadingViews.remove(this) } .start() } else { alpha = 1F visible() } } } }
apache-2.0
a9c153864186111eb59fe41194650642
32.6
83
0.553571
4.918919
false
false
false
false
xfournet/intellij-community
platform/lang-impl/src/com/intellij/openapi/module/impl/AutomaticModuleUnloader.kt
1
7679
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.module.impl import com.intellij.notification.Notification import com.intellij.notification.NotificationAction import com.intellij.notification.NotificationGroup import com.intellij.notification.NotificationType import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.components.* import com.intellij.openapi.module.ModuleDescription import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ui.configuration.ConfigureUnloadedModulesDialog import com.intellij.util.xmlb.annotations.XCollection import com.intellij.xml.util.XmlStringUtil /** * If some modules were unloaded and new modules appears after loading project configuration, automatically unloads those which * aren't required for loaded modules. * * @author nik */ @State(name = "AutomaticModuleUnloader", storages = [(Storage(StoragePathMacros.WORKSPACE_FILE))]) class AutomaticModuleUnloader(private val project: Project) : PersistentStateComponent<LoadedModulesListStorage> { private val loadedModulesListStorage = LoadedModulesListStorage() fun processNewModules(modulesToLoad: Set<ModulePath>, modulesToUnload: List<UnloadedModuleDescriptionImpl>): UnloadedModulesListChange { val oldLoaded = loadedModulesListStorage.modules.toSet() if (oldLoaded.isEmpty() || modulesToLoad.all { it.moduleName in oldLoaded }) { return UnloadedModulesListChange(emptyList(), emptyList(), emptyList()) } val moduleDescriptions = LinkedHashMap<String, UnloadedModuleDescriptionImpl>(modulesToLoad.size + modulesToUnload.size) UnloadedModuleDescriptionImpl.createFromPaths(modulesToLoad, project).associateByTo(moduleDescriptions) { it.name } modulesToUnload.associateByTo(moduleDescriptions) { it.name } val oldLoadedWithDependencies = HashSet<ModuleDescription>() val explicitlyUnloaded = modulesToUnload.mapTo(HashSet()) { it.name } for (name in oldLoaded) { processTransitiveDependencies(name, moduleDescriptions, explicitlyUnloaded, oldLoadedWithDependencies) } val newLoadedNames = oldLoadedWithDependencies.mapTo(LinkedHashSet()) { it.name } val toLoad = modulesToLoad.filter { it.moduleName in newLoadedNames && it.moduleName !in oldLoaded} val toUnload = modulesToLoad.filter { it.moduleName !in newLoadedNames } loadedModulesListStorage.modules.clear() modulesToLoad.filter { it.moduleName in newLoadedNames }.mapTo(loadedModulesListStorage.modules) { it.moduleName } val change = UnloadedModulesListChange(toLoad, toUnload, toUnload.map { moduleDescriptions[it.moduleName]!! }) fireNotifications(change) return change } private fun processTransitiveDependencies(name: String, moduleDescriptions: Map<String, UnloadedModuleDescriptionImpl>, explicitlyUnloaded: Set<String>, result: MutableSet<ModuleDescription>) { if (name in explicitlyUnloaded) return val module = moduleDescriptions[name] if (module == null || !result.add(module)) return module.dependencyModuleNames.forEach { processTransitiveDependencies(it, moduleDescriptions, explicitlyUnloaded, result) } } private fun fireNotifications(change: UnloadedModulesListChange) { if (change.toLoad.isEmpty() && change.toUnload.isEmpty()) return val messages = ArrayList<String>() val actions = ArrayList<NotificationAction>() populateNotification(change.toUnload, messages, actions, "Load", {"Load $it back"}, change.toLoad.isEmpty(), {"unloaded"}) { it.removeAll(change.toUnload.map { it.moduleName }) } populateNotification(change.toLoad, messages, actions, "Unload", {"Unload $it"}, change.toUnload.isEmpty(), {"loaded because some other modules depend on $it"}) { it.addAll(change.toLoad.map { it.moduleName }) } actions.add(object: NotificationAction("Configure Unloaded Modules") { override fun actionPerformed(e: AnActionEvent, notification: Notification) { val ok = ConfigureUnloadedModulesDialog(project, null).showAndGet() if (ok) { notification.expire() } } }) NOTIFICATION_GROUP.createNotification("New Modules are Added", XmlStringUtil.wrapInHtml(messages.joinToString("<br>")), NotificationType.INFORMATION, null) .apply { actions.forEach { addAction(it) } } .notify(project) } private fun populateNotification(modules: List<ModulePath>, messages: ArrayList<String>, actions: ArrayList<NotificationAction>, revertActionName: String, revertActionShortText: (String) -> String, useShortActionText: Boolean, statusDescription: (String) -> String, revertAction: (MutableList<String>) -> Unit) { when { modules.size == 1 -> { val moduleName = modules.single().moduleName messages.add("Newly added module '$moduleName' was automatically ${statusDescription("it")}.") val text = if (useShortActionText) revertActionShortText("it") else "$revertActionName '$moduleName' module" actions.add(createAction(text, revertAction)) } modules.size == 2 -> { val names = "'${modules[0].moduleName}' and '${modules[1].moduleName}'" messages.add("Newly added modules $names were automatically ${statusDescription("them")}.") val text = if (useShortActionText) revertActionShortText("them") else "$revertActionName modules $names" actions.add(createAction(text, revertAction)) } modules.size > 2 -> { val names = "'${modules.first().moduleName}' and ${modules.size - 1} more modules" messages.add("$names were automatically ${statusDescription("them")}.") val text = if (useShortActionText) revertActionShortText("them") else "$revertActionName $names" actions.add(createAction(text, revertAction)) } } } fun createAction(text: String, action: (MutableList<String>) -> Unit) = object : NotificationAction(text) { override fun actionPerformed(e: AnActionEvent, notification: Notification) { val unloaded = ArrayList<String>() val moduleManager = ModuleManager.getInstance(project) moduleManager.unloadedModuleDescriptions.mapTo(unloaded) { it.name } action(unloaded) moduleManager.setUnloadedModules(unloaded) notification.expire() } } fun setLoadedModules(modules: List<String>) { loadedModulesListStorage.modules.clear() loadedModulesListStorage.modules.addAll(modules) } override fun getState() = loadedModulesListStorage override fun loadState(state: LoadedModulesListStorage) { setLoadedModules(state.modules) } companion object { @JvmStatic fun getInstance(project: Project) = project.service<AutomaticModuleUnloader>() private val NOTIFICATION_GROUP = NotificationGroup.balloonGroup("Automatic Module Unloading") } } class LoadedModulesListStorage { @get:XCollection(elementName = "module", valueAttributeName = "name", propertyElementName = "loaded-modules") var modules: MutableList<String> = ArrayList() } class UnloadedModulesListChange(val toLoad: List<ModulePath>, val toUnload: List<ModulePath>, val toUnloadDescriptions: List<UnloadedModuleDescriptionImpl>)
apache-2.0
8388e9fa57ad0f29c42a3def902a19ff
47.601266
166
0.71676
5.122748
false
false
false
false
jmesserli/discord-bernbot
discord-bot/src/main/kotlin/nu/peg/discord/command/handler/internal/KeepOutCommandHandler.kt
1
4415
package nu.peg.discord.command.handler.internal import nu.peg.discord.command.Command import org.springframework.stereotype.Component import sx.blah.discord.handle.impl.events.guild.voice.user.UserVoiceChannelEvent import sx.blah.discord.handle.impl.events.guild.voice.user.UserVoiceChannelJoinEvent import sx.blah.discord.handle.impl.events.guild.voice.user.UserVoiceChannelMoveEvent import sx.blah.discord.handle.obj.IChannel import sx.blah.discord.handle.obj.IMessage import sx.blah.discord.handle.obj.IUser import sx.blah.discord.handle.obj.IVoiceChannel import java.time.Duration import java.time.LocalDateTime import java.time.format.DateTimeFormatter @Component class KeepOutCommandHandler : AbstractVoiceChannelCommandHandler(false) { override fun isAdminCommand() = true override fun getNames() = listOf("ko", "keepout") override fun getDescription() = "Keep a user out of the current channel for a period" override fun handle(command: Command, message: IMessage, userChannel: IVoiceChannel, targetChannel: IVoiceChannel?) { val channel = message.channel val targetUserArg = command.args[0] val targetUser = command.message.guild.users.firstOrNull { it.name.contains(targetUserArg, ignoreCase = true) } if (targetUser == null) { channel.sendMessage("No user found that matches \"$targetUserArg\"") return } val durationArg = command.args[1] val duration = try { Duration.parse(durationArg) } catch (e: Exception) { null } if (duration == null) { channel.sendMessage("Could not parse duration \"$durationArg\". Must be formatted according to https://en.wikipedia.org/wiki/ISO_8601#Durations") return } val dateFormat = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss") val endTime = LocalDateTime.now().plus(duration) if (endTime.isBefore(LocalDateTime.now())) { channel.sendMessage("End of duration must be in the future (ends at ${endTime.format(dateFormat)})") return } KeepOutEventHandler.addUserChannelBan(targetUser, ChannelDuration(userChannel, endTime)) channel.sendMessage("Keeping user ${targetUser.getDisplayName(channel.guild)} out of ${userChannel.name} until ${endTime.format(dateFormat)}") } } data class ChannelDuration( val channel: IVoiceChannel, val endTime: LocalDateTime ) object KeepOutEventHandler { private val userKeepOutMap: MutableMap<IUser, ChannelDuration> = mutableMapOf() fun addUserChannelBan(user: IUser, channelDuration: ChannelDuration) { userKeepOutMap[user] = channelDuration val userVoiceState = user.voiceStates[channelDuration.channel.guild.longID] if (userVoiceState != null && userVoiceState.channel != null) { user.moveToVoiceChannel(findMoveChannel(channelDuration.channel)) } } private fun userHasBanFromChannel(user: IUser, channel: IChannel): Boolean { val channelDuration = userKeepOutMap[user] ?: return false if (channelDuration.channel != channel) { return false } if (channelDuration.endTime.isBefore(LocalDateTime.now())) { userKeepOutMap.remove(user) return false } return true } private fun findMoveChannel(notChannel: IVoiceChannel): IVoiceChannel { val eligibleChannels = notChannel.guild.voiceChannels.filter { it != notChannel } return eligibleChannels.first { it.usersHere.isEmpty() } ?: return eligibleChannels.sortedBy { it.usersHere.size }.first<IVoiceChannel>() } fun handleEvent(userVoiceChannelEvent: UserVoiceChannelEvent) { if (userVoiceChannelEvent !is UserVoiceChannelJoinEvent && userVoiceChannelEvent !is UserVoiceChannelMoveEvent) { return } val user = userVoiceChannelEvent.user val targetChannel = userVoiceChannelEvent.voiceChannel val isBanned = userHasBanFromChannel(user, targetChannel) if (!isBanned) return if (userVoiceChannelEvent is UserVoiceChannelMoveEvent) { user.moveToVoiceChannel(userVoiceChannelEvent.oldChannel) } user.moveToVoiceChannel(findMoveChannel(targetChannel)) } fun clearBans() { userKeepOutMap.clear() } }
mit
f0a4b6ff686fe73838c5c33d126d1257
37.736842
157
0.699434
4.706823
false
false
false
false
noties/Markwon
app-sample/src/main/java/io/noties/markwon/app/samples/EnabledBlockTypesSample.kt
1
1495
package io.noties.markwon.app.samples import io.noties.markwon.AbstractMarkwonPlugin import io.noties.markwon.Markwon import io.noties.markwon.app.sample.ui.MarkwonTextViewSample import io.noties.markwon.core.CorePlugin import io.noties.markwon.sample.annotations.MarkwonArtifact import io.noties.markwon.sample.annotations.MarkwonSampleInfo import io.noties.markwon.sample.annotations.Tag import org.commonmark.node.BlockQuote import org.commonmark.parser.Parser @MarkwonSampleInfo( id = "20200627075012", title = "Enabled markdown blocks", description = "Modify/inspect enabled by `CorePlugin` block types. " + "Disable quotes or other blocks from being parsed", artifacts = [MarkwonArtifact.CORE], tags = [Tag.parsing, Tag.block, Tag.plugin] ) class EnabledBlockTypesSample : MarkwonTextViewSample() { override fun render() { val md = """ # Heading ## Second level > Quote is not handled """.trimIndent() val markwon = Markwon.builder(context) .usePlugin(object : AbstractMarkwonPlugin() { override fun configureParser(builder: Parser.Builder) { // obtain all enabled block types val enabledBlockTypes = CorePlugin.enabledBlockTypes() // it is safe to modify returned collection // remove quotes enabledBlockTypes.remove(BlockQuote::class.java) builder.enabledBlockTypes(enabledBlockTypes) } }) .build() markwon.setMarkdown(textView, md) } }
apache-2.0
0db2c6f90aa67009b123c9e141e35088
32.244444
72
0.721739
4.436202
false
false
false
false
noties/Markwon
app-sample/src/main/java/io/noties/markwon/app/samples/image/CoilImageSample.kt
1
2302
package io.noties.markwon.app.samples.image import coil.ImageLoader import coil.request.Disposable import coil.request.ImageRequest import coil.transform.CircleCropTransformation import io.noties.markwon.Markwon import io.noties.markwon.app.sample.ui.MarkwonTextViewSample import io.noties.markwon.image.AsyncDrawable import io.noties.markwon.image.coil.CoilImagesPlugin import io.noties.markwon.sample.annotations.MarkwonArtifact import io.noties.markwon.sample.annotations.MarkwonSampleInfo import io.noties.markwon.sample.annotations.Tag @MarkwonSampleInfo( id = "20200826101209", title = "Coil image", artifacts = [MarkwonArtifact.IMAGE_COIL], tags = [Tag.image] ) class CoilImageSample : MarkwonTextViewSample() { override fun render() { val md = """ # H1 ## H2 ### H3 #### H4 ##### H5 > a quote + one - two * three 1. one 1. two 1. three --- # Images ![img](https://picsum.photos/id/237/1024/800) """.trimIndent() // pick one val markwon = Markwon.builder(context) // .usePlugin(coilPlugin1) // .usePlugin(coilPlugin2) .usePlugin(coilPlugin3) .build() markwon.setMarkdown(textView, md) } val coilPlugin1: CoilImagesPlugin get() = CoilImagesPlugin.create(context) val coilPlugin2: CoilImagesPlugin get() = CoilImagesPlugin.create(context, imageLoader) val coilPlugin3: CoilImagesPlugin get() { val loader = imageLoader return CoilImagesPlugin.create( object : CoilImagesPlugin.CoilStore { override fun load(drawable: AsyncDrawable): ImageRequest { return ImageRequest.Builder(context) .defaults(loader.defaults) .data(drawable.destination) .crossfade(true) .transformations(CircleCropTransformation()) .build() } override fun cancel(disposable: Disposable) { disposable.dispose() } }, loader ) } val imageLoader: ImageLoader get() = ImageLoader.Builder(context) .apply { availableMemoryPercentage(0.5) bitmapPoolPercentage(0.5) crossfade(true) } .build() }
apache-2.0
38f76debaee38a51b892213a77e14a66
23.763441
68
0.634666
4.46124
false
false
false
false
hamen/kled
src/Main.kt
1
1577
import purejavahidapi.HidDeviceInfo import purejavahidapi.PureJavaHidApi fun main(args: Array<String>) { try { var devInfo: HidDeviceInfo? = getDevice() if (devInfo == null) { println("Device not found. Supported device are: ") println("VENDORID: 0x1294 - PRODUCTID: 0x1320 http://www.dx.com/p/usb-universal-e-mail-webmail-im-notifier-gmail-outlook-outlook-express-pop3-27062#.Vkw0at-rTo0") } else { val data: ByteArray if (args.size == 0 || (args.size == 1 && args[0] == "--help")) { println("Use one of these colors as first argument:") println("off, blue, red, green, liteblue, purple, yellow, white") data = byteArrayOf(Colors.OFF.second.toByte()) } else { val color = Colors.colors.get(args[0].toLowerCase()) ?: 0 data = byteArrayOf(color.toByte()) } setLedColor(data, devInfo) } } catch (e: Exception) { e.printStackTrace() } } private fun getDevice(): HidDeviceInfo? { val devList = PureJavaHidApi.enumerateDevices() var devInfo: HidDeviceInfo? = null for (info in devList) { if (info.vendorId == 0x1294.toShort() && info.productId == 0x1320.toShort()) { devInfo = info break } } return devInfo } private fun setLedColor(data: ByteArray, devInfo: HidDeviceInfo) { val dev = PureJavaHidApi.openDevice(devInfo.path) dev.setOutputReport(0.toByte(), data, data.size) dev.close() }
apache-2.0
3bbdc9efaa295a48af9faff6207507dc
33.304348
174
0.594166
3.763723
false
false
false
false
devunt/ika
app/src/main/kotlin/org/ozinger/ika/database/models/Account.kt
1
1895
package org.ozinger.ika.database.models import at.favre.lib.crypto.bcrypt.BCrypt import org.jetbrains.exposed.dao.IntEntity import org.jetbrains.exposed.dao.IntEntityClass import org.jetbrains.exposed.dao.id.EntityID import org.jetbrains.exposed.dao.id.IntIdTable import org.jetbrains.exposed.sql.javatime.datetime import java.security.MessageDigest import java.util.* object Accounts : IntIdTable() { val email = varchar("email", 255) val password = varchar("password", 128) val vhost = varchar("vhost", 255) val createdAt = datetime("created_on") val authenticatedAt = datetime("authenticated_on") } class Account(id: EntityID<Int>) : IntEntity(id) { companion object : IntEntityClass<Account>(Accounts) { fun getByNickname(nickname: String) = Nickname.find { Nicknames.name eq nickname }.firstOrNull()?.account } var email by Accounts.email var password by Accounts.password var vhost by Accounts.vhost var createdAt by Accounts.createdAt var authenticatedAt by Accounts.authenticatedAt val nicknames by Nickname referrersOn Nicknames.account val name get() = nicknames.first { it.isAccountName }.name fun changePassword(password: String) { // python passlib bcrypt sha256 compat val encoded = Base64.getEncoder().encodeToString(MessageDigest.getInstance("SHA-256").digest(password.toByteArray())) this.password = "passlib_bcrypt_sha256\$" + BCrypt.withDefaults().hashToString(12, encoded.toCharArray()) } fun verifyPassword(password: String): Boolean { // python passlib bcrypt sha256 compat val encoded = Base64.getEncoder().encodeToString(MessageDigest.getInstance("SHA-256").digest(password.toByteArray())) val hashed = this.password.drop(22) return BCrypt.verifyer().verify(encoded.toCharArray(), hashed).verified } }
agpl-3.0
fc4f3aa8e5a7a529f2a6e0c707ace323
36.9
115
0.725066
4.277652
false
false
false
false
alygin/intellij-rust
src/test/kotlin/org/rust/ide/inspections/RsDoubleNegInspectionTest.kt
4
996
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.inspections /** * Tests for Double Negation inspection. */ class RsDoubleNegInspectionTest : RsInspectionsTestBase(RsDoubleNegInspection()) { fun testSimple() = checkByText(""" fn main() { let a = 12; let b = <warning descr="--x could be misinterpreted as a pre-decrement, but effectively is a no-op">--a</warning>; } """) fun testWithSpaces() = checkByText(""" fn main() { let i = 10; while <warning descr="--x could be misinterpreted as a pre-decrement, but effectively is a no-op">- - i</warning> > 0 {} } """) fun testExpression() = checkByText(""" fn main() { let a = 7; println!("{}", <warning descr="--x could be misinterpreted as a pre-decrement, but effectively is a no-op">--(2*a + 1)</warning>); } """) }
mit
d2dfd7b9057c998520bed1ab33fcaafd
29.181818
143
0.576305
4.032389
false
true
false
false
VisualDig/visualdig-kotlin
dig/src/main/io/visualdig/DigController.kt
1
6605
package io.visualdig import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import com.fasterxml.jackson.module.kotlin.readValue import io.visualdig.actions.ClickAction import io.visualdig.actions.ExecutedQuery.Companion.createExecutedQuery import io.visualdig.actions.GoToAction import io.visualdig.actions.SpacialSearchAction import io.visualdig.element.DigElementQuery import io.visualdig.element.DigTextQuery import io.visualdig.exceptions.* import io.visualdig.results.* import org.springframework.beans.factory.config.BeanDefinition.SCOPE_SINGLETON import org.springframework.context.annotation.Scope import org.springframework.web.socket.TextMessage import org.springframework.web.socket.WebSocketSession import org.springframework.web.socket.handler.TextWebSocketHandler import java.net.URI import java.net.URL import java.util.concurrent.CompletableFuture import java.util.concurrent.TimeUnit import kotlin.properties.Delegates import kotlin.reflect.KClass @Scope(SCOPE_SINGLETON) open class DigController : TextWebSocketHandler() { private var initialized: Boolean = false private val futureSession: CompletableFuture<WebSocketSession> = CompletableFuture() private fun webSocketSession() = futureSession.get(5, TimeUnit.SECONDS) var messageListeners: MutableList<(String) -> Unit> = mutableListOf() var message: String by Delegates.observable("latestMessage") { _, _, new -> synchronized(messageListeners) { messageListeners.forEach { it(new) } messageListeners.clear() } } fun listenToNextMessage(handler: (String) -> Unit) { synchronized(messageListeners) { messageListeners.add(handler) } } @Throws(Exception::class) override fun afterConnectionEstablished(session: WebSocketSession) { if (futureSession.isDone && futureSession.get().id != session.id) { throw Exception("Session ids do not match. VisualDig does not support multiple websocket connections at once") } if (!futureSession.isDone) { futureSession.complete(session) } } override fun handleTextMessage(session: WebSocketSession?, message: TextMessage?) { if (message == null) { throw Exception("Message was null in the main websocket hanndler!") } if (session == null) { throw Exception("Session was null in the main websocket hanndler!") } if (futureSession.isDone && futureSession.get().id != session.id) { throw Exception("Session ids do not match. VisualDig does not support multiple websocket connections at once") } if (message.payload == null) { throw Exception("Response was empty, something went wrong") } this.message = message.payload } fun goTo(uri: URI) { val url: URL = uri.toURL() ?: throw Exception("URI provided was invalid") val urlString = url.toExternalForm() val goToAction = GoToAction(uri = urlString) val validResult = sendAndReceive(TestResult::class, goToAction, this::objectMap) if (validResult.result.isFailure()) { val message = validResult.message throw DigWebsiteException("Browser failed to go to URL: $urlString\n\n$message") } initialized = true } fun find(digTextQuery: DigTextQuery): FindTextResult { if (!initialized) { throw DigWebsiteException("Call Dig.goTo before calling any query or interaction methods.") } val validResult = sendAndReceive(FindTextResult::class, digTextQuery.specificAction(), this::objectMap) if (validResult.result.isFailure()) throw DigTextNotFoundException(digTextQuery, validResult.closestMatches.first()) return validResult } open fun click(digId: Int, prevQueries: List<DigElementQuery>) { if (!initialized) { throw DigWebsiteException("Call Dig.goTo before calling any queryUsed or interaction methods.") } val action = ClickAction.createClickAction(digId, prevQueries.map(::createExecutedQuery)) val validResult = sendAndReceive(TestResult::class, action, this::objectMap) if (validResult.result.isFailure() && action.prevQueries.isNotEmpty()) { throw DigPreviousQueryFailedException("Could not find previously found element, TODO more error message.") } } open fun search(action: SpacialSearchAction): SpacialSearchResult { if (!initialized) { throw DigWebsiteException("Call Dig.goTo before calling any action or interaction methods.") } val validResult : SpacialSearchResult = sendAndReceive(SpacialSearchResult::class, action, this::objectMap) if (validResult.result.isFailure()) { if (validResult.result.result.contains("QueryExpired")) { throw DigPreviousQueryFailedException("Could not find previously found element, TODO more error message.") } else { throw DigSpacialException(action, validResult) } } return validResult } private inline fun <reified R : Any> objectMap(text:String) : R { return jacksonObjectMapper().readValue(text) } private fun <A, R : Any> sendAndReceive(resultType: KClass<R>, action: A, method: (String) -> R): R { val resultWaiter: CompletableFuture<ResponseWrapper> = CompletableFuture() listenToNextMessage({ message -> try { val obj: R = method(message) resultWaiter.complete(ResponseWrapper.Success(obj)) } catch (e: Exception) { println(e.message) resultWaiter.complete(ResponseWrapper.BadMessage(message)) } }) val session: WebSocketSession = webSocketSession() ?: throw Exception("No session exists yet") session.sendMessage(TextMessage(jacksonObjectMapper().writeValueAsString(action))) val testResult = resultWaiter.get(5, TimeUnit.SECONDS) when (testResult) { is ResponseWrapper.BadMessage -> { val jsonMessage = testResult.jsonMessage val className = resultType.simpleName throw DigFatalException(""" Expected $className message but was unable to parse it. JSON message received from elm: $jsonMessage""") } is ResponseWrapper.Success<*> -> { return testResult.result as R } } } }
mit
f569cd434fe6966cf8eaae30e06f21d1
36.534091
122
0.674186
5.003788
false
false
false
false
ankidroid/Anki-Android
AnkiDroid/src/main/java/com/ichi2/anki/SharedDecksActivity.kt
1
8389
/**************************************************************************************** * * * Copyright (c) 2021 Shridhar Goel <[email protected]> * * * * This program is free software; you can redistribute it and/or modify it under * * the terms of the GNU General Public License as published by the Free Software * * Foundation; either version 3 of the License, or (at your option) any later * * version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along with * * this program. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************************/ package com.ichi2.anki import android.app.DownloadManager import android.content.* import android.os.Bundle import android.view.Menu import android.view.MenuItem import android.webkit.* import androidx.appcompat.widget.SearchView import androidx.appcompat.widget.Toolbar import androidx.core.content.ContextCompat import androidx.core.os.bundleOf import androidx.fragment.app.commit import timber.log.Timber import java.io.Serializable /** * Browse AnkiWeb shared decks with the functionality to download and import them. */ class SharedDecksActivity : AnkiActivity() { private lateinit var mWebView: WebView lateinit var downloadManager: DownloadManager private var mShouldHistoryBeCleared = false /** * Handle condition when page finishes loading and history needs to be cleared. * Currently, this condition arises when user presses the home button on the toolbar. * * History should not be cleared before the page finishes loading otherwise there would be * an extra entry in the history since the previous page would not get cleared. */ private val mWebViewClient = object : WebViewClient() { override fun onPageFinished(view: WebView?, url: String?) { // Clear history if mShouldHistoryBeCleared is true and set it to false if (mShouldHistoryBeCleared) { mWebView.clearHistory() mShouldHistoryBeCleared = false } super.onPageFinished(view, url) } override fun onReceivedError(view: WebView?, request: WebResourceRequest?, error: WebResourceError?) { // Set mShouldHistoryBeCleared to false if error occurs since it might have been true mShouldHistoryBeCleared = false super.onReceivedError(view, request, error) } } companion object { const val SHARED_DECKS_DOWNLOAD_FRAGMENT = "SharedDecksDownloadFragment" const val DOWNLOAD_FILE = "DownloadFile" } // Show WebView with AnkiWeb shared decks with the functionality to capture downloads and import decks. override fun onCreate(savedInstanceState: Bundle?) { if (showedActivityFailedScreen(savedInstanceState)) { return } super.onCreate(savedInstanceState) setContentView(R.layout.activity_shared_decks) setTitle(R.string.download_deck) val webviewToolbar: Toolbar = findViewById(R.id.webview_toolbar) webviewToolbar.setTitleTextColor(ContextCompat.getColor(this, R.color.white)) setSupportActionBar(webviewToolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) supportActionBar?.setDisplayShowHomeEnabled(true) webviewToolbar.navigationIcon = ContextCompat.getDrawable(this, R.drawable.close_icon) mWebView = findViewById(R.id.web_view) downloadManager = getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager mWebView.settings.javaScriptEnabled = true mWebView.loadUrl(resources.getString(R.string.shared_decks_url)) mWebView.webViewClient = WebViewClient() mWebView.setDownloadListener { url, userAgent, contentDisposition, mimetype, _ -> val sharedDecksDownloadFragment = SharedDecksDownloadFragment() sharedDecksDownloadFragment.arguments = bundleOf(DOWNLOAD_FILE to DownloadFile(url, userAgent, contentDisposition, mimetype)) supportFragmentManager.commit { add(R.id.shared_decks_fragment_container, sharedDecksDownloadFragment, SHARED_DECKS_DOWNLOAD_FRAGMENT) } } mWebView.webViewClient = mWebViewClient } /** * If download screen is open: * If download is in progress: Show download cancellation dialog * If download is not in progress: Close the download screen * If user can go back in WebView, navigate to previous webpage. * Otherwise, close the WebView. */ @Suppress("deprecation") // onBackPressed override fun onBackPressed() { when { sharedDecksDownloadFragmentExists() -> { supportFragmentManager.findFragmentByTag(SHARED_DECKS_DOWNLOAD_FRAGMENT)?.let { if ((it as SharedDecksDownloadFragment).isDownloadInProgress) { Timber.i("Back pressed when download is in progress, show cancellation confirmation dialog") // Show cancel confirmation dialog if download is in progress it.showCancelConfirmationDialog() } else { Timber.i("Back pressed when download is not in progress but download screen is open, close fragment") // Remove fragment supportFragmentManager.commit { remove(it) } } } supportFragmentManager.popBackStackImmediate() } mWebView.canGoBack() -> { Timber.i("Back pressed when user can navigate back to other webpages inside WebView") mWebView.goBack() } else -> { Timber.i("Back pressed which would lead to closing of the WebView") super.onBackPressed() } } } private fun sharedDecksDownloadFragmentExists(): Boolean { val sharedDecksDownloadFragment = supportFragmentManager.findFragmentByTag(SHARED_DECKS_DOWNLOAD_FRAGMENT) return sharedDecksDownloadFragment != null && sharedDecksDownloadFragment.isAdded } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.download_shared_decks_menu, menu) val searchView = menu.findItem(R.id.search)?.actionView as SearchView searchView.queryHint = getString(R.string.search_using_deck_name) searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextSubmit(query: String?): Boolean { mWebView.loadUrl(resources.getString(R.string.shared_decks_url) + query) return true } override fun onQueryTextChange(newText: String?): Boolean { // Nothing to do here return false } }) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == R.id.home) { mShouldHistoryBeCleared = true mWebView.loadUrl(resources.getString(R.string.shared_decks_url)) } return super.onOptionsItemSelected(item) } } /** * Used for sending URL, user agent, content disposition and mime type to SharedDecksDownloadFragment. */ data class DownloadFile( val url: String, val userAgent: String, val contentDisposition: String, val mimeType: String, ) : Serializable
gpl-3.0
12ae6d859d3a542e5620308970e3f8ff
43.152632
137
0.613303
5.785517
false
false
false
false
ebraminio/DroidPersianCalendar
PersianCalendar/src/main/java/com/byagowi/persiancalendar/ui/about/DeviceInformationFragment.kt
1
12492
package com.byagowi.persiancalendar.ui.about import android.app.Activity import android.app.ActivityManager import android.hardware.Sensor import android.hardware.SensorManager import android.opengl.EGL14 import android.opengl.EGLConfig import android.opengl.GLES10 import android.opengl.GLES20 import android.os.BatteryManager import android.os.Build import android.os.Bundle import android.text.SpannableString import android.text.SpannableStringBuilder import android.text.Spanned import android.text.method.LinkMovementMethod import android.text.style.ClickableSpan import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.browser.customtabs.CustomTabsIntent import androidx.core.content.getSystemService import androidx.core.net.toUri import androidx.fragment.app.Fragment import androidx.recyclerview.widget.* import com.byagowi.persiancalendar.R import com.byagowi.persiancalendar.databinding.DeviceInformationRowBinding import com.byagowi.persiancalendar.databinding.FragmentDeviceInfoBinding import com.byagowi.persiancalendar.ui.MainActivity import com.byagowi.persiancalendar.utils.circularRevealFromMiddle import com.byagowi.persiancalendar.utils.copyToClipboard import com.byagowi.persiancalendar.utils.layoutInflater import com.google.android.material.bottomnavigation.LabelVisibilityMode import com.google.android.material.bottomsheet.BottomSheetDialog import java.util.* /** * @author MEHDI DIMYADI * MEHDIMYADI */ class DeviceInformationFragment : Fragment() { private var clickCount: Int = 0 override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? = FragmentDeviceInfoBinding.inflate(inflater, container, false).apply { val mainActivity = activity as MainActivity mainActivity.setTitleAndSubtitle(getString(R.string.device_info), "") circularRevealFromMiddle(circularReveal) recyclerView.apply { setHasFixedSize(true) layoutManager = LinearLayoutManager(mainActivity) addItemDecoration(DividerItemDecoration(mainActivity, LinearLayoutManager.VERTICAL)) adapter = DeviceInformationAdapter(mainActivity, root) } bottomNavigation.apply { menu.apply { add(Build.VERSION.RELEASE) getItem(0).setIcon(R.drawable.ic_developer) add("API " + Build.VERSION.SDK_INT) getItem(1).setIcon(R.drawable.ic_settings) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { add(Build.SUPPORTED_ABIS[0]) } else { add(Build.CPU_ABI) } getItem(2).setIcon(R.drawable.ic_motorcycle) add(Build.MODEL) getItem(3).setIcon(R.drawable.ic_device_information_white) } labelVisibilityMode = LabelVisibilityMode.LABEL_VISIBILITY_LABELED setOnNavigationItemSelectedListener { // Easter egg if (++clickCount % 10 == 0) { BottomSheetDialog(mainActivity).apply { setContentView(IndeterminateProgressBar(mainActivity).apply { layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 700) }) }.show() } true } } }.root } class DeviceInformationAdapter(activity: Activity, private val rootView: View) : ListAdapter<DeviceInformationAdapter.Item, DeviceInformationAdapter.ViewHolder>( DeviceInformationDiffCallback() ) { data class Item(val title: String, val content: CharSequence?, val version: String) val deviceInformationItems: List<Item> = listOf( Item("Screen Resolution", activity.windowManager.run { "%d*%d pixels".format(Locale.ENGLISH, defaultDisplay.width, defaultDisplay.height) }, ""), Item("DPI", activity.resources.displayMetrics.densityDpi.toString(), ""), Item( "Android Version", Build.VERSION.CODENAME + " " + Build.VERSION.RELEASE, Build.VERSION.SDK_INT.toString() ), Item("Manufacturer", Build.MANUFACTURER, ""), Item("Brand", Build.BRAND, ""), Item("Model", Build.MODEL, ""), Item("Product", Build.PRODUCT, ""), Item("Instruction Architecture", Build.DEVICE, ""), Item("Android Id", Build.ID, ""), Item("Board", Build.BOARD, ""), Item("Radio Firmware Version", Build.getRadioVersion(), ""), Item("Build User", Build.USER, ""), Item("Host", Build.HOST, ""), Item("Display", Build.DISPLAY, ""), Item("Device Fingerprints", Build.FINGERPRINT, ""), Item( "CPU Instructions Sets", (if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) Build.SUPPORTED_ABIS else arrayOf(Build.CPU_ABI, Build.CPU_ABI2)).joinToString(", "), "" ), Item( "RAM", if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) android.text.format.Formatter.formatShortFileSize( activity, ActivityManager.MemoryInfo().apply { activity.getSystemService<ActivityManager>()?.getMemoryInfo(this) }.totalMem ) else "", "" ), Item( "Battery", if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) (activity.getSystemService<BatteryManager>())?.run { listOf("Charging: $isCharging") + listOf( "Capacity" to BatteryManager.BATTERY_PROPERTY_CAPACITY, "Charge Counter" to BatteryManager.BATTERY_PROPERTY_CHARGE_COUNTER, "Current Avg" to BatteryManager.BATTERY_PROPERTY_CURRENT_AVERAGE, "Current Now" to BatteryManager.BATTERY_PROPERTY_CURRENT_NOW, "Energy Counter" to BatteryManager.BATTERY_PROPERTY_ENERGY_COUNTER ).map { "${it.first}: ${getLongProperty(it.second)}" } }?.joinToString("\n") else "", "" ), Item( "Sensors", (activity.getSystemService<SensorManager>()) ?.getSensorList(Sensor.TYPE_ALL)?.joinToString("\n"), "" ) ) + (try { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { // Quick Kung-fu to create gl context, https://stackoverflow.com/a/27092070 val display = EGL14.eglGetDisplay(EGL14.EGL_DEFAULT_DISPLAY) val versions = IntArray(2) EGL14.eglInitialize(display, versions, 0, versions, 1) val configAttr = intArrayOf( EGL14.EGL_COLOR_BUFFER_TYPE, EGL14.EGL_RGB_BUFFER, EGL14.EGL_LEVEL, 0, EGL14.EGL_RENDERABLE_TYPE, EGL14.EGL_OPENGL_ES2_BIT, EGL14.EGL_SURFACE_TYPE, EGL14.EGL_PBUFFER_BIT, EGL14.EGL_NONE ) val configs = Array<EGLConfig?>(1) { null } val configsCount = IntArray(1) EGL14.eglChooseConfig(display, configAttr, 0, configs, 0, 1, configsCount, 0) if (configsCount[0] != 0) { val surf = EGL14.eglCreatePbufferSurface( display, configs[0], intArrayOf(EGL14.EGL_WIDTH, 64, EGL14.EGL_HEIGHT, 64, EGL14.EGL_NONE), 0 ) EGL14.eglMakeCurrent( display, surf, surf, EGL14.eglCreateContext( display, configs[0], EGL14.EGL_NO_CONTEXT, intArrayOf(EGL14.EGL_CONTEXT_CLIENT_VERSION, 2, EGL14.EGL_NONE), 0 ) ) } } listOf( Item( "OpenGL", (listOf( "GL_VERSION" to GLES20.GL_VERSION, "GL_RENDERER" to GLES20.GL_RENDERER, "GL_VENDOR" to GLES20.GL_VENDOR ).map { "${it.first}: ${GLES20.glGetString(it.second)}" } + listOf( "GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS" to GLES20.GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, "GL_MAX_CUBE_MAP_TEXTURE_SIZE" to GLES20.GL_MAX_CUBE_MAP_TEXTURE_SIZE, "GL_MAX_FRAGMENT_UNIFORM_VECTORS" to GLES20.GL_MAX_FRAGMENT_UNIFORM_VECTORS, "GL_MAX_RENDERBUFFER_SIZE" to GLES20.GL_MAX_RENDERBUFFER_SIZE, "GL_MAX_TEXTURE_IMAGE_UNITS" to GLES20.GL_MAX_TEXTURE_IMAGE_UNITS, "GL_MAX_TEXTURE_SIZE" to GLES20.GL_MAX_TEXTURE_SIZE, "GL_MAX_VARYING_VECTORS" to GLES20.GL_MAX_VARYING_VECTORS, "GL_MAX_VERTEX_ATTRIBS" to GLES20.GL_MAX_VERTEX_ATTRIBS, "GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS" to GLES20.GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS, "GL_MAX_VERTEX_UNIFORM_VECTORS" to GLES20.GL_MAX_VERTEX_UNIFORM_VECTORS, "GL_MAX_VIEWPORT_DIMS" to GLES20.GL_MAX_VIEWPORT_DIMS ).map { val intBuffer = IntArray(1) GLES10.glGetIntegerv(it.second, intBuffer, 0) "${it.first}: ${intBuffer[0]}" }).joinToString("\n"), "" ), Item( "OpenGL Extensions", SpannableStringBuilder().apply { val extensions = GLES20.glGetString(GLES20.GL_EXTENSIONS).trim().split(" ") val regex = "GL_([a-zA-Z]+)_(.+)".toRegex() extensions.forEachIndexed { i, it -> if (i != 0) append("\n") if (!regex.matches(it)) append(it) else append(SpannableString(it).apply { setSpan(object : ClickableSpan() { override fun onClick(textView: View) = try { CustomTabsIntent.Builder().build().launchUrl( activity, it.replace( regex, "https://www.khronos.org/registry/OpenGL/extensions/$1/$1_$2.txt" ).toUri() ) } catch (e: Exception) { e.printStackTrace() } }, 0, it.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) }) } }, "" ) ) } catch (e: Exception) { e.printStackTrace() emptyList<Item>() }) class DeviceInformationDiffCallback : DiffUtil.ItemCallback<Item>() { override fun areItemsTheSame(oldItem: Item, newItem: Item): Boolean = oldItem == newItem override fun areContentsTheSame(oldItem: Item, newItem: Item): Boolean = oldItem == newItem } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = ViewHolder( DeviceInformationRowBinding.inflate(parent.context.layoutInflater, parent, false) ) override fun onBindViewHolder(holder: ViewHolder, position: Int) = holder.bind(position) override fun getItemCount(): Int = deviceInformationItems.size inner class ViewHolder(private val binding: DeviceInformationRowBinding) : RecyclerView.ViewHolder(binding.root), View.OnClickListener { init { binding.root.setOnClickListener(this) } fun bind(position: Int) { deviceInformationItems[position].apply { binding.title.text = title binding.content.text = content ?: "Unknown" binding.version.text = version } binding.content.movementMethod = LinkMovementMethod.getInstance() } override fun onClick(v: View?) = copyToClipboard( rootView, deviceInformationItems[adapterPosition].title, deviceInformationItems[adapterPosition].content ) } }
gpl-3.0
b34743fa75916f5fea792550a35bf6db
42.224913
109
0.573567
4.866381
false
false
false
false
pdvrieze/ProcessManager
PE-common/src/commonMain/kotlin/org/w3/soapEnvelope/Body.kt
1
7377
/* * Copyright (c) 2018. * * This file is part of ProcessManager. * * ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the * GNU Lesser General Public License as published by the Free Software Foundation. * * ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not, * see <http://www.gnu.org/licenses/>. */ // // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2009.09.24 at 08:12:58 PM CEST // package org.w3.soapEnvelope import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.KSerializer import kotlinx.serialization.SerializationException import kotlinx.serialization.descriptors.SerialDescriptor import kotlinx.serialization.descriptors.buildClassSerialDescriptor import kotlinx.serialization.encoding.* import nl.adaptivity.serialutil.decodeElements import nl.adaptivity.util.multiplatform.URI import nl.adaptivity.util.multiplatform.createUri import nl.adaptivity.util.net.devrieze.serializers.URISerializer import nl.adaptivity.xmlutil.* import nl.adaptivity.xmlutil.core.impl.multiplatform.name import nl.adaptivity.xmlutil.serialization.XML import nl.adaptivity.xmlutil.serialization.XmlValue import nl.adaptivity.xmlutil.util.CompactFragment /** * * * Java class for Body complex type. * * * The following schema fragment specifies the expected content contained within * this class. * * ``` * <complexType name="Body"> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <sequence> * <any processContents='lax' maxOccurs="unbounded" minOccurs="0"/> * </sequence> * <anyAttribute processContents='lax' namespace='##other'/> * </restriction> * </complexContent> * </complexType> * ``` * */ class Body<T: Any>( @XmlValue(true) val child: T, val encodingStyle: URI = createUri("http://www.w3.org/2003/05/soap-encoding"), val otherAttributes: Map<QName, String> = emptyMap(), ) { fun copy( encodingStyle: URI = this.encodingStyle, otherAttributes: Map<QName, String> = this.otherAttributes, ): Body<T> = Body(child, encodingStyle, otherAttributes) fun <U: Any> copy( child: U, encodingStyle: URI = this.encodingStyle, otherAttributes: Map<QName, String> = this.otherAttributes, ): Body<U> = Body(child, encodingStyle, otherAttributes) class Serializer<T: Any>(private val contentSerializer: KSerializer<T>): KSerializer<Body<T>> { @OptIn(ExperimentalSerializationApi::class, XmlUtilInternal::class) override val descriptor: SerialDescriptor = buildClassSerialDescriptor(Body::class.name) { annotations = SoapSerialObjects.bodyAnnotations element("encodingStyle", URISerializer.descriptor, SoapSerialObjects.encodingStyleAnnotations, true) element("otherAttributes", SoapSerialObjects.attrsSerializer.descriptor, isOptional = true) element("child", contentSerializer.descriptor) } override fun deserialize(decoder: Decoder): Body<T> { var encodingStyle: URI? = null var otherAttributes: Map<QName, String> = emptyMap() lateinit var child: T decoder.decodeStructure(descriptor) { if (decoder is XML.XmlInput) { val reader: XmlReader = decoder.input otherAttributes = reader.attributes.filter { when { it.prefix == XMLConstants.XMLNS_ATTRIBUTE || (it.prefix=="" && it.localName == XMLConstants.XMLNS_ATTRIBUTE) -> false it.namespaceUri!= Envelope.NAMESPACE -> true it.localName == "encodingStyle" -> { encodingStyle = URI(it.value); false } else -> true } }.associate { QName(it.namespaceUri, it.localName, it.prefix) to it.value } child = decodeSerializableElement(descriptor, 2, contentSerializer, null) if (reader.nextTag()!=EventType.END_ELEMENT) throw SerializationException("Extra content in body") } else { decodeElements(this) { idx -> when (idx) { 0 -> encodingStyle = decodeSerializableElement(descriptor, idx, URISerializer, encodingStyle) 1 -> otherAttributes = decodeSerializableElement( descriptor, idx, SoapSerialObjects.attrsSerializer, otherAttributes) 2 -> child = decodeSerializableElement(descriptor, idx, contentSerializer) } } } } return Body(child) } override fun serialize(encoder: Encoder, value: Body<T>) { if (encoder is XML.XmlOutput) { val out = encoder.target out.smartStartTag(ELEMENTNAME) { value.encodingStyle?.also { style -> out.attribute(Envelope.NAMESPACE, "encodingStyle", Envelope.PREFIX, style.toString()) } for ((aName, aValue) in value.otherAttributes) { out.writeAttribute(aName, aValue) } val child = value.child when (child) { is CompactFragment -> { for (ns in child.namespaces) { if (out.getNamespaceUri(ns.prefix) != ns.namespaceURI) { out.namespaceAttr(ns) } } child.serialize(out) } else -> encoder.delegateFormat().encodeToWriter(out, contentSerializer, child) } } } else { encoder.encodeStructure(descriptor) { value.encodingStyle?.also { style -> encodeSerializableElement(descriptor, 0, URISerializer, style) } if (value.otherAttributes.isNotEmpty() || shouldEncodeElementDefault(descriptor, 1)) { encodeSerializableElement(descriptor, 1, SoapSerialObjects.attrsSerializer, value.otherAttributes) } encodeSerializableElement(descriptor, 2, contentSerializer, value.child) } } } } companion object { const val ELEMENTLOCALNAME = "Body" val ELEMENTNAME = QName(Envelope.NAMESPACE, ELEMENTLOCALNAME, Envelope.PREFIX) } }
lgpl-3.0
7544ab17265440a1aba61f3ee8e48316
41.396552
123
0.608106
5.08408
false
false
false
false
pdvrieze/ProcessManager
PE-common/src/commonMain/kotlin/nl/adaptivity/process/engine/processModel/NodeInstanceState.kt
1
4642
/* * Copyright (c) 2018. * * This file is part of ProcessManager. * * ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the * GNU Lesser General Public License as published by the Free Software Foundation. * * ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not, * see <http://www.gnu.org/licenses/>. */ package nl.adaptivity.process.engine.processModel import nl.adaptivity.util.multiplatform.Locale import nl.adaptivity.util.multiplatform.Locales import nl.adaptivity.util.multiplatform.toLowercase /** * Enumeration representing the various states a task can be in. * @author Paul de Vrieze */ enum class NodeInstanceState { /** * Initial task state. The instance has been created, but has not been successfully sent to a receiver. */ Pending { override val isActive: Boolean get() = true }, /** * The task is skipped due to split conditions */ Skipped { override val isFinal: Boolean get() = true override val isSkipped: Boolean get() = true }, /** * Signifies that the task has failed to be created, a new attempt should be made. */ FailRetry, /** * Indicates that the task has been communicated to a * handler, but receipt has not been acknowledged. */ Sent { override val isActive: Boolean get() = true }, /** * State acknowledging reception of the task. Note that this is generally * only used by process aware services. It signifies that a task has been * received, but processing has not started yet. */ Acknowledged { override val isActive: Boolean get() = true }, /** * Some tasks allow for alternatives (different users). Taken signifies that * the task has been claimed and others can not claim it anymore (unless * released again). */ Taken { override val isActive: Boolean get() = true override val isCommitted: Boolean get() = true }, /** * Signifies that work on the task has actually started. */ Started { override val isActive: Boolean get() = true override val isCommitted: Boolean get() = true }, /** * Signifies that the task is complete. This generally is the end state of a * task. */ Complete { override val isFinal: Boolean get() = true override val isCommitted: Boolean get() = true }, /** * Signifies that the task has failed for some reason. */ Failed { override val isFinal: Boolean get() = true override val isCommitted: Boolean get() = true }, /** * Signifies that the task has been automatically cancelled due to becoming part * of an inactive branch */ AutoCancelled { override val isFinal: Boolean get() = true override val isSkipped: Boolean get() = true }, /** * Signifies that the task has been cancelled directly (but not through a failure). */ Cancelled { override val isFinal: Boolean get() = true }, /** Signifies that the task has been skipped because a predecessor was cancelled */ SkippedCancel { override val isFinal: Boolean get() = true override val isSkipped: Boolean get() = true }, /** Signifies that the task has been skipped because a predecessor failed */ SkippedFail { override val isFinal: Boolean get() = true override val isSkipped: Boolean get() = true }, /** Signifies that the task is no longer valid, but overridden by an instance with higher entryno. */ SkippedInvalidated { override val isFinal: Boolean get() = true override val isSkipped: Boolean get() = true } ; open val isSkipped: Boolean get() = false open val isFinal: Boolean get() = false open val isActive: Boolean get() = false open val isCommitted: Boolean get() = false val canRestart get() = this == FailRetry || this == Pending val lcname = name.toLowercase(Locales.ENGLISH) companion object { fun fromString(string: CharSequence): NodeInstanceState? { val lowerCase = string.toLowercase() return values().firstOrNull { it.name.lowercase() == lowerCase } } } }
lgpl-3.0
7749454bef17f6d5e47d62129a01ec1e
32.157143
112
0.65209
4.761026
false
false
false
false
BasinMC/Basin
faucet/src/main/kotlin/org/basinmc/faucet/math/WorldVectorFloat.kt
1
3828
/* * Copyright 2019 Johannes Donath <[email protected]> * and other copyright owners as documented in the project's IP log. * * 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.basinmc.faucet.math import org.basinmc.faucet.world.World import kotlin.math.roundToInt import kotlin.math.roundToLong import kotlin.math.sqrt /** * @author <a href="mailto:[email protected]">Johannes Donath</a> */ data class WorldVectorFloat(override val x: Float, override val y: Float, override val z: Float, override val world: World) : WorldVector<Float> { override val length: Double by lazy { sqrt(Math.pow(this.x.toDouble(), 2.0) + Math.pow(this.y.toDouble(), 2.0) + Math.pow( this.z.toDouble(), 2.0)) } override val normalized: WorldVector<Float> by lazy { WorldVectorFloat((this.x / this.length).toFloat(), (this.y / this.length).toFloat(), (this.z / this.length).toFloat(), this.world) } override val int: WorldVectorInt get() = WorldVectorInt(this.x.roundToInt(), this.y.roundToInt(), this.z.roundToInt(), this.world) override val long: WorldVectorLong get() = WorldVectorLong(this.x.roundToLong(), this.y.roundToLong(), this.z.roundToLong(), this.world) override val float: WorldVectorFloat get() = this override fun plus(addend: Float) = WorldVectorFloat(this.x + addend, this.y + addend, this.z + addend, this.world) override fun plus(addend: Vector2<Float>) = WorldVectorFloat(this.x + addend.x, this.y + addend.y, this.z, this.world) override fun plus(addend: Vector3<Float>) = WorldVectorFloat(this.x + addend.x, this.y + addend.y, this.z + addend.z, this.world) override fun minus(subtrahend: Float) = WorldVectorFloat(this.x - subtrahend, this.y - subtrahend, this.z - subtrahend, this.world) override fun minus(subtrahend: Vector2<Float>) = WorldVectorFloat(this.x - subtrahend.x, this.y - subtrahend.y, this.z, this.world) override fun minus(subtrahend: Vector3<Float>) = WorldVectorFloat(this.x - subtrahend.x, this.y - subtrahend.y, this.z - subtrahend.z, this.world) override fun times(factor: Float) = WorldVectorFloat(this.x * factor, this.y * factor, this.z * factor, this.world) override fun times(factor: Vector2<Float>) = WorldVectorFloat(this.x * factor.x, this.y * factor.y, this.z, this.world) override fun times(factor: Vector3<Float>) = WorldVectorFloat(this.x * factor.x, this.y * factor.y, this.z * factor.z, this.world) override fun div(divisor: Float) = WorldVectorFloat(this.x / divisor, this.y / divisor, this.z / divisor, this.world) override fun div(divisor: Vector2<Float>) = WorldVectorFloat(this.x / divisor.x, this.y / divisor.y, this.z, this.world) override fun div(divisor: Vector3<Float>) = WorldVectorFloat(this.x / divisor.x, this.y / divisor.y, this.z / divisor.z, this.world) override fun rem(divisor: Float) = WorldVectorFloat(this.x % divisor, this.y % divisor, this.z % divisor, this.world) override fun rem(divisor: Vector2<Float>) = WorldVectorFloat(this.x % divisor.x, this.y % divisor.y, this.z, this.world) override fun rem(divisor: Vector3<Float>) = WorldVectorFloat(this.x % divisor.x, this.y % divisor.y, this.z % divisor.z, this.world) }
apache-2.0
09ab4c3fb5bbf4dea3bc5285d88143d1
40.608696
100
0.700627
3.60452
false
false
false
false
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/api/cause/entity/health/HealthModifier.kt
1
3540
/* * 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.api.cause.entity.health import org.lanternpowered.api.registry.builderOf import org.spongepowered.api.entity.Entity import org.lanternpowered.api.cause.Cause import org.spongepowered.api.util.ResettableBuilder import java.util.function.DoubleUnaryOperator /** * Represents a modifier that will apply a function on a damage value to deal * towards an entity such that the raw damage is the input of a * [DoubleUnaryOperator] such that the output will be the final damage * applied to the [Entity]. */ interface HealthModifier { /** * Gets the [HealthModifierType] for this [HealthModifier]. * * @return The damage modifier type */ val type: HealthModifierType /** * Gets the cause of this [HealthModifier]. * * @return The cause of this damage modifier */ val cause: Cause /** * A builder that creates [HealthModifier]s, for use in both plugin * and implementation requirements. */ class Builder private constructor() : ResettableBuilder<HealthModifier, Builder> { var type: HealthModifierType? = null var cause: Cause? = null /** * Sets the [HealthModifierType] for the [HealthModifier] to build. * * @param type The health modifier type * @return This builder, for chaining */ fun type(type: HealthModifierType): Builder = apply { this.type = type } /** * Sets the [Cause] for the [HealthModifier] to build. * * @param cause The cause for the health modifier * @return This builder, for chaining */ fun cause(cause: Cause): Builder = apply { this.cause = cause } /** * Creates a new [HealthModifier] with this builder's provided * [Cause] and [HealthModifierType]. * * @return The newly created health modifier */ fun build(): HealthModifier { val type = checkNotNull(this.type) { "The HealthModifierType must not be null!" } val cause = checkNotNull(this.cause) { "The cause for the HealthModifier must not be null!" } return ImplementedHealthModifier(type, cause) } fun from(value: HealthModifier): Builder = apply { reset() this.type = value.type this.cause = value.cause } override fun reset(): Builder = apply { this.type = null this.cause = null } private data class ImplementedHealthModifier( override val type: HealthModifierType, override val cause: Cause ) : HealthModifier companion object { /** * Creates a new [Builder]. * * @return The new builder instance */ fun builder(): Builder { return Builder() } } } companion object { /** * Creates a new [Builder] for constructing new [HealthModifier]s. * * @return A new builder */ fun builder(): Builder = builderOf() } }
mit
4b28bb6815c968d8fddba5be5a3db803
28.5
105
0.594915
4.849315
false
false
false
false
devulex/eventorage
backend/src/com/devulex/eventorage/ApplicationPage.kt
1
2418
package com.devulex.eventorage import com.devulex.eventorage.model.DynamicEventorageSettings import com.devulex.eventorage.model.StaticEventorageSettings import kotlinx.html.* import org.jetbrains.ktor.html.* class ApplicationPage(val staticSettings: StaticEventorageSettings, val dynamicSettings: DynamicEventorageSettings) : Template<HTML> { val caption = Placeholder<TITLE>() val head = Placeholder<HEAD>() override fun HTML.apply() { head { meta { charset = "utf-8" } meta { name = "application-name" content = "Eventorage" } meta { name = "description" content = "Event storage management at Elasticsearch." } link(rel = "icon", type = "image/png", href = "images/favicon-16x16.png") { sizes = "16x16" } link(rel = "icon", type = "image/png", href = "images/favicon-32x32.png") { sizes = "32x32" } link(rel = "apple-touch-icon", href = "images/favicon-180x180.png") { sizes = "180x180" } meta { name = "viewport" content = "width=device-width, initial-scale=1.0" } title { insert(caption) } insert(head) } body { div { id = "content" attributes["data-elasticsearch-cluster-name"] = staticSettings.elasticsearchClusterName attributes["data-elasticsearch-cluster-nodes"] = staticSettings.elasticsearchClusterNodes attributes["data-eventorage-remote-host"] = staticSettings.eventorageRemoteHost attributes["data-language"] = +dynamicSettings.language attributes["data-date-format"] = +dynamicSettings.dateFormat attributes["data-auto-check-updates"] = dynamicSettings.autoCheckUpdates.toString() attributes["data-version"] = thisRelease.version attributes["data-release-date"] = thisRelease.releaseDate.toString() attributes["data-pre-release"] = thisRelease.isPreRelease.toString() attributes["data-update-available"] = Updater.isUpdateAvailable.toString() } script(src = "frontend.bundle.js") } } }
mit
62bd99f57b822c47b396a0f5391be0c4
40.689655
134
0.57072
4.70428
false
false
false
false
Lumeer/engine
lumeer-core/src/main/kotlin/io/lumeer/core/util/js/DataFilterDecodingJsonTask.kt
2
4767
/* * Lumeer: Modern Data Definition and Processing Platform * * Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.lumeer.core.util.js import io.lumeer.api.model.* import io.lumeer.api.model.Collection import io.lumeer.core.constraint.ConstraintManager import io.lumeer.core.util.Tuple import java.util.concurrent.Callable import java.util.logging.Level import java.util.logging.Logger data class DataFilterDecodingJsonTask(val documents: List<Document>, val collections: List<Collection>, val linkTypes: List<LinkType>, val linkInstances: List<LinkInstance>, val query: Query, val collectionsPermissions: Map<String, AllowedPermissions>, val linkTypesPermissions: Map<String, AllowedPermissions>, val constraintData: ConstraintData, val includeChildren: Boolean, val language: Language = Language.EN) : Callable<Tuple<List<Document>, List<LinkInstance>>> { override fun call(): Tuple<List<Document>, List<LinkInstance>> { val constraintManager = ConstraintManager() constraintManager.locale = language.toLocale() val collectionsById = collections.associateBy { it.id } val decodedDocuments = ArrayList<Document>() documents.forEach { doc -> collectionsById[doc.collectionId]?.let { val collection = collectionsById[doc.collectionId] val decodedDoc = Document(doc) decodedDoc.data = constraintManager.decodeDataTypes(collection, doc.data) decodedDocuments.add(decodedDoc) } } val linkTypesById = linkTypes.associateBy { it.id } val decodedLinks = ArrayList<LinkInstance>() linkInstances.forEach { link -> linkTypesById[link.linkTypeId]?.let { val linkType = linkTypesById[link.linkTypeId] val decodedLink = LinkInstance(link) decodedLink.data = constraintManager.decodeDataTypes(linkType, link.data) decodedLinks.add(decodedLink) } } val emptyTuple = Tuple<List<Document>, List<LinkInstance>>(emptyList(), emptyList()) val context = DataFilterJsonTask.getContext() return try { val filterJsValue = DataFilterJsonTask.getFunction(context) val json = DataFilterJsonTask.convertToJson(DataFilterJson(decodedDocuments, collections, linkTypes, decodedLinks, query, collectionsPermissions, linkTypesPermissions, constraintData, includeChildren, language.toLanguageTag())) val result = filterJsValue.execute(json) if (result != null) { val documentsMap = documents.groupBy { it.id } val resultDocumentsList = mutableListOf<Document>() val resultDocuments = result.getMember("documentsIds") for (i in 0 until resultDocuments.arraySize) resultDocumentsList.addAll(documentsMap[resultDocuments.getArrayElement(i).asString()].orEmpty()) val linkInstancesMap = linkInstances.groupBy { it.id } val resultLinksList = mutableListOf<LinkInstance>() val resultLinks = result.getMember("linkInstancesIds") for (i in 0 until resultLinks.arraySize) resultLinksList.addAll(linkInstancesMap[resultLinks.getArrayElement(i).asString()].orEmpty()) Tuple(resultDocumentsList, resultLinksList) } else { logger.log(Level.SEVERE, "Error filtering data - null result.") emptyTuple } } catch (e: Exception) { logger.log(Level.SEVERE, "Error filtering data: ", e) emptyTuple } finally { context.close() } } companion object { private val logger: Logger = Logger.getLogger(DataFilterDecodingJsonTask::class.simpleName) } }
gpl-3.0
9ac90002be2b944fca5f78865429b8cf
45.281553
239
0.643801
5.033791
false
false
false
false
Ruben-Sten/TeXiFy-IDEA
src/nl/hannahsten/texifyidea/structure/latex/LatexStructureViewModel.kt
1
1473
package nl.hannahsten.texifyidea.structure.latex import com.intellij.ide.structureView.StructureViewModel.ElementInfoProvider import com.intellij.ide.structureView.StructureViewTreeElement import com.intellij.ide.structureView.TextEditorBasedStructureViewModel import com.intellij.ide.util.treeView.smartTree.Sorter import com.intellij.openapi.editor.Editor import com.intellij.psi.PsiFile import nl.hannahsten.texifyidea.psi.LatexCommands import nl.hannahsten.texifyidea.structure.filter.* /** * @author Hannah Schellekens */ class LatexStructureViewModel( psiFile: PsiFile, editor: Editor? ) : TextEditorBasedStructureViewModel(editor, psiFile), ElementInfoProvider { companion object { private val sorterArray = arrayOf(Sorter.ALPHA_SORTER) private val filterArray = arrayOf( IncludesFilter(), SectionFilter(), CommandDefinitionFilter(), LabelFilter(), BibitemFilter() ) } override fun getRoot() = LatexStructureViewElement(psiFile) override fun getSorters() = sorterArray override fun getFilters() = filterArray override fun isAlwaysShowsPlus(structureViewTreeElement: StructureViewTreeElement) = false override fun isAlwaysLeaf(structureViewTreeElement: StructureViewTreeElement) = false override fun getSuitableClasses(): Array<Class<LatexCommands>> { return arrayOf( LatexCommands::class.java ) } }
mit
9ea944580abda56aab8356165ddd010c
30.361702
94
0.743381
5.18662
false
false
false
false
debop/debop4k
debop4k-reactive/src/main/kotlin/debop4k/reactive/subscribers.kt
1
5693
/* * Copyright (c) 2016. Sunghyouk Bae <[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. */ @file:JvmName("subscribers") package debop4k.reactive import debop4k.core.loggerOf import rx.SingleSubscriber import rx.Subscriber import rx.exceptions.OnErrorNotImplementedException import rx.observers.SerializedSubscriber import rx.subscriptions.Subscriptions import java.util.* /** * [FunctionSubscriber] 를 생성합니다. */ fun <T> subscriber(): FunctionSubscriber<T> = FunctionSubscriber<T>() /** * [FunctionSingleSubscriber] 를 생성합니다. */ fun <T> singleSubscriber(): FunctionSingleSubscriber<T> = FunctionSingleSubscriber<T>() /** * [Subscriber]를 Single thread 에서 수행하도록 합니다. */ fun <T> Subscriber<T>.synchronized(): Subscriber<T> = SerializedSubscriber(this) fun Subscriber<*>.add(unsubscribe: () -> Unit) = add(Subscriptions.create(unsubscribe)) /** * Function 을 지정할 수 있는 [Subscriber] */ class FunctionSubscriber<T>() : Subscriber<T>() { private val onCompletedFunctions = ArrayList<() -> Unit>() private val onErrorFunctions = ArrayList<(e: Throwable) -> Unit>() private val onNextFunctions = ArrayList<(value: T) -> Unit>() private val onStartFunctions = ArrayList<() -> Unit>() override fun onCompleted() = onCompletedFunctions.forEach { it() } override fun onNext(t: T) = onNextFunctions.forEach { it(t) } override fun onError(e: Throwable?) = (e ?: RuntimeException("Unknown exception")).let { ex -> if (onErrorFunctions.isEmpty()) { throw OnErrorNotImplementedException(ex) } else { onErrorFunctions.forEach { it(ex) } } } override fun onStart() = onStartFunctions.forEach { it() } fun onCompleted(onCompletedFunc: () -> Unit): FunctionSubscriber<T> = copy { onCompletedFunctions.add(onCompletedFunc) } fun onError(onErrorFunc: (Throwable) -> Unit): FunctionSubscriber<T> = copy { onErrorFunctions.add(onErrorFunc) } fun onNext(onNextFunc: (T) -> Unit): FunctionSubscriber<T> = copy { onNextFunctions.add(onNextFunc) } fun onStart(onStartFunc: () -> Unit): FunctionSubscriber<T> = copy { onStartFunctions.add(onStartFunc) } private fun copy(block: FunctionSubscriber<T>.() -> Unit): FunctionSubscriber<T> { val newSubscriber = FunctionSubscriber<T>() newSubscriber.onCompletedFunctions.addAll(this.onCompletedFunctions) newSubscriber.onErrorFunctions.addAll(this.onErrorFunctions) newSubscriber.onNextFunctions.addAll(this.onNextFunctions) newSubscriber.onStartFunctions.addAll(this.onStartFunctions) newSubscriber.block() return newSubscriber } } /** * 함수로 작업을 수행하는 [SingleSubscriber] */ class FunctionSingleSubscriber<T>() : SingleSubscriber<T>() { private val log = loggerOf(javaClass) private val onSuccessFunctions = arrayListOf<(T) -> Unit>() private val onErrorFunctions = arrayListOf<(Throwable) -> Unit>() override fun onSuccess(value: T): Unit = onSuccessFunctions.forEach { it(value) } override fun onError(error: Throwable?): Unit { val err = error ?: RuntimeException("Unknown exception") return err.let { ex -> if (onErrorFunctions.isEmpty()) { throw OnErrorNotImplementedException(ex) } else { onErrorFunctions.forEach { it(ex) } } } } fun onSuccess(onSuccessFunc: (T) -> Unit): FunctionSingleSubscriber<T> = copy { log.trace("add onSuccessFunction") onSuccessFunctions.add(onSuccessFunc) } fun onError(onErrorFunc: (Throwable) -> Unit): FunctionSingleSubscriber<T> = copy { log.trace("add onErrorFunction") onErrorFunctions.add(onErrorFunc) } private fun copy(block: FunctionSingleSubscriber<T>.() -> Unit): FunctionSingleSubscriber<T> { val newSubscriber = FunctionSingleSubscriber<T>() newSubscriber.onSuccessFunctions.addAll(this.onSuccessFunctions) newSubscriber.onErrorFunctions.addAll(this.onErrorFunctions) newSubscriber.block() return newSubscriber } } /** * 함수로 [Subscriber]를 갱신하는 클래스 */ class FunctionSubscriberModifier<T>(functionSubscriber: FunctionSubscriber<T> = subscriber()) { var subscriber: FunctionSubscriber<T> = functionSubscriber private set fun onCompleted(onCompletedFunc: () -> Unit): Unit { subscriber = subscriber.onCompleted(onCompletedFunc) } fun onError(onErrorFunc: (t: Throwable) -> Unit): Unit { subscriber = subscriber.onError(onErrorFunc) } fun onNext(onNextFunc: (t: T) -> Unit): Unit { subscriber = subscriber.onNext(onNextFunc) } fun onStart(onStartFunc: () -> Unit): Unit { subscriber = subscriber.onStart(onStartFunc) } } /** * 함수로 [SingleSubscriber]를 갱신하는 클래스 */ class FunctionSingleSubscriberModifier<T>(functionSubscriber: FunctionSingleSubscriber<T> = singleSubscriber()) { var subscriber: FunctionSingleSubscriber<T> = functionSubscriber private set fun onSuccess(onSuccessFunc: (T) -> Unit): Unit { subscriber = subscriber.onSuccess(onSuccessFunc) } fun onError(onErrorFunc: (Throwable) -> Unit): Unit { subscriber = subscriber.onError(onErrorFunc) } }
apache-2.0
3fe2d6e4a5d0d506bd381b5a0f0c2907
29.938889
113
0.720057
4.333852
false
false
false
false
SimonVT/cathode
cathode/src/main/java/net/simonvt/cathode/ui/shows/upcoming/UpcomingShowsFragment.kt
1
6656
/* * Copyright (C) 2016 Simon Vig Therkildsen * * 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 net.simonvt.cathode.ui.shows.upcoming import android.content.Context import android.os.Bundle import android.view.MenuItem import android.view.View import androidx.appcompat.widget.Toolbar import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import androidx.recyclerview.widget.RecyclerView import net.simonvt.cathode.R import net.simonvt.cathode.common.ui.adapter.HeaderSpanLookup import net.simonvt.cathode.common.ui.fragment.ToolbarSwipeRefreshRecyclerFragment import net.simonvt.cathode.entity.ShowWithEpisode import net.simonvt.cathode.settings.TraktLinkSettings import net.simonvt.cathode.sync.scheduler.EpisodeTaskScheduler import net.simonvt.cathode.ui.CathodeViewModelFactory import net.simonvt.cathode.ui.NavigationListener import net.simonvt.cathode.ui.ShowsNavigationListener import net.simonvt.cathode.ui.lists.ListDialog import net.simonvt.cathode.ui.shows.upcoming.UpcomingSortByPreference.UpcomingSortByListener import javax.inject.Inject class UpcomingShowsFragment @Inject constructor( private val viewModelFactory: CathodeViewModelFactory, private val episodeScheduler: EpisodeTaskScheduler, private val upcomingSortByPreference: UpcomingSortByPreference ) : ToolbarSwipeRefreshRecyclerFragment<RecyclerView.ViewHolder>(), ListDialog.Callback, UpcomingAdapter.Callbacks { private lateinit var sortBy: UpcomingSortBy private lateinit var navigationListener: ShowsNavigationListener private lateinit var viewModel: UpcomingViewModel private var columnCount: Int = 0 private var adapter: UpcomingAdapter? = null private var scrollToTop: Boolean = false private val upcomingSortByListener = UpcomingSortByListener { sortBy -> [email protected] = sortBy scrollToTop = true } override fun onAttach(context: Context) { super.onAttach(context) navigationListener = requireActivity() as NavigationListener } override fun onCreate(inState: Bundle?) { super.onCreate(inState) sortBy = upcomingSortByPreference.get() upcomingSortByPreference.registerListener(upcomingSortByListener) setTitle(R.string.title_shows_upcoming) setEmptyText(R.string.empty_show_upcoming) columnCount = resources.getInteger(R.integer.showsColumns) viewModel = ViewModelProviders.of(this, viewModelFactory).get(UpcomingViewModel::class.java) viewModel.loading.observe(this, Observer { loading -> setRefreshing(loading) }) viewModel.shows.observe(this, Observer { shows -> setShows(shows) }) } override fun onDestroy() { upcomingSortByPreference.unregisterListener(upcomingSortByListener) super.onDestroy() } override fun onViewCreated(view: View, inState: Bundle?) { super.onViewCreated(view, inState) swipeRefreshLayout.isEnabled = TraktLinkSettings.isLinked(requireContext()) } override fun getColumnCount() = columnCount override fun getSpanSizeLookup() = HeaderSpanLookup(ensureAdapter(), columnCount) override fun displaysMenuIcon() = amITopLevel() override fun createMenu(toolbar: Toolbar) { super.createMenu(toolbar) toolbar.inflateMenu(R.menu.fragment_shows_upcoming) } override fun onMenuItemClick(item: MenuItem): Boolean { when (item.itemId) { R.id.sort_by -> { val items = arrayListOf<ListDialog.Item>() items.add(ListDialog.Item(R.id.sort_title, R.string.sort_title)) items.add(ListDialog.Item(R.id.sort_next_episode, R.string.sort_next_episode)) items.add(ListDialog.Item(R.id.sort_last_watched, R.string.sort_last_watched)) ListDialog.newInstance( requireFragmentManager(), R.string.action_sort_by, items, this@UpcomingShowsFragment ).show(requireFragmentManager(), DIALOG_SORT) return true } R.id.menu_search -> { navigationListener.onSearchClicked() return true } else -> return super.onMenuItemClick(item) } } override fun onEpisodeClicked(episodeId: Long, showTitle: String?) { navigationListener.onDisplayEpisode(episodeId, showTitle) } override fun onCheckin(episodeId: Long) { episodeScheduler.checkin(episodeId, null, false, false, false) } override fun onCancelCheckin() { episodeScheduler.cancelCheckin() } override fun onItemSelected(id: Int) { when (id) { R.id.sort_title -> if (sortBy != UpcomingSortBy.TITLE) { upcomingSortByPreference.set(UpcomingSortBy.TITLE) } R.id.sort_next_episode -> if (sortBy != UpcomingSortBy.NEXT_EPISODE) { upcomingSortByPreference.set(UpcomingSortBy.NEXT_EPISODE) } R.id.sort_last_watched -> if (sortBy != UpcomingSortBy.LAST_WATCHED) { upcomingSortByPreference.set(UpcomingSortBy.LAST_WATCHED) } } } override fun onRefresh() { viewModel.refresh() } private fun ensureAdapter(): UpcomingAdapter { if (adapter == null) { adapter = UpcomingAdapter(requireActivity(), this) adapter!!.addHeader(R.string.header_aired) adapter!!.addHeader(R.string.header_upcoming) setAdapter(adapter) } return adapter!! } private fun setShows(shows: List<ShowWithEpisode>) { var adapter: UpcomingAdapter? = getAdapter() as UpcomingAdapter if (adapter == null) { adapter = ensureAdapter() setAdapter(adapter) } val currentTime = System.currentTimeMillis() val airedShows = shows.filter { show -> show.episode.firstAired <= currentTime } val unairedShows = shows.filter { show -> show.episode.firstAired > currentTime } adapter.updateHeaderItems(R.string.header_aired, airedShows) adapter.updateHeaderItems(R.string.header_upcoming, unairedShows) if (scrollToTop) { recyclerView.scrollToPosition(0) scrollToTop = false } } companion object { const val TAG = "net.simonvt.cathode.ui.shows.upcoming.UpcomingShowsFragment" private const val DIALOG_SORT = "net.simonvt.cathode.ui.shows.upcoming.UpcomingShowsFragment.sortDialog" } }
apache-2.0
4d883f21dffe6481241ff3634e81ab01
32.28
96
0.743389
4.537151
false
false
false
false
ykrank/S1-Next
app/src/main/java/me/ykrank/s1next/view/fragment/setting/DownloadPreferenceFragment.kt
1
2486
package me.ykrank.s1next.view.fragment.setting import android.content.SharedPreferences import android.os.Bundle import androidx.preference.Preference import com.bumptech.glide.Glide import com.github.ykrank.androidtools.extension.toast import com.github.ykrank.androidtools.util.L import com.github.ykrank.androidtools.util.RxJavaUtil import io.reactivex.disposables.Disposable import me.ykrank.s1next.App import me.ykrank.s1next.R import me.ykrank.s1next.data.pref.DownloadPreferencesManager import javax.inject.Inject /** * An Activity includes download settings that allow users * to modify download features and behaviors such as cache * size and avatars/images download strategy. */ class DownloadPreferenceFragment : BasePreferenceFragment(), Preference.OnPreferenceClickListener { @Inject internal lateinit var mDownloadPreferencesManager: DownloadPreferencesManager private var disposable: Disposable? = null override fun onCreatePreferences(bundle: Bundle?, s: String?) { App.appComponent.inject(this) addPreferencesFromResource(R.xml.preference_download) findPreference(getString(R.string.pref_key_clear_image_cache)).onPreferenceClickListener = this } override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) { } override fun onPreferenceClick(preference: Preference): Boolean { val key = preference.key ?: return false if (key == getString(R.string.pref_key_clear_image_cache)) { try { RxJavaUtil.disposeIfNotNull(disposable) Glide.get(App.get()).clearMemory() disposable = RxJavaUtil.workWithUiThread({ Glide.get(App.get()).clearDiskCache() }, { activity?.toast(R.string.clear_image_cache_success) }, { L.report(it) RxJavaUtil.workInMainThread { activity?.toast(R.string.clear_image_cache_error) } }) } catch (e: Exception) { L.report(e) activity?.toast(R.string.clear_image_cache_error) } return true } return false } override fun onDestroy() { RxJavaUtil.disposeIfNotNull(disposable) super.onDestroy() } companion object { val TAG: String = DownloadPreferenceFragment::class.java.name } }
apache-2.0
2e0470ab78e2ac4ae514a93d4f28283d
33.054795
103
0.66613
4.817829
false
false
false
false
didi/DoraemonKit
Android/dokit-mc/src/main/java/com/didichuxing/doraemonkit/kit/mc/net/WSSRouter.kt
1
3634
package com.didichuxing.doraemonkit.kit.mc.net import android.os.Build import androidx.annotation.RequiresApi import com.didichuxing.doraemonkit.kit.test.event.ControlEvent import com.didichuxing.doraemonkit.kit.test.event.EventType import com.didichuxing.doraemonkit.kit.test.mock.data.HostInfo import com.didichuxing.doraemonkit.kit.mc.utils.WSPackageUtils import com.didichuxing.doraemonkit.util.* import io.ktor.application.* import io.ktor.features.* import io.ktor.http.cio.websocket.* import io.ktor.routing.* import io.ktor.websocket.* import kotlinx.coroutines.channels.consumeEach import java.time.Duration /** * ================================================ * 作 者:jint(金台) * 版 本:1.0 * 创建日期:2020/6/23-14:35 * 描 述: * 修订历史: * ================================================ */ @RequiresApi(Build.VERSION_CODES.O) val WSRouter: Application.() -> Unit = { install(DefaultHeaders) install(CallLogging) install(WebSockets) { pingPeriod = Duration.ofSeconds(60) timeout = Duration.ofSeconds(15) maxFrameSize = Long.MAX_VALUE masking = false } routing { //一机多控 webSocket("/mc") { val headers = this.call.request.headers val deviceModels = headers["deviceModel"] //保存 DoKitMcHostServer.wsSessionMaps[deviceModels] = this ToastUtils.showShort("从机【$deviceModels】已连接") val hostInfo = HostInfo( "${DeviceUtils.getManufacturer()}-${DeviceUtils.getModel()}", ScreenUtils.getAppScreenWidth().toFloat(), ScreenUtils.getAppScreenHeight().toFloat() ) val wsEvent = ControlEvent( "", EventType.WSE_CONNECTED, mutableMapOf( "hostInfo" to GsonUtils.toJson(hostInfo) ), null ) outgoing.send(Frame.Text(WSPackageUtils.toPackageJson(wsEvent))) /** * 避免ws在收到第一条消息以后 通道自动关闭的问题 * https://github.com/ktorio/ktor/issues/402 */ incoming.consumeEach { when (it) { is Frame.Text -> { try { val wsEvent = WSPackageUtils.jsonToEvent(it.readText()) if (wsEvent.eventType == EventType.WSE_CLOSE) { DoKitMcHostServer.send( ControlEvent( "", EventType.WSE_CLOSE, mutableMapOf( "command" to "confirmed bye" ), null ) ) close(CloseReason(CloseReason.Codes.NORMAL, "Client said BYE")) ToastUtils.showShort("从机【$deviceModels】已断开连接") } else { WSServerProcessor.process(wsEvent) } } catch (e: Exception) { e.printStackTrace() } } else -> { } } } } } } const val TAG = "WSRouter"
apache-2.0
81ebabb77559cc97e20a80ad4ed2501e
31.728972
95
0.470874
5.142438
false
false
false
false
nickthecoder/paratask
paratask-examples/src/main/kotlin/uk/co/nickthecoder/paratask/examples/AddRemoveExample.kt
1
1415
package uk.co.nickthecoder.paratask.examples import uk.co.nickthecoder.paratask.AbstractTask import uk.co.nickthecoder.paratask.TaskDescription import uk.co.nickthecoder.paratask.TaskParser import uk.co.nickthecoder.paratask.parameters.* /** * Adding and removing a parameter from a SimpleGroupParameter. * I created this class to help find a bug. */ class AddRemoveExample : AbstractTask() { val intP = IntParameter("normalInt", label = "Int") val stringP = StringParameter("normalString", label = "String", columns = 10) val infoP = InformationParameter("info", information = "Hello world") val groupP = SimpleGroupParameter("normalGroup") .addParameters(intP, stringP) val removeIntP = ButtonParameter("removeInt", buttonText = "Remove Int") { groupP.remove(intP) } val addIntP = ButtonParameter("addInt", buttonText = "Add Int") { groupP.add(intP) } val addInfoP = ButtonParameter("addInfo", buttonText = "Add Info") { groupP.add(infoP) } val removeInfoP = ButtonParameter("removeInfo", buttonText = "Remove Info") { groupP.remove(infoP) } override val taskD = TaskDescription("addRemoveExample") .addParameters(groupP, removeIntP, addIntP, addInfoP, removeInfoP) override fun run() { } } fun main(args: Array<String>) { TaskParser(AddRemoveExample()).go(args, prompt = true) }
gpl-3.0
a9b164ef834290709db295261a70fc61
30.444444
81
0.695406
3.985915
false
false
false
false
juxeii/dztools
java/dzjforex/src/main/kotlin/com/jforex/dzjforex/misc/Plugin.kt
1
4016
package com.jforex.dzjforex.misc import arrow.Kind import arrow.core.Try import arrow.effects.* import arrow.effects.instances.io.monadDefer.monadDefer import arrow.effects.typeclasses.MonadDefer import com.dukascopy.api.Instrument import com.dukascopy.api.system.ClientFactory import com.dukascopy.api.system.IClient import com.jakewharton.rxrelay2.BehaviorRelay import com.jforex.dzjforex.misc.PluginApi.progressWait import com.jforex.dzjforex.settings.PluginSettings import com.jforex.dzjforex.zorro.ZorroNatives import com.jforex.dzjforex.zorro.heartBeatIndication import com.jforex.kforexutils.client.init import com.jforex.kforexutils.instrument.InstrumentFactory import kotlinx.coroutines.delay import kotlinx.coroutines.runBlocking import org.aeonbits.owner.ConfigFactory import org.apache.logging.log4j.LogManager import org.apache.logging.log4j.Logger import java.io.PrintWriter import java.io.StringWriter val logger: Logger = LogManager.getLogger() val pluginApi = PluginDependencies( getClient(), ConfigFactory.create(PluginSettings::class.java), ZorroNatives(), IO.monadDefer() ) sealed class PluginException() : Throwable() { data class AssetNotTradeable(val instrument: Instrument) : PluginException() data class OrderIdNotFound(val orderId: Int) : PluginException() data class InvalidAssetName(val assetName: String) : PluginException() } typealias AssetNotTradeableException = PluginException.AssetNotTradeable typealias OrderIdNotFoundException = PluginException.OrderIdNotFound typealias InvalidAssetNameException = PluginException.InvalidAssetName typealias OrderId = Int fun getClient() = Try { val client = ClientFactory.getDefaultInstance() client.init() client }.fold({ throw it }) { it } fun getStackTrace(it: Throwable): String { val ex = Exception(it) val writer = StringWriter() val printWriter = PrintWriter(writer) ex.printStackTrace(printWriter) printWriter.flush() return writer.toString() } fun <D> runDirect(kind: Kind<ForIO, D>) = kind.fix().unsafeRunSync() fun <D> runWithProgress(kind: Kind<ForIO, D>) = pluginApi.progressWait(DeferredK { runDirect(kind) }) interface PluginDependencies<F> : MonadDefer<F> { val client: IClient val pluginSettings: PluginSettings val natives: ZorroNatives companion object { operator fun <F> invoke( client: IClient, pluginSettings: PluginSettings, natives: ZorroNatives, MD: MonadDefer<F> ): PluginDependencies<F> = object : PluginDependencies<F>, MonadDefer<F> by MD { override val client = client override val pluginSettings = pluginSettings override val natives = natives } } } object PluginApi { fun <F> PluginDependencies<F>.isConnected() = delay { client.isConnected } fun <F, T> PluginDependencies<F>.progressWait(task: DeferredK<T>): T { val resultRelay = BehaviorRelay.create<T>() task.unsafeRunAsync { result -> result.fold( { error -> "ProgressWait failed! Error message: ${error.message} " + "Stack trace: ${getStackTrace(error)}" }, { resultRelay.accept(it) }) } runBlocking { while (!resultRelay.hasValue()) { natives.jcallback_BrokerProgress(heartBeatIndication) delay(pluginSettings.zorroProgressInterval()) } } return resultRelay.value!! } fun <F> PluginDependencies<F>.createInstrument(assetName: String) = InstrumentFactory .fromName(assetName) .fromOption { InvalidAssetNameException(assetName) } fun <F> PluginDependencies<F>.filterTradeableInstrument(instrument: Instrument) = delay { if (!instrument.isTradable) throw AssetNotTradeableException(instrument) instrument } }
mit
670e5d27f0128f7630002f950cff89e9
31.658537
101
0.696713
4.45727
false
false
false
false
ReDFoX43rus/Sirius-Mileage
app/src/main/java/com/liberaid/siriusmileage/util/DialogBuilder.kt
1
1161
package com.liberaid.siriusmileage.util import android.content.Context import android.support.v7.app.AlertDialog import com.liberaid.siriusmileage.R /** * [DialogBuilder] class-helper that allows create dialogs fast * @property context is application context * */ class DialogBuilder(val context: Context) { /** * Creates an error dialog * @param msg is message that will be shown in dialog * @param callback calls when user close the dialog * */ fun error(msg: String, callback: () -> Unit = {}){ val builder = AlertDialog.Builder(context) builder.setTitle(getString(R.string.error)) .setMessage(msg) .setIcon(context.resources.getDrawable(R.drawable.app_icon, null)) .setCancelable(false) .setNegativeButton(getString(R.string.cancel), { dialog, id -> dialog.cancel() callback() }) builder.create().show() } fun error(stringID: Int, callback: () -> Unit = {}) = error(getString(stringID), callback) private fun getString(id: Int): String = context.resources.getString(id) }
gpl-3.0
c0c5a6ad6f1a1a1cb82e363f0a1ca8ab
29.432432
94
0.634798
4.176259
false
false
false
false
aglne/mycollab
mycollab-web/src/main/java/com/mycollab/module/project/view/settings/VersionUrlResolver.kt
3
4036
/** * Copyright © MyCollab * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.mycollab.module.project.view.settings import com.mycollab.common.UrlTokenizer import com.mycollab.core.ResourceNotFoundException import com.mycollab.db.arguments.NumberSearchField import com.mycollab.module.project.event.ProjectEvent import com.mycollab.module.project.view.ProjectUrlResolver import com.mycollab.module.project.view.parameters.ProjectScreenData import com.mycollab.module.project.view.parameters.VersionScreenData import com.mycollab.module.project.domain.Version import com.mycollab.module.project.domain.criteria.VersionSearchCriteria import com.mycollab.module.project.service.VersionService import com.mycollab.spring.AppContextUtil import com.mycollab.vaadin.AppUI import com.mycollab.vaadin.EventBusFactory import com.mycollab.vaadin.mvp.PageActionChain /** * @author MyCollab Ltd * @since 6.0.0 */ class VersionUrlResolver : ProjectUrlResolver() { init { this.addSubResolver("list", ListUrlResolver()) this.addSubResolver("add", AddUrlResolver()) this.addSubResolver("edit", EditUrlResolver()) this.addSubResolver("preview", PreviewUrlResolver()) } private class ListUrlResolver : ProjectUrlResolver() { override fun handlePage(vararg params: String) { val projectId = UrlTokenizer(params[0]).getInt() val versionSearchCriteria = VersionSearchCriteria() versionSearchCriteria.projectId = NumberSearchField(projectId) val chain = PageActionChain(ProjectScreenData.Goto(projectId), VersionScreenData.Search(versionSearchCriteria)) EventBusFactory.getInstance().post(ProjectEvent.GotoMyProject(this, chain)) } } private class PreviewUrlResolver : ProjectUrlResolver() { override fun handlePage(vararg params: String) { val token = UrlTokenizer(params[0]) val projectId = token.getInt() val versionId = token.getInt() val chain = PageActionChain(ProjectScreenData.Goto(projectId), VersionScreenData.Read(versionId)) EventBusFactory.getInstance().post(ProjectEvent.GotoMyProject(this, chain)) } } private class EditUrlResolver : ProjectUrlResolver() { override fun handlePage(vararg params: String) { val token = UrlTokenizer(params[0]) val projectId = token.getInt() val versionId = token.getInt() val versionService = AppContextUtil.getSpringBean(VersionService::class.java) val version = versionService.findById(versionId, AppUI.accountId) if (version != null) { val chain = PageActionChain(ProjectScreenData.Goto(projectId), VersionScreenData.Edit(version)) EventBusFactory.getInstance().post(ProjectEvent.GotoMyProject(this, chain)) } else { throw ResourceNotFoundException("Can not find version $params") } } } private class AddUrlResolver : ProjectUrlResolver() { protected override fun handlePage(vararg params: String) { val projectId = UrlTokenizer(params[0]).getInt() val chain = PageActionChain(ProjectScreenData.Goto(projectId), VersionScreenData.Add(Version())) EventBusFactory.getInstance().post(ProjectEvent.GotoMyProject(this, chain)) } } }
agpl-3.0
835881758b0d72b3db232d8a8670046c
44.348315
123
0.716976
4.902795
false
false
false
false
jguerinet/MyMartlet
app/src/main/java/util/manager/McGillManager.kt
1
9188
/* * Copyright 2014-2020 Julien Guerinet * * 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.guerinet.mymartlet.util.manager import com.guerinet.mymartlet.model.Course import com.guerinet.mymartlet.model.exception.MinervaException import com.guerinet.mymartlet.util.Prefs import com.guerinet.mymartlet.util.prefs.UsernamePref import com.guerinet.mymartlet.util.retrofit.CourseResultConverter import com.guerinet.mymartlet.util.retrofit.EbillConverter import com.guerinet.mymartlet.util.retrofit.McGillService import com.guerinet.mymartlet.util.retrofit.RegistrationErrorConverter import com.guerinet.mymartlet.util.retrofit.Result import com.guerinet.mymartlet.util.retrofit.ScheduleConverter import com.guerinet.mymartlet.util.retrofit.TranscriptConverter import com.jakewharton.retrofit2.adapter.kotlin.coroutines.CoroutineCallAdapterFactory import com.orhanobut.hawk.Hawk import okhttp3.Cookie import okhttp3.CookieJar import okhttp3.HttpUrl import okhttp3.OkHttpClient import okhttp3.ResponseBody import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Response import retrofit2.Retrofit import java.io.IOException /** * All of the McGill connection logic * * @author Shabbir Hussain * @author Rafi Uddin * @author Joshua David Alfaro * @author Julien Guerinet * @since 1.0.0 * * @param loggingInterceptor [HttpLoggingInterceptor] instance * @property usernamePref [UsernamePref] instance */ class McGillManager( loggingInterceptor: HttpLoggingInterceptor, private val usernamePref: UsernamePref ) { val mcGillService: McGillService // Stores McGill related cookies private val cookieJar = object : CookieJar { private val cookieStore = mutableMapOf<String, List<Cookie>>() override fun saveFromResponse(url: HttpUrl, cookies: List<Cookie>) { // Save the cookies per URL host cookieStore[url.host] = cookies } override fun loadForRequest(url: HttpUrl): List<Cookie> { // Use the cookies for the given URL host (if none, use an empty list) val cookies = cookieStore[url.host] ?: mutableListOf() // Go through the cookies and remove the proxy ones return cookies.filter { !it.name.toLowerCase().contains("proxy") } } } init { // Set up the client here in order to have access to the login methods val client = OkHttpClient.Builder() .cookieJar(cookieJar) .addInterceptor(loggingInterceptor) .addInterceptor { chain -> // Get the request and the response val request = chain.request() val response = chain.proceed(request) // If this is the login request, don't continue if (request.method.equals("POST", ignoreCase = true)) { // This is counting on the fact that the only POST request is for login response } else { // Go through the cookies val cookie = response.headers.values("Set-Cookie") // Filter the cookies to check if there is an empty session Id .firstOrNull { it.contains("SESSID=;") } if (cookie != null) { // Try logging in (if there's an error, it will be thrown) login() // Successfully logged them back in, try retrieving the data again chain.proceed(request) } else { // If we have the session Id in the cookies, return original response response } } } .build() mcGillService = Retrofit.Builder() .client(client) .baseUrl("https://horizon.mcgill.ca/pban1/") .addConverterFactory(ScheduleConverter()) .addConverterFactory(TranscriptConverter()) .addConverterFactory(EbillConverter()) .addConverterFactory(CourseResultConverter()) .addConverterFactory(RegistrationErrorConverter()) .addCallAdapterFactory(CoroutineCallAdapterFactory()) .build() .create(McGillService::class.java) } /* HELPERS */ /** * Returns a [Result] describing whether the login was successful or not given the [response] */ private fun handleLogin(response: Response<ResponseBody>): Result { // Get the body, error out if empty val body = response.body()?.string() ?: return Result.Failure(MinervaException()) if (!body.contains("twbkwbis.P_GenMenu?name=bmenu.P_MainMnu")) { // If we're not told to move to the main menu, then the user entered wrong info return Result.Failure(MinervaException()) } return Result.EmptySuccess() } /** * Initializes the [McGillService] because a call needs to be made before anything * happens for some reason */ fun init() { // Create a blank call when initializing because the first call never seems to work try { mcGillService.login("", "").execute() } catch (ignored: IOException) { } } /** * Attempts to log into Minerva asynchronously with the [username], [password], and returns the * corresponding [Result] */ fun login(username: String, password: String): Result { return try { val response = mcGillService.login(username, password).execute() handleLogin(response) } catch (e: IOException) { Result.Failure(e) } } /** * Attempts to log the user in with the stored username and password and returns the * corresponding result */ fun login(): Result { val username = usernamePref.full ?: "" val password: String = Hawk.get(Prefs.PASSWORD) // Create the POST request with the given username and password and handle the response return handleLogin(mcGillService.login(username, password).execute()) } companion object { /** * Prepares and returns the Url to use to (un)register [courses] (we are registering * or unregistering based on [isUnregistering] */ fun getRegistrationURL(courses: List<Course>, isUnregistering: Boolean): String { // Get the currentTerm from the first course (they'll all have the same currentTerm) val term = courses[0].term // Start the URL with the currentTerm and a bunch of apparently necessary junk var url = """https://horizon.mcgill.ca/pban1/bwckcoms.P_Regs?term_in=$term &RSTS_IN=DUMMY&assoc_term_in=DUMMY&CRN_IN=DUMMY&start_date_in=DUMMY &end_date_in=DUMMY&SUBJ=DUMMY&CRSE=DUMMY&SEC=DUMMY&LEVL=DUMMY &CRED=DUMMY&GMOD=DUMMY&TITLE=DUMMY&MESG=DUMMY&REG_BTN=DUMMY&MESG=DUMMY """ if (isUnregistering) { courses.forEach { url += """&RSTS_IN=DW&assoc_term_in=$term&CRN_IN=${it.crn}&start_date_in=DUMMY &end_date_in=DUMMY&SUBJ=DUMMY&CRSE=DUMMY&SEC=DUMMY&LEVL=DUMMY&CRED=DUMMY& GMOD=DUMMY&TITLE=DUMMY&MESG=DUMMY""" } } else { url += """&RSTS_IN=&assoc_term_in=$term&CRN_IN=DUMMY&start_date_in=DUMMY &end_date_in=DUMMY&SUBJ=DUMMY&CRSE=DUMMY&SEC=DUMMYLEVL=DUMMY&CRED=DUMMY& GMOD=DUMMY&TITLE=DUMMY&MESG=DUMMY""" } // Lots of junk for (i in 0..6) { url += """&RSTS_IN=&assoc_term_in=DUMMY&CRN_IN=DUMMY&start_date_in=DUMMY &end_date_in=DUMMY&SUBJ=DUMMY&CRSE=DUMMY&SEC=DUMMY&LEVL=DUMMY&CRED=DUMMY& GMOD=DUMMY&TITLE=DUMMY&MESG=DUMMY""" } // More junk url += """&RSTS_IN=&assoc_term_in=DUMMY&CRN_IN=DUMMY&start_date_in=DUMMY& end_date_in=DUMMY&SUBJ=DUMMY&CRSE=DUMMY&SEC=DUMMY&LEVL=DUMMY&CRED=DUMMY&GMOD=DUMMY &TITLE=DUMMY""" // Insert the CRNs into the URL courses.forEach { // Use a different URL if courses are being dropped url += """&RSTS_IN=${if (isUnregistering) "" else "RW"}RW&CRN_IN=${it.crn} &assoc_term_in=&start_date_in=&end_date_in=""" } url += "&regs_row=9&wait_row=0&add_row=10&REG_BTN=Submit+Changes" return url.trimMargin() } } }
apache-2.0
097a7854968225144a804b5ef7492ab5
38.947826
99
0.618742
4.486328
false
false
false
false
derveloper/kotlin-openapi3-dsl
src/main/kotlin/cc/vileda/openapi/dsl/OpenApiDsl.kt
1
11169
package cc.vileda.openapi.dsl import io.swagger.v3.core.converter.ModelConverters import io.swagger.v3.core.util.Json import io.swagger.v3.oas.models.* import io.swagger.v3.oas.models.examples.Example import io.swagger.v3.oas.models.info.Info import io.swagger.v3.oas.models.media.* import io.swagger.v3.oas.models.parameters.Parameter import io.swagger.v3.oas.models.parameters.RequestBody import io.swagger.v3.oas.models.responses.ApiResponse import io.swagger.v3.oas.models.responses.ApiResponses import io.swagger.v3.oas.models.security.* import io.swagger.v3.oas.models.servers.Server import io.swagger.v3.oas.models.servers.ServerVariable import io.swagger.v3.oas.models.servers.ServerVariables import io.swagger.v3.oas.models.tags.Tag import io.swagger.v3.parser.OpenAPIV3Parser import org.json.JSONObject import java.io.File import java.math.BigDecimal import java.nio.file.Files import java.time.LocalDate import java.time.LocalDateTime import java.util.* fun openapiDsl(init: OpenAPI.() -> Unit): OpenAPI { val openapi3 = OpenAPI() openapi3.init() return openapi3 } internal fun validatedJson(api: OpenAPI): JSONObject { val json = Json.mapper().writeValueAsString(api) OpenAPIV3Parser().read(toFile(json).absolutePath) return JSONObject(json) } fun OpenAPI.asJson(): JSONObject { return validatedJson(this) } fun OpenAPI.asFile(): File { return toFile(asJson().toString(2)) } private fun toFile(json: String): File { val file = Files.createTempFile("openapi-", ".json").toFile() file.writeText(json) file.deleteOnExit() return file } fun OpenAPI.info(init: Info.() -> Unit) { info = Info() info.init() } fun OpenAPI.externalDocs(init: ExternalDocumentation.() -> Unit) { externalDocs = ExternalDocumentation() externalDocs.init() } fun OpenAPI.server(init: Server.() -> Unit) { val server = Server() server.init() servers = servers ?: mutableListOf() servers.add(server) } fun OpenAPI.security(init: SecurityRequirement.() -> Unit) { val securityReq = SecurityRequirement() securityReq.init() security = security ?: mutableListOf() security.add(securityReq) } fun OpenAPI.tag(init: Tag.() -> Unit) { val tag = Tag() tag.init() tags = tags ?: mutableListOf() tags.add(tag) } fun OpenAPI.paths(init: Paths.() -> Unit) { paths = Paths() paths.init() } fun OpenAPI.extension(name: String, value: Any) { addExtension(name, value) } fun PathItem.extension(name: String, value: Any) { addExtension(name, value) } fun Operation.extension(name: String, value: Any) { addExtension(name, value) } fun Components.extension(name: String, value: Any) { addExtension(name, value) } fun ApiResponse.extension(name: String, value: Any) { addExtension(name, value) } fun OpenAPI.components(init: Components.() -> Unit) { components = components ?: Components() components.init() } inline fun <reified T> Components.schema(init: Schema<*>.() -> Unit) { schemas = schemas ?: mutableMapOf() val schema = findSchema<T>() ?: throw Exception("could not find schema") schema.init() schemas.put(T::class.java.simpleName, schema) } inline fun <reified T> Components.schema() { schemas = schemas ?: mutableMapOf() val schema = findSchema<T>() schemas.put(T::class.java.simpleName, schema) } fun Components.securityScheme(init: SecurityScheme.() -> Unit) { val security = SecurityScheme() security.init() securitySchemes = securitySchemes ?: mutableMapOf() // Security schemes will not validate with a name value. Use https://editor.swagger.io to validate. // Use the type as the name. see https://swagger.io/docs/specification/authentication/ securitySchemes.put(security.type.toString(), security) } fun SecurityScheme.flows(init: OAuthFlows.() -> Unit) { flows = OAuthFlows() flows.init() } fun OAuthFlows.password(init: OAuthFlow.() -> Unit) { password = OAuthFlow() password.init() } fun OAuthFlows.implicit(init: OAuthFlow.() -> Unit) { implicit = OAuthFlow() implicit.init() } fun OAuthFlows.clientCredentials(init: OAuthFlow.() -> Unit) { clientCredentials = OAuthFlow() clientCredentials.init() } fun OAuthFlows.authorizationCode(init: OAuthFlow.() -> Unit) { authorizationCode = OAuthFlow() authorizationCode.init() } fun OAuthFlow.scopes(init: Scopes.() -> Unit) { scopes = scopes ?: Scopes() scopes.init() } fun Scopes.scope(name: String, item: String) { addString(name, item) } fun OAuthFlow.scope(name: String, item: String) { scopes = scopes ?: Scopes() scopes.addString(name, item) } fun OAuthFlow.extension(name: String, value: Any) { addExtension(name, value) } fun Tag.extension(name: String, value: Any) { addExtension(name, value) } fun Paths.path(name: String, init: PathItem.() -> Unit) { val pathItem = PathItem() pathItem.init() addPathItem(name, pathItem) } fun Paths.extension(name: String, value: Any) { addExtension(name, value) } fun PathItem.get(init: Operation.() -> Unit) { get = Operation() get.init() } fun PathItem.put(init: Operation.() -> Unit) { put = Operation() put.init() } fun PathItem.post(init: Operation.() -> Unit) { post = Operation() post.init() } fun PathItem.delete(init: Operation.() -> Unit) { delete = Operation() delete.init() } fun PathItem.patch(init: Operation.() -> Unit) { patch = Operation() patch.init() } fun PathItem.options(init: Operation.() -> Unit) { options = Operation() options.init() } fun PathItem.head(init: Operation.() -> Unit) { head = Operation() head.init() } fun PathItem.trace(init: Operation.() -> Unit) { trace = Operation() trace.init() } fun Operation.responses(init: ApiResponses.() -> Unit) { responses = ApiResponses() responses.init() } fun Operation.requestBody(init: RequestBody.() -> Unit) { requestBody = RequestBody() requestBody.init() } fun Operation.parameter(init: Parameter.() -> Unit) { parameters = parameters ?: mutableListOf() val parameter = Parameter() parameter.init() parameters.add(parameter) } fun ApiResponses.response(name: String, init: ApiResponse.() -> Unit) { val response = ApiResponse() response.init() addApiResponse(name, response) } fun ApiResponse.content(init: Content.() -> Unit) { content = Content() content.init() } fun RequestBody.content(init: Content.() -> Unit) { content = Content() content.init() } fun RequestBody.extension(name: String, value: Any) { addExtension(name, value) } fun Parameter.extension(name: String, value: Any) { addExtension(name, value) } fun ExternalDocumentation.extension(name: String, value: Any) { addExtension(name, value) } fun Parameter.content(init: Content.() -> Unit) { content = Content() content.init() } inline fun <reified T> Parameter.schema(init: Schema<*>.() -> Unit) { schema = findSchema<T>() schema.init() } inline fun <reified T> Parameter.schema() { schema = findSchema<T>() } fun <T> Schema<T>.extension(name: String, value: Any) { addExtension(name, value) } inline fun <reified T> mediaType(): MediaType { val mediaType = MediaType() val modelSchema = findSchema<T>() mediaType.schema = modelSchema return mediaType } inline fun <reified T> mediaTypeRef(): MediaType { val mediaType = MediaType() mediaType.schema = Schema<T>() mediaType.schema.`$ref` = T::class.java.simpleName return mediaType } inline fun <reified T> Content.mediaType(name: String, init: MediaType.() -> Unit) { val mediaType = mediaType<T>() mediaType.init() addMediaType(name, mediaType) } inline fun <reified T> Content.mediaTypeRef(name: String, init: MediaType.() -> Unit) { val mediaType = mediaTypeRef<T>() mediaType.init() addMediaType(name, mediaType) } inline fun <reified T> Content.mediaTypeRef(name: String) { val mediaType = mediaTypeRef<T>() addMediaType(name, mediaType) } inline fun <reified T> Content.mediaType(name: String) { val mediaType = mediaType<T>() addMediaType(name, mediaType) } inline fun <reified T> Content.mediaTypeArrayOfRef(name: String, init: MediaType.() -> Unit) { val mediaTypeArray = mediaType<List<*>>() val mediaTypeObj = mediaTypeRef<T>() mediaTypeArray.init() val arraySchema = mediaTypeArray.schema as ArraySchema arraySchema.items(mediaTypeObj.schema) addMediaType(name, mediaTypeArray) } inline fun <reified T> Content.mediaTypeArrayOf(name: String, init: MediaType.() -> Unit) { val mediaTypeArray = mediaType<List<*>>() val mediaTypeObj = mediaType<T>() mediaTypeArray.init() val arraySchema = mediaTypeArray.schema as ArraySchema arraySchema.items(mediaTypeObj.schema) addMediaType(name, mediaTypeArray) } inline fun <reified T> Content.mediaTypeArrayOfRef(name: String) { val mediaTypeArray = mediaType<List<*>>() val mediaTypeObj = mediaTypeRef<T>() val arraySchema = mediaTypeArray.schema as ArraySchema arraySchema.items(mediaTypeObj.schema) addMediaType(name, mediaTypeArray) } inline fun <reified T> Content.mediaTypeArrayOf(name: String) { val mediaTypeArray = mediaType<List<*>>() val mediaTypeObj = mediaType<T>() val arraySchema = mediaTypeArray.schema as ArraySchema arraySchema.items(mediaTypeObj.schema) addMediaType(name, mediaTypeArray) } inline fun <reified T> findSchema(): Schema<*>? { return getEnumSchema<T>() ?: when (T::class) { String::class -> StringSchema() Boolean::class -> BooleanSchema() java.lang.Boolean::class -> BooleanSchema() Int::class -> IntegerSchema() Integer::class -> IntegerSchema() List::class -> ArraySchema() Long::class -> IntegerSchema().format("int64") BigDecimal::class -> IntegerSchema().format("") Date::class -> DateSchema() LocalDate::class -> DateSchema() LocalDateTime::class -> DateTimeSchema() else -> ModelConverters.getInstance().read(T::class.java)[T::class.java.simpleName] } } inline fun <reified T> getEnumSchema(): Schema<*>? { val values = T::class.java.enumConstants ?: return null val schema = StringSchema() for (enumVal in values) { schema.addEnumItem(enumVal.toString()) } return schema } fun MediaType.extension(name: String, value: Any) { addExtension(name, value) } inline fun <reified T> MediaType.example(value: T, init: Example.() -> Unit) { examples = examples ?: mutableMapOf() val example = Example() example.value = value example.init() examples[T::class.java.simpleName] = example } fun Server.variables(init: ServerVariables.() -> Unit) { variables = ServerVariables() variables.init() } fun Server.extension(name: String, value: Any) { addExtension(name, value) } fun ServerVariables.variable(name: String, init: ServerVariable.() -> Unit) { val serverVariable = ServerVariable() serverVariable.init() addServerVariable(name, serverVariable) }
apache-2.0
a180729ed4399648b4f41326e06fd2fe
25.529691
103
0.685916
3.823691
false
false
false
false
Kotlin/kotlin-coroutines
examples/sequence/optimized/sequenceOptimized-test.kt
1
386
package sequence.optimized val fibonacci: Sequence<Int> = sequence { yield(1) // first Fibonacci number var cur = 1 var next = 1 while (true) { yield(next) // next Fibonacci number val tmp = cur + next cur = next next = tmp } } fun main(args: Array<String>) { println(fibonacci) println(fibonacci.take(10).joinToString()) }
apache-2.0
d11efb3311c91853fa0c55725e7d6f37
20.444444
46
0.601036
3.86
false
false
false
false
soywiz/korge
korge/src/commonMain/kotlin/com/soywiz/korge/view/fast/FSprites.kt
1
8469
package com.soywiz.korge.view.fast import com.soywiz.kds.* import com.soywiz.kmem.* import com.soywiz.korag.* import com.soywiz.korag.shader.* import com.soywiz.korge.render.* import com.soywiz.korge.view.* import com.soywiz.korim.bitmap.* import com.soywiz.korim.color.* import com.soywiz.korma.geom.* @PublishedApi internal const val FSPRITES_STRIDE = 8 open class FSprites(val maxSize: Int) { var size = 0 val available get() = maxSize - size val data = FBuffer(maxSize * FSPRITES_STRIDE * 4) val dataColorMul = FBuffer(maxSize * 4) private val freeItems = IntArrayList() private val i32 = data.i32 private val f32 = data.f32 private val icolorMul32 = dataColorMul.i32 fun uploadVertices(ctx: RenderContext) { ctx.fastSpriteBuffer.buffer.upload(data, 0, size * FSPRITES_STRIDE * 4) ctx.fastSpriteBufferMul.buffer.upload(dataColorMul, 0, size * 4) } fun unloadVertices(ctx: RenderContext) { ctx.fastSpriteBuffer.buffer.upload(data, 0, 0) } fun FSprite.reset() { x = 0f y = 0f scaleX = 1f scaleY = 1f radiansf = 0f colorMul = Colors.WHITE } fun alloc(): FSprite = FSprite(when { freeItems.isNotEmpty() -> freeItems.removeAt(freeItems.size - 1) else -> size++ * FSPRITES_STRIDE }).also { it.reset() } fun free(item: FSprite) { freeItems.add(item.id) item.colorMul = Colors.TRANSPARENT_BLACK // Hide this } var FSprite.x: Float get() = f32[offset + 0] ; set(value) { f32[offset + 0] = value } var FSprite.y: Float get() = f32[offset + 1] ; set(value) { f32[offset + 1] = value } var FSprite.scaleX: Float get() = f32[offset + 2] ; set(value) { f32[offset + 2] = value } var FSprite.scaleY: Float get() = f32[offset + 3] ; set(value) { f32[offset + 3] = value } var FSprite.radiansf: Float get() = f32[offset + 4] ; set(value) { f32[offset + 4] = value } var FSprite.anchorRaw: Int get() = i32[offset + 5] ; set(value) { i32[offset + 5] = value } var FSprite.tex0Raw: Int get() = i32[offset + 6] ; set(value) { i32[offset + 6] = value } var FSprite.tex1Raw: Int get() = i32[offset + 7] ; set(value) { i32[offset + 7] = value } var FSprite.colorMul: RGBA get() = RGBA(icolorMul32[index]) ; set(value) { icolorMul32[index] = value.value } var FSprite.angle: Angle get() = radiansf.radians ; set(value) { radiansf = value.radians.toFloat() } fun FSprite.setAnchor(x: Float, y: Float) { anchorRaw = packAnchor(x, y) } fun FSprite.xy(x: Float, y: Float) { this.x = x this.y = y } fun FSprite.scale(sx: Float, sy: Float = sx) { this.scaleX = sx this.scaleY = sy } fun FSprite.setTex(tex: BmpSlice) { tex0Raw = tex.left or (tex.top shl 16) tex1Raw = tex.right or (tex.bottom shl 16) } fun createView(tex: Bitmap) = FView(this, tex) class FView(val sprites: FSprites, var tex: Bitmap) : View() { var smoothing: Boolean = true private val xyData = floatArrayOf(0f, 0f, /**/ 1f, 0f, /**/ 1f, 1f, /**/ 0f, 1f) private val u_i_texSizeData = FloatArray(2) // @TODO: fallback version when instanced rendering is not supported override fun renderInternal(ctx: RenderContext) { ctx.flush() val ttex = ctx.agBitmapTextureManager.getTextureBase(tex) u_i_texSizeData[0] = 1f / ttex.width.toFloat() u_i_texSizeData[1] = 1f / ttex.height.toFloat() ctx.useBatcher { batch -> batch.setTemporalUniform(u_i_texSize, u_i_texSizeData) { batch.updateStandardUniforms() batch.setViewMatrixTemp(globalMatrix) { //ctx.batch.setStateFast() batch.textureUnitN[0].set(ttex.base, smoothing) sprites.uploadVertices(ctx) ctx.xyBuffer.buffer.upload(xyData) ctx.ag.drawV2( vertexData = ctx.buffers, program = vprogram, type = AG.DrawType.TRIANGLE_FAN, vertexCount = 4, instances = sprites.size, uniforms = batch.uniforms, //renderState = AG.RenderState(depthFunc = AG.CompareMode.LESS), //blending = AG.Blending.NONE ) sprites.unloadVertices(ctx) } } batch.onInstanceCount(sprites.size) } } } companion object { //const val STRIDE = 8 val u_i_texSize = Uniform("u_texSize", VarType.Float2) val a_xy = Attribute("a_xy", VarType.Float2, false) val a_pos = Attribute("a_rxy", VarType.Float2, false).withDivisor(1) val a_scale = Attribute("a_scale", VarType.Float2, true).withDivisor(1) val a_angle = Attribute("a_rangle", VarType.Float1, false).withDivisor(1) val a_anchor = Attribute("a_axy", VarType.SShort2, true).withDivisor(1) val a_uv0 = Attribute("a_uv0", VarType.UShort2, false).withDivisor(1) val a_uv1 = Attribute("a_uv1", VarType.UShort2, false).withDivisor(1) val a_colMul = Attribute("a_colMul", VarType.Byte4, normalized = true, precision = Precision.LOW).withDivisor(1) val RenderContext.xyBuffer by Extra.PropertyThis<RenderContext, AG.VertexData> { ag.createVertexData(a_xy) } val RenderContext.fastSpriteBuffer by Extra.PropertyThis<RenderContext, AG.VertexData> { ag.createVertexData(a_pos, a_scale, a_angle, a_anchor, a_uv0, a_uv1) } val RenderContext.fastSpriteBufferMul by Extra.PropertyThis<RenderContext, AG.VertexData> { ag.createVertexData(a_colMul) } val RenderContext.buffers by Extra.PropertyThis<RenderContext, FastArrayList<AG.VertexData>> { fastArrayListOf(xyBuffer, fastSpriteBuffer, fastSpriteBufferMul) } val vprogram = Program(VertexShader { DefaultShaders.apply { //SET(out, (u_ProjMat * u_ViewMat) * vec4(vec2(a_x, a_y), 0f.lit, 1f.lit)) //SET(v_color, texture2D(u_Tex, vec2(vec1(id) / 4f.lit, 0f.lit))) val baseSize = t_Temp1["xy"] SET(baseSize, a_uv1 - a_uv0) SET(v_Col, a_colMul) SET(v_Tex, vec2( mix(a_uv0.x, a_uv1.x, a_xy.x), mix(a_uv0.y, a_uv1.y, a_xy.y), ) * u_i_texSize) val cos = t_Temp0["x"] val sin = t_Temp0["y"] SET(cos, cos(a_angle)) SET(sin, sin(a_angle)) SET(t_TempMat2, mat2( cos, -sin, sin, cos, )) val size = t_Temp0["zw"] val localPos = t_Temp0["xy"] //SET(size, (a_scale * ((a_uv1 - a_uv0) / u_texSize) * 10f.lit)) SET(size, baseSize) SET(localPos, t_TempMat2 * (a_xy - a_anchor) * size) SET(out, (u_ProjMat * u_ViewMat) * vec4(localPos + vec2(a_pos.x, a_pos.y), 0f.lit, 1f.lit)) } }, FragmentShader { DefaultShaders.apply { SET(out, texture2D(u_Tex, v_Tex["xy"])) //SET(out, vec4(1f.lit, 0f.lit, 1f.lit, .5f.lit)) IF(out["a"] le 0f.lit) { DISCARD() } SET(out["rgb"], out["rgb"] / out["a"]) SET(out["rgba"], out["rgba"] * v_Col) } }) private fun packAnchorComponent(v: Float): Int { return (((v + 1f) * .5f) * 0xFFFF).toInt() and 0xFFFF } fun packAnchor(x: Float, y: Float): Int { return (packAnchorComponent(x) and 0xFFFF) or (packAnchorComponent(y) shl 16) } } } inline class FSprite(val id: Int) { val offset get() = id val index get() = offset / FSPRITES_STRIDE //val offset get() = index * STRIDE } fun FSpriteFromIndex(index: Int) = FSprite(index * FSPRITES_STRIDE) inline fun <T : FSprites> T.fastForEach(callback: T.(sprite: FSprite) -> Unit) { var m = 0 for (n in 0 until size) { callback(FSprite(m)) m += FSPRITES_STRIDE } }
apache-2.0
9ef67f6fe5faed8bf731c0d73b9bcca0
38.208333
120
0.5565
3.585521
false
false
false
false
arturbosch/TiNBo
tinbo-projects/src/main/kotlin/io/gitlab/arturbosch/tinbo/psp/ProjectCommands.kt
1
2863
package io.gitlab.arturbosch.tinbo.psp import io.gitlab.arturbosch.tinbo.api.TinboTerminal import io.gitlab.arturbosch.tinbo.api.marker.Addable import io.gitlab.arturbosch.tinbo.api.marker.Command import io.gitlab.arturbosch.tinbo.api.marker.Listable import io.gitlab.arturbosch.tinbo.api.model.Task import io.gitlab.arturbosch.tinbo.api.model.Time import io.gitlab.arturbosch.tinbo.api.orThrow import io.gitlab.arturbosch.tinbo.api.utils.dateFormatter import org.springframework.beans.factory.annotation.Autowired import org.springframework.shell.core.annotation.CliAvailabilityIndicator import org.springframework.shell.core.annotation.CliCommand import org.springframework.shell.core.annotation.CliOption import org.springframework.stereotype.Component import java.time.LocalDate /** * @author Artur Bosch */ @Component class ProjectCommands @Autowired constructor(private val console: TinboTerminal, private val currentProject: CurrentProject) : Command, Listable, Addable { override val id: String = "psp" override fun list(categoryName: String, all: Boolean): String = currentProject.showTasks() override fun add(): String = newTask() @CliAvailabilityIndicator("show-tasks", "new-task", "close-task") fun isAvailable() = currentProject.isSpecified() @CliCommand("new-task", help = "Adds new task to current opened project.") fun newTask(): String { return try { val name = console.readLine("Enter a name: ").orThrow { "Specify task name!" } val pTime = console.readLine("Enter planned time: ").orThrow { "Specify planned time!" }.toInt() val pUnits = console.readLine("Enter planned units: ").orThrow { "Specify planned units!" }.toInt() val end = console.readLine("Enter end date of task (empty if today): ") val date = if (end.isEmpty()) LocalDate.now() else LocalDate.parse(end, dateFormatter) currentProject.addTask(Task(name = name, plannedTime = Time(pTime), plannedUnits = pUnits, end = date)) return "Successfully added task to ${currentProject.name()}" } catch (e: IllegalArgumentException) { printMessageOfException(e) } catch (e: NumberFormatException) { printMessageOfException(e) } } private fun printMessageOfException(e: Exception) = e.message ?: throw e @CliCommand("close-task", "finish", help = "Marks task with given starting name as finish.") fun finishTask(@CliOption(key = [""]) name: String?, @CliOption(key = ["time"]) minutes: Int?, @CliOption(key = ["units"]) units: Int?): String { val wrong = "There was no task starting with given characters!" return name?.let { if (minutes == null || units == null) return "Actual time and currencyUnit values must be specified!" val (success, task) = currentProject.closeTaskWithStartingName(name, minutes, units) return if (success) "Successfully closed task $task" else wrong } ?: wrong } }
apache-2.0
4bad8b7756d6378deca263664474adbe
43.734375
106
0.746769
3.900545
false
false
false
false
wikimedia/apps-android-wikipedia
app/src/main/java/org/wikipedia/dataclient/mwapi/MwServiceError.kt
1
2257
package org.wikipedia.dataclient.mwapi import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import org.wikipedia.dataclient.ServiceError import org.wikipedia.util.DateUtil import org.wikipedia.util.StringUtil import org.wikipedia.util.ThrowableUtil import java.util.* @Serializable class MwServiceError(val code: String? = null, var html: String? = null, val data: Data? = null) : ServiceError { fun badToken(): Boolean { return "badtoken" == code } fun badLoginState(): Boolean { return "assertuserfailed" == code } fun hasMessageName(messageName: String): Boolean { return data?.messages?.find { it.name == messageName } != null } fun getMessageHtml(messageName: String): String? { return data?.messages?.first { it.name == messageName }?.html } override val title: String get() = code.orEmpty() override val details: String get() = StringUtil.removeStyleTags(html.orEmpty()) init { // Special case: if it's a Blocked error, parse the blockinfo structure ourselves. if (("blocked" == code || "autoblocked" == code) && data?.blockinfo != null) { html = ThrowableUtil.getBlockMessageHtml(data.blockinfo) } } @Serializable class Data(val messages: List<Message>? = null, val blockinfo: BlockInfo? = null) @Serializable class Message(val name: String?, val html: String = "") @Serializable open class BlockInfo { @SerialName("blockedbyid") val blockedById = 0 @SerialName("blockid") val blockId = 0 @SerialName("blockedby") val blockedBy: String = "" @SerialName("blockreason") val blockReason: String = "" @SerialName("blockedtimestamp") val blockTimeStamp: String = "" @SerialName("blockexpiry") val blockExpiry: String = "" val isBlocked: Boolean get() { if (blockExpiry.isEmpty()) { return false } val now = Date() val expiry = DateUtil.iso8601DateParse(blockExpiry) return expiry.after(now) } } }
apache-2.0
05a2019ea02d18a19804197a09386727
29.093333
90
0.609659
4.559596
false
false
false
false
slartus/4pdaClient-plus
http/src/main/java/ru/slartus/http/PersistentCookieStore.kt
1
11075
package ru.slartus.http /* * Copyright (c) 2015 Fran Montiel * * 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 android.content.Context import android.preference.PreferenceManager import android.text.TextUtils import android.util.Log import java.io.File import java.net.CookieStore import java.net.HttpCookie import java.net.URI import java.net.URISyntaxException import java.util.ArrayList import java.util.HashMap import java.util.HashSet import io.reactivex.subjects.BehaviorSubject import ru.slartus.http.prefs.AppJsonSharedPrefs class PersistentCookieStore private constructor(cookieFilePath: String) : CookieStore { private val sharedPreferences: AppJsonSharedPrefs = AppJsonSharedPrefs(cookieFilePath) // In memory private var allCookies: MutableMap<URI, MutableSet<HttpCookie>> = HashMap() var memberId = BehaviorSubject.createDefault("") init { loadAllFromPersistence() } companion object { private var INSTANCE: PersistentCookieStore? = null fun getInstance(context: Context): PersistentCookieStore { if (INSTANCE == null) INSTANCE = PersistentCookieStore(getCookieFilePath(context)) return INSTANCE!! } private val TAG = PersistentCookieStore::class.java .simpleName @Suppress("DEPRECATION") private fun getSharedPreferences(context: Context) = PreferenceManager.getDefaultSharedPreferences(context) private fun getSystemDir(context: Context): String { var dir: File? = context.filesDir if (dir == null) dir = context.getExternalFilesDir(null) assert(dir != null) var res = getSharedPreferences(context).getString("path.system_path", dir!!.path) if (!res!!.endsWith(File.separator)) res += File.separator return res } private fun getCookieFilePath(context: Context): String { var res = getSharedPreferences(context).getString("cookies.path", "") if (TextUtils.isEmpty(res)) res = getSystemDir(context) + "cookieStore.json" return res!!.replace("/", File.separator) } private val SP_KEY_DELIMITER = "|" // Unusual char in URL private val SP_KEY_DELIMITER_REGEX = "\\" + SP_KEY_DELIMITER private val m_URI = URI.create("http://slartus.ru") /** * Get the real URI from the cookie "domain" and "path" attributes, if they * are not set then uses the URI provided (coming from the response) */ private fun cookieUri(uri: URI, cookie: HttpCookie): URI { var cookieUri = uri if (cookie.domain != null) { // Remove the starting dot character of the domain, if exists (e.g: .domain.com -> domain.com) var domain = cookie.domain if (domain[0] == '.') { domain = domain.substring(1) } try { cookieUri = URI(if (uri.scheme == null) "http" else uri.scheme, domain, if (cookie.path == null) "/" else cookie.path, null) } catch (e: URISyntaxException) { Log.w(TAG, e) } } return cookieUri } } fun reload() { sharedPreferences.reload() loadAllFromPersistence() } private fun loadAllFromPersistence() { allCookies = HashMap() val allPairs = sharedPreferences.all for ((key, value) in allPairs!!) { val uriAndName = key.split(SP_KEY_DELIMITER_REGEX.toRegex(), 2).toTypedArray() try { val uri = URI(uriAndName[0]) val encodedCookie = value as String val cookie = SerializableHttpCookie() .decode(encodedCookie) var targetCookies: MutableSet<HttpCookie>? = allCookies[uri] if (targetCookies == null) { targetCookies = HashSet() allCookies[uri] = targetCookies } // Repeated cookies cannot exist in persistence // targetCookies.remove(cookie) addedCookie(cookie!!) targetCookies.add(cookie) } catch (e: URISyntaxException) { Log.w(TAG, e) } } } private fun addedCookie(cookie: HttpCookie) { if ("member_id" == cookie.name) memberId.onNext(cookie.value) } private fun deletedCookit(cookie: HttpCookie) { if ("member_id" == cookie.name) memberId.onNext("") } fun addCustom(key: String, value: String) { add(m_URI, HttpCookie(key, value)) } @Synchronized override fun add(uri1: URI, cookie: HttpCookie) { var uri = uri1 uri = cookieUri(uri, cookie) var targetCookies: MutableSet<HttpCookie>? = allCookies[uri] if (targetCookies == null) { targetCookies = HashSet() allCookies[uri] = targetCookies } targetCookies.remove(cookie) targetCookies.add(cookie) saveToPersistence(uri, cookie) } private fun saveToPersistence(uri: URI, cookie: HttpCookie) { sharedPreferences.putString(uri.toString() + SP_KEY_DELIMITER + cookie.name, SerializableHttpCookie().encode(cookie)!!) sharedPreferences.apply() addedCookie(cookie) } @Synchronized override fun get(uri: URI): List<HttpCookie> { return getValidCookies(uri) } @Synchronized override fun getCookies(): List<HttpCookie> { val allValidCookies = ArrayList<HttpCookie>() for (storedUri in allCookies.keys) { allValidCookies.addAll(getValidCookies(storedUri)) } return allValidCookies } private fun getValidCookies(uri: URI): List<HttpCookie> { val targetCookies = ArrayList<HttpCookie>() // If the stored URI does not have a path then it must match any URI in // the same domain for (storedUri in allCookies.keys) { // Check ith the domains match according to RFC 6265 if (checkDomainsMatch(storedUri.host, uri.host)) { // Check if the paths match according to RFC 6265 if (checkPathsMatch(storedUri.path, uri.path)) { allCookies[storedUri]?.let { targetCookies.addAll(it) } } } } // Check it there are expired cookies and remove them if (targetCookies.isNotEmpty()) { val cookiesToRemoveFromPersistence = ArrayList<HttpCookie>() val it = targetCookies.iterator() while (it .hasNext()) { val currentCookie = it.next() if (currentCookie.hasExpired()) { cookiesToRemoveFromPersistence.add(currentCookie) it.remove() } } if (!cookiesToRemoveFromPersistence.isEmpty()) { removeFromPersistence(uri, cookiesToRemoveFromPersistence) } } return targetCookies } /* http://tools.ietf.org/html/rfc6265#section-5.1.3 A string domain-matches a given domain string if at least one of the following conditions hold: o The domain string and the string are identical. (Note that both the domain string and the string will have been canonicalized to lower case at this point.) o All of the following conditions hold: * The domain string is a suffix of the string. * The last character of the string that is not included in the domain string is a %x2E (".") character. * The string is a host name (i.e., not an IP address). */ private fun checkDomainsMatch(cookieHost: String, requestHost: String): Boolean { return requestHost == cookieHost || requestHost.endsWith(".$cookieHost") } /* http://tools.ietf.org/html/rfc6265#section-5.1.4 A response-path path-matches a given cookie-path if at least one of the following conditions holds: o The cookie-path and the response-path are identical. o The cookie-path is a prefix of the response-path, and the last character of the cookie-path is %x2F ("/"). o The cookie-path is a prefix of the response-path, and the first character of the response-path that is not included in the cookie- path is a %x2F ("/") character. */ private fun checkPathsMatch(cookiePath: String, requestPath: String): Boolean { if (cookiePath.isEmpty()&&requestPath.isEmpty()) return true if (cookiePath.isEmpty()) return false return requestPath == cookiePath || requestPath.startsWith(cookiePath) && cookiePath[cookiePath.length - 1] == '/' || requestPath.startsWith(cookiePath) && requestPath.substring(cookiePath.length)[0] == '/' } private fun removeFromPersistence(uri: URI, cookiesToRemove: List<HttpCookie>) { for (cookieToRemove in cookiesToRemove) { sharedPreferences.remove(uri.toString() + SP_KEY_DELIMITER + cookieToRemove.name) deletedCookit(cookieToRemove) } sharedPreferences.apply() } @Synchronized override fun getURIs(): List<URI> { return ArrayList(allCookies.keys) } @Synchronized override fun remove(uri: URI, cookie: HttpCookie): Boolean { val targetCookies = allCookies[uri] val cookieRemoved = targetCookies != null && targetCookies .remove(cookie) if (cookieRemoved) { removeFromPersistence(uri, cookie) } return cookieRemoved } private fun removeFromPersistence(uri: URI, cookieToRemove: HttpCookie) { sharedPreferences.remove(uri.toString() + SP_KEY_DELIMITER + cookieToRemove.name) sharedPreferences.apply() deletedCookit(cookieToRemove) } @Synchronized override fun removeAll(): Boolean { allCookies.clear() removeAllFromPersistence() return true } private fun removeAllFromPersistence() { sharedPreferences.clear().apply() memberId.onNext("") } }
apache-2.0
205916f6fde3b44e8cdda11ce19ab177
33.08
115
0.605237
4.920036
false
false
false
false
stripe/stripe-android
stripecardscan/src/main/java/com/stripe/android/stripecardscan/framework/ml/TensorFlowLiteAnalyzer.kt
1
2937
package com.stripe.android.stripecardscan.framework.ml import android.content.Context import android.util.Log import com.stripe.android.camera.framework.Analyzer import com.stripe.android.camera.framework.AnalyzerFactory import com.stripe.android.stripecardscan.framework.FetchedData import com.stripe.android.stripecardscan.framework.Loader import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import org.tensorflow.lite.Interpreter import org.tensorflow.lite.nnapi.NnApiDelegate import java.io.Closeable import java.nio.ByteBuffer /** * A TensorFlowLite analyzer uses an [Interpreter] to analyze data. */ internal abstract class TensorFlowLiteAnalyzer<Input, MLInput, Output, MLOutput>( private val tfInterpreter: Interpreter, private val delegate: NnApiDelegate? = null ) : Analyzer<Input, Any, Output>, Closeable { protected abstract suspend fun interpretMLOutput(data: Input, mlOutput: MLOutput): Output protected abstract suspend fun transformData(data: Input): MLInput protected abstract suspend fun executeInference( tfInterpreter: Interpreter, data: MLInput ): MLOutput override suspend fun analyze(data: Input, state: Any): Output { val mlInput = transformData(data) val mlOutput = executeInference(tfInterpreter, mlInput) return interpretMLOutput(data, mlOutput) } override fun close() { tfInterpreter.close() delegate?.close() } } /** * A factory that creates tensorflow models as analyzers. */ internal abstract class TFLAnalyzerFactory< Input, Output, AnalyzerType : Analyzer<Input, Any, Output> >( private val context: Context, private val fetchedModel: FetchedData ) : AnalyzerFactory<Input, Any, Output, AnalyzerType> { protected abstract val tfOptions: Interpreter.Options private val loader by lazy { Loader(context) } private val loadModelMutex = Mutex() private var loadedModel: ByteBuffer? = null protected suspend fun createInterpreter(): Interpreter? = createInterpreter(fetchedModel) private suspend fun createInterpreter(fetchedModel: FetchedData): Interpreter? = try { loadModel(fetchedModel)?.let { Interpreter(it, tfOptions) } } catch (t: Throwable) { Log.e( LOG_TAG, "Error loading ${fetchedModel.modelClass} version ${fetchedModel.modelVersion}", t ) null }.apply { if (this == null) { Log.w( LOG_TAG, "Unable to load ${fetchedModel.modelClass} version ${fetchedModel.modelVersion}" ) } } private suspend fun loadModel(fetchedModel: FetchedData): ByteBuffer? = loadModelMutex.withLock { loadedModel ?: run { loader.loadData(fetchedModel) } } companion object { private val LOG_TAG = TFLAnalyzerFactory::class.java.simpleName } }
mit
4d90df19521da5f0042885bc3d674257
30.580645
96
0.70446
4.560559
false
false
false
false
ejeinc/VR-MultiView-UDP
viewer-common/src/main/java/com/eje_c/multilink/MultiLinkApp.kt
1
2406
package com.eje_c.multilink import android.content.Context import android.os.Handler import android.os.Looper import com.eje_c.multilink.data.DeviceInfo import com.eje_c.multilink.udp.MultiLinkUdpMessenger import com.eje_c.player.ExoPlayerImpl import com.google.android.exoplayer2.DefaultRenderersFactory import com.google.android.exoplayer2.ExoPlayerFactory import com.google.android.exoplayer2.audio.AudioProcessor import com.google.android.exoplayer2.ext.gvr.GvrAudioProcessor import com.google.android.exoplayer2.trackselection.DefaultTrackSelector import java.net.SocketAddress import java.util.* /** * アプリケーションのメインクラス。 */ class MultiLinkApp(val context: Context) { private val gvrAudioProcessor = GvrAudioProcessor() val player: BasePlayer /** * trueの時かつUDP送信先がわかっている場合はヘッドトラッキング情報を毎フレーム送信する。 */ // var sendHeadTransform: Boolean = false init { check(Looper.getMainLooper() == Looper.myLooper(), { "Must be initialized in main thread!" }) val renderersFactory = object : DefaultRenderersFactory(context) { override fun buildAudioProcessors(): Array<AudioProcessor> { return arrayOf(gvrAudioProcessor) } } val exoPlayer = ExoPlayerFactory.newSimpleInstance(renderersFactory, DefaultTrackSelector()) player = BasePlayer(ExoPlayerImpl(context, exoPlayer)) // Set handler MultiLinkUdpMessenger.onReceivePing += ::respondWithMyDeviceInfo MultiLinkUdpMessenger.onReceiveControlMessage += player::updateState } /** * 毎フレーム更新時に呼ばれる。 */ fun updateHeadOrientation(x: Float, y: Float, z: Float, w: Float) { gvrAudioProcessor.updateOrientation(w, x, y, z) // ヘッドトラッキング情報の送信 // if (sendHeadTransform) { // udpSender.send(x, y, z, w) // } } /** * 端末情報をコントローラーに送る。 */ private fun respondWithMyDeviceInfo(remote: SocketAddress) { // ランダムでディレイを入れてから送り返す Handler(Looper.getMainLooper()).postDelayed({ MultiLinkUdpMessenger.sendDeviceInfo(DeviceInfo.get(context), remote) }, Random().nextInt(3000).toLong()) } }
apache-2.0
5697d5150d276a88b5ef3044efb55bb2
30.911765
101
0.703687
3.916968
false
false
false
false
dylan0011/kotlin_learning
src/basic/Visibility.kt
1
1062
package basic /** * Created by [email protected] on 2017/7/18. * Desc: */ open class Outer { private val a = 0 protected open val b = 1 internal val c = 2 val d = 3 protected class Nested { public val e = 4 } } class SubOuter : Outer() { override val b = 3 } class Unrelated(what: Outer) { var what: Outer get() = what set(value) { this.what = what } fun asd() { what.c what.d } } class Foo{ fun Outer.foo() { println("Outer foo") } fun caller(outer: Outer) { outer.foo() } } fun main(args: Array<String>) { whenTest(1) val man = Man() man.eat("apple") val foo = Foo() val outer = Outer() foo.caller(outer) val customer = Customer() println(customer.component1()) val customer2 = customer.copy() val customer3 = customer.copy(name = "3") val (name,email) = customer3.copy(name = "pair",email = "email") println(customer) println(customer2) println(customer3) }
apache-2.0
6f7557b268c1799600043fb9a80f0a1c
15.609375
68
0.550847
3.414791
false
false
false
false
deeplearning4j/deeplearning4j
nd4j/samediff-import/samediff-import-onnx/src/main/kotlin/org/nd4j/samediff/frameworkimport/onnx/ir/OnnxIRNode.kt
1
7707
/* * ****************************************************************************** * * * * * * This program and the accompanying materials are made available under the * * terms of the Apache License, Version 2.0 which is available at * * https://www.apache.org/licenses/LICENSE-2.0. * * * * See the NOTICE file distributed with this work for additional * * information regarding copyright ownership. * * 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. * * * * SPDX-License-Identifier: Apache-2.0 * ***************************************************************************** */ package org.nd4j.samediff.frameworkimport.onnx.ir import onnx.Onnx import org.nd4j.ir.OpNamespace import org.nd4j.samediff.frameworkimport.ir.IRAttribute import org.nd4j.samediff.frameworkimport.ir.IRNode import org.nd4j.samediff.frameworkimport.ir.IRTensor import org.nd4j.samediff.frameworkimport.lookupIndexForArgDescriptor import org.nd4j.samediff.frameworkimport.onnx.attrDefaultValue import org.nd4j.samediff.frameworkimport.process.MappingProcess import org.nd4j.samediff.frameworkimport.registry.OpMappingRegistry import java.lang.IllegalArgumentException import java.util.HashMap class OnnxIRNode(inputNode: Onnx.NodeProto, inputOpDef: Onnx.NodeProto,opMappingRegistry: OpMappingRegistry<Onnx.GraphProto, Onnx.NodeProto, Onnx.NodeProto, Onnx.TensorProto, Onnx.TensorProto.DataType, Onnx.AttributeProto, Onnx.AttributeProto> ): IRNode<Onnx.NodeProto, Onnx.TensorProto, Onnx.AttributeProto, Onnx.AttributeProto, Onnx.TensorProto.DataType> { private var nodeDef = inputNode private val opDef = inputOpDef private val attrDefsMap = attrDefsByName(inputOpDef.attributeList) private val attrMap: Map<String, IRAttribute<Onnx.AttributeProto, Onnx.AttributeProto, Onnx.TensorProto, Onnx.TensorProto.DataType>> = initAttrMapFromNode(inputNode) private val mappingProcess: MappingProcess<Onnx.GraphProto, Onnx.NodeProto, Onnx.NodeProto, Onnx.TensorProto, Onnx.AttributeProto, Onnx.AttributeProto, Onnx.TensorProto.DataType> private val opMappingRegistry = opMappingRegistry init { mappingProcess = opMappingRegistry.lookupOpMappingProcess(inputNode.opType) } private fun attrDefsByName(input: List<Onnx.AttributeProto>): Map<String, Onnx.AttributeProto> { val ret = HashMap<String, Onnx.AttributeProto>() input.forEach { ret[it.name] = it } return ret } private fun initAttrMapFromNode(input: Onnx.NodeProto): Map<String, IRAttribute<Onnx.AttributeProto, Onnx.AttributeProto, Onnx.TensorProto, Onnx.TensorProto.DataType>> { val ret = HashMap<String, IRAttribute<Onnx.AttributeProto, Onnx.AttributeProto, Onnx.TensorProto, Onnx.TensorProto.DataType>>() input.attributeList.forEach { ret[it.name] = OnnxIRAttr(it, it) } return ret } override fun opName(): String { return nodeDef.opType } override fun nodeName(): String { return nodeDef.name } override fun inputAt(index: Int): String { if(mappingProcess.indexOverrides().containsKey(index)) return nodeDef.getInput(mappingProcess.indexOverrides()[index]!!) return nodeDef.getInput(index) } override fun outputAt(index: Int): String { //Identity's output is just its node name and has no output if(nodeDef.outputCount < 1) { return nodeDef.name } else if(nodeDef.opType == "Identity" && index > 0) { throw IllegalArgumentException("Invalid index for Identity op. Only 0 is valid, received $index") } return nodeDef.getOutput(index) } override fun hasAttribute(inputName: String): Boolean { return nodeDef.attributeList.filter { it.name == inputName }.size > 0 } override fun attributeMap(): Map<String, IRAttribute<Onnx.AttributeProto, Onnx.AttributeProto, Onnx.TensorProto, Onnx.TensorProto.DataType>> { return attrMap } override fun createInputsFrom(inputData: List<Onnx.TensorProto>): List<IRTensor<Onnx.TensorProto, Onnx.TensorProto.DataType>> { return inputData.map { OnnxIRTensor(it) } } override fun createOutputsFrom(inputValues: List<Onnx.TensorProto>): List<IRTensor<Onnx.TensorProto, Onnx.TensorProto.DataType>> { return inputValues.map { OnnxIRTensor(it) } } override fun getAttribute(inputName: String): IRAttribute<Onnx.AttributeProto, Onnx.AttributeProto, Onnx.TensorProto, Onnx.TensorProto.DataType> { return attrMap.getOrDefault(inputName, attrDefaultValue()) } override fun internalValue(): Onnx.NodeProto { return nodeDef } override fun numInputs(): Int { return nodeDef.inputCount } override fun numOutputs(): Int { return nodeDef.outputCount } override fun inputs(): List<String> { return nodeDef.inputList } override fun outputs(): List<String> { return nodeDef.outputList } override fun numInputsForListOfTensors(name: String): Int { return nodeDef.inputCount } override fun inputNamesForListOfInputValues(inputListName: String): List<String> { return nodeDef.inputList } override fun computeAdjustedOffsetForInput( nd4jName: String, inputFrameworkName: String, tensorInputMappings: Map<String, String> ): Int { //onnx doesn't have lists of values like this return lookupIndexForArgDescriptor( argDescriptorName = nd4jName, opDescriptorName = this.opName(), argDescriptorType = OpNamespace.ArgDescriptor.ArgType.INPUT_TENSOR ) } override fun nd4jInputs(tensorMappings: Map<String, String>): List<String> { return nodeDef.inputList } override fun addInput(inputName: String) { val nodeBuilder = nodeDef.toBuilder() nodeBuilder.addInput(inputName) this.nodeDef = nodeBuilder.build() } override fun setInputAt(index: Int, name: String) { val nodeBuilder = nodeDef.toBuilder() nodeBuilder.setInput(index,name) this.nodeDef = nodeBuilder.build() } override fun setOutputAt(index: Int, name: String) { val nodeBuilder = nodeDef.toBuilder() nodeBuilder.setOutput(index,name) this.nodeDef = nodeBuilder.build() } override fun setNodeName(name: String) { val nodeBuilder = nodeDef.toBuilder() nodeBuilder.name = name this.nodeDef = nodeBuilder.build() } override fun removeAttribute(attributeName: String): Onnx.AttributeProto { val nodeBuilder = nodeDef.toBuilder() var index = -1 for(i in 0 until nodeDef.attributeCount) { if(nodeDef.attributeList[i].name == attributeName) { index = i break } } if(index >= 0) { val attrValue = nodeBuilder.attributeList[index] nodeBuilder.removeAttribute(index) this.nodeDef = nodeBuilder.build() return attrValue } return Onnx.AttributeProto.getDefaultInstance() } override fun isControlflowOp(): Boolean { return nodeDef.opType == "Loop" || nodeDef.opType == "If" || nodeDef.opType.contains("Sequence") } }
apache-2.0
56023eacaf5a92108c7e9d85782240ac
35.530806
182
0.673154
4.651177
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/ide/inspections/fixes/RemoveGenericArguments.kt
2
1478
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.inspections.fixes import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.openapi.project.Project import org.rust.ide.inspections.getTypeArgumentsAndDeclaration import org.rust.lang.core.psi.RsTypeArgumentList import org.rust.lang.core.psi.ext.RsMethodOrPath import org.rust.lang.core.psi.ext.deleteWithSurroundingComma import org.rust.lang.core.psi.ext.getNextNonCommentSibling import org.rust.lang.core.psi.ext.startOffset class RemoveGenericArguments( private val startIndex: Int, private val endIndex: Int ) : LocalQuickFix { override fun getFamilyName() = "Remove redundant generic arguments" override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val element = descriptor.psiElement as? RsMethodOrPath ?: return val (typeArguments) = getTypeArgumentsAndDeclaration(element) ?: return typeArguments?.removeTypeParameters() } private fun RsTypeArgumentList.removeTypeParameters() { (typeReferenceList + exprList) .sortedBy { it.startOffset } .subList(startIndex, endIndex) .forEach { it.deleteWithSurroundingComma() } // If the type argument list is empty, delete it if (lt.getNextNonCommentSibling() == gt) { delete() } } }
mit
7dc009e99ca4a30716480912626f0b0c
35.95
79
0.73613
4.519878
false
false
false
false
Undin/intellij-rust
src/test/kotlin/org/rust/ide/formatter/RsFormatterTestBase.kt
2
2420
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.formatter import com.intellij.openapi.application.ApplicationInfo import com.intellij.psi.formatter.FormatterTestCase import com.intellij.util.ThrowableRunnable import org.intellij.lang.annotations.Language import org.rust.IgnoreInPlatform import org.rust.TestCase import org.rust.findAnnotationInstance import kotlin.reflect.KMutableProperty0 abstract class RsFormatterTestBase : FormatterTestCase() { override fun getTestDataPath() = "src/test/resources" override fun getBasePath() = "org/rust/ide/formatter/fixtures" override fun getFileExtension() = "rs" override fun getTestName(lowercaseFirstLetter: Boolean): String { val camelCase = super.getTestName(lowercaseFirstLetter) return TestCase.camelOrWordsToSnake(camelCase) } override fun runTestRunnable(testRunnable: ThrowableRunnable<Throwable>) { val ignoreAnnotation = findAnnotationInstance<IgnoreInPlatform>() if (ignoreAnnotation != null) { val majorPlatformVersion = ApplicationInfo.getInstance().build.baselineVersion if (majorPlatformVersion in ignoreAnnotation.majorVersions) { System.err.println("SKIP \"$name\": test is ignored for `$majorPlatformVersion` platform") return } } return super.runTestRunnable(testRunnable) } override fun doTextTest(@Language("Rust") text: String, @Language("Rust") textAfter: String) { check(text.trimIndent() != textAfter.trimIndent()) super.doTextTest(text.trimIndent(), textAfter.trimIndent()) } fun checkNotChanged(@Language("Rust") text: String) { super.doTextTest(text.trimIndent(), text.trimIndent()) } fun doTextTest( optionProperty: KMutableProperty0<Boolean>, @Language("Rust") before: String, @Language("Rust") afterOn: String = before, @Language("Rust") afterOff: String = before ) { val initialValue = optionProperty.get() optionProperty.set(true) try { super.doTextTest(before.trimIndent(), afterOn.trimIndent()) optionProperty.set(false) super.doTextTest(before.trimIndent(), afterOff.trimIndent()) } finally { optionProperty.set(initialValue) } } }
mit
741c1667bc56bf653d5ecdcf04d1aa96
35.119403
106
0.691736
4.820717
false
true
false
false
deva666/anko
anko/library/generated/sdk19/src/Layouts.kt
2
62158
@file:JvmName("Sdk19LayoutsKt") package org.jetbrains.anko import android.content.Context import android.util.AttributeSet import android.view.ViewGroup import android.widget.FrameLayout import android.appwidget.AppWidgetHostView import android.view.View import android.webkit.WebView import android.widget.AbsoluteLayout import android.widget.Gallery import android.widget.GridLayout import android.widget.GridView import android.widget.AbsListView import android.widget.HorizontalScrollView import android.widget.ImageSwitcher import android.widget.LinearLayout import android.widget.RadioGroup import android.widget.RelativeLayout import android.widget.ScrollView import android.widget.TableLayout import android.widget.TableRow import android.widget.TextSwitcher import android.widget.ViewAnimator import android.widget.ViewSwitcher open class _AppWidgetHostView(ctx: Context): AppWidgetHostView(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = FrameLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _WebView(ctx: Context): WebView(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: ViewGroup.LayoutParams.() -> Unit ): T { val layoutParams = ViewGroup.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = ViewGroup.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: ViewGroup.LayoutParams.() -> Unit ): T { val layoutParams = ViewGroup.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = ViewGroup.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: ViewGroup.LayoutParams.() -> Unit ): T { val layoutParams = ViewGroup.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = ViewGroup.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _AbsoluteLayout(ctx: Context): AbsoluteLayout(ctx) { inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, x: Int, y: Int, init: AbsoluteLayout.LayoutParams.() -> Unit ): T { val layoutParams = AbsoluteLayout.LayoutParams(width, height, x, y) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, x: Int, y: Int ): T { val layoutParams = AbsoluteLayout.LayoutParams(width, height, x, y) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: AbsoluteLayout.LayoutParams.() -> Unit ): T { val layoutParams = AbsoluteLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = AbsoluteLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: AbsoluteLayout.LayoutParams.() -> Unit ): T { val layoutParams = AbsoluteLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = AbsoluteLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _FrameLayout(ctx: Context): FrameLayout(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = FrameLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _Gallery(ctx: Context): Gallery(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: Gallery.LayoutParams.() -> Unit ): T { val layoutParams = Gallery.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = Gallery.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: Gallery.LayoutParams.() -> Unit ): T { val layoutParams = Gallery.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = Gallery.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: Gallery.LayoutParams.() -> Unit ): T { val layoutParams = Gallery.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = Gallery.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _GridLayout(ctx: Context): GridLayout(ctx) { inline fun <T: View> T.lparams( rowSpec: GridLayout.Spec?, columnSpec: GridLayout.Spec?, init: GridLayout.LayoutParams.() -> Unit ): T { val layoutParams = GridLayout.LayoutParams(rowSpec!!, columnSpec!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( rowSpec: GridLayout.Spec?, columnSpec: GridLayout.Spec? ): T { val layoutParams = GridLayout.LayoutParams(rowSpec!!, columnSpec!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( init: GridLayout.LayoutParams.() -> Unit ): T { val layoutParams = GridLayout.LayoutParams() layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( ): T { val layoutParams = GridLayout.LayoutParams() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( params: ViewGroup.LayoutParams?, init: GridLayout.LayoutParams.() -> Unit ): T { val layoutParams = GridLayout.LayoutParams(params!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( params: ViewGroup.LayoutParams? ): T { val layoutParams = GridLayout.LayoutParams(params!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( params: ViewGroup.MarginLayoutParams?, init: GridLayout.LayoutParams.() -> Unit ): T { val layoutParams = GridLayout.LayoutParams(params!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( params: ViewGroup.MarginLayoutParams? ): T { val layoutParams = GridLayout.LayoutParams(params!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: GridLayout.LayoutParams?, init: GridLayout.LayoutParams.() -> Unit ): T { val layoutParams = GridLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: GridLayout.LayoutParams? ): T { val layoutParams = GridLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( context: Context?, attrs: AttributeSet?, init: GridLayout.LayoutParams.() -> Unit ): T { val layoutParams = GridLayout.LayoutParams(context!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( context: Context?, attrs: AttributeSet? ): T { val layoutParams = GridLayout.LayoutParams(context!!, attrs!!) [email protected] = layoutParams return this } } open class _GridView(ctx: Context): GridView(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: AbsListView.LayoutParams.() -> Unit ): T { val layoutParams = AbsListView.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = AbsListView.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: AbsListView.LayoutParams.() -> Unit ): T { val layoutParams = AbsListView.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = AbsListView.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, viewType: Int, init: AbsListView.LayoutParams.() -> Unit ): T { val layoutParams = AbsListView.LayoutParams(width, height, viewType) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, viewType: Int ): T { val layoutParams = AbsListView.LayoutParams(width, height, viewType) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: AbsListView.LayoutParams.() -> Unit ): T { val layoutParams = AbsListView.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = AbsListView.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _HorizontalScrollView(ctx: Context): HorizontalScrollView(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = FrameLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _ImageSwitcher(ctx: Context): ImageSwitcher(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = FrameLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _LinearLayout(ctx: Context): LinearLayout(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: LinearLayout.LayoutParams.() -> Unit ): T { val layoutParams = LinearLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = LinearLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: LinearLayout.LayoutParams.() -> Unit ): T { val layoutParams = LinearLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = LinearLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, weight: Float, init: LinearLayout.LayoutParams.() -> Unit ): T { val layoutParams = LinearLayout.LayoutParams(width, height, weight) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, weight: Float ): T { val layoutParams = LinearLayout.LayoutParams(width, height, weight) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: ViewGroup.LayoutParams?, init: LinearLayout.LayoutParams.() -> Unit ): T { val layoutParams = LinearLayout.LayoutParams(p!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: ViewGroup.LayoutParams? ): T { val layoutParams = LinearLayout.LayoutParams(p!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: LinearLayout.LayoutParams.() -> Unit ): T { val layoutParams = LinearLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = LinearLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: LinearLayout.LayoutParams?, init: LinearLayout.LayoutParams.() -> Unit ): T { val layoutParams = LinearLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: LinearLayout.LayoutParams? ): T { val layoutParams = LinearLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _RadioGroup(ctx: Context): RadioGroup(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: RadioGroup.LayoutParams.() -> Unit ): T { val layoutParams = RadioGroup.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = RadioGroup.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: RadioGroup.LayoutParams.() -> Unit ): T { val layoutParams = RadioGroup.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = RadioGroup.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, initWeight: Float, init: RadioGroup.LayoutParams.() -> Unit ): T { val layoutParams = RadioGroup.LayoutParams(width, height, initWeight) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, initWeight: Float ): T { val layoutParams = RadioGroup.LayoutParams(width, height, initWeight) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: ViewGroup.LayoutParams?, init: RadioGroup.LayoutParams.() -> Unit ): T { val layoutParams = RadioGroup.LayoutParams(p!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: ViewGroup.LayoutParams? ): T { val layoutParams = RadioGroup.LayoutParams(p!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: RadioGroup.LayoutParams.() -> Unit ): T { val layoutParams = RadioGroup.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = RadioGroup.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _RelativeLayout(ctx: Context): RelativeLayout(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: RelativeLayout.LayoutParams.() -> Unit ): T { val layoutParams = RelativeLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = RelativeLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: RelativeLayout.LayoutParams.() -> Unit ): T { val layoutParams = RelativeLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = RelativeLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: RelativeLayout.LayoutParams.() -> Unit ): T { val layoutParams = RelativeLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = RelativeLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: RelativeLayout.LayoutParams.() -> Unit ): T { val layoutParams = RelativeLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = RelativeLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: RelativeLayout.LayoutParams?, init: RelativeLayout.LayoutParams.() -> Unit ): T { val layoutParams = RelativeLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: RelativeLayout.LayoutParams? ): T { val layoutParams = RelativeLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _ScrollView(ctx: Context): ScrollView(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = FrameLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _TableLayout(ctx: Context): TableLayout(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: TableLayout.LayoutParams.() -> Unit ): T { val layoutParams = TableLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = TableLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: TableLayout.LayoutParams.() -> Unit ): T { val layoutParams = TableLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = TableLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, initWeight: Float, init: TableLayout.LayoutParams.() -> Unit ): T { val layoutParams = TableLayout.LayoutParams(width, height, initWeight) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, initWeight: Float ): T { val layoutParams = TableLayout.LayoutParams(width, height, initWeight) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( init: TableLayout.LayoutParams.() -> Unit ): T { val layoutParams = TableLayout.LayoutParams() layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( ): T { val layoutParams = TableLayout.LayoutParams() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: ViewGroup.LayoutParams?, init: TableLayout.LayoutParams.() -> Unit ): T { val layoutParams = TableLayout.LayoutParams(p!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: ViewGroup.LayoutParams? ): T { val layoutParams = TableLayout.LayoutParams(p!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: TableLayout.LayoutParams.() -> Unit ): T { val layoutParams = TableLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = TableLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _TableRow(ctx: Context): TableRow(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: TableRow.LayoutParams.() -> Unit ): T { val layoutParams = TableRow.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = TableRow.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: TableRow.LayoutParams.() -> Unit ): T { val layoutParams = TableRow.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = TableRow.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, initWeight: Float, init: TableRow.LayoutParams.() -> Unit ): T { val layoutParams = TableRow.LayoutParams(width, height, initWeight) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, initWeight: Float ): T { val layoutParams = TableRow.LayoutParams(width, height, initWeight) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( init: TableRow.LayoutParams.() -> Unit ): T { val layoutParams = TableRow.LayoutParams() layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( ): T { val layoutParams = TableRow.LayoutParams() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( column: Int, init: TableRow.LayoutParams.() -> Unit ): T { val layoutParams = TableRow.LayoutParams(column) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( column: Int ): T { val layoutParams = TableRow.LayoutParams(column) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: ViewGroup.LayoutParams?, init: TableRow.LayoutParams.() -> Unit ): T { val layoutParams = TableRow.LayoutParams(p!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: ViewGroup.LayoutParams? ): T { val layoutParams = TableRow.LayoutParams(p!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: TableRow.LayoutParams.() -> Unit ): T { val layoutParams = TableRow.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = TableRow.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _TextSwitcher(ctx: Context): TextSwitcher(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = FrameLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _ViewAnimator(ctx: Context): ViewAnimator(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = FrameLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _ViewSwitcher(ctx: Context): ViewSwitcher(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = FrameLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } }
apache-2.0
17ccfddb9b502e53ec0378c122c7416d
30.826933
78
0.610927
4.870935
false
false
false
false
foreverigor/TumCampusApp
app/src/main/java/de/tum/in/tumcampusapp/service/FcmTokenHandler.kt
1
5151
package de.tum.`in`.tumcampusapp.service import android.content.Context import com.google.android.gms.tasks.OnSuccessListener import com.google.firebase.iid.FirebaseInstanceId import de.tum.`in`.tumcampusapp.api.app.TUMCabeClient import de.tum.`in`.tumcampusapp.api.app.model.DeviceUploadFcmToken import de.tum.`in`.tumcampusapp.api.app.model.TUMCabeStatus import de.tum.`in`.tumcampusapp.utils.Const.FCM_INSTANCE_ID import de.tum.`in`.tumcampusapp.utils.Const.FCM_REG_ID_LAST_TRANSMISSION import de.tum.`in`.tumcampusapp.utils.Const.FCM_REG_ID_SENT_TO_SERVER import de.tum.`in`.tumcampusapp.utils.Const.FCM_TOKEN_ID import de.tum.`in`.tumcampusapp.utils.Utils import de.tum.`in`.tumcampusapp.utils.tryOrNull import retrofit2.Call import retrofit2.Callback import retrofit2.Response import java.util.* import java.util.concurrent.Executors object FcmTokenHandler { @JvmStatic fun checkSetup(context: Context) { val currentToken = Utils.getSetting(context, FCM_TOKEN_ID, "") // If we failed, we need to re register if (currentToken.isEmpty()) { registerInBackground(context) } else { // If the regId is not empty, we still need to check whether it was successfully sent to the // TCA server, because this can fail due to user not confirming their private key if (!Utils.getSettingBool(context, FCM_REG_ID_SENT_TO_SERVER, false)) { sendTokenToBackend(context, currentToken) } // Update the reg id in steady intervals checkRegisterIdUpdate(context, currentToken) } } /** * Registers the application with GCM servers asynchronously. * * * Stores the registration ID and app versionCode in the application's * shared preferences. */ private fun registerInBackground(context: Context) { val executor = Executors.newSingleThreadExecutor() FirebaseInstanceId.getInstance().instanceId.addOnSuccessListener(executor, OnSuccessListener { instanceIdResult -> val token = instanceIdResult.token Utils.setSetting(context, FCM_INSTANCE_ID, instanceIdResult.id) Utils.setSetting(context, FCM_TOKEN_ID, token) // Reset the lock in case we are updating and maybe failed Utils.setSetting(context, FCM_REG_ID_SENT_TO_SERVER, false) Utils.setSetting(context, FCM_REG_ID_LAST_TRANSMISSION, Date().time) // Let the server know of our new registration ID sendTokenToBackend(context, token) Utils.log("FCM registration successful") }) } /** * Sends the registration ID to your server over HTTP, so it can use GCM/HTTP * or CCS to send messages to your app. Not needed for this demo since the * device sends upstream messages to a server that echoes back the message * using the 'from' address in the message. */ private fun sendTokenToBackend(context: Context, token: String?) { // Check if all parameters are present if (token == null || token.isEmpty()) { Utils.logv("Parameter missing for sending reg id") return } // Try to create the message val uploadToken = tryOrNull { DeviceUploadFcmToken.getDeviceUploadFcmToken(context, token) } ?: return TUMCabeClient .getInstance(context) .deviceUploadGcmToken(uploadToken, object : Callback<TUMCabeStatus> { override fun onResponse(call: Call<TUMCabeStatus>, response: Response<TUMCabeStatus>) { if (!response.isSuccessful) { Utils.logv("Uploading FCM registration failed...") return } val body = response.body() ?: return Utils.logv("Success uploading FCM registration id: ${body.status}") // Store in shared preferences the information that the GCM registration id // was sent to the TCA server successfully Utils.setSetting(context, FCM_REG_ID_SENT_TO_SERVER, true) } override fun onFailure(call: Call<TUMCabeStatus>, t: Throwable) { Utils.log(t, "Failure uploading FCM registration id") Utils.setSetting(context, FCM_REG_ID_SENT_TO_SERVER, false) } }) } /** * Helper function to check if we need to update the regid * * @param regId registration ID */ private fun checkRegisterIdUpdate(context: Context, regId: String) { // Regularly (once a day) update the server with the reg id val lastTransmission = Utils.getSettingLong(context, FCM_REG_ID_LAST_TRANSMISSION, 0L) val now = Date() if (now.time - 24 * 3600000 > lastTransmission) { sendTokenToBackend(context, regId) } } }
gpl-3.0
56aaf6f664589af7076acef7ba69831d
40.878049
107
0.623762
4.787175
false
false
false
false