repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
eldelcesar/SkyNet
SkyNet/app/src/test/java/gdl/dreamteam/skynet/Others/SQLRepositoryTest.kt
2
1969
package gdl.dreamteam.skynet.Others import gdl.dreamteam.skynet.BuildConfig import gdl.dreamteam.skynet.Models.Client import gdl.dreamteam.skynet.Models.Device import gdl.dreamteam.skynet.Models.Fan import gdl.dreamteam.skynet.Models.Zone import org.junit.Test import org.junit.Assert.* import org.junit.Before import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.RuntimeEnvironment import org.robolectric.annotation.Config import java.util.* /** * Created by christopher on 31/08/17. */ @RunWith(RobolectricTestRunner::class) @Config(constants = BuildConfig::class) class SQLRepositoryTest { private lateinit var zone: Zone private lateinit var repo: IDataRepository @Before fun setup() { repo = SQLRepository(RuntimeEnvironment.application) zone = Zone( UUID.randomUUID(), "room1", arrayOf(Client( UUID.randomUUID(), "room1", "aosiherwela", arrayOf(Device( UUID.randomUUID(), "", Fan(25.2f, 0.45f, 1) )) )) ) //(zone.clients[0].devices[0].data as Fan).status = true } @Test fun setZone() { val result = repo.addZone(zone).get() } @Test fun getZone() { setZone() val repoZone: Zone? = repo.getZone("room1").get() assertNotNull(repoZone) assertEquals(zone, repoZone) } @Test fun deleteZone() { setZone() repo.deleteZone("room1").get() val repoZone: Zone? = repo.getZone("room1").get() assertNull(repoZone) } @Test fun updateZone() { setZone() zone.name = "room2" repo.updateZone("room1", zone).get() val zone: Zone? = repo.getZone("room2").get() assertNotNull(zone) assertEquals(this.zone, zone) } }
mit
9a7ab5eaeea1292ede8a995c0dc9bf74
23.02439
64
0.597765
3.969758
false
true
false
false
allotria/intellij-community
platform/lang-impl/src/com/intellij/workspaceModel/ide/impl/legacyBridge/library/LibraryModifiableModelBridgeImpl.kt
2
14197
// 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.workspaceModel.ide.impl.legacyBridge.library import com.intellij.openapi.Disposable import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.module.Module import com.intellij.openapi.roots.OrderRootType import com.intellij.openapi.roots.ProjectModelExternalSource import com.intellij.openapi.roots.RootProvider import com.intellij.openapi.roots.impl.libraries.LibraryEx import com.intellij.openapi.roots.impl.libraries.LibraryImpl import com.intellij.openapi.roots.libraries.* import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.containers.ContainerUtil import com.intellij.workspaceModel.ide.WorkspaceModel import com.intellij.workspaceModel.ide.getInstance import com.intellij.workspaceModel.ide.impl.IdeVirtualFileUrlManagerImpl import com.intellij.workspaceModel.ide.impl.legacyBridge.LegacyBridgeModifiableBase import com.intellij.workspaceModel.ide.impl.legacyBridge.library.LibraryBridgeImpl.Companion.toLibraryRootType import com.intellij.workspaceModel.ide.legacyBridge.LibraryModifiableModelBridge import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.bridgeEntities.* import com.intellij.workspaceModel.storage.url.VirtualFileUrl import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager import org.jdom.Element import org.jetbrains.jps.model.serialization.library.JpsLibraryTableSerializer internal class LibraryModifiableModelBridgeImpl( private val originalLibrary: LibraryBridgeImpl, private val originalLibrarySnapshot: LibraryStateSnapshot, diff: WorkspaceEntityStorageBuilder, private val targetBuilder: WorkspaceEntityStorageDiffBuilder?, cacheStorageResult: Boolean = true ) : LegacyBridgeModifiableBase(diff, cacheStorageResult), LibraryModifiableModelBridge, RootProvider { private val virtualFileManager: VirtualFileUrlManager = VirtualFileUrlManager.getInstance(originalLibrary.project) private var entityId = originalLibrarySnapshot.libraryEntity.persistentId() private var reloadKind = false private val currentLibraryValue = CachedValue { storage -> val newLibrary = LibraryStateSnapshot( libraryEntity = storage.resolve(entityId) ?: error("Can't resolve library via $entityId"), storage = storage, libraryTable = originalLibrarySnapshot.libraryTable, parentDisposable = originalLibrary ) newLibrary } private val currentLibrary: LibraryStateSnapshot get() = entityStorageOnDiff.cachedValue(currentLibraryValue) override fun getFiles(rootType: OrderRootType): Array<VirtualFile> = currentLibrary.getFiles(rootType) override fun getKind(): PersistentLibraryKind<*>? = currentLibrary.kind override fun getUrls(rootType: OrderRootType): Array<String> = currentLibrary.getUrls(rootType) override fun getName(): String? = currentLibrary.name override fun getPresentableName(): String = LibraryImpl.getPresentableName(this) override fun getProperties(): LibraryProperties<*>? = currentLibrary.properties override fun getExcludedRootUrls(): Array<String> = currentLibrary.excludedRootUrls override fun isJarDirectory(url: String): Boolean = currentLibrary.isJarDirectory(url) override fun isJarDirectory(url: String, rootType: OrderRootType): Boolean = currentLibrary.isJarDirectory(url, rootType) override fun setName(name: String) { assertModelIsLive() val entity = currentLibrary.libraryEntity if (entity.name == name) return if (currentLibrary.libraryTable.getLibraryByName(name) != null) { error("Library named $name already exists") } entityId = entity.persistentId().copy(name = name) diff.modifyEntity(ModifiableLibraryEntity::class.java, entity) { this.name = name } if (assertChangesApplied && currentLibrary.name != name) { error("setName: expected library name ${name}, but got ${currentLibrary.name}. Original name: ${originalLibrarySnapshot.name}") } } override fun commit() { assertModelIsLive() modelIsCommittedOrDisposed = true if (reloadKind) { originalLibrary.cleanCachedValue() } if (isChanged) { if (targetBuilder != null) { targetBuilder.addDiff(diff) } else { WorkspaceModel.getInstance(originalLibrary.project).updateProjectModel { it.addDiff(diff) } } originalLibrary.entityId = entityId originalLibrary.fireRootSetChanged() } } override fun prepareForCommit() { assertModelIsLive() modelIsCommittedOrDisposed = true if (reloadKind) originalLibrary.cleanCachedValue() if (isChanged) originalLibrary.entityId = entityId } private fun update(updater: ModifiableLibraryEntity.() -> Unit) { diff.modifyEntity(ModifiableLibraryEntity::class.java, currentLibrary.libraryEntity, updater) } private fun updateProperties(updater: ModifiableLibraryPropertiesEntity.() -> Unit) { val entity = currentLibrary.libraryEntity val referrers = entity.referrers(LibraryPropertiesEntity::library).toList() if (referrers.isEmpty()) { diff.addEntity(ModifiableLibraryPropertiesEntity::class.java, entity.entitySource) { library = entity updater() } } else { diff.modifyEntity(ModifiableLibraryPropertiesEntity::class.java, referrers.first(), updater) referrers.drop(1).forEach { diff.removeEntity(it) } } } override fun isChanged(): Boolean { if (!originalLibrarySnapshot.libraryEntity.hasEqualProperties(currentLibrary.libraryEntity)) return true val p1 = originalLibrarySnapshot.libraryEntity.getCustomProperties() val p2 = currentLibrary.libraryEntity.getCustomProperties() return !(p1 == null && p2 == null || p1 != null && p2 != null && p1.hasEqualProperties(p2)) } override fun addJarDirectory(url: String, recursive: Boolean) = addJarDirectory(url, recursive, OrderRootType.CLASSES) override fun addJarDirectory(url: String, recursive: Boolean, rootType: OrderRootType) { assertModelIsLive() val rootTypeId = rootType.toLibraryRootType() val virtualFileUrl = virtualFileManager.fromUrl(url) val inclusionOptions = if (recursive) LibraryRoot.InclusionOptions.ARCHIVES_UNDER_ROOT_RECURSIVELY else LibraryRoot.InclusionOptions.ARCHIVES_UNDER_ROOT update { roots = roots + listOf(LibraryRoot(virtualFileUrl, rootTypeId, inclusionOptions)) } if (assertChangesApplied && !currentLibrary.isJarDirectory(virtualFileUrl.url, rootType)) { error("addJarDirectory: expected jarDirectory exists for url '${virtualFileUrl.url}'") } } override fun addJarDirectory(file: VirtualFile, recursive: Boolean) = addJarDirectory(file.url, recursive) override fun addJarDirectory(file: VirtualFile, recursive: Boolean, rootType: OrderRootType) = addJarDirectory(file.url, recursive, rootType) override fun moveRootUp(url: String, rootType: OrderRootType) { assertModelIsLive() val virtualFileUrl = virtualFileManager.fromUrl(url) update { val index = roots.indexOfFirst { it.url == virtualFileUrl } if (index <= 0) return@update val prevRootIndex = roots.subList(0, index).indexOfLast { it.type.name == rootType.name() } if (prevRootIndex < 0) return@update val mutable = roots.toMutableList() ContainerUtil.swapElements(mutable, prevRootIndex, index) roots = mutable.toList() } } override fun moveRootDown(url: String, rootType: OrderRootType) { assertModelIsLive() val virtualFileUrl = virtualFileManager.fromUrl(url) update { val index = roots.indexOfFirst { it.url == virtualFileUrl } if (index < 0 || index + 1 >= roots.size) return@update val nextRootOffset = roots.subList(index + 1, roots.size).indexOfFirst { it.type.name == rootType.name() } if (nextRootOffset < 0) return@update val mutable = roots.toMutableList() ContainerUtil.swapElements(mutable, index + nextRootOffset + 1, index) roots = mutable.toList() } } override fun isValid(url: String, rootType: OrderRootType): Boolean = currentLibrary.isValid(url, rootType) override fun hasSameContent(library: Library): Boolean { if (this === library) return true if (library !is LibraryBridgeImpl) return false if (name != library.name) return false if (kind != library.kind) return false if (properties != library.properties) return false if (currentLibrary.libraryEntity.roots != library.librarySnapshot.libraryEntity.roots) return false if (!excludedRoots.contentEquals(library.excludedRoots)) return false return true } override fun addExcludedRoot(url: String) { assertModelIsLive() val virtualFileUrl = virtualFileManager.fromUrl(url) update { if (!excludedRoots.contains(virtualFileUrl)) { excludedRoots = excludedRoots + listOf(virtualFileUrl) } } if (assertChangesApplied && !currentLibrary.excludedRootUrls.contains(virtualFileUrl.url)) { error("addExcludedRoot: expected excluded urls contain url '${virtualFileUrl.url}'") } } override fun addRoot(url: String, rootType: OrderRootType) { assertModelIsLive() val virtualFileUrl = virtualFileManager.fromUrl(url) val root = LibraryRoot( url = virtualFileUrl, type = rootType.toLibraryRootType() ) update { roots = roots + root } if (assertChangesApplied && !currentLibrary.getUrls(rootType).contains(virtualFileUrl.url)) { error("addRoot: expected urls for root type '${rootType.name()}' contain url '${virtualFileUrl.url}'") } } override fun addRoot(file: VirtualFile, rootType: OrderRootType) = addRoot(file.url, rootType) override fun setProperties(properties: LibraryProperties<*>?) { assertModelIsLive() if (currentLibrary.properties == properties) return val kind = currentLibrary.kind if (kind == null) { if (properties != null && properties !is DummyLibraryProperties) { LOG.error("Setting properties with null kind is unsupported") } return } updateProperties { libraryType = kind.kindId propertiesXmlTag = serializeComponentAsString(JpsLibraryTableSerializer.PROPERTIES_TAG, properties) } if (assertChangesApplied && currentLibrary.properties != properties) { error("setProperties: properties are not equal after changing") } } override fun setKind(type: PersistentLibraryKind<*>) { assertModelIsLive() if (kind == type) return updateProperties { libraryType = type.kindId } if (assertChangesApplied && currentLibrary.kind?.kindId != type.kindId) { error("setKind: expected kindId ${type.kindId}, but got ${currentLibrary.kind?.kindId}. Original kind: ${originalLibrarySnapshot.kind?.kindId}") } } override fun forgetKind() { reloadKind = true } override fun restoreKind() { reloadKind = true } private fun isUnderRoots(url: VirtualFileUrl, roots: Collection<LibraryRoot>): Boolean { return VfsUtilCore.isUnder(url.url, roots.map { it.url.url }) } override fun removeRoot(url: String, rootType: OrderRootType): Boolean { assertModelIsLive() val virtualFileUrl = virtualFileManager.fromUrl(url) if (!currentLibrary.getUrls(rootType).contains(virtualFileUrl.url)) return false update { roots = roots.filterNot { it.url == virtualFileUrl && it.type.name == rootType.name() } excludedRoots = excludedRoots.filter { isUnderRoots(it, roots) } } if (assertChangesApplied && currentLibrary.getUrls(rootType).contains(virtualFileUrl.url)) { error("removeRoot: removed url '${virtualFileUrl.url}' type '${rootType.name()}' still exists after removing") } return true } override fun removeExcludedRoot(url: String): Boolean { assertModelIsLive() val virtualFileUrl = virtualFileManager.fromUrl(url) if (!currentLibrary.excludedRootUrls.contains(virtualFileUrl.url)) return false update { excludedRoots = excludedRoots.filter { it != virtualFileUrl } } if (assertChangesApplied && currentLibrary.excludedRootUrls.contains(virtualFileUrl.url)) { error("removeRoot: removed excluded url '${virtualFileUrl.url}' still exists after removing") } return true } private var disposed = false override fun dispose() { // No assertions here since it is ok to call dispose twice or more modelIsCommittedOrDisposed = true disposed = true } override fun isDisposed(): Boolean = disposed override fun toString(): String { return "Library '$name', roots: ${currentLibrary.libraryEntity.roots}" } override fun getInvalidRootUrls(type: OrderRootType): List<String> = currentLibrary.getInvalidRootUrls(type) override fun getExcludedRoots(): Array<VirtualFile> = currentLibrary.excludedRoots override fun getModule(): Module? = currentLibrary.module override fun addRootSetChangedListener(listener: RootProvider.RootSetChangedListener) = throw UnsupportedOperationException() override fun addRootSetChangedListener(listener: RootProvider.RootSetChangedListener, parentDisposable: Disposable) = throw UnsupportedOperationException() override fun removeRootSetChangedListener(listener: RootProvider.RootSetChangedListener) = throw UnsupportedOperationException() override fun getExternalSource(): ProjectModelExternalSource? = originalLibrarySnapshot.externalSource override fun getModifiableModel(): LibraryEx.ModifiableModelEx = throw UnsupportedOperationException() override fun getSource(): Library? = originalLibrary override fun getTable(): LibraryTable = originalLibrarySnapshot.libraryTable override fun getRootProvider(): RootProvider = this override fun readExternal(element: Element?) = throw UnsupportedOperationException() override fun writeExternal(element: Element?) = throw UnsupportedOperationException() companion object { private val LOG = logger<LibraryModifiableModelBridgeImpl>() } }
apache-2.0
88cd29ddbd2b233343cfb583b7e8c630
36.757979
157
0.747411
5.171949
false
false
false
false
zdary/intellij-community
plugins/completion-ml-ranking/src/com/intellij/completion/ml/actions/MLCompletionFeaturesUtil.kt
2
2996
// 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.completion.ml.actions import com.google.gson.Gson import com.google.gson.GsonBuilder import com.intellij.codeInsight.lookup.LookupElement import com.intellij.codeInsight.lookup.LookupManager import com.intellij.codeInsight.lookup.impl.LookupImpl import com.intellij.completion.ml.util.idString import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.ide.CopyPasteManager import com.intellij.completion.ml.storage.LookupStorage import java.awt.datatransfer.StringSelection object MLCompletionFeaturesUtil { fun getCommonFeatures(lookup: LookupImpl): CommonFeatures { val storage = LookupStorage.get(lookup) ?: return CommonFeatures() return CommonFeatures(storage.userFactors, storage.sessionFactors.getLastUsedCommonFactors(), storage.contextFactors) } fun getElementFeatures(lookup: LookupImpl, element: LookupElement): ElementFeatures { val id = element.idString() val storage = LookupStorage.get(lookup) ?: return ElementFeatures(id) val features = storage.getItemStorage(id).getLastUsedFactors() ?: return ElementFeatures(id) return ElementFeatures(id, features.mapValues { it.value.toString() }) } data class CommonFeatures(val user: Map<String, String> = emptyMap(), val session: Map<String, String> = emptyMap(), val context: Map<String, String> = emptyMap()) data class ElementFeatures(val id: String, val features: Map<String, String> = emptyMap()) class CopyFeaturesToClipboard : AnAction() { companion object { private val LOG: Logger = Logger.getInstance(CopyFeaturesToClipboard::class.java) private val gson: Gson = GsonBuilder().setPrettyPrinting().create() } override fun update(e: AnActionEvent) { val editor = e.getData(CommonDataKeys.EDITOR) e.presentation.isEnabled = editor != null && LookupManager.getActiveLookup(editor) != null } override fun actionPerformed(e: AnActionEvent) { val editor = e.getData(CommonDataKeys.EDITOR) val lookup = LookupManager.getActiveLookup(editor) as? LookupImpl ?: return val result = mapOf( "common" to getCommonFeatures(lookup), "elements" to lookup.items.associate { val elementFeatures = getElementFeatures(lookup, it) elementFeatures.id to elementFeatures.features } ) val json = gson.toJson(result) try { CopyPasteManager.getInstance().setContents(StringSelection(json)) } catch (e: Exception) { LOG.debug("Error on copying features to clipboard: $json") throw e } } } }
apache-2.0
c4a0d64795c2b9142e7b6b212a26f4d4
41.211268
140
0.718959
4.630603
false
false
false
false
zdary/intellij-community
plugins/ide-features-trainer/src/training/util/Utils.kt
1
7550
// 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 training.util import com.google.common.util.concurrent.ThreadFactoryBuilder import com.intellij.DynamicBundle import com.intellij.icons.AllIcons import com.intellij.ide.DataManager import com.intellij.ide.plugins.PluginManagerCore import com.intellij.lang.Language import com.intellij.openapi.actionSystem.ActionPlaces import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.ex.ActionUtil.performActionDumbAwareWithCallbacks import com.intellij.openapi.application.ApplicationNamesInfo import com.intellij.openapi.application.invokeLater import com.intellij.openapi.project.Project import com.intellij.openapi.ui.popup.Balloon import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.wm.ToolWindow import com.intellij.openapi.wm.ToolWindowManager import com.intellij.ui.components.labels.LinkLabel import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import org.jetbrains.annotations.Nls import training.lang.LangManager import training.lang.LangSupport import training.learn.CourseManager import training.learn.LearnBundle import training.learn.course.Lesson import training.learn.lesson.LessonManager import training.learn.lesson.LessonStateManager import training.ui.LearnToolWindowFactory import training.ui.LearningUiManager import java.awt.BorderLayout import java.awt.Component import java.awt.Desktop import java.awt.Dimension import java.net.URI import java.util.* import java.util.concurrent.ExecutorService import java.util.concurrent.Executors import javax.swing.* fun createNamedSingleThreadExecutor(name: String): ExecutorService = Executors.newSingleThreadExecutor(ThreadFactoryBuilder().setNameFormat(name).build()) private val excludedLanguages: Map<String, Array<String>> = mapOf("AppCode" to arrayOf("JavaScript")) //IDE name to language id fun courseCanBeUsed(languageId: String): Boolean { val excludedCourses = excludedLanguages[ApplicationNamesInfo.getInstance().productName] return excludedCourses == null || !excludedCourses.contains(languageId) } fun findLanguageByID(id: String): Language? { val effectiveId = if (id.toLowerCase() == "cpp") { "ObjectiveC" } else { id } return Language.findLanguageByID(effectiveId) } fun createBalloon(@Nls text: String): Balloon = createBalloon(text, 3000) fun createBalloon(@Nls text: String, delay: Long): Balloon = JBPopupFactory.getInstance() .createHtmlTextBalloonBuilder(text, null, UIUtil.getToolTipBackground(), null) .setHideOnClickOutside(true) .setCloseButtonEnabled(true) .setHideOnKeyOutside(true) .setAnimationCycle(0) .setFadeoutTime(delay) .createBalloon() internal const val trainerPluginConfigName: String = "ide-features-trainer.xml" internal val featureTrainerVersion: String by lazy { val featureTrainerPluginId = PluginManagerCore.getPluginByClassName(CourseManager::class.java.name) PluginManagerCore.getPlugin(featureTrainerPluginId)?.version ?: "UNKNOWN" } val adaptToNotNativeLocalization: Boolean get() = Registry.`is`("ift.adapt.to.not.native.localization") || DynamicBundle.getLocale() != Locale.ENGLISH internal fun clearTrainingProgress() { LessonManager.instance.stopLesson() LessonStateManager.resetPassedStatus() for (toolWindow in LearnToolWindowFactory.learnWindowPerProject.values) { toolWindow.reinitViews() toolWindow.setModulesPanel() } LearningUiManager.activeToolWindow = null } internal fun resetPrimaryLanguage(activeLangSupport: LangSupport): Boolean { val old = LangManager.getInstance().getLangSupport() if (activeLangSupport != old) { LessonManager.instance.stopLesson() LangManager.getInstance().updateLangSupport(activeLangSupport) LearningUiManager.activeToolWindow?.setModulesPanel() return true } return false } fun findLanguageSupport(project: Project): LangSupport? { val langSupport = LangManager.getInstance().getLangSupport() ?: return null if (isLearningProject(project, langSupport)) { return langSupport } return null } fun isLearningProject(project: Project, langSupport: LangSupport): Boolean { return FileUtil.pathsEqual(project.basePath, LangManager.getInstance().getLearningProjectPath(langSupport)) } fun getFeedbackLink(langSupport: LangSupport, ownRegistry: Boolean): String? { val suffix = langSupport.primaryLanguage.toLowerCase() val needToShow = Registry.`is`("ift.show.feedback.link" + if (ownRegistry) ".$suffix" else "", false) return if (needToShow) "https://surveys.jetbrains.com/s3/features-trainer-feedback-$suffix" else null } val switchOnExperimentalLessons: Boolean get() = Registry.`is`("ift.experimental.lessons", false) fun invokeActionForFocusContext(action: AnAction) { DataManager.getInstance().dataContextFromFocusAsync.onSuccess { dataContext -> invokeLater { val event = AnActionEvent.createFromAnAction(action, null, ActionPlaces.LEARN_TOOLWINDOW, dataContext) performActionDumbAwareWithCallbacks(action, event) } } } fun openLinkInBrowser(link: String) { val desktop = if (Desktop.isDesktopSupported()) Desktop.getDesktop() else null if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) { desktop.browse(URI(link)) } } fun LinkLabel<Any>.wrapWithUrlPanel(): JPanel { val jPanel = JPanel() jPanel.isOpaque = false jPanel.layout = BoxLayout(jPanel, BoxLayout.LINE_AXIS) jPanel.add(this, BorderLayout.CENTER) jPanel.add(JLabel(AllIcons.Ide.External_link_arrow), BorderLayout.EAST) jPanel.maximumSize = jPanel.preferredSize jPanel.alignmentX = JPanel.LEFT_ALIGNMENT return jPanel } fun rigid(width: Int, height: Int): Component { return scaledRigid(JBUI.scale(width), JBUI.scale(height)) } fun scaledRigid(width: Int, height: Int): Component { return (Box.createRigidArea(Dimension(width, height)) as JComponent).apply { alignmentX = Component.LEFT_ALIGNMENT alignmentY = Component.TOP_ALIGNMENT } } fun lessonOpenedInProject(project: Project?): Lesson? { return if (LearnToolWindowFactory.learnWindowPerProject[project] != null) LessonManager.instance.currentLesson else null } fun getNextLessonForCurrent(): Lesson? { val lesson = LessonManager.instance.currentLesson ?: return null val lessonsForModules = CourseManager.instance.lessonsForModules val index = lessonsForModules.indexOf(lesson) if (index < 0 || index >= lessonsForModules.size - 1) return null return lessonsForModules[index + 1] } fun getPreviousLessonForCurrent(): Lesson? { val lesson = LessonManager.instance.currentLesson ?: return null val lessonsForModules = CourseManager.instance.lessonsForModules val index = lessonsForModules.indexOf(lesson) if (index <= 0) return null return lessonsForModules[index - 1] } @Nls fun learningProgressString(lessons: List<Lesson>): String { val total = lessons.size var done = 0 for (lesson in lessons) { if (lesson.passed) done++ } return if (done == total) LearnBundle.message("learn.module.progress.completed") else LearnBundle.message("learn.module.progress", done, total) } fun learningToolWindow(project: Project): ToolWindow? { return ToolWindowManager.getInstance(project).getToolWindow(LearnToolWindowFactory.LEARN_TOOL_WINDOW) }
apache-2.0
2be10d9421fb12140c15cc569148aa64
36.197044
140
0.789669
4.289773
false
false
false
false
agoda-com/Kakao
kakao/src/main/kotlin/com/agoda/kakao/common/builders/ViewBuilder.kt
1
10997
@file:Suppress("unused") package com.agoda.kakao.common.builders import android.graphics.Bitmap import android.graphics.drawable.Drawable import android.view.View import androidx.annotation.ColorRes import androidx.annotation.DrawableRes import androidx.annotation.StringRes import androidx.test.espresso.Espresso import androidx.test.espresso.matcher.ViewMatchers import com.agoda.kakao.common.KakaoDslMarker import com.agoda.kakao.common.matchers.AnyTextMatcher import com.agoda.kakao.common.matchers.BackgroundColorMatcher import com.agoda.kakao.common.matchers.DrawableMatcher import com.agoda.kakao.common.matchers.FirstViewMatcher import com.agoda.kakao.common.matchers.IndexMatcher import com.agoda.kakao.common.matchers.RatingBarMatcher import com.agoda.kakao.delegate.ViewInteractionDelegate import org.hamcrest.CoreMatchers import org.hamcrest.Matcher import org.hamcrest.Matchers import org.hamcrest.core.AllOf /** * Class for building view matchers and interactions * * This class helps to build matches for views and get their interactions. * Please note that any function invoking will add specific matcher to the list * and after that all of them will be combined with help of AllOf.allOf() * * @see AllOf.allOf() */ @KakaoDslMarker class ViewBuilder { private val viewMatchers = arrayListOf<Matcher<View>>() /** * Matches only view at given [index], if there are multiple views that matches * * @param index Index of the view to match * @param function [ViewBuilder] that will result in matcher */ fun withIndex(index: Int, function: ViewBuilder.() -> Unit) { viewMatchers.add(IndexMatcher(ViewBuilder().apply(function).getViewMatcher(), index)) } /** * Matches only root views * * @see ViewMatchers.isRoot */ fun isRoot() { viewMatchers.add(ViewMatchers.isRoot()) } /** * Matches the view with given resource id * * @param id Resource id to match */ fun withId(id: Int) { viewMatchers.add(ViewMatchers.withId(id)) } /** * Matches the view with given tag assigned * * @param tag Tag object to match */ fun withTag(tag: Any) { viewMatchers.add(ViewMatchers.withTagValue(Matchers.equalTo(tag))) } /** * Matches the view if it is in ENABLED state */ fun isEnabled() { viewMatchers.add(ViewMatchers.isEnabled()) } /** * Matches the view if it is not in ENABLED state */ fun isDisabled() { viewMatchers.add(CoreMatchers.not(ViewMatchers.isEnabled())) } /** * Matches the view with given text * * @param text Text to match */ fun withText(text: String) { viewMatchers.add(ViewMatchers.withText(text)) } /** * Matches the view with given text * * @param textId String resource to match */ fun withText(@StringRes textId: Int) { viewMatchers.add(ViewMatchers.withText(textId)) } /** * Matches the view with given text matcher * * @param matcher Text matcher to add */ fun withText(matcher: Matcher<String>) { viewMatchers.add(ViewMatchers.withText(matcher)) } /** * Matches if the view does not have a given text * * @param text Text to be matched */ fun withoutText(text: String) { viewMatchers.add(CoreMatchers.not(ViewMatchers.withText(text))) } /** * Matches if the view does not have a given text * * @param resId String resource to be matched */ fun withoutText(@StringRes resId: Int) { viewMatchers.add(CoreMatchers.not(ViewMatchers.withText(resId))) } /** * Matches the view which contains any text */ fun withAnyText() { viewMatchers.add(AnyTextMatcher()) } /** * Matches the view which contain given text * * @param text Text to search */ fun containsText(text: String) { viewMatchers.add(ViewMatchers.withText(Matchers.containsString(text))) } /** * Matches the view with given resource name * * @param name Resource name to match */ fun withResourceName(name: String) { viewMatchers.add(ViewMatchers.withResourceName(name)) } /** * Matches the view by resource name with given matcher * * @param matcher Matcher for resource name */ fun withResourceName(matcher: Matcher<String>) { viewMatchers.add(ViewMatchers.withResourceName(matcher)) } /** * Matches the view with given content description * * @param description Content description to match */ fun withContentDescription(description: String) { viewMatchers.add(ViewMatchers.withContentDescription(description)) } /** * Matches the view with given content description * * @param resourceId Resource id of content description to match */ fun withContentDescription(@StringRes resourceId: Int) { viewMatchers.add(ViewMatchers.withContentDescription(resourceId)) } /** * Matches the view which has parent with given matcher * * @param function ViewBuilder which will result in parent matcher */ fun withParent(function: ViewBuilder.() -> Unit) { viewMatchers.add(ViewMatchers.withParent(ViewBuilder().apply(function).getViewMatcher())) } /** * Matches the view with given drawable * * @param resId Drawable resource to match * @param toBitmap Lambda with custom Drawable -> Bitmap converter (default is null) */ fun withDrawable(@DrawableRes resId: Int, toBitmap: ((drawable: Drawable) -> Bitmap)? = null) { viewMatchers.add(DrawableMatcher(resId = resId, toBitmap = toBitmap)) } /** * Matches the view which is RatingBar with given value * * @param rating value of RatingBar */ fun withRating(rating: Float) { viewMatchers.add(RatingBarMatcher(rating)) } /** * Matches the view with given drawable * * @param drawable Drawable to match * @param toBitmap Lambda with custom Drawable -> Bitmap converter (default is null) */ fun withDrawable(drawable: Drawable, toBitmap: ((drawable: Drawable) -> Bitmap)? = null) { viewMatchers.add(DrawableMatcher(drawable = drawable, toBitmap = toBitmap)) } /** * Matches the view with given background color * * @param resId Color to match */ fun withBackgroundColor(@ColorRes resId: Int) { viewMatchers.add(BackgroundColorMatcher(resId = resId)) } /** * Matches the view with given background color code * * @param colorCode Color code to match */ fun withBackgroundColor(colorCode: String) { viewMatchers.add(BackgroundColorMatcher(colorCode = colorCode)) } /** * Matches the first view */ fun isFirst() { viewMatchers.add(FirstViewMatcher()) } /** * Matches the view with VISIBLE visibility */ fun isVisible() { viewMatchers.add(ViewMatchers.withEffectiveVisibility(ViewMatchers.Visibility.VISIBLE)) } /** * Matches the view with INVISIBLE visibility */ fun isInvisible() { viewMatchers.add(ViewMatchers.withEffectiveVisibility(ViewMatchers.Visibility.INVISIBLE)) } /** * Matches the view with GONE visibility */ fun isGone() { viewMatchers.add(ViewMatchers.withEffectiveVisibility(ViewMatchers.Visibility.GONE)) } /** * Matches the view that is displayed */ fun isDisplayed() { viewMatchers.add(ViewMatchers.isDisplayed()) } /** * Matches the view that is not displayed */ fun isNotDisplayed() { viewMatchers.add(Matchers.not(ViewMatchers.isDisplayed())) } /** * Matches the view that is completely displayed */ fun isCompletelyDisplayed() { viewMatchers.add(ViewMatchers.isCompletelyDisplayed()) } /** * Matches the view that is not completely displayed */ fun isNotCompletelyDisplayed() { viewMatchers.add(Matchers.not(ViewMatchers.isCompletelyDisplayed())) } /** * Matches the view that is clickable */ fun isClickable() { viewMatchers.add(ViewMatchers.isClickable()) } /** * Matches the view that is not clickable */ fun isNotClickable() { viewMatchers.add(Matchers.not(ViewMatchers.isClickable())) } /** * Matches the view which is descendant of given matcher * * @param function ViewBuilder which will result in parent matcher */ fun isDescendantOfA(function: ViewBuilder.() -> Unit) { viewMatchers.add(ViewMatchers.isDescendantOfA(ViewBuilder().apply(function).getViewMatcher())) } /** * Matches the view which has descendant of given matcher * * @param function ViewBuilder which will result in descendant matcher */ fun withDescendant(function: ViewBuilder.() -> Unit) { viewMatchers.add(ViewMatchers.hasDescendant(ViewBuilder().apply(function).getViewMatcher())) } /** * Matches the view which has sibling of given matcher * * @param function ViewBuilder which will result in sibling matcher */ fun withSibling(function: ViewBuilder.() -> Unit) { viewMatchers.add(ViewMatchers.hasSibling(ViewBuilder().apply(function).getViewMatcher())) } /** * Matches the view which class name matches given matcher * * @param matcher Matcher of class name */ fun withClassName(matcher: Matcher<String>) { viewMatchers.add(ViewMatchers.withClassName(matcher)) } /** * Matches the view by class instance * * @param clazz Class to match */ fun isInstanceOf(clazz: Class<*>) { viewMatchers.add(Matchers.instanceOf(clazz)) } /** * Matches views based on instance or subclass of the provided class. * * @param clazz Class to match */ fun isAssignableFrom(clazz: Class<out View>) { viewMatchers.add(ViewMatchers.isAssignableFrom(clazz)) } /** * Matches the view with given custom matcher * * @param matcher Matcher that needs to be added */ fun withMatcher(matcher: Matcher<View>) { viewMatchers.add(matcher) } /** * Returns view interaction delegate based on all given matchers * * @return ViewInteractionDelegate */ fun getViewInteractionDelegate(): ViewInteractionDelegate { check(viewMatchers.isNotEmpty()) { "No matchers inside InteractionBuilder" } return ViewInteractionDelegate(Espresso.onView(AllOf.allOf(viewMatchers))) } /** * Returns combined view matcher with AllOf.allOf() * * @return Matcher<View> */ fun getViewMatcher(): Matcher<View> = AllOf.allOf(viewMatchers) }
apache-2.0
a02e6c1665b5b441b4dddab200e48454
26.982188
102
0.655451
4.636172
false
false
false
false
zdary/intellij-community
platform/platform-impl/src/com/intellij/openapi/project/impl/ProjectExImpl.kt
1
11981
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.project.impl import com.intellij.diagnostic.ActivityCategory import com.intellij.diagnostic.StartUpMeasurer import com.intellij.diagnostic.StartUpMeasurer.startActivity import com.intellij.ide.plugins.PluginManagerCore import com.intellij.ide.startup.StartupManagerEx import com.intellij.idea.preloadServices import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ModalityState import com.intellij.openapi.application.impl.LaterInvocator import com.intellij.openapi.components.StorageScheme import com.intellij.openapi.components.impl.stores.IProjectStore import com.intellij.openapi.components.serviceIfCreated import com.intellij.openapi.extensions.impl.ExtensionsAreaImpl import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.startup.StartupManager import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.Key import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.wm.WindowManager import com.intellij.openapi.wm.impl.FrameTitleBuilder import com.intellij.project.ProjectStoreOwner import com.intellij.serviceContainer.AlreadyDisposedException import com.intellij.serviceContainer.ComponentManagerImpl import com.intellij.util.ExceptionUtil import com.intellij.util.TimedReference import com.intellij.util.concurrency.SynchronizedClearableLazy import com.intellij.util.io.systemIndependentPath import com.intellij.util.messages.impl.MessageBusEx import org.jetbrains.annotations.ApiStatus import org.jetbrains.annotations.TestOnly import java.nio.file.Path import java.util.concurrent.atomic.AtomicReference private val DISPOSE_EARLY_DISPOSABLE_TRACE = Key.create<String>("ProjectImpl.DISPOSE_EARLY_DISPOSABLE_TRACE") @ApiStatus.Internal open class ProjectExImpl(filePath: Path, projectName: String?) : ProjectImpl(ApplicationManager.getApplication() as ComponentManagerImpl), ProjectStoreOwner { companion object { @ApiStatus.Internal val RUN_START_UP_ACTIVITIES = Key.create<Boolean>("RUN_START_UP_ACTIVITIES") } private val earlyDisposable = AtomicReference(Disposer.newDisposable()) @Volatile var isTemporarilyDisposed = false private set private val isLight: Boolean private var cachedName: String? = null private var componentStoreValue = SynchronizedClearableLazy { ApplicationManager.getApplication().getService(ProjectStoreFactory::class.java).createStore(this) } init { @Suppress("LeakingThis") putUserData(CREATION_TIME, System.nanoTime()) @Suppress("LeakingThis") registerServiceInstance(Project::class.java, this, fakeCorePluginDescriptor) cachedName = projectName // light project may be changed later during test, so we need to remember its initial state //noinspection TestOnlyProblems // light project may be changed later during test, so we need to remember its initial state isLight = ApplicationManager.getApplication().isUnitTestMode && filePath.toString().contains(LIGHT_PROJECT_NAME) } override fun isInitialized(): Boolean { val containerState = containerState.get() if ((containerState < ContainerState.COMPONENT_CREATED || containerState >= ContainerState.DISPOSE_IN_PROGRESS) || isTemporarilyDisposed || !isOpen) { return false } else if (ApplicationManager.getApplication().isUnitTestMode && getUserData(RUN_START_UP_ACTIVITIES) == false) { // if test asks to not run RUN_START_UP_ACTIVITIES, it means "ignore start-up activities", but project considered as initialized return true } else { return (serviceIfCreated<StartupManager>() as StartupManagerEx?)?.startupActivityPassed() == true } } override fun getName(): String { var result = cachedName if (result == null) { // ProjectPathMacroManager adds macro PROJECT_NAME_MACRO_NAME and so, project name is required on each load of configuration file. // So, anyway name is computed very early. result = componentStore.projectName cachedName = result } return result } override fun setProjectName(value: String) { if (cachedName == value) { return } cachedName = value if (!ApplicationManager.getApplication().isUnitTestMode) { StartupManager.getInstance(this).runAfterOpened { ApplicationManager.getApplication().invokeLater(Runnable { val frame = WindowManager.getInstance().getFrame(this) ?: return@Runnable val title = FrameTitleBuilder.getInstance().getProjectTitle(this) ?: return@Runnable frame.title = title }, ModalityState.NON_MODAL, disposed) } } } final override var componentStore: IProjectStore get() = componentStoreValue.value set(value) { if (componentStoreValue.isInitialized()) { throw java.lang.IllegalStateException("store is already initialized") } componentStoreValue.value = value } final override fun getStateStore() = componentStore final override fun getProjectFilePath() = componentStore.projectFilePath.systemIndependentPath final override fun getProjectFile(): VirtualFile? { return LocalFileSystem.getInstance().findFileByNioFile(componentStore.projectFilePath) } final override fun getBaseDir(): VirtualFile? { return LocalFileSystem.getInstance().findFileByNioFile(componentStore.projectBasePath) } final override fun getBasePath() = componentStore.projectBasePath.systemIndependentPath final override fun getPresentableUrl(): String { val store = componentStore return if (store.storageScheme == StorageScheme.DIRECTORY_BASED) store.projectBasePath.systemIndependentPath else store.projectFilePath.systemIndependentPath } override fun getLocationHash(): String { val store = componentStore val prefix: String val path: Path if (store.storageScheme == StorageScheme.DIRECTORY_BASED) { path = store.projectBasePath prefix = "" } else { path = store.projectFilePath prefix = getName() } return "$prefix${Integer.toHexString(path.systemIndependentPath.hashCode())}" } final override fun getWorkspaceFile(): VirtualFile? { return LocalFileSystem.getInstance().findFileByNioFile(componentStore.workspacePath) } final override fun isLight() = isLight @ApiStatus.Internal final override fun activityNamePrefix() = "project " override fun init(preloadServices: Boolean, indicator: ProgressIndicator?) { val app = ApplicationManager.getApplication() // for light project preload only services that are essential // (await means "project component loading activity is completed only when all such services are completed") val servicePreloadingFuture = if (preloadServices) { preloadServices(PluginManagerCore.getLoadedPlugins(null), container = this, activityPrefix = "project ", onlyIfAwait = isLight) } else { null } createComponents(indicator) servicePreloadingFuture?.join() var activity = if (StartUpMeasurer.isEnabled()) startActivity("projectComponentCreated event handling", ActivityCategory.DEFAULT) else null @Suppress("DEPRECATION") app.messageBus.syncPublisher(ProjectLifecycleListener.TOPIC).projectComponentsInitialized(this) activity = activity?.endAndStart("projectComponentCreated") runOnlyCorePluginExtensions((app.extensionArea as ExtensionsAreaImpl).getExtensionPoint<ProjectServiceContainerInitializedListener>( "com.intellij.projectServiceContainerInitializedListener")) { it.serviceCreated(this) } activity?.end() } @TestOnly fun setTemporarilyDisposed(value: Boolean) { if (isTemporarilyDisposed == value) { return } if (value && super.isDisposed()) { throw IllegalStateException("Project was already disposed, flag temporarilyDisposed cannot be set to `true`") } if (!value) { val newDisposable = Disposer.newDisposable() if (!earlyDisposable.compareAndSet(null, newDisposable)) { throw IllegalStateException("earlyDisposable must be null on second opening of light project") } } // Must be not only on temporarilyDisposed = true, but also on temporarilyDisposed = false, // because events fired for temporarilyDisposed project between project close and project open and it can lead to cache population. // Message bus implementation can be complicated to add owner.isDisposed check before getting subscribers, but as bus is a very important subsystem, // better to not add any non-production logic // light project is not disposed, so, subscriber cache contains handlers that will handle events for a temporarily disposed project, // so, we clear subscriber cache. `isDisposed` for project returns `true` if `temporarilyDisposed`, so, handler will be not added. (messageBus as MessageBusEx).clearAllSubscriberCache() isTemporarilyDisposed = value } @ApiStatus.Experimental @ApiStatus.Internal final override fun getEarlyDisposable(): Disposable { if (isDisposed) { throw AlreadyDisposedException("$this is disposed already") } return earlyDisposable.get() ?: throw createEarlyDisposableError("earlyDisposable is null for") } fun disposeEarlyDisposable() { if (LOG.isDebugEnabled || ApplicationManager.getApplication().isUnitTestMode) { LOG.debug("dispose early disposable: ${toString()}") } val disposable = earlyDisposable.getAndSet(null) ?: throw createEarlyDisposableError("earlyDisposable was already disposed") if (ApplicationManager.getApplication().isUnitTestMode) { putUserData(DISPOSE_EARLY_DISPOSABLE_TRACE, ExceptionUtil.currentStackTrace()) } Disposer.dispose(disposable) } private fun createEarlyDisposableError(error: String): RuntimeException { return IllegalStateException("$error for ${toString()}\n---begin of dispose trace--" + getUserData(DISPOSE_EARLY_DISPOSABLE_TRACE) + "}---end of dispose trace---\n") } final override fun isDisposed(): Boolean { return super.isDisposed() || isTemporarilyDisposed } @Synchronized final override fun dispose() { val app = ApplicationManager.getApplication() // dispose must be under write action app.assertWriteAccessAllowed() val projectManager = ProjectManager.getInstance() as ProjectManagerImpl // can call dispose only via com.intellij.ide.impl.ProjectUtil.closeAndDispose() if (projectManager.isProjectOpened(this)) { throw IllegalStateException( "Must call .dispose() for a closed project only. See ProjectManager.closeProject() or ProjectUtil.closeAndDispose().") } super.dispose() componentStoreValue.valueIfInitialized?.release() if (!app.isDisposed) { @Suppress("DEPRECATION") app.messageBus.syncPublisher(ProjectLifecycleListener.TOPIC).afterProjectClosed(this) } projectManager.updateTheOnlyProjectField() TimedReference.disposeTimed() LaterInvocator.purgeExpiredItems() } final override fun toString(): String { val store = componentStoreValue.valueIfInitialized val containerState = if (isTemporarilyDisposed) "disposed temporarily" else containerStateName val componentStore = if (store == null) "<not initialized>" else if (store.storageScheme == StorageScheme.DIRECTORY_BASED) store.projectBasePath.toString() else store.projectFilePath val disposedStr = if (isDisposed) " (disposed)" else "" return "Project(name=$cachedName, containerState=$containerState, componentStore=$componentStore)$disposedStr" } }
apache-2.0
d4c49506cec665a1b7c7342f26a94e84
40.317241
186
0.757115
5.091798
false
false
false
false
JuliusKunze/kotlin-native
tools/kotlin-native-gradle-plugin/src/main/kotlin/org/jetbrains/kotlin/gradle/plugin/tasks/KonanGenerateCMakeTask.kt
1
5605
/* * Copyright 2010-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.gradle.plugin.tasks import org.gradle.api.DefaultTask import org.gradle.api.file.FileCollection import org.gradle.api.tasks.TaskAction import org.jetbrains.kotlin.gradle.plugin.KonanInteropLibrary import org.jetbrains.kotlin.gradle.plugin.KonanLibrary import org.jetbrains.kotlin.gradle.plugin.KonanProgram import org.jetbrains.kotlin.gradle.plugin.konanArtifactsContainer import org.jetbrains.kotlin.konan.target.Family import org.jetbrains.kotlin.konan.target.TargetManager import java.io.File open class KonanGenerateCMakeTask : DefaultTask() { @Suppress("unused") @TaskAction fun generateCMake() { val interops = project.konanArtifactsContainer.toList().filterIsInstance<KonanInteropLibrary>() val libraries = project.konanArtifactsContainer.toList().filterIsInstance<KonanLibrary>() val programs = project.konanArtifactsContainer.toList().filterIsInstance<KonanProgram>() val cMakeLists = generateCMakeLists( project.name, interops, libraries, programs ) File(project.projectDir, "CMakeLists.txt") .writeText(cMakeLists) // This directory is filled out by the IDE File(project.projectDir, "KotlinCMakeModule") .mkdir() } private fun generateCMakeLists( projectName: String, interops: List<KonanInteropLibrary>, libraries: List<KonanLibrary>, programs: List<KonanProgram> ): String { val cMakeCurrentListDir = "$" + "{CMAKE_CURRENT_LIST_DIR}" return buildString { appendln(""" cmake_minimum_required(VERSION 3.8) set(CMAKE_MODULE_PATH $cMakeCurrentListDir/KotlinCMakeModule) project($projectName Kotlin) """.trimIndent()) appendln() for (interop in interops) { val task = interop[TargetManager.host] ?: continue appendln( Call("cinterop") .arg("NAME", interop.name) .arg("DEF_FILE", task.defFile.relativePath.toString().crossPlatformPath) .arg("COMPILER_OPTS", task.cMakeCompilerOpts) ) } for (library in libraries) { val task = library[TargetManager.host] ?: continue appendln( Call("konanc_library") .arg("NAME", library.name) .arg("SOURCES", task.cMakeSources) .arg("LIBRARIES", task.cMakeLibraries) .arg("LINKER_OPTS", task.cMakeLinkerOpts)) } for (program in programs) { val task = program[TargetManager.host] ?: continue appendln( Call("konanc_executable") .arg("NAME", program.name) .arg("SOURCES", task.cMakeSources) .arg("LIBRARIES", task.cMakeLibraries) .arg("LINKER_OPTS", task.cMakeLinkerOpts)) } } } private val File.relativePath get() = relativeTo(project.projectDir) private val String.crossPlatformPath get() = if (TargetManager.host.family == Family.WINDOWS) replace('\\', '/') else this private val FileCollection.asCMakeSourceList: List<String> get() = files.map { it.relativePath.toString().crossPlatformPath } private val KonanInteropTask.cMakeCompilerOpts: String get() = (compilerOpts + includeDirs.allHeadersDirs.map { "-I${it.absolutePath.crossPlatformPath}" }) .joinToString(" ") private val KonanCompileTask.cMakeSources: String get() = srcFiles.flatMap { it.asCMakeSourceList }.joinToString(" ") private val KonanCompileTask.cMakeLibraries: String get() = mutableListOf<String>().apply { addAll(libraries.artifacts.map { it.artifactName }) addAll(libraries.namedKlibs) addAll(libraries.files.flatMap { it.files }.map { it.canonicalPath.crossPlatformPath }) }.joinToString(" ") private val KonanCompileTask.cMakeLinkerOpts: String get() = linkerOpts.joinToString(" ") } private class Call(val name: String) { private val args: MutableList<Pair<String, String>> = mutableListOf() fun arg(key: String, value: String?): Call { if (value != null && value.isNotBlank()) args += key to value return this } override fun toString(): String = buildString { append(name) append("(") for ((key, value) in args) { appendln() append(" $key $value") } appendln(")") } }
apache-2.0
82a1519b9c440e33d6d2e1ce26047bcf
37.655172
108
0.595183
4.836066
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/properties/protectedJavaPropertyInCompanion.kt
2
812
// TODO: muted automatically, investigate should it be ran for JS or not // IGNORE_BACKEND: JS, NATIVE // WITH_RUNTIME // FILE: JavaBaseClass.java public class JavaBaseClass { private String field = "fail"; protected String getFoo() { return field; } protected void setFoo(String foo) { field = foo; } } // FILE: kotlin.kt package z import JavaBaseClass class A { @JvmField var foo = "fail" companion object : JavaBaseClass() { @JvmStatic fun test(): String { return runSlowly { foo = "OK" foo } } } } fun runSlowly(f: () -> String): String { return f() } fun box(): String { val a = A() a.foo = "Kotlin" if (a.foo != "Kotlin") return "fail" return A.test() }
apache-2.0
eda67fa3aa50dbcc10d68520c6df6e62
15.916667
72
0.555419
3.776744
false
false
false
false
smmribeiro/intellij-community
platform/platform-impl/src/com/intellij/internal/ui/uiDslTestAction/UiDslTestAction.kt
2
11634
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.internal.ui.uiDslTestAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogPanel import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.util.Disposer import com.intellij.ui.CollectionComboBoxModel import com.intellij.ui.components.JBCheckBox import com.intellij.ui.components.JBTabbedPane import com.intellij.ui.dsl.builder.* import com.intellij.ui.dsl.gridLayout.HorizontalAlign import com.intellij.ui.dsl.gridLayout.VerticalAlign import org.jetbrains.annotations.ApiStatus import java.awt.BorderLayout import java.awt.Dimension import java.awt.event.ItemEvent import javax.swing.JComponent import javax.swing.JPanel import javax.swing.JScrollPane import javax.swing.border.Border @ApiStatus.Internal class UiDslTestAction : DumbAwareAction("Show UI DSL Tests") { override fun actionPerformed(e: AnActionEvent) { UiDslTestDialog(e.project).show() } } @Suppress("DialogTitleCapitalization") private class UiDslTestDialog(project: Project?) : DialogWrapper(project, null, true, IdeModalityType.IDE, false) { init { title = "UI DSL Tests" init() } override fun createContentPaneBorder(): Border? { return null } override fun createCenterPanel(): JComponent { val result = JBTabbedPane() result.minimumSize = Dimension(300, 200) result.preferredSize = Dimension(800, 600) result.addTab("Labels", JScrollPane(LabelsPanel().panel)) result.addTab("Text Fields", createTextFields()) result.addTab("Comments", JScrollPane(createCommentsPanel())) result.addTab("Text MaxLine", createTextMaxLinePanel()) result.addTab("Groups", JScrollPane(GroupsPanel().panel)) result.addTab("Segmented Button", SegmentedButtonPanel().panel) result.addTab("Visible/Enabled", createVisibleEnabled()) result.addTab("Cells With Sub-Panels", createCellsWithPanels()) result.addTab("Placeholder", PlaceholderPanel(myDisposable).panel) result.addTab("Resizable Rows", createResizableRows()) result.addTab("Others", OthersPanel().panel) result.addTab("Deprecated Api", JScrollPane(DeprecatedApiPanel().panel)) return result } fun createTextFields(): JPanel { val result = panel { row("Text field 1:") { textField() .columns(10) .comment("columns = 10") } row("Text field 2:") { textField() .horizontalAlign(HorizontalAlign.FILL) .comment("horizontalAlign(HorizontalAlign.FILL)") } row("Int text field 1:") { intTextField() .columns(10) .comment("columns = 10") } row("Int text field 2:") { intTextField(range = 0..1000) .comment("range = 0..1000") } row("Int text field 2:") { intTextField(range = 0..1000, keyboardStep = 100) .comment("range = 0..1000, keyboardStep = 100") } } val disposable = Disposer.newDisposable() result.registerValidators(disposable) Disposer.register(myDisposable, disposable) return result } fun createVisibleEnabled(): JPanel { val entities = mutableMapOf<String, Any>() return panel { row { label("<html>Example test cases:<br>" + "1. Hide Group, hide/show sub elements from Group<br>" + " * they shouldn't be visible until Group becomes visible<br>" + " * after Group becomes shown visible state of sub elements correspondent to checkboxes<br>" + "2. Similar to 1 test case but with enabled state") } row { panel { entities["Row 1"] = row("Row 1") { entities["textField1"] = textField() .text("textField1") } entities["Group"] = group("Group") { entities["Row 2"] = row("Row 2") { entities["textField2"] = textField() .text("textField2") .comment("Comment with a <a>link</a>") } entities["Row 3"] = row("Row 3") { entities["panel"] = panel { row { label("Panel inside row3") } entities["Row 4"] = row("Row 4") { entities["textField3"] = textField() .text("textField3") } } } } }.verticalAlign(VerticalAlign.TOP) panel { row { label("Visible/Enabled") .bold() } for ((name, entity) in entities.toSortedMap()) { row(name) { checkBox("visible") .applyToComponent { isSelected = true addItemListener { when (entity) { is Cell<*> -> entity.visible(this.isSelected) is Row -> entity.visible(this.isSelected) is Panel -> entity.visible(this.isSelected) } } } checkBox("enabled") .applyToComponent { isSelected = true addItemListener { when (entity) { is Cell<*> -> entity.enabled(this.isSelected) is Row -> entity.enabled(this.isSelected) is Panel -> entity.enabled(this.isSelected) } } } } } }.horizontalAlign(HorizontalAlign.RIGHT) } group("Control visibility by visibleIf") { lateinit var checkBoxText: Cell<JBCheckBox> lateinit var checkBoxRow: Cell<JBCheckBox> row { checkBoxRow = checkBox("Row") .applyToComponent { isSelected = true } checkBoxText = checkBox("textField") .applyToComponent { isSelected = true } } row("visibleIf test row") { textField() .text("textField") .visibleIf(checkBoxText.selected) label("some label") }.visibleIf(checkBoxRow.selected) } } } fun createCellsWithPanels(): JPanel { return panel { row("Row") { textField() .columns(20) } row("Row 2") { val subPanel = com.intellij.ui.dsl.builder.panel { row { textField() .columns(20) .text("Sub-Paneled Row") } } cell(subPanel) } row("Row 3") { textField() .horizontalAlign(HorizontalAlign.FILL) } row("Row 4") { val subPanel = com.intellij.ui.dsl.builder.panel { row { textField() .horizontalAlign(HorizontalAlign.FILL) .text("Sub-Paneled Row") } } cell(subPanel) .horizontalAlign(HorizontalAlign.FILL) } } } fun createResizableRows(): JPanel { return panel { for (rowLayout in RowLayout.values()) { row(rowLayout.name) { textArea() .horizontalAlign(HorizontalAlign.FILL) .verticalAlign(VerticalAlign.FILL) }.layout(rowLayout) .resizableRow() } } } fun createCommentsPanel(): JPanel { var type = CommentComponentType.CHECKBOX val placeholder = JPanel(BorderLayout()) fun applyType() { val builder = CommentPanelBuilder(type) placeholder.removeAll() placeholder.add(builder.build(), BorderLayout.CENTER) } val result = panel { row("Component type") { comboBox(CollectionComboBoxModel(CommentComponentType.values().asList())) .applyToComponent { addItemListener { if (it.stateChange == ItemEvent.SELECTED) { type = it?.item as? CommentComponentType ?: CommentComponentType.CHECKBOX applyType() placeholder.revalidate() } } } } row { cell(placeholder) } } applyType() return result } fun createTextMaxLinePanel(): JPanel { val longLine = (1..4).joinToString { "A very long string with a <a>link</a>" } val string = "$longLine<br>$longLine" return panel { row("comment(string):") { comment(string) } row("comment(string, DEFAULT_COMMENT_WIDTH):") { comment(string, maxLineLength = DEFAULT_COMMENT_WIDTH) } row("comment(string, MAX_LINE_LENGTH_NO_WRAP):") { comment(string, maxLineLength = MAX_LINE_LENGTH_NO_WRAP) } row("text(string):") { text(string) } row("text(string, DEFAULT_COMMENT_WIDTH):") { text(string, maxLineLength = DEFAULT_COMMENT_WIDTH) } row("text(string, MAX_LINE_LENGTH_NO_WRAP):") { text(string, maxLineLength = MAX_LINE_LENGTH_NO_WRAP) } } } } @Suppress("DialogTitleCapitalization") private class CommentPanelBuilder(val type: CommentComponentType) { fun build(): DialogPanel { return panel { for (rowLayout in RowLayout.values()) { val labelAligned = rowLayout == RowLayout.LABEL_ALIGNED group("rowLayout = $rowLayout") { row("With Label:") { customComponent("Long Component1") .comment("Component1 comment is aligned with Component1") customComponent("Component2") button("button") { } }.layout(rowLayout) row("With Long Label:") { customComponent("Component1") customComponent("Long Component2") .comment( if (labelAligned) "LABEL_ALIGNED: Component2 comment is aligned with Component1 (cell[1]), hard to fix, rare use case" else "Component2 comment is aligned with Component2") button("button") { } }.layout(rowLayout) row("With Very Long Label:") { customComponent("Component1") customComponent("Long Component2") button("button") { } .comment(if (labelAligned) "LABEL_ALIGNED: Button comment is aligned with Component1 (cell[1]), hard to fix, rare use case" else "Button comment is aligned with button") }.layout(rowLayout) if (labelAligned) { row { label("LABEL_ALIGNED: in the next row only two first comments are shown") } } row { customComponent("Component1 extra width") .comment("Component1 comment") customComponent("Component2 extra width") .comment("Component2 comment<br>second line") customComponent("One More Long Component3") .comment("Component3 comment") button("button") { } .comment("Button comment") }.layout(rowLayout) } } } } private fun Row.customComponent(text: String): Cell<JComponent> { return when (type) { CommentComponentType.CHECKBOX -> checkBox(text) CommentComponentType.TEXT_FIELD -> textField().text(text) CommentComponentType.TEXT_FIELD_WITH_BROWSE_BUTTON -> textFieldWithBrowseButton().text(text) } } } private enum class CommentComponentType { CHECKBOX, TEXT_FIELD, TEXT_FIELD_WITH_BROWSE_BUTTON }
apache-2.0
0ca4d98fea03a78d212b3b090370ed4c
30.961538
158
0.581657
4.702506
false
false
false
false
smmribeiro/intellij-community
plugins/github/src/org/jetbrains/plugins/github/pullrequest/GHRepoVirtualFile.kt
1
2406
// 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.diff.editor.DiffVirtualFile.Companion.turnOffReopeningWindow import com.intellij.openapi.fileTypes.FileType import com.intellij.openapi.fileTypes.FileTypes import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFilePathWrapper import com.intellij.openapi.vfs.VirtualFileSystem import com.intellij.openapi.vfs.VirtualFileWithoutContent import com.intellij.testFramework.LightVirtualFileBase import org.jetbrains.plugins.github.api.GHRepositoryCoordinates /** * [fileManagerId] is a [org.jetbrains.plugins.github.pullrequest.data.GHPRFilesManagerImpl.id] which is required to differentiate files * between launches of a PR toolwindow. * This is necessary to make the files appear in "Recent Files" correctly. * See [com.intellij.vcs.editor.ComplexPathVirtualFileSystem.ComplexPath.sessionId] for details. */ abstract class GHRepoVirtualFile(protected val fileManagerId: String, val project: Project, val repository: GHRepositoryCoordinates) : LightVirtualFileBase("", null, 0), VirtualFileWithoutContent, VirtualFilePathWrapper { init { turnOffReopeningWindow() } override fun enforcePresentableName() = true override fun getFileSystem(): VirtualFileSystem = GHPRVirtualFileSystem.getInstance() override fun getFileType(): FileType = FileTypes.UNKNOWN override fun getLength() = 0L override fun contentsToByteArray() = throw UnsupportedOperationException() override fun getInputStream() = throw UnsupportedOperationException() override fun getOutputStream(requestor: Any?, newModificationStamp: Long, newTimeStamp: Long) = throw UnsupportedOperationException() override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is GHRepoVirtualFile) return false if (fileManagerId != other.fileManagerId) return false if (project != other.project) return false if (repository != other.repository) return false return true } override fun hashCode(): Int { var result = fileManagerId.hashCode() result = 31 * result + project.hashCode() result = 31 * result + repository.hashCode() return result } }
apache-2.0
9cd47a08a1e9d5565a476c59ec7cdee3
41.982143
140
0.765586
4.850806
false
false
false
false
smmribeiro/intellij-community
plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/elements/CreateMethodAction.kt
8
4381
// 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.plugins.groovy.annotator.intentions.elements import com.intellij.codeInsight.CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement import com.intellij.codeInsight.daemon.QuickFixBundle.message import com.intellij.lang.jvm.JvmModifier import com.intellij.lang.jvm.actions.* import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiFile import com.intellij.psi.PsiNameHelper import com.intellij.psi.PsiType import com.intellij.psi.presentation.java.ClassPresentationUtil.getNameForClass import com.intellij.psi.util.JavaElementKind import org.jetbrains.plugins.groovy.intentions.base.IntentionUtils.createTemplateForMethod import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifier import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod /** * @param abstract whether this action creates a method with explicit abstract modifier */ internal class CreateMethodAction( targetClass: GrTypeDefinition, override val request: CreateMethodRequest, private val abstract: Boolean ) : CreateMemberAction(targetClass, request), JvmGroupIntentionAction { override fun getActionGroup(): JvmActionGroup = if (abstract) CreateAbstractMethodActionGroup else CreateMethodActionGroup override fun isAvailable(project: Project, editor: Editor?, file: PsiFile?): Boolean { return super.isAvailable(project, editor, file) && PsiNameHelper.getInstance(project).isIdentifier(request.methodName) } override fun getRenderData() = JvmActionGroup.RenderData { request.methodName } override fun getFamilyName(): String = message("create.method.from.usage.family") override fun getText(): String { val what = request.methodName val where = getNameForClass(target, false) val kind = if (abstract && !target.isInterface) JavaElementKind.ABSTRACT_METHOD else JavaElementKind.METHOD return message("create.element.in.class", kind.`object`(), what, where) } override fun invoke(project: Project, editor: Editor?, file: PsiFile?) { MethodRenderer(project, abstract, target, request).execute() } } private class MethodRenderer( val project: Project, val abstract: Boolean, val targetClass: GrTypeDefinition, val request: CreateMethodRequest ) { fun execute() { var method = renderMethod() method = insertMethod(method) method = forcePsiPostprocessAndRestoreElement(method) ?: return setupTemplate(method) } private fun setupTemplate(method: GrMethod) { val parameters = request.expectedParameters val typeExpressions = setupParameters(method, parameters).toTypedArray() val nameExpressions = setupNameExpressions(parameters, project).toTypedArray() val returnExpression = setupTypeElement(method, createConstraints(project, request.returnType)) createTemplateForMethod(typeExpressions, nameExpressions, method, targetClass, returnExpression, false, null) } private fun renderMethod(): GrMethod { val factory = GroovyPsiElementFactory.getInstance(project) val method = factory.createMethod(request.methodName, PsiType.VOID) val modifiersToRender = request.modifiers.toMutableList() if (targetClass.isInterface) { modifiersToRender -= (visibilityModifiers + JvmModifier.ABSTRACT) } else if (abstract) { if (modifiersToRender.remove(JvmModifier.PRIVATE)) { modifiersToRender += JvmModifier.PROTECTED } modifiersToRender += JvmModifier.ABSTRACT } modifiersToRender -= JvmModifier.PUBLIC //public by default val modifierList = method.modifierList for (modifier in modifiersToRender) { modifierList.setModifierProperty(modifier.toPsiModifier(), true) } modifierList.setModifierProperty(GrModifier.DEF, true) for (annotation in request.annotations) { modifierList.addAnnotation(annotation.qualifiedName) } if (abstract) method.body?.delete() return method } private fun insertMethod(method: GrMethod): GrMethod { return targetClass.add(method) as GrMethod } }
apache-2.0
adbde94b39e12f3d0038b444e4d70530
39.201835
140
0.779959
4.741342
false
false
false
false
smmribeiro/intellij-community
plugins/git4idea/src/git4idea/index/StagePopupVerticalLayout.kt
12
2157
// 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 java.awt.* import kotlin.math.max /** * Put two scrollable panels in a vertical stack. * If both panels preferred height is bigger than `panel.size / 2`, give them both equal height. */ internal class StagePopupVerticalLayout : LayoutManager { override fun addLayoutComponent(name: String?, comp: Component) = Unit override fun removeLayoutComponent(comp: Component) = Unit override fun preferredLayoutSize(parent: Container): Dimension = computeLayoutSize(parent) { it.preferredSize } override fun minimumLayoutSize(parent: Container): Dimension = computeLayoutSize(parent) { it.minimumSize } private fun computeLayoutSize(parent: Container, sizeFun: (Component) -> Dimension): Dimension { var width = 0 var height = 0 for (component in parent.components) { val size = sizeFun(component) width = max(width, size.width) height += size.height } return Dimension(width, height) } override fun layoutContainer(parent: Container) { assert(parent.componentCount == 2) val size = parent.size val panel1 = parent.getComponent(0) val panel2 = parent.getComponent(1) val height = size.height val prefHeight1 = panel1.preferredSize.height val prefHeight2 = panel2.preferredSize.height val height1: Int val height2: Int val isBig1 = prefHeight1 > height / 2 val isBig2 = prefHeight2 > height / 2 if (isBig1 && isBig2) { // split panel in half height1 = height / 2 height2 = height - height1 } else if (isBig1) { // scrollbar for panel1 height2 = prefHeight2 height1 = height - height2 } else if (isBig2) { // scrollbar for panel2 height1 = prefHeight1 height2 = height - height1 } else { // no scrollbar necessary height1 = prefHeight1 height2 = prefHeight2 } panel1.bounds = Rectangle(0, 0, size.width, height1) panel2.bounds = Rectangle(0, height1, size.width, height2) } }
apache-2.0
92351a09f60aa9cef641429e12d32c57
30.735294
140
0.685675
4.085227
false
false
false
false
smmribeiro/intellij-community
python/src/com/jetbrains/python/sdk/PySdkExt.kt
1
15791
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jetbrains.python.sdk import com.intellij.execution.ExecutionException import com.intellij.execution.target.TargetEnvironmentConfiguration import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.WriteAction import com.intellij.openapi.application.runInEdt import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleUtil import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.Task import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.projectRoots.impl.SdkConfigurationUtil import com.intellij.openapi.roots.ModuleRootManager import com.intellij.openapi.roots.ModuleRootModificationUtil import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.util.Key import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.UserDataHolder import com.intellij.openapi.util.UserDataHolderBase import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.StandardFileSystems import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.PathUtil import com.intellij.webcore.packaging.PackagesNotificationPanel import com.jetbrains.python.PyBundle import com.jetbrains.python.packaging.ui.PyPackageManagementService import com.jetbrains.python.psi.LanguageLevel import com.jetbrains.python.remote.PyRemoteSdkAdditionalDataBase import com.jetbrains.python.sdk.flavors.CondaEnvSdkFlavor import com.jetbrains.python.sdk.flavors.PythonSdkFlavor import com.jetbrains.python.sdk.flavors.VirtualEnvSdkFlavor import com.jetbrains.python.target.PyTargetAwareAdditionalData import com.jetbrains.python.ui.PyUiUtil import java.io.File import java.io.IOException import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths /** * @author vlan */ val BASE_DIR: Key<Path> = Key.create("PYTHON_PROJECT_BASE_PATH") fun findAllPythonSdks(baseDir: Path?): List<Sdk> { val context: UserDataHolder = UserDataHolderBase() if (baseDir != null) { context.putUserData(BASE_DIR, baseDir) } val existing = PythonSdkUtil.getAllSdks() return detectCondaEnvs(null, existing, context) + detectVirtualEnvs(null, existing, context) + findBaseSdks(existing, null, context) } fun findBaseSdks(existingSdks: List<Sdk>, module: Module?, context: UserDataHolder): List<Sdk> { val existing = filterSystemWideSdks(existingSdks) .sortedWith(PreferredSdkComparator.INSTANCE) .filterNot { PythonSdkUtil.isBaseConda(it.homePath) } val detected = detectSystemWideSdks(module, existingSdks, context).filterNot { PythonSdkUtil.isBaseConda(it.homePath) } return existing + detected } fun mostPreferred(sdks: List<Sdk>): Sdk? = sdks.minWithOrNull(PreferredSdkComparator.INSTANCE) fun filterSystemWideSdks(existingSdks: List<Sdk>): List<Sdk> { return existingSdks.filter { it.sdkType is PythonSdkType && it.isSystemWide } } @JvmOverloads fun detectSystemWideSdks(module: Module?, existingSdks: List<Sdk>, context: UserDataHolder = UserDataHolderBase()): List<PyDetectedSdk> { if (module != null && module.isDisposed) return emptyList() val existingPaths = existingSdks.map { it.homePath }.toSet() return PythonSdkFlavor.getApplicableFlavors(false) .asSequence() .flatMap { it.suggestHomePaths(module, context).asSequence() } .filter { it !in existingPaths } .map { PyDetectedSdk(it) } .sortedWith(compareBy<PyDetectedSdk>({ it.guessedLanguageLevel }, { it.homePath }).reversed()) .toList() } fun resetSystemWideSdksDetectors() { PythonSdkFlavor.getApplicableFlavors(false).forEach(PythonSdkFlavor::dropCaches) } fun detectVirtualEnvs(module: Module?, existingSdks: List<Sdk>, context: UserDataHolder): List<PyDetectedSdk> = filterSuggestedPaths(VirtualEnvSdkFlavor.getInstance().suggestHomePaths(module, context), existingSdks, module, context) fun filterSharedCondaEnvs(module: Module?, existingSdks: List<Sdk>): List<Sdk> { return existingSdks.filter { it.sdkType is PythonSdkType && PythonSdkUtil.isConda(it) && !it.isAssociatedWithAnotherModule(module) } } fun detectCondaEnvs(module: Module?, existingSdks: List<Sdk>, context: UserDataHolder): List<PyDetectedSdk> = filterSuggestedPaths(CondaEnvSdkFlavor.getInstance().suggestHomePaths(module, context), existingSdks, module, context, true) fun filterAssociatedSdks(module: Module, existingSdks: List<Sdk>): List<Sdk> { return existingSdks.filter { it.sdkType is PythonSdkType && it.isAssociatedWithModule(module) } } fun detectAssociatedEnvironments(module: Module, existingSdks: List<Sdk>, context: UserDataHolder): List<PyDetectedSdk> { val virtualEnvs = detectVirtualEnvs(module, existingSdks, context).filter { it.isAssociatedWithModule(module) } val condaEnvs = detectCondaEnvs(module, existingSdks, context).filter { it.isAssociatedWithModule(module) } return virtualEnvs + condaEnvs } fun createSdkByGenerateTask(generateSdkHomePath: Task.WithResult<String, ExecutionException>, existingSdks: List<Sdk>, baseSdk: Sdk?, associatedProjectPath: String?, suggestedSdkName: String?): Sdk? { val homeFile = try { val homePath = ProgressManager.getInstance().run(generateSdkHomePath) StandardFileSystems.local().refreshAndFindFileByPath(homePath) ?: throw ExecutionException( PyBundle.message("python.sdk.directory.not.found", homePath) ) } catch (e: ExecutionException) { showSdkExecutionException(baseSdk, e, PyBundle.message("python.sdk.failed.to.create.interpreter.title")) return null } val suggestedName = suggestedSdkName ?: suggestAssociatedSdkName(homeFile.path, associatedProjectPath) return SdkConfigurationUtil.setupSdk(existingSdks.toTypedArray(), homeFile, PythonSdkType.getInstance(), false, null, suggestedName) } fun showSdkExecutionException(sdk: Sdk?, e: ExecutionException, @NlsContexts.DialogTitle title: String) { runInEdt { val description = PyPackageManagementService.toErrorDescription(listOf(e), sdk) ?: return@runInEdt PackagesNotificationPanel.showError(title, description) } } fun Sdk.associateWithModule(module: Module?, newProjectPath: String?) { getOrCreateAdditionalData().apply { when { newProjectPath != null -> associateWithModulePath(newProjectPath) module != null -> associateWithModule(module) } } } fun Sdk.isAssociatedWithModule(module: Module?): Boolean { val basePath = module?.basePath val associatedPath = associatedModulePath if (basePath != null && associatedPath == basePath) return true if (isAssociatedWithAnotherModule(module)) return false return isLocatedInsideModule(module) || containsModuleName(module) } fun Sdk.isAssociatedWithAnotherModule(module: Module?): Boolean { val basePath = module?.basePath ?: return false val associatedPath = associatedModulePath ?: return false return basePath != associatedPath } val Sdk.associatedModulePath: String? // TODO: Support .project associations get() = associatedPathFromAdditionalData /*?: associatedPathFromDotProject*/ val Sdk.associatedModuleDir: VirtualFile? get() = associatedModulePath?.let { StandardFileSystems.local().findFileByPath(it) } fun Sdk.adminPermissionsNeeded(): Boolean { val pathToCheck = sitePackagesDirectory?.path ?: homePath ?: return false return !Files.isWritable(Paths.get(pathToCheck)) } fun PyDetectedSdk.setup(existingSdks: List<Sdk>): Sdk? { val homeDir = homeDirectory ?: return null return SdkConfigurationUtil.setupSdk(existingSdks.toTypedArray(), homeDir, PythonSdkType.getInstance(), false, null, null) } fun PyDetectedSdk.setupTargetAware(existingSdks: List<Sdk>, targetEnvironmentConfiguration: TargetEnvironmentConfiguration?): Sdk? { val homeDir = homeDirectory ?: return null val sdk = SdkConfigurationUtil.createSdk(existingSdks, homeDir, PythonSdkType.getInstance(), null, null) sdk.sdkAdditionalData = PyTargetAwareAdditionalData(flavor = null) .also { it.targetEnvironmentConfiguration = targetEnvironmentConfiguration } PythonSdkType.getInstance().setupSdkPaths(sdk) return sdk } fun PyDetectedSdk.setupAssociated(existingSdks: List<Sdk>, associatedModulePath: String?): Sdk? { val homeDir = homeDirectory ?: return null val suggestedName = homePath?.let { suggestAssociatedSdkName(it, associatedModulePath) } return SdkConfigurationUtil.setupSdk(existingSdks.toTypedArray(), homeDir, PythonSdkType.getInstance(), false, null, suggestedName) } var Module.pythonSdk: Sdk? get() = PythonSdkUtil.findPythonSdk(this) set(value) { ModuleRootModificationUtil.setModuleSdk(this, value) PyUiUtil.clearFileLevelInspectionResults(project) } var Project.pythonSdk: Sdk? get() { val sdk = ProjectRootManager.getInstance(this).projectSdk return when (sdk?.sdkType) { is PythonSdkType -> sdk else -> null } } set(value) { val application = ApplicationManager.getApplication() application.invokeAndWait { application.runWriteAction { ProjectRootManager.getInstance(this).projectSdk = value } } } fun Module.excludeInnerVirtualEnv(sdk: Sdk) { val root = getInnerVirtualEnvRoot(sdk) ?: return val model = ModuleRootManager.getInstance(this).modifiableModel val contentEntry = model.contentEntries.firstOrNull { val contentFile = it.file contentFile != null && VfsUtil.isAncestor(contentFile, root, true) } ?: return contentEntry.addExcludeFolder(root) WriteAction.run<Throwable> { model.commit() } } fun Project?.excludeInnerVirtualEnv(sdk: Sdk) { val binary = sdk.homeDirectory ?: return val possibleProjects = if (this != null) listOf(this) else ProjectManager.getInstance().openProjects.asList() possibleProjects.firstNotNullOfOrNull { ModuleUtil.findModuleForFile(binary, it) }?.excludeInnerVirtualEnv(sdk) } fun getInnerVirtualEnvRoot(sdk: Sdk): VirtualFile? { val binaryPath = sdk.homePath ?: return null val possibleVirtualEnv = PythonSdkUtil.getVirtualEnvRoot(binaryPath) return if (possibleVirtualEnv != null) { LocalFileSystem.getInstance().findFileByIoFile(possibleVirtualEnv) } else if (PythonSdkUtil.isCondaVirtualEnv(binaryPath)) { PythonSdkUtil.getCondaDirectory(sdk) } else { null } } private fun suggestAssociatedSdkName(sdkHome: String, associatedPath: String?): String? { // please don't forget to update com.jetbrains.python.inspections.PyInterpreterInspection.Visitor#getSuitableSdkFix // after changing this method val baseSdkName = PythonSdkType.suggestBaseSdkName(sdkHome) ?: return null val venvRoot = PythonSdkUtil.getVirtualEnvRoot(sdkHome)?.path val condaRoot = CondaEnvSdkFlavor.getCondaEnvRoot(sdkHome)?.path val associatedName = when { venvRoot != null && (associatedPath == null || !FileUtil.isAncestor(associatedPath, venvRoot, true)) -> PathUtil.getFileName(venvRoot) condaRoot != null && (associatedPath == null || !FileUtil.isAncestor(associatedPath, condaRoot, true)) -> PathUtil.getFileName(condaRoot) PythonSdkUtil.isBaseConda(sdkHome) -> "base" else -> associatedPath?.let { PathUtil.getFileName(associatedPath) } ?: return null } return "$baseSdkName ($associatedName)" } val File.isNotEmptyDirectory: Boolean get() = exists() && isDirectory && list()?.isEmpty()?.not() ?: false private val Sdk.isSystemWide: Boolean get() = !PythonSdkUtil.isRemote(this) && !PythonSdkUtil.isVirtualEnv( this) && !PythonSdkUtil.isCondaVirtualEnv(this) @Suppress("unused") private val Sdk.associatedPathFromDotProject: String? get() { val binaryPath = homePath ?: return null val virtualEnvRoot = PythonSdkUtil.getVirtualEnvRoot(binaryPath) ?: return null val projectFile = File(virtualEnvRoot, ".project") return try { projectFile.readText().trim() } catch (e: IOException) { null } } private val Sdk.associatedPathFromAdditionalData: String? get() = (sdkAdditionalData as? PythonSdkAdditionalData)?.associatedModulePath private val Sdk.sitePackagesDirectory: VirtualFile? get() = PythonSdkUtil.getSitePackagesDirectory(this) val Sdk.sdkFlavor: PythonSdkFlavor? get() { val remoteSdkData = remoteSdkAdditionalData if (remoteSdkData != null) { return remoteSdkData.flavor } return PythonSdkFlavor.getFlavor(this) } val Sdk.remoteSdkAdditionalData: PyRemoteSdkAdditionalDataBase? get() = sdkAdditionalData as? PyRemoteSdkAdditionalDataBase fun Sdk.isLocatedInsideModule(module: Module?): Boolean { val baseDirPath = try { module?.baseDir?.toNioPath() } catch (e: UnsupportedOperationException) { return false } return isLocatedInsideBaseDir(baseDirPath) } private fun Sdk.isLocatedInsideBaseDir(baseDir: Path?): Boolean { val homePath = homePath ?: return false val basePath = baseDir?.toString() ?: return false return FileUtil.isAncestor(basePath, homePath, true) } val PyDetectedSdk.guessedLanguageLevel: LanguageLevel? get() { val path = homePath ?: return null val result = Regex(""".*python(\d\.\d)""").find(path) ?: return null val versionString = result.groupValues.getOrNull(1) ?: return null return LanguageLevel.fromPythonVersion(versionString) } private fun Sdk.containsModuleName(module: Module?): Boolean { val path = homePath ?: return false val name = module?.name ?: return false return path.contains(name, true) } fun Sdk.getOrCreateAdditionalData(): PythonSdkAdditionalData { val existingData = sdkAdditionalData as? PythonSdkAdditionalData if (existingData != null) return existingData val newData = PythonSdkAdditionalData(PythonSdkFlavor.getFlavor(homePath)) val modificator = sdkModificator modificator.sdkAdditionalData = newData ApplicationManager.getApplication().runWriteAction { modificator.commitChanges() } return newData } private fun filterSuggestedPaths(suggestedPaths: Collection<String>, existingSdks: List<Sdk>, module: Module?, context: UserDataHolder, mayContainCondaEnvs: Boolean = false): List<PyDetectedSdk> { val existingPaths = existingSdks.mapTo(HashSet()) { it.homePath } val baseDirFromContext = context.getUserData(BASE_DIR) return suggestedPaths .asSequence() .filterNot { it in existingPaths } .distinct() .map { PyDetectedSdk(it) } .sortedWith( compareBy( { !it.isAssociatedWithModule(module) && !it.isLocatedInsideBaseDir(baseDirFromContext) }, { if (mayContainCondaEnvs) !PythonSdkUtil.isBaseConda(it.homePath) else false }, { it.homePath } ) ) .toList() } fun Sdk?.isTargetBased(): Boolean = this != null && sdkAdditionalData is PyTargetAwareAdditionalData
apache-2.0
03fdd55279a033296abc47e8134a5497
38.979747
137
0.753214
4.566512
false
false
false
false
kickstarter/android-oss
app/src/main/java/com/kickstarter/services/apirequests/PushTokenBody.kt
1
1177
package com.kickstarter.services.apirequests import android.os.Parcelable import kotlinx.parcelize.Parcelize @Parcelize class PushTokenBody private constructor( private val pushServer: String?, private val token: String? ) : Parcelable { fun pushServer() = this.pushServer fun token() = this.token @Parcelize data class Builder( private var pushServer: String? = null, private var token: String? = null ) : Parcelable { fun pushServer(pushServer: String?) = apply { this.pushServer = pushServer } fun token(token: String?) = apply { this.token = token } fun build() = PushTokenBody( pushServer = pushServer, token = token ) } fun toBuilder() = Builder( pushServer = pushServer, token = token ) companion object { @JvmStatic fun builder() = Builder() } override fun equals(other: Any?): Boolean { var equals = super.equals(other) if (other is PushTokenBody) { equals = pushServer() == other.pushServer() && token() == other.token() } return equals } }
apache-2.0
a949de35f9b012e62a59017b5720ab66
25.155556
84
0.59983
4.391791
false
false
false
false
cout970/Modeler
src/main/kotlin/com/cout970/modeler/core/model/material/MaterialNone.kt
1
868
package com.cout970.modeler.core.model.material import com.cout970.glutilities.texture.Texture import com.cout970.modeler.api.model.material.IMaterial import com.cout970.modeler.core.resource.ResourceLoader import com.cout970.vector.api.IVector2 import com.cout970.vector.extensions.vec2Of import java.util.* object MaterialNone : IMaterial { override val id: UUID = UUID.fromString("89672293-60d2-46ea-9b56-46c624dec60a") override val name: String = "No Texture" override val size: IVector2 = vec2Of(32) lateinit var whiteTexture: Texture private set override fun loadTexture(resourceLoader: ResourceLoader): Boolean { whiteTexture = resourceLoader.getTexture("assets/textures/white.png") return false } override fun hasChanged(): Boolean = false override fun bind() { whiteTexture.bind() } }
gpl-3.0
d7f40988f8b132fc42433185b497131b
28.965517
83
0.743088
3.875
false
false
false
false
FuturemanGaming/FutureBot-Discord
src/main/kotlin/com/futuremangaming/futurebot/music/music.kt
1
3222
/* * Copyright 2014-2017 FuturemanGaming * * 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("Music") package com.futuremangaming.futurebot.music import club.minnced.kjda.catch import club.minnced.kjda.entities.sendTextAsync import com.futuremangaming.futurebot.getLogger import com.sedmelluq.discord.lavaplayer.player.AudioLoadResultHandler import com.sedmelluq.discord.lavaplayer.player.AudioPlayerManager import com.sedmelluq.discord.lavaplayer.tools.FriendlyException import com.sedmelluq.discord.lavaplayer.track.AudioPlaylist import com.sedmelluq.discord.lavaplayer.track.AudioTrack import net.dv8tion.jda.core.entities.Member import net.dv8tion.jda.core.entities.Message import net.dv8tion.jda.core.entities.MessageChannel import net.dv8tion.jda.core.entities.TextChannel import net.dv8tion.jda.core.exceptions.PermissionException val LOG = getLogger(MusicModule::class.java) data class TrackRequest( val manager: PlayerRemote, val id: String, val member: Member, val channel: TextChannel, val message: Message ) fun Message.delete(formatReason: String, vararg args: Any) = try { delete().reason(formatReason.format(*args)) catch { } } catch (ex: PermissionException) { } fun send(channel: MessageChannel, msg: String) { try { channel.sendTextAsync { msg } catch { } } catch (ex: PermissionException) { } catch (ex: Exception) { LOG.error("Failed to send message", ex) } } fun AudioPlayerManager.loadItem(id: String, block: LoadHandlerBuilder.() -> Unit) { val builder = LoadHandlerBuilder() builder.block() loadItem(id, builder.build()) } class LoadHandlerBuilder { var onFailure: (FriendlyException) -> Unit = { } var onPlaylist: (AudioPlaylist) -> Unit = { } var onTrack: (AudioTrack) -> Unit = { } var onNoMatch: () -> Unit = { } fun build() = object : AudioLoadResultHandler { override fun loadFailed(exception: FriendlyException) = onFailure(exception) override fun trackLoaded(track: AudioTrack) = onTrack(track) override fun noMatches() = onNoMatch() override fun playlistLoaded(playlist: AudioPlaylist) = onPlaylist(playlist) } infix fun onFailure(block: (FriendlyException) -> Unit): LoadHandlerBuilder { onFailure = block return this } infix fun onPlaylist(block: (AudioPlaylist) -> Unit): LoadHandlerBuilder { onPlaylist = block return this } infix fun onTrack(block: (AudioTrack) -> Unit): LoadHandlerBuilder { onTrack = block return this } infix fun onNoMatch(block: () -> Unit): LoadHandlerBuilder { onNoMatch = block return this } }
apache-2.0
d3570b565c3aed480b2d7df9757700c6
32.216495
84
0.716946
4.063052
false
false
false
false
MaTriXy/TourGuide
tourguide/src/main/java/tourguide/tourguide/Overlay.kt
2
4941
package tourguide.tourguide import android.graphics.Color import android.view.View import android.view.animation.Animation /** * [Overlay] shows a tinted background to cover up the rest of the screen. A 'hole' will be made on this overlay to let users obtain focus on the targeted element. */ class Overlay @JvmOverloads constructor(var mDisableClick: Boolean = true, var backgroundColor: Int = Color.parseColor("#55000000"), var mStyle: Style = Style.CIRCLE) { var mDisableClickThroughHole: Boolean = false var mEnterAnimation: Animation? = null var mExitAnimation: Animation? = null var mHoleOffsetLeft = 0 var mHoleOffsetTop = 0 var mOnClickListener: View.OnClickListener? = null var mHoleRadius = NOT_SET var mPaddingDp = 10 var mRoundedCornerRadiusDp = 0 enum class Style { CIRCLE, RECTANGLE, ROUNDED_RECTANGLE, NO_HOLE } fun backgroundColor(block: () -> Int) { backgroundColor = block() } /** * Set to true if you want to block all user input to pass through this overlay, set to false if you want to allow user input under the overlay * @param yesNo * @return return [Overlay] instance for chaining purpose */ fun disableClick(yesNo: Boolean): Overlay { mDisableClick = yesNo return this } fun disableClick(block: () -> Boolean) { mDisableClick = block() } /** * Set to true if you want to disallow the highlighted view to be clicked through the hole, * set to false if you want to allow the highlighted view to be clicked through the hole * @param yesNo * @return return Overlay instance for chaining purpose */ fun disableClickThroughHole(yesNo: Boolean): Overlay { mDisableClickThroughHole = yesNo return this } fun disableClickThroughHole(block: () -> Boolean) { mDisableClickThroughHole = block() } fun setStyle(style: Style): Overlay { mStyle = style return this } fun style(block: () -> Style) { mStyle = block() } /** * Set enter animation * @param enterAnimation * @return return [Overlay] instance for chaining purpose */ fun setEnterAnimation(enterAnimation: Animation): Overlay { mEnterAnimation = enterAnimation return this } /** * Set exit animation * @param exitAnimation * @return return [Overlay] instance for chaining purpose */ fun setExitAnimation(exitAnimation: Animation): Overlay { mExitAnimation = exitAnimation return this } /** * Set [Overlay.mOnClickListener] for the [Overlay] * @param onClickListener * @return return [Overlay] instance for chaining purpose */ fun setOnClickListener(onClickListener: View.OnClickListener): Overlay { mOnClickListener = onClickListener return this } fun onClickListener(block: () -> View.OnClickListener) { mOnClickListener = block() } /** * This method sets the hole's radius. * If this is not set, the size of view hole fill follow the max(view.width, view.height) * If this is set, it will take precedence * It only has effect when [Overlay.Style.CIRCLE] is chosen * @param holeRadius the radius of the view hole, setting 0 will make the hole disappear, in pixels * @return return [Overlay] instance for chaining purpose */ fun setHoleRadius(holeRadius: Int): Overlay { mHoleRadius = holeRadius return this } /** * This method sets offsets to the hole's position relative the position of the targeted view. * @param offsetLeft left offset, in pixels * @param offsetTop top offset, in pixels * @return [Overlay] instance for chaining purpose */ fun setHoleOffsets(offsetLeft: Int, offsetTop: Int): Overlay { mHoleOffsetLeft = offsetLeft mHoleOffsetTop = offsetTop return this } /** * This method sets the padding to be applied to the hole cutout from the overlay * @param paddingDp padding, in dp * @return [Overlay] intance for chaining purpose */ fun setHolePadding(paddingDp: Int): Overlay { mPaddingDp = paddingDp return this } fun holePadding(block: () -> Int) { mPaddingDp = block() } /** * This method sets the radius for the rounded corner * It only has effect when [Overlay.Style.ROUNDED_RECTANGLE] is chosen * @param roundedCornerRadiusDp padding, in pixels * @return [Overlay] intance for chaining purpose */ fun setRoundedCornerRadius(roundedCornerRadiusDp: Int): Overlay { mRoundedCornerRadiusDp = roundedCornerRadiusDp return this } fun roundedCornerRadius(block: () -> Int) { mRoundedCornerRadiusDp = block() } companion object { const val NOT_SET = -1 } }
mit
7393bfe93b07da03b99b6765a2f7ffd7
30.075472
168
0.656952
4.562327
false
false
false
false
JetBrains/kotlin-native
tools/performance-server/src/main/kotlin/routes/route.kt
1
32839
/* * Copyright 2010-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. */ import org.w3c.xhr.* import kotlin.js.json import kotlin.js.Date import kotlin.js.Promise import org.jetbrains.database.* import org.jetbrains.report.json.* import org.jetbrains.elastic.* import org.jetbrains.network.* import org.jetbrains.buildInfo.Build import org.jetbrains.analyzer.* import org.jetbrains.report.* import org.jetbrains.utils.* // TODO - create DSL for ES requests? const val teamCityUrl = "https://buildserver.labs.intellij.net/app/rest" const val artifactoryUrl = "https://repo.labs.intellij.net/kotlin-native-benchmarks" operator fun <K, V> Map<K, V>?.get(key: K) = this?.get(key) fun getArtifactoryHeader(artifactoryApiKey: String) = Pair("X-JFrog-Art-Api", artifactoryApiKey) external fun decodeURIComponent(url: String): String // Convert saved old report to expected new format. internal fun convertToNewFormat(data: JsonObject): List<Any> { val env = Environment.create(data.getRequiredField("env")) val benchmarksObj = data.getRequiredField("benchmarks") val compilerDescription = data.getRequiredField("kotlin") val compiler = Compiler.create(compilerDescription) val backend = (compilerDescription as JsonObject).getRequiredField("backend") val flagsArray = (backend as JsonObject).getOptionalField("flags") var flags: List<String> = emptyList() if (flagsArray != null && flagsArray is JsonArray) { flags = flagsArray.jsonArray.map { (it as JsonLiteral).unquoted() } } val benchmarksList = parseBenchmarksArray(benchmarksObj) return listOf(env, compiler, benchmarksList, flags) } // Convert data results to expected format. internal fun convert(json: String, buildNumber: String, target: String): List<BenchmarksReport> { val data = JsonTreeParser.parse(json) val reports = if (data is JsonArray) { data.map { convertToNewFormat(it as JsonObject) } } else listOf(convertToNewFormat(data as JsonObject)) // Restored flags for old reports. val knownFlags = mapOf( "Cinterop" to listOf("-opt"), "FrameworkBenchmarksAnalyzer" to listOf("-g"), "HelloWorld" to if (target == "Mac OS X") listOf("-Xcache-directory=/Users/teamcity/buildAgent/work/c104dee5223a31c5/test_dist/klib/cache/macos_x64-gSTATIC", "-g") else listOf("-g"), "Numerical" to listOf("-opt"), "ObjCInterop" to listOf("-opt"), "Ring" to listOf("-opt"), "Startup" to listOf("-opt"), "swiftInterop" to listOf("-opt"), "Videoplayer" to if (target == "Mac OS X") listOf("-Xcache-directory=/Users/teamcity/buildAgent/work/c104dee5223a31c5/test_dist/klib/cache/macos_x64-gSTATIC", "-g") else listOf("-g") ) return reports.map { elements -> val benchmarks = (elements[2] as List<BenchmarkResult>).groupBy { it.name.substringBefore('.').substringBefore(':') } val parsedFlags = elements[3] as List<String> benchmarks.map { (setName, results) -> val flags = if (parsedFlags.isNotEmpty() && parsedFlags[0] == "-opt") knownFlags[setName]!! else parsedFlags val savedCompiler = elements[1] as Compiler val compiler = Compiler(Compiler.Backend(savedCompiler.backend.type, savedCompiler.backend.version, flags), savedCompiler.kotlinVersion) val newReport = BenchmarksReport(elements[0] as Environment, results, compiler) newReport.buildNumber = buildNumber newReport } }.flatten() } // Golden result value used to get normalized results. data class GoldenResult(val benchmarkName: String, val metric: String, val value: Double) data class GoldenResultsInfo(val goldenResults: Array<GoldenResult>) // Convert information about golden results to benchmarks report format. fun GoldenResultsInfo.toBenchmarksReport(): BenchmarksReport { val benchmarksSamples = goldenResults.map { BenchmarkResult(it.benchmarkName, BenchmarkResult.Status.PASSED, it.value, BenchmarkResult.metricFromString(it.metric)!!, it.value, 1, 0) } val compiler = Compiler(Compiler.Backend(Compiler.BackendType.NATIVE, "golden", emptyList()), "golden") val environment = Environment(Environment.Machine("golden", "golden"), Environment.JDKInstance("golden", "golden")) return BenchmarksReport(environment, benchmarksSamples, compiler) } // Build information provided from request. data class TCBuildInfo(val buildNumber: String, val branch: String, val startTime: String, val finishTime: String) data class BuildRegister(val buildId: String, val teamCityUser: String, val teamCityPassword: String, val bundleSize: String?, val fileWithResult: String) { companion object { fun create(json: String): BuildRegister { val requestDetails = JSON.parse<BuildRegister>(json) // Parse method doesn't create real instance with all methods. So create it by hands. return BuildRegister(requestDetails.buildId, requestDetails.teamCityUser, requestDetails.teamCityPassword, requestDetails.bundleSize, requestDetails.fileWithResult) } } private val teamCityBuildUrl: String by lazy { "builds/id:$buildId" } val changesListUrl: String by lazy { "changes/?locator=build:id:$buildId" } val teamCityArtifactsUrl: String by lazy { "builds/id:$buildId/artifacts/content/$fileWithResult" } fun sendTeamCityRequest(url: String, json: Boolean = false) = UrlNetworkConnector(teamCityUrl).sendRequest(RequestMethod.GET, url, teamCityUser, teamCityPassword, json) fun getBranchName(project: String): Promise<String> { val url = "builds?locator=id:$buildId&fields=build(revisions(revision(vcsBranchName,vcs-root-instance)))" var branch: String? = null return sendTeamCityRequest(url, true).then { response -> val data = JsonTreeParser.parse(response).jsonObject data.getArray("build").forEach { (it as JsonObject).getObject("revisions").getArray("revision").forEach { val currentBranch = (it as JsonObject).getPrimitive("vcsBranchName").content.removePrefix("refs/heads/") val currentProject = (it as JsonObject).getObject("vcs-root-instance").getPrimitive("name").content if (project == currentProject) { branch = currentBranch } return@forEach } } branch ?: error("No project $project can be found in build $buildId") } } private fun format(timeValue: Int): String = if (timeValue < 10) "0$timeValue" else "$timeValue" fun getBuildInformation(): Promise<TCBuildInfo> { return Promise.all(arrayOf(sendTeamCityRequest("$teamCityBuildUrl/number"), getBranchName("Kotlin Native"), sendTeamCityRequest("$teamCityBuildUrl/startDate"))).then { results -> val (buildNumber, branch, startTime) = results val currentTime = Date() val timeZone = currentTime.getTimezoneOffset() / -60 // Convert to hours. // Get finish time as current time, because buid on TeamCity isn't finished. val finishTime = "${format(currentTime.getUTCFullYear())}" + "${format(currentTime.getUTCMonth() + 1)}" + "${format(currentTime.getUTCDate())}" + "T${format(currentTime.getUTCHours())}" + "${format(currentTime.getUTCMinutes())}" + "${format(currentTime.getUTCSeconds())}" + "${if (timeZone > 0) "+" else "-"}${format(timeZone)}${format(0)}" TCBuildInfo(buildNumber, branch, startTime, finishTime) } } } // Get builds numbers in right order. internal fun <T> orderedValues(values: List<T>, buildElement: (T) -> String = { it -> it.toString() }, skipMilestones: Boolean = false) = values.sortedWith( compareBy({ buildElement(it).substringBefore(".").toInt() }, { buildElement(it).substringAfter(".").substringBefore("-").toDouble() }, { if (skipMilestones) 0 else if (buildElement(it).substringAfter("-").startsWith("M")) buildElement(it).substringAfter("M").substringBefore("-").toInt() else Int.MAX_VALUE }, { buildElement(it).substringAfterLast("-").toDouble() } ) ) // ElasticSearch connector for work with custom instance. internal val localHostElasticConnector = UrlNetworkConnector("http://localhost", 9200) // ElasticSearch connector for work with AWS instance. internal val awsElasticConnector = AWSNetworkConnector() internal val networkConnector = awsElasticConnector fun urlParameterToBaseFormat(value: dynamic) = value.toString().replace("_", " ") // Routing of requests to current server. fun router() { val express = require("express") val router = express.Router() val connector = ElasticSearchConnector(networkConnector) val benchmarksDispatcher = BenchmarksIndexesDispatcher(connector, "env.machine.os", listOf("Linux", "Mac OS X", "Windows 10") ) val goldenIndex = GoldenResultsIndex(connector) val buildInfoIndex = BuildInfoIndex(connector) router.get("/createMapping") { _, response -> buildInfoIndex.createMapping().then { _ -> response.sendStatus(200) }.catch { _ -> response.sendStatus(400) } } // Get consistent build information in cases of rerunning the same build. suspend fun getConsistentBuildInfo(buildInfoInstance: BuildInfo, reports: List<BenchmarksReport>, rerunNumber: Int = 1): BuildInfo { var currentBuildInfo = buildInfoInstance if (buildExists(currentBuildInfo, buildInfoIndex)) { // Check if benchmarks aren't repeated. val existingBecnhmarks = benchmarksDispatcher.getBenchmarksList(currentBuildInfo.buildNumber, currentBuildInfo.agentInfo).await() val benchmarksToRegister = reports.map { it.benchmarks.keys }.flatten() if (existingBecnhmarks.toTypedArray().intersect(benchmarksToRegister).isNotEmpty()) { // Build was rerun. val buildNumber = "${currentBuildInfo.buildNumber}.$rerunNumber" currentBuildInfo = BuildInfo(buildNumber, currentBuildInfo.startTime, currentBuildInfo.endTime, currentBuildInfo.commitsList, currentBuildInfo.branch, currentBuildInfo.agentInfo) return getConsistentBuildInfo(currentBuildInfo, reports, rerunNumber + 1) } } return currentBuildInfo } // Register build on Artifactory. router.post("/register") { request, response -> val register = BuildRegister.create(JSON.stringify(request.body)) // Get information from TeamCity. register.getBuildInformation().then { buildInfo -> register.sendTeamCityRequest(register.changesListUrl, true).then { changes -> val commitsList = CommitsList(JsonTreeParser.parse(changes)) // Get artifact. val content = if(register.fileWithResult.contains("/")) UrlNetworkConnector(artifactoryUrl).sendRequest(RequestMethod.GET, register.fileWithResult) else register.sendTeamCityRequest(register.teamCityArtifactsUrl) content.then { resultsContent -> launch { val reportData = JsonTreeParser.parse(resultsContent) val reports = if (reportData is JsonArray) { reportData.map { BenchmarksReport.create(it as JsonObject) } } else listOf(BenchmarksReport.create(reportData as JsonObject)) val goldenResultPromise = getGoldenResults(goldenIndex) val goldenResults = goldenResultPromise.await() // Register build information. var buildInfoInstance = getConsistentBuildInfo( BuildInfo(buildInfo.buildNumber, buildInfo.startTime, buildInfo.finishTime, commitsList, buildInfo.branch, reports[0].env.machine.os), reports ) if (register.bundleSize != null) { // Add bundle size. val bundleSizeBenchmark = BenchmarkResult("KotlinNative", BenchmarkResult.Status.PASSED, register.bundleSize.toDouble(), BenchmarkResult.Metric.BUNDLE_SIZE, 0.0, 1, 0) val bundleSizeReport = BenchmarksReport(reports[0].env, listOf(bundleSizeBenchmark), reports[0].compiler) bundleSizeReport.buildNumber = buildInfoInstance.buildNumber benchmarksDispatcher.insert(bundleSizeReport, reports[0].env.machine.os).then { _ -> println("[BUNDLE] Success insert ${buildInfoInstance.buildNumber}") }.catch { errorResponse -> println("Failed to insert data for build") println(errorResponse) } } val insertResults = reports.map { val benchmarksReport = SummaryBenchmarksReport(it).getBenchmarksReport() .normalizeBenchmarksSet(goldenResults) benchmarksReport.buildNumber = buildInfoInstance.buildNumber // Save results in database. benchmarksDispatcher.insert(benchmarksReport, benchmarksReport.env.machine.os) } if (!buildExists(buildInfoInstance, buildInfoIndex)) { buildInfoIndex.insert(buildInfoInstance).then { _ -> println("Success insert build information for ${buildInfoInstance.buildNumber}") }.catch { response.sendStatus(400) } } Promise.all(insertResults.toTypedArray()).then { _ -> response.sendStatus(200) }.catch { response.sendStatus(400) } } } } } } // Register golden results to normalize on Artifactory. router.post("/registerGolden", { request, response -> val goldenResultsInfo: GoldenResultsInfo = JSON.parse<GoldenResultsInfo>(JSON.stringify(request.body)) val goldenReport = goldenResultsInfo.toBenchmarksReport() goldenIndex.insert(goldenReport).then { _ -> response.sendStatus(200) }.catch { response.sendStatus(400) } }) // Get builds description with additional information. router.get("/buildsDesc/:target", { request, response -> CachableResponseDispatcher.getResponse(request, response) { success, reject -> val target = request.params.target.toString().replace('_', ' ') var branch: String? = null var type: String? = null var buildsCountToShow = 200 var beforeDate: String? = null var afterDate: String? = null if (request.query != undefined) { if (request.query.branch != undefined) { branch = request.query.branch } if (request.query.type != undefined) { type = request.query.type } if (request.query.count != undefined) { buildsCountToShow = request.query.count.toString().toInt() } if (request.query.before != undefined) { beforeDate = decodeURIComponent(request.query.before) } if (request.query.after != undefined) { afterDate = decodeURIComponent(request.query.after) } } getBuildsInfo(type, branch, target, buildsCountToShow, buildInfoIndex, beforeDate, afterDate) .then { buildsInfo -> val buildNumbers = buildsInfo.map { it.buildNumber } // Get number of failed benchmarks for each build. benchmarksDispatcher.getFailuresNumber(target, buildNumbers).then { failures -> success(orderedValues(buildsInfo, { it -> it.buildNumber }, branch == "master").map { Build(it.buildNumber, it.startTime, it.endTime, it.branch, it.commitsList.serializeFields(), failures[it.buildNumber] ?: 0) }) }.catch { errorResponse -> println("Error during getting failures numbers") println(errorResponse) reject() } }.catch { reject() } } }) // Get values of current metric. router.get("/metricValue/:target/:metric", { request, response -> CachableResponseDispatcher.getResponse(request, response) { success, reject -> val metric = request.params.metric val target = request.params.target.toString().replace('_', ' ') var samples: List<String> = emptyList() var aggregation = "geomean" var normalize = false var branch: String? = null var type: String? = null var excludeNames: List<String> = emptyList() var buildsCountToShow = 200 var beforeDate: String? = null var afterDate: String? = null // Parse parameters from request if it exists. if (request.query != undefined) { if (request.query.samples != undefined) { samples = request.query.samples.toString().split(",").map { it.trim() } } if (request.query.agr != undefined) { aggregation = request.query.agr.toString() } if (request.query.normalize != undefined) { normalize = true } if (request.query.branch != undefined) { branch = request.query.branch } if (request.query.type != undefined) { type = request.query.type } if (request.query.exclude != undefined) { excludeNames = request.query.exclude.toString().split(",").map { it.trim() } } if (request.query.count != undefined) { buildsCountToShow = request.query.count.toString().toInt() } if (request.query.before != undefined) { beforeDate = decodeURIComponent(request.query.before) } if (request.query.after != undefined) { afterDate = decodeURIComponent(request.query.after) } } getBuildsNumbers(type, branch, target, buildsCountToShow, buildInfoIndex, beforeDate, afterDate).then { buildNumbers -> if (aggregation == "geomean") { // Get geometric mean for samples. benchmarksDispatcher.getGeometricMean(metric, target, buildNumbers, normalize, excludeNames).then { geoMeansValues -> success(orderedValues(geoMeansValues, { it -> it.first }, branch == "master")) }.catch { errorResponse -> println("Error during getting geometric mean") println(errorResponse) reject() } } else { benchmarksDispatcher.getSamples(metric, target, samples, buildsCountToShow, buildNumbers, normalize) .then { geoMeansValues -> success(orderedValues(geoMeansValues, { it -> it.first }, branch == "master")) }.catch { println("Error during getting samples") reject() } } }.catch { println("Error during getting builds information") reject() } } }) // Get branches for [target]. router.get("/branches", { request, response -> CachableResponseDispatcher.getResponse(request, response) { success, reject -> distinctValues("branch", buildInfoIndex).then { results -> success(results) }.catch { errorMessage -> error(errorMessage.message ?: "Failed getting branches list.") reject() } } }) // Get build numbers for [target]. router.get("/buildsNumbers/:target", { request, response -> CachableResponseDispatcher.getResponse(request, response) { success, reject -> distinctValues("buildNumber", buildInfoIndex).then { results -> success(results) }.catch { errorMessage -> println(errorMessage.message ?: "Failed getting branches list.") reject() } } }) // Conert data and migrate it from Artifactory to DB. router.get("/migrate/:target", { request, response -> val target = urlParameterToBaseFormat(request.params.target) val targetPathName = target.replace(" ", "") var buildNumber: String? = null if (request.query != undefined) { if (request.query.buildNumber != undefined) { buildNumber = request.query.buildNumber buildNumber = request.query.buildNumber } } getBuildsInfoFromArtifactory(targetPathName).then { buildInfo -> launch { val buildsDescription = buildInfo.lines().drop(1) var shouldConvert = buildNumber?.let { false } ?: true val goldenResultPromise = getGoldenResults(goldenIndex) val goldenResults = goldenResultPromise.await() val buildsSet = mutableSetOf<String>() buildsDescription.forEach { if (!it.isEmpty()) { val currentBuildNumber = it.substringBefore(',') if (!"\\d+(\\.\\d+)+(-M\\d)?-\\w+-\\d+(\\.\\d+)?".toRegex().matches(currentBuildNumber)) { error("Build number $currentBuildNumber differs from expected format. File with data for " + "target $target could be corrupted.") } if (!shouldConvert && buildNumber != null && buildNumber == currentBuildNumber) { shouldConvert = true } if (shouldConvert) { // Save data from Artifactory into database. val artifactoryUrlConnector = UrlNetworkConnector(artifactoryUrl) val fileName = "nativeReport.json" val accessFileUrl = "$targetPathName/$currentBuildNumber/$fileName" val extrenalFileName = if (target == "Linux") "externalReport.json" else "spaceFrameworkReport.json" val accessExternalFileUrl = "$targetPathName/$currentBuildNumber/$extrenalFileName" val infoParts = it.split(", ") if ((infoParts[3] == "master" || "eap" in currentBuildNumber || "release" in currentBuildNumber) && currentBuildNumber !in buildsSet) { try { buildsSet.add(currentBuildNumber) val jsonReport = artifactoryUrlConnector.sendRequest(RequestMethod.GET, accessFileUrl).await() var reports = convert(jsonReport, currentBuildNumber, target) val buildInfoRecord = BuildInfo(currentBuildNumber, infoParts[1], infoParts[2], CommitsList.parse(infoParts[4]), infoParts[3], target) val externalJsonReport = artifactoryUrlConnector.sendOptionalRequest(RequestMethod.GET, accessExternalFileUrl) .await() buildInfoIndex.insert(buildInfoRecord).then { _ -> println("[BUILD INFO] Success insert build number ${buildInfoRecord.buildNumber}") externalJsonReport?.let { var externalReports = convert(externalJsonReport.replace("circlet_iosX64", "SpaceFramework_iosX64"), currentBuildNumber, target) externalReports.forEach { externalReport -> val extrenalAdditionalReport = SummaryBenchmarksReport(externalReport) .getBenchmarksReport().normalizeBenchmarksSet(goldenResults) extrenalAdditionalReport.buildNumber = currentBuildNumber benchmarksDispatcher.insert(extrenalAdditionalReport, target).then { _ -> println("[External] Success insert ${buildInfoRecord.buildNumber}") }.catch { errorResponse -> println("Failed to insert data for build") println(errorResponse) } } } val bundleSize = if (infoParts[10] != "-") infoParts[10] else null if (bundleSize != null) { // Add bundle size. val bundleSizeBenchmark = BenchmarkResult("KotlinNative", BenchmarkResult.Status.PASSED, bundleSize.toDouble(), BenchmarkResult.Metric.BUNDLE_SIZE, 0.0, 1, 0) val bundleSizeReport = BenchmarksReport(reports[0].env, listOf(bundleSizeBenchmark), reports[0].compiler) bundleSizeReport.buildNumber = currentBuildNumber benchmarksDispatcher.insert(bundleSizeReport, target).then { _ -> println("[BUNDLE] Success insert ${buildInfoRecord.buildNumber}") }.catch { errorResponse -> println("Failed to insert data for build") println(errorResponse) } } reports.forEach { report -> val summaryReport = SummaryBenchmarksReport(report).getBenchmarksReport() .normalizeBenchmarksSet(goldenResults) summaryReport.buildNumber = currentBuildNumber // Save results in database. benchmarksDispatcher.insert(summaryReport, target).then { _ -> println("Success insert ${buildInfoRecord.buildNumber}") }.catch { errorResponse -> println("Failed to insert data for build") println(errorResponse.message) } } }.catch { errorResponse -> println("Failed to insert data for build") println(errorResponse) } } catch (e: Exception) { println(e) } } } } } } response.sendStatus(200) }.catch { response.sendStatus(400) } }) router.get("/delete/:target", { request, response -> val target = urlParameterToBaseFormat(request.params.target) var buildNumber: String? = null if (request.query != undefined) { if (request.query.buildNumber != undefined) { buildNumber = request.query.buildNumber } } benchmarksDispatcher.deleteBenchmarks(target, buildNumber).then { deleteBuildInfo(target, buildInfoIndex, buildNumber).then { response.sendStatus(200) }.catch { response.sendStatus(400) } }.catch { response.sendStatus(400) } }) // Get builds description with additional information. router.get("/unstable", { request, response -> CachableResponseDispatcher.getResponse(request, response) { success, reject -> getUnstableResults(goldenIndex).then { unstableBenchmarks -> success(unstableBenchmarks) }.catch { println("Error during getting unstable benchmarks") reject() } } }) router.get("/report/:target/:buildNumber", { request, response -> val target = urlParameterToBaseFormat(request.params.target) val buildNumber = request.params.buildNumber.toString() benchmarksDispatcher.getBenchmarksReports(buildNumber, target).then { reports -> response.send(reports.joinToString(", ", "[", "]")) }.catch { response.sendStatus(400) } }) router.get("/clear", { _, response -> CachableResponseDispatcher.clear() response.sendStatus(200) }) // Main page. router.get("/", { _, response -> response.render("index") }) return router } fun getBuildsInfoFromArtifactory(target: String): Promise<String> { val buildsFileName = "buildsSummary.csv" val artifactoryBuildsDirectory = "builds" return UrlNetworkConnector(artifactoryUrl).sendRequest(RequestMethod.GET, "$artifactoryBuildsDirectory/$target/$buildsFileName") } fun BenchmarksReport.normalizeBenchmarksSet(dataForNormalization: Map<String, List<BenchmarkResult>>): BenchmarksReport { val resultBenchmarksList = benchmarks.map { benchmarksList -> benchmarksList.value.map { NormalizedMeanVarianceBenchmark(it.name, it.status, it.score, it.metric, it.runtimeInUs, it.repeat, it.warmup, (it as MeanVarianceBenchmark).variance, dataForNormalization[benchmarksList.key]?.get(0)?.score?.let { golden -> it.score / golden } ?: 0.0) } }.flatten() return BenchmarksReport(env, resultBenchmarksList, compiler) }
apache-2.0
4d967fe4b7953db3f389f6152ec3f4fe
50.152648
146
0.548829
5.46952
false
false
false
false
androidx/androidx
graphics/graphics-core/src/main/java/androidx/hardware/SyncFence.kt
3
5318
/* * 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. */ package androidx.hardware import android.os.Build import androidx.annotation.RequiresApi import java.util.concurrent.TimeUnit import java.util.concurrent.locks.ReentrantLock import kotlin.concurrent.withLock /** * A SyncFence represents a synchronization primitive which signals when hardware buffers have * completed work on a particular resource. * * For example, GPU rendering to a frame buffer may generate a synchronization fence which signals * when rendering has completed. * * When the fence signals, then the backing storage for the framebuffer may be safely read from, * such as for display or media encoding. */ @RequiresApi(Build.VERSION_CODES.KITKAT) class SyncFence(private var fd: Int) : AutoCloseable { private val fenceLock = ReentrantLock() /** * Checks if the SyncFence object is valid. * @return `true` if it is valid, `false` otherwise */ fun isValid(): Boolean = fenceLock.withLock { fd != -1 } /** * Returns the time that the fence signaled in the [CLOCK_MONOTONIC] time domain. * This returns [SyncFence.SIGNAL_TIME_INVALID] if the SyncFence is invalid. */ // Relies on NDK APIs sync_file_info/sync_file_info_free which were introduced in API level 26 @RequiresApi(Build.VERSION_CODES.O) fun getSignalTime(): Long = fenceLock.withLock { if (isValid()) { nGetSignalTime(fd) } else { SIGNAL_TIME_INVALID } } // Accessed through JNI to obtain the dup'ed file descriptor in a thread safe manner private fun dupeFileDescriptor(): Int = fenceLock.withLock { return if (isValid()) { nDup(fd) } else { -1 } } /** * Waits for a SyncFence to signal for up to the [timeoutNanos] duration. An invalid SyncFence, * that is if [isValid] is `false`, is treated equivalently to a SyncFence that has already * signaled. That is, wait() will immediately return `true`. * * @param timeoutNanos Timeout duration in nanoseconds. Providing a negative value will wait * indefinitely until the fence is signaled * @return `true` if the fence signaled or is not valid, `false` otherwise */ fun await(timeoutNanos: Long): Boolean { fenceLock.withLock { if (isValid()) { val timeout: Int if (timeoutNanos < 0) { timeout = -1 } else { timeout = TimeUnit.NANOSECONDS.toMillis(timeoutNanos).toInt() } return nWait(fd, timeout) } else { // invalid file descriptors will always return true return true } } } /** * Waits forever for a SyncFence to signal. An invalid SyncFence is treated equivalently to a * SyncFence that has already signaled. That is, wait() will immediately return `true`. * * @return `true` if the fence signaled or isn't valid, `false` otherwise */ fun awaitForever(): Boolean = await(-1) /** * Close the SyncFence instance. After this method is invoked the fence is invalid. That * is subsequent calls to [isValid] will return `false` */ override fun close() { fenceLock.withLock { if (isValid()) { nClose(fd) fd = -1 } } } protected fun finalize() { close() } // SyncFence in the framework implements timeoutNanos as a long but // it is casted down to an int within native code and eventually calls into // the poll API which consumes a timeout in nanoseconds as an int. private external fun nWait(fd: Int, timeoutMillis: Int): Boolean private external fun nGetSignalTime(fd: Int): Long private external fun nClose(fd: Int) /** * Dup the provided file descriptor, this method requires the caller to acquire the corresponding * [fenceLock] before invoking */ private external fun nDup(fd: Int): Int companion object { /** * An invalid signal time. Represents either the signal time for a SyncFence that isn't * valid (that is, [isValid] is `false`), or if an error occurred while attempting to * retrieve the signal time. */ const val SIGNAL_TIME_INVALID: Long = -1L /** * A pending signal time. This is equivalent to the max value of a long, representing an * infinitely far point in the future. */ const val SIGNAL_TIME_PENDING: Long = Long.MAX_VALUE init { System.loadLibrary("sync-fence") } } }
apache-2.0
85e9af051433ba332ca2d1794e74b326
33.538961
101
0.638774
4.510602
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantSuspendModifierInspection.kt
5
4042
// 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.inspections import com.intellij.codeInspection.IntentionWrapper import com.intellij.codeInspection.LocalInspectionToolSession import com.intellij.codeInspection.ProblemsHolder import com.intellij.psi.PsiElementVisitor import org.jetbrains.kotlin.config.LanguageFeature import org.jetbrains.kotlin.descriptors.Modality import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithContent import org.jetbrains.kotlin.idea.highlighter.SuspendCallKind import org.jetbrains.kotlin.idea.highlighter.getSuspendCallKind import org.jetbrains.kotlin.idea.quickfix.RemoveModifierFixBase import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.KtNamedFunction import org.jetbrains.kotlin.psi.namedFunctionVisitor import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType import org.jetbrains.kotlin.psi.psiUtil.isAncestor import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.model.VariableAsFunctionResolvedCall import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection class RedundantSuspendModifierInspection : AbstractKotlinInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor { return namedFunctionVisitor(fun(function) { if (!function.languageVersionSettings.supportsFeature(LanguageFeature.Coroutines)) return val suspendModifier = function.modifierList?.getModifier(KtTokens.SUSPEND_KEYWORD) ?: return if (!function.hasBody()) return if (function.hasModifier(KtTokens.OVERRIDE_KEYWORD) || function.hasModifier(KtTokens.ACTUAL_KEYWORD)) return val context = function.analyzeWithContent() val descriptor = context[BindingContext.FUNCTION, function] ?: return if (descriptor.modality == Modality.OPEN) return if (function.hasSuspendCalls(context)) return if (function.hasAnyUnresolvedCalls(context)) return holder.registerProblem( suspendModifier, KotlinBundle.message("redundant.suspend.modifier"), IntentionWrapper(RemoveModifierFixBase(function, KtTokens.SUSPEND_KEYWORD, isRedundant = true)) ) }) } private fun KtNamedFunction.hasAnyUnresolvedCalls(context: BindingContext): Boolean { return context.diagnostics.any { it.factory == Errors.UNRESOLVED_REFERENCE && this.isAncestor(it.psiElement) } } private fun KtNamedFunction.hasSuspendCalls(bindingContext: BindingContext): Boolean { val selfDescriptor = bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, this] ?: return false return anyDescendantOfType<KtExpression> { expression -> val kind = getSuspendCallKind(expression, bindingContext) ?: return@anyDescendantOfType false if (kind is SuspendCallKind.FunctionCall) { val resolvedCall = kind.element.getResolvedCall(bindingContext) if (resolvedCall != null) { val isRecursiveCall = when (resolvedCall) { is VariableAsFunctionResolvedCall -> selfDescriptor == resolvedCall.functionCall.candidateDescriptor else -> selfDescriptor == resolvedCall.candidateDescriptor } if (isRecursiveCall) { return@anyDescendantOfType false } } } return@anyDescendantOfType true } } }
apache-2.0
a7b6ca849a7ca67e6048bd3d8fa2b7ca
47.698795
132
0.734537
5.454791
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/tests/testData/refactoring/inline/namedFunction/fromKotlinToJava/conflictWithSuperFunctions.kt
12
478
// ERROR: Inlined function overrides function Adw1.a\nInlined function overrides function Asswe.a\nInlined function overrides function D.a open class A { open fun a() = Unit fun ds() = Unit } open class B: A() { override fun a() = Unit open fun c() = a() } open class D: B() { override fun a() = Unit override fun c() = a() } interface Asswe { fun a() } class M: D(), Adw1, Asswe { override fun <caret>a() = Unit override fun c() = a() }
apache-2.0
7663ce910919db097b6b34bb5a1bdc85
18.16
138
0.608787
3.165563
false
false
false
false
GunoH/intellij-community
platform/workspaceModel/storage/gen/com/intellij/workspaceModel/storage/bridgeEntities/ModuleCustomImlDataEntityImpl.kt
2
10905
// 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.workspaceModel.storage.bridgeEntities import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.EntityLink import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.UsedClassesCollector import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList import com.intellij.workspaceModel.storage.impl.extractOneToOneParent import com.intellij.workspaceModel.storage.impl.updateOneToOneParentOfChild import com.intellij.workspaceModel.storage.url.VirtualFileUrl import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Child @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class ModuleCustomImlDataEntityImpl(val dataSource: ModuleCustomImlDataEntityData) : ModuleCustomImlDataEntity, WorkspaceEntityBase() { companion object { internal val MODULE_CONNECTION_ID: ConnectionId = ConnectionId.create(ModuleEntity::class.java, ModuleCustomImlDataEntity::class.java, ConnectionId.ConnectionType.ONE_TO_ONE, false) val connections = listOf<ConnectionId>( MODULE_CONNECTION_ID, ) } override val module: ModuleEntity get() = snapshot.extractOneToOneParent(MODULE_CONNECTION_ID, this)!! override val rootManagerTagCustomData: String? get() = dataSource.rootManagerTagCustomData override val customModuleOptions: Map<String, String> get() = dataSource.customModuleOptions override val entitySource: EntitySource get() = dataSource.entitySource override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(result: ModuleCustomImlDataEntityData?) : ModifiableWorkspaceEntityBase<ModuleCustomImlDataEntity, ModuleCustomImlDataEntityData>( result), ModuleCustomImlDataEntity.Builder { constructor() : this(ModuleCustomImlDataEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity ModuleCustomImlDataEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // After adding entity data to the builder, we need to unbind it and move the control over entity data to builder // Builder may switch to snapshot at any moment and lock entity data to modification this.currentEntityData = null // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isEntitySourceInitialized()) { error("Field WorkspaceEntity#entitySource should be initialized") } if (_diff != null) { if (_diff.extractOneToOneParent<WorkspaceEntityBase>(MODULE_CONNECTION_ID, this) == null) { error("Field ModuleCustomImlDataEntity#module should be initialized") } } else { if (this.entityLinks[EntityLink(false, MODULE_CONNECTION_ID)] == null) { error("Field ModuleCustomImlDataEntity#module should be initialized") } } if (!getEntityData().isCustomModuleOptionsInitialized()) { error("Field ModuleCustomImlDataEntity#customModuleOptions should be initialized") } } override fun connectionIdList(): List<ConnectionId> { return connections } // Relabeling code, move information from dataSource to this builder override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) { dataSource as ModuleCustomImlDataEntity if (this.entitySource != dataSource.entitySource) this.entitySource = dataSource.entitySource if (this.rootManagerTagCustomData != dataSource?.rootManagerTagCustomData) this.rootManagerTagCustomData = dataSource.rootManagerTagCustomData if (this.customModuleOptions != dataSource.customModuleOptions) this.customModuleOptions = dataSource.customModuleOptions.toMutableMap() if (parents != null) { val moduleNew = parents.filterIsInstance<ModuleEntity>().single() if ((this.module as WorkspaceEntityBase).id != (moduleNew as WorkspaceEntityBase).id) { this.module = moduleNew } } } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData(true).entitySource = value changedProperty.add("entitySource") } override var module: ModuleEntity get() { val _diff = diff return if (_diff != null) { _diff.extractOneToOneParent(MODULE_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, MODULE_CONNECTION_ID)]!! as ModuleEntity } else { this.entityLinks[EntityLink(false, MODULE_CONNECTION_ID)]!! as ModuleEntity } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*, *> && value.diff == null) { if (value is ModifiableWorkspaceEntityBase<*, *>) { value.entityLinks[EntityLink(true, MODULE_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(value) } if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*, *> || value.diff != null)) { _diff.updateOneToOneParentOfChild(MODULE_CONNECTION_ID, this, value) } else { if (value is ModifiableWorkspaceEntityBase<*, *>) { value.entityLinks[EntityLink(true, MODULE_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable this.entityLinks[EntityLink(false, MODULE_CONNECTION_ID)] = value } changedProperty.add("module") } override var rootManagerTagCustomData: String? get() = getEntityData().rootManagerTagCustomData set(value) { checkModificationAllowed() getEntityData(true).rootManagerTagCustomData = value changedProperty.add("rootManagerTagCustomData") } override var customModuleOptions: Map<String, String> get() = getEntityData().customModuleOptions set(value) { checkModificationAllowed() getEntityData(true).customModuleOptions = value changedProperty.add("customModuleOptions") } override fun getEntityClass(): Class<ModuleCustomImlDataEntity> = ModuleCustomImlDataEntity::class.java } } class ModuleCustomImlDataEntityData : WorkspaceEntityData<ModuleCustomImlDataEntity>() { var rootManagerTagCustomData: String? = null lateinit var customModuleOptions: Map<String, String> fun isCustomModuleOptionsInitialized(): Boolean = ::customModuleOptions.isInitialized override fun wrapAsModifiable(diff: MutableEntityStorage): WorkspaceEntity.Builder<ModuleCustomImlDataEntity> { val modifiable = ModuleCustomImlDataEntityImpl.Builder(null) modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() return modifiable } override fun createEntity(snapshot: EntityStorage): ModuleCustomImlDataEntity { return getCached(snapshot) { val entity = ModuleCustomImlDataEntityImpl(this) entity.snapshot = snapshot entity.id = createEntityId() entity } } override fun getEntityInterface(): Class<out WorkspaceEntity> { return ModuleCustomImlDataEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity { return ModuleCustomImlDataEntity(customModuleOptions, entitySource) { this.rootManagerTagCustomData = [email protected] this.module = parents.filterIsInstance<ModuleEntity>().single() } } override fun getRequiredParents(): List<Class<out WorkspaceEntity>> { val res = mutableListOf<Class<out WorkspaceEntity>>() res.add(ModuleEntity::class.java) return res } override fun equals(other: Any?): Boolean { if (other == null) return false if (this.javaClass != other.javaClass) return false other as ModuleCustomImlDataEntityData if (this.entitySource != other.entitySource) return false if (this.rootManagerTagCustomData != other.rootManagerTagCustomData) return false if (this.customModuleOptions != other.customModuleOptions) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this.javaClass != other.javaClass) return false other as ModuleCustomImlDataEntityData if (this.rootManagerTagCustomData != other.rootManagerTagCustomData) return false if (this.customModuleOptions != other.customModuleOptions) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + rootManagerTagCustomData.hashCode() result = 31 * result + customModuleOptions.hashCode() return result } override fun hashCodeIgnoringEntitySource(): Int { var result = javaClass.hashCode() result = 31 * result + rootManagerTagCustomData.hashCode() result = 31 * result + customModuleOptions.hashCode() return result } override fun collectClassUsagesData(collector: UsedClassesCollector) { this.customModuleOptions?.let { collector.add(it::class.java) } collector.sameForAllEntities = false } }
apache-2.0
cac206ab798734c44a1a4e7ff491b134
38.79927
148
0.720037
5.569459
false
false
false
false
GunoH/intellij-community
plugins/git4idea/src/git4idea/stash/ui/GitStashProvider.kt
4
10005
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package git4idea.stash.ui import com.intellij.dvcs.ui.RepositoryChangesBrowserNode import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.components.service import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.project.Project import com.intellij.openapi.util.ClearableLazyValue import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.Key import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vcs.FilePath import com.intellij.openapi.vcs.FileStatus import com.intellij.openapi.vcs.VcsBundle import com.intellij.openapi.vcs.VcsException import com.intellij.openapi.vcs.changes.Change import com.intellij.openapi.vcs.changes.ChangesUtil import com.intellij.openapi.vcs.changes.actions.ShowDiffWithLocalAction import com.intellij.openapi.vcs.changes.actions.diff.ChangeDiffRequestProducer import com.intellij.openapi.vcs.changes.savedPatches.SavedPatchesProvider import com.intellij.openapi.vcs.changes.savedPatches.SavedPatchesTree import com.intellij.openapi.vcs.changes.ui.* import com.intellij.openapi.vfs.VirtualFile import com.intellij.ui.SimpleTextAttributes import com.intellij.util.FontUtil import com.intellij.util.text.DateFormatUtil import com.intellij.vcs.log.Hash import com.intellij.vcs.log.ui.render.LabelIconCache import git4idea.i18n.GitBundle import git4idea.repo.GitRepository import git4idea.repo.GitRepositoryManager import git4idea.stash.GitStashCache import git4idea.stash.GitStashTracker import git4idea.stash.GitStashTrackerListener import git4idea.stash.isNotEmpty import git4idea.ui.StashInfo import git4idea.ui.StashInfo.Companion.subject import one.util.streamex.StreamEx import org.jetbrains.annotations.Nls import java.util.concurrent.CancellationException import java.util.concurrent.CompletableFuture import java.util.stream.Stream class GitStashProvider(val project: Project, parent: Disposable) : SavedPatchesProvider<StashInfo>, Disposable { private val iconCache = LabelIconCache() private val stashTracker get() = project.service<GitStashTracker>() private val stashCache: GitStashCache get() = project.service() override val dataClass: Class<StashInfo> get() = StashInfo::class.java override val applyAction: AnAction get() = ActionManager.getInstance().getAction(GIT_STASH_APPLY_ACTION) override val popAction: AnAction get() = ActionManager.getInstance().getAction(GIT_STASH_POP_ACTION) init { Disposer.register(parent, this) stashTracker.addListener(object : GitStashTrackerListener { override fun stashesUpdated() { stashCache.preloadStashes() } }, this) stashCache.preloadStashes() } override fun subscribeToPatchesListChanges(disposable: Disposable, listener: () -> Unit) { stashTracker.addListener(object : GitStashTrackerListener { override fun stashesUpdated() { listener() } }, disposable) } override fun isEmpty() = !stashTracker.isNotEmpty() override fun buildPatchesTree(modelBuilder: TreeModelBuilder) { val stashesMap = stashTracker.stashes val stashesRoot = SavedPatchesTree.TagWithCounterChangesBrowserNode(GitBundle.message("stash.root.node.title")) modelBuilder.insertSubtreeRoot(stashesRoot) for ((root, stashesList) in stashesMap) { val rootNode = if (stashesMap.size > 1 && !(stashesList is GitStashTracker.Stashes.Loaded && stashesList.stashes.isEmpty())) { createRootNode(root)?.also { modelBuilder.insertSubtreeRoot(it, stashesRoot) } ?: stashesRoot } else { stashesRoot } when (stashesList) { is GitStashTracker.Stashes.Error -> { modelBuilder.insertErrorNode(stashesList.error, rootNode) } is GitStashTracker.Stashes.Loaded -> { for (stash in stashesList.stashes) { modelBuilder.insertSubtreeRoot(StashInfoChangesBrowserNode(StashObject(stash)), rootNode) } } } } } private fun createRootNode(root: VirtualFile): ChangesBrowserNode<*>? { val repository = GitRepositoryManager.getInstance(project).getRepositoryForRootQuick(root) ?: return null return StashRepositoryChangesBrowserNode(repository) } private fun TreeModelBuilder.insertErrorNode(error: VcsException, parent: ChangesBrowserNode<*>) { val errorNode = ChangesBrowserStringNode(error.localizedMessage, SimpleTextAttributes.ERROR_ATTRIBUTES) insertSubtreeRoot(errorNode, parent) } override fun getData(dataId: String, selectedObjects: Stream<SavedPatchesProvider.PatchObject<*>>): Any? { if (STASH_INFO.`is`(dataId)) { return StreamEx.of(selectedObjects.map(SavedPatchesProvider.PatchObject<*>::data)).filterIsInstance(dataClass).toList() } return null } override fun dispose() { stashCache.clear() } private data class MyTag(@Nls private val text: String, private val hash: Hash) : ChangesBrowserNode.Tag { override fun toString(): String = text } private class StashInfoChangesBrowserNode(private val stash: StashObject) : ChangesBrowserNode<StashObject>(stash) { override fun render(renderer: ChangesBrowserNodeRenderer, selected: Boolean, expanded: Boolean, hasFocus: Boolean) { renderer.append(stash.data.subject) renderer.toolTipText = VcsBundle.message("saved.patch.created.on.date.at.time.tooltip", stash.data.stash, DateFormatUtil.formatDate(stash.data.authorTime), DateFormatUtil.formatTime(stash.data.authorTime)) } override fun getTextPresentation(): String = stash.data.subject } private class StashRepositoryChangesBrowserNode(repository: GitRepository) : RepositoryChangesBrowserNode(repository) { private val stashCount = ClearableLazyValue.create { VcsTreeModelData.children(this).userObjects(StashObject::class.java).size } override fun getCountText() = FontUtil.spaceAndThinSpace() + stashCount.value override fun resetCounters() { super.resetCounters() stashCount.drop() } } inner class StashObject(override val data: StashInfo) : SavedPatchesProvider.PatchObject<StashInfo> { override fun cachedChanges(): Collection<SavedPatchesProvider.ChangeObject>? { return stashCache.getCachedData(data)?.toChangeObjects() } override fun loadChanges(): CompletableFuture<SavedPatchesProvider.LoadingResult>? { val loadStashData = stashCache.loadStashData(data) val processResults = loadStashData?.thenApply { stashData -> when (stashData) { is GitStashCache.StashData.Changes -> { SavedPatchesProvider.LoadingResult.Changes(stashData.toChangeObjects()) } is GitStashCache.StashData.Error -> SavedPatchesProvider.LoadingResult.Error(stashData.error) } } processResults?.propagateCancellationTo(loadStashData) return processResults } private fun GitStashCache.StashData.Changes.toChangeObjects(): List<GitStashChange> { val stashChanges = changes.map { GitStashChange(it, null) } val otherChanges = parentCommits.flatMap { parent -> val tag: ChangesBrowserNode.Tag = MyTag(StringUtil.capitalize(parent.subject.substringBefore(":")), parent.id) parent.changes.map { GitStashChange(it, tag) } } return stashChanges + otherChanges } override fun getDiffPreviewTitle(changeName: String?): String { return changeName?.let { name -> GitBundle.message("stash.editor.diff.preview.id.change.title", data.stash.capitalize(), name) } ?: GitBundle.message("stash.editor.diff.preview.empty.title") } override fun createPainter(tree: ChangesTree, renderer: ChangesTreeCellRenderer, row: Int, selected: Boolean): SavedPatchesProvider.PatchObject.Painter { val painter = GitStashPainter(tree, renderer, iconCache) painter.customise(data, row, selected) return painter } } class GitStashChange(private val change: Change, private val changeTag: ChangesBrowserNode.Tag?) : SavedPatchesProvider.ChangeObject { override fun createDiffRequestProducer(project: Project?): ChangeDiffRequestChain.Producer? { return ChangeDiffRequestProducer.create(project, change, prepareChangeContext()) } override fun createDiffWithLocalRequestProducer(project: Project?, useBeforeVersion: Boolean): ChangeDiffRequestChain.Producer? { val changeWithLocal = ShowDiffWithLocalAction.getChangeWithLocal(change, useBeforeVersion) ?: return null return ChangeDiffRequestProducer.create(project, changeWithLocal, prepareChangeContext()) } override fun asChange(): Change = change override fun getFilePath(): FilePath = ChangesUtil.getFilePath(change) override val originalFilePath: FilePath? get() = ChangesUtil.getBeforePath(change) override fun getFileStatus(): FileStatus = change.fileStatus override fun getTag(): ChangesBrowserNode.Tag? = changeTag private fun prepareChangeContext(): Map<Key<*>, Any> { val context = mutableMapOf<Key<*>, Any>() changeTag?.let { context[ChangeDiffRequestProducer.TAG_KEY] = it } return context } } companion object { private const val GIT_STASH_APPLY_ACTION = "Git.Stash.Apply" private const val GIT_STASH_POP_ACTION = "Git.Stash.Pop" fun CompletableFuture<*>.propagateCancellationTo(future: CompletableFuture<*>) { whenComplete { _, t -> if (t is CancellationException || t is ProcessCanceledException) { future.cancel(false) } } } } }
apache-2.0
6b5f646bf86e96f9f1d4049aecf4708a
41.394068
136
0.735932
4.692777
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/commonUtils.kt
1
7839
// 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.loopToCallChain import com.intellij.psi.PsiWhiteSpace import com.intellij.psi.search.LocalSearchScope import com.intellij.psi.search.searches.ReferencesSearch import org.jetbrains.kotlin.KtNodeTypes import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.imports.importableFqName import org.jetbrains.kotlin.idea.references.KtSimpleNameReference import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.idea.references.readWriteAccess import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.PsiChildRange import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelector import org.jetbrains.kotlin.psi.psiUtil.parents import org.jetbrains.kotlin.psi.psiUtil.siblings import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluator import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstance import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull fun KtExpression.isConstant(): Boolean { val bindingContext = analyze(BodyResolveMode.PARTIAL) return ConstantExpressionEvaluator.getConstant(this, bindingContext) != null } fun KtExpression?.isTrueConstant() = this != null && node?.elementType == KtNodeTypes.BOOLEAN_CONSTANT && text == "true" fun KtExpression?.isFalseConstant() = this != null && node?.elementType == KtNodeTypes.BOOLEAN_CONSTANT && text == "false" private val ZERO_VALUES = setOf(0, 0L, 0f, 0.0) fun KtExpression.isZeroConstant(): Boolean { if (this !is KtConstantExpression) return false val bindingContext = analyze(BodyResolveMode.PARTIAL) val type = bindingContext.getType(this) ?: return false val constant = ConstantExpressionEvaluator.getConstant(this, bindingContext) ?: return false return constant.getValue(type) in ZERO_VALUES } fun KtExpression?.isVariableReference(variable: KtCallableDeclaration): Boolean { return this is KtNameReferenceExpression && this.mainReference.isReferenceTo(variable) } fun KtExpression?.isSimpleName(name: Name): Boolean { return this is KtNameReferenceExpression && this.getQualifiedExpressionForSelector() == null && this.getReferencedNameAsName() == name } fun KtCallableDeclaration.hasUsages(inElement: KtElement): Boolean { assert(inElement.isPhysical) return hasUsages(listOf(inElement)) } fun KtCallableDeclaration.hasUsages(inElements: Collection<KtElement>): Boolean { assert(this.isPhysical) // TODO: it's a temporary workaround about strange dead-lock when running inspections return inElements.any { ReferencesSearch.search(this, LocalSearchScope(it)).any() } // return ReferencesSearch.search(this, LocalSearchScope(inElements.toTypedArray())).any() } fun KtVariableDeclaration.hasWriteUsages(): Boolean { assert(this.isPhysical) if (!isVar) return false return ReferencesSearch.search(this, useScope).any { (it as? KtSimpleNameReference)?.element?.readWriteAccess(useResolveForReadWrite = true)?.isWrite == true } } fun KtCallableDeclaration.countUsages(inElement: KtElement): Int { assert(this.isPhysical) return ReferencesSearch.search(this, LocalSearchScope(inElement)).count() } fun KtCallableDeclaration.countUsages(inElements: Collection<KtElement>): Int { assert(this.isPhysical) // TODO: it's a temporary workaround about strange dead-lock when running inspections return inElements.sumBy { ReferencesSearch.search(this, LocalSearchScope(it)).count() } } fun KtCallableDeclaration.countUsages(): Int { assert(this.isPhysical) return ReferencesSearch.search(this, useScope).count() } fun KtVariableDeclaration.countWriteUsages(): Int { assert(this.isPhysical) if (!isVar) return 0 return ReferencesSearch.search(this, useScope).count { (it as? KtSimpleNameReference)?.element?.readWriteAccess(useResolveForReadWrite = true)?.isWrite == true } } fun KtVariableDeclaration.countWriteUsages(inElement: KtElement): Int { assert(this.isPhysical) if (!isVar) return 0 return ReferencesSearch.search(this, LocalSearchScope(inElement)).count { (it as? KtSimpleNameReference)?.element?.readWriteAccess(useResolveForReadWrite = true)?.isWrite == true } } fun KtVariableDeclaration.hasWriteUsages(inElement: KtElement): Boolean { assert(this.isPhysical) if (!isVar) return false return ReferencesSearch.search(this, LocalSearchScope(inElement)).any { (it as? KtSimpleNameReference)?.element?.readWriteAccess(useResolveForReadWrite = true)?.isWrite == true } } fun KtCallableDeclaration.hasDifferentSetsOfUsages(elements1: Collection<KtElement>, elements2: Collection<KtElement>): Boolean { return countUsages(elements1 - elements2) != countUsages(elements2 - elements1) } fun KtExpressionWithLabel.targetLoop(context: BindingContext? = null): KtLoopExpression? { val label = getTargetLabel() return if (label == null) { parents.firstIsInstance<KtLoopExpression>() } else { //TODO: does PARTIAL always work here? (context ?: analyze(BodyResolveMode.PARTIAL))[BindingContext.LABEL_TARGET, label] as? KtLoopExpression } } fun KtExpression.isPlusPlusOf(): KtExpression? { if (this !is KtUnaryExpression) return null if (operationToken != KtTokens.PLUSPLUS) return null return baseExpression } fun KtExpression.previousStatement(): KtExpression? { val statement = unwrapIfLabeled() if (statement.parent !is KtBlockExpression) return null return statement.siblings(forward = false, withItself = false).firstIsInstanceOrNull<KtExpression>() } fun KtExpression.nextStatement(): KtExpression? { val statement = unwrapIfLabeled() if (statement.parent !is KtBlockExpression) return null return statement.siblings(forward = true, withItself = false).firstIsInstanceOrNull<KtExpression>() } fun KtExpression.unwrapIfLabeled(): KtExpression { var statement = this while (true) { statement = statement.parent as? KtLabeledExpression ?: return statement } } fun KtLoopExpression.deleteWithLabels() { unwrapIfLabeled().delete() } fun PsiChildRange.withoutFirstStatement(): PsiChildRange { val newFirst = first!!.siblings(forward = true, withItself = false).first { it !is PsiWhiteSpace } return PsiChildRange(newFirst, last) } fun PsiChildRange.withoutLastStatement(): PsiChildRange { val newLast = last!!.siblings(forward = false, withItself = false).first { it !is PsiWhiteSpace } return PsiChildRange(first, newLast) } fun KtExpression?.extractStaticFunctionCallArguments(functionFqName: String): List<KtExpression?>? { val callExpression = when (this) { is KtDotQualifiedExpression -> selectorExpression as? KtCallExpression is KtCallExpression -> this else -> null } ?: return null val resolvedCall = callExpression.resolveToCall() ?: return null val functionDescriptor = resolvedCall.resultingDescriptor as? FunctionDescriptor ?: return null if (functionDescriptor.dispatchReceiverParameter != null || functionDescriptor.extensionReceiverParameter != null) return null if (functionDescriptor.importableFqName?.asString() != functionFqName) return null return resolvedCall.valueArgumentsByIndex?.map { it?.arguments?.singleOrNull()?.getArgumentExpression() } }
apache-2.0
f0c5c83ef6541b68658512f668483774
42.071429
158
0.77293
4.899375
false
false
false
false
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeFunctionSignatureFix.kt
1
8022
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import org.jetbrains.kotlin.descriptors.CallableDescriptor import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor.Kind.SYNTHESIZED import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.DiagnosticFactory import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde import org.jetbrains.kotlin.idea.core.KotlinNameSuggester import org.jetbrains.kotlin.idea.core.mapArgumentsToParameters import org.jetbrains.kotlin.idea.refactoring.canRefactor import org.jetbrains.kotlin.idea.refactoring.changeSignature.KotlinChangeSignatureConfiguration import org.jetbrains.kotlin.idea.refactoring.changeSignature.KotlinMethodDescriptor import org.jetbrains.kotlin.idea.refactoring.changeSignature.modify import org.jetbrains.kotlin.idea.refactoring.changeSignature.runChangeSignature import org.jetbrains.kotlin.idea.util.getDataFlowAwareTypes import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.resolve.calls.util.getCall import org.jetbrains.kotlin.resolve.calls.util.getType import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.checker.KotlinTypeChecker abstract class ChangeFunctionSignatureFix( element: PsiElement, protected val functionDescriptor: FunctionDescriptor ) : KotlinQuickFixAction<PsiElement>(element) { override fun getFamilyName() = FAMILY_NAME override fun startInWriteAction() = false override fun isAvailable(project: Project, editor: Editor?, file: KtFile): Boolean { val declarations = DescriptorToSourceUtilsIde.getAllDeclarations(project, functionDescriptor) return declarations.isNotEmpty() && declarations.all { it.isValid && it.canRefactor() } } protected fun getNewArgumentName(argument: ValueArgument, validator: Function1<String, Boolean>): String { val expression = KtPsiUtil.deparenthesize(argument.getArgumentExpression()) val argumentName = argument.getArgumentName()?.asName?.asString() ?: (expression as? KtNameReferenceExpression)?.getReferencedName()?.takeIf { !isSpecialName(it) } return when { argumentName != null -> KotlinNameSuggester.suggestNameByName(argumentName, validator) expression != null -> { val bindingContext = expression.analyze(BodyResolveMode.PARTIAL) val expressionText = expression.text if (isSpecialName(expressionText)) { val type = expression.getType(bindingContext) if (type != null) { return KotlinNameSuggester.suggestNamesByType(type, validator, "param").first() } } KotlinNameSuggester.suggestNamesByExpressionAndType(expression, null, bindingContext, validator, "param").first() } else -> KotlinNameSuggester.suggestNameByName("param", validator) } } private fun isSpecialName(name: String): Boolean { return name == "it" || name == "field" } companion object : KotlinSingleIntentionActionFactoryWithDelegate<KtCallElement, CallableDescriptor>() { override fun getElementOfInterest(diagnostic: Diagnostic): KtCallElement? = diagnostic.psiElement.getStrictParentOfType() override fun extractFixData(element: KtCallElement, diagnostic: Diagnostic): CallableDescriptor? { return DiagnosticFactory.cast(diagnostic, Errors.TOO_MANY_ARGUMENTS, Errors.NO_VALUE_FOR_PARAMETER).a } override fun createFix(originalElement: KtCallElement, data: CallableDescriptor): ChangeFunctionSignatureFix? { val functionDescriptor = data as? FunctionDescriptor ?: (data as? ValueParameterDescriptor)?.containingDeclaration as? FunctionDescriptor ?: return null if (functionDescriptor.kind == SYNTHESIZED) return null if (data is ValueParameterDescriptor) { return RemoveParameterFix(originalElement, functionDescriptor, data) } else { val parameters = functionDescriptor.valueParameters val arguments = originalElement.valueArguments if (arguments.size > parameters.size) { val bindingContext = originalElement.analyze() val call = originalElement.getCall(bindingContext) ?: return null val argumentToParameter = call.mapArgumentsToParameters(functionDescriptor) val hasTypeMismatches = argumentToParameter.any { (argument, parameter) -> val argumentTypes = argument.getArgumentExpression()?.let { getDataFlowAwareTypes( it, bindingContext ) } argumentTypes?.none { dataFlowAwareType -> KotlinTypeChecker.DEFAULT.isSubtypeOf(dataFlowAwareType, parameter.type) } ?: true } val kind = when { hasTypeMismatches -> AddFunctionParametersFix.Kind.ChangeSignature else -> AddFunctionParametersFix.Kind.AddParameterGeneric } return AddFunctionParametersFix(originalElement, functionDescriptor, kind) } } return null } private class RemoveParameterFix( element: PsiElement, functionDescriptor: FunctionDescriptor, private val parameterToRemove: ValueParameterDescriptor ) : ChangeFunctionSignatureFix(element, functionDescriptor) { override fun getText() = KotlinBundle.message("fix.change.signature.remove.parameter", parameterToRemove.name.asString()) override fun invoke(project: Project, editor: Editor?, file: KtFile) { runRemoveParameter(parameterToRemove, element ?: return, editor) } } val FAMILY_NAME = KotlinBundle.message("fix.change.signature.family") fun runRemoveParameter(parameterDescriptor: ValueParameterDescriptor, context: PsiElement, editor: Editor?) { val functionDescriptor = parameterDescriptor.containingDeclaration as FunctionDescriptor runChangeSignature( context.project, editor, functionDescriptor, object : KotlinChangeSignatureConfiguration { override fun configure(originalDescriptor: KotlinMethodDescriptor): KotlinMethodDescriptor { return originalDescriptor.modify { descriptor -> val index = if (descriptor.receiver != null) parameterDescriptor.index + 1 else parameterDescriptor.index descriptor.removeParameter(index) } } override fun performSilently(affectedFunctions: Collection<PsiElement>) = true override fun forcePerformForSelectedFunctionOnly() = false }, context, KotlinBundle.message("fix.change.signature.remove.parameter.command", parameterDescriptor.name.asString()) ) } } }
apache-2.0
02b226b10293b521a85c491a6e500489
50.095541
158
0.67826
6.045215
false
false
false
false
jwren/intellij-community
platform/lang-impl/src/com/intellij/codeInsight/editorActions/ReaderModeFileEditorListener.kt
5
1948
// 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.codeInsight.editorActions import com.intellij.codeInsight.actions.ReaderModeSettings import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.editor.colors.EditorColorsListener import com.intellij.openapi.editor.colors.EditorColorsManager import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileEditor.FileEditorManagerListener import com.intellij.openapi.fileEditor.ex.FileEditorWithProvider import com.intellij.openapi.fileEditor.impl.text.PsiAwareTextEditorImpl import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileListener import com.intellij.openapi.vfs.VirtualFilePropertyEvent private class ReaderModeFileEditorListener : FileEditorManagerListener { override fun fileOpenedSync(source: FileEditorManager, file: VirtualFile, editorsWithProviders: List<FileEditorWithProvider>) { val project = source.project val fileEditor = editorsWithProviders.firstNotNullOfOrNull { it.fileEditor as? PsiAwareTextEditorImpl } ?: return file.fileSystem.addVirtualFileListener(object : VirtualFileListener { override fun propertyChanged(event: VirtualFilePropertyEvent) { if (event.propertyName == VirtualFile.PROP_WRITABLE) { ReaderModeSettings.applyReaderMode(project, fileEditor.editor, file, fileIsOpenAlready = true, forceUpdate = true) } } }, fileEditor) if (!ReaderModeSettings.getInstance(project).enabled) { return } ReaderModeSettings.applyReaderMode(project, fileEditor.editor, file) ApplicationManager.getApplication().messageBus.connect(fileEditor).subscribe(EditorColorsManager.TOPIC, EditorColorsListener { ReaderModeSettings.applyReaderMode(project, fileEditor.editor, file, fileIsOpenAlready = true) }) } }
apache-2.0
c18d9834417542be3720a7c470af2631
48.974359
130
0.810575
4.882206
false
false
false
false
jwren/intellij-community
platform/projectModel-impl/src/com/intellij/workspaceModel/ide/WorkspaceModelTopics.kt
1
4684
// 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.workspaceModel.ide import com.intellij.diagnostic.ActivityCategory import com.intellij.diagnostic.StartUpMeasurer import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import com.intellij.util.containers.ContainerUtil import com.intellij.util.messages.MessageBus import com.intellij.util.messages.MessageBusConnection import com.intellij.util.messages.Topic import com.intellij.workspaceModel.storage.VersionedStorageChange import java.util.* interface WorkspaceModelChangeListener : EventListener { fun beforeChanged(event: VersionedStorageChange) {} fun changed(event: VersionedStorageChange) {} } /** * Topics to subscribe to Workspace changes * * Please use [subscribeImmediately] and [subscribeAfterModuleLoading] to subscribe to changes */ class WorkspaceModelTopics : Disposable { companion object { /** Please use [subscribeImmediately] and [subscribeAfterModuleLoading] to subscribe to changes */ @Topic.ProjectLevel private val CHANGED = Topic(WorkspaceModelChangeListener::class.java, Topic.BroadcastDirection.NONE, true) @JvmStatic fun getInstance(project: Project): WorkspaceModelTopics = project.service() } private val allEvents = ContainerUtil.createConcurrentList<EventsDispatcher>() private var sendToQueue = true var modulesAreLoaded = false /** * Subscribe to topic and start to receive changes immediately. * * Topic is project-level only without broadcasting - connection expected to be to project message bus only. */ fun subscribeImmediately(connection: MessageBusConnection, listener: WorkspaceModelChangeListener) { connection.subscribe(CHANGED, listener) } /** * Subscribe to the topic and start to receive changes only *after* all the modules get loaded. * All the events that will be fired before the modules loading, will be collected to the queue. After the modules are loaded, all events * from the queue will be dispatched to listener under the write action and the further events will be dispatched to listener * without passing to event queue. * * Topic is project-level only without broadcasting - connection expected to be to project message bus only. */ fun subscribeAfterModuleLoading(connection: MessageBusConnection, listener: WorkspaceModelChangeListener) { if (!sendToQueue) { subscribeImmediately(connection, listener) } else { val queue = EventsDispatcher(listener) allEvents += queue subscribeImmediately(connection, queue) } } fun syncPublisher(messageBus: MessageBus): WorkspaceModelChangeListener = messageBus.syncPublisher(CHANGED) fun notifyModulesAreLoaded() { val activity = StartUpMeasurer.startActivity("postponed events sending", ActivityCategory.DEFAULT) sendToQueue = false if (allEvents.isNotEmpty() && allEvents.any { it.events.isNotEmpty() }) { val activityInQueue = activity.startChild("events sending (in queue)") val application = ApplicationManager.getApplication() application.invokeAndWait { application.runWriteAction { val innerActivity = activityInQueue.endAndStart("events sending") allEvents.forEach { queue -> queue.collectToQueue = false queue.events.forEach { (isBefore, event) -> if (isBefore) queue.originalListener.beforeChanged(event) else queue.originalListener.changed(event) } queue.events.clear() } innerActivity.end() } } } else { allEvents.forEach { queue -> queue.collectToQueue = false } } allEvents.clear() modulesAreLoaded = true activity.end() } private class EventsDispatcher(val originalListener: WorkspaceModelChangeListener) : WorkspaceModelChangeListener { val events = mutableListOf<Pair<Boolean, VersionedStorageChange>>() var collectToQueue = true override fun beforeChanged(event: VersionedStorageChange) { if (collectToQueue) { events += true to event } else { originalListener.beforeChanged(event) } } override fun changed(event: VersionedStorageChange) { if (collectToQueue) { events += false to event } else { originalListener.changed(event) } } } override fun dispose() { allEvents.forEach { it.events.clear() } allEvents.clear() } }
apache-2.0
d6f09cac63eb991e92e30e0724c87c43
35.59375
139
0.728864
4.998933
false
false
false
false
OlegAndreych/work_calendar
src/main/kotlin/org/andreych/workcalendar/datasource/CalendarDataRetriever.kt
1
1544
package org.andreych.workcalendar.datasource import com.fasterxml.jackson.databind.ObjectMapper import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.async import kotlinx.coroutines.withContext import org.andreych.workcalendar.datasource.model.YearData import org.slf4j.LoggerFactory import org.springframework.boot.web.client.RestTemplateBuilder import org.springframework.web.client.RestTemplate import java.time.LocalDate class CalendarDataRetriever( restTemplateBuilder: RestTemplateBuilder, private val objectMapper: ObjectMapper ) { companion object { private const val URL_TEMPLATE = "/data/ru/{year}/calendar.json" private val LOG = LoggerFactory.getLogger(CalendarDataRetriever::class.java) } private val restTemplate: RestTemplate = restTemplateBuilder .rootUri("http://xmlcalendar.ru") .build() suspend fun getData(): Pair<String?, YearData> { LOG.info("Fetching calendar data from government service.") val deferred = withContext(Dispatchers.IO) { return@withContext async { val yearParam = mapOf("year" to LocalDate.now().year) val response: String? = restTemplate.getForObject(URL_TEMPLATE, String::class.java, yearParam) val value = objectMapper.readValue(response, YearData::class.java) return@async Pair(response, value) } } val result = deferred.await() LOG.info("Calendar data has been fetched.") return result } }
apache-2.0
e2bba5dfc5a07ec858887cda2740835a
36.682927
110
0.709845
4.693009
false
false
false
false
vector-im/vector-android
vector/src/main/java/im/vector/util/AssetReader.kt
2
2349
/* * Copyright 2018 New Vector Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package im.vector.util import android.content.Context import org.matrix.androidsdk.core.Log import java.io.InputStreamReader /** * Singleton to read asset files */ object AssetReader { /* ========================================================================================== * CACHE * ========================================================================================== */ private val cache = HashMap<String, String>() /** * Read an asset from resource and return a String or null in cas of error. * * @param assetFilename Asset filename * @return the content of the asset file */ fun readAssetFile(context: Context, assetFilename: String): String? { // Check if it is available in cache if (cache.contains(assetFilename)) { return cache[assetFilename] } var assetContent: String? = null try { val inputStream = context.assets.open(assetFilename) val buffer = CharArray(1024) val out = StringBuilder() val inputStreamReader = InputStreamReader(inputStream, "UTF-8") while (true) { val rsz = inputStreamReader.read(buffer, 0, buffer.size) if (rsz < 0) break out.append(buffer, 0, rsz) } assetContent = out.toString() // Keep in cache cache[assetFilename] = assetContent inputStreamReader.close() inputStream.close() } catch (e: Exception) { Log.e("AssetReader", "## readAssetFile() failed : " + e.message, e) } return assetContent } fun clearCache() { cache.clear() } }
apache-2.0
ef9410c845eafa9a29c9508b4a7b0309
29.921053
100
0.566198
4.793878
false
false
false
false
vector-im/vector-android
vector/src/main/java/im/vector/activity/HistoricalRoomsActivity.kt
2
10474
/* * Copyright 2018 New Vector Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package im.vector.activity import android.app.SearchManager import android.content.Context import android.os.Handler import android.os.Looper import android.text.TextUtils import android.view.View import android.widget.TextView import android.widget.Toast import androidx.appcompat.widget.SearchView import androidx.core.view.isVisible import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.RecyclerView import butterknife.BindView import im.vector.Matrix import im.vector.R import im.vector.adapters.AbsAdapter import im.vector.adapters.HomeRoomAdapter import im.vector.extensions.withoutLeftMargin import im.vector.ui.themes.ActivityOtherThemes import im.vector.util.RoomUtils import im.vector.view.EmptyViewItemDecoration import im.vector.view.SimpleDividerItemDecoration import org.jetbrains.anko.doAsync import org.jetbrains.anko.uiThread import org.matrix.androidsdk.MXSession import org.matrix.androidsdk.core.Log import org.matrix.androidsdk.core.callback.ApiCallback import org.matrix.androidsdk.core.model.MatrixError import org.matrix.androidsdk.data.Room import java.util.* /** * Displays the historical rooms list */ class HistoricalRoomsActivity : VectorAppCompatActivity(), SearchView.OnQueryTextListener, HomeRoomAdapter.OnSelectRoomListener, AbsAdapter.MoreRoomActionListener, RoomUtils.HistoricalRoomActionListener { @BindView(R.id.historical_search_view) internal lateinit var mSearchView: SearchView @BindView(R.id.historical_recycler_view) internal lateinit var mHistoricalRecyclerView: androidx.recyclerview.widget.RecyclerView @BindView(R.id.historical_no_results) internal lateinit var mHistoricalPlaceHolder: TextView // historical adapter private lateinit var mHistoricalAdapter: HomeRoomAdapter // sessions private var mSession: MXSession? = null /* * ********************************************************************************************* * Activity lifecycle * ********************************************************************************************* */ override fun getOtherThemes() = ActivityOtherThemes.Home override fun getLayoutRes() = R.layout.activity_historical override fun getTitleRes() = R.string.title_activity_historical override fun initUiAndData() { if (CommonActivityUtils.shouldRestartApp(this)) { Log.e(LOG_TAG, "Restart the application.") CommonActivityUtils.restartApp(this) return } if (CommonActivityUtils.isGoingToSplash(this)) { Log.d(LOG_TAG, "onCreate : Going to splash screen") return } initViews() } override fun onResume() { super.onResume() refreshHistorical() } override fun onLowMemory() { super.onLowMemory() CommonActivityUtils.onLowMemory(this) } override fun onTrimMemory(level: Int) { super.onTrimMemory(level) CommonActivityUtils.onTrimMemory(this, level) } /* * ********************************************************************************************* * UI management * ********************************************************************************************* */ private fun initViews() { // Waiting View waitingView = findViewById(R.id.historical_waiting_view) // Toolbar configureToolbar() mSession = Matrix.getInstance(this).defaultSession val margin = resources.getDimension(R.dimen.item_decoration_left_margin).toInt() mHistoricalAdapter = HomeRoomAdapter(this, R.layout.adapter_item_room_view, this, null, this) mHistoricalRecyclerView.let { it.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(this, RecyclerView.VERTICAL, false) it.setHasFixedSize(true) it.isNestedScrollingEnabled = false it.addItemDecoration(SimpleDividerItemDecoration(this, DividerItemDecoration.VERTICAL, margin)) it.addItemDecoration(EmptyViewItemDecoration(this, DividerItemDecoration.VERTICAL, 40, 16, 14)) it.adapter = mHistoricalAdapter } val searchManager = getSystemService(Context.SEARCH_SERVICE) as SearchManager // Remove unwanted left margin mSearchView.withoutLeftMargin() toolbar.contentInsetStartWithNavigation = 0 mSearchView.let { it.maxWidth = Integer.MAX_VALUE it.isSubmitButtonEnabled = false it.setSearchableInfo(searchManager.getSearchableInfo(componentName)) it.setOnQueryTextListener(this) } } /* * ********************************************************************************************* * historical management * ********************************************************************************************* */ private fun refreshHistorical() { val dataHandler = mSession!!.dataHandler if (!dataHandler.areLeftRoomsSynced()) { mHistoricalAdapter.setRooms(ArrayList()) showWaitingView() dataHandler.retrieveLeftRooms(object : HistoricalRoomApiCallback() { override fun onSuccess(info: Void?) { runOnUiThread { initHistoricalRoomsData() } } }) } else { initHistoricalRoomsData() } } /** * Init history rooms data */ private fun initHistoricalRoomsData() { hideWaitingView() val historicalRooms = ArrayList(mSession!!.dataHandler.leftRooms) val iterator = historicalRooms.iterator() while (iterator.hasNext()) { val room = iterator.next() if (room.isConferenceUserRoom) { iterator.remove() } } doAsync { Collections.sort(historicalRooms, RoomUtils.getHistoricalRoomsComparator(mSession, false)) uiThread { mHistoricalAdapter.setRooms(historicalRooms) } } } /* * ********************************************************************************************* * User action management * ********************************************************************************************* */ override fun onQueryTextChange(newText: String): Boolean { // compute an unique pattern if (mSession!!.dataHandler.areLeftRoomsSynced()) { // wait before really triggering the search // else a search is triggered for each new character // eg "matt" triggers // 1 - search for m // 2 - search for ma // 3 - search for mat // 4 - search for matt // whereas only one search should have been triggered // else it might trigger some lags evenif the search is done in a background thread Handler(Looper.getMainLooper()).postDelayed({ val queryText = mSearchView.query.toString() // display if the pattern matched if (TextUtils.equals(queryText, newText)) { mHistoricalAdapter.filter.filter(newText) { count -> mHistoricalRecyclerView.scrollToPosition(0) mHistoricalPlaceHolder.isVisible = count == 0 } } }, 500) } return true } override fun onQueryTextSubmit(query: String): Boolean { return true } /* * ********************************************************************************************* * Listeners * ********************************************************************************************* */ private abstract inner class HistoricalRoomApiCallback : ApiCallback<Void> { /** * Handle the end of any request : hide loading wheel and display error message if there is any * * @param errorMessage the localized error message */ protected fun onRequestDone(errorMessage: String?) { if (!isFinishing) { runOnUiThread { hideWaitingView() if (!TextUtils.isEmpty(errorMessage)) { Toast.makeText(this@HistoricalRoomsActivity, errorMessage, Toast.LENGTH_SHORT).show() } } } } override fun onNetworkError(e: Exception) { onRequestDone(e.localizedMessage) } override fun onMatrixError(e: MatrixError) { onRequestDone(e.localizedMessage) } override fun onUnexpectedError(e: Exception) { onRequestDone(e.localizedMessage) } } override fun onSelectRoom(room: Room, position: Int) { showWaitingView() CommonActivityUtils.previewRoom(this, mSession, room.roomId, "", object : HistoricalRoomApiCallback() { override fun onSuccess(info: Void?) { onRequestDone(null) } }) } override fun onLongClickRoom(v: View, room: Room, position: Int) { RoomUtils.displayHistoricalRoomMenu(this, mSession, room, v, this) } override fun onMoreActionClick(itemView: View, room: Room) { RoomUtils.displayHistoricalRoomMenu(this, mSession, room, itemView, this) } override fun onForgotRoom(room: Room) { showWaitingView() room.forget(object : HistoricalRoomApiCallback() { override fun onSuccess(info: Void?) { initHistoricalRoomsData() } }) } companion object { private val LOG_TAG = HistoricalRoomsActivity::class.java.simpleName } }
apache-2.0
b13fa1f7790e3d8f379e9a4935dcfcca
33.006494
115
0.5865
5.376797
false
false
false
false
mikepenz/MaterialDrawer
materialdrawer/src/main/java/com/mikepenz/materialdrawer/model/interfaces/Iconable.kt
1
2895
package com.mikepenz.materialdrawer.model.interfaces import android.content.res.ColorStateList import android.graphics.Bitmap import android.graphics.drawable.Drawable import android.net.Uri import androidx.annotation.DrawableRes import com.mikepenz.materialdrawer.holder.ImageHolder /** * Defines a [IDrawerItem] with support for an icon */ interface Iconable { /** the icon to show in the drawer */ var icon: ImageHolder? /** the color of the icon */ var iconColor: ColorStateList? } @Deprecated("Please consider to replace with the actual property setter") fun <T : Iconable> T.withIconColor(iconColor: ColorStateList): T { this.iconColor = iconColor return this } var <T : Iconable> T.iconDrawable: Drawable? @Deprecated(level = DeprecationLevel.ERROR, message = "Not readable") get() = throw UnsupportedOperationException("Please use the direct property") set(value) { if (value != null) { this.icon = ImageHolder(value) } else { this.icon = null } } var <T : Iconable> T.iconBitmap: Bitmap @Deprecated(level = DeprecationLevel.ERROR, message = "Not readable") get() = throw UnsupportedOperationException("Please use the direct property") set(value) { this.icon = ImageHolder(value) } var <T : Iconable> T.iconRes: Int @Deprecated(level = DeprecationLevel.ERROR, message = "Not readable") get() = throw UnsupportedOperationException("Please use the direct property") set(@DrawableRes value) { this.icon = ImageHolder(value) } var <T : Iconable> T.iconUrl: String @Deprecated(level = DeprecationLevel.ERROR, message = "Not readable") get() = throw UnsupportedOperationException("Please use the direct property") set(value) { this.icon = ImageHolder(value) } @Deprecated("Please consider to replace with the actual property setter") fun <T : Iconable> T.withIcon(icon: Drawable?): T { this.icon = ImageHolder(icon) return this } @Deprecated("Please consider to replace with the actual property setter") fun <T : Iconable> T.withIcon(icon: Bitmap): T { this.icon = ImageHolder(icon) return this } @Deprecated("Please consider to replace with the actual property setter") fun <T : Iconable> T.withIcon(@DrawableRes imageRes: Int): T { this.icon = ImageHolder(imageRes) return this } @Deprecated("Please consider to replace with the actual property setter") fun <T : Iconable> T.withIcon(url: String): T { this.icon = ImageHolder(url) return this } @Deprecated("Please consider to replace with the actual property setter") fun <T : Iconable> T.withIcon(uri: Uri): T { this.icon = ImageHolder(uri) return this } @Deprecated("Please consider to replace with the actual property setter") fun <T : Iconable> T.withIcon(icon: ImageHolder?): T { this.icon = icon return this }
apache-2.0
1f8148ededca03d34dc2e7021349f06b
30.129032
81
0.702245
4.106383
false
false
false
false
kerubistan/kerub
src/main/kotlin/com/github/kerubistan/kerub/planner/OperationalStateBuilderImpl.kt
2
2678
package com.github.kerubistan.kerub.planner import com.github.kerubistan.kerub.data.AssignmentDao import com.github.kerubistan.kerub.data.ControllerConfigDao import com.github.kerubistan.kerub.data.DaoOperations import com.github.kerubistan.kerub.data.HostDao import com.github.kerubistan.kerub.data.VirtualMachineDao import com.github.kerubistan.kerub.data.VirtualStorageDeviceDao import com.github.kerubistan.kerub.data.config.HostConfigurationDao import com.github.kerubistan.kerub.data.dynamic.HostDynamicDao import com.github.kerubistan.kerub.data.dynamic.VirtualMachineDynamicDao import com.github.kerubistan.kerub.data.dynamic.VirtualStorageDeviceDynamicDao import com.github.kerubistan.kerub.host.ControllerManager import com.github.kerubistan.kerub.model.Entity import com.github.kerubistan.kerub.model.controller.Assignment import com.github.kerubistan.kerub.model.controller.AssignmentType import java.util.UUID class OperationalStateBuilderImpl( private val controllerManager: ControllerManager, private val assignments: AssignmentDao, private val hostDyn: HostDynamicDao, private val hostCfg: HostConfigurationDao, private val hostDao: HostDao, private val virtualStorageDao: VirtualStorageDeviceDao, private val virtualStorageDynDao: VirtualStorageDeviceDynamicDao, private val vmDao: VirtualMachineDao, private val vmDynDao: VirtualMachineDynamicDao, private val configDao: ControllerConfigDao ) : OperationalStateBuilder { companion object { fun assignmentsOfType(assignments: List<Assignment>, type: AssignmentType): List<UUID> = assignments.filter { it.type == type }.map { it.entityId } //some parallelism would be definitely welcome here fun <T : Entity<UUID>> retrieveAll(assignments: List<UUID>, dao: DaoOperations.Read<T, UUID>): List<T> = assignments.mapNotNull { dao[it] } } override fun buildState(): OperationalState { val assignments = assignments.listByController(controllerManager.getControllerId()) val hostAssignments = assignmentsOfType(assignments, AssignmentType.host) val vmAssignments = assignmentsOfType(assignments, AssignmentType.vm) val vstorageAssignments = assignmentsOfType(assignments, AssignmentType.vstorage) return OperationalState.fromLists( hosts = retrieveAll(hostAssignments, hostDao), hostDyns = retrieveAll(hostAssignments, hostDyn), hostCfgs = retrieveAll(hostAssignments, hostCfg), vms = retrieveAll(vmAssignments, vmDao), vmDyns = retrieveAll(vmAssignments, vmDynDao), vStorage = retrieveAll(vstorageAssignments, virtualStorageDao), vStorageDyns = retrieveAll(vstorageAssignments, virtualStorageDynDao), config = configDao.get() ) } }
apache-2.0
82b50409b6dd6d7b4b937fc3767bdbd4
46
106
0.816654
4.264331
false
true
false
false
Bambooin/trime
app/src/main/java/com/osfans/trime/util/Logcat.kt
2
2672
/** * Adapted from [fcitx5-android/Logcat.kt](https://github.com/fcitx5-android/fcitx5-android/blob/e44c1c7/app/src/main/java/org/fcitx/fcitx5/android/utils/Logcat.kt) */ package com.osfans.trime.util import android.os.Process import com.osfans.trime.R import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Deferred import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.async import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.SharedFlow import kotlinx.coroutines.flow.asFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.cancellable import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.launch class Logcat(val pid: Int? = Process.myPid()) : CoroutineScope by CoroutineScope(Dispatchers.IO) { private var process: java.lang.Process? = null private var emittingJob: Job? = null private val flow: MutableSharedFlow<String> = MutableSharedFlow() /** * Subscribe to this flow to receive log in app * Nothing would be emitted until [initLogFlow] was called */ val logFlow: SharedFlow<String> by lazy { flow.asSharedFlow() } /** * Get a snapshot of logcat */ fun getLogAsync(): Deferred<Result<List<String>>> = async { runCatching { Runtime.getRuntime() .exec(arrayOf("logcat", pid?.let { "--pid=$it" } ?: "", "-d")) .inputStream .bufferedReader() .readLines() } } /** * Clear logcat */ fun clearLog(): Job = launch { runCatching { Runtime.getRuntime().exec(arrayOf("logcat", "-c")) } } /** * Create a process reading logcat, sending lines to [logFlow] */ fun initLogFlow() = if (process != null) errorState(R.string.exception_logcat_created) else launch { runCatching { Runtime .getRuntime() .exec(arrayOf("logcat", pid?.let { "--pid=$it" } ?: "", "-v", "brief")) .also { process = it } .inputStream .bufferedReader() .lineSequence() .asFlow() .flowOn(Dispatchers.IO) .cancellable() .collect { flow.emit(it) } } }.also { emittingJob = it } /** * Destroy the reading process */ fun shutdownLogFlow() { process?.destroy() emittingJob?.cancel() } companion object { val default by lazy { Logcat() } } }
gpl-3.0
b4cf14e8ec0049b74028f206b02efc9c
29.363636
164
0.590569
4.423841
false
false
false
false
BlueBoxWare/LibGDXPlugin
src/test/testdata/assetsInCode/findUsages/FindUsages2.kt
1
596
import com.badlogic.gdx.scenes.scene2d.ui.TextButton import com.badlogic.gdx.scenes.scene2d.ui.Skin import com.gmail.blueboxware.libgdxplugin.annotations.GDXAssets @GDXAssets(atlasFiles = arrayOf(""), skinFiles = ["src\\findUsages/findUsages2.skin"]) val s: Skin = Skin() object O { @GDXAssets(atlasFiles = arrayOf(""), skinFiles = arrayOf("src\\findUsages\\findUsages1.skin", "src/findUsages/findUsages2.skin")) val skin: Skin = Skin() } fun f() { val c = s.get("toggle", TextButton.TextButtonStyle::class.java) val d = O.skin.has("toggle", TextButton.TextButtonStyle::class.java) }
apache-2.0
034297789f18443f4925684689fdc28a
36.3125
131
0.738255
3.445087
false
false
false
false
kingsleyadio/android_commons
view/src/main/java/com/kingsleyadio/appcommons/view/DatetimeView.kt
1
6256
package com.kingsleyadio.appcommons.view import android.app.TimePickerDialog import android.content.Context import android.content.ContextWrapper import android.os.Bundle import android.os.Parcelable import android.text.InputType import android.text.format.DateFormat import android.util.AttributeSet import android.view.View import androidx.core.content.withStyledAttributes import androidx.fragment.app.FragmentActivity import com.google.android.material.datepicker.CalendarConstraints import com.google.android.material.datepicker.MaterialDatePicker import com.google.android.material.textfield.TextInputEditText import com.google.android.material.textfield.TextInputLayout import java.util.Calendar import java.util.Date import java.util.TimeZone /** * @author ADIO Kingsley O. * @since 26 May, 2016 */ class DatetimeView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = R.attr.editTextStyle ) : TextInputEditText(context, attrs, defStyleAttr) { var onDateChangeListener: ((Date) -> Unit)? = null var date: Date? = null set(value) { field = value updateText() } var displayMode: DisplayMode = DisplayMode.DATE_ONLY set(value) { field = value updateText() } var minDate: Date? = null var maxDate: Date? = null init { isFocusableInTouchMode = false isClickable = true isLongClickable = false isCursorVisible = false inputType = InputType.TYPE_CLASS_TEXT setSingleLine(true) context.withStyledAttributes(attrs, R.styleable.DatetimeView, defStyleAttr) { val modeIndex = getInt(R.styleable.DatetimeView_displayMode, 0) % DisplayMode.values().size displayMode = DisplayMode.values()[modeIndex] } setOnClickListener { pickDate() } } override fun onAttachedToWindow() { super.onAttachedToWindow() val layout = getTextInputLayout() ?: return layout.endIconMode = TextInputLayout.END_ICON_CUSTOM layout.setEndIconDrawable(R.drawable.ic_event_note_black_24dp) } private fun updateText() { if (date == null) text = null else setText(DateFormat.format(displayMode.format, date)) } override fun getDefaultEditable(): Boolean { return false } private fun pickDate() = when (displayMode) { DisplayMode.DATE_ONLY -> startDatePicker(false) DisplayMode.DATE_TIME -> startDatePicker(true) DisplayMode.TIME_ONLY -> startTimePicker() } private fun startDatePicker(proceedToTime: Boolean) { val currentSelection = (date ?: Date()).time.localToUtc() MaterialDatePicker.Builder.datePicker() .setCalendarConstraints( CalendarConstraints.Builder() .apply { minDate?.let { setStart(it.time.localToUtc()) } } .apply { maxDate?.let { setEnd(it.time.localToUtc()) } } .setOpenAt(currentSelection) .build() ) .setSelection(currentSelection) .build() .apply { addOnPositiveButtonClickListener { selection -> val selectedDate = Date(selection.utcToLocal()) if (proceedToTime) startTimePicker(selectedDate) else date = selectedDate.also { onDateChangeListener?.invoke(it) } } } .show(getActivityContext().supportFragmentManager, null) } private fun startTimePicker(initialDate: Date? = null) { val cal = Calendar.getInstance() if (initialDate != null) cal.time = initialDate else if (date != null) cal.time = date val listener = TimePickerDialog.OnTimeSetListener { _, hourOfDay, minute -> cal.apply { set(Calendar.HOUR_OF_DAY, hourOfDay) set(Calendar.MINUTE, minute) set(Calendar.SECOND, 0) set(Calendar.MILLISECOND, 0) } date = cal.time.also { onDateChangeListener?.invoke(it) } } TimePickerDialog( getActivityContext(), listener, cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), false ).show() } private fun getTextInputLayout(): TextInputLayout? { var parent = parent while (parent is View) { if (parent is TextInputLayout) { return parent } parent = parent.getParent() } return null } private fun getActivityContext(): FragmentActivity { var context = context while (context !is FragmentActivity) { if (context is ContextWrapper) { context = context.baseContext } else { error("FragmentActivity context not found!") } } return context } private fun Long.localToUtc(): Long = this + TimeZone.getDefault().getOffset(this) private fun Long.utcToLocal(): Long = this - TimeZone.getDefault().getOffset(this) override fun onRestoreInstanceState(state: Parcelable) { val b = state as Bundle super.onRestoreInstanceState(b.getParcelable(KEY_SUPER)) displayMode = DisplayMode.valueOf(b.getString(KEY_DISPLAY_MODE, DisplayMode.DATE_ONLY.name)) if (b.containsKey(KEY_DATE)) { date = Date(b.getLong(KEY_DATE, System.currentTimeMillis())) } } override fun onSaveInstanceState(): Parcelable { val b = Bundle() b.putParcelable(KEY_SUPER, super.onSaveInstanceState()) b.putString(KEY_DISPLAY_MODE, displayMode.name) val dateLocal = date if (dateLocal != null) b.putLong(KEY_DATE, dateLocal.time) return b } enum class DisplayMode(val format: String) { DATE_ONLY("MMM d, yyyy"), TIME_ONLY("hh:mma"), DATE_TIME("MMM d, yyyy - hh:mma") } companion object { private const val KEY_SUPER = "key_super" private const val KEY_DISPLAY_MODE = "key_display_mode" private const val KEY_DATE = "key_date" } }
apache-2.0
d546715c266e00cfd283cc24506e81f3
31.583333
100
0.62452
4.746586
false
false
false
false
xwiki-contrib/android-authenticator
app/src/main/java/org/xwiki/android/sync/activities/OIDC/OIDCActivity.kt
1
9480
package org.xwiki.android.sync.activities.OIDC import android.accounts.AccountManager import android.app.Activity import android.content.Intent import android.net.Uri import android.os.Build import android.os.Bundle import android.provider.Settings import android.util.Log import android.view.View import android.webkit.CookieManager import android.webkit.CookieSyncManager import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.databinding.DataBindingUtil import com.google.api.client.auth.oauth2.AuthorizationCodeFlow import com.google.api.client.auth.oauth2.BearerToken import com.google.api.client.auth.oauth2.ClientParametersAuthentication import com.google.api.client.auth.openidconnect.IdTokenResponse import com.google.api.client.http.GenericUrl import com.google.api.client.http.javanet.NetHttpTransport import com.google.api.client.json.jackson2.JacksonFactory import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import okhttp3.* import org.json.JSONObject import org.xwiki.android.sync.* import org.xwiki.android.sync.auth.AuthenticatorActivity import org.xwiki.android.sync.contactdb.UserAccount import org.xwiki.android.sync.databinding.ActOidcChooseAccountBinding import org.xwiki.android.sync.utils.AccountClickListener import org.xwiki.android.sync.utils.OIDCWebViewClient import org.xwiki.android.sync.utils.WebViewPageLoadedListener import org.xwiki.android.sync.utils.extensions.TAG import java.io.IOException import java.net.URL private suspend fun createAuthorizationCodeFlow(serverUrl: String): AuthorizationCodeFlow { return AuthorizationCodeFlow.Builder( BearerToken.authorizationHeaderAccessMethod(), NetHttpTransport(), JacksonFactory(), GenericUrl( buildOIDCTokenServerUrl( serverUrl ) ), ClientParametersAuthentication( Settings.Secure.ANDROID_ID, "" ), Settings.Secure.ANDROID_ID, buildOIDCAuthorizationServerUrl( serverUrl ) ).apply { scopes = mutableListOf( "openid", "offline_access", "profile" ) }.build() } class OIDCActivity: AppCompatActivity(), AccountClickListener, WebViewPageLoadedListener { private lateinit var binding: ActOidcChooseAccountBinding private var allUsersList: List<UserAccount> = listOf() private var requestNewLogin = false private var serverUrl = "" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = DataBindingUtil.setContentView(this, R.layout.act_oidc_choose_account) if (!intent.getStringExtra("serverUrl").isNullOrEmpty()) { serverUrl = intent.getStringExtra("serverUrl") binding.cvOIDCAccountList.visibility = View.GONE binding.tvPleaseWait.visibility = View.VISIBLE binding.webview.visibility = View.VISIBLE requestNewLogin = intent.getBooleanExtra("requestNewLogin",false) } init() } private fun init() { val cookieManager = CookieManager.getInstance() if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { cookieManager.flush() cookieManager.removeAllCookies(null) cookieManager.removeSessionCookies(null) } else { val cookieSyncManager = CookieSyncManager.createInstance(this) cookieSyncManager.startSync() cookieManager.removeAllCookie() cookieManager.removeSessionCookie() cookieSyncManager.stopSync() } appCoroutineScope.launch { allUsersList = userAccountsRepo.getAll() if (requestNewLogin) { startAuthorization() } else { if (allUsersList.isEmpty()) { addNewAccount() } val adapter = OIDCAccountAdapter( this@OIDCActivity, allUsersList, this@OIDCActivity ) binding.lvAddAnotherAccount.setOnClickListener { addNewAccount() } binding.lvSelectAccount.adapter = adapter } } } private fun extractAuthorizationCode(intent: Intent): String? { val data = intent.dataString val uri = Uri.parse(data) return uri.getQueryParameter("code") } private fun requestAccessToken(flow: AuthorizationCodeFlow, authorizationCode: String?) { appCoroutineScope.launch { try { val idTokenResponse = IdTokenResponse.execute( flow.newTokenRequest( authorizationCode ).setRedirectUri( REDIRECT_URI ) ) Log.d(TAG, idTokenResponse.parseIdToken().payload["sub"].toString()) val accessToken = idTokenResponse.accessToken withContext(Dispatchers.Main) { // launch on UI thread. TODO:: Check necessarily of UI scope sendResult(accessToken) } } catch(ex: IOException) { Log.e(TAG, ex.message) withContext(Dispatchers.Main) { sendResult("") finish() } } catch (ex: Exception) { Log.e(TAG, ex.message) withContext(Dispatchers.Main) { sendResult("") finish() } } } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) when (requestCode) { REQUEST_NEW_ACCOUNT -> { appCoroutineScope.launch { allUsersList = userAccountsRepo.getAll() } val adapter = OIDCAccountAdapter(this, allUsersList, this) binding.lvSelectAccount.adapter = adapter serverUrl = data?.getStringExtra("serverUrl").toString() appCoroutineScope.launch { startAuthorization() } } } } private fun sendResult(accessToken: String) { if (accessToken.isNullOrEmpty()) { Toast.makeText(this, "Something went wrong. Please try again.", Toast.LENGTH_SHORT).show() } else { getUserInfo(accessToken) } } override fun onNewIntent(intent: Intent?) { super.onNewIntent(intent) intent ?: return val authorizationCode = extractAuthorizationCode(intent) appCoroutineScope.launch { requestAccessToken(createAuthorizationCodeFlow(serverUrl), authorizationCode) } } override fun invoke(selectedAccount: UserAccount) { binding.webview.visibility = View.VISIBLE serverUrl = selectedAccount.serverAddress appCoroutineScope.launch { startAuthorization() } } private suspend fun startAuthorization() { try { val flow: AuthorizationCodeFlow = createAuthorizationCodeFlow(serverUrl) flow.newAuthorizationUrl().setRedirectUri(REDIRECT_URI).build().let { appCoroutineScope.launch (Dispatchers.Main) { binding.webview.webViewClient = OIDCWebViewClient(this@OIDCActivity) binding.webview.loadUrl(it) } } } catch (ex: Exception) { Log.e(TAG, ex.message) } } private fun addNewAccount() { val i = Intent(this, AuthenticatorActivity::class.java) i.putExtra(ADD_NEW_ACCOUNT, true) startActivityForResult(i, REQUEST_NEW_ACCOUNT) } override fun onPageLoaded(authorizationCode: String?) { appCoroutineScope.launch { requestAccessToken(createAuthorizationCodeFlow(serverUrl), authorizationCode) } } private fun getUserInfo(token: String) { val url = URL ("$serverUrl/oidc/userinfo") val request = Request.Builder() .url(url) .addHeader("Authorization", "Bearer $token") .build() val client = OkHttpClient() client .newCall(request) .enqueue(object :Callback { override fun onResponse(call: Call, response: Response) { if (response.code() == 200) { val userInfo = JSONObject(response.body()?.string()) val sub = userInfo.getString("sub").split(".") val i = Intent() i.putExtra(ACCESS_TOKEN, token) i.putExtra(AccountManager.KEY_ACCOUNT_NAME, sub[sub.size-1]) setResult(Activity.RESULT_OK, i) finish() } else { Toast.makeText(this@OIDCActivity, "Something went wrong. Please try again.", Toast.LENGTH_SHORT).show() } } override fun onFailure(call: Call, e: IOException) { Toast.makeText(this@OIDCActivity, "Something went wrong. Please try again.", Toast.LENGTH_SHORT).show() } }) } }
lgpl-2.1
600456d382b259bb07b504aeb41f03c6
33.60219
123
0.611392
5.180328
false
false
false
false
google/private-compute-libraries
java/com/google/android/libraries/pcc/chronicle/codegen/util/ProcessingEnv.kt
1
5444
/* * 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 * * 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.google.android.libraries.pcc.chronicle.codegen.util import com.google.android.libraries.pcc.chronicle.codegen.TypeLocation import javax.annotation.processing.ProcessingEnvironment import javax.lang.model.element.AnnotationMirror import javax.lang.model.element.Element import javax.lang.model.element.ElementKind import javax.lang.model.element.PackageElement import javax.lang.model.type.DeclaredType import javax.lang.model.type.TypeMirror interface ProcessingEnvHelpers { val processingEnv: ProcessingEnvironment /** * Returns a list of strings where each string represents the name of the enum constants in an * enum. This helper doesn't check that the provided type is actually an enum. */ fun Element.enumValues(): List<String> = enclosedElements.filter { it.kind == ElementKind.ENUM_CONSTANT }.map { it.simpleName.toString() } /** * Returns the provided [TypeMirror] wrapped in a [ComparableType] comparison helper class to make * comparisons via `equals` work. */ fun TypeMirror.comparableType(): ComparableType = ComparableType(this, processingEnv) /** Removes any type parameter information from a type. Useful for comparisons. */ fun TypeMirror.rawType(): TypeMirror = processingEnv.typeUtils.erasure(this) /** Converts a string literal class name into a [TypeMirror], ignoring type params. */ fun String.asNamedRawType(): TypeMirror = requireNotNull(asNamedRawTypeOrNull()) /** Converts a string literal class name into a [TypeMirror], or null if not found. */ fun String.asNamedRawTypeOrNull(): TypeMirror? = processingEnv.elementUtils.getTypeElement(this)?.asType()?.rawType() /** Returns the [Element] that represents the type of the receiving [Element]. */ fun Element.asTypeElement(): Element = processingEnv.typeUtils.asElement(this.asType()) /** Returns the [idx]th type parameter for the [TypeMirror]. Does not do any validity checks. */ fun TypeMirror.typeParameter(idx: Int): TypeMirror = (this as DeclaredType).typeArguments[idx] /** Returns the [PackageElement] associated with this [Element]. */ fun Element.packageName(): PackageElement = processingEnv.elementUtils.getPackageOf(this) /** * Returns a list of strings representing an enclosing types for a class. * * The enclosing types will be returned in list ordered inner-most first. * * For example, `java.util.Map.Entry` will return ["Map"]. * `some.package.OuterMost.Middle.Inner.ClassName` will return ["Inner", "Middle", "OuterMost"] */ fun Element.enclosingTypeNames(): List<String> = generateSequence(this) { element -> element.enclosingElement?.takeIf { it.kind != ElementKind.PACKAGE } } .drop(1) // Skip the top level .map { it.simpleName.toString() } .toList() /** Creates a [TypeLocation] from the information present int he [Element]. */ fun Element.asTypeLocation() = TypeLocation( asTypeElement().simpleName.toString(), asTypeElement().enclosingTypeNames(), asTypeElement().packageName().toString() ) /** Converts the receiving [TypeMirror] into a [TypeLocation]. */ fun TypeMirror.asTypeLocation(): TypeLocation = processingEnv.typeUtils.asElement(this).asTypeLocation() /** * Returns true if one of the [AnnotationMirror] items on this element has the same * fully-qualified name as the provided [Class]. */ fun Element.isAnnotatedWith(cls: Class<*>): Boolean { return asTypeElement().annotationMirrors.any { it.annotationType.asElement().asTypeLocation().toString() == cls.name } } } /** * It's a bit annoying to compare two [TypeMirrors][TypeMirror]. This is a simple wrapper class that * makes them comparable by equals. */ class ComparableType(val type: TypeMirror, val processingEnv: ProcessingEnvironment) : TypeMirror by type { override fun hashCode() = type.hashCode() override fun equals(other: Any?) = when (other) { is ComparableType -> processingEnv.typeUtils.isSameType(this.type, other.type) is TypeMirror -> processingEnv.typeUtils.isSameType(this.type, other) else -> false } } /** * Create a new instance of the [ProcessingEnvHelpers interface for the provided * [ProcessingEnvironment]. * * To make these helpers available directly in a class that's being constructed with a * [ProcessingEnvironment] as a constructor parameter, you can delegate to this implementation: * ``` * class MyClass( * processingEnv: ProcessingEnvironment * ) : ProcessingEnvHelpers by processingEnvHelpers(processingEnv) { * // Extension methods in ProcessingEnvironment will be available here. * } * ``` */ fun processingEnvHelpers(processingEnv: ProcessingEnvironment): ProcessingEnvHelpers = object : ProcessingEnvHelpers { override val processingEnv = processingEnv }
apache-2.0
e4c4adab33e14e189bf3688800f93c21
39.325926
100
0.734386
4.517842
false
false
false
false
soeminnminn/EngMyanDictionary
app/src/main/java/com/s16/view/BottomNavigationBehavior.kt
1
4705
/** MIT License Copyright (c) 2018 Valentin Hinov Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.s16.view import android.animation.ValueAnimator import android.content.Context import android.util.AttributeSet import android.view.Gravity import android.view.View import android.view.animation.DecelerateInterpolator import androidx.coordinatorlayout.widget.CoordinatorLayout import androidx.core.view.ViewCompat import com.google.android.material.snackbar.Snackbar import kotlin.math.max import kotlin.math.min // Apply to BottomNavigationView class BottomNavigationBehavior<V : View>(context: Context, attrs: AttributeSet) : CoordinatorLayout.Behavior<V>(context, attrs) { @ViewCompat.NestedScrollType private var lastStartedType: Int = 0 private var offsetAnimator: ValueAnimator? = null var isSnappingEnabled = false override fun layoutDependsOn(parent: CoordinatorLayout, child: V, dependency: View): Boolean { if (dependency is Snackbar.SnackbarLayout) { updateSnackbar(child, dependency) } return super.layoutDependsOn(parent, child, dependency) } override fun onStartNestedScroll( coordinatorLayout: CoordinatorLayout, child: V, directTargetChild: View, target: View, axes: Int, type: Int ): Boolean { if (axes != ViewCompat.SCROLL_AXIS_VERTICAL) return false lastStartedType = type offsetAnimator?.cancel() return true } override fun onNestedPreScroll( coordinatorLayout: CoordinatorLayout, child: V, target: View, dx: Int, dy: Int, consumed: IntArray, type: Int ) { super.onNestedPreScroll(coordinatorLayout, child, target, dx, dy, consumed, type) child.translationY = max(0f, min(child.height.toFloat(), child.translationY + dy)) } override fun onStopNestedScroll(coordinatorLayout: CoordinatorLayout, child: V, target: View, type: Int) { if (!isSnappingEnabled) return // add snap behaviour // Logic here borrowed from AppBarLayout onStopNestedScroll code if (lastStartedType == ViewCompat.TYPE_TOUCH || type == ViewCompat.TYPE_NON_TOUCH) { // find nearest seam val currTranslation = child.translationY val childHalfHeight = child.height * 0.5f // translate down if (currTranslation >= childHalfHeight) { animateBarVisibility(child, isVisible = false) } // translate up else { animateBarVisibility(child, isVisible = true) } } } private fun animateBarVisibility(child: View, isVisible: Boolean) { if (offsetAnimator == null) { offsetAnimator = ValueAnimator().apply { interpolator = DecelerateInterpolator() duration = 150L } offsetAnimator?.addUpdateListener { child.translationY = it.animatedValue as Float } } else { offsetAnimator?.cancel() } val targetTranslation = if (isVisible) 0f else child.height.toFloat() offsetAnimator?.setFloatValues(child.translationY, targetTranslation) offsetAnimator?.start() } private fun updateSnackbar(child: View, snackbarLayout: Snackbar.SnackbarLayout) { if (snackbarLayout.layoutParams is CoordinatorLayout.LayoutParams) { val params = snackbarLayout.layoutParams as CoordinatorLayout.LayoutParams params.anchorId = child.id params.anchorGravity = Gravity.TOP params.gravity = Gravity.TOP snackbarLayout.layoutParams = params } } }
gpl-2.0
5898f3a666adc068e2424619b67dd380
36.951613
117
0.695643
4.973573
false
false
false
false
daemontus/Distributed-CTL-Model-Checker
src/main/kotlin/com/github/sybila/checker/partition/UniformPartition.kt
3
1271
package com.github.sybila.checker.partition import com.github.sybila.checker.Model import com.github.sybila.checker.MutableStateMap import com.github.sybila.checker.Partition import com.github.sybila.checker.map.mutable.ContinuousStateMap import com.github.sybila.checker.map.mutable.HashStateMap class UniformPartition<Params : Any>( override val partitionId: Int, override val partitionCount: Int, model: Model<Params> ) : Partition<Params>, Model<Params> by model { //Ceil ensures that partitionCount * statesPerPartition >= stateCount, hence //stateId / statesPerPartition will end in [0, partitionCount) range. private val statesPerPartition = Math.ceil(stateCount.toDouble() / partitionCount.toDouble()).toInt() override fun Int.owner(): Int = this / statesPerPartition override fun newLocalMutableMap(partition: Int): MutableStateMap<Params> { return if (partition == partitionId) { ContinuousStateMap(partition * statesPerPartition, (partition + 1) * statesPerPartition, ff) } else HashStateMap(ff) } } fun <Params : Any> List<Model<Params>>.asUniformPartitions(): List<UniformPartition<Params>> { return this.mapIndexed { i, model -> UniformPartition(i, this.size, model) } }
gpl-3.0
a019999d15916a6202f6a0ab11b5ecc8
40.032258
105
0.740362
4.236667
false
false
false
false
katanagari7c1/wolverine-comics-kotlin
app/src/main/kotlin/dev/katanagari7c1/wolverine/presentation/detail/DetailActivity.kt
1
2726
package dev.katanagari7c1.wolverine.presentation.detail import android.os.Bundle import android.support.v7.widget.Toolbar import android.widget.ImageView import dev.katanagari7c1.wolverine.R import dev.katanagari7c1.wolverine.domain.entity.Comic import dev.katanagari7c1.wolverine.domain.repository.ComicRepository import dev.katanagari7c1.wolverine.domain.use_case.ComicFindByIdUseCase import dev.katanagari7c1.wolverine.domain.util.ImageLoader import dev.katanagari7c1.wolverine.presentation.application.WolverineApplication import dev.katanagari7c1.wolverine.presentation.base.DialogActivity import dev.katanagari7c1.wolverine.presentation.helper.StringToHtmlConverter import kotlinx.android.synthetic.main.activity_detail.* import org.jetbrains.anko.doAsync import org.jetbrains.anko.find import org.jetbrains.anko.uiThread import java.util.* import javax.inject.Inject import javax.inject.Named class DetailActivity : DialogActivity() { companion object { const val EXTRA_COMIC_ID = "comic_id" } @field:[Inject Named ("persistence")] lateinit var repository: ComicRepository @Inject lateinit var stringToHtmlConverter: StringToHtmlConverter @Inject lateinit var imageLoader: ImageLoader override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_detail) WolverineApplication.getInjectorComponent(this).inject(this) val comicId = this.intent.getStringExtra(EXTRA_COMIC_ID) this.initializeToolbar(find<Toolbar>(R.id.detail_toolbar)) .withUpNavigation() .title(getString(R.string.detail_title)) this.fetchComicAndRender(comicId) } private fun fetchComicAndRender(comicId:String) { this.showLoading(R.string.loading_comic_data) val comicFindByIdUseCase = ComicFindByIdUseCase(repository) doAsync { val comic = comicFindByIdUseCase.execute(comicId) uiThread { if (comic != null) { renderComic(comic) hideLoading() } } } } private fun renderComic(comic: Comic) { this.detail_title.text = comic.title this.detail_description.text = if (comic.description.isEmpty()) getString(R.string.no_description) else stringToHtmlConverter.convert(comic.description) this.showRandomImage(comic, detail_image) this.detail_series_field.text = comic.series this.detail_pages.text = String.format(getString(R.string.page_number_template), comic.numPages) } private fun showRandomImage(comic: Comic, detail_image: ImageView) { if (comic.images.isEmpty()) { this.imageLoader.loadImageInto(comic.thumbnail, detail_image) } else { val randomIndex = Random().nextInt(comic.images.size) this.imageLoader.loadImageInto(comic.images[randomIndex], detail_image) } } }
mit
75b4830afb1af90213a4b78fa91d3fe0
30.333333
98
0.791636
3.563399
false
false
false
false
VerifAPS/verifaps-lib
lang/src/main/kotlin/edu/kit/iti/formal/automation/parser/IECParseTreeToAST.kt
1
45303
package edu.kit.iti.formal.automation.parser /*- * #%L * iec61131lang * %% * Copyright (C) 2017 Alexander Weigl * %% * This program isType 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 isType 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 clone of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. * #L% */ import edu.kit.iti.formal.automation.datatypes.AnyInt import edu.kit.iti.formal.automation.datatypes.IECString import edu.kit.iti.formal.automation.datatypes.values.DateAndTimeData import edu.kit.iti.formal.automation.datatypes.values.DateData import edu.kit.iti.formal.automation.datatypes.values.TimeData import edu.kit.iti.formal.automation.datatypes.values.TimeofDayData import edu.kit.iti.formal.automation.fbd.FbdBody import edu.kit.iti.formal.automation.il.* import edu.kit.iti.formal.automation.operators.BinaryOperator import edu.kit.iti.formal.automation.operators.Operators import edu.kit.iti.formal.automation.scope.Scope import edu.kit.iti.formal.automation.scope.TypeScope import edu.kit.iti.formal.automation.sfclang.split import edu.kit.iti.formal.automation.st.RefTo import edu.kit.iti.formal.automation.st.ast.* import edu.kit.iti.formal.automation.st.util.setAll import org.antlr.v4.runtime.ParserRuleContext import org.antlr.v4.runtime.Token import java.math.BigInteger import java.util.* import kotlin.collections.HashMap /** * @author Alexander Weigl, Augusto Modanese * @version 1 (23.06.17) */ class IECParseTreeToAST : IEC61131ParserBaseVisitor<Any>() { private lateinit var network: SFCNetwork private lateinit var gather: VariableBuilder private lateinit var sfc: SFCImplementation private lateinit var currentStep: SFCStep //private lateinit var currentTopLevelScopeElement: HasScope private var tscope = TypeScope.builtin() override fun visitStart( ctx: IEC61131Parser.StartContext): PouElements { val ast = PouElements() ast.ruleContext = ctx ctx.library_element_declaration().forEach { l -> val accept = l.accept(this) as? PouElement if (accept != null) ast.add(accept) } return ast } override fun visitLibrary_element_declaration(ctx: IEC61131Parser.Library_element_declarationContext): Any { val elemen = oneOf<Top>( ctx.class_declaration(), ctx.data_type_declaration(), ctx.function_block_declaration(), ctx.function_declaration(), ctx.global_variable_list_declaration(), ctx.interface_declaration(), ctx.namespace_declaration(), ctx.program_declaration()) if (ctx.pragma() != null && elemen != null) { if (elemen is HasPragma) { val p = ctx.pragma().map { it.accept(this) as Pragma } elemen.pragmas.addAll(p) } else { throw RuntimeException("Pragma not supported ${elemen.nodeName} " + "at line ${ctx.start.tokenSource.sourceName}:${ctx.start.line}.") } } return elemen!! } override fun visitNamespace_elements(ctx: IEC61131Parser.Namespace_elementsContext): Any { val elemen = oneOf<Any>(ctx.class_declaration(), ctx.data_type_declaration(), ctx.function_block_declaration(), ctx.function_declaration(), ctx.interface_declaration(), ctx.namespace_declaration()) if (ctx.pragma() != null) { if (elemen is HasPragma) { val p = ctx.pragma().map { it.accept(this) as Pragma } elemen.pragmas.addAll(p) } else { throw RuntimeException("Pragma not supported at line ${ctx.start.line}.") } } return elemen!! } override fun visitPragma(ctx: IEC61131Parser.PragmaContext): Any { val rawParameters = HashMap<String, String>() var position: Int = 0; ctx.pragma_arg().forEach { val value = it.value.text.trim('\'', '"') if (it.ASSIGN() == null) rawParameters["#" + (position++)] = value else rawParameters[it.arg.text.trim('"', '\'')] = value } val p = makePragma(ctx.type.text, rawParameters) ?: throw IllegalArgumentException("Pragma ${ctx.type.text} in line ${ctx.type.line} not supported") return p } override fun visitCast(ctx: IEC61131Parser.CastContext): Literal { val (dt, _, v) = split(ctx.CAST_LITERAL().text) val ast = EnumLit(dt, v) //ast.originalToken = ctx.CAST_LITERAL().symbol ast.ruleContext = ctx return ast } override fun visitInteger(ctx: IEC61131Parser.IntegerContext): Any { val text = ctx.INTEGER_LITERAL().symbol val splitted = split(text.text) val dt = splitted.prefix val v = splitted.value val ordinal = splitted.ordinal ?: 10 var int = BigInteger(v.replace("_", ""), ordinal) if (ctx.MINUS() != null) int *= -BigInteger.ONE val ast = IntegerLit(dt, int) try { //weigl: quick type for common integer type if (dt in tscope) ast.dataType.obj = tscope[dt] as AnyInt } catch (e: ClassCastException) { } ast.ruleContext = ctx return ast } override fun visitBits(ctx: IEC61131Parser.BitsContext): Any { val text = ctx.BITS_LITERAL().symbol val splitted = split(text.text) val dt = splitted.prefix val v = splitted.value if (v.equals("false", true)) return BooleanLit(false) if (v.equals("true", true)) return BooleanLit(true) val ordinal = splitted.ordinal ?: 10 val ast = BitLit(dt, v.toLong(ordinal)) ast.ruleContext = ctx return ast } override fun visitReal(ctx: IEC61131Parser.RealContext): Any { val (dt, _, v) = split(ctx.REAL_LITERAL().text) val ast = RealLit(dt, v.toBigDecimal()) ast.ruleContext = ctx return ast } override fun visitString(ctx: IEC61131Parser.StringContext): Any { val ast = StringLit( if (ctx.STRING_LITERAL() != null) IECString.STRING else IECString.WSTRING, if (ctx.WSTRING_LITERAL() != null) ctx.text.trim('"') else ctx.text.trim('\'')) ast.ruleContext = ctx return ast } override fun visitTime(ctx: IEC61131Parser.TimeContext): Any { val ast = TimeLit(value = TimeData(ctx.text)) ast.ruleContext = ctx return ast } override fun visitTimeofday(ctx: IEC61131Parser.TimeofdayContext): Any { val ast = ToDLit(value = TimeofDayData.parse(ctx.TOD_LITERAL().text!!)) ast.ruleContext = ctx return ast } override fun visitDate(ctx: IEC61131Parser.DateContext): Any { val ast = DateLit(value = DateData.parse(ctx.DATE_LITERAL().text!!)) ast.ruleContext = ctx return ast } override fun visitDatetime(ctx: IEC61131Parser.DatetimeContext): Any { val ast = DateAndTimeLit(value = DateAndTimeData.parse(ctx.DATETIME().text)) ast.ruleContext = ctx return ast } override fun visitRef_null(ctx: IEC61131Parser.Ref_nullContext): Any { val ast = NullLit() ast.ruleContext = ctx return ast } override fun visitReference_value(ctx: IEC61131Parser.Reference_valueContext): Any { val ast = Invocation("ref") val p = InvocationParameter(ctx.ref_to.accept(this) as SymbolicReference) p.ruleContext = ctx.ref_to ast.addParameter(p) return ast } override fun visitData_type_declaration( ctx: IEC61131Parser.Data_type_declarationContext): Any { val ast = TypeDeclarations() ast.ruleContext = ctx for (i in 0 until ctx.type_declaration().size) { val t = ctx.type_declaration(i).accept(this) as TypeDeclaration ast.add(t) t.name = ctx.IDENTIFIER(i).text } //Utils.setPosition(ast, ctx.TYPE, ctx.END_TYPE); return ast } override fun visitData_type_name( ctx: IEC61131Parser.Data_type_nameContext): SimpleTypeDeclaration { val td = SimpleTypeDeclaration() td.ruleContext = ctx td.baseType.identifier = ctx.non_generic_type_name().text return td } private fun <T> allOf(ctx: List<ParserRuleContext>) = ctx.map { a -> a.accept(this) as T } .toMutableList() private fun <T> oneOf(vararg children: ParserRuleContext?): T? { val fnn = children.find { it != null } if (fnn != null) { return fnn.accept(this) as T } else { return null } /* val call = { r: ParserRuleContext -> if (r != null) r.accept(this) as T else null } for (c in children) { val a = call(c) if (a != null) return a } return null*/ } override fun visitType_declaration( ctx: IEC61131Parser.Type_declarationContext): Any { val init = (if (ctx.initializations() != null) ctx.initializations().accept(this) else null) as Initialization? if (ctx.array_specification() != null) { val t = visitArray_specification(ctx.array_specification()) t.initialization = init as ArrayInitialization? return t } else if (ctx.enumerated_specification() != null) { val t = visitEnumerated_specification(ctx.enumerated_specification()) t.initialization = init as IdentifierInitializer? return t } else if (ctx.string_type_declaration() != null) { val t = visitString_type_declaration(ctx.string_type_declaration()) t.initialization = init as Literal? return t } else if (ctx.subrange_spec_init() != null) { val t = visitSubrange_spec_init(ctx.subrange_spec_init()) t.initialization = init as? IntegerLit return t } else if (ctx.structure_declaration() != null) { val t = visitStructure_declaration(ctx.structure_declaration()) t.initialization = init as StructureInitialization? return t } else if (ctx.reference_specification() != null) { val t = visitReference_specification(ctx.reference_specification()) t.initialization = init as Literal? return t } else //if(ctx.data_type_name() != null) { val t = visitData_type_name(ctx.data_type_name()) t.setInit(init) return t } } override fun visitInitializations_identifier( ctx: IEC61131Parser.Initializations_identifierContext) = IdentifierInitializer(null, ctx.IDENTIFIER().text) override fun visitSubrange_spec_init( ctx: IEC61131Parser.Subrange_spec_initContext): SubRangeTypeDeclaration { val ast = SubRangeTypeDeclaration() ast.ruleContext = ctx ast.baseType.identifier = ctx.integer_type_name().text ast.range = ctx.subrange().accept(this) as Range //Utils.setPosition(ast, ctx.integer_type_name.ctx, ctx.RPAREN); return ast } override fun visitSubrange(ctx: IEC61131Parser.SubrangeContext) = Range(ctx.c.accept(this) as IntegerLit, ctx.d.accept(this) as IntegerLit) override fun visitEnumerated_specification( ctx: IEC61131Parser.Enumerated_specificationContext): EnumerationTypeDeclaration { val ast = EnumerationTypeDeclaration() ast.ruleContext = ctx for (i in ctx.value.indices) { ast.addValue(ctx.value[i]) if (ctx.integer(i) != null) { ast.setInt(ctx.integer(i).accept(this) as IntegerLit) } } /*if (ctx.basename != null) { ast.setBaseTypeName(ctx.basename.getText()); }*/ return ast } override fun visitArray_specification( ctx: IEC61131Parser.Array_specificationContext): ArrayTypeDeclaration { val ast = ArrayTypeDeclaration( type = if (ctx.non_generic_type_name() != null) SimpleTypeDeclaration(ctx.non_generic_type_name()!!.text) else ctx.string_type_declaration().accept(this) as StringTypeDeclaration ) for (src in ctx.ranges) ast.addSubRange(src.accept(this) as Range) return ast } override fun visitArray_initialization( ctx: IEC61131Parser.Array_initializationContext): Any { val ast = ArrayInitialization() ast.ruleContext = ctx ctx.array_initial_elements().forEach { a -> val inits = a.accept(this) as List<Initialization> ast.initValues.addAll(inits) } return ast } override fun visitArray_initial_elements( ctx: IEC61131Parser.Array_initial_elementsContext): Any { val initializations = ArrayList<Initialization>() var count = 1 if (ctx.integer() != null) { val lit = ctx.integer().accept(this) as IntegerLit count = lit.value.toInt() } for (i in 0 until count) initializations.add(ctx.array_initial_element().accept(this) as Initialization) return initializations } override fun visitArray_initial_element( ctx: IEC61131Parser.Array_initial_elementContext): Any? { return oneOf<Any>(ctx.constant(), ctx.structure_initialization(), ctx.array_initialization()) } override fun visitStructure_declaration( ctx: IEC61131Parser.Structure_declarationContext): StructureTypeDeclaration { val ast = StructureTypeDeclaration() val localScope = Scope() gather = localScope.builder() ctx.ids.zip(ctx.tds).forEach { (id, type) -> gather.identifiers(id.IDENTIFIER().symbol).type(type.accept(this) as TypeDeclaration).close() } //gather = null ast.fields = localScope.variables return ast } override fun visitStructure_initialization( ctx: IEC61131Parser.Structure_initializationContext): Any { // Includes class and FB initializations val ast = StructureInitialization() ast.ruleContext = ctx for (i in ctx.IDENT.indices) ast.addField(ctx.IDENT[i].text, ctx.init[i].accept(this) as Initialization) return ast } override fun visitReference_specification(ctx: IEC61131Parser.Reference_specificationContext): ReferenceTypeDeclaration { val ast = ReferenceTypeDeclaration() ast.ruleContext = ctx ast.refTo = ctx.data_type_name().accept(this) as SimpleTypeDeclaration return ast } override fun visitString_type_declaration( ctx: IEC61131Parser.String_type_declarationContext): StringTypeDeclaration { val ast = StringTypeDeclaration() ast.ruleContext = ctx ast.baseType.identifier = ctx.baseType.text if (ctx.integer() != null) { ast.size = ctx.integer().accept(this) as Literal } return ast } override fun visitIdentifier_list( ctx: IEC61131Parser.Identifier_listContext): List<String> { return ctx.names.map { it.text } } override fun visitFunction_declaration( ctx: IEC61131Parser.Function_declarationContext): Any { val ast = FunctionDeclaration() //currentTopLevelScopeElement = ast ast.ruleContext = ctx ast.name = ctx.identifier.text ast.scope = ctx.var_decls().accept(this) as Scope if (ctx.returnET != null) { ast.returnType.identifier = ctx.returnET.text } else { ast.returnType.identifier = ctx.returnID.text } ast.name = ctx.identifier.text ast.stBody = ctx.funcBody().statement_list().accept(this) as StatementList return ast } override fun visitGlobal_variable_list_declaration(ctx: IEC61131Parser.Global_variable_list_declarationContext): Any { val gvl = GlobalVariableListDeclaration() gather = gvl.scope.builder() gather.push(VariableDeclaration.GLOBAL) ctx.var_decl_inner().accept(this) //gvl.scope.forEach { v -> v.parent = gvl } //gather = null return gvl } override fun visitVar_decls(ctx: IEC61131Parser.Var_declsContext): Any { val localScope = Scope() gather = localScope.builder() ctx.var_decl().forEach { vd -> vd.accept(this) } return localScope } override fun visitVar_decl(ctx: IEC61131Parser.Var_declContext): Any? { gather.clear() val p = ctx.pragma().map { it.accept(this) as Pragma } gather.pushPragma(p) ctx.variable_keyword().accept(this) ctx.var_decl_inner().accept(this) gather.popPragma() return null } fun <T> List<ParserRuleContext>.map(): MutableList<T> = this.map { it -> it.accept(this@IECParseTreeToAST) as T }.toMutableList() override fun visitBlock_statement(ctx: IEC61131Parser.Block_statementContext): BlockStatement { val bs = BlockStatement() val statementList = ctx.statement_list().accept(this) as StatementList bs.statements = statementList bs.name = ctx.id.text bs.state = ctx.state?.accept(this) as MutableList<SymbolicReference>? ?: arrayListOf() bs.input = ctx.input?.accept(this) as MutableList<SymbolicReference>? ?: arrayListOf() bs.output = ctx.output?.accept(this) as MutableList<SymbolicReference>? ?: arrayListOf() bs.ruleContext = ctx return bs } override fun visitRef_list(ctx: IEC61131Parser.Ref_listContext): Any { return ctx.symbolic_variable().map { it.accept(this) } } override fun visitVar_decl_inner(ctx: IEC61131Parser.Var_decl_innerContext): Any? { val p: List<Pragma> = ctx.pragma().map() for (i in 0 until ctx.type_declaration().size) { val seq = ctx.identifier_list(i).names.map { it } gather .pushPragma(p) .identifiers(seq) .type(ctx.type_declaration(i).accept(this) as TypeDeclaration) .close() .popPragma() } return null } override fun visitVariable_keyword(ctx: IEC61131Parser.Variable_keywordContext): Any? { if (ctx.VAR() != null) { gather.push(VariableDeclaration.LOCAL) } if (ctx.VAR_INPUT() != null) { gather.push(VariableDeclaration.INPUT) } if (ctx.VAR_OUTPUT() != null) { gather.push(VariableDeclaration.OUTPUT) } if (ctx.VAR_IN_OUT() != null) { gather.push(VariableDeclaration.INOUT) } if (ctx.VAR_EXTERNAL() != null) { gather.push(VariableDeclaration.EXTERNAL) } if (ctx.VAR_GLOBAL() != null) { gather.push(VariableDeclaration.GLOBAL) } if (ctx.CONSTANT() != null) { gather.mix(VariableDeclaration.CONSTANT) } if (ctx.RETAIN() != null) { gather.mix(VariableDeclaration.RETAIN) } // Access specifier if (ctx.access_specifier() != null) { val accessSpecifier = AccessSpecifier.valueOf(ctx.access_specifier().text) gather.mix(accessSpecifier.flag) } return null } override fun visitFunction_block_declaration(ctx: IEC61131Parser.Function_block_declarationContext): Any { val ast = FunctionBlockDeclaration() //currentTopLevelScopeElement = ast ast.ruleContext = ctx ast.scope = ctx.var_decls().accept(this) as Scope ast.isFinal = ctx.FINAL() != null ast.isAbstract = ctx.ABSTRACT() != null ast.name = ctx.identifier.text if (ctx.inherit != null) { ast.setParentName(ctx.inherit.text) } if (ctx.interfaces != null) { (ctx.interfaces.accept(this) as List<String>) .forEach { i -> ast.interfaces.add(RefTo(i)) } } ast.scope = ctx.var_decls().accept(this) as Scope ast.methods.addAll(ctx.methods().accept(this) as List<MethodDeclaration>) ctx.action().forEach { act -> ast.addAction(act.accept(this) as ActionDeclaration) } if (ctx.body().stBody() != null) ast.stBody = ctx.body().stBody().accept(this) as StatementList if (ctx.body().sfc() != null) ast.sfcBody = ctx.body().sfc().accept(this) as SFCImplementation if (ctx.body().ilBody() != null) ast.ilBody = ctx.body().ilBody().accept(this) as IlBody if (ctx.body().fbBody() != null) ast.fbBody = ctx.body().fbBody().accept(this) as FbdBody return ast } override fun visitInterface_declaration(ctx: IEC61131Parser.Interface_declarationContext): Any { val ast = InterfaceDeclaration() ast.ruleContext = ctx //ast.scope = ctx.var_decls().accept(this) as Scope ast.name = ctx.identifier.text ast.methods.setAll(ctx.methods().accept(this) as List<MethodDeclaration>) if (ctx.sp != null) { (ctx.sp.accept(this) as List<String>).forEach { i -> ast.interfaces.add(RefTo(i)) } } return ast } override fun visitClass_declaration(ctx: IEC61131Parser.Class_declarationContext): Any { val ast = ClassDeclaration() ast.ruleContext = ctx //currentTopLevelScopeElement = ast ast.scope = ctx.var_decls().accept(this) as Scope ast.isFinal = ctx.FINAL() != null ast.isAbstract = ctx.ABSTRACT() != null ast.name = ctx.identifier.text if (ctx.inherit != null) { ast.parent.identifier = ctx.inherit.text } if (ctx.interfaces != null) { (ctx.interfaces.accept(this) as List<String>) .forEach { ast.interfaces.add(it) } } ast.methods.setAll(ctx.methods().accept(this) as List<MethodDeclaration>) return ast } override fun visitMethods( ctx: IEC61131Parser.MethodsContext): List<MethodDeclaration> { return ctx.method().map { a -> a.accept(this) as MethodDeclaration } } override fun visitMethod(ctx: IEC61131Parser.MethodContext): Any { val ast = MethodDeclaration() //ast.ruleContext = (ctx); ast.name = ctx.identifier.text //ast.parent = currentTopLevelScopeElement as Classifier<*>? if (ctx.access_specifier() != null) { ast.accessSpecifier = AccessSpecifier.valueOf(ctx.access_specifier().text) } ast.isFinal = ctx.FINAL() != null ast.isAbstract = ctx.ABSTRACT() != null ast.isOverride = ctx.OVERRIDE() != null if (ctx.returnET != null) { ast.returnType.identifier = ctx.returnET.text } else { if (ctx.returnID != null) { ast.returnType.identifier = ctx.returnID.text } else { ast.returnType.identifier = "VOID" } } //currentTopLevelScopeElement = ast; ast.scope = ctx.var_decls().accept(this) as Scope if (ctx.body().stBody() != null) ast.stBody = ctx.body().stBody().accept(this) as StatementList //currentTopLevelScopeElement = ast.getParent(); return ast } override fun visitProgram_declaration( ctx: IEC61131Parser.Program_declarationContext): Any { val ast = ProgramDeclaration() ast.ruleContext = ctx ast.name = ctx.identifier.text //currentTopLevelScopeElement = ast ast.scope = ctx.var_decls().accept(this) as Scope if (ctx.body().stBody() != null) ast.stBody = ctx.body().stBody().accept(this) as StatementList if (ctx.body().sfc() != null) ast.sfcBody = ctx.body().sfc().accept(this) as SFCImplementation if (ctx.body().ilBody() != null) ast.ilBody = ctx.body().ilBody().accept(this) as IlBody if (ctx.body().fbBody() != null) ast.fbBody = ctx.body().fbBody().accept(this) as FbdBody ctx.action().forEach { act -> ast.addAction(act.accept(this) as ActionDeclaration) } return ast } override fun visitUnaryNegateExpr( ctx: IEC61131Parser.UnaryNegateExprContext): Expression { val ast = UnaryExpression(Operators.NOT, ctx.sub.accept(this) as Expression) //Utils.setPosition(ast, ctx.NOT(), ctx.sub); ast.ruleContext = ctx return ast } override fun visitBinaryOrExpr( ctx: IEC61131Parser.BinaryOrExprContext): Any { val binaryExpr = binaryExpr(ctx.left, ctx.op, ctx.right) binaryExpr.ruleContext = (ctx) return binaryExpr } override fun visitBinaryCmpExpr( ctx: IEC61131Parser.BinaryCmpExprContext): Any { val expr = binaryExpr(ctx.left, ctx.op, ctx.right) expr.ruleContext = (ctx) return expr } override fun visitBinaryModDivExpr( ctx: IEC61131Parser.BinaryModDivExprContext): Any { val e = binaryExpr(ctx.left, ctx.op, ctx.right) e.ruleContext = (ctx) return e } override fun visitParenExpr( ctx: IEC61131Parser.ParenExprContext): Any { return ctx.expression().accept(this) } override fun visitBinaryXORExpr( ctx: IEC61131Parser.BinaryXORExprContext): Any { val e = binaryExpr(ctx.left, ctx.op, ctx.right) e.ruleContext = (ctx) return e } override fun visitUnaryMinusExpr( ctx: IEC61131Parser.UnaryMinusExprContext): Any { val ast = UnaryExpression(Operators.MINUS, ctx.sub.accept(this) as Expression) //Utils.setPosition(ast, ctx.NOT, ctx.sub.accept(this)); ast.ruleContext = ctx return ast } override fun visitBinaryPowerExpr( ctx: IEC61131Parser.BinaryPowerExprContext): Any { val e = binaryExpr(ctx.left, ctx.op, ctx.right) e.ruleContext = (ctx) return e } override fun visitBinaryMultExpr( ctx: IEC61131Parser.BinaryMultExprContext): Any { val e = binaryExpr(ctx.left, ctx.op, ctx.right) e.ruleContext = (ctx) return e } override fun visitBinaryPlusMinusExpr( ctx: IEC61131Parser.BinaryPlusMinusExprContext): Any { val e = binaryExpr(ctx.left, ctx.op, ctx.right) e.ruleContext = (ctx) return e } override fun visitBinaryEqExpr( ctx: IEC61131Parser.BinaryEqExprContext): Any { val e = binaryExpr(ctx.left, ctx.op, ctx.right) e.ruleContext = (ctx) return e } override fun visitBinaryAndExpr( ctx: IEC61131Parser.BinaryAndExprContext): Any { val e = binaryExpr(ctx.left, ctx.op, ctx.right) e.ruleContext = (ctx) return e } fun binaryExpr(left: IEC61131Parser.ExpressionContext, op: Token, right: IEC61131Parser.ExpressionContext): Expression { val binOp = Operators.lookup(op.text) as BinaryOperator return BinaryExpression( left.accept(this) as Expression, binOp, right.accept(this) as Expression) } override fun visitInvocation(ctx: IEC61131Parser.InvocationContext): Any { val i = Invocation() i.callee = ctx.id.accept(this) as SymbolicReference if (ctx.expression().isEmpty()) { // Using parameters i.addParameters(allOf(ctx.param_assignment())) } else { // Using expressions i.addExpressionParameters(allOf(ctx.expression())) } i.ruleContext = (ctx) return i } override fun visitStatement_list( ctx: IEC61131Parser.Statement_listContext): Any { return StatementList(allOf(ctx.statement())) } override fun visitAssignment_statement( ctx: IEC61131Parser.Assignment_statementContext): Any { val ast = AssignmentStatement( ctx.a.accept(this) as SymbolicReference, ctx.expression().accept(this) as Expression) ast.reference = ctx.RASSIGN() != null ast.isAssignmentAttempt = ctx.ASSIGN_ATTEMPT() != null ast.ruleContext = ctx return ast } override fun visitStatement(ctx: IEC61131Parser.StatementContext): Any? { val statement = oneOf<Any>(ctx.assignment_statement(), ctx.if_statement(), ctx.exit_statement(), ctx.repeat_statement(), ctx.return_statement(), ctx.while_statement(), ctx.case_statement(), ctx.invocation_statement(), ctx.block_statement(), ctx.jump_statement(), ctx.for_statement(), ctx.special_statement()) as Statement val p = ctx.pragma().map { it.accept(this) as Pragma } if (p.isNullOrEmpty()) statement.pragmas += p return statement } override fun visitJump_statement(ctx: IEC61131Parser.Jump_statementContext) = JumpStatement(ctx.id.text) override fun visitLabel_statement(ctx: IEC61131Parser.Label_statementContext) = LabelStatement(ctx.id.text) override fun visitSymbolic_variable(ctx: IEC61131Parser.Symbolic_variableContext): Any { //TODO REWORK val ast = SymbolicReference() ast.ruleContext = ctx ast.identifier = ctx.a.text.trim('`') ast.sub = if (ctx.DOT() != null) ctx.other.accept(this) as SymbolicReference else null if (ctx.subscript_list() != null) { ast.subscripts = ctx.subscript_list().accept(this) as ExpressionList } ast.derefCount = ctx.deref.size return ast } override fun visitSubscript_list( ctx: IEC61131Parser.Subscript_listContext): ExpressionList { return ExpressionList(allOf<Expression>(ctx.expression())) } override fun visitDirect_variable( ctx: IEC61131Parser.Direct_variableContext): Any { val ast = DirectVariable(ctx.text) ast.ruleContext = ctx return ast } override fun visitReturn_statement(ctx: IEC61131Parser.Return_statementContext): Any { val ast = ReturnStatement() ast.ruleContext = ctx return ast // Utils.setPosition(ast, ctx.RETURN); } override fun visitInvocation_statement(ctx: IEC61131Parser.Invocation_statementContext): Any { val call = InvocationStatement() val o = ctx.invocation().accept(this) as Invocation call.callee = o.callee call.parameters = o.parameters call.ruleContext = ctx return call } override fun visitParam_assignment( ctx: IEC61131Parser.Param_assignmentContext): Any { val p = InvocationParameter() p.ruleContext = ctx if (ctx.ARROW_RIGHT() != null) { p.isOutput = true p.expression = ctx.v.accept(this) as Expression } else p.expression = ctx.expression().accept(this) as Expression if (ctx.id != null) p.name = ctx.id.text return p } override fun visitIf_statement( ctx: IEC61131Parser.If_statementContext): Any { val ast = IfStatement() ast.ruleContext = ctx for (i in ctx.cond.indices) { val c = ctx.cond[i].accept(this) as Expression val b = ctx.thenlist[i].accept(this) as StatementList val gs = GuardedStatement(c, b) gs.ruleContext = ctx.cond[i] ast.addGuardedCommand(gs) } if (ctx.ELSE() != null) { ast.elseBranch = ctx.elselist.accept(this) as StatementList } return ast } override fun visitCase_statement( ctx: IEC61131Parser.Case_statementContext): Any { val ast = CaseStatement() ast.ruleContext = ctx ast.cases.addAll(allOf<Case>(ctx.case_entry())) if (ctx.elselist != null) ast.elseCase = ctx.elselist.accept(this) as StatementList ast.expression = ctx.cond.accept(this) as Expression return ast } override fun visitCase_entry(ctx: IEC61131Parser.Case_entryContext): Any { val ast = Case() ast.ruleContext = ctx ast.conditions.addAll(allOf(ctx.case_condition())) ast.statements = ctx.statement_list().accept(this) as StatementList return ast } override fun visitCase_condition(ctx: IEC61131Parser.Case_conditionContext): Any { var cc: CaseCondition? = null if (ctx.IDENTIFIER() != null) { cc = CaseCondition.Enumeration(EnumLit(null, ctx.IDENTIFIER().text)) } if (ctx.integer() != null) { cc = CaseCondition.IntegerCondition(ctx.integer().accept(this) as IntegerLit) } if (ctx.subrange() != null) { val r = ctx.subrange().accept(this) as Range cc = CaseCondition.Range(Range(r.start, r.stop)) } if (ctx.cast() != null) { cc = CaseCondition.Enumeration(ctx.cast().accept(this) as EnumLit) } cc!!.ruleContext = ctx return cc } override fun visitFor_statement(ctx: IEC61131Parser.For_statementContext): Any { val ast = ForStatement() ast.ruleContext = ctx if (ctx.by != null) { ast.step = ctx.by.accept(this) as Expression } ast.variable = ctx.`var`.text ast.statements = ctx.statement_list().accept(this) as StatementList ast.stop = ctx.endPosition.accept(this) as Expression ast.start = ctx.begin.accept(this) as Expression return ast } override fun visitWhile_statement( ctx: IEC61131Parser.While_statementContext): Any { val ast = WhileStatement() ast.ruleContext = ctx ast.condition = ctx.expression().accept(this) as Expression ast.statements = ctx.statement_list().accept(this) as StatementList return ast } override fun visitRepeat_statement( ctx: IEC61131Parser.Repeat_statementContext): Any { val ast = RepeatStatement() ast.condition = ctx.expression().accept(this) as Expression ast.statements = ctx.statement_list().accept(this) as StatementList return ast } override fun visitExit_statement(ctx: IEC61131Parser.Exit_statementContext): Any { val ast = ExitStatement() ast.ruleContext = ctx return ast } override fun visitSpecial_statement(ctx: IEC61131Parser.Special_statementContext): SpecialStatement { val exprs = ctx.expression() .map { it.accept(this) as Expression } .toMutableList() val id = ctx.id?.text val s = when (val name = ctx.type.text) { "assert" -> SpecialStatement.Assert(exprs, id) "assume" -> SpecialStatement.Assume(exprs, id) "havoc" -> SpecialStatement.Havoc(exprs.map { it as SymbolicReference }.toMutableList(), id) else -> error("Special statement of name $name unknown/unsupported.") } s.ruleContext = ctx return s } //region sfc override fun visitSfc(ctx: IEC61131Parser.SfcContext): Any { sfc = SFCImplementation() ctx.sfc_network().forEach { nc -> sfc.networks.add(visitSfc_network(nc)) } return sfc } override fun visitSfc_network(ctx: IEC61131Parser.Sfc_networkContext): SFCNetwork { network = SFCNetwork() network.steps.add(visitInit_step(ctx.init_step())) network.ruleContext = ctx for (stepContext in ctx.step()) { network.steps.add(visitStep(stepContext)) } //ctx.action().forEach { a -> sfc!!.actions.add(visitAction(a)) } ctx.transition().forEach { t -> visitTransition(t) } return network } override fun visitAction(ctx: IEC61131Parser.ActionContext): ActionDeclaration { val action = ActionDeclaration() action.name = ctx.IDENTIFIER().symbol.text if (ctx.body().stBody() != null) action.stBody = ctx.body().stBody().accept(this) as StatementList if (ctx.body().sfc() != null) action.sfcBody = ctx.body().sfc().accept(this) as SFCImplementation if (ctx.body().ilBody() != null) action.ilBody = ctx.body().ilBody().accept(this) as IlBody if (ctx.body().fbBody() != null) action.fbBody = ctx.body().fbBody().accept(this) as FbdBody action.ruleContext = ctx return action } override fun visitStBody(ctx: IEC61131Parser.StBodyContext): Any { val statements = StatementList() if (ctx.startlbl != null) statements.add(ctx.startlbl.accept()) statements.addAll(ctx.startstmts.accept()); for (i in 0 until ctx.lbls.size) { statements.add(ctx.lbls[i].accept()) statements.addAll(ctx.stmts[i].accept()) } return statements } inline fun <T> ParserRuleContext?.accept(): T = this?.accept(this@IECParseTreeToAST) as T override fun visitInit_step(ctx: IEC61131Parser.Init_stepContext): SFCStep { currentStep = SFCStep() currentStep.name = ctx.step_name.text currentStep.isInitial = true visitActionAssociations(ctx.action_association()) currentStep.ruleContext = ctx return currentStep } private fun visitActionAssociations(seq: List<IEC61131Parser.Action_associationContext>) { seq.forEach { ctx -> visitAction_association(ctx) } } override fun visitAction_association(ctx: IEC61131Parser.Action_associationContext): Any? { // 'N' | 'R' | 'S' | 'P' | ( ( 'L' | 'D' | 'SD' | 'DS' | 'SL' ) ',' Action_Time ); val qualifier = SFCActionQualifier() if (null != ctx.actionQualifier().expression()) { val expr = ctx.actionQualifier().expression().accept(this) as Expression qualifier.time = expr } val q = ctx.actionQualifier().IDENTIFIER().text qualifier.qualifier = SFCActionQualifier.Qualifier.NON_STORED for (qual in SFCActionQualifier.Qualifier.values()) { if (qual.symbol.equals(q, ignoreCase = true)) qualifier.qualifier = qual } currentStep.addAction(qualifier, ctx.actionName.text) return null } override fun visitStep(ctx: IEC61131Parser.StepContext): SFCStep { currentStep = SFCStep() currentStep.ruleContext = ctx currentStep.name = ctx.step_name.text currentStep.isInitial = false visitActionAssociations(ctx.action_association()) currentStep.ruleContext = ctx return currentStep } override fun visitTransition(ctx: IEC61131Parser.TransitionContext): Any { val transition = SFCTransition() transition.ruleContext = ctx if (ctx.id != null) transition.name = ctx.id.text if (ctx.INTEGER_LITERAL() != null) { val s = split(ctx.INTEGER_LITERAL().text) val priority = s.number().toInt() transition.priority = priority } transition.to = visitSteps(ctx.to) transition.from = visitSteps(ctx.from) transition.guard = ctx.transitionCond().expression().accept(this) as Expression transition.from.forEach { it.outgoing.add(transition) } transition.to.forEach { it.incoming.add(transition) } return transition } override fun visitSteps(ctx: IEC61131Parser.StepsContext): MutableSet<SFCStep> { return ctx.IDENTIFIER() .map { n -> network.getStep(n.symbol.text) } .filter { it.isPresent() } .map { it.get() } .toHashSet() } //endregion //region il override fun visitIlBody(ctx: IEC61131Parser.IlBodyContext): IlBody { val body = IlBody() ctx.ilInstruction().map { it.accept(this) }.forEach { body.add(it as IlInstr) } return body } override fun visitIlInstruction(ctx: IEC61131Parser.IlInstructionContext): IlInstr { val instr: IlInstr = ctx.ilInstr().accept(this) as IlInstr if (ctx.COLON() != null) { instr.labelled = ctx.IDENTIFIER()?.text } instr.ruleContext = ctx return instr } override fun visitIlInstr(ctx: IEC61131Parser.IlInstrContext) = oneOf<IlInstr>(ctx.ilCall(), ctx.ilExpr(), ctx.ilFormalFunctionCall(), ctx.ilJump(), ctx.ilSimple(), ctx.ilFunctionCall())!! override fun visitIlSInstr(ctx: IEC61131Parser.IlSInstrContext) = oneOf<IlInstr>(ctx.ilExpr(), ctx.ilFormalFunctionCall(), ctx.ilSimple(), ctx.ilFunctionCall())!! override fun visitIlSimple(ctx: IEC61131Parser.IlSimpleContext) = SimpleInstr(SimpleOperand.valueOf(ctx.op.text), ctx.ilOperand().accept(this) as IlOperand) .also { it.ruleContext = ctx } override fun visitIlExpr(ctx: IEC61131Parser.IlExprContext) = ExprInstr(ExprOperand.valueOf(ctx.op.text), ctx.ilOperand()?.accept(this) as? IlOperand, ctx.ilSInstrList()?.accept(this) as? IlBody) .also { it.ruleContext = ctx } override fun visitIlSInstrList(ctx: IEC61131Parser.IlSInstrListContext): IlBody { val body = IlBody() ctx.ilSInstr().forEach { body += it.accept(this) as IlInstr } return body } override fun visitIlFunctionCall(ctx: IEC61131Parser.IlFunctionCallContext) = FunctionCallInstr(ctx.symbolic_variable().accept(this) as SymbolicReference, ctx.ilOperand().map { it.accept(this) as IlOperand }.toMutableList()) .also { it.ruleContext = ctx } override fun visitIlFormalFunctionCall(ctx: IEC61131Parser.IlFormalFunctionCallContext): CallInstr { return CallInstr(CallOperand.IMPLICIT_CALLED, ctx.symbolic_variable().accept(this) as SymbolicReference, ctx.il_param_assignment().map { it.accept(this) as IlParameter }.toMutableList()) .also { it.ruleContext = ctx } } override fun visitIlJump(ctx: IEC61131Parser.IlJumpContext) = JumpInstr(JumpOperand.valueOf(ctx.op.text), ctx.label.text) .also { it.ruleContext = ctx } override fun visitIlCall(ctx: IEC61131Parser.IlCallContext): CallInstr { val callInstr = CallInstr(CallOperand.valueOf(ctx.op.text), ctx.symbolic_variable().accept(this) as SymbolicReference, ctx.il_param_assignment() .map { it.accept(this) as IlParameter }.toMutableList()) val seq = if (ctx.LPAREN() != null) { ctx.ilOperand() .map { it.accept(this) as IlOperand } .map { IlParameter(right = it) } } else { ctx.il_param_assignment().map { it.accept(this) as IlParameter } } callInstr.parameters = seq.toMutableList() return callInstr } override fun visitIlOperand(ctx: IEC61131Parser.IlOperandContext): Any { if (ctx.constant() != null) { val const = ctx.constant()!!.accept(this) as Literal return IlOperand.Constant(const).also { it.ruleContext = ctx.symbolic_variable() } } if (ctx.symbolic_variable() != null) { val a = ctx.symbolic_variable() val sr = a.accept(this) as SymbolicReference return IlOperand.Variable(sr).also { it.ruleContext = ctx.symbolic_variable() } } throw IllegalStateException() } override fun visitIl_param_assignment(ctx: IEC61131Parser.Il_param_assignmentContext): IlParameter { return IlParameter(negated = ctx.NOT() != null, input = ctx.ASSIGN() != null, left = ctx.id.text, right = if (ctx.ASSIGN() != null) ctx.arg.accept(this) as IlOperand else IlOperand.Variable(SymbolicReference(ctx.target.text)) ) } //endregion override fun visitFbBody(ctx: IEC61131Parser.FbBodyContext): FbdBody { val json = ctx.FBD_CODE().text.removeSurrounding("(***FBD", "***)").trim() return FbdBody.fromJson(json) } }
gpl-3.0
8d034bdfe35eaa06ea39fd9f3a117940
36.28642
158
0.614065
4.171163
false
false
false
false
Stargamers/FastHub
app/src/main/java/com/fastaccess/ui/modules/repos/projects/list/RepoProjectPresenter.kt
6
10647
package com.fastaccess.ui.modules.repos.projects.list import android.os.Bundle import android.view.View import com.apollographql.apollo.rx2.Rx2Apollo import com.fastaccess.data.dao.types.IssueState import com.fastaccess.helper.BundleConstant import com.fastaccess.helper.Logger import com.fastaccess.provider.rest.ApolloProdivder import com.fastaccess.ui.base.mvp.presenter.BasePresenter import com.fastaccess.ui.modules.repos.projects.details.ProjectPagerActivity import github.OrgProjectsClosedQuery import github.OrgProjectsOpenQuery import github.RepoProjectsClosedQuery import github.RepoProjectsOpenQuery import io.reactivex.Observable /** * Created by kosh on 09/09/2017. */ class RepoProjectPresenter : BasePresenter<RepoProjectMvp.View>(), RepoProjectMvp.Presenter { private val projects = arrayListOf<RepoProjectsOpenQuery.Node>() private var page: Int = 0 private var previousTotal: Int = 0 private var lastPage = Integer.MAX_VALUE @com.evernote.android.state.State var login: String = "" @com.evernote.android.state.State var repoId: String? = null var count: Int = 0 val pages = arrayListOf<String>() override fun onItemClick(position: Int, v: View, item: RepoProjectsOpenQuery.Node) { item.databaseId()?.let { ProjectPagerActivity.startActivity(v.context, login, repoId, it.toLong(), isEnterprise) } } override fun onItemLongClick(position: Int, v: View?, item: RepoProjectsOpenQuery.Node?) {} override fun onFragmentCreate(bundle: Bundle?) { bundle?.let { repoId = it.getString(BundleConstant.ID) login = it.getString(BundleConstant.EXTRA) } } override fun getProjects(): ArrayList<RepoProjectsOpenQuery.Node> = projects override fun getCurrentPage(): Int = page override fun getPreviousTotal(): Int = previousTotal override fun setCurrentPage(page: Int) { this.page = page } override fun setPreviousTotal(previousTotal: Int) { this.previousTotal = previousTotal } override fun onCallApi(page: Int, parameter: IssueState?): Boolean { if (page == 1) { lastPage = Integer.MAX_VALUE sendToView { view -> view.getLoadMore().reset() } } if (page > lastPage || lastPage == 0 || parameter == null) { sendToView({ it.hideProgress() }) return false } currentPage = page Logger.e(login) val repoId = repoId val apollo = ApolloProdivder.getApollo(isEnterprise) if (repoId != null && !repoId.isNullOrBlank()) { if (parameter == IssueState.open) { val query = RepoProjectsOpenQuery.builder() .name(repoId) .owner(login) .page(getPage()) .build() makeRestCall(Rx2Apollo.from(apollo.query(query)) .flatMap { val list = arrayListOf<RepoProjectsOpenQuery.Node>() it.data()?.repository()?.let { it.projects().let { lastPage = if (it.pageInfo().hasNextPage()) Int.MAX_VALUE else 0 pages.clear() count = it.totalCount() it.edges()?.let { pages.addAll(it.map { it.cursor() }) } it.nodes()?.let { list.addAll(it) } } } return@flatMap Observable.just(list) }, { sendToView({ v -> v.onNotifyAdapter(it, page) if (page == 1) v.onChangeTotalCount(count) }) }) } else { val query = RepoProjectsClosedQuery.builder() .name(repoId) .owner(login) .page(getPage()) .build() makeRestCall(Rx2Apollo.from(apollo.query(query)) .flatMap { val list = arrayListOf<RepoProjectsOpenQuery.Node>() it.data()?.repository()?.let { it.projects().let { lastPage = if (it.pageInfo().hasNextPage()) Int.MAX_VALUE else 0 pages.clear() count = it.totalCount() it.edges()?.let { pages.addAll(it.map { it.cursor() }) } it.nodes()?.let { val toConvert = arrayListOf<RepoProjectsOpenQuery.Node>() it.onEach { val columns = RepoProjectsOpenQuery.Columns(it.columns().__typename(), it.columns().totalCount()) val node = RepoProjectsOpenQuery.Node(it.__typename(), it.name(), it.number(), it.body(), it.createdAt(), it.id(), it.viewerCanUpdate(), columns, it.databaseId()) toConvert.add(node) } list.addAll(toConvert) } } } return@flatMap Observable.just(list) }, { sendToView({ v -> v.onNotifyAdapter(it, page) if (page == 1) v.onChangeTotalCount(count) }) }) } } else { if (parameter == IssueState.open) { val query = OrgProjectsOpenQuery.builder() .owner(login) .page(getPage()) .build() makeRestCall(Rx2Apollo.from(apollo.query(query)) .flatMap { val list = arrayListOf<RepoProjectsOpenQuery.Node>() it.data()?.organization()?.let { it.projects().let { lastPage = if (it.pageInfo().hasNextPage()) Int.MAX_VALUE else 0 pages.clear() count = it.totalCount() it.edges()?.let { pages.addAll(it.map { it.cursor() }) } it.nodes()?.let { val toConvert = arrayListOf<RepoProjectsOpenQuery.Node>() it.onEach { val columns = RepoProjectsOpenQuery.Columns(it.columns().__typename(), it.columns().totalCount()) val node = RepoProjectsOpenQuery.Node(it.__typename(), it.name(), it.number(), it.body(), it.createdAt(), it.id(), it.viewerCanUpdate(), columns, it.databaseId()) toConvert.add(node) } list.addAll(toConvert) } } } return@flatMap Observable.just(list) }, { sendToView({ v -> v.onNotifyAdapter(it, page) if (page == 1) v.onChangeTotalCount(count) }) }) } else { val query = OrgProjectsClosedQuery.builder() .owner(login) .page(getPage()) .build() makeRestCall(Rx2Apollo.from(apollo.query(query)) .flatMap { val list = arrayListOf<RepoProjectsOpenQuery.Node>() it.data()?.organization()?.let { it.projects().let { lastPage = if (it.pageInfo().hasNextPage()) Int.MAX_VALUE else 0 pages.clear() count = it.totalCount() it.edges()?.let { pages.addAll(it.map { it.cursor() }) } it.nodes()?.let { val toConvert = arrayListOf<RepoProjectsOpenQuery.Node>() it.onEach { val columns = RepoProjectsOpenQuery.Columns(it.columns().__typename(), it.columns().totalCount()) val node = RepoProjectsOpenQuery.Node(it.__typename(), it.name(), it.number(), it.body(), it.createdAt(), it.id(), it.viewerCanUpdate(), columns, it.databaseId()) toConvert.add(node) } list.addAll(toConvert) } } } return@flatMap Observable.just(list) }, { sendToView({ v -> v.onNotifyAdapter(it, page) if (page == 1) v.onChangeTotalCount(count) }) }) } } return true } private fun getPage(): String? = if (pages.isNotEmpty()) pages.last() else null }
gpl-3.0
0313e75865acd8377ca2c66a99a68c0a
46.963964
141
0.415328
5.974747
false
false
false
false
AlmasB/FXGL
fxgl-core/src/main/kotlin/com/almasb/fxgl/audio/impl/DesktopAudio.kt
1
1594
/* * FXGL - JavaFX Game Library. The MIT License (MIT). * Copyright (c) AlmasB ([email protected]). * See LICENSE for details. */ package com.almasb.fxgl.audio.impl import com.almasb.fxgl.audio.Audio import com.almasb.fxgl.audio.AudioType import javafx.scene.media.AudioClip import javafx.scene.media.MediaPlayer /** * @author Almas Baimagambetov ([email protected]) */ class DesktopMusic(private val mediaPlayer: MediaPlayer) : Audio(AudioType.MUSIC) { override fun setLooping(looping: Boolean) { mediaPlayer.cycleCount = if (looping) Integer.MAX_VALUE else 1 } override fun setVolume(volume: Double) { mediaPlayer.volume = volume } override fun setOnFinished(action: Runnable) { mediaPlayer.onEndOfMedia = action } override fun play() { mediaPlayer.play() } override fun pause() { mediaPlayer.pause() } override fun stop() { mediaPlayer.stop() } override fun dispose() { mediaPlayer.dispose() } } class DesktopSound(private val clip: AudioClip) : Audio(AudioType.SOUND) { override fun setLooping(looping: Boolean) { clip.cycleCount = if (looping) Integer.MAX_VALUE else 1 } override fun setVolume(volume: Double) { clip.volume = volume } override fun setOnFinished(action: Runnable) { // no-op } override fun play() { clip.play() } override fun pause() { clip.stop() } override fun stop() { clip.stop() } override fun dispose() { // no-op } }
mit
48213ac4f1d3de24ebe7fca20e9be925
19.714286
83
0.631117
3.965174
false
false
false
false
googlecodelabs/android-compose-codelabs
AdvancedStateAndSideEffectsCodelab/app/src/main/java/androidx/compose/samples/crane/base/CraneDrawer.kt
1
2085
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.samples.crane.base import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.samples.crane.R import androidx.compose.samples.crane.ui.CraneTheme import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp private val screens = listOf("Find Trips", "My Trips", "Saved Trips", "Price Alerts", "My Account") @Composable fun CraneDrawer(modifier: Modifier = Modifier) { Column( modifier .fillMaxSize() .padding(start = 24.dp, top = 48.dp) ) { Image( painter = painterResource(R.drawable.ic_crane_drawer), contentDescription = stringResource(R.string.cd_drawer) ) for (screen in screens) { Spacer(Modifier.height(24.dp)) Text(text = screen, style = MaterialTheme.typography.h4) } } } @Preview @Composable fun CraneDrawerPreview() { CraneTheme { CraneDrawer() } }
apache-2.0
0c4214c4ffccf48a140994136ba5b745
32.629032
99
0.736211
4.136905
false
false
false
false
ajalt/clikt
clikt/src/commonMain/kotlin/com/github/ajalt/clikt/parameters/options/ValueWithDefault.kt
1
513
package com.github.ajalt.clikt.parameters.options /** A container for a value that can have a default value and can be manually set */ data class ValueWithDefault<out T>(val explicit: T?, val default: T) { val value: T get() = explicit ?: default } /** Create a copy with a new [default] value */ fun <T> ValueWithDefault<T>.withDefault(default: T) = copy(default = default) /** Create a copy with a new [explicit] value */ fun <T> ValueWithDefault<T>.withExplicit(explicit: T) = copy(explicit = explicit)
apache-2.0
9fe0a5081e1d992f2cdcd45fb8136538
41.75
84
0.7154
3.638298
false
false
false
false
thetric/ilias-downloader
src/main/kotlin/com/github/thetric/iliasdownloader/connector/IliasItemParser.kt
1
1216
package com.github.thetric.iliasdownloader.connector import com.github.thetric.iliasdownloader.connector.model.Course import org.jsoup.nodes.Element internal class IliasItemParser( private val courseWebDavPrefix: String, private val courseLinkPrefix: String ) { fun parseCourse(courseElement: Element): Course { val courseId = getCourseId(courseElement) val courseName = courseElement.text() val courseUrl = "$courseWebDavPrefix$courseId/" return Course(id = courseId, url = courseUrl, name = courseName) } private fun getCourseId(aTag: Element): Long { val href = aTag.attr("href") // href="http://www.ilias.fh-dortmund.de/ilias/goto_ilias-fhdo_crs_\d+.html" val idString = href.replaceFirst(courseLinkPrefix, "").replace(".html", "") // der Rest muss ein int sein return parseId(href, idString) } } private fun parseId(href: String, probableIdString: String): Long { try { return probableIdString.toLong() } catch (e: NumberFormatException) { val msg = "Failed to parse \'$probableIdString\', original string was \'$href\'" throw IliasItemIdStringParsingException(msg, e) } }
mit
cd01b791884acb82db3dd2c3478ef498
33.742857
88
0.685033
4.06689
false
false
false
false
lice-lang/lice
src/test/kotlin/org/lice/parse/IntegratedTest.kt
1
2821
package org.lice.parse import org.intellij.lang.annotations.Language import org.junit.Test import org.lice.Lice import org.lice.core.SymbolList import org.lice.evalTo import kotlin.test.assertFails class IntegratedTest { @Test fun test1() { @Language("Lice") val srcCode = """ (def fibonacci n (if (== n 1) (1) (if (== n 2) (1) (+ (fibonacci (- n 1)) (fibonacci (- n 2)))))) (-> i 1) (while (< i 20) (|> (print (fibonacci i)) (print ("\n")) (-> i (+ i 1)))) (fibonacci 10) """ srcCode evalTo 55 } @Test fun test2() { @Language("Lice") val srcCode = """ (print (+ 1 1) "\n") (print (- 10N 1.0) "\n") (print (/ 10.2M 5) "\n") (print (/ 10 5.0) "\n") (print (* 10 5.2M) "\n") (alias + plus) (undef +) (alias plus +) (print (+ 1 2) "\n") (type 23) (-> ass 10) (str->sym "ass") (print (format "ass %s can", "we") "\n") """ Parser.parseTokenStream(Lexer(srcCode)).accept(SymbolList()).eval() } @Test fun test3() { /// Intentionally empty translation unit val srcCode = """ """ srcCode evalTo null } @Test fun test4() { val srcCode = """ ; defining functions (def check (if (def? println) (print "defined: println. ") (print "undefined: println. "))) ; calling functions (check) (def println anything (print anything " ")) (check) ; plus (println (+ 1 1)) (println (|| true false)) ; defining call-by-name functions (defexpr unless cond block (|> (if (! cond) (block)))) ; calling that function (unless false (lambda (println "on! false"))) ; loops (def loop count block (|> (-> i 0) (while (< i count) (|> (block i) (-> i (+ i 1)))))) (loop 20 (lambda i (println i))) ; let (defexpr let x y block (|> (-> x y) (block) (undef x))) (let reimu 100 (lambda (|> (print x)))) ; extern functions ; must be a static Java function (extern "java.util.Objects" "equals") ; calling the extern function (equals 1 1) """ Lice.runBarely(srcCode) } @Test fun test5() { "233" evalTo 233 "0x233" evalTo 0x233 "0b10101" evalTo 0b10101 } @Test fun failTests() { assertFails { Lice.runBarely("1a") } assertFails { Lice.runBarely("0xz") } assertFails { Lice.runBarely("0b2") } assertFails { Lice.runBarely("0o9") } assertFails { Lice.runBarely("undefined-variable") } assertFails { Lice.runBarely("(+ (->str 1))") } assertFails { Lice.runBarely("(def)") } assertFails { Lice.runBarely("(def name)") } assertFails { Lice.runBarely("(-> name)") } assertFails { Lice.runBarely("(; 1)") } assertFails { Lice.runBarely(""""\g"""") } assertFails { Lice.runBarely("(") } assertFails { Lice.runBarely(")") } assertFails { Lice.runBarely("\"") } assertFails { SymbolList().extractLiceFunction("undefined-function")(emptyList()) } assertFails { SymbolList().extractLiceVariable("undefined-variable") } } }
gpl-3.0
b2e141f35bd0facc54ab51d93c27b2bf
17.682119
85
0.61184
2.762977
false
true
false
false
android/user-interface-samples
SplashScreen/app/src/main/java/com/example/android/splashscreen/CustomActivity.kt
1
3282
/* * Copyright (C) 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.splashscreen import android.animation.ObjectAnimator import android.os.Bundle import android.view.View import android.view.animation.AnticipateInterpolator import androidx.core.animation.doOnEnd import androidx.core.splashscreen.SplashScreenViewProvider /** * "Custom Splash Screen". This is similar to [AnimatedActivity], but also has a custom animation * for the splash screen exit. */ class CustomActivity : MainActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // This callback is called when the app is ready to draw its content and replace the splash // screen. We can customize the exit animation of the splash screen here. splashScreen.setOnExitAnimationListener { splashScreenViewProvider -> // The animated vector drawable is already animating at this point. Depending on the // duration of the app launch, the animation might not have finished yet. // Check the extension property to see how to calculate the remaining duration of the // icon animation. val remainingDuration = splashScreenViewProvider.iconAnimationRemainingDurationMillis // The callback gives us a `SplashScreenViewProvider` as its parameter. It holds the // view for the entire splash screen. val splashScreenView = splashScreenViewProvider.view val slideUp = ObjectAnimator.ofFloat( splashScreenView, View.TRANSLATION_Y, 0f, -splashScreenView.height.toFloat() ) slideUp.interpolator = AnticipateInterpolator() slideUp.duration = 200L // Make sure to call SplashScreenViewProvider.remove at the end of your custom // animation. slideUp.doOnEnd { splashScreenViewProvider.remove() } // For the purpose of the demo, we wait for the icon animation to finish. Your app // should prioritize showing app content as soon as possible. slideUp.startDelay = remainingDuration slideUp.start() } } } /** * Calculates the remaining duration of the icon animation based on the total duration * ([SplashScreenViewProvider.iconAnimationDurationMillis]) and the start time * ([SplashScreenViewProvider.iconAnimationStartMillis]) */ private val SplashScreenViewProvider.iconAnimationRemainingDurationMillis: Long get() { return iconAnimationDurationMillis - (System.currentTimeMillis() - iconAnimationStartMillis) .coerceAtLeast(0L) }
apache-2.0
5cf93d915d374fb6ae2878a4331538e3
41.076923
100
0.705058
5.293548
false
false
false
false
fnouama/gradle-kotlin
src/main/kotlin/services/WeatherService.kt
1
934
package services import com.github.kittinunf.fuel.httpGet import com.github.salomonbrys.kotson.double import com.github.salomonbrys.kotson.get import com.github.salomonbrys.kotson.obj import com.google.gson.JsonParser import nl.komponents.kovenant.Promise import nl.komponents.kovenant.task import java.nio.charset.Charset data class SunWeatherInfo(val sunInfo: SunInfo, val temperature: Double) class WeatherService { fun getTemperature(lat: Double, lon: Double): Promise<Double, Exception> = task { val url = "http://api.openweathermap.org/data/2.5/" + "weather?lat=-33.8830&lon=151.2167&units=metric" + "&APPID=c811ac9ca7d078bc338e0e6b46efac58" val (request, response, result) = url.httpGet().responseString() val jsonStr = String(response.data, Charset.forName("UTF-8")) val json = JsonParser().parse(jsonStr).obj json["main"]["temp"].double } }
mit
ff9b8df85a8bc50bc71bb5f781515046
36.36
85
0.718415
3.606178
false
false
false
false
kmizu/kollection
src/main/kotlin/com/github/kmizu/kollection/KTreeSet.kt
1
1611
package com.github.kmizu.kollection import com.github.kmizu.kollection.RedBlackTree as RB import com.github.kmizu.kollection.RedBlackTree.Tree import com.github.kmizu.kollection.RedBlackTree.Tree.RedTree import com.github.kmizu.kollection.RedBlackTree.Tree.BlackTree import java.util.* class KTreeSet<A:Any>(val tree: Tree<A, Unit>?, val comparator: Comparator<A>): KSet<A> { companion object { fun <A:Any> empty(comparator: Comparator<A>): KTreeSet<A> = KTreeSet(null, comparator) } private fun elementsOf(tree: Tree<A, Unit>?): KList<A> = run { if(tree === null) { KList.Nil } else { elementsOf(tree.left) concat KList(tree.key) concat elementsOf(tree.right) } } private fun newSet(t: RB.Tree<A, Unit>?): KTreeSet<A> = KTreeSet<A>(t, comparator) override fun iterator(): Iterator<A> = object: Iterator<A> { private var list: KList<A> = elementsOf(tree) override fun hasNext(): Boolean = list is KList.Cons override fun next(): A = run { val v = list.hd list = list.tl v } } override infix operator fun plus(element: A): KTreeSet<A> = run { newSet(RB.update(tree, element, Unit, false, comparator)) } override fun remove(element:A): KTreeSet<A> = run { if (!RB.contains(tree, element, comparator)) this else newSet(RB.delete(tree, element, comparator)) } override fun get(element: A): Boolean = RB.contains(tree, element, comparator) override val isEmpty: Boolean get() = RB.isEmpty(tree) }
mit
a53fd7a6fdd0991d6084144bf476f540
31.877551
94
0.639975
3.729167
false
false
false
false
carlphilipp/chicago-commutes
android-app/src/main/kotlin/fr/cph/chicago/entity/BusResponse.kt
1
3725
/** * Copyright 2021 Carl-Philipp Harmant * * * 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 fr.cph.chicago.entity import com.fasterxml.jackson.annotation.JsonProperty data class BusArrivalResponse( @JsonProperty("bustime-response") val bustimeResponse: BustimeResponse) { data class BustimeResponse(var prd: List<Prd>? = null, var error: List<Error>? = null) data class Prd( val tmstmp: String, val typ: String, val stpnm: String, val stpid: String, val vid: String, val dstp: Int, val rt: String, val rtdd: String, val rtdir: String, val des: String, val prdtm: String, val tablockid: String, val tatripid: String, val dly: Boolean, val prdctdn: String, val zone: String) } data class BusDirectionResponse( @JsonProperty("bustime-response") val bustimeResponse: BustimeResponse) { data class BustimeResponse(val directions: List<Direction>? = null, val error: List<Error>? = null) data class Direction(val dir: String) } data class BusPatternResponse( @JsonProperty("bustime-response") var bustimeResponse: BustimeResponse) { data class BustimeResponse(val ptr: List<Ptr>? = null, val error: List<Error>? = null) data class Ptr( val pid: Int, val ln: Int, val rtdir: String, val pt: List<Pt>) data class Pt( val seq: Int, val lat: Double, var lon: Double, val typ: String, val stpid: String? = null, val stpnm: String? = null, var pdist: Int) } data class BusPositionResponse(@JsonProperty("bustime-response") var bustimeResponse: BustimeResponse) { data class BustimeResponse(val vehicle: List<Vehicle>? = null, val error: List<Error>? = null) data class Vehicle( val vid: String, val tmstmp: String, val lat: String, val lon: String, val hdg: String, val pid: Int, val rt: String, val des: String, val pdist: Int, val dly: Boolean, val tatripid: String, val tablockid: String, val zone: String ) } data class BusRoutesResponse( @JsonProperty("bustime-response") val bustimeResponse: BustimeResponse) { data class BustimeResponse(var routes: List<Route>) data class Route( @JsonProperty("rt") val routeId: String, @JsonProperty("rtnm") val routeName: String) } data class BusStopsResponse( @JsonProperty("bustime-response") val bustimeResponse: BustimeResponse) { data class BustimeResponse(var stops: List<Stop>? = null, var error: List<Error>? = null) data class Stop( val stpid: String, val stpnm: String, val lat: Double, val lon: Double) } data class Error(private val underlying: HashMap<String, Any> = HashMap()) : MutableMap<String, Any> by underlying { fun noServiceScheduled(): Boolean { if (!this.contains("msg")) { return false } val msg = this.getValue("msg") return "No service scheduled" == msg || "No arrival times" == msg } }
apache-2.0
fbc459f8bded61787763d3f1465b16cc
26.592593
116
0.635973
3.84814
false
false
false
false
jaychang0917/SimpleApiClient
library-jsonparser-gson/src/main/java/com/jaychang/sac/jsonparser/gson/GsonJsonParser.kt
1
1458
package com.jaychang.sac.jsonparser.gson import com.google.gson.* import retrofit2.Converter import retrofit2.converter.gson.GsonConverterFactory import java.lang.reflect.Type class GsonJsonParser : com.jaychang.sac.JsonParser { private var gson = Gson() override fun getConverterFactory(): Converter.Factory { return GsonConverterFactory.create(gson) } override fun <T> parse(json: String, typeOfT: Type, keyPath: String?): T { return if (keyPath == null) { gson.fromJson(json, typeOfT) } else { createGson(typeOfT, keyPath).fromJson(json, typeOfT) } } override fun update(type: Type, keyPath: String) { gson = createGson(type, keyPath) } private fun createGson(type: Type, keyPath: String): Gson { val deserializer = KeyPathDeserializer(keyPath) return GsonBuilder().registerTypeAdapter(type, deserializer).create() } private class KeyPathDeserializer(private val keyPath: String) : JsonDeserializer<Any> { override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): Any { val parts = keyPath.split(".") var jsonObject = json.asJsonObject var jsonElement: JsonElement = jsonObject[parts[0]] for (part in parts) { jsonElement = jsonObject[part] if (jsonElement is JsonObject) { jsonObject = jsonElement.asJsonObject } } return Gson().fromJson(jsonElement, typeOfT) } } }
apache-2.0
fdb02e59c02d24b8ba1ca3eadc06aacb
29.375
106
0.70096
4.263158
false
false
false
false
halawata13/ArtichForAndroid
app/src/main/java/net/halawata/artich/model/menu/CommonMenu.kt
2
706
package net.halawata.artich.model.menu import android.content.res.Resources import android.database.sqlite.SQLiteOpenHelper import net.halawata.artich.entity.SideMenuItem import net.halawata.artich.enum.Media class CommonMenu(helper: SQLiteOpenHelper, resources: Resources) : MediaMenu(helper, resources) { override fun get(): ArrayList<String> = fetch(Media.COMMON) override fun save(data: ArrayList<String>) { update(Media.COMMON, data) } override fun getMenuList(): ArrayList<SideMenuItem> = arrayListOf() override fun getUrlStringFrom(title: String): String? { val list = getMenuList() return list.firstOrNull { it.title == title }?.urlString } }
mit
77fc330869fe9f060b0caae0711b47e4
29.695652
97
0.733711
4.177515
false
false
false
false
robinverduijn/gradle
buildSrc/subprojects/docs/src/main/kotlin/org/gradle/gradlebuild/docs/RenderMarkdownTask.kt
1
1541
package org.gradle.gradlebuild.docs import com.vladsch.flexmark.ext.tables.TablesExtension import com.vladsch.flexmark.html.HtmlRenderer import com.vladsch.flexmark.parser.Parser import com.vladsch.flexmark.util.options.MutableDataSet import org.gradle.api.DefaultTask import org.gradle.api.tasks.CacheableTask import org.gradle.api.tasks.Input import org.gradle.api.tasks.InputFile import org.gradle.api.tasks.OutputFile import org.gradle.api.tasks.PathSensitive import org.gradle.api.tasks.PathSensitivity import org.gradle.api.tasks.TaskAction import java.io.File import java.nio.charset.Charset import java.nio.charset.Charset.defaultCharset import javax.inject.Inject @CacheableTask open class RenderMarkdownTask @Inject constructor( @get:PathSensitive(PathSensitivity.NONE) @get:InputFile val markdownFile: File, @get:OutputFile val destination: File ) : DefaultTask() { @Input val inputEncoding = defaultCharset().name() @Input val outputEncoding = defaultCharset().name() @TaskAction fun process() { val options = MutableDataSet().apply { set(Parser.EXTENSIONS, listOf(TablesExtension.create())) } val parser = Parser.builder(options).build() val renderer = HtmlRenderer.builder(options).build() val markdown = markdownFile.readText(Charset.forName(inputEncoding)) val html = renderer.render(parser.parse(markdown)) destination.writeText(html, Charset.forName(outputEncoding)) } } private const val PEGDOWN_PARSING_TIMEOUT_MILLIS = 10_000L
apache-2.0
ae9bc937a2a5754be162a52b5a017ea3
31.787234
105
0.771577
4.098404
false
false
false
false
wireapp/wire-android
app/src/main/kotlin/com/waz/zclient/core/images/AssetKey.kt
1
786
package com.waz.zclient.core.images import com.bumptech.glide.load.Key import com.bumptech.glide.load.Options import java.security.MessageDigest class AssetKey( private val key: String, private val width: Int, private val height: Int, private val options: Options ) : Key { override fun hashCode(): Int = toString().hashCode() override fun equals(other: Any?): Boolean { return other is AssetKey && other.key == this.key && other.width == this.width && other.height == this.height && other.options == this.options } override fun toString(): String = "$key-$width-$height-$options" override fun updateDiskCacheKey(messageDigest: MessageDigest) = messageDigest.update(toString().toByteArray(Key.CHARSET)) }
gpl-3.0
760b765ff90b5b32c980905de719e1e4
30.44
72
0.683206
4.225806
false
false
false
false
robinverduijn/gradle
buildSrc/subprojects/kotlin-dsl/src/main/kotlin/accessors/accessors.kt
1
1723
/* * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package accessors import org.gradle.api.Project import org.gradle.api.artifacts.dsl.RepositoryHandler import org.gradle.api.file.SourceDirectorySet import org.gradle.api.plugins.BasePluginConvention import org.gradle.api.plugins.ExtensionAware import org.gradle.api.plugins.JavaPluginConvention import org.gradle.api.reporting.ReportingExtension import org.gradle.api.tasks.GroovySourceSet import org.gradle.api.tasks.SourceSet import org.gradle.plugins.ide.eclipse.model.EclipseModel import org.gradle.plugins.javascript.base.JavaScriptRepositoriesExtension import org.gradle.kotlin.dsl.* val Project.base get() = the<BasePluginConvention>() val Project.java get() = the<JavaPluginConvention>() val Project.reporting get() = the<ReportingExtension>() val SourceSet.groovy: SourceDirectorySet get() = withConvention(GroovySourceSet::class) { groovy } fun Project.eclipse(configure: EclipseModel.() -> Unit): Unit = extensions.configure("eclipse", configure) val RepositoryHandler.javaScript get() = (this as ExtensionAware).the<JavaScriptRepositoriesExtension>()
apache-2.0
5d7d961d82196a7f6e1291a0d507f495
27.716667
75
0.775972
4.161836
false
false
false
false
yshrsmz/monotweety
app2/src/main/java/net/yslibrary/monotweety/ui/base/ContextExtensions.kt
1
1038
package net.yslibrary.monotweety.ui.base import android.content.Context import android.content.Intent import android.net.Uri import android.util.TypedValue import androidx.annotation.AttrRes fun Context.openExternalAppWithUrl(url: String) { val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url)) startActivity(intent) } fun Context.openExternalAppWithShareIntent(text: String) { val intent = Intent(Intent.ACTION_SEND) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) .putExtra(Intent.EXTRA_TEXT, text) .setType("text/plain") startActivity(intent) } fun Context.getIntValueFromAttribute(@AttrRes attrId: Int): Int { val tv = TypedValue() theme.resolveAttribute(attrId, tv, true) return tv.data } fun Context.getColorFromAttribute(@AttrRes attrId: Int): Int { val tv = TypedValue() theme.resolveAttribute(attrId, tv, true) val arr = obtainStyledAttributes(tv.data, intArrayOf(attrId)) return try { arr.getColor(0, -1) } finally { arr.recycle() } }
apache-2.0
41058662de372ede96ecde3f2ee9142f
26.315789
65
0.7158
3.830258
false
false
false
false
charlesmadere/smash-ranks-android
smash-ranks-android/app/src/main/java/com/garpr/android/features/players/PlayersViewModel.kt
1
4445
package com.garpr.android.features.players import androidx.annotation.WorkerThread import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.garpr.android.data.models.AbsPlayer import com.garpr.android.data.models.FavoritePlayer import com.garpr.android.data.models.Optional import com.garpr.android.data.models.PlayersBundle import com.garpr.android.data.models.Region import com.garpr.android.extensions.takeSingle import com.garpr.android.features.common.viewModels.BaseViewModel import com.garpr.android.misc.PlayerListBuilder import com.garpr.android.misc.PlayerListBuilder.PlayerListItem import com.garpr.android.misc.Schedulers import com.garpr.android.misc.Searchable import com.garpr.android.misc.ThreadUtils import com.garpr.android.misc.Timber import com.garpr.android.repositories.IdentityRepository import com.garpr.android.repositories.PlayersRepository import io.reactivex.Single import io.reactivex.functions.BiFunction class PlayersViewModel( private val identityRepository: IdentityRepository, private val playerListBuilder: PlayerListBuilder, private val playersRepository: PlayersRepository, private val schedulers: Schedulers, private val threadUtils: ThreadUtils, private val timber: Timber ) : BaseViewModel(), Searchable { private val _stateLiveData = MutableLiveData<State>() val stateLiveData: LiveData<State> = _stateLiveData private var state: State = State() set(value) { field = value _stateLiveData.postValue(value) } companion object { private const val TAG = "PlayersViewModel" } init { initListeners() } fun fetchPlayers(region: Region) { state = state.copy(isFetching = true) disposables.add(Single.zip(playersRepository.getPlayers(region), identityRepository.identityObservable.takeSingle(), BiFunction<PlayersBundle, Optional<FavoritePlayer>, Pair<PlayersBundle, Optional<FavoritePlayer>>> { t1, t2 -> Pair(t1, t2) }) .subscribeOn(schedulers.background) .observeOn(schedulers.background) .subscribe({ (bundle, identity) -> val list = playerListBuilder.create(bundle, identity.orNull()) state = state.copy( hasError = false, isEmpty = list.isNullOrEmpty(), isFetching = false, showSearchIcon = !list.isNullOrEmpty(), list = list, searchResults = null ) }, { timber.e(TAG, "Error fetching players", it) state = state.copy( hasError = true, isEmpty = false, isFetching = false, showSearchIcon = false, list = null, searchResults = null ) })) } private fun initListeners() { disposables.add(identityRepository.identityObservable .subscribeOn(schedulers.background) .observeOn(schedulers.background) .subscribe { identity -> refreshIdentity(identity.orNull()) }) } @WorkerThread private fun refreshIdentity(identity: AbsPlayer?) { val list = playerListBuilder.refresh(state.list, identity) val searchResults = playerListBuilder.refresh(state.searchResults, identity) state = state.copy( list = list, searchResults = searchResults ) } override fun search(query: String?) { threadUtils.background.submit { val searchResults = playerListBuilder.search(state.list, query) state = state.copy(searchResults = searchResults) } } data class State( val hasError: Boolean = false, val isEmpty: Boolean = false, val isFetching: Boolean = false, val showSearchIcon: Boolean = false, val list: List<PlayerListItem>? = null, val searchResults: List<PlayerListItem>? = null ) }
unlicense
7b595ea906bf82765f4abfd17069ed3e
35.434426
84
0.603825
5.355422
false
false
false
false
orbit/orbit
src/orbit-client/src/main/kotlin/orbit/client/serializer/Serializer.kt
1
1211
/* Copyright (C) 2015 - 2019 Electronic Arts Inc. All rights reserved. This file is part of the Orbit Project <https://www.orbit.cloud>. See license in LICENSE. */ package orbit.client.serializer import com.fasterxml.jackson.databind.DeserializationFeature import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.databind.jsontype.BasicPolymorphicTypeValidator import com.fasterxml.jackson.databind.jsontype.PolymorphicTypeValidator import com.fasterxml.jackson.module.kotlin.registerKotlinModule internal class Serializer { private val validator: PolymorphicTypeValidator = BasicPolymorphicTypeValidator.builder() .allowIfBaseType(Any::class.java) .build() private val mapper = ObjectMapper() .activateDefaultTyping(validator, ObjectMapper.DefaultTyping.EVERYTHING) .registerKotlinModule() .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) fun <T : Any> serialize(obj: T?): String = mapper.writeValueAsString(obj) fun <T : Any> deserialize(str: String, clazz: Class<out T>): T = mapper.readValue(str, clazz) inline fun <reified T : Any> deserialize(str: String) = deserialize(str, T::class.java) }
bsd-3-clause
244033e6389df0c20cbaea7b35a409da
42.285714
97
0.766309
4.279152
false
false
false
false
rei-m/android_hyakuninisshu
domain/src/main/java/me/rei_m/hyakuninisshu/domain/question/model/QuestionCollection.kt
1
2560
/* * Copyright (c) 2020. Rei Matsushita * * 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 me.rei_m.hyakuninisshu.domain.question.model import me.rei_m.hyakuninisshu.domain.karuta.model.KarutaNoCollection import java.util.concurrent.TimeUnit /** * 問題コレクション. * * @param values 問題のリスト */ data class QuestionCollection( val values: List<Question> ) { val wrongKarutaNoCollection: KarutaNoCollection by lazy { KarutaNoCollection( values .asSequence() .mapNotNull { question -> question.state.let { state -> if (state is Question.State.Answered) { state.result } else { null } } } .filterNot { it.judgement.isCorrect } .map { it.judgement.karutaNo } .toList() ) } val resultSummary: QuestionResultSummary by lazy { val questionCount = values.size if (questionCount == 0) { QuestionResultSummary(0, 0, 0f) } else { var totalAnswerTimeMillSec: Long = 0 var collectCount = 0 values.forEach { val result = it.state.let { state -> if (state is Question.State.Answered) { return@let state.result } throw IllegalStateException("Question is not finished.") } totalAnswerTimeMillSec += result.answerMillSec if (result.judgement.isCorrect) { collectCount++ } } val averageAnswerTime = totalAnswerTimeMillSec.toFloat() / questionCount.toFloat() / TimeUnit.SECONDS.toMillis( 1 ).toFloat() QuestionResultSummary(questionCount, collectCount, averageAnswerTime) } } }
apache-2.0
3055039658651a60ba7c3c49d64af79d
31.883117
112
0.560032
4.859885
false
false
false
false
sangcomz/FishBun
FishBun/src/main/java/com/sangcomz/fishbun/ui/picker/PickerPresenter.kt
1
8617
package com.sangcomz.fishbun.ui.picker import android.net.Uri import com.sangcomz.fishbun.ui.picker.model.PickerListItem import com.sangcomz.fishbun.ui.picker.model.PickerMenuViewData import com.sangcomz.fishbun.ui.picker.model.PickerRepository import com.sangcomz.fishbun.util.UiHandler import com.sangcomz.fishbun.util.future.CallableFutureTask import com.sangcomz.fishbun.util.future.FutureCallback import java.util.concurrent.ExecutionException /** * Created by sangcomz on 2015-11-05. */ class PickerPresenter internal constructor( private val pickerView: PickerContract.View, private val pickerRepository: PickerRepository, private val uiHandler: UiHandler ) : PickerContract.Presenter { private var imageListFuture: CallableFutureTask<List<Uri>>? = null private var dirPathFuture: CallableFutureTask<String>? = null override fun addAddedPath(addedImagePath: Uri) { pickerRepository.addAddedPath(addedImagePath) } override fun addAllAddedPath(addedImagePathList: List<Uri>) { pickerRepository.addAllAddedPath(addedImagePathList) } override fun getAddedImagePathList() = pickerRepository.getAddedPathList() override fun getPickerListItem() { val albumData = pickerRepository.getPickerAlbumData() ?: return imageListFuture = getAllMediaThumbnailsPath(albumData.albumId) .also { it.execute(object : FutureCallback<List<Uri>> { override fun onSuccess(result: List<Uri>) { onSuccessAllMediaThumbnailsPath(result) } }) } } override fun transImageFinish() { val albumData = pickerRepository.getPickerAlbumData() ?: return pickerView.takeANewPictureWithFinish(albumData.albumPosition, pickerRepository.getAddedPathList()) } override fun takePicture() { val albumData = pickerRepository.getPickerAlbumData() ?: return if (albumData.albumId == 0L) { pickerRepository.getDefaultSavePath()?.let { pickerView.takePicture(it) } } else { try { dirPathFuture = pickerRepository.getDirectoryPath(albumData.albumId) .also { it.execute(object : FutureCallback<String> { override fun onSuccess(result: String) { pickerView.takePicture(result) } }) } } catch (e: ExecutionException) { e.printStackTrace() } catch (e: InterruptedException) { e.printStackTrace() } } } override fun successTakePicture(addedImagePath: Uri) { addAddedPath(addedImagePath) updatePickerListItem() } override fun getDesignViewData() { val viewData = pickerRepository.getPickerViewData() with(pickerView) { initToolBar(viewData) initRecyclerView(viewData) } setToolbarTitle() } override fun onClickThumbCount(position: Int) { changeImageStatus(position) } override fun onClickImage(position: Int) { if (pickerRepository.useDetailView()) { pickerView.showDetailView(getImagePosition(position)) } else { changeImageStatus(position) } } override fun onDetailImageActivityResult() { val pickerViewData = pickerRepository.getPickerViewData() if (pickerRepository.isLimitReached() && pickerViewData.isAutomaticClose) { finish() } else { getPickerListItem() } } override fun getPickerMenuViewData(callback: (PickerMenuViewData) -> Unit) { callback.invoke(pickerRepository.getPickerMenuViewData()) } override fun onClickMenuDone() { val selectedCount = pickerRepository.getSelectedImageList().size when { selectedCount == 0 -> { pickerView.showNothingSelectedMessage(pickerRepository.getMessageNotingSelected()) } selectedCount < pickerRepository.getMinCount() -> { pickerView.showMinimumImageMessage(pickerRepository.getMinCount()) } else -> { pickerView.finishActivity() } } } override fun onClickMenuAllDone() { pickerRepository.getPickerImages().forEach { if (pickerRepository.isLimitReached()) { return@forEach } if (pickerRepository.isNotSelectedImage(it)) { pickerRepository.selectImage(it) } } pickerView.finishActivity() } override fun onSuccessTakePicture() { pickerView.onSuccessTakePicture() } override fun release() { dirPathFuture?.cancel(true) imageListFuture?.cancel(true) } private fun changeImageStatus(position: Int) { val imagePosition = getImagePosition(position) val imageUri = pickerRepository.getPickerImage(imagePosition) if (pickerRepository.isNotSelectedImage(imageUri)) { selectImage(position, imageUri) } else { unselectImage(position, imageUri) } } private fun onCheckStateChange(position: Int, imageUri: Uri) { pickerView.onCheckStateChange( position, PickerListItem.Image( imageUri, pickerRepository.getSelectedIndex(imageUri), pickerRepository.getPickerViewData() ) ) } private fun selectImage(position: Int, imageUri: Uri) { if (pickerRepository.isLimitReached()) { pickerView.showLimitReachedMessage(pickerRepository.getMessageLimitReached()) return } pickerRepository.selectImage(imageUri) if (pickerRepository.checkForFinish()) { finish() } else { onCheckStateChange(position, imageUri) setToolbarTitle() } } private fun unselectImage(position: Int, imageUri: Uri) { pickerRepository.unselectImage(imageUri) onCheckStateChange(position, imageUri) setToolbarTitle() } private fun setToolbarTitle() { val albumName = pickerRepository.getPickerAlbumData()?.albumName ?: "" pickerView.setToolbarTitle( pickerRepository.getPickerViewData(), pickerRepository.getSelectedImageList().size, albumName ) } private fun getImagePosition(position: Int) = if (pickerRepository.hasCameraInPickerPage()) position - 1 else position private fun getAllMediaThumbnailsPath( albumId: Long, clearCache: Boolean = false ): CallableFutureTask<List<Uri>> { return pickerRepository.getAllBucketImageUri(albumId, clearCache) } private fun onSuccessAllMediaThumbnailsPath(imageUriList: List<Uri>) { pickerRepository.setCurrentPickerImageList(imageUriList) val viewData = pickerRepository.getPickerViewData() val selectedImageList = pickerRepository.getSelectedImageList().toMutableList() val pickerList = arrayListOf<PickerListItem>() if (pickerRepository.hasCameraInPickerPage()) { pickerList.add(PickerListItem.Camera) } imageUriList.map { PickerListItem.Image(it, selectedImageList.indexOf(it), viewData) }.also { pickerList.addAll(it) uiHandler.run { pickerView.showImageList( pickerList, pickerRepository.getImageAdapter(), pickerRepository.hasCameraInPickerPage() ) setToolbarTitle() } } } private fun updatePickerListItem() { val albumData = pickerRepository.getPickerAlbumData() ?: return imageListFuture = getAllMediaThumbnailsPath(albumData.albumId, true) .also { it.execute(object : FutureCallback<List<Uri>> { override fun onSuccess(result: List<Uri>) { onSuccessAllMediaThumbnailsPath(result) } }) } } private fun finish() { if (pickerRepository.isStartInAllView()) { pickerView.finishActivityWithResult(pickerRepository.getSelectedImageList()) } else { pickerView.finishActivity() } } }
apache-2.0
a3080df20586b80ff576755a47f7e8cb
31.398496
106
0.620053
5.206647
false
false
false
false
openMF/android-client
mifosng-android/src/main/java/com/mifos/mifosxdroid/online/documentlist/DocumentListFragment.kt
1
12086
/* * This project is licensed under the open source MPL V2. * See https://github.com/openMF/android-client/blob/master/LICENSE.md */ package com.mifos.mifosxdroid.online.documentlist import android.Manifest import android.content.Intent import android.content.pm.PackageManager import android.net.Uri import android.os.Bundle import android.os.Environment import android.view.* import android.widget.ImageView import android.widget.LinearLayout import android.widget.TextView import androidx.core.content.ContextCompat import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.swiperefreshlayout.widget.SwipeRefreshLayout import androidx.swiperefreshlayout.widget.SwipeRefreshLayout.OnRefreshListener import butterknife.BindView import butterknife.ButterKnife import butterknife.OnClick import com.mifos.mifosxdroid.R import com.mifos.mifosxdroid.adapters.DocumentListAdapter import com.mifos.mifosxdroid.core.MaterialDialog import com.mifos.mifosxdroid.core.MifosBaseActivity import com.mifos.mifosxdroid.core.MifosBaseFragment import com.mifos.mifosxdroid.core.util.Toaster import com.mifos.mifosxdroid.dialogfragments.documentdialog.DocumentDialogFragment import com.mifos.objects.noncore.Document import com.mifos.utils.CheckSelfPermissionAndRequest import com.mifos.utils.Constants import com.mifos.utils.FileUtils import com.mifos.utils.FragmentConstants import okhttp3.ResponseBody import java.io.File import javax.inject.Inject class DocumentListFragment : MifosBaseFragment(), DocumentListMvpView, OnRefreshListener { @JvmField @BindView(R.id.rv_documents) var rv_documents: RecyclerView? = null @JvmField @BindView(R.id.swipe_container) var swipeRefreshLayout: SwipeRefreshLayout? = null @JvmField @BindView(R.id.noDocumentText) var mNoChargesText: TextView? = null @JvmField @BindView(R.id.noDocumentIcon) var mNoChargesIcon: ImageView? = null @JvmField @BindView(R.id.ll_error) var ll_error: LinearLayout? = null @JvmField @Inject var mDocumentListPresenter: DocumentListPresenter? = null private val mDocumentListAdapter by lazy { DocumentListAdapter( onDocumentClick = { documentSelected -> document = documentSelected showDocumentActions(documentSelected.id) } ) } private lateinit var rootView: View private var entityType: String? = null private var entityId = 0 private var document: Document? = null private var documentBody: ResponseBody? = null private var mDocumentList: List<Document>? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) (activity as MifosBaseActivity?)!!.activityComponent.inject(this) mDocumentList = ArrayList() if (arguments != null) { entityType = requireArguments().getString(Constants.ENTITY_TYPE) entityId = requireArguments().getInt(Constants.ENTITY_ID) } setHasOptionsMenu(true) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { // Inflate the layout for this fragment rootView = inflater.inflate(R.layout.fragment_document_list, container, false) ButterKnife.bind(this, rootView) mDocumentListPresenter!!.attachView(this) setToolbarTitle(getString(R.string.documents)) val layoutManager = LinearLayoutManager(activity) layoutManager.orientation = LinearLayoutManager.VERTICAL rv_documents!!.layoutManager = layoutManager rv_documents!!.setHasFixedSize(true) rv_documents!!.adapter = mDocumentListAdapter swipeRefreshLayout!!.setColorSchemeColors(*activity ?.getResources()!!.getIntArray(R.array.swipeRefreshColors)) swipeRefreshLayout!!.setOnRefreshListener(this) mDocumentListPresenter!!.loadDocumentList(entityType, entityId) return rootView } override fun onRefresh() { mDocumentListPresenter!!.loadDocumentList(entityType, entityId) } override fun onResume() { super.onResume() mDocumentListPresenter!!.loadDocumentList(entityType, entityId) } @OnClick(R.id.noDocumentIcon) fun reloadOnError() { ll_error!!.visibility = View.GONE mDocumentListPresenter!!.loadDocumentList(entityType, entityId) } /** * This Method Checking the Permission WRITE_EXTERNAL_STORAGE is granted or not. * If not then prompt user a dialog to grant the WRITE_EXTERNAL_STORAGE permission. * and If Permission is granted already then Save the documentBody in external storage; */ override fun checkPermissionAndRequest() { if (CheckSelfPermissionAndRequest.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { checkExternalStorageAndCreateDocument() } else { requestPermission() } } override fun requestPermission() { CheckSelfPermissionAndRequest.requestPermission( activity as MifosBaseActivity?, Manifest.permission.WRITE_EXTERNAL_STORAGE, Constants.PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE, resources.getString( R.string.dialog_message_write_external_storage_permission_denied), resources.getString(R.string.dialog_message_permission_never_ask_again_write), Constants.WRITE_EXTERNAL_STORAGE_STATUS) } /** * This Method getting the Response after User Grant or denied the Permission * * @param requestCode Request Code * @param permissions Permission * @param grantResults GrantResults */ override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) { when (requestCode) { Constants.PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE -> { // If request is cancelled, the result arrays are empty. if (grantResults.size > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // permission was granted, yay! Do the checkExternalStorageAndCreateDocument() } else { // permission denied, boo! Disable the Toaster.show(rootView, resources .getString(R.string.permission_denied_to_write_external_document)) } } } } override fun showDocumentList(documents: List<Document>) { mDocumentList = documents mDocumentListAdapter!!.documents = documents if (documents.isEmpty()) { showEmptyDocuments() } else { if (ll_error!!.visibility == View.VISIBLE) { ll_error!!.visibility = View.GONE } } } override fun showDocumentFetchSuccessfully(responseBody: ResponseBody?) { documentBody = responseBody checkPermissionAndRequest() } override fun showDocumentActions(documentId: Int) { MaterialDialog.Builder().init(activity) .setItems(R.array.document_options) { dialog, which -> when (which) { 0 -> mDocumentListPresenter!!.downloadDocument(entityType, entityId, documentId) 1 -> showDocumentDialog(getString(R.string.update_document)) 2 -> mDocumentListPresenter!!.removeDocument(entityType, entityId, documentId) else -> { } } } .createMaterialDialog() .show() } override fun checkExternalStorageAndCreateDocument() { // Create a path where we will place our documents in the user's // public directory and check if the file exists. val mifosDirectory = File(Environment.getExternalStorageDirectory(), resources.getString(R.string.document_directory)) if (!mifosDirectory.exists()) { mifosDirectory.mkdirs() } val documentFile = File(mifosDirectory.path, document!!.fileName) FileUtils.writeInputStreamDataToFile(documentBody!!.byteStream(), documentFile) //Opening the Saved Document val intent = Intent(Intent.ACTION_VIEW) intent.setDataAndType(Uri.fromFile(documentFile), FileUtils.getMimeType(mifosDirectory.path + resources.getString(R.string.slash) + document!!.fileName)) startActivity(intent) } override fun showDocumentRemovedSuccessfully() { Toaster.show(rootView, resources.getString(R.string.document_remove_successfully)) mDocumentListPresenter!!.loadDocumentList(entityType, entityId) } override fun showDocumentDialog(documentAction: String?) { val documentDialogFragment = DocumentDialogFragment.newInstance(entityType, entityId, documentAction, document) val fragmentTransaction = requireActivity().supportFragmentManager .beginTransaction() fragmentTransaction.addToBackStack(FragmentConstants.FRAG_DOCUMENT_LIST) documentDialogFragment.show(fragmentTransaction, "Document Dialog Fragment") } override fun showEmptyDocuments() { ll_error!!.visibility = View.VISIBLE mNoChargesText!!.text = resources.getString(R.string.no_document_to_show) mNoChargesIcon!!.setImageResource(R.drawable.ic_assignment_turned_in_black_24dp) } override fun showFetchingError(message: Int) { if (mDocumentListAdapter!!.itemCount == 0) { ll_error!!.visibility = View.VISIBLE val errorMessage = getStringMessage(message) + getStringMessage(R.string.new_line) + getStringMessage(R.string.click_to_refresh) mNoChargesText!!.text = errorMessage } else { Toaster.show(rootView, getStringMessage(message)) } } override fun showProgressbar(show: Boolean) { swipeRefreshLayout!!.isRefreshing = show if (show && mDocumentListAdapter!!.itemCount == 0) { showMifosProgressBar() swipeRefreshLayout!!.isRefreshing = false } else { hideMifosProgressBar() } } override fun onDestroyView() { super.onDestroyView() mDocumentListPresenter!!.detachView() hideMifosProgressBar() } override fun onPrepareOptionsMenu(menu: Menu) { menu.clear() val menuItemAddNewDocument = menu.add(Menu.NONE, MENU_ITEM_ADD_NEW_DOCUMENT, Menu.NONE, getString(R.string.add_new)) menuItemAddNewDocument.icon = ContextCompat .getDrawable(requireActivity(), R.drawable.ic_add_white_24dp) menuItemAddNewDocument.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM) super.onPrepareOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { val id = item.itemId if (id == MENU_ITEM_ADD_NEW_DOCUMENT) { showDocumentDialog(getString(R.string.upload_document)) } return super.onOptionsItemSelected(item) } companion object { const val MENU_ITEM_ADD_NEW_DOCUMENT = 1000 val LOG_TAG = DocumentListFragment::class.java.simpleName @JvmStatic fun newInstance(entityType: String?, entiyId: Int): DocumentListFragment { val fragment = DocumentListFragment() val args = Bundle() args.putString(Constants.ENTITY_TYPE, entityType) args.putInt(Constants.ENTITY_ID, entiyId) fragment.arguments = args return fragment } } }
mpl-2.0
352bf5463968a29f25d705f3f6231c3a
38.243506
124
0.664322
5.158344
false
false
false
false
Abestanis/APython
app/src/androidTest/java/com/apython/python/pythonhost/TestUtil.kt
1
7614
package com.apython.python.pythonhost import android.content.Context import android.util.Log import org.apache.commons.compress.archivers.ArchiveEntry import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream import java.io.* /** * Created by Sebastian on 20.10.2017. */ object TestUtil { private data class VersionResolver(val entryPath: String, val versionRegex: Regex) { fun resolve(zipStream: ZipArchiveInputStream): String { var zipEntry: ArchiveEntry while (zipStream.nextEntry.also { zipEntry = it } != null) { if (zipEntry.name == entryPath) { val versionMatch = zipStream.bufferedReader().lines() .map { line -> versionRegex.matchEntire(line) } .filter { match -> match != null } .findFirst().orElse(null) if (versionMatch != null && versionMatch.groups.size > 1) { return versionMatch.groupValues[1] } } } throw RuntimeException("'$entryPath' was not found in test asset") } } private data class LibraryData( val assetName: String, private val destinationPath: String, val versionResolver: VersionResolver? = null ) { private object VersionCache { val versions: MutableMap<String, String> = mutableMapOf() fun format(libraryData: LibraryData, instrumentationContext: Context): String { if (libraryData.versionResolver != null) { versions[libraryData.assetName.replace("_library.zip", "Version")] = libraryData.versionResolver.resolve( ZipArchiveInputStream( libraryData.open(instrumentationContext) ) ) } var formattedPath = libraryData.destinationPath versions.forEach { (name, value) -> formattedPath = formattedPath.replace("{$name}", value) } Log.i(MainActivity.TAG, "'$formattedPath'") return formattedPath } } fun open(instrumentationContext: Context): InputStream { return instrumentationContext.assets.open(assetName) } fun destinationDir(instrumentationContext: Context, targetContext: Context): File { return File(targetContext.filesDir, VersionCache.format(this, instrumentationContext)) } } fun installLibraryData(instrumentationContext: Context, targetContext: Context): Boolean { val data = arrayOf( LibraryData( "tcl_library.zip", "data/tcl{tclVersion}/library", VersionResolver( "init.tcl", Regex("""package require -exact Tcl (\d+\.\d+\.\d+)""") ) ), LibraryData( "tk_library.zip", "data/tcl{tclVersion}/library/tk{tkVersion}", VersionResolver( "tk.tcl", Regex("""package require -exact Tk\s+(\d+\.\d+)\.\d+""") ) ), LibraryData("terminfo.tar", "data/terminfo") ) for (libraryData in data) { val destinationDir = try { libraryData.destinationDir(instrumentationContext, targetContext) } catch (error: IOException) { Log.e(MainActivity.TAG, "Unable to read test asset ${libraryData.assetName}", error) return false } if (destinationDir.exists()) { continue } if (!destinationDir.mkdirs()) { Log.e( MainActivity.TAG, "Could not create directory " + destinationDir.absolutePath ) return false } val tempArchive = File(targetContext.cacheDir, libraryData.assetName) try { if (!Util.installFromInputStream( tempArchive, libraryData.open(instrumentationContext), null ) ) { throw IOException("Unable to install from the asset resource") } } catch (error: IOException) { Util.deleteDirectory(destinationDir) Log.e( MainActivity.TAG, "Could not create temporary archive at " + tempArchive.absolutePath, error ) return false } val success = Util.extractArchive( tempArchive, destinationDir, null ) // TODO: See if there is a zip stream tempArchive.delete() if (!success) { Util.deleteDirectory(destinationDir) Log.e( MainActivity.TAG, "Failed to extract archive to " + destinationDir.absolutePath ) return false } } return true } fun copyNativePythonLibraries(context: Context): Boolean { val excludeLibList = listOf( System.mapLibraryName("application"), System.mapLibraryName("pyInterpreter"), System.mapLibraryName("pyLog") ) val dynLibPath = PackageManager.getDynamicLibraryPath(context) val nativeLibDir = File(context.applicationInfo.nativeLibraryDir) if (!dynLibPath.isDirectory && !dynLibPath.mkdirs()) { Log.e(MainActivity.TAG, "Failed to create the dynLib path") return false } for (libFile in nativeLibDir.listFiles().orEmpty()) { if (!excludeLibList.contains(libFile.name)) { try { val inStream = FileInputStream(libFile) val outStream = FileOutputStream(File(dynLibPath, libFile.name)) val inChannel = inStream.channel inChannel.transferTo(0, inChannel.size(), outStream.channel) inStream.close() outStream.close() } catch (error: IOException) { Log.e(MainActivity.TAG, "Failed to copy native library " + libFile.name, error) return false } } } return true } fun installPythonLibraries( instrumentationContext: Context, targetContext: Context?, pythonVersion: String ): Boolean { val libDest = PackageManager.getStandardLibPath(targetContext) if (!(libDest.mkdirs() || libDest.isDirectory)) { Log.e(MainActivity.TAG, "Failed to create the 'lib' directory!") return false } val libZip = File(libDest, "python" + pythonVersion.replace(".", "") + ".zip") if (libZip.exists()) { return true } Util.makeFileAccessible(libDest, false) val testAssets = instrumentationContext.assets val libLocation: InputStream = try { testAssets.open("lib" + pythonVersion.replace('.', '_') + ".zip") } catch (error: IOException) { Log.e( MainActivity.TAG, "Did not find the library Zip for the Python version " + pythonVersion, error ) return false } return Util.installFromInputStream(libZip, libLocation, null) } }
mit
fe0cbd2011d119b6b97099e2a499c237
39.291005
100
0.53927
5.339411
false
false
false
false
google/play-services-plugins
strict-version-matcher-plugin/src/main/kotlin/com/google/android/gms/dependencies/Versions.kt
1
4042
package com.google.android.gms.dependencies import java.util.regex.Pattern /** * Allow storing, comparing, and parsing of SemVer version strings. */ data class SemVerVersionInfo(val major: Int, val minor: Int, val patch: Int) { companion object { /** * Parse a SemVer formatted string to {SemVerVersionInfo}. * * Current implementation is rudimentary, but supports the Google Play * services current use. * * @param[versionString] Three-part Semver string to convert. */ fun parseString(versionString:String) : SemVerVersionInfo { val version = versionString.trim(); val parts = version.split(".") if (parts.size != 3) { throw IllegalArgumentException("versionString didn't have 3 parts divided by periods."); } val major = Integer.valueOf(parts[0]) val minor = Integer.valueOf(parts[1]) var patchString = parts[2] var dashIndex = patchString.indexOf("-") if (dashIndex != -1) { patchString = patchString.substring(0, dashIndex) } // TODO: Update to account for qualifiers to the version. val patch = Integer.valueOf(patchString) return SemVerVersionInfo(major= major, minor = minor, patch = patch) } } } data class Version(val rawString: String, val trimmedString: String) { companion object { fun fromString(version: String?) : Version? { if (version == null) { return null } return Version(version, version.split("-")[0]) } } } data class VersionRange(val closedStart: Boolean, val closedEnd: Boolean, val rangeStart: Version, val rangeEnd:Version) { fun toVersionString() : String { return (if (closedStart) "[" else "(") + rangeStart.trimmedString + "," + rangeEnd.trimmedString + (if (closedEnd) "]" else ")") } fun versionInRange(compareTo : Version) : Boolean { if (closedStart) { if (versionCompare(rangeStart.trimmedString, compareTo.trimmedString) > 0) { return false } } else { if (versionCompare(rangeStart.trimmedString, compareTo.trimmedString) >= 0) { return false } } if (closedEnd) { if (versionCompare(rangeEnd.trimmedString, compareTo.trimmedString) < 0) { return false } } else { if (versionCompare(rangeEnd.trimmedString, compareTo.trimmedString) <= 0) { return false } } return true } companion object { fun versionCompare(str1 : String, str2 : String) : Int { val vals1 = str1.split("\\.") val vals2 = str2.split("\\.") var i = 0 while (i < vals1.size && i < vals2.size && vals1[i] == vals2[i]) { i++ } if (i < vals1.size && i < vals2.size) { val diff = Integer.compare(Integer.valueOf(vals1[i]), Integer.valueOf(vals2[i])) return Integer.signum(diff) } return Integer.signum(vals1.size - vals2.size) } // Some example of things that match this pattern are: // "[1]" "[10]" "[10.3.234]" // And here is an example with the capture group 1 in <triangle brackets> // [<1.><2.><3>] or // VisibleForTesting(otherwise = Private) val VERSION_RANGE_PATTERN = Pattern.compile("\\[(\\d+\\.)*(\\d+)+(-\\w)*\\]") fun fromString(versionRange : String) : VersionRange? { val versionRangeMatcher = VERSION_RANGE_PATTERN.matcher(versionRange) if (versionRangeMatcher.matches()) { val v = Version.fromString(versionRangeMatcher.group(1)) ?: return null return VersionRange( true, true, v, v) } return null } } }
apache-2.0
51beba2db5004bed88af7277eec488e3
36.425926
136
0.556903
4.471239
false
false
false
false
EasySpringBoot/picture-crawler
src/main/kotlin/com/easy/kotlin/picturecrawler/controller/CrawController.kt
1
1364
package com.easy.kotlin.picturecrawler.controller import com.easy.kotlin.picturecrawler.job.BatchUpdateJob import com.easy.kotlin.picturecrawler.service.CrawImageService import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Controller import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestMethod import org.springframework.web.bind.annotation.ResponseBody /** * Created by jack on 2017/7/22. */ @Controller class CrawController { @Autowired lateinit var crawImageService: CrawImageService @Autowired lateinit var batchUpdateJob: BatchUpdateJob @RequestMapping(value = ["doBaiduImageCrawJob"], method = [RequestMethod.GET]) @ResponseBody fun doBaiduImageCrawJob(): String { crawImageService.doBaiduImageCrawJob() return "doBaiduImageCrawJob JOB Started" } @RequestMapping(value = ["doGankImageCrawJob"], method = [RequestMethod.GET]) @ResponseBody fun doGankImageCrawJob(): String { crawImageService.doGankImageCrawJob() return "doBaiduImageCrawJob JOB Started" } @RequestMapping(value = ["doBatchUpdateJob"], method = [RequestMethod.GET]) @ResponseBody fun BatchUpdateJob(): String { batchUpdateJob.job() return "BatchUpdateJob Started" } }
apache-2.0
12cd221f1bd232f26298248a8c67f056
30.72093
82
0.758798
4.22291
false
false
false
false
openhab/openhab.android
mobile/src/main/java/org/openhab/habdroid/model/LinkedPage.kt
1
2121
/* * Copyright (c) 2010-2022 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.habdroid.model import android.os.Parcelable import kotlinx.parcelize.Parcelize import org.json.JSONObject import org.openhab.habdroid.util.forEach import org.openhab.habdroid.util.optStringOrNull import org.w3c.dom.Node /** * This is a class to hold information about openHAB linked page. */ @Parcelize data class LinkedPage( val id: String, val title: String, val icon: IconResource?, val link: String ) : Parcelable { companion object { internal fun build( id: String, title: String?, icon: IconResource?, link: String ): LinkedPage { val actualTitle = if (title != null && title.indexOf('[') > 0) title.substring(0, title.indexOf('[')) else title return LinkedPage(id, actualTitle.orEmpty(), icon, link) } } } fun Node.toLinkedPage(): LinkedPage? { var id: String? = null var title: String? = null var icon: String? = null var link: String? = null childNodes.forEach { node -> when (node.nodeName) { "id" -> id = node.textContent "title" -> title = node.textContent "icon" -> icon = node.textContent "link" -> link = node.textContent } } val finalId = id ?: return null val finalLink = link ?: return null return LinkedPage.build(finalId, title, icon.toOH1IconResource(), finalLink) } fun JSONObject?.toLinkedPage(): LinkedPage? { if (this == null) { return null } val icon = optStringOrNull("icon") return LinkedPage.build( getString("id"), optStringOrNull("title"), icon.toOH2IconResource(), getString("link")) }
epl-1.0
770c7a7aea0e7353872f1d4df8fbafe9
25.848101
80
0.62942
4.032319
false
false
false
false
mingdroid/tumbviewer
app/src/main/java/com/nutrition/express/ui/reblog/ReblogActivity.kt
1
4015
package com.nutrition.express.ui.reblog import android.os.Bundle import android.view.MenuItem import android.view.View import android.widget.AdapterView import android.widget.AdapterView.OnItemSelectedListener import android.widget.ArrayAdapter import android.widget.SpinnerAdapter import androidx.activity.viewModels import androidx.lifecycle.Observer import com.nutrition.express.R import com.nutrition.express.application.BaseActivity import com.nutrition.express.application.toast import com.nutrition.express.databinding.ActivityReblogBinding import com.nutrition.express.model.api.Resource import com.nutrition.express.model.data.AppData import com.nutrition.express.model.api.bean.UserInfoItem import com.nutrition.express.ui.main.UserViewModel class ReblogActivity : BaseActivity() { private lateinit var binding: ActivityReblogBinding private val reblogViewModel: ReblogViewModel by viewModels() private val userViewModel: UserViewModel by viewModels() private var name: String? = null private lateinit var id: String private lateinit var key: String private lateinit var type: String override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityReblogBinding.inflate(layoutInflater) setContentView(binding.root) setSupportActionBar(binding.toolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) supportActionBar?.setDisplayShowTitleEnabled(false) binding.post.setOnClickListener { name?.let { reblogViewModel.reblog(it, id, key, type, binding.comment.text.toString()) } } if (AppData.users == null) { userViewModel.userInfoData.observe(this, Observer { when (it) { is Resource.Success -> it.data?.user?.let { user -> setNames(user) } is Resource.Error -> toast(it.message) is Resource.Loading -> {} } }) userViewModel.fetchUserInfo() } else { setNames(AppData.users!!) } reblogViewModel.reblogResult.observe(this, Observer { when (it) { is Resource.Success -> { toast(R.string.reblog_success) finish() } is Resource.Error -> { binding.post.visibility = View.VISIBLE binding.progressBar.visibility = View.GONE toast(it.message) } is Resource.Loading -> { binding.post.visibility = View.GONE binding.progressBar.visibility = View.VISIBLE } } }) id = intent.getStringExtra("id") ?: "" key = intent.getStringExtra("reblog_key") ?: "" type = intent.getStringExtra("type") ?: "" } private fun setNames(user: UserInfoItem) { val names: MutableList<String> = ArrayList() for (item in user.blogs) { names.add(item.name) } if (names.isNotEmpty()) { name = names[0] binding.spinner.visibility = View.VISIBLE val adapter: SpinnerAdapter = ArrayAdapter(this, R.layout.item_text, R.id.text, names) binding.spinner.adapter = adapter binding.spinner.onItemSelectedListener = object : OnItemSelectedListener { override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) { name = parent.getItemAtPosition(position) as String } override fun onNothingSelected(parent: AdapterView<*>?) {} } } } override fun onOptionsItemSelected(item: MenuItem): Boolean { return if (item.itemId == android.R.id.home) { finish() true } else { super.onOptionsItemSelected(item) } } }
apache-2.0
00713842a8164a42a593c1d9fdec331e
36.523364
106
0.619427
5.04397
false
false
false
false
nosix/vue-kotlin
vuekt/src/main/kotlin/org/musyozoku/vuekt/vue.kt
1
5365
@file:Suppress("unused", "UnsafeCastFromDynamic", "NOTHING_TO_INLINE") // See also: Vue 2.x [https://vuejs.org/v2/api/] package org.musyozoku.vuekt import org.w3c.dom.HTMLElement import kotlin.js.* object vue { const val MODULE = "vue" const val CLASS = "Vue" } /** * `??? -> VNode` */ typealias CreateElement = Function<VNode> /** * # Example * * ``` * @JsModule(vue.MODULE) * @JsNonModule * @JsName(vue.CLASS) * external class MyVue(options: ComponentOptions<MyVue>) : Vue { * var message: String * } * * MyVue(ComponentOptions { * ... * }) * ``` * * # Example Component * * ``` * external class MyComponent : Vue * * Vue.component("my-component", Component(ComponentOptions<MyComponent> { * ... * }) * ``` */ @JsModule(vue.MODULE) @JsNonModule @JsName(vue.CLASS) external open class Vue(options: ComponentOptions<Vue>? = definedExternally) { companion object { // Global Config val config: VueConfig // Global API fun extend(options: Any /* ComponentOptions<Vue> | FunctionalComponentOptions */): Any // typeof Vue fun nextTick(callback: () -> Unit, context: Array<Any>? = definedExternally) fun nextTick(): Promise<Unit> fun <T> set(target: Any, key: String, value: T): T fun <T> set(target: Array<T>, key: Int, value: T): T fun delete(target: Json, key: String) fun <T> delete(target: Array<T>, key: Int) fun directive(id: String, definition: DirectiveConfig? = definedExternally): DirectiveOptions fun filter(id: String, definition: Function<Unit>? = definedExternally): Function<Unit> fun component(id: String, definition: Component? = definedExternally): Any // typeof Vue fun component(id: String, definition: AsyncComponent? = definedExternally): Any // typeof Vue fun <T> use(plugin: PluginConfig, options: T?) fun mixin(mixin: Any /* typeof Vue | ComponentOptions */) fun compile(template: String) val version: String } // Instance Properties var `$data`: Vue val `$el`: HTMLElement val `$options`: ComponentOptions<Vue> val `$parent`: Vue val `$root`: Vue val `$children`: Array<Vue> val `$refs`: JsonOf<Ref?> // { [key: String]: Vue | Element | Array<Vue> | Array<Element> } val `$slots`: JsonOf<Array<VNode>?> // { [key: String]: Array<VNode> } val `$scopedSlots`: ScopedSlotMap val `$isServer`: Boolean val `$ssrContext`: Any val `$props`: Any val `$vnode`: VNode val `$attrs`: Any // { [key: String]: String } | void val `$listeners`: Any // { [key: String]: Function | Array<Function> } | void var `$createElement`: CreateElement // Instance Methods / Data fun <T> `$watch`( exp: String, callback: WatchHandler<T>, options: WatchOptions? = definedExternally): () -> Unit fun <T> `$watch`( fn: () -> T, callback: WatchHandler<T>, options: WatchOptions? = definedExternally): () -> Unit fun <T> `$set`(target: Any, key: String, value: T): T fun <T> `$set`(target: Array<T>, key: Int, value: T): T fun `$delete`(target: Json, key: String) fun <T> `$delete`(target: Array<T>, key: Int) // Instance Methods / Event fun `$on`(event: String, callback: Function<Unit>): Vue // -> this fun `$on`(event: Array<String>, callback: Function<Unit>): Vue // -> this fun `$once`(event: String, callback: Function<Unit>): Vue // -> this fun `$off`(event: String? = definedExternally, callback: Function<Unit>? = definedExternally): Vue // -> this fun `$off`(event: Array<String>? = definedExternally, callback: Function<Unit>? = definedExternally): Vue // -> this fun `$emit`(event: String, vararg args: Any): Vue // -> this // Instance Methods / Lifecycle fun `$mount`(elementOrSelector: Any? /* Element | String */ = definedExternally, hydrating: Boolean? = definedExternally): Vue // -> this fun `$forceUpdate`() fun `$destroy`() fun `$nextTick`(callback: () -> Unit) // V.() -> Unit fun `$nextTick`(): Promise<Unit> } external interface VueConfig { val silent: Boolean val optionMergeStrategies: JsonOf<Function<Any>?> // { [key: String]: Function } val devtools: Boolean val productionTip: Boolean val performance: Boolean val errorHandler: (err: Error, vm: Vue, info: String) -> Unit val warnHandler: (msg: String, vm: Vue, trace: String) -> Unit val ignoredElements: Array<String> val keyCodes: JsonOf<Int> // { [key: String]: Number } } external interface CompileResult { fun render(createElement: Any /* typeof Vue.prototype.$createElement */): VNode var staticRenderFns: Array<() -> VNode> } /** * `Vue | Element | Array<Vue> | Array<Element>` */ external interface Ref inline fun Ref(vm: Vue): Ref = vm.asDynamic() inline fun Ref(element: HTMLElement): Ref = element.asDynamic() inline fun Ref(vms: Array<Vue>): Ref = vms.asDynamic() inline fun Ref(elements: Array<HTMLElement>): Ref = elements.asDynamic() inline fun Ref.toVue(): Vue = this.asDynamic() inline fun Ref.toHTMLElement(): HTMLElement = this.asDynamic() inline fun Ref.toVueList(): Array<Vue> = this.asDynamic() inline fun Ref.toHTMLElementList(): Array<HTMLElement> = this.asDynamic()
apache-2.0
14325d0ff6b77dfbe0756e779855a539
33.171975
120
0.630568
3.788842
false
false
false
false
rock3r/detekt
detekt-core/src/test/kotlin/io/gitlab/arturbosch/detekt/core/CustomRuleSetProviderSpec.kt
1
1429
package io.gitlab.arturbosch.detekt.core import io.gitlab.arturbosch.detekt.test.createProcessingSettings import io.gitlab.arturbosch.detekt.test.resource import org.assertj.core.api.Assertions.assertThat import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe import java.nio.file.Paths /** * This test runs a precompiled jar with a custom rule provider. * When any breaking change in 'detekt-api' is done, this test will break. * * The procedure to repair this test is: * 1. 'gradle build -x test publishToMavenLocal' * 2. 'gradle build' again to let the 'sample' project pick up the new api changes. * 3. 'cp detekt-sample-extensions/build/libs/detekt-sample-extensions-<version>.jar detekt-core/src/test/resources/sample-rule-set.jar' * 4. Now 'gradle build' should be green again. */ @Suppress("MaxLineLength") class CustomRuleSetProviderSpec : Spek({ describe("custom rule sets should be loadable through jars") { val sampleRuleSet = Paths.get(resource("sample-rule-set.jar")) it("should load the sample provider") { val providers = createProcessingSettings( path, excludeDefaultRuleSets = true, pluginPaths = listOf(sampleRuleSet) ).use { RuleSetLocator(it).load() } assertThat(providers).filteredOn { it.ruleSetId == "sample" }.hasSize(1) } } })
apache-2.0
db46b4db7b94ee7a3e1ec7a227ab85ae
37.621622
137
0.706788
4.036723
false
true
false
false
JetBrains/anko
anko/library/generated/design-coroutines/src/main/java/ListenersWithCoroutines.kt
2
4754
@file:JvmName("DesignCoroutinesListenersWithCoroutinesKt") package org.jetbrains.anko.design.coroutines import kotlin.coroutines.CoroutineContext import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import kotlinx.coroutines.CoroutineStart fun android.support.design.widget.AppBarLayout.onOffsetChanged( context: CoroutineContext = Dispatchers.Main, handler: suspend CoroutineScope.(appBarLayout: android.support.design.widget.AppBarLayout?, verticalOffset: Int) -> Unit ) { addOnOffsetChangedListener { appBarLayout, verticalOffset -> GlobalScope.launch(context, CoroutineStart.DEFAULT) { handler(appBarLayout, verticalOffset) } } } fun android.support.design.widget.TabLayout.onTabSelectedListener( context: CoroutineContext = Dispatchers.Main, init: __TabLayout_OnTabSelectedListener.() -> Unit ) { val listener = __TabLayout_OnTabSelectedListener(context) listener.init() addOnTabSelectedListener(listener) } class __TabLayout_OnTabSelectedListener(private val context: CoroutineContext) : android.support.design.widget.TabLayout.OnTabSelectedListener { private var _onTabSelected: (suspend CoroutineScope.(android.support.design.widget.TabLayout.Tab?) -> Unit)? = null override fun onTabSelected(tab: android.support.design.widget.TabLayout.Tab?) { val handler = _onTabSelected ?: return GlobalScope.launch(context) { handler(tab) } } fun onTabSelected( listener: suspend CoroutineScope.(android.support.design.widget.TabLayout.Tab?) -> Unit ) { _onTabSelected = listener } private var _onTabUnselected: (suspend CoroutineScope.(android.support.design.widget.TabLayout.Tab?) -> Unit)? = null override fun onTabUnselected(tab: android.support.design.widget.TabLayout.Tab?) { val handler = _onTabUnselected ?: return GlobalScope.launch(context) { handler(tab) } } fun onTabUnselected( listener: suspend CoroutineScope.(android.support.design.widget.TabLayout.Tab?) -> Unit ) { _onTabUnselected = listener } private var _onTabReselected: (suspend CoroutineScope.(android.support.design.widget.TabLayout.Tab?) -> Unit)? = null override fun onTabReselected(tab: android.support.design.widget.TabLayout.Tab?) { val handler = _onTabReselected ?: return GlobalScope.launch(context) { handler(tab) } } fun onTabReselected( listener: suspend CoroutineScope.(android.support.design.widget.TabLayout.Tab?) -> Unit ) { _onTabReselected = listener } }fun android.support.design.widget.BottomNavigationView.onNavigationItemSelected( context: CoroutineContext = Dispatchers.Main, returnValue: Boolean = false, handler: suspend CoroutineScope.(item: android.view.MenuItem?) -> Unit ) { setOnNavigationItemSelectedListener { item -> GlobalScope.launch(context, CoroutineStart.DEFAULT) { handler(item) } returnValue } } fun android.support.design.widget.CoordinatorLayout.onHierarchyChangeListener( context: CoroutineContext = Dispatchers.Main, init: __ViewGroup_OnHierarchyChangeListener.() -> Unit ) { val listener = __ViewGroup_OnHierarchyChangeListener(context) listener.init() setOnHierarchyChangeListener(listener) } class __ViewGroup_OnHierarchyChangeListener(private val context: CoroutineContext) : android.view.ViewGroup.OnHierarchyChangeListener { private var _onChildViewAdded: (suspend CoroutineScope.(android.view.View?, android.view.View?) -> Unit)? = null override fun onChildViewAdded(parent: android.view.View?, child: android.view.View?) { val handler = _onChildViewAdded ?: return GlobalScope.launch(context) { handler(parent, child) } } fun onChildViewAdded( listener: suspend CoroutineScope.(android.view.View?, android.view.View?) -> Unit ) { _onChildViewAdded = listener } private var _onChildViewRemoved: (suspend CoroutineScope.(android.view.View?, android.view.View?) -> Unit)? = null override fun onChildViewRemoved(parent: android.view.View?, child: android.view.View?) { val handler = _onChildViewRemoved ?: return GlobalScope.launch(context) { handler(parent, child) } } fun onChildViewRemoved( listener: suspend CoroutineScope.(android.view.View?, android.view.View?) -> Unit ) { _onChildViewRemoved = listener } }
apache-2.0
28893bbd2af076b487daf52e0a6dcb12
33.456522
144
0.696466
4.97801
false
false
false
false
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/server/data/ValueContainerBase.kt
1
3484
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.data import org.lanternpowered.api.util.optional.emptyOptionalDouble import org.lanternpowered.api.util.optional.emptyOptionalInt import org.lanternpowered.api.util.optional.emptyOptionalLong import org.lanternpowered.api.util.optional.asOptionalDouble import org.lanternpowered.api.util.optional.asOptionalInt import org.lanternpowered.api.util.optional.asOptionalLong import org.spongepowered.api.data.Key import org.spongepowered.api.data.value.Value import org.spongepowered.api.data.value.ValueContainer import java.util.Optional import java.util.OptionalDouble import java.util.OptionalInt import java.util.OptionalLong import java.util.function.Supplier /** * The base class for all the [ValueContainer]s. */ @LocalDataDsl interface ValueContainerBase : ValueContainer { @JvmDefault override fun getInt(key: Supplier<out Key<out Value<Int>>>): OptionalInt = getInt(key.get()) @JvmDefault override fun getInt(key: Key<out Value<Int>>): OptionalInt = get(key).map { it.asOptionalInt() }.orElseGet { emptyOptionalInt() } @JvmDefault override fun getDouble(key: Supplier<out Key<out Value<Double>>>): OptionalDouble = getDouble(key.get()) @JvmDefault override fun getDouble(key: Key<out Value<Double>>): OptionalDouble = get(key).map { it.asOptionalDouble() }.orElseGet { emptyOptionalDouble() } @JvmDefault override fun getLong(key: Supplier<out Key<out Value<Long>>>): OptionalLong = getLong(key.get()) @JvmDefault override fun getLong(key: Key<out Value<Long>>): OptionalLong = get(key).map { it.asOptionalLong() }.orElseGet { emptyOptionalLong() } @JvmDefault override fun <E : Any> get(key: Supplier<out Key<out Value<E>>>): Optional<E> = get(key.get()) @JvmDefault override fun <E : Any> get(key: Key<out Value<E>>): Optional<E> @JvmDefault override fun <E : Any, V : Value<E>> getValue(key: Supplier<out Key<V>>): Optional<V> = getValue(key.get()) @JvmDefault override fun <E : Any, V : Value<E>> getValue(key: Key<V>): Optional<V> override fun getKeys(): Set<Key<*>> override fun getValues(): Set<Value.Immutable<*>> @JvmDefault override fun <E : Any> getOrElse(key: Supplier<out Key<out Value<E>>>, defaultValue: E): E = getOrElse(key.get(), defaultValue) @JvmDefault override fun <E : Any> getOrElse(key: Key<out Value<E>>, defaultValue: E): E = super.getOrElse(key, defaultValue) @JvmDefault override fun <E : Any> getOrNull(key: Supplier<out Key<out Value<E>>>): E? = getOrNull(key.get()) @JvmDefault override fun <E : Any> getOrNull(key: Key<out Value<E>>): E? = super.getOrNull(key) @JvmDefault override fun supports(key: Supplier<out Key<*>>): Boolean = supports(key.get()) override fun supports(key: Key<*>): Boolean @JvmDefault override fun supports(value: Value<*>) = super.supports(value) @JvmDefault override fun <E : Any> require(key: Supplier<out Key<out Value<E>>>): E = require(key.get()) @JvmDefault override fun <E : Any> require(key: Key<out Value<E>>): E = super.require(key) }
mit
203d315d3c361f50a27248156f0579ac
35.291667
131
0.704076
3.90583
false
false
false
false
andersonlucasg3/SpriteKit-Android
SpriteKitLib/src/main/java/br/com/insanitech/spritekit/easing/Circ.kt
1
982
package br.com.insanitech.spritekit.easing object Circ { fun easeIn(t: Float, b: Float, c: Float, d: Float): Float { var t = t val tLambda = { a: Float -> Float t = a t } return -c * (Math.sqrt((1 - (tLambda(t / d)) * t).toDouble()).toFloat() - 1) + b } fun easeOut(t: Float, b: Float, c: Float, d: Float): Float { var t = t val tLambda = { a: Float -> Float t = a t } return c * Math.sqrt((1 - (tLambda(t / d - 1)) * t).toDouble()).toFloat() + b } fun easeInOut(t: Float, b: Float, c: Float, d: Float): Float { var t = t val tLambda = { a: Float -> Float t = a t } return if ((tLambda(t / d / 2)) < 1) -c / 2 * (Math.sqrt((1 - t * t).toDouble()).toFloat() - 1) + b else c / 2 * (Math.sqrt((1 - (tLambda(t - 2f)) * t).toDouble()).toFloat() + 1) + b } }
bsd-3-clause
246c2b907ff28be3c8c99a17f4d59b95
28.6875
190
0.437882
3.251656
false
false
false
false
Kotlin/kotlinx.serialization
formats/properties/commonMain/src/kotlinx/serialization/properties/Properties.kt
1
11432
/* * Copyright 2017-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ @file:Suppress("FunctionName", "DeprecatedCallableAddReplaceWith") package kotlinx.serialization.properties import kotlinx.serialization.* import kotlinx.serialization.descriptors.* import kotlinx.serialization.encoding.* import kotlinx.serialization.internal.* import kotlinx.serialization.modules.* /** * Transforms a [Serializable] class' properties into a single flat [Map] consisting of * string keys and primitive type values, and vice versa. * * If the given class has non-primitive property `d` of arbitrary type `D`, `D` values are inserted * into the same map; keys for such values are prefixed with string `d.`: * * ``` * @Serializable * class Data(val property1: String) * * @Serializable * class DataHolder(val data: Data, val property2: String) * * val map = Properties.store(DataHolder(Data("value1"), "value2")) * // map contents will be the following: * // property2 = value2 * // data.property1 = value1 * ``` * * If the given class has a [List] property `l`, each value from the list * would be prefixed with `l.N.`, where N is an index for a particular value. * [Map] is treated as a `[key,value,...]` list. * * @param serializersModule A [SerializersModule] which should contain registered serializers * for [Contextual] and [Polymorphic] serialization, if you have any. */ @ExperimentalSerializationApi @Suppress("UNUSED_PARAMETER") public sealed class Properties( override val serializersModule: SerializersModule, ctorMarker: Nothing? ) : SerialFormat { private abstract inner class OutMapper<Value : Any> : NamedValueEncoder() { override val serializersModule: SerializersModule = [email protected] val map: MutableMap<String, Value> = mutableMapOf() protected abstract fun encode(value: Any): Value @Suppress("UNCHECKED_CAST") final override fun <T> encodeSerializableValue(serializer: SerializationStrategy<T>, value: T) { if (serializer is AbstractPolymorphicSerializer<*>) { val casted = serializer as AbstractPolymorphicSerializer<Any> val actualSerializer = casted.findPolymorphicSerializer(this, value as Any) return actualSerializer.serialize(this, value) } return serializer.serialize(this, value) } override fun encodeTaggedValue(tag: String, value: Any) { map[tag] = encode(value) } override fun encodeTaggedNull(tag: String) { // ignore nulls in output } override fun encodeTaggedEnum(tag: String, enumDescriptor: SerialDescriptor, ordinal: Int) { map[tag] = encode(enumDescriptor.getElementName(ordinal)) } } private inner class OutAnyMapper : OutMapper<Any>() { override fun encode(value: Any): Any = value } private inner class OutStringMapper : OutMapper<String>() { override fun encode(value: Any): String = value.toString() } private abstract inner class InMapper<Value : Any>( protected val map: Map<String, Value>, descriptor: SerialDescriptor ) : NamedValueDecoder() { override val serializersModule: SerializersModule = [email protected] private var currentIndex = 0 private val isCollection = descriptor.kind == StructureKind.LIST || descriptor.kind == StructureKind.MAP private val size = if (isCollection) Int.MAX_VALUE else descriptor.elementsCount protected abstract fun structure(descriptor: SerialDescriptor): InMapper<Value> final override fun beginStructure(descriptor: SerialDescriptor): CompositeDecoder { return structure(descriptor).also { copyTagsTo(it) } } final override fun <T> decodeSerializableValue(deserializer: DeserializationStrategy<T>): T { val type = map["type"]?.toString() if (deserializer is AbstractPolymorphicSerializer<*>) { val actualSerializer: DeserializationStrategy<out Any> = deserializer.findPolymorphicSerializer(this, type) @Suppress("UNCHECKED_CAST") return actualSerializer.deserialize(this) as T } return deserializer.deserialize(this) } final override fun decodeTaggedValue(tag: String): Value { return map.getValue(tag) } final override fun decodeTaggedEnum(tag: String, enumDescriptor: SerialDescriptor): Int { return when (val taggedValue = map.getValue(tag)) { is Int -> taggedValue is String -> enumDescriptor.getElementIndex(taggedValue) .also { if (it == CompositeDecoder.UNKNOWN_NAME) throw SerializationException("Enum '${enumDescriptor.serialName}' does not contain element with name '$taggedValue'") } else -> throw SerializationException("Value of enum entry '$tag' is neither an Int nor a String") } } final override fun decodeElementIndex(descriptor: SerialDescriptor): Int { while (currentIndex < size) { val name = descriptor.getTag(currentIndex++) if (map.keys.any { it.startsWith(name) && (it.length == name.length || it[name.length] == '.') }) return currentIndex - 1 if (isCollection) { // if map does not contain key we look for, then indices in collection have ended break } } return CompositeDecoder.DECODE_DONE } } private inner class InAnyMapper( map: Map<String, Any>, descriptor: SerialDescriptor ) : InMapper<Any>(map, descriptor) { override fun structure(descriptor: SerialDescriptor): InAnyMapper = InAnyMapper(map, descriptor) } private inner class InStringMapper( map: Map<String, String>, descriptor: SerialDescriptor ) : InMapper<String>(map, descriptor) { override fun structure(descriptor: SerialDescriptor): InStringMapper = InStringMapper(map, descriptor) override fun decodeTaggedBoolean(tag: String): Boolean = decodeTaggedValue(tag).toBoolean() override fun decodeTaggedByte(tag: String): Byte = decodeTaggedValue(tag).toByte() override fun decodeTaggedShort(tag: String): Short = decodeTaggedValue(tag).toShort() override fun decodeTaggedInt(tag: String): Int = decodeTaggedValue(tag).toInt() override fun decodeTaggedLong(tag: String): Long = decodeTaggedValue(tag).toLong() override fun decodeTaggedFloat(tag: String): Float = decodeTaggedValue(tag).toFloat() override fun decodeTaggedDouble(tag: String): Double = decodeTaggedValue(tag).toDouble() override fun decodeTaggedChar(tag: String): Char = decodeTaggedValue(tag).single() } /** * Encodes properties from the given [value] to a map using the given [serializer]. * `null` values are omitted from the output. */ @ExperimentalSerializationApi public fun <T> encodeToMap(serializer: SerializationStrategy<T>, value: T): Map<String, Any> { val m = OutAnyMapper() m.encodeSerializableValue(serializer, value) return m.map } /** * Encodes properties from the given [value] to a map using the given [serializer]. * Converts all primitive types to [String] using [toString] method. * `null` values are omitted from the output. */ @ExperimentalSerializationApi public fun <T> encodeToStringMap(serializer: SerializationStrategy<T>, value: T): Map<String, String> { val m = OutStringMapper() m.encodeSerializableValue(serializer, value) return m.map } /** * Decodes properties from the given [map] to a value of type [T] using the given [deserializer]. * [T] may contain properties of nullable types; they will be filled by non-null values from the [map], if present. */ @ExperimentalSerializationApi public fun <T> decodeFromMap(deserializer: DeserializationStrategy<T>, map: Map<String, Any>): T { val m = InAnyMapper(map, deserializer.descriptor) return m.decodeSerializableValue(deserializer) } /** * Decodes properties from the given [map] to a value of type [T] using the given [deserializer]. * [String] values are converted to respective primitive types using default conversion methods. * [T] may contain properties of nullable types; they will be filled by non-null values from the [map], if present. */ @ExperimentalSerializationApi public fun <T> decodeFromStringMap(deserializer: DeserializationStrategy<T>, map: Map<String, String>): T { val m = InStringMapper(map, deserializer.descriptor) return m.decodeSerializableValue(deserializer) } /** * A [Properties] instance that can be used as default and does not have any [SerializersModule] installed. */ @ExperimentalSerializationApi public companion object Default : Properties(EmptySerializersModule(), null) } @OptIn(ExperimentalSerializationApi::class) private class PropertiesImpl(serializersModule: SerializersModule) : Properties(serializersModule, null) /** * Creates an instance of [Properties] with a given [module]. */ @ExperimentalSerializationApi public fun Properties(module: SerializersModule): Properties = PropertiesImpl(module) /** * Encodes properties from given [value] to a map using serializer for reified type [T] and returns this map. * `null` values are omitted from the output. */ @ExperimentalSerializationApi public inline fun <reified T> Properties.encodeToMap(value: T): Map<String, Any> = encodeToMap(serializersModule.serializer(), value) /** * Encodes properties from given [value] to a map using serializer for reified type [T] and returns this map. * Converts all primitive types to [String] using [toString] method. * `null` values are omitted from the output. */ @ExperimentalSerializationApi public inline fun <reified T> Properties.encodeToStringMap(value: T): Map<String, String> = encodeToStringMap(serializersModule.serializer(), value) /** * Decodes properties from given [map], assigns them to an object using serializer for reified type [T] and returns this object. * [T] may contain properties of nullable types; they will be filled by non-null values from the [map], if present. */ @ExperimentalSerializationApi public inline fun <reified T> Properties.decodeFromMap(map: Map<String, Any>): T = decodeFromMap(serializersModule.serializer(), map) /** * Decodes properties from given [map], assigns them to an object using serializer for reified type [T] and returns this object. * [String] values are converted to respective primitive types using default conversion methods. * [T] may contain properties of nullable types; they will be filled by non-null values from the [map], if present. */ @ExperimentalSerializationApi public inline fun <reified T> Properties.decodeFromStringMap(map: Map<String, String>): T = decodeFromStringMap(serializersModule.serializer(), map) // Migrations below @PublishedApi internal fun noImpl(): Nothing = throw UnsupportedOperationException("Not implemented, should not be called")
apache-2.0
b6fc4d4f5262e040adc0aee251165318
42.139623
188
0.692005
4.78727
false
false
false
false
world-federation-of-advertisers/cross-media-measurement
src/main/kotlin/org/wfanet/measurement/kingdom/deploy/gcloud/spanner/writers/ReleaseCertificateHold.kt
1
7161
// Copyright 2021 The Cross-Media Measurement Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.wfanet.measurement.kingdom.deploy.gcloud.spanner.writers import java.lang.IllegalStateException import kotlinx.coroutines.flow.singleOrNull import org.wfanet.measurement.common.identity.ExternalId import org.wfanet.measurement.common.identity.InternalId import org.wfanet.measurement.gcloud.spanner.bufferUpdateMutation import org.wfanet.measurement.gcloud.spanner.set import org.wfanet.measurement.internal.kingdom.Certificate import org.wfanet.measurement.internal.kingdom.Certificate.RevocationState import org.wfanet.measurement.internal.kingdom.ReleaseCertificateHoldRequest import org.wfanet.measurement.internal.kingdom.copy import org.wfanet.measurement.kingdom.deploy.common.DuchyIds import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.common.CertificateRevocationStateIllegalException import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.common.DataProviderCertificateNotFoundException import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.common.DuchyCertificateNotFoundException import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.common.DuchyNotFoundException import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.common.KingdomInternalException import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.common.MeasurementConsumerCertificateNotFoundException import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.common.ModelProviderCertificateNotFoundException import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.readers.CertificateReader /** * Revokes a certificate in the database. * * Throws a subclass of [KingdomInternalException] on [execute]. * @throws [MeasurementConsumerCertificateNotFoundException] Certificate not found * @throws [DataProviderCertificateNotFoundException] Certificate not found * @throws [DuchyCertificateNotFoundException] Certificate not found * @throws [DuchyNotFoundException] Duchy not found * @throws [CertificateRevocationStateIllegalException] CertificateRevocation state is REVOKED or * not specified * * TODO(world-federation-of-advertisers/cross-media-measurement#305) : Consider cancelling all * associated active measurements if a certificate is revoked */ class ReleaseCertificateHold(private val request: ReleaseCertificateHoldRequest) : SpannerWriter<Certificate, Certificate>() { override suspend fun TransactionScope.runTransaction(): Certificate { val externalCertificateId = ExternalId(request.externalCertificateId) @Suppress("WHEN_ENUM_CAN_BE_NULL_IN_JAVA") // Proto enum fields are never null. val certificateResult = when (request.parentCase) { ReleaseCertificateHoldRequest.ParentCase.EXTERNAL_DATA_PROVIDER_ID -> { val externalDataProviderId = ExternalId(request.externalDataProviderId) val reader = CertificateReader(CertificateReader.ParentType.DATA_PROVIDER) .bindWhereClause(externalDataProviderId, externalCertificateId) reader.execute(transactionContext).singleOrNull() ?: throw DataProviderCertificateNotFoundException( externalDataProviderId, externalCertificateId ) } ReleaseCertificateHoldRequest.ParentCase.EXTERNAL_MEASUREMENT_CONSUMER_ID -> { val externalMeasurementConsumerId = ExternalId(request.externalMeasurementConsumerId) val reader = CertificateReader(CertificateReader.ParentType.MEASUREMENT_CONSUMER) .bindWhereClause(externalMeasurementConsumerId, externalCertificateId) reader.execute(transactionContext).singleOrNull() ?: throw MeasurementConsumerCertificateNotFoundException( externalMeasurementConsumerId, externalCertificateId ) { "Certificate not found." } } ReleaseCertificateHoldRequest.ParentCase.EXTERNAL_MODEL_PROVIDER_ID -> { val externalModelProviderId = ExternalId(request.externalModelProviderId) val reader = CertificateReader(CertificateReader.ParentType.MODEL_PROVIDER) .bindWhereClause(externalModelProviderId, externalCertificateId) reader.execute(transactionContext).singleOrNull() ?: throw ModelProviderCertificateNotFoundException( externalModelProviderId, externalCertificateId ) { "Certificate not found." } } ReleaseCertificateHoldRequest.ParentCase.EXTERNAL_DUCHY_ID -> { val duchyId = InternalId( DuchyIds.getInternalId(request.externalDuchyId) ?: throw DuchyNotFoundException(request.externalDuchyId) { " Duchy not found." } ) val reader = CertificateReader(CertificateReader.ParentType.DUCHY) .bindWhereClause(duchyId, externalCertificateId) reader.execute(transactionContext).singleOrNull() ?: throw DuchyCertificateNotFoundException( request.externalDuchyId, externalCertificateId ) { "Certificate not found." } } ReleaseCertificateHoldRequest.ParentCase.PARENT_NOT_SET -> throw IllegalStateException("ReleaseCertificateHoldRequest is missing parent field.") } val certificateRevocationState = certificateResult.certificate.revocationState @Suppress("WHEN_ENUM_CAN_BE_NULL_IN_JAVA") // Proto enum fields are never null. return when (certificateRevocationState) { RevocationState.HOLD -> { transactionContext.bufferUpdateMutation("Certificates") { set("CertificateId" to certificateResult.certificateId.value) set("RevocationState" to RevocationState.REVOCATION_STATE_UNSPECIFIED) } certificateResult.certificate.copy { revocationState = RevocationState.REVOCATION_STATE_UNSPECIFIED } } RevocationState.REVOKED, RevocationState.REVOCATION_STATE_UNSPECIFIED -> throw CertificateRevocationStateIllegalException( ExternalId(externalCertificateId.value), certificateRevocationState ) { "Certificate is in $certificateRevocationState state, cannot release hold." } RevocationState.UNRECOGNIZED -> throw IllegalStateException("Certificate RevocationState field is unrecognized.") } } override fun ResultScope<Certificate>.buildResult(): Certificate { return checkNotNull(transactionResult) } }
apache-2.0
77e2990741acdc3e54d99c53f49992c4
48.386207
114
0.743472
5.192893
false
false
false
false
mercadopago/px-android
example/src/main/java/com/mercadopago/android/px/base/TintableImageView.kt
1
961
package com.mercadopago.android.px.base import android.content.Context import android.content.res.ColorStateList import android.support.v7.widget.AppCompatImageView import android.util.AttributeSet class TintableImageView(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : AppCompatImageView(context, attrs, defStyleAttr) { constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0) constructor(context: Context) : this(context, null) private var tint: ColorStateList? = null override fun drawableStateChanged() { super.drawableStateChanged() if (tint?.isStateful == true) updateTintColor() } fun setColorFilter(tint: ColorStateList) { this.tint = tint super.setColorFilter(tint.getColorForState(drawableState, 0)) } private fun updateTintColor() { val color: Int = tint?.getColorForState(drawableState, 0) ?: 0 setColorFilter(color) } }
mit
b1cc760604fb18398dae7c45f884d360
31.066667
84
0.723205
4.469767
false
false
false
false
kassisdion/workshpKotlin
app/src/main/java/com/eldorne/workshop/di/modules/NetworkModule.kt
1
3707
package com.eldorne.workshop.di.modules import com.eldorne.workshop.BuildConfig import com.eldorne.workshop.api.NasaApi import dagger.Module import dagger.Provides import okhttp3.Interceptor import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import java.util.concurrent.TimeUnit import javax.inject.Singleton @Module class NetworkModule { /* ************************************************************************************************ ** Public dependencies for injection ************************************************************************************************ */ /** * Create a new instance of [AnilistApi] * * @param retrofitBuilder provided by [provideDefaultRetrofit] * @param okhtttpClientBuilder provided by [provideDefaultClient] */ @Provides @Singleton fun provideApi(retrofitBuilder: Retrofit.Builder, okHttpClientBuilder: OkHttpClient.Builder): NasaApi { /*Add interceptor for completing header*/ okHttpClientBuilder .interceptors() .add(0, Interceptor { chain -> val originalRequest = chain.request() val authenticatedRequest = originalRequest .newBuilder() .header("Content-Type", "application/json") .header("Accept", "application/json") .method(originalRequest.method(), originalRequest.body()) .build() chain.proceed(authenticatedRequest) }) /*Build API*/ return retrofitBuilder .baseUrl(NasaApi.BASE_URL) /*Set the converter (response->Json)*/ .addConverterFactory(GsonConverterFactory.create()) /*Set client (used to send request)*/ .client(okHttpClientBuilder.build()) .build() .create(NasaApi::class.java) } /* ************************************************************************************************ ** Internal dependencies ************************************************************************************************ */ /** * create a [retrofit2.Retrofit.Builder] with a default configuration : */ @Provides @Singleton fun provideDefaultRetrofit(): Retrofit.Builder { val builder = Retrofit.Builder() //Could add more stuff like a default converter strategy return builder } /** * Create a [okhttp3.OkHttpClient.Builder] with a default configuration: */ @Provides @Singleton fun provideDefaultClient(): OkHttpClient.Builder { val builder = OkHttpClient.Builder() //Set custom time out builder .connectTimeout(30000, TimeUnit.MILLISECONDS) .readTimeout(30000, TimeUnit.MILLISECONDS) .writeTimeout(30000, TimeUnit.MILLISECONDS) //Add interceptor for showing request in log // /!\ log shouldn't be displayed in a production environement /!\ if (BuildConfig.DEBUG) { builder.addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)) } builder.addInterceptor { chain -> val request = chain.request().newBuilder() request.addHeader("accept", "contentType/json") chain.proceed(request.build()) } //Could add more stuff like a cache strategy return builder } }
mit
ea47b79edd091ecf8c308e2c58fc853b
33.018349
104
0.543296
5.783151
false
false
false
false
Ray-Eldath/Avalon
src/main/kotlin/avalon/api/DelayResponse.kt
1
604
package avalon.api import avalon.util.DelayMessage import avalon.util.Message import java.util.concurrent.DelayQueue /** * Created by Eldath Ray on 2017/3/22. * * @author Eldath Ray */ class DelayResponse : Thread() { private val messages = DelayQueue<DelayMessage>() fun delay(message: DelayMessage): Boolean = messages.offer(message) override fun run() { var delayMessage: DelayMessage? = messages.poll() var message: Message while (delayMessage != null) { message = delayMessage.message message.response(delayMessage.doWhat.invoke()) delayMessage = messages.poll() } } }
agpl-3.0
9db3c993b42cb5de7d9b66e5dd099d28
21.37037
68
0.730132
3.431818
false
false
false
false
DSolyom/ViolinDS
ViolinDS/app/src/main/java/ds/violin/v1/util/LazyImageLoader.kt
1
7676
/* Copyright 2016 Dániel Sólyom 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 ds.violin.v1.util import android.app.ActivityManager import android.content.Context import android.graphics.Bitmap import android.os.Handler import android.util.LruCache import ds.violin.v1.Global import ds.violin.v1.util.cache.ImageFileCache import ds.violin.v1.util.common.Bitmaps import ds.violin.v1.util.common.Debug import ds.violin.v1.datasource.base.LazyLoader import ds.violin.v1.datasource.base.LazyLoaderTask import java.io.FileNotFoundException import java.net.URL private val TAG = "ImageLoader" /** * a [LazyLoader] singleton for bitmaps (images) * * @use call load with an [ImageDescriptor] to start loading * posts completion even if image found in cache */ object ImageLoader : LazyLoader<ImageDescriptor, Bitmap>() { init { needSleepingBetweenRetries = true } override fun load(descriptor: ImageDescriptor, completion: (ImageDescriptor, Bitmap?, Throwable?) -> Unit): Boolean { try { // cache first var bmp = LruBitmapCache.get(descriptor.prefix + descriptor.url); if (bmp != null) { Debug.logD(TAG, "loaded from cache: " + descriptor.prefix + " " + descriptor.url); /** post [completion] */ Handler().post { completion(descriptor, bmp, null) } return false } if (!descriptor.alwaysInBackground) { // file cache if it is safe/fast to load it on the current thread bmp = FileCache.get(descriptor) if (bmp != null) { /** post [completion] */ Handler().post { completion(descriptor, bmp, null) } return false } } /** real [LazyLoader]ing */ super.load(descriptor, completion) return true } catch(error: Throwable) { completion(descriptor, null, error) return false } } override fun createLoaderFor(descriptor: ImageDescriptor, lazyLoader: LazyLoader<ImageDescriptor, Bitmap>): LazyLoaderTask<ImageDescriptor, Bitmap> { return LazyImageDownloaderTask(descriptor, lazyLoader) } fun download(descriptor: ImageDescriptor): Bitmap? { if (!descriptor.url.substring(0, 4).equals("http")) { descriptor.url = "http://" + descriptor.url; } Debug.logD(TAG, "downloading: " + descriptor.prefix + " " + descriptor.url); var bmp: Bitmap? try { if (descriptor.maxX == -1) { bmp = Bitmaps.downloadImage(URL(descriptor.url)); } else { bmp = Bitmaps.getResizedImageFromHttpStream(URL(descriptor.url), descriptor.maxX, descriptor.maxY); } } catch(e: FileNotFoundException) { // no retries throw e } catch(e: Throwable) { Debug.logException(e) bmp = null } if (bmp == null) { // not found return null; } // set in bitmap cache LruBitmapCache.put(descriptor.prefix + descriptor.url, bmp); // set in file cache (in another thread - so we can give this bitmap right away Thread() { FileCache.put(descriptor.prefix + descriptor.url, Bitmaps.compressBitmapToByteArray(bmp!!)); }.start(); return bmp; } } private class LazyImageDownloaderTask(imageDescriptor: ImageDescriptor, lazyLoader: LazyLoader<ImageDescriptor, Bitmap>) : LazyLoaderTask<ImageDescriptor, Bitmap> { override val retryLimit: Int = 5 override val key: ImageDescriptor = imageDescriptor override val lazyLoader: LazyLoader<ImageDescriptor, Bitmap> = lazyLoader override var thread: Thread? = null override var retries: Int = 0 override lateinit var handler: Handler override var interrupted = false override fun load(descriptor: ImageDescriptor): Bitmap? { if (descriptor.alwaysInBackground) { val bmp = FileCache.get(descriptor) if (bmp != null) { return bmp } } return ImageLoader.download(descriptor) } } /** * data class for describing downloadable image * * @param url the image's origin * @param maxXDp the approximate maximum width in dp (will be doubled for large screens) of the loaded image * will scale if the original image was bigger * if left unset or set to 0, will use screen's width as the maximum * if set to -1 the original image will be loaded (be wary of it's size) * @param maxYDp the approximate maximum height in dp (will be doubled for large screens) of the loaded image * will scale if the original image was bigger * if left unset or set to 0, will use screen's height as the maximum */ data class ImageDescriptor(var url: String, val maxXDp: Int = 0, val maxYDp: Int = 0) { var alwaysInBackground = true val maxX: Int val maxY: Int init { maxX = when (maxXDp) { -1 -> -1 0 -> Global.screenWidth else -> (maxXDp * Global.dipImageMultiplier).toInt() } maxY = when (maxYDp) { -1 -> -1 0 -> Global.screenHeight else -> (maxYDp * Global.dipImageMultiplier).toInt() } } val prefix: String get() { return "" + maxX + "X" + maxY } override fun equals(other: Any?): Boolean { return other != null && other is ImageDescriptor && url == other.url && maxX == other.maxX && maxY == other.maxY } override fun hashCode(): Int { return (prefix + url).hashCode() } } private object LruBitmapCache : LruCache<String, Bitmap>({ val am = Global.context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager 1024 * am.largeMemoryClass / 7 }()) { override fun sizeOf(key: String, bitmap: Bitmap): Int { return bitmap.byteCount / 1024; } } private object FileCache : ImageFileCache(Global.context, "" + Global.context.packageName + "/images/", -1) { fun get(descriptor: ImageDescriptor): Bitmap? { var bmpBytes = FileCache[descriptor.prefix + descriptor.url] if (bmpBytes == null || bmpBytes.size == 0) { bmpBytes = FileCache[descriptor.url, descriptor.maxX, descriptor.maxY]; if (bmpBytes == null || bmpBytes.size == 0) { return null; } put(descriptor.prefix + descriptor.url, bmpBytes); } val bmp: Bitmap? try { bmp = Bitmaps.createBitmap(bmpBytes); LruBitmapCache.put(descriptor.prefix + descriptor.url, bmp); } catch(e: Throwable) { Debug.logException(e) bmp = null } Debug.logD(TAG, "loaded from file: " + descriptor.prefix + " " + descriptor.url); return bmp; } }
apache-2.0
4fed9d47a585f1e557a2ac6513d4df2e
31.247899
122
0.605682
4.443544
false
false
false
false
PolymerLabs/arcs-live
particles/Tutorial/Kotlin/7_Functional/GetPerson.kt
4
765
/* * Copyright 2020 Google LLC. * * This code may only be used under the BSD style license found at * http://polymer.github.io/LICENSE.txt * * Code distributed by Google as part of this project is also subject to an additional IP rights * grant found at * http://polymer.github.io/PATENTS.txt */ package arcs.tutorials /** * Sample WASM Particle. */ class GetPerson : AbstractGetPerson() { override fun getTemplate(slotName: String) = """ <input placeholder="Enter your name" spellcheck="false" on-change="onNameInputChange"> <div slotid="greetingSlot"></div>""".trimIndent() init { eventHandler("onNameInputChange") { eventData -> handles.person.store(GetPerson_Person(name = eventData["value"] ?: "Human")) } } }
bsd-3-clause
ebb53836ca3992a8049cdb27c319fda4
27.333333
96
0.687582
3.963731
false
false
false
false
cfieber/spinnaker-gradle-project
spinnaker-extensions/src/main/kotlin/com/netflix/spinnaker/gradle/extension/extensions/SpinnakerPluginExtension.kt
2
1906
/* * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.gradle.extension.extensions /** * Configuration for backend service modules. */ open class SpinnakerPluginExtension { /** * The Spinnaker service name that this plugin is for. */ var serviceName: String? set(value) { _serviceName = value } get() = requireValue("serviceName", _serviceName) private var _serviceName: String? = null /** * The fully qualified plugin class name. */ var pluginClass: String? set(value) { _pluginClass = value } get() = requireValue("pluginClass", _pluginClass) private var _pluginClass: String? = null /** * Service version requirements for the plugin, e.g. "orca>=7.0.0". * * If this value remains unset, the value will be `$serviceName>=0.0.0`, effectively matching any version of the * target Spinnaker service. */ var requires: String? set(value) { _requires = value } get() { return _requires ?: "$serviceName>=0.0.0" } private var _requires: String? = null /** * Not yet supported. */ var dependencies: String? = null private fun requireValue(name: String, value: String?): String { if (value == null) { throw IllegalStateException("spinnakerPlugin.$name must not be null") } return value } }
apache-2.0
989641182bd2519a92e49de9c285c4fd
25.472222
114
0.670514
4.161572
false
false
false
false
nemerosa/ontrack
ontrack-extension-sonarqube/src/main/java/net/nemerosa/ontrack/extension/sonarqube/measures/SonarQubeMeasuresCollectionServiceImpl.kt
1
10562
package net.nemerosa.ontrack.extension.sonarqube.measures import io.micrometer.core.instrument.MeterRegistry import net.nemerosa.ontrack.extension.sonarqube.client.SonarQubeClientFactory import net.nemerosa.ontrack.extension.sonarqube.property.SonarQubeProperty import net.nemerosa.ontrack.extension.sonarqube.property.SonarQubePropertyType import net.nemerosa.ontrack.model.buildfilter.BuildFilterService import net.nemerosa.ontrack.model.metrics.MetricsExportService import net.nemerosa.ontrack.model.metrics.increment import net.nemerosa.ontrack.model.metrics.measure import net.nemerosa.ontrack.model.security.SecurityService import net.nemerosa.ontrack.model.settings.CachedSettingsService import net.nemerosa.ontrack.model.structure.* import org.slf4j.LoggerFactory import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional @Service @Transactional class SonarQubeMeasuresCollectionServiceImpl( private val clientFactory: SonarQubeClientFactory, private val entityDataService: EntityDataService, private val buildDisplayNameService: BuildDisplayNameService, private val branchDisplayNameService: BranchDisplayNameService, private val metricsExportService: MetricsExportService, private val meterRegistry: MeterRegistry, private val structureService: StructureService, private val propertyService: PropertyService, private val branchModelMatcherService: BranchModelMatcherService, private val buildFilterService: BuildFilterService, private val cachedSettingsService: CachedSettingsService, private val securityService: SecurityService ) : SonarQubeMeasuresCollectionService { private val logger = LoggerFactory.getLogger(SonarQubeMeasuresCollectionService::class.java) override fun collect(project: Project, logger: (String) -> Unit) { // Gets the SonarQube property of the project val property = propertyService.getProperty(project, SonarQubePropertyType::class.java).value if (property != null) { // List of metrics to collect // Configurable list of metrics val metrics: List<String> = getListOfMetrics(property) // For all project branches structureService.getBranchesForProject(project.id) // ... filter branches according to the model matcher .filter { branch -> matches(branch, property) } // ... scans the branch .forEach { collect(it, property, metrics, logger) } } } private fun collect(branch: Branch, property: SonarQubeProperty, metrics: List<String>, logger: (String) -> Unit) { // Logging logger("Getting SonarQube measures for ${branch.entityDisplayName}") // Gets the validation stamp for this branch val vs = structureService.getValidationStampListForBranch(branch.id) .find { it.name == property.validationStamp } if (vs != null) { // Loops over all builds and launch the collection structureService.forEachBuild(branch, BuildSortDirection.FROM_NEWEST) { build -> // Logging logger("Getting SonarQube measures for ${build.entityDisplayName}") // Processing doCollect(build, property, metrics, vs) // Going on true } } } override fun getLastMeasures(branch: Branch): SonarQubeMeasures? { // Gets the SonarQube property of the project val property = propertyService.getProperty(branch.project, SonarQubePropertyType::class.java).value if (property != null) { // Gets the validation stamp for this branch val vs = structureService.getValidationStampListForBranch(branch.id) .find { it.name == property.validationStamp } if (vs != null) { // Gets the latest build for this branch having a scan val build = buildFilterService.standardFilterProviderData(1) .withWithValidationStamp(vs.name) .withWithValidationStampStatus(ValidationRunStatusID.PASSED) .build() .filterBranchBuilds(branch) .firstOrNull() if (build != null) { return getMeasures(build) } } } return null } override fun matches(build: Build, property: SonarQubeProperty): Boolean { return matches(build.branch, property) } private fun matches(branch: Branch, property: SonarQubeProperty): Boolean { val path: String = getBranchPath(branch) return matchesPattern(path, property.branchPattern) && (!property.branchModel || matchesModel(branch)) } private fun matchesModel(branch: Branch): Boolean { val matcher = branchModelMatcherService.getBranchModelMatcher(branch.project) return matcher?.matches(branch) ?: true } private fun matchesPattern(path: String, branchPattern: String?): Boolean { return branchPattern.isNullOrBlank() || branchPattern.toRegex().matches(path) } private fun getBranchPath(branch: Branch): String = branchDisplayNameService.getBranchDisplayName(branch) override fun collect(build: Build, property: SonarQubeProperty): SonarQubeMeasuresCollectionResult { // Gets the validation stamp for this branch val vs = structureService.getValidationStampListForBranch(build.branch.id) .find { it.name == property.validationStamp } // Collection for this build, only if there is a validation stamp being defined return if (vs != null) { val result = doCollect(build, property, getListOfMetrics(property), vs) if (logger.isDebugEnabled) { logger.debug("build=${build.entityDisplayName},scan=${result.ok},result=${result.message}") } result } else { SonarQubeMeasuresCollectionResult.error("Validation stamp ${property.validationStamp} cannot be found in ${build.branch.entityDisplayName}") } } private fun doCollect(build: Build, property: SonarQubeProperty, metrics: List<String>, validationStamp: ValidationStamp): SonarQubeMeasuresCollectionResult { // Gets the last validation run for this build and the validation stamp val lastRun = structureService.getValidationRunsForBuildAndValidationStamp( buildId = build.id, validationStampId = validationStamp.id, offset = 0, count = 1 ).firstOrNull() // If no run, we don't want to go further ?: return SonarQubeMeasuresCollectionResult.error("No validation run for ${validationStamp.name} can be found for ${build.entityDisplayName}") // Gets the status of the last run val status = lastRun.lastStatus.statusID.id // Client val client = clientFactory.getClient(property.configuration) // Name of the build val version: String = buildDisplayNameService.getBuildDisplayName(build) // Getting the measures val metricTags = mapOf( "project" to build.project.name, "branch" to build.branch.name, "uri" to property.configuration.url ) val measures: Map<String, Double?>? = meterRegistry.measure( started = SonarQubeMetrics.METRIC_ONTRACK_SONARQUBE_COLLECTION_STARTED_COUNT, success = SonarQubeMetrics.METRIC_ONTRACK_SONARQUBE_COLLECTION_SUCCESS_COUNT, error = SonarQubeMetrics.METRIC_ONTRACK_SONARQUBE_COLLECTION_ERROR_COUNT, time = SonarQubeMetrics.METRIC_ONTRACK_SONARQUBE_COLLECTION_TIME, tags = metricTags ) { val scmBranch = getBranchPath(build.branch) client.getMeasuresForVersion(property.key, scmBranch, version, metrics) } // Safe measures if (!measures.isNullOrEmpty()) { val safeMeasures = mutableMapOf<String, Double>() measures.forEach { (name, value) -> if (value != null) { safeMeasures[name] = value } else { // No metric collected meterRegistry.increment( SonarQubeMetrics.METRIC_ONTRACK_SONARQUBE_COLLECTION_NONE_COUNT, *(metricTags + ("measure" to name)).toList().toTypedArray() ) } } // Metrics safeMeasures.forEach { (name, value) -> metricsExportService.exportMetrics( SonarQubeMetrics.METRIC_ONTRACK_SONARQUBE_MEASURE, tags = mapOf( "project" to build.project.name, "branch" to build.branch.name, "status" to status, "measure" to name ), fields = mapOf( "value" to value ), timestamp = build.signature.time ) } // Storage of metrics for build securityService.asAdmin { entityDataService.store( build, SonarQubeMeasures::class.java.name, SonarQubeMeasures(safeMeasures) ) } // OK return SonarQubeMeasuresCollectionResult.ok(safeMeasures) } else { return SonarQubeMeasuresCollectionResult.error("No SonarQube measure can be found for ${build.entityDisplayName}") } } private fun getListOfMetrics(property: SonarQubeProperty): List<String> { return if (property.override) { property.measures } else { val settings = cachedSettingsService.getCachedSettings(SonarQubeMeasuresSettings::class.java) (settings.measures.toSet() + property.measures).toList() } } override fun getMeasures(build: Build): SonarQubeMeasures? = entityDataService.retrieve( build, SonarQubeMeasures::class.java.name, SonarQubeMeasures::class.java ) }
mit
90cd79fd42d17c16b449fe4fb88de27f
46.581081
162
0.628953
5.315551
false
false
false
false
nemerosa/ontrack
ontrack-kdsl/src/main/java/net/nemerosa/ontrack/kdsl/spec/extension/av/AutoVersioningAuditMgt.kt
1
1911
package net.nemerosa.ontrack.kdsl.spec.extension.av import net.nemerosa.ontrack.kdsl.connector.Connected import net.nemerosa.ontrack.kdsl.connector.Connector import net.nemerosa.ontrack.kdsl.connector.graphql.schema.AutoVersioningAuditEntriesQuery import net.nemerosa.ontrack.kdsl.connector.graphqlConnector /** * Management interface for the audit of the auto versioning */ class AutoVersioningAuditMgt(connector: Connector) : Connected(connector) { /** * Gets the list of auto versioning audit entries */ fun entries( offset: Int = 0, size: Int = 10, source: String? = null, project: String, branch: String? = null, version: String? = null, ): List<AutoVersioningAuditEntry> = graphqlConnector.query( AutoVersioningAuditEntriesQuery.builder() .offset(offset) .size(size) .source(source) .project(project) .branch(branch) .version(version) .build() )?.autoVersioningAuditEntries()?.pageItems()?.map { item -> AutoVersioningAuditEntry( order = AutoVersioningOrder( uuid = item.order().uuid(), ), running = item.running() ?: false, mostRecentState = AutoVersioningAuditEntryState( state = item.mostRecentState().state().name, data = item.mostRecentState().data(), ), audit = item.audit().map { auditEntry -> AutoVersioningAuditEntryState( state = auditEntry.state().name, data = auditEntry.data(), ) }, routing = item.routing(), queue = item.queue(), ) } ?: emptyList() }
mit
bb7dd5dabf531c1d280dc2743c0cd7f0
33.763636
89
0.548927
5.137097
false
false
false
false
nemerosa/ontrack
ontrack-ui/src/main/java/net/nemerosa/ontrack/boot/ui/AccountController.kt
1
6263
package net.nemerosa.ontrack.boot.ui import net.nemerosa.ontrack.model.Ack import net.nemerosa.ontrack.model.form.* import net.nemerosa.ontrack.model.form.Form.Companion.create import net.nemerosa.ontrack.model.form.Form.Companion.defaultNameField import net.nemerosa.ontrack.model.security.* import net.nemerosa.ontrack.model.structure.ID import net.nemerosa.ontrack.ui.controller.AbstractResourceController import net.nemerosa.ontrack.ui.resource.Link import net.nemerosa.ontrack.ui.resource.Resources import org.springframework.web.bind.annotation.* import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder import javax.validation.Valid /** * Management of accounts */ @RestController @RequestMapping("/rest/accounts") class AccountController( private val accountService: AccountService ) : AbstractResourceController() { /** * List of accounts */ @GetMapping("") fun getAccounts(): Resources<Account> = Resources.of( accountService.accounts, uri(MvcUriComponentsBuilder.on(javaClass).getAccounts()) ) .with(Link.CREATE, uri(MvcUriComponentsBuilder.on(AccountController::class.java).getCreationForm())) /** * Form to create a built-in account */ @GetMapping("create") fun getCreationForm(): Form = create() .with(defaultNameField()) .with(Text.of("fullName").length(100).label("Full name").help("Display name for the account")) .with(Email.of("email").label("Email").length(200).help("Contact email for the account")) .with(Password.of("password").label("Password").length(40).help("Password for the account")) .with( MultiSelection.of("groups").label("Groups") .items(accountService.getAccountGroupsForSelection(ID.NONE)) ) .with( YesNo.of(Account::disabled.name) .label("Disabled") .help("Is this account disabled? If disabled, it cannot be used to access Ontrack any longer.") .value(false) ) .with( YesNo.of(Account::locked.name) .label("Locked") .help("Is this account locked? If locked, it can be updated only by an administrator.") .value(false) ) /** * Creation of a built-in account */ @PostMapping("create") fun create(@RequestBody @Valid input: AccountInput): Account { return accountService.create(input) } /** * Gets an account by its ID */ @GetMapping("{accountId}") fun getAccount(@PathVariable accountId: ID): Account { return accountService.getAccount(accountId) } /** * Update form for an account */ @GetMapping("{accountId}/update") fun getUpdateForm(@PathVariable accountId: ID): Form { val account = accountService.getAccount(accountId) var form = getCreationForm() // Name in read-only mode for the default admin if (account.isDefaultAdmin) { form = form.with(defaultNameField().readOnly()) } // Password not filled in, and not required on update form = form.with(Password.of("password").label("Password").length(40).help("Password for the account. Leave blank to keep it unchanged.").optional()) // Groups form = form.with( MultiSelection.of("groups").label("Groups") .items(accountService.getAccountGroupsForSelection(accountId)) ) // OK return form .fill("name", account.name) .fill("fullName", account.fullName) .fill("email", account.email) .fill(Account::disabled.name, account.disabled) .fill(Account::locked.name, account.locked) } /** * Updating an account */ @PutMapping("{accountId}/update") fun updateAccount(@PathVariable accountId: ID, @RequestBody @Valid input: AccountInput): Account { return accountService.updateAccount(accountId, input) } /** * Deleting an account */ @DeleteMapping("{accountId}") fun deleteAccount(@PathVariable accountId: ID): Ack { return accountService.deleteAccount(accountId) } /** * List of groups */ @GetMapping("groups") fun getAccountGroups(): Resources<AccountGroup> = Resources.of( accountService.accountGroups, uri(MvcUriComponentsBuilder.on(javaClass).getAccountGroups()) ) .with(Link.CREATE, uri(MvcUriComponentsBuilder.on(AccountController::class.java).getGroupCreationForm())) /** * Form to create an account group */ @GetMapping("groups/create") fun getGroupCreationForm(): Form = create() .name() .description() /** * Creation of an account group */ @PostMapping("groups/create") fun create(@RequestBody @Valid input: AccountGroupInput): AccountGroup { return accountService.createGroup(input) } /** * Getting a group */ @GetMapping("groups/{groupId}") fun getGroup(@PathVariable groupId: ID): AccountGroup { return accountService.getAccountGroup(groupId) } /** * Form to update an account group */ @GetMapping("groups/{groupId}/update") fun getGroupUpdateForm(@PathVariable groupId: ID): Form { val accountGroup = accountService.getAccountGroup(groupId) return getGroupCreationForm() .fill("name", accountGroup.name) .fill("description", accountGroup.description) } /** * Updating a group */ @PutMapping("groups/{groupId}/update") fun updateGroup(@PathVariable groupId: ID, @RequestBody @Valid input: AccountGroupInput): AccountGroup { return accountService.updateGroup(groupId, input) } /** * Deleting a group. This does not delete the associated accounts, only the links to them. */ @DeleteMapping("groups/{groupId}") fun deleteGroup(@PathVariable groupId: ID): Ack { return accountService.deleteGroup(groupId) } }
mit
e24010796c50d3e9949bb9e17e7b61e2
33.8
157
0.62957
4.748294
false
false
false
false
BOINC/boinc
android/BOINC/app/src/main/java/edu/berkeley/boinc/rpc/AccountManagerClasses.kt
4
3640
/* * This file is part of BOINC. * http://boinc.berkeley.edu * Copyright (C) 2020 University of California * * BOINC is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation, * either version 3 of the License, or (at your option) any later version. * * BOINC is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with BOINC. If not, see <http://www.gnu.org/licenses/>. */ package edu.berkeley.boinc.rpc import android.os.Parcel import android.os.Parcelable import androidx.core.os.ParcelCompat.readBoolean import androidx.core.os.ParcelCompat.writeBoolean /** * Holds information about the attachable account managers. * The source of the account managers is all_projects_list.xml. */ data class AccountManager internal constructor( var name: String = "", var url: String = "", var description: String = "", var imageUrl: String = "" ) : Parcelable { private constructor(parcel: Parcel) : this(parcel.readString() ?: "", parcel.readString() ?: "", parcel.readString() ?: "", parcel.readString() ?: "") override fun describeContents() = 0 override fun writeToParcel(dest: Parcel, arg1: Int) { dest.writeString(name) dest.writeString(url) dest.writeString(description) dest.writeString(imageUrl) } companion object { @JvmField val CREATOR: Parcelable.Creator<AccountManager> = object : Parcelable.Creator<AccountManager> { override fun createFromParcel(parcel: Parcel) = AccountManager(parcel) override fun newArray(size: Int) = arrayOfNulls<AccountManager>(size) } } } /** * Holds information about the currently used account manager. */ data class AcctMgrInfo internal constructor( var acctMgrName: String = "", var acctMgrUrl: String = "", var isHavingCredentials: Boolean = false ) : Parcelable { var isPresent: Boolean = false constructor( acctMgrName: String, acctMgrUrl: String, isHavingCredentials: Boolean, isPresent: Boolean) : this(acctMgrName, acctMgrUrl, isHavingCredentials) { this.isPresent = isPresent } private constructor(parcel: Parcel) : this(parcel.readString() ?: "", parcel.readString() ?: "", readBoolean(parcel), readBoolean(parcel)) override fun describeContents() = 0 override fun writeToParcel(dest: Parcel, flags: Int) { dest.writeString(acctMgrName) dest.writeString(acctMgrUrl) writeBoolean(dest, isHavingCredentials) writeBoolean(dest, isPresent) } object Fields { const val ACCT_MGR_NAME = "acct_mgr_name" const val ACCT_MGR_URL = "acct_mgr_url" const val HAVING_CREDENTIALS = "have_credentials" } companion object { @JvmField val CREATOR: Parcelable.Creator<AcctMgrInfo> = object : Parcelable.Creator<AcctMgrInfo> { override fun createFromParcel(parcel: Parcel) = AcctMgrInfo(parcel) override fun newArray(size: Int) = arrayOfNulls<AcctMgrInfo>(size) } } } data class AcctMgrRPCReply(var errorNum: Int = 0, val messages: MutableList<String> = arrayListOf())
lgpl-3.0
e23cc4b02b385912b0c3944ce29e426d
33.018692
103
0.666209
4.455324
false
true
false
false
DemonWav/IntelliJBukkitSupport
src/main/kotlin/translations/actions/SortTranslationsAction.kt
1
1112
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2021 minecraft-dev * * MIT License */ package com.demonwav.mcdev.translations.actions import com.demonwav.mcdev.translations.TranslationFiles import com.demonwav.mcdev.translations.sorting.TranslationSorter import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.LangDataKeys import com.intellij.openapi.actionSystem.PlatformDataKeys class SortTranslationsAction : AnAction() { override fun actionPerformed(e: AnActionEvent) { val file = e.getData(LangDataKeys.PSI_FILE) ?: return TranslationSorter.query(file.project, file) } override fun update(e: AnActionEvent) { val file = e.getData(LangDataKeys.VIRTUAL_FILE) val editor = e.getData(PlatformDataKeys.EDITOR) if (file == null || editor == null) { e.presentation.isEnabledAndVisible = false return } e.presentation.isEnabledAndVisible = TranslationFiles.isTranslationFile(file) } }
mit
88c01c865f6ebb43bf7fad4a177902b5
30.771429
85
0.732014
4.483871
false
false
false
false
hewking/HUILibrary
app/src/main/java/com/hewking/custom/TideRippleView2.kt
1
7633
package com.hewking.custom import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.animation.ValueAnimator import android.content.Context import android.graphics.* import android.util.AttributeSet import android.view.View import android.view.animation.LinearInterpolator import com.hewking.custom.util.dp2px import com.hewking.custom.util.getColor import java.util.concurrent.CopyOnWriteArrayList /** * 项目名称:FlowChat * 类的描述:xfermode 的使用采用canvas.drawBitmap 的方式实现 * 创建人员:hewking * 创建时间:2018/12/11 0011 * 修改人员:hewking * 修改时间:2018/12/11 0011 * 修改备注: * Version: 1.0.0 */ class TideRippleView2(ctx: Context, attrs: AttributeSet) : View(ctx, attrs) { private var radiuls: Int = 0 private val rippleCircles = CopyOnWriteArrayList<RippleCircle>() init { } private val ripplePaint by lazy { Paint().apply { style = Paint.Style.STROKE strokeWidth = dp2px(0.5f).toFloat() color = getColor(R.color.pink_f5b8c2) isAntiAlias = true } } private val backPaint by lazy { Paint().apply { style = Paint.Style.FILL isAntiAlias = true strokeWidth = dp2px(0.5f).toFloat() } } private var sweepProgress = 0 set(value) { if (value >= 360) { field = 0 } else { field = value } } private var fps: Int = 0 private var fpsPaint = Paint().apply { isAntiAlias = true style = Paint.Style.STROKE color = Color.GREEN textSize = dp2px(20f).toFloat() strokeWidth = dp2px(1f).toFloat() } private val renderAnimator by lazy { ValueAnimator.ofInt(0, 60) .apply { interpolator = LinearInterpolator() duration = 1000 repeatMode = ValueAnimator.RESTART repeatCount = ValueAnimator.INFINITE addUpdateListener { postInvalidateOnAnimation() fps++ sweepProgress++ } addListener(object : AnimatorListenerAdapter() { override fun onAnimationRepeat(animation: Animator?) { super.onAnimationRepeat(animation) fps = 0 } }) } } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) val wMode = MeasureSpec.getMode(widthMeasureSpec) val wSize = MeasureSpec.getSize(widthMeasureSpec) val hMode = MeasureSpec.getMode(heightMeasureSpec) val hSize = MeasureSpec.getSize(heightMeasureSpec) val size = Math.min(wSize, hSize) if (wMode == MeasureSpec.AT_MOST || hMode == MeasureSpec.AT_MOST) { radiuls = size.div(2) } } var backCanvas: Canvas? = null var backBitmap: Bitmap? = null override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { super.onSizeChanged(w, h, oldw, oldh) backBitmap?.recycle() if (w != 0 && h != 0) { backBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888) backCanvas = Canvas(backBitmap) } } override fun onDraw(canvas: Canvas?) { canvas ?: return for (i in 0 until rippleCircles.size) { rippleCircles[i].draw(canvas) } val maxRadius = Math.min(width, height).div(2).toFloat() val radius = maxRadius.div(2) canvas.save() canvas.rotate(sweepProgress.toFloat(), width.div(2f), height.div(2f)) val colors = intArrayOf(getColor(R.color.pink_fa758a), getColor(R.color.pink_f5b8c2), getColor(R.color.top_background_color), getColor(R.color.white)) backPaint.setShader(SweepGradient(width.div(2).toFloat(), height.div(2).toFloat(), colors, floatArrayOf(0f, 0.001f, 0.9f, 1f))) val rectF = RectF(width.div(2f) - radius , height.div(2f) - radius , width.div(2f) + radius , height.div(2f) + radius) val sc = canvas.saveLayer(rectF, backPaint, Canvas.ALL_SAVE_FLAG) // canvas.drawBitmap(makeDst(), null,rectF, backPaint) canvas.drawCircle(width.div(2).toFloat(), height.div(2).toFloat(), radius, backPaint) backPaint.setXfermode(PorterDuffXfermode(PorterDuff.Mode.DST_OUT)) // canvas.drawCircle(width.div(2f), height.div(2f), radius.div(3f), backPaint) /* rectF.apply { left = width.div(2f) - radius * 1f.div(3) top = height.div(2f) - radius * 1f.div(3) right = width.div(2f) + radius * 1f.div(3) bottom = height.div(2f) + radius * 1f.div(3) } canvas.drawBitmap(makeSrc(),null,rectF,backPaint)*/ canvas.drawCircle(width.div(2f), height.div(2f), radius.div(3f), backPaint) backPaint.setXfermode(null) backPaint.setShader(null) canvas.restoreToCount(sc) canvas.restore() if (BuildConfig.DEBUG) { canvas.drawText(fps.toString(), paddingStart.toFloat() , height - dp2px(10f).toFloat() - paddingBottom, fpsPaint) } } fun makeSrc(): Bitmap { val size = Math.min(width, height).div(6) val bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888) val canvas = Canvas(bitmap) val radius = size.div(2f) canvas.drawCircle(radius, radius, radius, backPaint) return bitmap } fun makeDst(): Bitmap { val size = Math.min(width, height).div(2) val bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888) val canvas = Canvas(bitmap) val radius = size.div(2f) canvas.drawCircle(radius, radius, radius, backPaint) return bitmap } override fun onAttachedToWindow() { super.onAttachedToWindow() // start anim startRipple() renderAnimator.start() } private fun startRipple() { val runnable = Runnable { rippleCircles.add(RippleCircle().apply { cx = width.div(2).toFloat() cy = height.div(2).toFloat() val maxRadius = Math.min(width, height).div(2).toFloat() startRadius = maxRadius.div(2) endRadius = maxRadius }) startRipple() } postOnAnimationDelayed(runnable, 2000) } override fun onDetachedFromWindow() { super.onDetachedFromWindow() // end anim renderAnimator.end() backBitmap?.recycle() } inner class RippleCircle { // 4s * 60 frms = 240 private val slice = 300 var startRadius = 0f var endRadius = 0f var cx = 0f var cy = 0f private var progress = 0 fun draw(canvas: Canvas) { if (progress >= slice) { // remove post { rippleCircles.remove(this) } return } progress++ ripplePaint.alpha = (1 - progress.div(slice * 1.0f)).times(255).toInt() val radis = startRadius + (endRadius - startRadius).div(slice).times(progress) canvas.drawCircle(cx, cy, radis, ripplePaint) } } }
mit
8da331710267217a8acf3b939a65b096
32.087719
158
0.573379
4.315217
false
false
false
false
bozaro/git-as-svn
src/main/kotlin/svnserver/repository/git/prop/GitIgnore.kt
1
6416
/* * This file is part of git-as-svn. It is subject to the license terms * in the LICENSE file found in the top-level directory of this distribution * and at http://www.gnu.org/licenses/gpl-2.0.html. No part of git-as-svn, * including this file, may be copied, modified, propagated, or distributed * except according to the terms contained in the LICENSE file. */ package svnserver.repository.git.prop import org.eclipse.jgit.errors.InvalidPatternException import org.eclipse.jgit.lib.Constants import org.eclipse.jgit.lib.FileMode import org.slf4j.Logger import org.tmatesoft.svn.core.SVNProperty import svnserver.Loggers import svnserver.repository.git.path.PathMatcher import svnserver.repository.git.path.Wildcard import java.io.BufferedReader import java.io.IOException import java.io.InputStream import java.io.InputStreamReader import java.nio.charset.StandardCharsets import java.util.* import java.util.regex.PatternSyntaxException /** * Parse and processing .gitignore. * * @author Artem V. Navrotskiy <[email protected]> */ internal class GitIgnore : GitProperty { private val matchers: MutableList<PathMatcher> // svn:global-ignores private val global: Array<String> // svn:ignore private val local: Array<String> /** * Parse and store .gitignore data (http://git-scm.com/docs/gitignore). * * * Important: * * An optional prefix "!" which negates the pattern is not supported. * * Mask trailing slash is not supported (/foo/bar/ works like /foo/bar). * * @param reader Original file content. */ constructor(reader: BufferedReader) { val localList = ArrayList<String>() val globalList = ArrayList<String>() matchers = ArrayList() for (txt in reader.lines()) { val line = trimLine(txt) if (line.isEmpty()) continue try { val wildcard = Wildcard(line) if (wildcard.isSvnCompatible) { processMatcher(localList, globalList, matchers, wildcard.matcher) } } catch (e: InvalidPatternException) { log.warn("Found invalid git pattern: {}", line) } catch (e: PatternSyntaxException) { log.warn("Found invalid git pattern: {}", line) } } local = localList.toTypedArray() global = globalList.toTypedArray() } private fun trimLine(line: String): String { if (line.isEmpty() || line.startsWith("#") || line.startsWith("!") || line.startsWith("\\!")) return "" // Remove trailing spaces end escapes. var end: Int = line.length while (end > 0) { val c: Char = line[end - 1] if (c != ' ') { if ((end < line.length) && (line[end - 1] == '\\')) { end++ } break } end-- } return line.substring(0, end) } private constructor(local: List<String>, global: List<String>, matchers: MutableList<PathMatcher>) { this.local = local.toTypedArray() this.global = global.toTypedArray() this.matchers = matchers } override fun apply(props: MutableMap<String, String>) { if (global.isNotEmpty()) { props.compute(SVNProperty.INHERITABLE_IGNORES) { _, value -> addIgnore(value, global) } } if (local.isNotEmpty()) { props.compute(SVNProperty.IGNORE) { _, value -> addIgnore(value, local) } } } override fun createForChild(name: String, mode: FileMode): GitProperty? { if (matchers.isEmpty() || (mode.objectType == Constants.OBJ_BLOB)) { return null } val localList: MutableList<String> = ArrayList() val globalList: MutableList<String> = ArrayList() val childMatchers: MutableList<PathMatcher> = ArrayList() for (matcher: PathMatcher in matchers) { processMatcher(localList, globalList, childMatchers, matcher.createChild(name, true)) } if (localList.isEmpty() && globalList.isEmpty() && childMatchers.isEmpty()) { return null } return GitIgnore(localList, globalList, childMatchers) } override val filterName: String? get() { return null } override fun hashCode(): Int { var result: Int = matchers.hashCode() result = 31 * result + global.contentHashCode() result = 31 * result + local.contentHashCode() return result } override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || javaClass != other.javaClass) return false val gitIgnore: GitIgnore = other as GitIgnore return (global.contentEquals(gitIgnore.global) && local.contentEquals(gitIgnore.local) && (matchers == gitIgnore.matchers)) } companion object { private val log: Logger = Loggers.git private fun processMatcher(local: MutableList<String>, global: MutableList<String>, matchers: MutableList<PathMatcher>, matcher: PathMatcher?) { if (matcher == null) { return } val maskGlobal: String? = matcher.svnMaskGlobal if (maskGlobal != null) { global.add(maskGlobal) return } val maskLocal: String? = matcher.svnMaskLocal if (maskLocal != null) { local.add(maskLocal) } matchers.add(matcher) } @Throws(IOException::class) fun parseConfig(stream: InputStream): GitIgnore { val reader = BufferedReader(InputStreamReader(stream, StandardCharsets.UTF_8)) return GitIgnore(reader) } private fun addIgnore(oldValue: String?, ignores: Array<String>): String { val contains = HashSet<String>() val result = StringBuilder() if (oldValue != null) { result.append(oldValue) contains.addAll(oldValue.split("\n")) } for (ignore in ignores) { if (contains.add(ignore)) { result.append(ignore).append('\n') } } return result.toString() } } }
gpl-2.0
75738f399eae1a2fd67367af6945d9fd
34.644444
152
0.594919
4.556818
false
false
false
false
cashapp/sqldelight
sqldelight-compiler/src/main/kotlin/app/cash/sqldelight/core/lang/util/ExprUtil.kt
1
10011
/* * Copyright (C) 2017 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package app.cash.sqldelight.core.lang.util import app.cash.sqldelight.core.compiler.SqlDelightCompiler.allocateName import app.cash.sqldelight.core.compiler.model.PragmaWithResults import app.cash.sqldelight.core.compiler.model.SelectQueryable import app.cash.sqldelight.core.lang.types.typeResolver import app.cash.sqldelight.dialect.api.IntermediateType import app.cash.sqldelight.dialect.api.PrimitiveType import app.cash.sqldelight.dialect.api.PrimitiveType.ARGUMENT import app.cash.sqldelight.dialect.api.PrimitiveType.BLOB import app.cash.sqldelight.dialect.api.PrimitiveType.INTEGER import app.cash.sqldelight.dialect.api.PrimitiveType.NULL import app.cash.sqldelight.dialect.api.PrimitiveType.REAL import app.cash.sqldelight.dialect.api.PrimitiveType.TEXT import app.cash.sqldelight.dialect.api.QueryWithResults import app.cash.sqldelight.dialect.api.TypeResolver import app.cash.sqldelight.dialect.api.encapsulatingType import com.alecstrong.sql.psi.core.psi.SqlBetweenExpr import com.alecstrong.sql.psi.core.psi.SqlBinaryAddExpr import com.alecstrong.sql.psi.core.psi.SqlBinaryExpr import com.alecstrong.sql.psi.core.psi.SqlBinaryLikeExpr import com.alecstrong.sql.psi.core.psi.SqlBinaryMultExpr import com.alecstrong.sql.psi.core.psi.SqlBinaryPipeExpr import com.alecstrong.sql.psi.core.psi.SqlBindExpr import com.alecstrong.sql.psi.core.psi.SqlCaseExpr import com.alecstrong.sql.psi.core.psi.SqlCastExpr import com.alecstrong.sql.psi.core.psi.SqlCollateExpr import com.alecstrong.sql.psi.core.psi.SqlColumnExpr import com.alecstrong.sql.psi.core.psi.SqlExistsExpr import com.alecstrong.sql.psi.core.psi.SqlExpr import com.alecstrong.sql.psi.core.psi.SqlFunctionExpr import com.alecstrong.sql.psi.core.psi.SqlInExpr import com.alecstrong.sql.psi.core.psi.SqlIsExpr import com.alecstrong.sql.psi.core.psi.SqlLiteralExpr import com.alecstrong.sql.psi.core.psi.SqlNullExpr import com.alecstrong.sql.psi.core.psi.SqlOtherExpr import com.alecstrong.sql.psi.core.psi.SqlParenExpr import com.alecstrong.sql.psi.core.psi.SqlRaiseExpr import com.alecstrong.sql.psi.core.psi.SqlSetterExpression import com.alecstrong.sql.psi.core.psi.SqlStmt import com.alecstrong.sql.psi.core.psi.SqlTypeName import com.alecstrong.sql.psi.core.psi.SqlTypes import com.alecstrong.sql.psi.core.psi.SqlUnaryExpr import com.intellij.psi.PsiElement import com.intellij.psi.tree.TokenSet internal val SqlExpr.name: String get() = when (this) { is SqlCastExpr -> expr.name is SqlParenExpr -> expr?.name ?: "value" is SqlFunctionExpr -> functionName.text is SqlColumnExpr -> allocateName(columnName) else -> "expr" } internal object AnsiSqlTypeResolver : TypeResolver { override fun resolvedType(expr: SqlExpr): IntermediateType { return expr.ansiType() } override fun functionType(functionExpr: SqlFunctionExpr): IntermediateType? { return functionExpr.typeReturned() } override fun definitionType(typeName: SqlTypeName) = throw UnsupportedOperationException("ANSI SQL is not supported for being used as a dialect.") override fun argumentType( parent: PsiElement, argument: SqlExpr, ): IntermediateType { return when (parent) { is SqlExpr -> parent.argumentType(argument) is SqlSetterExpression -> parent.argumentType() else -> throw IllegalStateException("Cannot infer argument type for $parent") } } private fun SqlFunctionExpr.typeReturned() = when (functionName.text.lowercase()) { "round" -> { // Single arg round function returns an int. Otherwise real. if (exprList.size == 1) { IntermediateType(INTEGER).nullableIf(exprList[0].type().javaType.isNullable) } else { IntermediateType(REAL).nullableIf(exprList.any { it.type().javaType.isNullable }) } } /** * sum's output is always nullable because it returns NULL for an input that's empty or only contains NULLs. * * https://www.sqlite.org/lang_aggfunc.html#sumunc * >>> The result of sum() is an integer value if all non-NULL inputs are integers. If any input to sum() is neither * >>> an integer or a NULL then sum() returns a floating point value which might be an approximation to the true sum. * */ "sum" -> { val type = exprList[0].type() if (type.dialectType == INTEGER && !type.javaType.isNullable) { type.asNullable() } else { IntermediateType(REAL).asNullable() } } "lower", "ltrim", "replace", "rtrim", "substr", "trim", "upper", "group_concat" -> { IntermediateType(TEXT).nullableIf(exprList[0].type().javaType.isNullable) } "date", "time", "char", "hex", "quote", "soundex", "typeof" -> { IntermediateType(TEXT) } "random", "count" -> { IntermediateType(INTEGER) } "instr", "length" -> { IntermediateType(INTEGER).nullableIf(exprList.any { it.type().javaType.isNullable }) } "avg" -> IntermediateType(REAL).asNullable() "abs" -> encapsulatingType(exprList, INTEGER, REAL) "iif" -> exprList[1].type() "coalesce", "ifnull" -> encapsulatingType(exprList, INTEGER, REAL, TEXT, BLOB) "nullif" -> exprList[0].type().asNullable() "max" -> encapsulatingType(exprList, INTEGER, REAL, TEXT, BLOB).asNullable() "min" -> encapsulatingType(exprList, BLOB, TEXT, INTEGER, REAL).asNullable() else -> null } override fun simplifyType(intermediateType: IntermediateType): IntermediateType { with(intermediateType) { if (javaType != dialectType.javaType && javaType.copy(nullable = false, annotations = emptyList()) == dialectType.javaType ) { // We don't need an adapter for only annotations. return copy(simplified = true) } } return intermediateType } override fun queryWithResults(sqlStmt: SqlStmt): QueryWithResults? { sqlStmt.compoundSelectStmt?.let { return SelectQueryable(it) } sqlStmt.pragmaStmt?.let { if (it.pragmaValue == null) return PragmaWithResults(it) } return null } } internal fun TypeResolver.argumentType(bindArg: SqlBindExpr): IntermediateType { return bindArg.inferredType().copy(bindArg = bindArg) } private fun SqlExpr.type(): IntermediateType { return typeResolver.resolvedType(this) } /** * If javaType is true, this will return a possible more descriptive type for column expressions. * * Order of operations: * expr ::= ( raise_expr * | case_expr * | exists_expr * | in_expr * | between_expr * | is_expr * | null_expr * | like_expr * | collate_expr * | cast_expr * | paren_expr * | function_expr * | binary_expr * | unary_expr * | bind_expr * | literal_expr * | column_expr ) */ private fun SqlExpr.ansiType(): IntermediateType = when (this) { is SqlRaiseExpr -> IntermediateType(NULL) is SqlCaseExpr -> childOfType(SqlTypes.THEN)!!.nextSiblingOfType<SqlExpr>().type() is SqlExistsExpr -> { val isExists = childOfType(SqlTypes.EXISTS) != null if (isExists) { IntermediateType(PrimitiveType.BOOLEAN) } else { compoundSelectStmt.queryExposed().single().columns.single().element.type() } } is SqlInExpr -> IntermediateType(PrimitiveType.BOOLEAN) is SqlBetweenExpr -> IntermediateType(PrimitiveType.BOOLEAN) is SqlIsExpr -> IntermediateType(PrimitiveType.BOOLEAN) is SqlNullExpr -> IntermediateType(PrimitiveType.BOOLEAN) is SqlBinaryLikeExpr -> IntermediateType(PrimitiveType.BOOLEAN) is SqlCollateExpr -> expr.type() is SqlCastExpr -> typeName.type().nullableIf(expr.type().javaType.isNullable) is SqlParenExpr -> expr?.type() ?: IntermediateType(NULL) is SqlFunctionExpr -> typeResolver.functionType(this) ?: IntermediateType(NULL) is SqlBinaryExpr -> { if (childOfType( TokenSet.create( SqlTypes.EQ, SqlTypes.EQ2, SqlTypes.NEQ, SqlTypes.NEQ2, SqlTypes.AND, SqlTypes.OR, SqlTypes.GT, SqlTypes.GTE, SqlTypes.LT, SqlTypes.LTE, ), ) != null ) { IntermediateType(PrimitiveType.BOOLEAN) } else { typeResolver.encapsulatingType( exprList = getExprList(), nullableIfAny = ( this is SqlBinaryAddExpr || this is SqlBinaryMultExpr || this is SqlBinaryPipeExpr ), INTEGER, REAL, TEXT, BLOB, ) } } is SqlUnaryExpr -> expr.type() is SqlBindExpr -> IntermediateType(ARGUMENT) is SqlLiteralExpr -> when { (literalValue.stringLiteral != null) -> IntermediateType(TEXT) (literalValue.blobLiteral != null) -> IntermediateType(BLOB) (literalValue.numericLiteral != null) -> { if (literalValue.text.contains('.')) { IntermediateType(REAL) } else { IntermediateType(INTEGER) } } ( literalValue.childOfType( TokenSet.create( SqlTypes.CURRENT_TIMESTAMP, SqlTypes.CURRENT_TIME, SqlTypes.CURRENT_DATE, ), ) != null ) -> IntermediateType(TEXT) (literalValue.childOfType(SqlTypes.NULL) != null) -> IntermediateType(NULL) else -> IntermediateType(BLOB).asNullable() } is SqlColumnExpr -> columnName.type() is SqlOtherExpr -> { extensionExpr.type() } else -> throw IllegalStateException("Unknown expression type $this") }
apache-2.0
425e6e23509cc2845ce809a434229f76
34.753571
122
0.701229
3.991627
false
false
false
false
donald-w/Anki-Android
AnkiDroid/src/main/java/com/ichi2/themes/StyledProgressDialog.kt
1
3553
/**************************************************************************************** * Copyright (c) 2011 Norbert Nagold <[email protected]> * * * * based on custom Dialog windows by antoine vianey * * * * This program is free software; you can redistribute it and/or modify it under * * the terms of the GNU General Public License as published by the Free Software * * Foundation; either version 3 of the License, or (at your option) any later * * version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along with * * this program. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************************/ package com.ichi2.themes import android.app.Dialog import android.content.Context import android.content.DialogInterface import android.view.WindowManager.BadTokenException import com.afollestad.materialdialogs.MaterialDialog import com.ichi2.anki.AnkiActivity import com.ichi2.utils.cancelListenerNullable import com.ichi2.utils.contentNullable import com.ichi2.utils.titleNullable import timber.log.Timber class StyledProgressDialog(context: Context?) : Dialog(context!!) { override fun show() { try { setCanceledOnTouchOutside(false) super.show() } catch (e: BadTokenException) { Timber.e(e, "Could not show dialog") } } @Suppress("unused_parameter") fun setMax(max: Int) { // TODO } @Suppress("unused_parameter") fun setProgress(progress: Int) { // TODO } @Suppress("unused_parameter") fun setProgressStyle(style: Int) { // TODO } companion object { @JvmStatic @JvmOverloads fun show( context: Context, title: CharSequence?, message: CharSequence?, cancelable: Boolean = false, cancelListener: DialogInterface.OnCancelListener? = null ): MaterialDialog { var t = title if ("" == t) { t = null Timber.d("Invalid title was provided. Using null") } return MaterialDialog.Builder(context) .titleNullable(t) .contentNullable(message) .progress(true, 0) .cancelable(cancelable) .cancelListenerNullable(cancelListener) .show() } @Suppress("unused") @JvmStatic private fun animationEnabled(context: Context): Boolean { return if (context is AnkiActivity) { context.animationEnabled() } else { true } } } }
gpl-3.0
02fe9dead30bcfa7a726ecf723b2f7a8
38.043956
90
0.491416
5.612954
false
false
false
false
wikimedia/apps-android-wikipedia
app/src/main/java/org/wikipedia/notifications/NotificationViewModel.kt
1
8034
package org.wikipedia.notifications import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import kotlinx.coroutines.CoroutineExceptionHandler import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.collect import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import org.wikipedia.Constants import org.wikipedia.WikipediaApp import org.wikipedia.analytics.eventplatform.NotificationInteractionEvent import org.wikipedia.database.AppDatabase import org.wikipedia.dataclient.WikiSite import org.wikipedia.notifications.db.Notification import org.wikipedia.settings.Prefs import org.wikipedia.util.StringUtil import java.util.* class NotificationViewModel : ViewModel() { private val notificationRepository = NotificationRepository(AppDatabase.instance.notificationDao()) private val handler = CoroutineExceptionHandler { _, throwable -> _uiState.value = UiState.Error(throwable) } private val notificationList = mutableListOf<Notification>() private var dbNameMap = mapOf<String, WikiSite>() private var selectedFilterTab: Int = 0 private var currentContinueStr: String? = null var currentSearchQuery: String? = null private set var mentionsUnreadCount: Int = 0 var allUnreadCount: Int = 0 private val _uiState = MutableStateFlow(UiState()) val uiState = _uiState init { viewModelScope.launch(handler) { withContext(Dispatchers.IO) { dbNameMap = notificationRepository.fetchUnreadWikiDbNames() } } } private suspend fun collectionNotifications() = notificationRepository.getAllNotifications() .collect { list -> _uiState.value = UiState.Success(processList(list), !currentContinueStr.isNullOrEmpty()) } private fun processList(list: List<Notification>): List<NotificationListItemContainer> { // Reduce duplicate notifications if (currentContinueStr.isNullOrEmpty()) { notificationList.clear() } for (n in list) { if (notificationList.none { it.id == n.id }) { notificationList.add(n) } } // Sort them by descending date... notificationList.sortByDescending { it.date() } // Filtered the tab selection val tabSelectedList = notificationList .filter { if (Prefs.hideReadNotificationsEnabled) it.isUnread else true } val excludedTypeCodes = Prefs.notificationExcludedTypeCodes val excludedWikiCodes = Prefs.notificationExcludedWikiCodes val includedWikiCodes = NotificationFilterActivity.allWikisList().minus(excludedWikiCodes).map { it.split("-")[0] } val checkExcludedWikiCodes = NotificationFilterActivity.allWikisList().size != includedWikiCodes.size val notificationContainerList = mutableListOf<NotificationListItemContainer>() allUnreadCount = 0 mentionsUnreadCount = 0 // Save into display list for (n in tabSelectedList) { val linkText = n.contents?.links?.secondary?.firstOrNull()?.label val searchQuery = currentSearchQuery if (!searchQuery.isNullOrEmpty() && !(n.title?.full?.contains(searchQuery, true) == true || n.contents?.header?.contains(searchQuery, true) == true || n.contents?.body?.contains(searchQuery, true) == true || (linkText?.contains(searchQuery, true) == true))) { continue } if (excludedTypeCodes.find { n.category.startsWith(it) } != null) { continue } if (checkExcludedWikiCodes) { val wikiCode = StringUtil.dbNameToLangCode(n.wiki) if (!includedWikiCodes.contains(wikiCode)) { continue } } val isMention = NotificationCategory.isMentionsGroup(n.category) if (n.isUnread) { allUnreadCount++ if (isMention) { mentionsUnreadCount++ } } if (selectedFilterTab == 1 && !isMention) { continue } notificationContainerList.add(NotificationListItemContainer(n)) } return notificationContainerList } private fun delimitedWikiList(): String { return dbNameMap.keys.union(NotificationFilterActivity.allWikisList().map { val defaultLangCode = WikipediaApp.instance.languageState.getDefaultLanguageCode(it) ?: it "${defaultLangCode.replace("-", "_")}wiki" }).joinToString("|") } fun excludedFiltersCount(): Int { val excludedWikiCodes = Prefs.notificationExcludedWikiCodes val excludedTypeCodes = Prefs.notificationExcludedTypeCodes return NotificationFilterActivity.allWikisList().count { excludedWikiCodes.contains(it) } + NotificationFilterActivity.allTypesIdList().count { excludedTypeCodes.contains(it) } } fun fetchAndSave() { viewModelScope.launch(handler) { if (WikipediaApp.instance.isOnline) { withContext(Dispatchers.IO) { currentContinueStr = notificationRepository.fetchAndSave(delimitedWikiList(), "read|!read", currentContinueStr) } } collectionNotifications() } } fun updateSearchQuery(query: String?) { currentSearchQuery = query viewModelScope.launch(handler) { collectionNotifications() } } fun updateTabSelection(position: Int) { selectedFilterTab = position viewModelScope.launch(handler) { collectionNotifications() } } fun markItemsAsRead(items: List<NotificationListItemContainer>, markUnread: Boolean) { val notificationsPerWiki = mutableMapOf<WikiSite, MutableList<Notification>>() val selectionKey = if (items.size > 1) Random().nextLong() else null for (item in items) { val notification = item.notification!! val wiki = dbNameMap.getOrElse(notification.wiki) { when (notification.wiki) { Constants.COMMONS_DB_NAME -> Constants.commonsWikiSite Constants.WIKIDATA_DB_NAME -> Constants.wikidataWikiSite else -> { val langCode = StringUtil.dbNameToLangCode(notification.wiki) WikiSite.forLanguageCode(WikipediaApp.instance.languageState.getDefaultLanguageCode(langCode) ?: langCode) } } } notificationsPerWiki.getOrPut(wiki) { ArrayList() }.add(notification) if (!markUnread) { NotificationInteractionEvent.logMarkRead(notification, selectionKey) } } for ((wiki, notifications) in notificationsPerWiki) { NotificationPollBroadcastReceiver.markRead(wiki, notifications, markUnread) } // Mark items in read state and save into database notificationList .filter { n -> items.map { container -> container.notification?.id } .firstOrNull { it == n.id } != null } .map { it.read = if (markUnread) null else Date().toString() viewModelScope.launch(handler) { withContext(Dispatchers.IO) { notificationRepository.updateNotification(it) } collectionNotifications() } } } open class UiState { data class Success(val notifications: List<NotificationListItemContainer>, val fromContinuation: Boolean) : UiState() data class Error(val throwable: Throwable) : UiState() } }
apache-2.0
460166e385ddae40f9ce34358384e253
38.772277
131
0.62945
5.373913
false
false
false
false
wikimedia/apps-android-wikipedia
app/src/main/java/org/wikipedia/views/ViewUtil.kt
1
5021
package org.wikipedia.views import android.app.Activity import android.content.Context import android.content.ContextWrapper import android.graphics.Rect import android.graphics.drawable.ColorDrawable import android.graphics.drawable.Drawable import android.net.Uri import android.text.TextUtils import android.view.* import android.widget.ImageView import android.widget.TextView import androidx.core.view.isVisible import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.bumptech.glide.load.MultiTransformation import com.bumptech.glide.load.resource.bitmap.CenterCrop import com.bumptech.glide.load.resource.bitmap.DownsampleStrategy import com.bumptech.glide.load.resource.bitmap.RoundedCorners import com.bumptech.glide.request.RequestListener import org.wikipedia.Constants import org.wikipedia.R import org.wikipedia.databinding.ViewActionModeCloseButtonBinding import org.wikipedia.settings.Prefs import org.wikipedia.util.DimenUtil.roundedDpToPx import org.wikipedia.util.ResourceUtil.getThemedColor import org.wikipedia.util.WhiteBackgroundTransformation object ViewUtil { private val CENTER_CROP_ROUNDED_CORNERS = MultiTransformation(CenterCrop(), WhiteBackgroundTransformation(), RoundedCorners(roundedDpToPx(2f))) val ROUNDED_CORNERS = RoundedCorners(roundedDpToPx(15f)) val CENTER_CROP_LARGE_ROUNDED_CORNERS = MultiTransformation(CenterCrop(), WhiteBackgroundTransformation(), ROUNDED_CORNERS) fun loadImageWithRoundedCorners(view: ImageView, url: String?, largeRoundedSize: Boolean = false) { loadImage(view, url, true, largeRoundedSize) } fun loadImage(view: ImageView, url: String?, roundedCorners: Boolean = false, largeRoundedSize: Boolean = false, force: Boolean = false, listener: RequestListener<Drawable?>? = null) { val placeholder = getPlaceholderDrawable(view.context) var builder = Glide.with(view) .load(if ((Prefs.isImageDownloadEnabled || force) && !TextUtils.isEmpty(url)) Uri.parse(url) else null) .placeholder(placeholder) .downsample(DownsampleStrategy.CENTER_INSIDE) .error(placeholder) builder = if (roundedCorners) { builder.transform(if (largeRoundedSize) CENTER_CROP_LARGE_ROUNDED_CORNERS else CENTER_CROP_ROUNDED_CORNERS) } else { builder.transform(WhiteBackgroundTransformation()) } if (listener != null) { builder = builder.listener(listener) } builder.into(view) } fun getPlaceholderDrawable(context: Context): Drawable { return ColorDrawable(getThemedColor(context, R.attr.material_theme_border_color)) } fun setCloseButtonInActionMode(context: Context, actionMode: ActionMode) { val binding = ViewActionModeCloseButtonBinding.inflate(LayoutInflater.from(context)) actionMode.customView = binding.root binding.closeButton.setOnClickListener { actionMode.finish() } } fun formatLangButton(langButton: TextView, langCode: String, langButtonTextSizeSmaller: Int, langButtonTextSizeLarger: Int) { val langCodeStandardLength = 3 if (langCode.length > langCodeStandardLength) { langButton.textSize = langButtonTextSizeSmaller.toFloat() return } langButton.textSize = langButtonTextSizeLarger.toFloat() } fun adjustImagePlaceholderHeight(containerWidth: Float, thumbWidth: Float, thumbHeight: Float): Int { return (Constants.PREFERRED_GALLERY_IMAGE_SIZE.toFloat() / thumbWidth * thumbHeight * containerWidth / Constants.PREFERRED_GALLERY_IMAGE_SIZE.toFloat()).toInt() } tailrec fun Context.getActivity(): Activity? = this as? Activity ?: (this as? ContextWrapper)?.baseContext?.getActivity() fun findClickableViewAtPoint(parentView: View, x: Int, y: Int): View? { val location = IntArray(2) parentView.getLocationOnScreen(location) val rect = Rect(location[0], location[1], location[0] + parentView.width, location[1] + parentView.height) if (rect.contains(x, y) && parentView.isVisible) { if (parentView is ViewGroup) { for (i in parentView.childCount - 1 downTo 0) { val v = parentView.getChildAt(i) findClickableViewAtPoint(v, x, y)?.let { return it } } } if (parentView.isEnabled && parentView.isClickable) { return parentView } } return null } fun jumpToPositionWithoutAnimation(recyclerView: RecyclerView, position: Int) { recyclerView.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener { override fun onGlobalLayout() { recyclerView.scrollToPosition(position) recyclerView.viewTreeObserver.removeOnGlobalLayoutListener(this) } }) } }
apache-2.0
1c44d8751f61bf8acfdff6edb8746ff0
44.234234
168
0.709819
4.855899
false
false
false
false
stripe/stripe-android
stripecardscan/src/main/java/com/stripe/android/stripecardscan/framework/util/ArrayExtensions.kt
1
3728
package com.stripe.android.stripecardscan.framework.util import androidx.annotation.CheckResult import kotlin.math.max import kotlin.math.min /** * Update an array in place with a modifier function. */ internal fun <T> Array<T>.updateEach(operation: (original: T) -> T) { for (i in this.indices) { this[i] = operation(this[i]) } } /** * Update a [FloatArray] in place with a modifier function. */ internal fun FloatArray.updateEach(operation: (original: Float) -> Float) { for (i in this.indices) { this[i] = operation(this[i]) } } /** * Filter an array to only those values specified in an index array. */ @CheckResult internal inline fun <reified T> Array<T>.filterByIndexes(indexesToKeep: IntArray) = Array(indexesToKeep.size) { this[indexesToKeep[it]] } /** * Filter an array to only those values specified in an index array. */ @CheckResult internal fun FloatArray.filterByIndexes(indexesToKeep: IntArray) = FloatArray(indexesToKeep.size) { this[indexesToKeep[it]] } /** * Flatten an array of arrays into a single array of sequential values. */ @CheckResult internal fun Array<FloatArray>.flatten() = if (this.isNotEmpty()) { this.reshape(this.size * this[0].size)[0] } else { floatArrayOf() } /** * Transpose an array of float arrays. */ @CheckResult internal fun Array<FloatArray>.transpose() = if (this.isNotEmpty()) { val oldRows = this.size val oldColumns = this[0].size Array(oldColumns) { newRow -> FloatArray(oldRows) { newColumn -> this[newColumn][newRow] } } } else { this } /** * Reshape a two-dimensional array. Assume all rows of the original array are the same length, and * that the array is evenly divisible by the new columns. */ @CheckResult internal fun Array<FloatArray>.reshape(newColumns: Int): Array<FloatArray> { val oldRows = this.size val oldColumns = if (this.isNotEmpty()) this[0].size else 0 val linearSize = oldRows * oldColumns val newRows = linearSize / newColumns + if (linearSize % newColumns != 0) 1 else 0 var oldRow = 0 var oldColumn = 0 return Array(newRows) { FloatArray(newColumns) { val value = this[oldRow][oldColumn] if (++oldColumn == oldColumns) { oldColumn = 0 oldRow++ } value } } } /** * Clamp the value between min and max */ @CheckResult internal fun clamp(value: Float, minimum: Float, maximum: Float): Float = max(minimum, min(maximum, value)) /** * Return a list of indexes that pass the filter. */ @CheckResult internal fun FloatArray.filteredIndexes(predicate: (Float) -> Boolean): IntArray { val filteredIndexes = ArrayList<Int>() for (index in this.indices) { if (predicate(this[index])) { filteredIndexes.add(index) } } return filteredIndexes.toIntArray() } /** * Divide a [ByteArray] into an array of byte arrays of a given size. If the original array is not * evenly divisible by the [chunkSize], the last ByteArray may be smaller than the chunk size. */ @CheckResult internal fun ByteArray.chunk(chunkSize: Int): Array<ByteArray> = Array(this.size / chunkSize + if (this.size % chunkSize == 0) 0 else 1) { copyOfRange(it * chunkSize, min((it + 1) * chunkSize, this.size)) } /** * Find the index of the maximum value in the array. */ @CheckResult internal fun FloatArray.indexOfMax(): Int? { if (isEmpty()) { return null } var maxIndex = 0 var maxValue = this[maxIndex] for (index in this.indices) { if (this[index] > maxValue) { maxIndex = index maxValue = this[index] } } return maxIndex }
mit
4330fe113892c1bf3961c49348692bed
26.411765
98
0.656116
3.815763
false
false
false
false
pyamsoft/padlock
padlock/src/main/java/com/pyamsoft/padlock/list/LockListItemViewImpl.kt
1
2842
/* * Copyright 2019 Peter Kenji Yamanaka * * 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.pyamsoft.padlock.list import android.view.View import androidx.core.view.isInvisible import androidx.core.view.isVisible import com.pyamsoft.padlock.R import com.pyamsoft.padlock.databinding.AdapterItemLocklistBinding import com.pyamsoft.padlock.loader.AppIconLoader import com.pyamsoft.padlock.model.list.AppEntry import com.pyamsoft.pydroid.loader.ImageLoader import com.pyamsoft.pydroid.loader.Loaded import javax.inject.Inject internal class LockListItemViewImpl @Inject internal constructor( itemView: View, private val imageLoader: ImageLoader, private val appIconLoader: AppIconLoader ) : LockListItemView { private val binding = AdapterItemLocklistBinding.bind(itemView) private var whitelistLoaded: Loaded? = null private var blacklistLoaded: Loaded? = null private var iconLoaded: Loaded? = null override fun bind(model: AppEntry) { binding.apply { lockListTitle.text = model.name lockListWhite.isInvisible = model.whitelisted.isEmpty() lockListLocked.isInvisible = model.hardLocked.isEmpty() // Must null out the old listener to avoid loops lockListToggle.setOnCheckedChangeListener(null) lockListToggle.isChecked = model.locked if (lockListWhite.isVisible) { whitelistLoaded?.dispose() whitelistLoaded = imageLoader.load(R.drawable.ic_whitelisted) .into(lockListWhite) } if (lockListLocked.isVisible) { blacklistLoaded?.dispose() blacklistLoaded = imageLoader.load(R.drawable.ic_hardlocked) .into(lockListLocked) } if (lockListIcon.isVisible) { iconLoaded?.dispose() iconLoaded = appIconLoader.loadAppIcon(model.packageName, model.icon) .into(lockListIcon) } } } override fun onSwitchChanged(onChange: (isChecked: Boolean) -> Unit) { binding.lockListToggle.setOnCheckedChangeListener { buttonView, isChecked -> buttonView.isChecked = !isChecked onChange(isChecked) } } override fun unbind() { binding.apply { lockListToggle.setOnCheckedChangeListener(null) whitelistLoaded?.dispose() blacklistLoaded?.dispose() iconLoaded?.dispose() unbind() } } }
apache-2.0
7cda93e4f032fdb2e199e5b9f8e552d7
29.891304
80
0.726953
4.365591
false
false
false
false
AndroidX/androidx
core/core-ktx/src/main/java/androidx/core/util/Runnable.kt
3
2411
/* * 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. */ package androidx.core.util import java.util.concurrent.atomic.AtomicBoolean import kotlin.coroutines.Continuation import kotlin.coroutines.resume /** * Returns a [Runnable] that will resume this [Continuation] when an operation completes and * the returned [Runnable]'s [Runnable.run] method is called. * * Useful for writing `suspend` bindings to async Jetpack library methods that accept [Runnable] * as a completion callback for a one-time operation: * * ``` * public suspend fun FancinessManager.setFanciness( * fanciness: Float * ): Unit = suspendCancellableCoroutine<Unit> { continuation -> * * // Any Android API that supports cancellation should be configured to propagate * // coroutine cancellation as follows: * val canceller = CancellationSignal() * continuation.invokeOnCancellation { canceller.cancel() } * * // Invoke the FancinessManager#setFanciness method as follows: * queryAsync( * fanciness, * canceller, * // Use a direct executor to avoid extra dispatch. Resuming the continuation will * // handle getting to the right thread or pool via the ContinuationInterceptor. * Runnable::run, * continuation.asRunnable() * ) * } * ``` */ public fun Continuation<Unit>.asRunnable(): Runnable = ContinuationRunnable(this) private class ContinuationRunnable( private val continuation: Continuation<Unit> ) : Runnable, AtomicBoolean(false) { override fun run() { // Do not attempt to resume more than once, even if the caller of the returned // Runnable is buggy and tries anyway. if (compareAndSet(false, true)) { continuation.resume(Unit) } } override fun toString() = "ContinuationRunnable(ran = ${get()})" }
apache-2.0
f2deb9b142ab6a272a4d1b56ec4cb467
35.530303
96
0.703857
4.344144
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/ide/annotator/fixes/AddAttrParenthesesFix.kt
2
1288
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.annotator.fixes import com.intellij.codeInspection.LocalQuickFixAndIntentionActionOnPsiElement import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import org.rust.lang.core.psi.RsMetaItem import org.rust.lang.core.psi.RsPsiFactory class AddAttrParenthesesFix(element: RsMetaItem, private val attrName: String) : LocalQuickFixAndIntentionActionOnPsiElement(element) { override fun getFamilyName(): String = "Add parentheses" override fun getText(): String = "Add parentheses to `$attrName`" override fun invoke(project: Project, file: PsiFile, editor: Editor?, startElement: PsiElement, endElement: PsiElement) { if (startElement !is RsMetaItem) return val newItem = RsPsiFactory(project).createOuterAttr("$attrName()").metaItem val replaced = startElement.replace(newItem) as? RsMetaItem ?: return // Place caret between parentheses, so the user can immediately start typing val offset = replaced.metaItemArgs?.lparen?.textOffset ?: return editor?.caretModel?.moveToOffset(offset + 1) } }
mit
bf2bfffbe93d5f7583b72426b40ecc39
41.933333
135
0.76087
4.535211
false
false
false
false
jk1/youtrack-idea-plugin
src/main/kotlin/com/github/jk1/ytplugin/commands/lang/CommandSuggestionInsertHandler.kt
1
2077
package com.github.jk1.ytplugin.commands.lang import com.github.jk1.ytplugin.commands.model.CommandSuggestion import com.intellij.codeInsight.completion.InsertHandler import com.intellij.codeInsight.completion.InsertionContext import com.intellij.codeInsight.lookup.LookupElement /** * Inserts additional braces around values that contains spaces, colon after attribute names * and '#' before short-cut attributes if any */ object CommandSuggestionInsertHandler: InsertHandler<LookupElement> { override fun handleInsert(context: InsertionContext, item: LookupElement) { val completionItem = item.`object` as CommandSuggestion val document = context.document val editor = context.editor context.commitDocument() context.setAddCompletionChar(false) val prefix = completionItem.prefix val suffix = completionItem.suffix var text = document.text var offset = context.startOffset // skip possible spaces after '{', e.g. "{ My Project <caret>" if (prefix.endsWith("{")) { while (offset > prefix.length && Character.isWhitespace(text[offset - 1])) { offset-- } } if (!prefix.isEmpty() && !hasPrefixAt(document.text, offset - prefix.length, prefix)) { document.insertString(offset, prefix) } offset = context.tailOffset text = document.text if (suffix.startsWith("} ")) { while (offset < text.length - suffix.length && Character.isWhitespace(text[offset])) { offset++ } } if (!suffix.isEmpty() && !hasPrefixAt(text, offset, suffix)) { document.insertString(offset, suffix) } editor.caretModel.moveToOffset(context.tailOffset) } private fun hasPrefixAt(text: String, offset: Int, prefix: String): Boolean { if (text.isEmpty() || offset < 0 || offset >= text.length) { return false } return text.regionMatches(offset, prefix, 0, prefix.length, true) } }
apache-2.0
eedc34eadd1e4f126df8108ccf8d6049
37.481481
98
0.64805
4.709751
false
false
false
false
SimpleMobileTools/Simple-Commons
commons/src/main/kotlin/com/simplemobiletools/commons/dialogs/PurchaseThankYouDialog.kt
1
1262
package com.simplemobiletools.commons.dialogs import android.app.Activity import android.text.Html import android.text.method.LinkMovementMethod import com.simplemobiletools.commons.R import com.simplemobiletools.commons.extensions.* import kotlinx.android.synthetic.main.dialog_purchase_thank_you.view.* class PurchaseThankYouDialog(val activity: Activity) { init { val view = activity.layoutInflater.inflate(R.layout.dialog_purchase_thank_you, null).apply { var text = activity.getString(R.string.purchase_thank_you) if (activity.baseConfig.appId.removeSuffix(".debug").endsWith(".pro")) { text += "<br><br>${activity.getString(R.string.shared_theme_note)}" } purchase_thank_you.text = Html.fromHtml(text) purchase_thank_you.movementMethod = LinkMovementMethod.getInstance() purchase_thank_you.removeUnderlines() } activity.getAlertDialogBuilder() .setPositiveButton(R.string.purchase) { dialog, which -> activity.launchPurchaseThankYouIntent() } .setNegativeButton(R.string.cancel, null) .apply { activity.setupDialogStuff(view, this, cancelOnTouchOutside = false) } } }
gpl-3.0
4b674f1ccbbc40f7cfac531813d3aa1c
41.066667
110
0.68542
4.491103
false
false
false
false
androidx/androidx
room/room-runtime/src/test/java/androidx/room/InvalidationTrackerTest.kt
3
19132
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.room import android.database.Cursor import android.database.sqlite.SQLiteException import androidx.arch.core.executor.ArchTaskExecutor import androidx.arch.core.executor.JunitTaskExecutorRule import androidx.sqlite.db.SimpleSQLiteQuery import androidx.sqlite.db.SupportSQLiteDatabase import androidx.sqlite.db.SupportSQLiteOpenHelper import androidx.sqlite.db.SupportSQLiteStatement import com.google.common.truth.Truth.assertThat import com.google.common.truth.Truth.assertWithMessage import java.lang.ref.ReferenceQueue import java.lang.ref.WeakReference import java.util.Locale import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicInteger import java.util.concurrent.locks.ReentrantLock import kotlin.test.assertFailsWith import kotlin.test.fail import org.junit.After import org.junit.Before import org.junit.Ignore import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 import org.mockito.ArgumentMatchers.anyInt import org.mockito.kotlin.KArgumentCaptor import org.mockito.kotlin.any import org.mockito.kotlin.argThat import org.mockito.kotlin.argumentCaptor import org.mockito.kotlin.doReturn import org.mockito.kotlin.doThrow import org.mockito.kotlin.eq import org.mockito.kotlin.isNull import org.mockito.kotlin.mock import org.mockito.kotlin.reset import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.whenever import org.mockito.stubbing.Answer @RunWith(JUnit4::class) class InvalidationTrackerTest { private lateinit var mTracker: InvalidationTracker private val mRoomDatabase: RoomDatabase = mock() private val mSqliteDb: SupportSQLiteDatabase = mock() private val mOpenHelper: SupportSQLiteOpenHelper = mock() @get:Rule var mTaskExecutorRule = JunitTaskExecutorRule(1, true) @Before fun setup() { val statement: SupportSQLiteStatement = mock() doReturn(statement).whenever(mSqliteDb) .compileStatement(eq(InvalidationTracker.RESET_UPDATED_TABLES_SQL)) doReturn(mSqliteDb).whenever(mOpenHelper).writableDatabase doReturn(true).whenever(mRoomDatabase).isOpen doReturn(ArchTaskExecutor.getIOThreadExecutor()).whenever(mRoomDatabase).queryExecutor val closeLock = ReentrantLock() doReturn(closeLock).whenever(mRoomDatabase).getCloseLock() doReturn(mOpenHelper).whenever(mRoomDatabase).openHelper val shadowTables = HashMap<String, String>() shadowTables["C"] = "C_content" shadowTables["d"] = "a" val viewTables = HashMap<String, Set<String>>() val tableSet = HashSet<String>() tableSet.add("a") viewTables["e"] = tableSet mTracker = InvalidationTracker( mRoomDatabase, shadowTables, viewTables, "a", "B", "i", "C", "d" ) mTracker.internalInit(mSqliteDb) reset(mSqliteDb) } @Before fun setLocale() { Locale.setDefault(Locale.forLanguageTag("tr-TR")) } @After fun unsetLocale() { Locale.setDefault(Locale.US) } @Test fun tableIds() { assertThat(mTracker.tableIdLookup.size).isEqualTo(5) assertThat(mTracker.tableIdLookup["a"]).isEqualTo(0) assertThat(mTracker.tableIdLookup["b"]).isEqualTo(1) assertThat(mTracker.tableIdLookup["i"]).isEqualTo(2) assertThat(mTracker.tableIdLookup["c"]).isEqualTo(3) // fts assertThat(mTracker.tableIdLookup["d"]).isEqualTo(0) // external content fts } @Test fun tableNames() { assertThat(mTracker.tablesNames.size).isEqualTo(5) assertThat(mTracker.tablesNames[0]).isEqualTo("a") assertThat(mTracker.tablesNames[1]).isEqualTo("b") assertThat(mTracker.tablesNames[2]).isEqualTo("i") assertThat(mTracker.tablesNames[3]).isEqualTo("c_content") // fts assertThat(mTracker.tablesNames[4]).isEqualTo("a") // external content fts } @Test @org.junit.Ignore // TODO(b/233855234) - disabled until test is moved to Kotlin fun testWeak() { val data = AtomicInteger(0) var observer: InvalidationTracker.Observer? = object : InvalidationTracker.Observer("a") { override fun onInvalidated(tables: Set<String>) { data.incrementAndGet() } } val queue = ReferenceQueue<Any?>() WeakReference(observer, queue) mTracker.addWeakObserver(observer!!) setInvalidatedTables(0) refreshSync() assertThat(data.get()).isEqualTo(1) @Suppress("UNUSED_VALUE") // On purpose, to dereference the observer and GC it observer = null forceGc(queue) setInvalidatedTables(0) refreshSync() assertThat(data.get()).isEqualTo(1) } @Test fun addRemoveObserver() { val observer: InvalidationTracker.Observer = LatchObserver(1, "a") mTracker.addObserver(observer) assertThat(mTracker.observerMap.size()).isEqualTo(1) mTracker.removeObserver(LatchObserver(1, "a")) assertThat(mTracker.observerMap.size()).isEqualTo(1) mTracker.removeObserver(observer) assertThat(mTracker.observerMap.size()).isEqualTo(0) } private fun drainTasks() { mTaskExecutorRule.drainTasks(200) } @Test fun badObserver() { assertFailsWith<IllegalArgumentException>(message = "There is no table with name x") { val observer: InvalidationTracker.Observer = LatchObserver(1, "x") mTracker.addObserver(observer) } } private fun refreshSync() { mTracker.refreshVersionsAsync() drainTasks() } @Ignore // b/253058904 @Test fun refreshCheckTasks() { whenever(mRoomDatabase.query(any<SimpleSQLiteQuery>(), isNull())).thenReturn(mock<Cursor>()) mTracker.refreshVersionsAsync() mTracker.refreshVersionsAsync() verify(mTaskExecutorRule.taskExecutor).executeOnDiskIO(mTracker.refreshRunnable) drainTasks() reset(mTaskExecutorRule.taskExecutor) mTracker.refreshVersionsAsync() verify(mTaskExecutorRule.taskExecutor).executeOnDiskIO(mTracker.refreshRunnable) } @Test @Throws(Exception::class) fun observe1Table() { val observer = LatchObserver(1, "a") mTracker.addObserver(observer) setInvalidatedTables(0) refreshSync() assertThat(observer.await()).isEqualTo(true) assertThat(observer.invalidatedTables!!.size).isEqualTo(1) assertThat(observer.invalidatedTables).contains("a") setInvalidatedTables(1) observer.reset(1) refreshSync() assertThat(observer.await()).isEqualTo(false) setInvalidatedTables(0) refreshSync() assertThat(observer.await()).isEqualTo(true) assertThat(observer.invalidatedTables!!.size).isEqualTo(1) assertThat(observer.invalidatedTables).contains("a") } @Test @Throws(Exception::class) fun observe2Tables() { val observer = LatchObserver(1, "A", "B") mTracker.addObserver(observer) setInvalidatedTables(0, 1) refreshSync() assertThat(observer.await()).isEqualTo(true) assertThat(observer.invalidatedTables!!.size).isEqualTo(2) assertThat(observer.invalidatedTables).containsAtLeast("A", "B") setInvalidatedTables(1, 2) observer.reset(1) refreshSync() assertThat(observer.await()).isEqualTo(true) assertThat(observer.invalidatedTables!!.size).isEqualTo(1) assertThat(observer.invalidatedTables).contains("B") setInvalidatedTables(0, 3) observer.reset(1) refreshSync() assertThat(observer.await()).isEqualTo(true) assertThat(observer.invalidatedTables!!.size).isEqualTo(1) assertThat(observer.invalidatedTables).contains("A") observer.reset(1) refreshSync() assertThat(observer.await()).isEqualTo(false) } @Test fun locale() { val observer = LatchObserver(1, "I") mTracker.addObserver(observer) } @Test fun closedDb() { doReturn(false).whenever(mRoomDatabase).isOpen doThrow(IllegalStateException("foo")).whenever(mOpenHelper).writableDatabase mTracker.addObserver(LatchObserver(1, "a", "b")) mTracker.refreshRunnable.run() } @Test fun createTriggerOnShadowTable() { val observer = LatchObserver(1, "C") val triggers = arrayOf("UPDATE", "DELETE", "INSERT") var sqlCaptorValues: List<String> mTracker.addObserver(observer) var sqlArgCaptor: KArgumentCaptor<String> = argumentCaptor() verify(mSqliteDb, times(4)).execSQL(sqlArgCaptor.capture()) sqlCaptorValues = sqlArgCaptor.allValues assertThat(sqlCaptorValues[0]) .isEqualTo("INSERT OR IGNORE INTO room_table_modification_log VALUES(3, 0)") for (i in triggers.indices) { assertThat(sqlCaptorValues[i + 1]) .isEqualTo( "CREATE TEMP TRIGGER IF NOT EXISTS " + "`room_table_modification_trigger_c_content_" + triggers[i] + "` AFTER " + triggers[i] + " ON `c_content` BEGIN UPDATE " + "room_table_modification_log SET invalidated = 1 WHERE table_id = 3 " + "AND invalidated = 0; END" ) } reset(mSqliteDb) mTracker.removeObserver(observer) sqlArgCaptor = argumentCaptor() verify(mSqliteDb, times(3)).execSQL(sqlArgCaptor.capture()) sqlCaptorValues = sqlArgCaptor.allValues for (i in triggers.indices) { assertThat(sqlCaptorValues[i]) .isEqualTo( "DROP TRIGGER IF EXISTS `room_table_modification_trigger_c_content_" + triggers[i] + "`" ) } } @Test fun observeFtsTable() { val observer = LatchObserver(1, "C") mTracker.addObserver(observer) setInvalidatedTables(3) refreshSync() assertThat(observer.await()).isEqualTo(true) assertThat(observer.invalidatedTables!!.size).isEqualTo(1) assertThat(observer.invalidatedTables).contains("C") setInvalidatedTables(1) observer.reset(1) refreshSync() assertThat(observer.await()).isEqualTo(false) setInvalidatedTables(0, 3) refreshSync() assertThat(observer.await()).isEqualTo(true) assertThat(observer.invalidatedTables!!.size).isEqualTo(1) assertThat(observer.invalidatedTables).contains("C") } @Test fun observeExternalContentFtsTable() { val observer = LatchObserver(1, "d") mTracker.addObserver(observer) setInvalidatedTables(0) refreshSync() assertThat(observer.await()).isEqualTo(true) assertThat(observer.invalidatedTables!!.size).isEqualTo(1) assertThat(observer.invalidatedTables).contains("d") setInvalidatedTables(2, 3) observer.reset(1) refreshSync() assertThat(observer.await()).isEqualTo(false) setInvalidatedTables(0, 1) refreshSync() assertThat(observer.await()).isEqualTo(true) assertThat(observer.invalidatedTables!!.size).isEqualTo(1) assertThat(observer.invalidatedTables).contains("d") } @Test fun observeExternalContentFtsTableAndContentTable() { val observer = LatchObserver(1, "d", "a") mTracker.addObserver(observer) setInvalidatedTables(0) refreshSync() assertThat(observer.await()).isEqualTo(true) assertThat(observer.invalidatedTables!!.size).isEqualTo(2) assertThat(observer.invalidatedTables).containsAtLeast("d", "a") setInvalidatedTables(2, 3) observer.reset(1) refreshSync() assertThat(observer.await()).isEqualTo(false) setInvalidatedTables(0, 1) refreshSync() assertThat(observer.await()).isEqualTo(true) assertThat(observer.invalidatedTables!!.size).isEqualTo(2) assertThat(observer.invalidatedTables).containsAtLeast("d", "a") } @Test fun observeExternalContentFatsTableAndContentTableSeparately() { val observerA = LatchObserver(1, "a") val observerD = LatchObserver(1, "d") mTracker.addObserver(observerA) mTracker.addObserver(observerD) setInvalidatedTables(0) refreshSync() assertThat(observerA.await()).isEqualTo(true) assertThat(observerD.await()).isEqualTo(true) assertThat(observerA.invalidatedTables!!.size).isEqualTo(1) assertThat(observerD.invalidatedTables!!.size).isEqualTo(1) assertThat(observerA.invalidatedTables).contains("a") assertThat(observerD.invalidatedTables).contains("d") // Remove observer 'd' which is backed by 'a', observers to 'a' should still work. mTracker.removeObserver(observerD) setInvalidatedTables(0) observerA.reset(1) observerD.reset(1) refreshSync() assertThat(observerA.await()).isEqualTo(true) assertThat(observerD.await()).isEqualTo(false) assertThat(observerA.invalidatedTables!!.size).isEqualTo(1) assertThat(observerA.invalidatedTables).contains("a") } @Test fun observeView() { val observer = LatchObserver(1, "E") mTracker.addObserver(observer) setInvalidatedTables(0, 1) refreshSync() assertThat(observer.await()).isEqualTo(true) assertThat(observer.invalidatedTables!!.size).isEqualTo(1) assertThat(observer.invalidatedTables).contains("a") setInvalidatedTables(2, 3) observer.reset(1) refreshSync() assertThat(observer.await()).isEqualTo(false) setInvalidatedTables(0, 1) refreshSync() assertThat(observer.await()).isEqualTo(true) assertThat(observer.invalidatedTables!!.size).isEqualTo(1) assertThat(observer.invalidatedTables).contains("a") } @Test fun failFastCreateLiveData() { // assert that sending a bad createLiveData table name fails instantly try { mTracker.createLiveData<Unit>( tableNames = arrayOf("invalid table name"), inTransaction = false ) {} fail("should've throw an exception for invalid table name") } catch (expected: IllegalArgumentException) { // expected } } @Test fun closedDbAfterOpen() { setInvalidatedTables(3, 1) mTracker.addObserver(LatchObserver(1, "a", "b")) mTracker.syncTriggers() mTracker.refreshRunnable.run() doThrow(SQLiteException("foo")).whenever(mRoomDatabase)?.query( query = InvalidationTracker.SELECT_UPDATED_TABLES_SQL, args = arrayOf(Array<Any>::class.java) ) mTracker.pendingRefresh.set(true) mTracker.refreshRunnable.run() } /** * Setup Cursor result to return INVALIDATED for given tableIds */ private fun setInvalidatedTables(vararg tableIds: Int) { // mockito does not like multi-threaded access so before setting versions, make sure we // sync background tasks. drainTasks() val cursor = createCursorWithValues(*tableIds) doReturn(cursor).whenever(mRoomDatabase)?.query( query = argThat<SimpleSQLiteQuery> { argument -> argument.sql == InvalidationTracker.SELECT_UPDATED_TABLES_SQL }, signal = isNull(), ) } private fun createCursorWithValues(vararg tableIds: Int): Cursor { val cursor: Cursor = mock() val index = AtomicInteger(-1) whenever(cursor.moveToNext()).thenAnswer { index.addAndGet(1) < tableIds.size } val intAnswer = Answer { invocation -> // checkUpdatedTable only checks for column 0 (invalidated table id) assert(invocation.arguments[0] as Int == 0) tableIds[index.toInt()] } whenever(cursor.getInt(anyInt())).thenAnswer(intAnswer) return cursor } internal class LatchObserver( count: Int, vararg tableNames: String ) : InvalidationTracker.Observer(arrayOf(*tableNames)) { private var mLatch: CountDownLatch var invalidatedTables: Set<String>? = null private set init { mLatch = CountDownLatch(count) } fun await(): Boolean { return mLatch.await(3, TimeUnit.SECONDS) } override fun onInvalidated(tables: Set<String>) { invalidatedTables = tables mLatch.countDown() } fun reset(count: Int) { invalidatedTables = null mLatch = CountDownLatch(count) } } companion object { /** * Tries to trigger garbage collection by allocating in the heap until an element is * available in the given reference queue. */ private fun forceGc(queue: ReferenceQueue<Any?>) { val continueTriggeringGc = AtomicBoolean(true) val t = Thread { var byteCount = 0 try { val leak = ArrayList<ByteArray>() do { val arraySize = (Math.random() * 1000).toInt() byteCount += arraySize leak.add(ByteArray(arraySize)) System.gc() // Not guaranteed to trigger GC, hence the leak and the timeout Thread.sleep(10) } while (continueTriggeringGc.get()) } catch (e: InterruptedException) { // Ignored } println("Allocated $byteCount bytes trying to force a GC.") } t.start() val result = queue.remove(TimeUnit.SECONDS.toMillis(10)) continueTriggeringGc.set(false) t.interrupt() assertWithMessage("Couldn't trigger garbage collection, test flake") .that(result) .isNotNull() result.clear() } } }
apache-2.0
cdf0ea4edfacf520ecedc224c079f70d
36.079457
100
0.647554
4.62014
false
true
false
false
crabzilla/crabzilla
crabzilla-stack/src/main/kotlin/io/github/crabzilla/stack/subscription/internal/SubscriptionComponent.kt
1
11677
package io.github.crabzilla.stack.subscription.internal import io.github.crabzilla.stack.CrabzillaContext import io.github.crabzilla.stack.CrabzillaContext.Companion.EVENTBUS_GLOBAL_TOPIC import io.github.crabzilla.stack.CrabzillaContext.Companion.POSTGRES_NOTIFICATION_CHANNEL import io.github.crabzilla.stack.EventProjector import io.github.crabzilla.stack.EventRecord import io.github.crabzilla.stack.subscription.SubscriptionConfig import io.github.crabzilla.stack.subscription.SubscriptionSink.* import io.vertx.core.Future import io.vertx.core.Future.succeededFuture import io.vertx.core.Handler import io.vertx.core.Promise import io.vertx.core.json.JsonArray import io.vertx.core.json.JsonObject import io.vertx.sqlclient.SqlConnection import io.vertx.sqlclient.Tuple import org.slf4j.LoggerFactory import java.lang.management.ManagementFactory import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicLong import kotlin.math.min internal class SubscriptionComponent( private val crabzillaContext: CrabzillaContext, private val options: SubscriptionConfig, private val eventProjector: EventProjector?, ) { companion object { private val node: String = ManagementFactory.getRuntimeMXBean().name private const val GREED_INTERVAL = 100L } private val log = LoggerFactory .getLogger("${SubscriptionComponent::class.java.simpleName}-${options.subscriptionName}") private var greedy = AtomicBoolean(false) private val failures = AtomicLong(0L) private val backOff = AtomicLong(0L) private var currentOffset = 0L private var isPaused = AtomicBoolean(false) private var isBusy = AtomicBoolean(false) private lateinit var scanner: EventsScanner private lateinit var subscriptionEndpoints: SubscriptionEndpoints fun start(): Future<Void> { fun status(): JsonObject { return JsonObject() .put("node", node) .put("paused", isPaused.get()) .put("busy", isBusy.get()) .put("greedy", greedy.get()) .put("failures", failures.get()) .put("backOff", backOff.get()) .put("currentOffset", currentOffset) } fun startManagementEndpoints() { crabzillaContext.vertx().eventBus() .consumer<Nothing>(subscriptionEndpoints.status()) { msg -> log.debug("Status: {}", status().encodePrettily()) msg.reply(status()) } crabzillaContext.vertx().eventBus() .consumer<Nothing>(subscriptionEndpoints.pause()) { msg -> log.debug("Status: {}", status().encodePrettily()) isPaused.set(true) msg.reply(status()) } crabzillaContext.vertx().eventBus() .consumer<Nothing>(subscriptionEndpoints.resume()) { msg -> log.debug("Status: {}", status().encodePrettily()) isPaused.set(false) msg.reply(status()) } crabzillaContext.vertx().eventBus().consumer<Nothing>(subscriptionEndpoints.handle()) { msg -> log.debug("Will handle") action() .onFailure { log.error(it.message) } .onSuccess { log.debug("Handle finished") } .onComplete { msg.reply(status()) } } } fun startPgNotificationSubscriber(): Future<Void> { val promise = Promise.promise<Void>() val subscriber = crabzillaContext.pgSubscriber() subscriber.connect() .onSuccess { subscriber.channel(POSTGRES_NOTIFICATION_CHANNEL) .handler { stateType -> if (!greedy.get() && (options.stateTypes.isEmpty() || options.stateTypes.contains(stateType))) { greedy.set(true) log.debug("Greedy {}", stateType) } } promise.complete() }.onFailure { promise.fail(it) } return promise.future() } fun startEventsScanner() { val query = QuerySpecification.query(options.stateTypes, options.eventTypes) log.debug( "Will start subscription [{}] using query [{}] in [{}] milliseconds", options.subscriptionName, query, options.initialInterval ) scanner = EventsScanner(crabzillaContext.pgPool(), options.subscriptionName, query) } fun startProjection(): Future<Void> { return scanner.getCurrentOffset() .onSuccess { offset -> currentOffset = offset } .compose { scanner.getGlobalOffset() } .onSuccess { globalOffset -> greedy.set(globalOffset > currentOffset) val effectiveInitialInterval = if (greedy.get()) 1 else options.initialInterval log.info( "Subscription [{}] current offset [{}] global offset [{}]", options.subscriptionName, currentOffset, globalOffset ) log.info("Subscription [{}] started pooling events with {}", options.subscriptionName, options) // Schedule the first execution crabzillaContext.vertx().setTimer(effectiveInitialInterval, handler()) // Schedule the metrics crabzillaContext.vertx().setPeriodic(options.metricsInterval) { log.info("Subscription [{}] current offset [{}]", options.subscriptionName, currentOffset) } }.mapEmpty() } log.info("Node {} starting with {}", node, options) subscriptionEndpoints = SubscriptionEndpoints(options.subscriptionName) startManagementEndpoints() startEventsScanner() return startPgNotificationSubscriber() .compose { startProjection() } } private fun handler(): Handler<Long> { return Handler<Long> { action() } } private fun action(): Future<Void> { fun scanEvents(): Future<List<EventRecord>> { log.debug("Scanning for new events for subscription {}", options.subscriptionName) return scanner.scanPendingEvents(options.maxNumberOfRows) } fun requestEventbus(eventsList: List<EventRecord>): Future<Long> { val eventsAsJson: List<JsonObject> = eventsList.map { it.toJsonObject() } val array = JsonArray(eventsAsJson) log.debug("Will publish {} events", eventsAsJson.size) val promise = Promise.promise<Long>() crabzillaContext.vertx().eventBus().request<Long>(EVENTBUS_GLOBAL_TOPIC, array) { if (it.failed()) { promise.fail(it.cause()) } else { log.debug("Got response {}", it.result().body()) promise.complete(eventsList.last().metadata.eventSequence) } } return promise.future() } fun requestEventbusBlocking(eventsList: List<EventRecord>): Future<Long> { val eventsAsJson: List<JsonObject> = eventsList.map { it.toJsonObject() } val array = JsonArray(eventsAsJson) log.debug("Will publish ${eventsAsJson.size} -> ${array.encodePrettily()}") return crabzillaContext.vertx().executeBlocking<Long> { promise -> crabzillaContext.vertx().eventBus().request<Long>(EVENTBUS_GLOBAL_TOPIC, array) { if (it.failed()) { promise.fail(it.cause()) } else { log.debug("Got response {}", it.result().body()) promise.complete(eventsList.last().metadata.eventSequence) } } } } fun projectEventsToPostgres(conn: SqlConnection, eventsList: List<EventRecord>): Future<Void> { val initialFuture = succeededFuture<Void>() return eventsList.fold( initialFuture ) { currentFuture: Future<Void>, eventRecord: EventRecord -> currentFuture.compose { log.debug("Will project event {} to postgres", eventRecord.metadata.eventSequence) eventProjector!!.project(conn, eventRecord) } } } fun updateOffset(conn: SqlConnection, offset: Long): Future<Void> { return conn .preparedQuery("update subscriptions set sequence = $2 where name = $1") .execute(Tuple.of(options.subscriptionName, offset)) .mapEmpty() } fun registerNoNewEvents() { greedy.set(false) val jitter = ((0..5).random() * 200) val nextInterval = min(options.maxInterval, options.interval * backOff.incrementAndGet() + jitter) crabzillaContext.vertx().setTimer(nextInterval, handler()) log.debug("registerNoNewEvents - Rescheduled to next {} milliseconds", nextInterval) } fun registerFailure(throwable: Throwable) { greedy.set(false) val jitter = ((0..5).random() * 200) val nextInterval = min(options.maxInterval, (options.interval * failures.incrementAndGet()) + jitter) crabzillaContext.vertx().setTimer(nextInterval, handler()) log.error("registerFailure - Rescheduled to next {} milliseconds", nextInterval, throwable) } fun registerSuccess(eventSequence: Long) { currentOffset = eventSequence failures.set(0) backOff.set(0) val nextInterval = if (greedy.get()) GREED_INTERVAL else options.interval crabzillaContext.vertx().setTimer(nextInterval, handler()) log.debug("registerSuccess - Rescheduled to next {} milliseconds", nextInterval) } fun justReschedule() { crabzillaContext.vertx().setTimer(options.interval, handler()) log.debug("It is busy=$isBusy or paused=$isPaused. Will just reschedule.") log.debug("justReschedule - Rescheduled to next {} milliseconds", options.interval) } fun project(eventsList: List<EventRecord>): Future<Void> { log.debug("Found {} new events. The first is {} and last is {}", eventsList.size, eventsList.first().metadata.eventSequence, eventsList.last().metadata.eventSequence ) return when (options.sink ?: EVENTBUS_REQUEST_REPLY) { POSTGRES_PROJECTOR -> { crabzillaContext.pgPool().withTransaction { conn -> projectEventsToPostgres(conn, eventsList) .compose { updateOffset(conn, eventsList.last().metadata.eventSequence) } } } EVENTBUS_REQUEST_REPLY -> { requestEventbus(eventsList) .compose { eventSequence -> crabzillaContext.pgPool().withTransaction { conn -> updateOffset(conn, eventSequence) } } } EVENTBUS_REQUEST_REPLY_BLOCKING -> { requestEventbusBlocking(eventsList) .compose { eventSequence -> crabzillaContext.pgPool().withTransaction { conn -> updateOffset(conn, eventSequence) } } } EVENTBUS_PUBLISH -> { val eventsAsJson: List<JsonObject> = eventsList.map { it.toJsonObject() } val array = JsonArray(eventsAsJson) log.info("Will publish ${eventsAsJson.size} -> ${array.encodePrettily()}") crabzillaContext.vertx().eventBus().publish(EVENTBUS_GLOBAL_TOPIC, array) succeededFuture(eventsList.last().metadata.eventSequence) .compose { eventSequence -> crabzillaContext.pgPool().withTransaction { conn -> updateOffset(conn, eventSequence) } } } } } if (isBusy.get() || isPaused.get()) { justReschedule() return succeededFuture() } isBusy.set(true) return scanEvents() .compose { eventsList -> if (eventsList.isEmpty()) { registerNoNewEvents() succeededFuture() } else { project(eventsList) .onSuccess { registerSuccess(eventsList.last().metadata.eventSequence) } } }.onFailure { registerFailure(it) }.onComplete { isBusy.set(false) } } }
apache-2.0
16f73d6f82a350a81f906120a3b31762
36.789644
110
0.644087
4.63557
false
false
false
false
andstatus/andstatus
app/src/main/kotlin/org/andstatus/app/service/QueueAccessor.kt
1
7447
package org.andstatus.app.service import kotlinx.coroutines.sync.withLock import org.andstatus.app.context.MyPreferences import org.andstatus.app.util.MyLog import java.util.concurrent.TimeUnit class QueueAccessor(private val cq: CommandQueue, val accessorType: CommandQueue.AccessorType) { fun isAnythingToExecuteNow(): Boolean = !cq.loaded || isAnythingToExecuteNowIn(mainQueueType) || isAnythingToExecuteNowIn(QueueType.SKIPPED) || isAnythingToExecuteNowIn(QueueType.RETRY) val countToExecute: Int get() = countToExecuteIn(mainQueueType) + countToExecuteIn(QueueType.PRE) + countToExecuteIn(QueueType.SKIPPED) + countToExecuteIn(QueueType.RETRY) private fun isForAccessor(cd: CommandData): Boolean { val commandForDownloads = (cd.command == CommandEnum.GET_ATTACHMENT || cd.command == CommandEnum.GET_AVATAR) return (accessorType == CommandQueue.AccessorType.GENERAL) xor commandForDownloads } private val mainQueueType: QueueType get() = if (accessorType == CommandQueue.AccessorType.GENERAL) QueueType.CURRENT else QueueType.DOWNLOADS private fun countToExecuteIn(queueType: QueueType): Int = cq.get(queueType).count { it.mayBeExecuted(queueType) } private fun isAnythingToExecuteNowIn(queueType: QueueType): Boolean = cq.get(queueType).any { it.mayBeExecuted(queueType) } private fun CommandData.mayBeExecuted(queueType: QueueType): Boolean = isForAccessor(this) && !skip(this) && (queueType != QueueType.RETRY || isTimeToRetry) suspend fun nextToExecute(queueExecutor: QueueExecutor): CommandData { moveCommandsFromPreToMainQueue() CommandQueue.mutex.withLock { var commandData: CommandData do { commandData = cq.pollOrEmpty(mainQueueType) if (commandData.isEmpty) { moveCommandsFromSkippedToMainQueue() commandData = cq.pollOrEmpty(mainQueueType) } if (commandData.isEmpty) { moveCommandsFromRetryToMainQueue() commandData = cq.pollOrEmpty(mainQueueType) } if (commandData.isEmpty) { break } commandData = findInRetryQueue(commandData) if (commandData.nonEmpty) { commandData = findInErrorQueue(commandData) } if (commandData.hasDuplicateIn(QueueType.EXECUTING)) { commandData = CommandData.EMPTY } if (skip(commandData) && cq.addToQueue(QueueType.SKIPPED, commandData)) { commandData = CommandData.EMPTY } } while (commandData.isEmpty) if (commandData.nonEmpty) { MyLog.v( queueExecutor, "ToExecute $accessorType in " + (if (cq.myContext.isInForeground) "foreground " + (if (MyPreferences.isSyncWhileUsingApplicationEnabled) "enabled" else "disabled") else "background") + ": " + commandData.toString() ) commandData.setManuallyLaunched(false) cq[QueueType.EXECUTING].addToQueue(commandData) } return commandData } } private fun skip(commandData: CommandData): Boolean { if (commandData.isEmpty) return false if (!commandData.isInForeground() && cq.myContext.isInForeground && !MyPreferences.isSyncWhileUsingApplicationEnabled ) { return true } return !commandData.command.getConnectionRequired().isConnectionStateOk(cq.myContext.connectionState) } suspend fun moveCommandsFromPreToMainQueue() { CommandQueue.mutex.withLock { cq[QueueType.PRE].forEachEx { cd -> if (cd.hasDuplicateInMainOrExecuting || addToMainOrSkipQueue(cd)) { remove(cd) } } } } private val CommandData.hasDuplicateInMainOrExecuting: Boolean get() = this.hasDuplicateIn(QueueType.CURRENT) || this.hasDuplicateIn(QueueType.DOWNLOADS) || this.hasDuplicateIn(QueueType.EXECUTING) private fun CommandData.hasDuplicateIn(queueType: QueueType): Boolean = this.nonEmpty && cq[queueType].contains(this).also { if (it) MyLog.v("") { "Duplicate found in $queueType: $this" } } private fun moveCommandsFromSkippedToMainQueue() { cq[QueueType.SKIPPED].forEachEx { cd -> if (cd.hasDuplicateInMainOrExecuting) { remove(cd) } else if (!skip(cd)) { remove(cd) if (!addToMainOrSkipQueue(cd)) { addToQueue(cd) } } } } /** @return true if command was added */ private fun addToMainOrSkipQueue(commandData: CommandData): Boolean { if (!isForAccessor(commandData)) return false return if (skip(commandData)) { cq.addToQueue(QueueType.SKIPPED, commandData) } else { cq.addToQueue(mainQueueType, commandData) } } private fun moveCommandsFromRetryToMainQueue() { cq[QueueType.RETRY].forEachEx { cd -> if (cd.mayBeExecuted(queueType) && addToMainOrSkipQueue(cd)) { remove(cd) MyLog.v(this) { "Moved from Retry to Main queue: $cd" } } } } private fun findInRetryQueue(cdIn: CommandData): CommandData { cq[QueueType.RETRY].forEachEx { cd -> if (cd == cdIn) { return if (cdIn.isManuallyLaunched() || cd.mayBeExecuted(QueueType.RETRY)) { cd.resetRetries() remove(cd) MyLog.v(CommandQueue.TAG) { "Returned from Retry queue: $cd" } cd } else { MyLog.v(CommandQueue.TAG) { "Found in Retry queue, but left there: $cd" } CommandData.EMPTY } } } return cdIn } private fun findInErrorQueue(cdIn: CommandData): CommandData { cq[QueueType.ERROR].forEachEx { cd -> if (cd == cdIn) { return if (cdIn.isManuallyLaunched()) { remove(cd) MyLog.v(CommandQueue.TAG) { "Returned from Error queue: $cd" } cd.resetRetries() cd } else { MyLog.v(CommandQueue.TAG) { "Found in Error queue, but left there: $cd" } CommandData.EMPTY } } else { if (cd.executedMoreSecondsAgoThan(MAX_SECONDS_IN_ERROR_QUEUE)) { remove(cd) MyLog.i(CommandQueue.TAG, "Removed old from Error queue: $cd") } } } return cdIn } fun onPostExecute(commandData: CommandData) { cq[QueueType.EXECUTING].remove(commandData) } companion object { const val MIN_RETRY_PERIOD_SECONDS: Long = 900 private val MAX_SECONDS_IN_ERROR_QUEUE: Long = TimeUnit.DAYS.toSeconds(10) } }
apache-2.0
c5154a84981575fbd7fe93926ca7500d
36.994898
125
0.573654
4.743312
false
false
false
false