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
nsk-mironov/sento
sento-compiler/src/main/kotlin/io/mironov/sento/compiler/model/ListenerTargetSpec.kt
1
2917
package io.mironov.sento.compiler.model import io.mironov.sento.compiler.GenerationEnvironment import io.mironov.sento.compiler.SentoException import io.mironov.sento.compiler.common.Types import io.mironov.sento.compiler.common.simpleName import io.mironov.sento.compiler.reflect.AnnotationSpec import io.mironov.sento.compiler.reflect.ClassSpec import io.mironov.sento.compiler.reflect.MethodSpec import org.objectweb.asm.Type import java.util.ArrayList import java.util.LinkedHashSet internal data class ListenerTargetSpec private constructor( val clazz: ClassSpec, val method: MethodSpec, val annotation: AnnotationSpec, val listener: ListenerClassSpec, val views: Collection<ViewSpec>, val arguments: Collection<ArgumentSpec>, val type: Type ) { companion object { fun create(clazz: ClassSpec, method: MethodSpec, annotation: AnnotationSpec, optional: Boolean, environment: GenerationEnvironment): ListenerTargetSpec { val listener = environment.registry.resolveListenerClassSpec(annotation)!! val binding = environment.naming.getBindingType(clazz) val type = environment.naming.getAnonymousType(Type.getObjectType("${binding.internalName}\$${method.name}")) val arguments = remapMethodArguments(clazz, method, annotation, listener, environment) val views = annotation.value<IntArray>("value").map { ViewSpec(it, optional, clazz, ViewOwner.from(method)) } if (method.returns !in listOf(Types.VOID, Types.BOOLEAN)) { throw SentoException("Unable to generate @{0} binding for ''{1}#{2}'' method - it returns ''{3}'', but only {4} are supported.", annotation.type.simpleName, clazz.type.className, method.name, method.returns.className, listOf(Types.VOID.className, Types.BOOLEAN.className)) } return ListenerTargetSpec(clazz, method, annotation, listener, views, arguments, type) } private fun remapMethodArguments(clazz: ClassSpec, method: MethodSpec, annotation: AnnotationSpec, binding: ListenerClassSpec, environment: GenerationEnvironment): Collection<ArgumentSpec> { val result = ArrayList<ArgumentSpec>() val available = LinkedHashSet<Int>() for (index in 0..binding.callback.arguments.size - 1) { available.add(index) } for (argument in method.arguments) { val index = available.firstOrNull { available.contains(it) && environment.registry.isCastableFromTo(binding.callback.arguments[it], argument) } if (index == null) { throw SentoException("Unable to generate @{0} binding for ''{1}#{2}'' method - argument ''{3}'' didn''t match any listener parameters.", annotation.type.simpleName, clazz.type.className, method.name, argument.className) } result.add(ArgumentSpec(index, argument)) available.remove(index) } return result } } }
apache-2.0
46f68f5831d6d0bd453be8c0299f55df
41.897059
194
0.722317
4.37988
false
false
false
false
dkrivoruchko/ScreenStream
app/src/main/kotlin/info/dvkr/screenstream/ui/activity/CastPermissionActivity.kt
1
4207
package info.dvkr.screenstream.ui.activity import android.content.ActivityNotFoundException import android.media.projection.MediaProjectionManager import android.os.Bundle import androidx.activity.result.contract.ActivityResultContracts import androidx.annotation.LayoutRes import androidx.annotation.StringRes import androidx.core.content.ContextCompat import com.afollestad.materialdialogs.MaterialDialog import com.afollestad.materialdialogs.callbacks.onDismiss import com.afollestad.materialdialogs.lifecycle.lifecycleOwner import com.elvishew.xlog.XLog import info.dvkr.screenstream.R import info.dvkr.screenstream.common.getLog import info.dvkr.screenstream.service.ServiceMessage import info.dvkr.screenstream.service.helper.IntentAction abstract class CastPermissionActivity(@LayoutRes contentLayoutId: Int) : NotificationPermissionActivity(contentLayoutId) { private companion object { private const val KEY_CAST_PERMISSION_PENDING = "KEY_CAST_PERMISSION_PENDING" } private var permissionsErrorDialog: MaterialDialog? = null private var castPermissionsPending: Boolean = false private val startMediaProjection = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> if (result.resultCode == RESULT_OK) { XLog.d(getLog("registerForActivityResult", "Cast permission granted")) IntentAction.CastIntent(result.data!!).sendToAppService(this@CastPermissionActivity) } else { XLog.w(getLog("registerForActivityResult", "Cast permission denied")) IntentAction.CastPermissionsDenied.sendToAppService(this@CastPermissionActivity) permissionsErrorDialog?.dismiss() showErrorDialog( R.string.permission_activity_permission_required_title, R.string.permission_activity_cast_permission_required ) } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) castPermissionsPending = savedInstanceState?.getBoolean(KEY_CAST_PERMISSION_PENDING) ?: false XLog.d(getLog("onCreate", "castPermissionsPending: $castPermissionsPending")) } override fun onSaveInstanceState(outState: Bundle) { XLog.d(getLog("onSaveInstanceState", "castPermissionsPending: $castPermissionsPending")) outState.putBoolean(KEY_CAST_PERMISSION_PENDING, castPermissionsPending) super.onSaveInstanceState(outState) } override fun onServiceMessage(serviceMessage: ServiceMessage) { super.onServiceMessage(serviceMessage) if (serviceMessage is ServiceMessage.ServiceState) { if (serviceMessage.waitingForCastPermission.not()) { castPermissionsPending = false return } if (castPermissionsPending) { XLog.i(getLog("onServiceMessage", "Ignoring: castPermissionsPending == true")) return } permissionsErrorDialog?.dismiss() castPermissionsPending = true try { val projectionManager = ContextCompat.getSystemService(this, MediaProjectionManager::class.java)!! startMediaProjection.launch(projectionManager.createScreenCaptureIntent()) } catch (ignore: ActivityNotFoundException) { IntentAction.CastPermissionsDenied.sendToAppService(this@CastPermissionActivity) showErrorDialog( R.string.permission_activity_error_title_activity_not_found, R.string.permission_activity_error_activity_not_found ) } } } private fun showErrorDialog(@StringRes titleRes: Int, @StringRes messageRes: Int) { permissionsErrorDialog = MaterialDialog(this).show { lifecycleOwner(this@CastPermissionActivity) icon(R.drawable.ic_permission_dialog_24dp) title(titleRes) message(messageRes) positiveButton(android.R.string.ok) cancelable(false) cancelOnTouchOutside(false) onDismiss { permissionsErrorDialog = null } } } }
mit
cfc2a42b0a69e2a7ff32ee8269fab5c8
42.381443
126
0.705729
5.499346
false
false
false
false
jwren/intellij-community
platform/lang-impl/src/com/intellij/lang/documentation/ide/impl/DocumentationManager.kt
1
9414
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("TestOnlyProblems") // KTIJ-19938 package com.intellij.lang.documentation.ide.impl import com.intellij.codeInsight.CodeInsightSettings import com.intellij.codeInsight.lookup.LookupElement import com.intellij.codeInsight.lookup.LookupEvent import com.intellij.codeInsight.lookup.LookupEx import com.intellij.codeInsight.lookup.LookupListener import com.intellij.codeInsight.lookup.impl.LookupManagerImpl import com.intellij.ide.util.propComponentProperty import com.intellij.lang.documentation.DocumentationTarget import com.intellij.lang.documentation.ide.actions.DOCUMENTATION_TARGETS import com.intellij.lang.documentation.ide.ui.toolWindowUI import com.intellij.lang.documentation.impl.DocumentationRequest import com.intellij.lang.documentation.impl.InternalResolveLinkResult import com.intellij.lang.documentation.impl.documentationRequest import com.intellij.lang.documentation.impl.resolveLink import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.application.EDT import com.intellij.openapi.application.ModalityState import com.intellij.openapi.application.asContextElement import com.intellij.openapi.components.Service import com.intellij.openapi.components.service import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.ui.popup.AbstractPopup import com.intellij.util.ui.EDT import kotlinx.coroutines.* import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.collectLatest import java.awt.Point import java.lang.ref.WeakReference @Service internal class DocumentationManager(private val project: Project) : Disposable { companion object { @JvmStatic fun instance(project: Project): DocumentationManager = project.service() var skipPopup: Boolean by propComponentProperty(name = "documentation.skip.popup", defaultValue = false) } private val cs: CoroutineScope = CoroutineScope(SupervisorJob()) // separate scope is needed for the ability to cancel its children private val popupScope: CoroutineScope = CoroutineScope(SupervisorJob(parent = cs.coroutineContext.job)) override fun dispose() { cs.cancel() } private val toolWindowManager: DocumentationToolWindowManager get() = DocumentationToolWindowManager.instance(project) fun actionPerformed(dataContext: DataContext) { EDT.assertIsEdt() val editor = dataContext.getData(CommonDataKeys.EDITOR) val currentPopup = getPopup() if (currentPopup != null) { // focused popup would eat the shortcut itself // => at this point there is an unfocused documentation popup near lookup or search component currentPopup.focusPreferredComponent() return } val secondaryPopupContext = lookupPopupContext(editor) ?: quickSearchPopupContext(project) if (secondaryPopupContext == null) { // no popups if (toolWindowManager.focusVisibleReusableTab()) { // Explicit invocation moves focus to a visible preview tab. return } } else { // some popup is already visible if (toolWindowManager.hasVisibleAutoUpdatingTab()) { // don't show another popup is a preview tab is visible, it will be updated return } } val targets = dataContext.getData(DOCUMENTATION_TARGETS) val target = targets?.firstOrNull() ?: return // TODO multiple targets // This happens in the UI thread because IntelliJ action system returns `DocumentationTarget` instance from the `DataContext`, // and it's not possible to guarantee that it will still be valid when sent to another thread, // so we create pointer and presentation right in the UI thread. val request = target.documentationRequest() val popupContext = secondaryPopupContext ?: DefaultPopupContext(project, editor) showDocumentation(request, popupContext) } private var popup: WeakReference<AbstractPopup>? = null val isPopupVisible: Boolean get() { EDT.assertIsEdt() return popup?.get()?.isVisible == true } private fun getPopup(): AbstractPopup? { EDT.assertIsEdt() val popup: AbstractPopup? = popup?.get() if (popup == null) { return null } if (!popup.isVisible) { // hint's window might've been hidden by AWT without notifying us // dispose to remove the popup from IDE hierarchy and avoid leaking components popup.cancel() check(this.popup == null) return null } return popup } private fun setPopup(popup: AbstractPopup) { EDT.assertIsEdt() this.popup = WeakReference(popup) Disposer.register(popup) { EDT.assertIsEdt() this.popup = null } } private fun showDocumentation(request: DocumentationRequest, popupContext: PopupContext) { if (skipPopup) { toolWindowManager.showInToolWindow(request) return } else if (toolWindowManager.updateVisibleReusableTab(request)) { return } if (getPopup() != null) { return } popupScope.coroutineContext.job.cancelChildren() popupScope.launch(context = Dispatchers.EDT + ModalityState.current().asContextElement(), start = CoroutineStart.UNDISPATCHED) { val popup = showDocumentationPopup(project, request, popupContext) setPopup(popup) } } internal fun autoShowDocumentationOnItemChange(lookup: LookupEx) { val settings = CodeInsightSettings.getInstance() if (!settings.AUTO_POPUP_JAVADOC_INFO) { return } val delay = settings.JAVADOC_INFO_DELAY.toLong() val showDocJob = autoShowDocumentationOnItemChange(lookup, delay) lookup.addLookupListener(object : LookupListener { override fun itemSelected(event: LookupEvent): Unit = lookupClosed() override fun lookupCanceled(event: LookupEvent): Unit = lookupClosed() private fun lookupClosed() { showDocJob.cancel() lookup.removeLookupListener(this) } }) } private fun autoShowDocumentationOnItemChange(lookup: LookupEx, delay: Long): Job { val elements: Flow<LookupElement> = lookup.elementFlow() val mapper = lookupElementToRequestMapper(lookup) return cs.launch(Dispatchers.EDT + ModalityState.current().asContextElement()) { elements.collectLatest { handleElementChange(lookup, it, delay, mapper) } } } private suspend fun handleElementChange( lookup: LookupEx, lookupElement: LookupElement, delay: Long, mapper: suspend (LookupElement) -> DocumentationRequest? ) { if (getPopup() != null) { return // return here to avoid showing another popup if the current one gets cancelled during the delay } if (!LookupManagerImpl.isAutoPopupJavadocSupportedBy(lookupElement)) { return } delay(delay) if (getPopup() != null) { // the user might've explicitly invoked the action during the delay return // return here to not compute the request unnecessarily } if (toolWindowManager.hasVisibleAutoUpdatingTab()) { return // don't show a documentation popup if an auto-updating tab is visible, it will be updated } val request = withContext(Dispatchers.Default) { mapper(lookupElement) } if (request == null) { return } showDocumentation(request, LookupPopupContext(lookup)) } fun navigateInlineLink( url: String, targetSupplier: () -> DocumentationTarget? ) { EDT.assertIsEdt() cs.launch(Dispatchers.EDT + ModalityState.current().asContextElement(), start = CoroutineStart.UNDISPATCHED) { val result = withContext(Dispatchers.IO) { resolveLink(targetSupplier, url, DocumentationTarget::navigatable) } if (result is InternalResolveLinkResult.Value) { val navigatable = result.value if (navigatable != null && navigatable.canNavigate()) { navigatable.navigate(true) } } } } fun activateInlineLink( url: String, targetSupplier: () -> DocumentationTarget?, editor: Editor, popupPosition: Point ) { EDT.assertIsEdt() cs.launch(Dispatchers.EDT + ModalityState.current().asContextElement(), start = CoroutineStart.UNDISPATCHED) { activateInlineLinkS(targetSupplier, url, editor, popupPosition) } } /** * @return `true` if the request was handled, * or `false` if nothing happened (e.g. [url] was not resolved, or [targetSupplier] returned `null`) */ suspend fun activateInlineLinkS( targetSupplier: () -> DocumentationTarget?, url: String, editor: Editor, popupPosition: Point, ): Boolean = coroutineScope { val pauseAutoUpdateHandle = toolWindowManager.getVisibleAutoUpdatingContent()?.toolWindowUI?.pauseAutoUpdate() try { val result = withContext(Dispatchers.Default) { resolveLink(targetSupplier, url) } if (result !is InternalResolveLinkResult.Value) { browseAbsolute(project, url) } else { showDocumentation(result.value, InlinePopupContext(project, editor, popupPosition)) true } } finally { pauseAutoUpdateHandle?.let(Disposer::dispose) } } }
apache-2.0
58216f766b9a1d925810ee46f2000cdd
34.524528
132
0.722116
4.69995
false
false
false
false
jwren/intellij-community
plugins/kotlin/project-wizard/idea/src/org/jetbrains/kotlin/tools/projectWizard/wizard/ui/firstStep/FirstWizardStepComponent.kt
1
10054
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.tools.projectWizard.wizard.ui.firstStep import com.intellij.icons.AllIcons import com.intellij.ide.util.projectWizard.JavaModuleBuilder import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.project.ex.ProjectManagerEx import com.intellij.openapi.projectRoots.ProjectJdkTable import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.roots.ex.ProjectRootManagerEx import com.intellij.openapi.roots.ui.configuration.JdkComboBox import com.intellij.openapi.roots.ui.configuration.projectRoot.ProjectSdksModel import com.intellij.openapi.util.Condition import com.intellij.openapi.util.NlsContexts import com.intellij.ui.IdeBorderFactory import com.intellij.ui.TitledSeparator import com.intellij.ui.dsl.builder.* import com.intellij.ui.dsl.gridLayout.HorizontalAlign import com.intellij.util.ui.JBInsets import com.intellij.util.ui.JBUI import com.intellij.util.ui.components.BorderLayoutPanel import org.jetbrains.kotlin.idea.projectWizard.WizardStatsService import org.jetbrains.kotlin.tools.projectWizard.core.Context import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.SettingReference import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.reference import org.jetbrains.kotlin.tools.projectWizard.plugins.StructurePlugin import org.jetbrains.kotlin.tools.projectWizard.plugins.buildSystem.BuildSystemPlugin import org.jetbrains.kotlin.tools.projectWizard.plugins.buildSystem.BuildSystemType import org.jetbrains.kotlin.tools.projectWizard.wizard.IdeWizard import org.jetbrains.kotlin.tools.projectWizard.wizard.KotlinNewProjectWizardUIBundle import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.* import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.setting.PathSettingComponent import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.setting.StringSettingComponent import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.setting.TitledComponentsList import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.setting.createSettingComponent import java.awt.Cursor import java.awt.event.MouseAdapter import java.awt.event.MouseEvent import javax.swing.JComponent class FirstWizardStepComponent(ideWizard: IdeWizard) : WizardStepComponent(ideWizard.context) { private val projectSettingsComponent = ProjectSettingsComponent(ideWizard).asSubComponent() override val component: JComponent = projectSettingsComponent.component } class ProjectSettingsComponent(ideWizard: IdeWizard) : DynamicComponent(ideWizard.context) { private val context = ideWizard.context private val projectTemplateComponent = ProjectTemplateSettingComponent(context).asSubComponent() private val buildSystemSetting = BuildSystemTypeSettingComponent(context).asSubComponent().apply { component.addBorder(JBUI.Borders.empty(0, /*left&right*/4)) } private var locationWasUpdatedByHand: Boolean = false private var artifactIdWasUpdatedByHand: Boolean = false private val buildSystemAdditionalSettingsComponent = BuildSystemAdditionalSettingsComponent( ideWizard, onUserTypeInArtifactId = { artifactIdWasUpdatedByHand = true }, ).asSubComponent() private val jdkComponent = JdkComponent(ideWizard).asSubComponent() private val nameAndLocationComponent = TitledComponentsList( listOf( StructurePlugin.name.reference.createSettingComponent(context), StructurePlugin.projectPath.reference.createSettingComponent(context).also { (it as? PathSettingComponent)?.onUserType { locationWasUpdatedByHand = true } }, projectTemplateComponent, buildSystemSetting, jdkComponent ), context, stretchY = true, useBigYGap = true, xPadding = 0, yPadding = 0 ).asSubComponent() override val component: JComponent by lazy(LazyThreadSafetyMode.NONE) { panel { row { cell(nameAndLocationComponent.component) .horizontalAlign(HorizontalAlign.FILL) .resizableColumn() bottomGap(BottomGap.SMALL) } row { cell(buildSystemAdditionalSettingsComponent.component) .horizontalAlign(HorizontalAlign.FILL) .resizableColumn() bottomGap(BottomGap.SMALL) } }.addBorder(IdeBorderFactory.createEmptyBorder(JBInsets(20, 20, 20, 20))) } override fun onValueUpdated(reference: SettingReference<*, *>?) { super.onValueUpdated(reference) when (reference?.path) { StructurePlugin.name.path -> { val isNameValid = read { StructurePlugin.name.reference.validate().isOk } if (isNameValid) { tryUpdateLocationByProjectName() tryArtifactIdByProjectName() } } } } private fun tryUpdateLocationByProjectName() { if (!locationWasUpdatedByHand) { val location = read { StructurePlugin.projectPath.settingValue } if (location.parent != null) modify { StructurePlugin.projectPath.reference.setValue(location.resolveSibling(StructurePlugin.name.settingValue)) locationWasUpdatedByHand = false } } } private fun tryArtifactIdByProjectName() { if (!artifactIdWasUpdatedByHand) modify { StructurePlugin.artifactId.reference.setValue(StructurePlugin.name.settingValue) artifactIdWasUpdatedByHand = false } } } class BuildSystemAdditionalSettingsComponent( ideWizard: IdeWizard, onUserTypeInArtifactId: () -> Unit, ) : DynamicComponent(ideWizard.context) { private val pomSettingsList = PomSettingsComponent(ideWizard.context, onUserTypeInArtifactId).asSubComponent() override fun onValueUpdated(reference: SettingReference<*, *>?) { super.onValueUpdated(reference) if (reference == BuildSystemPlugin.type.reference) { updateBuildSystemComponent() } } override fun onInit() { super.onInit() updateBuildSystemComponent() } private fun updateBuildSystemComponent() { val buildSystemType = read { BuildSystemPlugin.type.settingValue } section.isVisible = buildSystemType != BuildSystemType.Jps } private val section = HideableSection( KotlinNewProjectWizardUIBundle.message("additional.buildsystem.settings.artifact.coordinates"), pomSettingsList.component ) override val component: JComponent = section } private class PomSettingsComponent(context: Context, onUserTypeInArtifactId: () -> Unit) : TitledComponentsList( listOf( StructurePlugin.groupId.reference.createSettingComponent(context), StructurePlugin.artifactId.reference.createSettingComponent(context).also { (it as? StringSettingComponent)?.onUserType(onUserTypeInArtifactId) }, StructurePlugin.version.reference.createSettingComponent(context) ), context, stretchY = true ) private class JdkComponent(ideWizard: IdeWizard) : TitledComponent(ideWizard.context) { private val javaModuleBuilder = JavaModuleBuilder() private val jdkComboBox: JdkComboBox private val sdksModel: ProjectSdksModel init { val project = ProjectManager.getInstance().defaultProject sdksModel = ProjectSdksModel() sdksModel.reset(project) jdkComboBox = JdkComboBox( project, sdksModel, Condition(javaModuleBuilder::isSuitableSdkType), null, null, null ).apply { reloadModel() getDefaultJdk()?.let { jdk -> selectedJdk = jdk } ideWizard.jdk = selectedJdk addActionListener { ideWizard.jdk = selectedJdk WizardStatsService.logDataOnJdkChanged(ideWizard.context.contextComponents.get()) } } } private fun getDefaultJdk(): Sdk? { val defaultProject = ProjectManagerEx.getInstanceEx().defaultProject return ProjectRootManagerEx.getInstanceEx(defaultProject).projectSdk ?: run { val sdks = ProjectJdkTable.getInstance().allJdks .filter { it.homeDirectory?.isValid == true && javaModuleBuilder.isSuitableSdkType(it.sdkType) } .groupBy(Sdk::getSdkType) .entries.firstOrNull() ?.value?.filterNotNull() ?: return@run null sdks.maxWithOrNull(sdks.firstOrNull()?.sdkType?.versionComparator() ?: return@run null) } } override val title: String = KotlinNewProjectWizardUIBundle.message("additional.buildsystem.settings.project.jdk") override val component: JComponent = jdkComboBox } @Suppress("SpellCheckingInspection") private class HideableSection(@NlsContexts.Separator text: String, component: JComponent) : BorderLayoutPanel() { private val titledSeparator = TitledSeparator(text) private val contentPanel = borderPanel { addBorder(JBUI.Borders.emptyLeft(20)) addToCenter(component) } private var isExpanded = false init { titledSeparator.label.cursor = Cursor(Cursor.HAND_CURSOR) addToTop(titledSeparator) addToCenter(contentPanel) update(isExpanded) titledSeparator.addMouseListener(object : MouseAdapter() { override fun mouseReleased(e: MouseEvent) = update(!isExpanded) }) } private fun update(isExpanded: Boolean) { this.isExpanded = isExpanded contentPanel.isVisible = isExpanded titledSeparator.label.icon = if (isExpanded) AllIcons.General.ArrowDown else AllIcons.General.ArrowRight } }
apache-2.0
f0a52890d75e8d14aaa6e3d864756913
40.040816
158
0.714144
5.06754
false
false
false
false
youdonghai/intellij-community
platform/diff-impl/tests/com/intellij/diff/tools/fragmented/UnifiedFragmentBuilderAutoTest.kt
1
5422
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.diff.tools.fragmented import com.intellij.diff.DiffTestCase import com.intellij.diff.comparison.ComparisonPolicy import com.intellij.diff.util.DiffUtil import com.intellij.diff.util.LineRange import com.intellij.diff.util.Side import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.impl.DocumentImpl import com.intellij.openapi.progress.DumbProgressIndicator import com.intellij.openapi.util.text.StringUtil class UnifiedFragmentBuilderAutoTest : DiffTestCase() { fun test() { doTest(System.currentTimeMillis(), 30, 30) } fun doTest(seed: Long, runs: Int, maxLength: Int) { doAutoTest(seed, runs) { debugData -> debugData.put("MaxLength", maxLength) val text1 = DocumentImpl(generateText(maxLength)) val text2 = DocumentImpl(generateText(maxLength)) debugData.put("Text1", textToReadableFormat(text1.charsSequence)) debugData.put("Text2", textToReadableFormat(text2.charsSequence)) for (side in Side.values()) { for (comparisonPolicy in ComparisonPolicy.values()) { debugData.put("Policy", comparisonPolicy) debugData.put("Current side", side) doTest(text1, text2, comparisonPolicy, side) } } } } fun doTest(document1: Document, document2: Document, policy: ComparisonPolicy, masterSide: Side) { val sequence1 = document1.charsSequence val sequence2 = document2.charsSequence val fragments = MANAGER.compareLinesInner(sequence1, sequence2, policy, DumbProgressIndicator.INSTANCE) val builder = UnifiedFragmentBuilder(fragments, document1, document2, masterSide) builder.exec() val ignoreWhitespaces = policy !== ComparisonPolicy.DEFAULT val text = builder.text val blocks = builder.blocks val convertor = builder.convertor val changedLines = builder.changedLines val ranges = builder.ranges val document = DocumentImpl(text) // both documents - before and after - should be subsequence of result text. assertTrue(isSubsequence(text, sequence1, ignoreWhitespaces)) assertTrue(isSubsequence(text, sequence2, ignoreWhitespaces)) // all changes should be inside ChangedLines for (fragment in fragments) { val startLine1 = fragment.startLine1 val endLine1 = fragment.endLine1 val startLine2 = fragment.startLine2 val endLine2 = fragment.endLine2 for (i in startLine1 until endLine1) { val targetLine = convertor.convertInv1(i) assertTrue(targetLine != -1) assertTrue(isLineChanged(targetLine, changedLines)) } for (i in startLine2 until endLine2) { val targetLine = convertor.convertInv2(i) assertTrue(targetLine != -1) assertTrue(isLineChanged(targetLine, changedLines)) } } // changed fragments and changed blocks should have same content assertEquals(blocks.size, fragments.size) for (i in fragments.indices) { val fragment = fragments[i] val block = blocks[i] val fragment1 = sequence1.subSequence(fragment.startOffset1, fragment.endOffset1) val fragment2 = sequence2.subSequence(fragment.startOffset2, fragment.endOffset2) val block1 = DiffUtil.getLinesContent(document, block.range1.start, block.range1.end) val block2 = DiffUtil.getLinesContent(document, block.range2.start, block.range2.end) assertEqualsCharSequences(fragment1, block1, ignoreWhitespaces, true) assertEqualsCharSequences(fragment2, block2, ignoreWhitespaces, true) } // ranges should have exact same content for (range in ranges) { val sideSequence = range.side.select(sequence1, sequence2)!! val baseRange = text.subSequence(range.base.startOffset, range.base.endOffset) val sideRange = sideSequence.subSequence(range.changed.startOffset, range.changed.endOffset) assertTrue(StringUtil.equals(baseRange, sideRange)) } } private fun isSubsequence(text: CharSequence, sequence: CharSequence, ignoreWhitespaces: Boolean): Boolean { var index1 = 0 var index2 = 0 while (index2 < sequence.length) { val c2 = sequence[index2] if (c2 == '\n' || (StringUtil.isWhiteSpace(c2) && ignoreWhitespaces)) { index2++ continue } assertTrue(index1 < text.length) val c1 = text[index1] if (c1 == '\n' || (StringUtil.isWhiteSpace(c1) && ignoreWhitespaces)) { index1++ continue } if (c1 == c2) { index1++ index2++ } else { index1++ } } return true } private fun isLineChanged(line: Int, changedLines: List<LineRange>): Boolean { for (changedLine in changedLines) { if (changedLine.start <= line && changedLine.end > line) return true } return false } }
apache-2.0
cb5a1c17ad099c15648c6f2979adb853
33.980645
110
0.703799
4.296355
false
true
false
false
androidx/androidx
compose/material/material/src/commonMain/kotlin/androidx/compose/material/BackdropScaffold.kt
3
20772
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.material import androidx.compose.animation.core.AnimationSpec import androidx.compose.animation.core.TweenSpec import androidx.compose.animation.core.animateFloatAsState import androidx.compose.foundation.Canvas import androidx.compose.foundation.gestures.Orientation import androidx.compose.foundation.gestures.detectTapGestures import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.CornerSize import androidx.compose.material.BackdropValue.Concealed import androidx.compose.material.BackdropValue.Revealed import androidx.compose.runtime.Composable import androidx.compose.runtime.Stable import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.saveable.Saver import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.UiComposable import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Shape import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.graphics.isSpecified import androidx.compose.ui.input.nestedscroll.nestedScroll import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.layout.SubcomposeLayout import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.semantics.collapse import androidx.compose.ui.semantics.expand import androidx.compose.ui.semantics.semantics import androidx.compose.ui.unit.Constraints import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.offset import androidx.compose.ui.util.fastForEach import androidx.compose.ui.util.fastMap import androidx.compose.ui.zIndex import kotlinx.coroutines.CancellationException import kotlinx.coroutines.launch import kotlin.math.max import kotlin.math.min import kotlin.math.roundToInt /** * Possible values of [BackdropScaffoldState]. */ @ExperimentalMaterialApi enum class BackdropValue { /** * Indicates the back layer is concealed and the front layer is active. */ Concealed, /** * Indicates the back layer is revealed and the front layer is inactive. */ Revealed } /** * State of the [BackdropScaffold] composable. * * @param initialValue The initial value of the state. * @param animationSpec The default animation that will be used to animate to a new state. * @param confirmStateChange Optional callback invoked to confirm or veto a pending state change. * @param snackbarHostState The [SnackbarHostState] used to show snackbars inside the scaffold. */ @ExperimentalMaterialApi @Stable class BackdropScaffoldState( initialValue: BackdropValue, animationSpec: AnimationSpec<Float> = SwipeableDefaults.AnimationSpec, confirmStateChange: (BackdropValue) -> Boolean = { true }, val snackbarHostState: SnackbarHostState = SnackbarHostState() ) : SwipeableState<BackdropValue>( initialValue = initialValue, animationSpec = animationSpec, confirmStateChange = confirmStateChange ) { /** * Whether the back layer is revealed. */ val isRevealed: Boolean get() = currentValue == Revealed /** * Whether the back layer is concealed. */ val isConcealed: Boolean get() = currentValue == Concealed /** * Reveal the back layer with animation and suspend until it if fully revealed or animation * has been cancelled. This method will throw [CancellationException] if the animation is * interrupted * * @return the reason the reveal animation ended */ suspend fun reveal() = animateTo(targetValue = Revealed) /** * Conceal the back layer with animation and suspend until it if fully concealed or animation * has been cancelled. This method will throw [CancellationException] if the animation is * interrupted * * @return the reason the conceal animation ended */ suspend fun conceal() = animateTo(targetValue = Concealed) internal val nestedScrollConnection = this.PreUpPostDownNestedScrollConnection companion object { /** * The default [Saver] implementation for [BackdropScaffoldState]. */ fun Saver( animationSpec: AnimationSpec<Float>, confirmStateChange: (BackdropValue) -> Boolean, snackbarHostState: SnackbarHostState ): Saver<BackdropScaffoldState, *> = Saver( save = { it.currentValue }, restore = { BackdropScaffoldState( initialValue = it, animationSpec = animationSpec, confirmStateChange = confirmStateChange, snackbarHostState = snackbarHostState ) } ) } } /** * Create and [remember] a [BackdropScaffoldState]. * * @param initialValue The initial value of the state. * @param animationSpec The default animation that will be used to animate to a new state. * @param confirmStateChange Optional callback invoked to confirm or veto a pending state change. * @param snackbarHostState The [SnackbarHostState] used to show snackbars inside the scaffold. */ @Composable @ExperimentalMaterialApi fun rememberBackdropScaffoldState( initialValue: BackdropValue, animationSpec: AnimationSpec<Float> = SwipeableDefaults.AnimationSpec, confirmStateChange: (BackdropValue) -> Boolean = { true }, snackbarHostState: SnackbarHostState = remember { SnackbarHostState() } ): BackdropScaffoldState { return rememberSaveable( animationSpec, confirmStateChange, snackbarHostState, saver = BackdropScaffoldState.Saver( animationSpec = animationSpec, confirmStateChange = confirmStateChange, snackbarHostState = snackbarHostState ) ) { BackdropScaffoldState( initialValue = initialValue, animationSpec = animationSpec, confirmStateChange = confirmStateChange, snackbarHostState = snackbarHostState ) } } /** * <a href="https://material.io/components/backdrop" class="external" target="_blank">Material Design backdrop</a>. * * A backdrop appears behind all other surfaces in an app, displaying contextual and actionable * content. * * ![Backdrop image](https://developer.android.com/images/reference/androidx/compose/material/backdrop.png) * * This component provides an API to put together several material components to construct your * screen. For a similar component which implements the basic material design layout strategy * with app bars, floating action buttons and navigation drawers, use the standard [Scaffold]. * For similar component that uses a bottom sheet as the centerpiece of the screen, use * [BottomSheetScaffold]. * * Either the back layer or front layer can be active at a time. When the front layer is active, * it sits at an offset below the top of the screen. This is the [peekHeight] and defaults to * 56dp which is the default app bar height. When the front layer is inactive, it sticks to the * height of the back layer's content if [stickyFrontLayer] is set to `true` and the height of * the front layer exceeds the [headerHeight], and otherwise it minimizes to the [headerHeight]. * To switch between the back layer and front layer, you can either swipe on the front layer if * [gesturesEnabled] is set to `true` or use any of the methods in [BackdropScaffoldState]. * * The scaffold also contains an app bar, which by default is placed above the back layer's * content. If [persistentAppBar] is set to `false`, then the backdrop will not show the app bar * when the back layer is revealed; instead it will switch between the app bar and the provided * content with an animation. For best results, the [peekHeight] should match the app bar height. * To show a snackbar, use the method `showSnackbar` of [BackdropScaffoldState.snackbarHostState]. * * A simple example of a backdrop scaffold looks like this: * * @sample androidx.compose.material.samples.BackdropScaffoldSample * * @param appBar App bar for the back layer. Make sure that the [peekHeight] is equal to the * height of the app bar, so that the app bar is fully visible. Consider using [TopAppBar] but * set the elevation to 0dp and background color to transparent as a surface is already provided. * @param backLayerContent The content of the back layer. * @param frontLayerContent The content of the front layer. * @param modifier Optional [Modifier] for the root of the scaffold. * @param scaffoldState The state of the scaffold. * @param gesturesEnabled Whether or not the backdrop can be interacted with by gestures. * @param peekHeight The height of the visible part of the back layer when it is concealed. * @param headerHeight The minimum height of the front layer when it is inactive. * @param persistentAppBar Whether the app bar should be shown when the back layer is revealed. * By default, it will always be shown above the back layer's content. If this is set to `false`, * the back layer will automatically switch between the app bar and its content with an animation. * @param stickyFrontLayer Whether the front layer should stick to the height of the back layer. * @param backLayerBackgroundColor The background color of the back layer. * @param backLayerContentColor The preferred content color provided by the back layer to its * children. Defaults to the matching content color for [backLayerBackgroundColor], or if that * is not a color from the theme, this will keep the same content color set above the back layer. * @param frontLayerShape The shape of the front layer. * @param frontLayerElevation The elevation of the front layer. * @param frontLayerBackgroundColor The background color of the front layer. * @param frontLayerContentColor The preferred content color provided by the back front to its * children. Defaults to the matching content color for [frontLayerBackgroundColor], or if that * is not a color from the theme, this will keep the same content color set above the front layer. * @param frontLayerScrimColor The color of the scrim applied to the front layer when the back * layer is revealed. If the color passed is [Color.Unspecified], then a scrim will not be * applied and interaction with the front layer will not be blocked when the back layer is revealed. * @param snackbarHost The component hosting the snackbars shown inside the scaffold. */ @Composable @ExperimentalMaterialApi fun BackdropScaffold( appBar: @Composable () -> Unit, backLayerContent: @Composable () -> Unit, frontLayerContent: @Composable () -> Unit, modifier: Modifier = Modifier, scaffoldState: BackdropScaffoldState = rememberBackdropScaffoldState(Concealed), gesturesEnabled: Boolean = true, peekHeight: Dp = BackdropScaffoldDefaults.PeekHeight, headerHeight: Dp = BackdropScaffoldDefaults.HeaderHeight, persistentAppBar: Boolean = true, stickyFrontLayer: Boolean = true, backLayerBackgroundColor: Color = MaterialTheme.colors.primary, backLayerContentColor: Color = contentColorFor(backLayerBackgroundColor), frontLayerShape: Shape = BackdropScaffoldDefaults.frontLayerShape, frontLayerElevation: Dp = BackdropScaffoldDefaults.FrontLayerElevation, frontLayerBackgroundColor: Color = MaterialTheme.colors.surface, frontLayerContentColor: Color = contentColorFor(frontLayerBackgroundColor), frontLayerScrimColor: Color = BackdropScaffoldDefaults.frontLayerScrimColor, snackbarHost: @Composable (SnackbarHostState) -> Unit = { SnackbarHost(it) } ) { val peekHeightPx = with(LocalDensity.current) { peekHeight.toPx() } val headerHeightPx = with(LocalDensity.current) { headerHeight.toPx() } val backLayer = @Composable { if (persistentAppBar) { Column { appBar() backLayerContent() } } else { BackLayerTransition(scaffoldState.targetValue, appBar, backLayerContent) } } val calculateBackLayerConstraints: (Constraints) -> Constraints = { it.copy(minWidth = 0, minHeight = 0).offset(vertical = -headerHeightPx.roundToInt()) } // Back layer Surface( color = backLayerBackgroundColor, contentColor = backLayerContentColor ) { val scope = rememberCoroutineScope() BackdropStack( modifier.fillMaxSize(), backLayer, calculateBackLayerConstraints ) { constraints, backLayerHeight -> val fullHeight = constraints.maxHeight.toFloat() var revealedHeight = fullHeight - headerHeightPx if (stickyFrontLayer) { revealedHeight = min(revealedHeight, backLayerHeight) } val nestedScroll = if (gesturesEnabled) { Modifier.nestedScroll(scaffoldState.nestedScrollConnection) } else { Modifier } val swipeable = Modifier .then(nestedScroll) .swipeable( state = scaffoldState, anchors = mapOf( peekHeightPx to Concealed, revealedHeight to Revealed ), orientation = Orientation.Vertical, enabled = gesturesEnabled ) .semantics { if (scaffoldState.isConcealed) { collapse { if (scaffoldState.confirmStateChange(Revealed)) { scope.launch { scaffoldState.reveal() } }; true } } else { expand { if (scaffoldState.confirmStateChange(Concealed)) { scope.launch { scaffoldState.conceal() } }; true } } } // Front layer Surface( Modifier .offset { IntOffset(0, scaffoldState.offset.value.roundToInt()) } .then(swipeable), shape = frontLayerShape, elevation = frontLayerElevation, color = frontLayerBackgroundColor, contentColor = frontLayerContentColor ) { Box(Modifier.padding(bottom = peekHeight)) { frontLayerContent() Scrim( color = frontLayerScrimColor, onDismiss = { if (gesturesEnabled && scaffoldState.confirmStateChange(Concealed)) { scope.launch { scaffoldState.conceal() } } }, visible = scaffoldState.targetValue == Revealed ) } } // Snackbar host Box( Modifier .padding( bottom = if (scaffoldState.isRevealed && revealedHeight == fullHeight - headerHeightPx ) headerHeight else 0.dp ), contentAlignment = Alignment.BottomCenter ) { snackbarHost(scaffoldState.snackbarHostState) } } } } @Composable private fun Scrim( color: Color, onDismiss: () -> Unit, visible: Boolean ) { if (color.isSpecified) { val alpha by animateFloatAsState( targetValue = if (visible) 1f else 0f, animationSpec = TweenSpec() ) val dismissModifier = if (visible) { Modifier.pointerInput(Unit) { detectTapGestures { onDismiss() } } } else { Modifier } Canvas( Modifier .fillMaxSize() .then(dismissModifier) ) { drawRect(color = color, alpha = alpha) } } } /** * A shared axis transition, used in the back layer. Both the [appBar] and the [content] shift * vertically, while they crossfade. It is very important that both are composed and measured, * even if invisible, and that this component is as large as both of them. */ @OptIn(ExperimentalMaterialApi::class) @Composable private fun BackLayerTransition( target: BackdropValue, appBar: @Composable () -> Unit, content: @Composable () -> Unit ) { // The progress of the animation between Revealed (0) and Concealed (2). // The midpoint (1) is the point where the appBar and backContent are switched. val animationProgress by animateFloatAsState( targetValue = if (target == Revealed) 0f else 2f, animationSpec = TweenSpec() ) val animationSlideOffset = with(LocalDensity.current) { AnimationSlideOffset.toPx() } val appBarFloat = (animationProgress - 1).coerceIn(0f, 1f) val contentFloat = (1 - animationProgress).coerceIn(0f, 1f) Box { Box( Modifier.zIndex(appBarFloat).graphicsLayer( alpha = appBarFloat, translationY = (1 - appBarFloat) * animationSlideOffset ) ) { appBar() } Box( Modifier.zIndex(contentFloat).graphicsLayer( alpha = contentFloat, translationY = (1 - contentFloat) * -animationSlideOffset ) ) { content() } } } @Composable @UiComposable private fun BackdropStack( modifier: Modifier, backLayer: @Composable @UiComposable () -> Unit, calculateBackLayerConstraints: (Constraints) -> Constraints, frontLayer: @Composable @UiComposable (Constraints, Float) -> Unit ) { SubcomposeLayout(modifier) { constraints -> val backLayerPlaceable = subcompose(BackdropLayers.Back, backLayer).first() .measure(calculateBackLayerConstraints(constraints)) val backLayerHeight = backLayerPlaceable.height.toFloat() val placeables = subcompose(BackdropLayers.Front) { frontLayer(constraints, backLayerHeight) }.fastMap { it.measure(constraints) } var maxWidth = max(constraints.minWidth, backLayerPlaceable.width) var maxHeight = max(constraints.minHeight, backLayerPlaceable.height) placeables.fastForEach { maxWidth = max(maxWidth, it.width) maxHeight = max(maxHeight, it.height) } layout(maxWidth, maxHeight) { backLayerPlaceable.placeRelative(0, 0) placeables.fastForEach { it.placeRelative(0, 0) } } } } private enum class BackdropLayers { Back, Front } /** * Contains useful defaults for [BackdropScaffold]. */ object BackdropScaffoldDefaults { /** * The default peek height of the back layer. */ val PeekHeight = 56.dp /** * The default header height of the front layer. */ val HeaderHeight = 48.dp /** * The default shape of the front layer. */ val frontLayerShape: Shape @Composable get() = MaterialTheme.shapes.large .copy(topStart = CornerSize(16.dp), topEnd = CornerSize(16.dp)) /** * The default elevation of the front layer. */ val FrontLayerElevation = 1.dp /** * The default color of the scrim applied to the front layer. */ val frontLayerScrimColor: Color @Composable get() = MaterialTheme.colors.surface.copy(alpha = 0.60f) } private val AnimationSlideOffset = 20.dp
apache-2.0
95ba0caab229b656b26a48a8ac35f6ae
38.869482
115
0.673214
4.911799
false
false
false
false
DSteve595/Put.io
app/src/main/java/com/stevenschoen/putionew/files/FileDetailsLoader.kt
1
2138
package com.stevenschoen.putionew.files import android.content.Context import android.os.AsyncTask import android.os.Bundle import androidx.loader.app.LoaderManager import androidx.loader.content.Loader import com.stevenschoen.putionew.PutioBaseLoader import com.stevenschoen.putionew.getUniqueLoaderId import com.stevenschoen.putionew.model.files.PutioFile import com.stevenschoen.putionew.putioApp import timber.log.Timber class FileDetailsLoader(context: Context, private val file: PutioFile) : PutioBaseLoader(context) { fun checkDownload() { AsyncTask.execute { putioApp(context).fileDownloadDatabase.fileDownloadsDao().getByFileIdSynchronous(file.id)?.let { val isDownloaded = it.status == FileDownload.Status.Downloaded val isDownloading = it.status == FileDownload.Status.InProgress if ((isDownloaded || isDownloading) && !isFileDownloadedOrDownloading(context, it)) { Timber.d("${file.name} appears to not be downloaded, marking NotDownloaded") markFileNotDownloaded(context, it) } else if (isDownloading && isFileDownloaded(context, it)) { Timber.d("${file.name} appears to be downloaded, marking Downloaded") markFileDownloaded(context, it) } /* If, for some reason, a download finished but DownloadFinishedService didn't receive the event, downloads can get into a state where they're completed as far as the DownloadManager's concerned, but the FileDownload has no Uri. That hasn't come up, but if it ever does, the Uri should be fetched from the DownloadManager and updated (as well as its status) in the FileDownload. */ } } } companion object { fun get(loaderManager: LoaderManager, context: Context, file: PutioFile): FileDetailsLoader { return loaderManager.initLoader( getUniqueLoaderId(FileDetailsLoader::class.java), null, object : Callbacks(context) { override fun onCreateLoader(id: Int, args: Bundle?): Loader<Any> { return FileDetailsLoader(context, file) } }) as FileDetailsLoader } } }
mit
0494761bf2f6cc759a7e3ccab84133dd
42.632653
102
0.720299
4.501053
false
false
false
false
hellenxu/TipsProject
DroidDailyProject/app/src/main/java/six/ca/droiddailyproject/arch/db/DbActivity.kt
1
3963
package six.ca.droiddailyproject.arch.db import android.app.Activity import androidx.room.Room import android.os.Bundle import android.view.View import io.reactivex.Maybe import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import io.reactivex.schedulers.Schedulers import kotlinx.android.synthetic.main.act_db.* import six.ca.droiddailyproject.R import six.ca.droiddailyproject.rx.disposedBy /** * @CopyRight six.ca * Created by Heavens on 2018-11-21. */ class DbActivity : Activity(), View.OnClickListener { private lateinit var userDao: UserDao private val compositeDisposable = CompositeDisposable() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.act_db) val db = Room.databaseBuilder(applicationContext, AppDb::class.java, "helloRoom") // .addMigrations(AppDb.MIGRATION_1_2) .build() userDao = db.getUserDao() btnQuery.setOnClickListener(this) btnInsert.setOnClickListener(this) btnUpdate.setOnClickListener(this) btnDelete.setOnClickListener(this) } override fun onClick(v: View?) { when (v?.id) { R.id.btnQuery -> getUserList() R.id.btnInsert -> insertUser() R.id.btnDelete -> deleteUser() R.id.btnUpdate -> updateUser() } } private fun getUserList() { Maybe.create<List<User>> { it.onSuccess(userDao.getUserList()) }.subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ println("xxl-onsucess: ${it.size}") val sb = StringBuilder("user list: \n") it.forEach { user -> println("xxl-user: $user") sb.append(user) } tvResult.text = sb.toString() }, { println("xxl-user-list-error:$it") }) .disposedBy(compositeDisposable) } private fun insertUser() { Maybe.create<Long> { val id = System.currentTimeMillis() val user = User(id, "test$id", "six") it.onSuccess(userDao.insertUser(user)) }.subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ val sb = StringBuilder("inserted user index: $it") tvResult.text = sb.toString() }, { println("xxl-insert-user-error:$it") }) .disposedBy(compositeDisposable) } private fun deleteUser() { Maybe.create<Int> { val user = userDao.getUserList()[0] it.onSuccess(userDao.deleteUser(user)) }.subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ val sb = StringBuilder("delete user index: $it") tvResult.text = sb.toString() }, { println("xxl-delete-user-error:$it") }) .disposedBy(compositeDisposable) } private fun updateUser() { Maybe.create<Int> { val user = userDao.getUserList()[0] val newUser = User(user.uid, "updated: ${user.firstName}", user.lastName) it.onSuccess(userDao.updateUser(newUser)) }.subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ val sb = StringBuilder("updated user index: $it") tvResult.text = sb.toString() }, { println("xxl-update-user-error:$it") }) .disposedBy(compositeDisposable) } override fun onDestroy() { super.onDestroy() compositeDisposable.clear() } }
apache-2.0
73bd8b29e173edf2fed78b4dceba791f
33.469565
89
0.581378
4.701068
false
false
false
false
siosio/intellij-community
plugins/kotlin/jps/jps-plugin/src/org/jetbrains/kotlin/compilerRunner/CompilerRunnerUtil.kt
1
3488
// 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.compilerRunner import org.jetbrains.kotlin.idea.artifacts.KotlinClassPath import org.jetbrains.kotlin.preloading.ClassPreloadingUtils import org.jetbrains.kotlin.preloading.Preloader import java.io.File import java.io.PrintStream import java.lang.ref.SoftReference import kotlin.io.path.Path import kotlin.io.path.exists import kotlin.io.path.name object CompilerRunnerUtil { private var ourClassLoaderRef = SoftReference<ClassLoader>(null) internal val jdkToolsJar: File? get() { val javaHomePath = System.getProperty("java.home") if (javaHomePath == null || javaHomePath.isEmpty()) { return null } val javaHome = Path(javaHomePath) var toolsJar = javaHome.resolve("lib/tools.jar") if (toolsJar.exists()) { return toolsJar.toFile() } // We might be inside jre. if (javaHome.name == "jre") { toolsJar = javaHome.resolveSibling("lib/tools.jar") if (toolsJar.exists()) { return toolsJar.toFile() } } return null } @Synchronized private fun getOrCreateClassLoader( environment: JpsCompilerEnvironment, paths: List<File> ): ClassLoader { var classLoader = ourClassLoaderRef.get() if (classLoader == null) { classLoader = ClassPreloadingUtils.preloadClasses( paths, Preloader.DEFAULT_CLASS_NUMBER_ESTIMATE, CompilerRunnerUtil::class.java.classLoader, environment.classesToLoadByParent ) ourClassLoaderRef = SoftReference(classLoader) } return classLoader!! } fun invokeExecMethod( compilerClassName: String, arguments: Array<String>, environment: JpsCompilerEnvironment, out: PrintStream ): Any? = withCompilerClassloader(environment) { classLoader -> val compiler = Class.forName(compilerClassName, true, classLoader) val exec = compiler.getMethod( "execAndOutputXml", PrintStream::class.java, Class.forName("org.jetbrains.kotlin.config.Services", true, classLoader), Array<String>::class.java ) exec.invoke(compiler.newInstance(), out, environment.services, arguments) } fun invokeClassesFqNames( environment: JpsCompilerEnvironment, files: Set<File> ): Set<String> = withCompilerClassloader(environment) { classLoader -> val klass = Class.forName("org.jetbrains.kotlin.incremental.parsing.ParseFileUtilsKt", true, classLoader) val method = klass.getMethod("classesFqNames", Set::class.java) @Suppress("UNCHECKED_CAST") method.invoke(klass, files) as? Set<String> } ?: emptySet() private fun <T> withCompilerClassloader( environment: JpsCompilerEnvironment, fn: (ClassLoader) -> T ): T? { val paths = KotlinClassPath.CompilerWithScripting.computeClassPath().let { classPath -> jdkToolsJar?.let { classPath + it } ?: classPath } val classLoader = getOrCreateClassLoader(environment, paths) return fn(classLoader) } }
apache-2.0
cb749d8a4311ba14eeacea87ae1098be
35.333333
158
0.636468
4.804408
false
false
false
false
JetBrains/kotlin-native
backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/ir/interop/cenum/CEnumClassGenerator.kt
1
8783
/* * Copyright 2010-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE file. */ package org.jetbrains.kotlin.backend.konan.ir.interop.cenum import org.jetbrains.kotlin.backend.konan.descriptors.enumEntries import org.jetbrains.kotlin.backend.konan.ir.interop.DescriptorToIrTranslationMixin import org.jetbrains.kotlin.backend.konan.ir.interop.findDeclarationByName import org.jetbrains.kotlin.backend.konan.ir.interop.irInstanceInitializer import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.descriptors.PropertyDescriptor import org.jetbrains.kotlin.descriptors.DescriptorVisibilities import org.jetbrains.kotlin.ir.builders.* import org.jetbrains.kotlin.ir.declarations.* import org.jetbrains.kotlin.ir.descriptors.IrBuiltIns import org.jetbrains.kotlin.ir.expressions.IrExpression import org.jetbrains.kotlin.ir.expressions.impl.IrEnumConstructorCallImpl import org.jetbrains.kotlin.ir.expressions.impl.IrExpressionBodyImpl import org.jetbrains.kotlin.ir.util.* import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi2ir.generators.DeclarationGenerator import org.jetbrains.kotlin.psi2ir.generators.EnumClassMembersGenerator import org.jetbrains.kotlin.psi2ir.generators.GeneratorContext import org.jetbrains.kotlin.resolve.constants.ConstantValue import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult private fun extractConstantValue(descriptor: DeclarationDescriptor, type: String): ConstantValue<*>? = descriptor.annotations .findAnnotation(cEnumEntryValueAnnotationName.child(Name.identifier(type))) ?.allValueArguments ?.getValue(Name.identifier("value")) private val cEnumEntryValueAnnotationName = FqName("kotlinx.cinterop.internal.ConstantValue") private val cEnumEntryValueTypes = setOf( "Byte", "Short", "Int", "Long", "UByte", "UShort", "UInt", "ULong" ) internal class CEnumClassGenerator( val context: GeneratorContext, private val cEnumCompanionGenerator: CEnumCompanionGenerator, private val cEnumVarClassGenerator: CEnumVarClassGenerator ) : DescriptorToIrTranslationMixin { override val irBuiltIns: IrBuiltIns = context.irBuiltIns override val symbolTable: SymbolTable = context.symbolTable override val typeTranslator: TypeTranslator = context.typeTranslator override val postLinkageSteps: MutableList<() -> Unit> = mutableListOf() private val enumClassMembersGenerator = EnumClassMembersGenerator(DeclarationGenerator(context)) /** * Searches for an IR class for [classDescriptor] in symbol table. * Generates one if absent. */ fun findOrGenerateCEnum(classDescriptor: ClassDescriptor, parent: IrDeclarationContainer): IrClass { val irClassSymbol = symbolTable.referenceClass(classDescriptor) return if (!irClassSymbol.isBound) { provideIrClassForCEnum(classDescriptor).also { it.patchDeclarationParents(parent) parent.declarations += it } } else { irClassSymbol.owner } } /** * The main function that for given [descriptor] of the enum generates the whole * IR tree including entries, CEnumVar class, and companion objects. */ private fun provideIrClassForCEnum(descriptor: ClassDescriptor): IrClass = createClass(descriptor) { enumIrClass -> enumIrClass.addMember(createEnumPrimaryConstructor(descriptor)) enumIrClass.addMember(createValueProperty(enumIrClass)) descriptor.enumEntries.mapTo(enumIrClass.declarations) { entryDescriptor -> createEnumEntry(descriptor, entryDescriptor) } enumClassMembersGenerator.generateSpecialMembers(enumIrClass) enumIrClass.addChild(cEnumCompanionGenerator.generate(enumIrClass)) enumIrClass.addChild(cEnumVarClassGenerator.generate(enumIrClass)) } /** * Creates `value` property that stores integral value of the enum. */ private fun createValueProperty(irClass: IrClass): IrProperty { val propertyDescriptor = irClass.descriptor .findDeclarationByName<PropertyDescriptor>("value") ?: error("No `value` property in ${irClass.name}") val irProperty = createProperty(propertyDescriptor) symbolTable.withScope(irProperty) { irProperty.backingField = symbolTable.declareField( SYNTHETIC_OFFSET, SYNTHETIC_OFFSET, IrDeclarationOrigin.PROPERTY_BACKING_FIELD, propertyDescriptor, propertyDescriptor.type.toIrType(), DescriptorVisibilities.PRIVATE ).also { postLinkageSteps.add { it.initializer = irBuilder(irBuiltIns, it.symbol, SYNTHETIC_OFFSET, SYNTHETIC_OFFSET).run { irExprBody(irGet(irClass.primaryConstructor!!.valueParameters[0])) } } } } val getter = irProperty.getter!! getter.correspondingPropertySymbol = irProperty.symbol postLinkageSteps.add { getter.body = irBuilder(irBuiltIns, getter.symbol, SYNTHETIC_OFFSET, SYNTHETIC_OFFSET).irBlockBody { +irReturn( irGetField( irGet(getter.dispatchReceiverParameter!!), irProperty.backingField!! ) ) } } return irProperty } private fun createEnumEntry(enumDescriptor: ClassDescriptor, entryDescriptor: ClassDescriptor): IrEnumEntry { val enumEntry = symbolTable.declareEnumEntry( SYNTHETIC_OFFSET, SYNTHETIC_OFFSET, IrDeclarationOrigin.IR_EXTERNAL_DECLARATION_STUB, entryDescriptor ) val constructorSymbol = symbolTable.referenceConstructor(enumDescriptor.unsubstitutedPrimaryConstructor!!) postLinkageSteps.add { enumEntry.initializerExpression = IrExpressionBodyImpl(IrEnumConstructorCallImpl( SYNTHETIC_OFFSET, SYNTHETIC_OFFSET, type = irBuiltIns.unitType, symbol = constructorSymbol, typeArgumentsCount = 0, valueArgumentsCount = constructorSymbol.owner.valueParameters.size ).also { it.putValueArgument(0, extractEnumEntryValue(entryDescriptor)) }) } return enumEntry } /** * Every enum entry that came from metadata-based interop library is annotated with * [kotlinx.cinterop.internal.ConstantValue] annotation that holds internal constant value of the * corresponding entry. * * This function extracts value from the annotation. */ private fun extractEnumEntryValue(entryDescriptor: ClassDescriptor): IrExpression = cEnumEntryValueTypes.firstNotNullResult { extractConstantValue(entryDescriptor, it) } ?.let { context.constantValueGenerator.generateConstantValueAsExpression(SYNTHETIC_OFFSET, SYNTHETIC_OFFSET, it) } ?: error("Enum entry $entryDescriptor has no appropriate @$cEnumEntryValueAnnotationName annotation!") private fun createEnumPrimaryConstructor(descriptor: ClassDescriptor): IrConstructor { val irConstructor = createConstructor(descriptor.unsubstitutedPrimaryConstructor!!) val enumConstructor = context.builtIns.enum.constructors.single() val constructorSymbol = symbolTable.referenceConstructor(enumConstructor) val classSymbol = symbolTable.referenceClass(descriptor) val type = descriptor.defaultType.toIrType() postLinkageSteps.add { irConstructor.body = irBuilder(irBuiltIns, irConstructor.symbol, SYNTHETIC_OFFSET, SYNTHETIC_OFFSET) .irBlockBody { +IrEnumConstructorCallImpl( startOffset, endOffset, context.irBuiltIns.unitType, constructorSymbol, typeArgumentsCount = 1, // kotlin.Enum<T> has a single type parameter. valueArgumentsCount = constructorSymbol.owner.valueParameters.size ).apply { putTypeArgument(0, type) } +irInstanceInitializer(classSymbol) } } return irConstructor } }
apache-2.0
94e2d48178a5dae903b77eff94e76efc
48.342697
120
0.680861
5.45528
false
false
false
false
jwren/intellij-community
plugins/kotlin/jvm-debugger/test/testData/variables/optimisedVariablesInNestedFunctions.kt
6
1136
package optimisedVariablesInNestedFunctions // ATTACH_LIBRARY: maven(org.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.2) // SHOW_KOTLIN_VARIABLES import kotlinx.coroutines.runBlocking fun main() = runBlocking { fun foo(p: Int) { val a = 1; //Breakpoint! println("") } suspend fun suspendFoo(p: Int) { val a = 1; //Breakpoint! suspendUse(p) //Breakpoint! suspendUse(a) //Breakpoint! println("") } fun bar(p: Int) = //Breakpoint! when (val x = 1) { is Int -> { //Breakpoint! println("") } else -> {} } suspend fun suspendBar(p: Int) = //Breakpoint! when (val x = 1) { is Int -> { //Breakpoint! suspendUse(p) //Breakpoint! suspendUse(x) //Breakpoint! println("") } else -> {} } foo(1) suspendFoo(1) bar(1) suspendBar(1) } suspend fun suspendUse(value: Any) { }
apache-2.0
d6d50faae334b9087a9d56339c5cfdb9
18.929825
77
0.455986
4.270677
false
false
false
false
OnyxDevTools/onyx-database-parent
onyx-database/src/main/kotlin/com/onyx/persistence/query/AttributeUpdate.kt
1
1404
package com.onyx.persistence.query import com.onyx.buffer.BufferStream import com.onyx.buffer.BufferStreamable import com.onyx.descriptor.AttributeDescriptor import com.onyx.interactors.index.IndexInteractor import com.onyx.persistence.manager.PersistenceManager /** * Used to specify what attributes to update. * * * @author Chris Osborn * @since 1.0.0 * * PersistenceManager manager = factory.getPersistenceManager(); // Get the Persistence manager from the persistence manager factory * * Query query = new Query(MyEntity.class, new QueryCriteria("attributeName", QueryCriteriaOperator.EQUAL, "key")); * query.setUpdates(new AttributeUpdate("name", "Bob"); * query.setQueryOrders(new QueryOrder("name", true) * * List results = manager.executeUpdate(query); * * @see com.onyx.persistence.query.Query * * @see PersistenceManager.executeQuery */ @Suppress("UNCHECKED_CAST") class AttributeUpdate @JvmOverloads constructor(var fieldName: String? = null, var value: Any? = null): BufferStreamable { @Transient var attributeDescriptor: AttributeDescriptor? = null @Transient var indexInteractor: IndexInteractor? = null override fun write(buffer: BufferStream) { buffer.putObject(fieldName) buffer.putObject(value) } override fun read(buffer: BufferStream) { fieldName = buffer.value as String value = buffer.value } }
agpl-3.0
7cc9591410f46fd74b5d46e75218c5eb
30.2
132
0.741453
4.241692
false
false
false
false
GunoH/intellij-community
plugins/kotlin/code-insight/line-markers/testData/recursive/propertyAccessors.kt
2
896
class A { var mutable = 0 set(value) { mutable<lineMarker text="Recursive call">++</lineMarker> mutable<lineMarker text="Recursive call">+=</lineMarker>1 mutable <lineMarker text="Recursive call">=</lineMarker> value } var immutable = 0 get() { println("$<lineMarker text="Recursive call">immutable</lineMarker>") immutable<lineMarker text="Recursive call">++</lineMarker> immutable <lineMarker text="Recursive call">+=</lineMarker> 1 return <lineMarker text="Recursive call">immutable</lineMarker> } var simpleGetter = 0 get() = <lineMarker text="Recursive call">simpleGetter</lineMarker> var field = 0 get() { return if (field != 0) field else -1 } set(value) { if (value >= 0) field = value } }
apache-2.0
fc747c1ab2cbc164123bde2e7718ffaf
32.222222
80
0.565848
4.791444
false
false
false
false
GunoH/intellij-community
python/python-features-trainer/src/com/jetbrains/python/ift/lesson/essensial/PythonOnboardingTourLesson.kt
2
23781
// 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.jetbrains.python.ift.lesson.essensial import com.intellij.codeInsight.template.impl.TemplateManagerImpl import com.intellij.execution.RunManager import com.intellij.execution.console.DuplexConsoleListener import com.intellij.execution.console.DuplexConsoleView import com.intellij.execution.ui.UIExperiment import com.intellij.icons.AllIcons import com.intellij.ide.DataManager import com.intellij.ide.actions.searcheverywhere.SearchEverywhereManagerImpl import com.intellij.ide.actions.searcheverywhere.SearchEverywhereUI import com.intellij.ide.ui.UISettings import com.intellij.ide.util.gotoByName.GotoActionModel import com.intellij.idea.ActionsBundle import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.actionSystem.ActionPlaces import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.ex.ActionUtil import com.intellij.openapi.actionSystem.impl.ActionButton import com.intellij.openapi.application.invokeLater import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.diagnostic.thisLogger import com.intellij.openapi.editor.LogicalPosition import com.intellij.openapi.editor.actions.ToggleCaseAction import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.project.Project import com.intellij.openapi.ui.MessageDialogBuilder import com.intellij.openapi.ui.Messages import com.intellij.openapi.ui.popup.Balloon import com.intellij.openapi.util.WindowStateService import com.intellij.openapi.wm.ToolWindowManager import com.intellij.openapi.wm.impl.status.TextPanel import com.intellij.toolWindow.StripeButton import com.intellij.ui.UIBundle import com.intellij.ui.components.fields.ExtendableTextField import com.intellij.ui.components.panels.NonOpaquePanel import com.intellij.ui.tree.TreeVisitor import com.intellij.util.Alarm import com.intellij.util.PlatformUtils import com.intellij.util.ui.UIUtil import com.intellij.util.ui.tree.TreeUtil import com.intellij.xdebugger.XDebuggerManager import com.jetbrains.python.PyBundle import com.jetbrains.python.PyPsiBundle import com.jetbrains.python.ift.PythonLessonsBundle import com.jetbrains.python.ift.PythonLessonsUtil import com.jetbrains.python.sdk.pythonSdk import training.FeaturesTrainerIcons import training.dsl.* import training.dsl.LessonUtil.adjustSearchEverywherePosition import training.dsl.LessonUtil.checkEditorModification import training.dsl.LessonUtil.checkExpectedStateOfEditor import training.dsl.LessonUtil.restoreIfModified import training.dsl.LessonUtil.restoreIfModifiedOrMoved import training.dsl.LessonUtil.restorePopupPosition import training.learn.LearnBundle import training.learn.LessonsBundle import training.learn.course.KLesson import training.learn.course.LessonProperties import training.learn.lesson.LessonManager import training.learn.lesson.general.run.clearBreakpoints import training.learn.lesson.general.run.toggleBreakpointTask import training.project.ProjectUtils import training.ui.LearningUiHighlightingManager import training.ui.LearningUiManager import training.ui.getFeedbackProposedPropertyName import training.util.* import java.awt.Point import java.awt.event.KeyEvent import javax.swing.JTree import javax.swing.JWindow import javax.swing.tree.TreePath class PythonOnboardingTourLesson : KLesson("python.onboarding", PythonLessonsBundle.message("python.onboarding.lesson.name")) { private lateinit var openLearnTaskId: TaskContext.TaskId private var useDelay: Boolean = false private val demoFileName: String = "welcome.py" private val uiSettings get() = UISettings.getInstance() override val properties = LessonProperties( canStartInDumbMode = true, openFileAtStart = false ) override val testScriptProperties = TaskTestContext.TestScriptProperties(skipTesting = true) private var backupPopupLocation: Point? = null private var hideToolStripesPreference = false private var showNavigationBarPreference = true private var usedInterpreterAtStart: String = "undefined" val sample: LessonSample = parseLessonSample(""" def find_average(values)<caret id=3/>: result = 0 for v in values: result += v <caret>return result<caret id=2/> print("AVERAGE", find_average([5,6, 7, 8])) """.trimIndent()) override val lessonContent: LessonContext.() -> Unit = { prepareRuntimeTask { usedInterpreterAtStart = project.pythonSdk?.versionString ?: "none" useDelay = true invokeActionForFocusContext(getActionById("Stop")) val runManager = RunManager.getInstance(project) runManager.allSettings.forEach(runManager::removeConfiguration) val root = ProjectUtils.getCurrentLearningProjectRoot() if (root.findChild(demoFileName) == null) invokeLater { runWriteAction { root.createChildData(this, demoFileName) } } } clearBreakpoints() checkUiSettings() projectTasks() prepareSample(sample, checkSdkConfiguration = false) openLearnToolwindow() sdkConfigurationTasks() showInterpreterConfiguration() waitIndexingTasks() runTasks() debugTasks() completionSteps() waitBeforeContinue(500) contextActions() waitBeforeContinue(500) searchEverywhereTasks() task { text(PythonLessonsBundle.message("python.onboarding.epilog", getCallBackActionId("CloseProject"), LessonUtil.returnToWelcomeScreenRemark(), LearningUiManager.addCallback { LearningUiManager.resetModulesView() })) } } override fun onLessonEnd(project: Project, lessonEndInfo: LessonEndInfo) { val primaryLanguage = module.primaryLanguage if (primaryLanguage == null) { thisLogger().error("Onboarding lesson has no language support for some magical reason") return } PythonLessonsUtil.prepareFeedbackDataForOnboardingLesson( project, getFeedbackProposedPropertyName(primaryLanguage), "PyCharm Onboarding Tour Feedback", "pycharm_onboarding_tour", primaryLanguage, lessonEndInfo, usedInterpreterAtStart, ) restorePopupPosition(project, SearchEverywhereManagerImpl.LOCATION_SETTINGS_KEY, backupPopupLocation) backupPopupLocation = null uiSettings.hideToolStripes = hideToolStripesPreference uiSettings.showNavigationBar = showNavigationBarPreference uiSettings.fireUISettingsChanged() if (!lessonEndInfo.lessonPassed) { LessonUtil.showFeedbackNotification(this, project) return } val dataContextPromise = DataManager.getInstance().dataContextFromFocusAsync invokeLater { val result = MessageDialogBuilder.yesNoCancel(PythonLessonsBundle.message("python.onboarding.finish.title"), PythonLessonsBundle.message("python.onboarding.finish.text", LessonUtil.returnToWelcomeScreenRemark())) .yesText(PythonLessonsBundle.message("python.onboarding.finish.exit")) .noText(PythonLessonsBundle.message("python.onboarding.finish.modules")) .icon(FeaturesTrainerIcons.PluginIcon) .show(project) when (result) { Messages.YES -> invokeLater { LessonManager.instance.stopLesson() val closeAction = getActionById("CloseProject") dataContextPromise.onSuccess { context -> invokeLater { val event = AnActionEvent.createFromAnAction(closeAction, null, ActionPlaces.LEARN_TOOLWINDOW, context) ActionUtil.performActionDumbAwareWithCallbacks(closeAction, event) } } } Messages.NO -> invokeLater { LearningUiManager.resetModulesView() } } if (result != Messages.YES) { LessonUtil.showFeedbackNotification(this, project) } } } private fun getCallBackActionId(@Suppress("SameParameterValue") actionId: String): Int { val action = getActionById(actionId) return LearningUiManager.addCallback { invokeActionForFocusContext(action) } } private fun LessonContext.debugTasks() { clearBreakpoints() var logicalPosition = LogicalPosition(0, 0) prepareRuntimeTask { logicalPosition = editor.offsetToLogicalPosition(sample.startOffset) } caret(sample.startOffset) toggleBreakpointTask(sample, { logicalPosition }, checkLine = false) { text(PythonLessonsBundle.message("python.onboarding.balloon.click.here"), LearningBalloonConfig(Balloon.Position.below, width = 0, duplicateMessage = false)) text(PythonLessonsBundle.message("python.onboarding.toggle.breakpoint.1", code("6.5"), code("find_average"), code("26"))) text(PythonLessonsBundle.message("python.onboarding.toggle.breakpoint.2")) } highlightButtonById("Debug", highlightInside = false, usePulsation = false) actionTask("Debug") { showBalloonOnHighlightingComponent(PythonLessonsBundle.message("python.onboarding.balloon.start.debugging")) restoreState { lineWithBreakpoints() != setOf(logicalPosition.line) } restoreIfModified(sample) PythonLessonsBundle.message("python.onboarding.start.debugging", icon(AllIcons.Actions.StartDebugger)) } highlightDebugActionsToolbar(highlightInside = false, usePulsation = false) task { rehighlightPreviousUi = true gotItStep(Balloon.Position.above, 400, PythonLessonsBundle.message("python.onboarding.balloon.about.debug.panel", strong(UIBundle.message("tool.window.name.debug")), if (UIExperiment.isNewDebuggerUIEnabled()) 0 else 1, strong(LessonsBundle.message("debug.workflow.lesson.name")))) restoreIfModified(sample) } highlightButtonById("Stop", highlightInside = false, usePulsation = false) task { val position = if (UIExperiment.isNewDebuggerUIEnabled()) Balloon.Position.above else Balloon.Position.atRight showBalloonOnHighlightingComponent(PythonLessonsBundle.message("python.onboarding.balloon.stop.debugging"), position) { list -> list.maxByOrNull { it.locationOnScreen.y } } text(PythonLessonsBundle.message("python.onboarding.stop.debugging", icon(AllIcons.Actions.Suspend))) restoreIfModified(sample) addFutureStep { val process = XDebuggerManager.getInstance(project).currentSession?.debugProcess val console = process?.createConsole() as? DuplexConsoleView<*, *> if (console != null) { // When debug process terminates the console tab become activated and brings focus. // So, we need to finish this task only after tab is activated. // And then focus will be returned to editor in the start of completion tasks. console.addSwitchListener(DuplexConsoleListener { completeStep() }, taskDisposable) } else completeStep() } stateCheck { XDebuggerManager.getInstance(project).currentSession == null } } prepareRuntimeTask { LearningUiHighlightingManager.clearHighlights() } } private fun LessonContext.waitIndexingTasks() { task { triggerAndBorderHighlight().component { progress: NonOpaquePanel -> progress.javaClass.name.contains("InlineProgressPanel") } } task { text(PythonLessonsBundle.message("python.onboarding.indexing.description")) waitSmartModeStep() } waitBeforeContinue(300) prepareRuntimeTask { LearningUiHighlightingManager.clearHighlights() } } private fun LessonContext.runTasks() { highlightRunToolbar(highlightInside = false, usePulsation = false) task { triggerUI { clearPreviousHighlights = false }.component { ui: ActionButton -> ActionManager.getInstance().getId(ui.action) == "Run" } } task { val runOptionsText = if (PlatformUtils.isPyCharmCommunity()) { PythonLessonsBundle.message("python.onboarding.run.options.community", icon(AllIcons.Actions.Execute), icon(AllIcons.Actions.StartDebugger)) } else { PythonLessonsBundle.message("python.onboarding.run.options.professional", icon(AllIcons.Actions.Execute), icon(AllIcons.Actions.StartDebugger), icon(AllIcons.Actions.Profile), icon(AllIcons.General.RunWithCoverage)) } text(PythonLessonsBundle.message("python.onboarding.temporary.configuration.description") + " $runOptionsText") text(PythonLessonsBundle.message("python.onboarding.run.sample", icon(AllIcons.Actions.Execute), action("Run"))) text(PythonLessonsBundle.message("python.onboarding.run.sample.balloon", icon(AllIcons.Actions.Execute), action("Run")), LearningBalloonConfig(Balloon.Position.below, 0)) checkToolWindowState("Run", true) restoreIfModified(sample) } } private fun LessonContext.openLearnToolwindow() { task { triggerAndBorderHighlight().component { stripe: StripeButton -> stripe.windowInfo.id == "Learn" } } task { openLearnTaskId = taskId text(PythonLessonsBundle.message("python.onboarding.balloon.open.learn.toolbar", strong(LearnBundle.message("toolwindow.stripe.Learn"))), LearningBalloonConfig(Balloon.Position.atRight, width = 0, duplicateMessage = true)) stateCheck { ToolWindowManager.getInstance(project).getToolWindow("Learn")?.isVisible == true } restoreIfModified(sample) } prepareRuntimeTask { LearningUiHighlightingManager.clearHighlights() requestEditorFocus() } } private fun LessonContext.checkUiSettings() { hideToolStripesPreference = uiSettings.hideToolStripes showNavigationBarPreference = uiSettings.showNavigationBar showInvalidDebugLayoutWarning() if (!hideToolStripesPreference && (showNavigationBarPreference || uiSettings.showMainToolbar)) { // a small hack to have same tasks count. It is needed to track statistics result. task { } task { } return } task { text(PythonLessonsBundle.message("python.onboarding.change.ui.settings")) proceedLink() } prepareRuntimeTask { uiSettings.hideToolStripes = false uiSettings.showNavigationBar = true uiSettings.fireUISettingsChanged() } } private fun LessonContext.projectTasks() { prepareRuntimeTask { LessonUtil.hideStandardToolwindows(project) } task { triggerAndBorderHighlight().component { stripe: StripeButton -> stripe.windowInfo.id == "Project" } } task { var collapsed = false text(PythonLessonsBundle.message("python.onboarding.project.view.description", action("ActivateProjectToolWindow"))) text(PythonLessonsBundle.message("python.onboarding.balloon.project.view"), LearningBalloonConfig(Balloon.Position.atRight, width = 0)) triggerAndBorderHighlight().treeItem { tree: JTree, path: TreePath -> val result = path.pathCount >= 1 && path.getPathComponent(0).isToStringContains("PyCharmLearningProject") if (result) { if (!collapsed) { invokeLater { tree.collapsePath(path) } } collapsed = true } result } } fun isDemoFilePath(path: TreePath) = path.pathCount >= 3 && path.getPathComponent(2).isToStringContains(demoFileName) task { text(PythonLessonsBundle.message("python.onboarding.balloon.project.directory"), LearningBalloonConfig(Balloon.Position.atRight, duplicateMessage = true, width = 0)) triggerAndBorderHighlight().treeItem { _: JTree, path: TreePath -> isDemoFilePath(path) } restoreByUi() } task { text(PythonLessonsBundle.message("python.onboarding.balloon.open.file", strong(demoFileName)), LearningBalloonConfig(Balloon.Position.atRight, duplicateMessage = true, width = 0)) stateCheck l@{ if (FileEditorManager.getInstance(project).selectedTextEditor == null) return@l false virtualFile.name == demoFileName } restoreState { (previous.ui as? JTree)?.takeIf { tree -> TreeUtil.visitVisibleRows(tree, TreeVisitor { path -> if (isDemoFilePath(path)) TreeVisitor.Action.INTERRUPT else TreeVisitor.Action.CONTINUE }) != null }?.isShowing?.not() ?: true } } } private fun LessonContext.completionSteps() { prepareRuntimeTask { setSample(sample.insertAtPosition(2, " / len(<caret>)")) } task { text(PythonLessonsBundle.message("python.onboarding.type.division", code(" / len()"))) text(PythonLessonsBundle.message("python.onboarding.invoke.completion", code("values"), code("()"), action("CodeCompletion"))) triggerAndBorderHighlight().listItem { // no highlighting it.isToStringContains("values") } proposeRestoreForInvalidText("values") } task { text(PythonLessonsBundle.message("python.onboarding.choose.values.item", code("values"), action("EditorChooseLookupItem"))) stateCheck { checkEditorModification(sample, modificationPositionId = 2, needChange = "/len(values)") } restoreByUi() } } private fun LessonContext.contextActions() { val reformatMessage = PyBundle.message("QFIX.reformat.file") caret(",6") task("ShowIntentionActions") { text(PythonLessonsBundle.message("python.onboarding.invoke.intention.for.warning.1")) text(PythonLessonsBundle.message("python.onboarding.invoke.intention.for.warning.2", action(it))) triggerAndBorderHighlight().listItem { item -> item.isToStringContains(reformatMessage) } restoreIfModifiedOrMoved() } task { text(PythonLessonsBundle.message("python.onboarding.select.fix", strong(reformatMessage))) stateCheck { // TODO: make normal check previous.sample.text != editor.document.text } restoreByUi(delayMillis = defaultRestoreDelay) } fun returnTypeMessage(project: Project) = if (PythonLessonsUtil.isPython3Installed(project)) PyPsiBundle.message("INTN.specify.return.type.in.annotation") else PyPsiBundle.message("INTN.specify.return.type.in.docstring") caret("find_average") task("ShowIntentionActions") { text(PythonLessonsBundle.message("python.onboarding.invoke.intention.for.code", code("find_average"), action(it))) triggerAndBorderHighlight().listItem { item -> item.isToStringContains(returnTypeMessage(project)) } restoreIfModifiedOrMoved() } task { text(PythonLessonsBundle.message("python.onboarding.apply.intention", strong(returnTypeMessage(project)), LessonUtil.rawEnter())) stateCheck { val text = editor.document.text previous.sample.text != text && text.contains("object") && !text.contains("values: object") } restoreByUi(delayMillis = defaultRestoreDelay) } task { lateinit var forRestore: LessonSample before { val text = previous.sample.text val toReplace = "object" forRestore = LessonSample(text.replace(toReplace, ""), text.indexOf(toReplace).takeIf { it != -1 } ?: 0) } text(PythonLessonsBundle.message("python.onboarding.complete.template", code("float"), LessonUtil.rawEnter())) stateCheck { // TODO: make normal check val activeTemplate = TemplateManagerImpl.getInstance(project).getActiveTemplate(editor) editor.document.text.contains("float") && activeTemplate == null } proposeRestore { checkExpectedStateOfEditor(forRestore) { "object".contains(it) || "float".contains(it) } } } } private fun LessonContext.searchEverywhereTasks() { val toggleCase = ActionsBundle.message("action.EditorToggleCase.text") caret("AVERAGE", select = true) task("SearchEverywhere") { text(PythonLessonsBundle.message("python.onboarding.invoke.search.everywhere.1", strong(toggleCase), code("AVERAGE"))) text(PythonLessonsBundle.message("python.onboarding.invoke.search.everywhere.2", LessonUtil.rawKeyStroke(KeyEvent.VK_SHIFT), LessonUtil.actionName(it))) triggerAndBorderHighlight().component { ui: ExtendableTextField -> UIUtil.getParentOfType(SearchEverywhereUI::class.java, ui) != null } restoreIfModifiedOrMoved() } task { transparentRestore = true before { if (backupPopupLocation != null) return@before val ui = previous.ui ?: return@before val popupWindow = UIUtil.getParentOfType(JWindow::class.java, ui) ?: return@before val oldPopupLocation = WindowStateService.getInstance(project).getLocation(SearchEverywhereManagerImpl.LOCATION_SETTINGS_KEY) if (adjustSearchEverywherePosition(popupWindow, "8]))") || LessonUtil.adjustPopupPosition(project, popupWindow)) { backupPopupLocation = oldPopupLocation } } text(PythonLessonsBundle.message("python.onboarding.search.everywhere.description", strong("AVERAGE"), strong(PythonLessonsBundle.message("toggle.case.part")))) triggerAndBorderHighlight().listItem { item -> val value = (item as? GotoActionModel.MatchedValue)?.value (value as? GotoActionModel.ActionWrapper)?.action is ToggleCaseAction } restoreByUi() restoreIfModifiedOrMoved() } task { text(PythonLessonsBundle.message("python.onboarding.apply.action", strong(toggleCase), LessonUtil.rawEnter())) stateCheck { editor.document.text.contains("\"average") } restoreByUi(delayMillis = defaultRestoreDelay) } text(PythonLessonsBundle.message("python.onboarding.case.changed")) } private fun LessonContext.showInterpreterConfiguration() { task { addFutureStep { if (useDelay) { Alarm().addRequest({ completeStep() }, 500) } else { completeStep() } } } task { triggerAndBorderHighlight().component { info: TextPanel.WithIconAndArrows -> info.toolTipText.isToStringContains(PyBundle.message("current.interpreter", "")) } } task { before { useDelay = false } text(PythonLessonsBundle.message("python.onboarding.interpreter.description")) gotItStep(Balloon.Position.above, 0, PythonLessonsBundle.message("python.onboarding.interpreter.tip"), duplicateMessage = false) restoreState(restoreId = openLearnTaskId) { learningToolWindow(project)?.isVisible?.not() ?: true } restoreIfModified(sample) } prepareRuntimeTask { LearningUiHighlightingManager.clearHighlights() } } }
apache-2.0
01582209f496789e7eb174a09184a593
37.110577
143
0.693074
5.21742
false
false
false
false
smmribeiro/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/GrExpressionLambdaBodyImpl.kt
5
1398
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.lang.psi.impl import com.intellij.lang.ASTNode import com.intellij.psi.PsiType import com.intellij.psi.util.parentOfType import org.jetbrains.plugins.groovy.lang.psi.GroovyElementVisitor import org.jetbrains.plugins.groovy.lang.psi.api.GrExpressionLambdaBody import org.jetbrains.plugins.groovy.lang.psi.api.GrLambdaExpression import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression import org.jetbrains.plugins.groovy.lang.psi.controlFlow.Instruction import org.jetbrains.plugins.groovy.lang.psi.controlFlow.impl.ControlFlowBuilder class GrExpressionLambdaBodyImpl(node: ASTNode) : GroovyPsiElementImpl(node), GrExpressionLambdaBody { override fun getReturnType(): PsiType? = expression.type override fun getLambdaExpression(): GrLambdaExpression = requireNotNull(parentOfType()) override fun getExpression() : GrExpression = findNotNullChildByClass(GrExpression::class.java) override fun accept(visitor: GroovyElementVisitor) = visitor.visitExpressionLambdaBody(this) override fun toString(): String = "Lambda body" override fun getControlFlow(): Array<Instruction> = ControlFlowBuilder().buildControlFlow(this) override fun isTopControlFlowOwner(): Boolean = true }
apache-2.0
fd478eb9a74bbb356ab90fa473a5e3b7
48.928571
140
0.823319
4.524272
false
false
false
false
nwillc/vplugin
src/main/kotlin/com/github/nwillc/vplugin/VersionsPlugin.kt
1
1876
/* * Copyright (c) 2020, [email protected] * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ package com.github.nwillc.vplugin import org.gradle.api.Plugin import org.gradle.api.Project class VersionsPlugin : Plugin<Project> { @SuppressWarnings("TooGenericExceptionCaught") override fun apply(project: Project) { project.tasks.create(TASK_NAME) { task -> task.group = "help" task.doLast { try { println("\nPlugins") println("=======") versions( project.buildscript.configurations, project.buildscript.repositories, "https://plugins.gradle.org/m2/" ) println("\nDependencies") println("============") versions(project.configurations, project.repositories) print("\n") } catch (e: Exception) { project.logger.error("$TASK_NAME encountered $e") } } } } companion object { const val TASK_NAME = "versions" } }
isc
939d37f18c28a670943593336e1c4288
36.52
75
0.597548
4.810256
false
false
false
false
breadwallet/breadwallet-android
app/src/main/java/com/breadwallet/tools/util/SupportManager.kt
1
10721
/** * BreadWallet * * Created by Mihail Gutan on <[email protected]> 11/5/18. * Copyright (c) 2018 breadwallet LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.breadwallet.tools.util import android.content.ActivityNotFoundException import android.content.Context import android.content.Intent import android.net.Uri import android.os.Build import android.widget.Toast import androidx.core.content.FileProvider import com.breadwallet.BuildConfig import com.breadwallet.app.BreadApp.Companion.generateWalletId import com.breadwallet.breadbox.BreadBox import com.breadwallet.breadbox.isEthereum import com.breadwallet.crypto.Address import com.breadwallet.crypto.TransferState import com.breadwallet.crypto.errors.TransferSubmitPosixError import com.breadwallet.tools.manager.BRSharedPrefs.getBundleHash import com.breadwallet.tools.manager.BRSharedPrefs.getDeviceId import com.breadwallet.tools.manager.BRSharedPrefs.getWalletRewardId import com.breadwallet.tools.security.BrdUserManager import com.breadwallet.tools.security.CryptoUserManager import com.breadwallet.util.pubKeyToEthAddress import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import org.apache.commons.io.IOUtils import java.io.IOException import java.util.Locale import java.util.TimeZone // Filters out our apps events at log level = verbose private const val LOGCAT_COMMAND = "logcat -d ${BuildConfig.APPLICATION_ID}:V" private const val DEFAULT_EMAIL_SUBJECT = "BRD Android App Feedback [ID:%s]" // Placeholder is for a unique id. private const val DEFAULT_EMAIL_BODY = "[Please add your feedback.]" private val DEFAULT_DEBUG_INFO = listOf(DebugInfo.APPLICATION, DebugInfo.DEVICE, DebugInfo.WALLET) private const val DEFAULT_LOG_ATTACHMENT_BODY = "No logs." private const val FAILED_ERROR_MESSAGE = "Failed to get logs." private const val NO_EMAIL_APP_ERROR_MESSAGE = "No email app found." private const val LOGS_FILE_NAME = "Logs.txt" const val CUSTOM_DATA_KEY_TITLE = "title" enum class DebugInfo { DEVICE, WALLET, APPLICATION, CUSTOM } enum class EmailTarget(val address: String) { ANDROID_TEAM("[email protected]"), SUPPORT_TEAM("[email protected]") } class SupportManager( private val context: Context, private val breadBox: BreadBox, private val userManager: BrdUserManager ) { fun submitEmailRequest( to: EmailTarget = EmailTarget.SUPPORT_TEAM, subject: String = String.format(DEFAULT_EMAIL_SUBJECT, getDeviceId()), body: String = DEFAULT_EMAIL_BODY, diagnostics: List<DebugInfo> = DEFAULT_DEBUG_INFO, customData: Map<String, String> = emptyMap(), attachLogs: Boolean = true ) { val emailIntent = createEmailIntent(to.address, subject, body, diagnostics, customData, attachLogs) launchIntent(emailIntent, to.address) } private fun createEmailIntent( to: String, subject: String, body: String, diagnostics: List<DebugInfo>, customData: Map<String, String>, attachLogs: Boolean ) = Intent(Intent.ACTION_SEND).apply { putExtra(Intent.EXTRA_EMAIL, arrayOf(to)) putExtra(Intent.EXTRA_SUBJECT, subject) putExtra(Intent.EXTRA_TEXT, buildBody(body, diagnostics, customData)) if (attachLogs) { addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) putExtra(Intent.EXTRA_STREAM, getLogsUri()) } } private fun launchIntent( emailIntent: Intent, to: String ) { try { context.startActivity( emailIntent.apply { selector = Intent.parseUri("mailto:$to", 0) addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) } ) } catch (e: ActivityNotFoundException) { GlobalScope.launch(Dispatchers.Main) { Toast.makeText(context, NO_EMAIL_APP_ERROR_MESSAGE, Toast.LENGTH_LONG).show() } } } private fun getLogsUri(): Uri { val file = FileHelper.saveToExternalStorage(context, LOGS_FILE_NAME, getLogs()) return FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID, file) } private fun buildBody( bodyText: String, debugInfo: List<DebugInfo>, customData: Map<String, String> ) = buildString { addFeedbackBlock(bodyText) appendln() debugInfo.forEach { debugInfo -> when (debugInfo) { DebugInfo.APPLICATION -> addApplicationBlock() DebugInfo.DEVICE -> addDeviceBlock() DebugInfo.WALLET -> addWalletBlock() DebugInfo.CUSTOM -> addDebugBlock(customData) } appendln() } } private fun getLogs(): String = try { val process = Runtime.getRuntime().exec(LOGCAT_COMMAND) IOUtils.toString(process.inputStream, Charsets.UTF_8) } catch (ex: IOException) { GlobalScope.launch(Dispatchers.Main) { Toast.makeText(context, FAILED_ERROR_MESSAGE, Toast.LENGTH_LONG).show() } DEFAULT_LOG_ATTACHMENT_BODY } private fun StringBuilder.addFeedbackBlock(feedback: String) { appendln("Feedback") appendln("------------") appendln(feedback) } private fun StringBuilder.addApplicationBlock() { appendln("Application (${BuildConfig.BUILD_TYPE})") appendln("------------") appendln("Package: ${BuildConfig.APPLICATION_ID}") appendln("Version: ${BuildConfig.VERSION_NAME} Build ${BuildConfig.BUILD_VERSION}") appendln( if (BuildConfig.BITCOIN_TESTNET) { "Network: Testnet" } else { "Network: Mainnet" } ) for (bundleName in ServerBundlesHelper.getBundleNames()) { appendln("Bundle '$bundleName' version: ${getBundleHash(bundleName)}") } } private fun StringBuilder.addDeviceBlock() { appendln("Device") appendln("------------") appendln("Android Version: ${Build.VERSION.RELEASE}") appendln("Device Model: ${Build.MANUFACTURER} ${Build.MODEL}") appendln("Time Zone: ${TimeZone.getDefault().id}") appendln("Locale: ${Locale.getDefault().displayName}") } private fun StringBuilder.addWalletBlock() { appendln("Wallet") appendln("------------") appendln("Wallet id: ${getWalletRewardId()}") appendln("Device id: ${getDeviceId()}") breadBox.getSystemUnsafe()?.let { system -> system.walletManagers?.forEach { manager -> append("${manager.currency.name}: ") append("mode=${manager.mode.name}, ") append("state=${manager.state.type.name}, ") append("height=${manager.network.height}") appendln() } system.wallets.forEach { wallet -> val count = wallet.transfers.count { transfer -> transfer.state.type == TransferState.Type.SUBMITTED } if (count > 0) { appendln("Submitted ${wallet.currency.code} transfers: $count") } } system.wallets .flatMap { wallet -> wallet.transfers.filter { transfer -> transfer.state.type == TransferState.Type.FAILED && !transfer.confirmation.isPresent } } .forEach { transfer -> val currencyCode = transfer.wallet.currency.code val errorMessage = when (val transferError = transfer.state.failedError.orNull()) { is TransferSubmitPosixError -> { "Posix Error: ${transferError.errnum}, ${transferError.message}" } else -> "Unknown Error ${transferError?.message ?: ""}" } appendln("Failed $currencyCode Transfer: error='$errorMessage'") } if (userManager is CryptoUserManager) { val ethWallet = system.wallets .firstOrNull { wallet -> wallet.currency.isEthereum() } val storedAddress = userManager.getEthPublicKey().pubKeyToEthAddress() if (storedAddress != null && ethWallet != null) { val network = ethWallet.walletManager.network val coreAddress = Address.create(storedAddress, network).orNull()?.toString() val walletAddress = ethWallet.target.toString() if (!walletAddress.equals(coreAddress, true)) { appendln("Stored Address: $storedAddress") appendln("Stored Address Id: ${generateWalletId(storedAddress)}") } } } } } private fun StringBuilder.addDebugBlock(debugData: Map<String, String>) { if (debugData.isEmpty()) return appendln( if (debugData.containsKey(CUSTOM_DATA_KEY_TITLE)) { debugData[CUSTOM_DATA_KEY_TITLE] } else { "Debug" } ) appendln("------------") debugData.entries .filter { !it.key.equals(CUSTOM_DATA_KEY_TITLE) } .forEach { appendln("${it.key} : ${it.value}") } } }
mit
85d66d8d61aadb481055dbaffd69e790
37.426523
111
0.619345
4.748007
false
false
false
false
breadwallet/breadwallet-android
app-core/src/main/java/com/breadwallet/logger/Logger.kt
1
10910
/** * BreadWallet * * Created by Drew Carlson <[email protected]> on 8/13/19. * Copyright (c) 2019 breadwallet LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ @file:Suppress("NOTHING_TO_INLINE") package com.breadwallet.logger import android.os.Build import android.util.Log import com.breadwallet.logger.Logger.Companion import com.breadwallet.logger.Logger.Companion.create import com.breadwallet.logger.Logger.Companion.tag import java.util.logging.Formatter import java.util.logging.Handler import java.util.logging.Level import java.util.logging.LogManager import java.util.logging.LogRecord /** * A simple and instantiable logger with a default implementation * via [Companion]. Loggers can also be produced with a one-time * tag via [tag] or with a permanent manual tag via [create]. * * When a tag is not specified, the calling class name will be used. */ interface Logger { companion object : Logger { private val defaultLogger = DefaultLogger() /** Acquire a default logger that will use [tag] for a single call. */ fun tag(tag: String): Logger = defaultLogger.withTagForCall(tag) /** Create a new logger that will always use [tag]. */ fun create(tag: String): Logger = DefaultLogger(tag) override fun verbose(message: String, vararg data: Any?) = defaultLogger.verbose(message, *data) override fun debug(message: String, vararg data: Any?) = defaultLogger.debug(message, *data) override fun info(message: String, vararg data: Any?) = defaultLogger.info(message, *data) override fun warning(message: String, vararg data: Any?) = defaultLogger.warning(message, *data) override fun error(message: String, vararg data: Any?) = defaultLogger.error(message, *data) override fun wtf(message: String, vararg data: Any?) = defaultLogger.wtf(message, *data) fun setJulLevel(level: Level) { defaultLogger.initialize(level) } } /** Log verbose [message] and any [data] objects. */ fun verbose(message: String, vararg data: Any?) /** Log debug [message] and any [data] objects. */ fun debug(message: String, vararg data: Any?) /** Log info [message] and any [data] objects. */ fun info(message: String, vararg data: Any?) /** Log warning [message] and any [data] objects. */ fun warning(message: String, vararg data: Any?) /** Log error [message] and any [data] objects. */ fun error(message: String, vararg data: Any?) /** Log wtf [message] and any [data] objects. */ fun wtf(message: String, vararg data: Any?) } /** Log verbose [message] and any [data] objects. */ inline fun logVerbose(message: String, vararg data: Any?) = Logger.verbose(message, *data) /** Log debug [message] and any [data] objects. */ inline fun logDebug(message: String, vararg data: Any?) = Logger.debug(message, *data) /** Log info [message] and any [data] objects. */ inline fun logInfo(message: String, vararg data: Any?) = Logger.info(message, *data) /** Log warning [message] and any [data] objects. */ inline fun logWarning(message: String, vararg data: Any?) = Logger.warning(message, *data) /** Log error [message] and any [data] objects. */ inline fun logError(message: String, vararg data: Any?) = Logger.error(message, *data) /** Log wtf [message] and any [data] objects. */ inline fun logWtf(message: String, vararg data: Any?) = Logger.wtf(message, *data) /** A default [Logger] implementation for use on Android. */ private class DefaultLogger( /** Used instead of looking up the calling element's name. */ private val manualTag: String? = null ) : Handler(), Logger { companion object { /** Max character count for Logcat tags below Android N. */ private const val MAX_TAG_LENGTH = 23 /** Pattern matching anonymous class name. */ private val ANONYMOUS_CLASS = "(\\$\\d+)+$".toPattern() } private val recordFormatter = object : Formatter() { override fun format(record: LogRecord): String = buildString { appendLine(record.message) record.thrown ?.run(Log::getStackTraceString) ?.run(::appendLine) } } init { formatter = recordFormatter initialize() } internal fun initialize(minimumLevel: Level = Level.INFO) { LogManager.getLogManager().reset() java.util.logging.Logger.getLogger("").apply { addHandler(this@DefaultLogger) level = minimumLevel } } /** Holds a tag that will be used once after [withTagForCall]. */ private val overrideTag = ThreadLocal<String>() /** Get the expected tag name for a given log call. */ private val nextTag: String? get() { val tag = overrideTag.get() if (tag != null) { overrideTag.remove() return tag } return manualTag ?: Throwable().stackTrace .first { it.className !in ignoredStackClassNames } .asTag() } /** A list of class names to filter when searching for the calling element name. */ private val ignoredStackClassNames = listOf( DefaultLogger::class.java.name, Logger::class.java.name, Logger.Companion::class.java.name ) /** Set the tag to use for the next log call. */ fun withTagForCall(tag: String): DefaultLogger { overrideTag.set(tag) return this } override fun verbose(message: String, vararg data: Any?) = logWith({ tag, _message, error -> when (error) { null -> Log.v(tag, _message) else -> Log.v(tag, _message, error) } }, message, data) override fun debug(message: String, vararg data: Any?) = logWith({ tag, _message, error -> when (error) { null -> Log.d(tag, _message) else -> Log.d(tag, _message, error) } }, message, data) override fun info(message: String, vararg data: Any?) = logWith({ tag, _message, error -> when (error) { null -> Log.i(tag, _message) else -> Log.i(tag, _message, error) } }, message, data) override fun warning(message: String, vararg data: Any?) = logWith({ tag, _message, error -> when (error) { null -> Log.w(tag, _message) else -> Log.w(tag, _message, error) } }, message, data) override fun error(message: String, vararg data: Any?) = logWith({ tag, _message, error -> when (error) { null -> Log.e(tag, _message) else -> Log.e(tag, _message, error) } }, message, data) override fun wtf(message: String, vararg data: Any?) = logWith({ tag, _message, error -> when (error) { null -> Log.wtf(tag, _message) else -> Log.wtf(tag, _message, error) } }, message, data) /** Logs [message] and [data] objects using [logFunc]. */ private inline fun logWith( crossinline logFunc: ( @ParameterName("tag") String?, @ParameterName("_message") String, @ParameterName("error") Throwable? ) -> Unit, message: String, data: Array<out Any?> ) { val tag = nextTag if (data.isEmpty()) logFunc(tag, message, null) else { val hadException = when (val first = data.first()) { is Throwable -> { logFunc(tag, message, first) true } else -> { logFunc(tag, message, null) false } } data.drop(if (hadException) 1 else 0) .forEachIndexed { index, obj -> logFunc(tag, "\tData ${index + 1}:", null) logFunc(tag, "\t\t$obj", null) } } } /** * Returns a tag or null using [StackTraceElement.getClassName] * removing anonymous class name suffix and trimming to 23 * characters when below Android N. */ private fun StackTraceElement.asTag(): String? { return className.substringAfterLast('.') .let { val tag = ANONYMOUS_CLASS.matcher(it) .run { if (find()) replaceAll("") else it } if (tag.length <= MAX_TAG_LENGTH || Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { tag } else { tag.take(MAX_TAG_LENGTH) } } } override fun publish(record: LogRecord) { val julInt = level.intValue() val priority = when { julInt >= Level.SEVERE.intValue() -> Log.ERROR julInt >= Level.WARNING.intValue() -> Log.WARN julInt >= Level.INFO.intValue() -> Log.INFO else -> Log.DEBUG } val tag = record.loggerName .substringAfterLast('.') .takeLast(MAX_TAG_LENGTH) try { Log.println(priority, tag, formatter.format(record)) } catch (e: RuntimeException) { error("Failed to print log record", e) } } override fun flush() = Unit override fun close() = Unit }
mit
220b995084e03229e593c232d746cf23
36.491409
105
0.578093
4.433157
false
false
false
false
orgzly/orgzly-android
app/src/main/java/com/orgzly/android/reminders/NoteReminders.kt
1
5104
package com.orgzly.android.reminders import android.content.Context import com.orgzly.android.data.DataRepository import com.orgzly.android.db.dao.ReminderTimeDao import com.orgzly.android.db.dao.ReminderTimeDao.NoteTime import com.orgzly.android.prefs.AppPreferences import com.orgzly.org.datetime.OrgDateTime import com.orgzly.org.datetime.OrgDateTimeUtils import com.orgzly.org.datetime.OrgInterval import org.joda.time.DateTime import org.joda.time.ReadableInstant import java.util.* object NoteReminders { // private val TAG: String = NoteReminders::class.java.name const val INTERVAL_FROM_LAST_TO_NOW = 1 const val INTERVAL_FROM_NOW = 2 @JvmStatic fun getNoteReminders( context: Context, dataRepository: DataRepository, now: ReadableInstant, lastRun: LastRun, intervalType: Int): List<NoteReminder> { val result: MutableList<NoteReminder> = ArrayList() for (noteTime in dataRepository.times()) { if (isRelevantNoteTime(context, noteTime)) { val orgDateTime = OrgDateTime.parse(noteTime.orgTimestampString) val interval = intervalToConsider(intervalType, now, lastRun, noteTime.timeType) // Deadline warning period val warningPeriod = if (isWarningPeriodSupported(noteTime)) { if (orgDateTime.hasDelay()) { orgDateTime.delay as OrgInterval } else { // TODO: Use default from user preference // OrgInterval(1, OrgInterval.Unit.DAY) null } } else { null } val time = getFirstTime( orgDateTime, interval, AppPreferences.reminderDailyTime(context), warningPeriod ) // if (BuildConfig.LOG_DEBUG) { // LogUtils.d(TAG, // "Note's time", noteTime, // "Interval", interval, // "Found first time", time) // } if (time != null) { val payload = NoteReminderPayload( noteTime.noteId, noteTime.bookId, noteTime.bookName, noteTime.title, noteTime.timeType, orgDateTime) result.add(NoteReminder(time, payload)) } } } // Sort by time, older first result.sortWith { o1, o2 -> o1.runTime.compareTo(o2.runTime) } return result } fun isRelevantNoteTime(context: Context, noteTime: NoteTime): Boolean { val doneStateKeywords = AppPreferences.doneKeywordsSet(context) val isDone = doneStateKeywords.contains(noteTime.state) val isEnabled = AppPreferences.remindersForScheduledEnabled(context) && noteTime.timeType == ReminderTimeDao.SCHEDULED_TIME || AppPreferences.remindersForDeadlineEnabled(context) && noteTime.timeType == ReminderTimeDao.DEADLINE_TIME || AppPreferences.remindersForEventsEnabled(context) && noteTime.timeType == ReminderTimeDao.EVENT_TIME return isEnabled && !isDone } private fun isWarningPeriodSupported(noteTime: NoteTime): Boolean { return noteTime.timeType == ReminderTimeDao.DEADLINE_TIME || noteTime.timeType == ReminderTimeDao.EVENT_TIME } private fun intervalToConsider( intervalType: Int, now: ReadableInstant, lastRun: LastRun, timeType: Int ): Pair<ReadableInstant, ReadableInstant?> { when (intervalType) { INTERVAL_FROM_LAST_TO_NOW -> { val from = when (timeType) { ReminderTimeDao.SCHEDULED_TIME -> { lastRun.scheduled } ReminderTimeDao.DEADLINE_TIME -> { lastRun.deadline } else -> { lastRun.event } } return Pair(from ?: now, now) } INTERVAL_FROM_NOW -> { return Pair(now, null) } else -> throw IllegalArgumentException("Before or after now?") } } private fun getFirstTime( orgDateTime: OrgDateTime, interval: Pair<ReadableInstant, ReadableInstant?>, defaultTimeOfDay: Int, warningPeriod: OrgInterval?): DateTime? { val times = OrgDateTimeUtils.getTimesInInterval( orgDateTime, interval.first, interval.second, defaultTimeOfDay, false, // Do not use repeater for reminders warningPeriod, 1) return times.firstOrNull() } }
gpl-3.0
e41d74dc29ff571d4e9531aa362f69cf
32.807947
96
0.547806
5.119358
false
false
false
false
hazuki0x0/YuzuBrowser
legacy/src/test/java/jp/hazuki/yuzubrowser/legacy/action/item/OpenOptionsMenuActionTest.kt
1
2389
/* * Copyright (C) 2017-2019 Hazuki * * 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 jp.hazuki.yuzubrowser.legacy.action.item import assertk.assertThat import assertk.assertions.isEqualTo import com.squareup.moshi.JsonReader import com.squareup.moshi.JsonWriter import jp.hazuki.yuzubrowser.legacy.pickValue import okio.buffer import okio.sink import okio.source import org.junit.Test import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream class OpenOptionsMenuActionTest { @Test fun testZeroDecodeEncode() { val fiftyJson = """{"0":0}""" val trueReader = JsonReader.of(ByteArrayInputStream(fiftyJson.toByteArray()).source().buffer()) val trueAction = OpenOptionsMenuAction(0, trueReader) assertThat(trueAction.pickValue<Int>("showMode")).isEqualTo(0) assertThat(trueReader.peek()).isEqualTo(JsonReader.Token.END_DOCUMENT) val os = ByteArrayOutputStream() val writer = JsonWriter.of(os.sink().buffer()) writer.beginArray() trueAction.writeIdAndData(writer) writer.endArray() writer.flush() assertThat(os.toString()).isEqualTo("""[0,{"0":0}]""") } @Test fun testTwoDecodeEncode() { val fiftyJson = """{"0":2}""" val trueReader = JsonReader.of(ByteArrayInputStream(fiftyJson.toByteArray()).source().buffer()) val trueAction = OpenOptionsMenuAction(0, trueReader) assertThat(trueAction.pickValue<Int>("showMode")).isEqualTo(2) assertThat(trueReader.peek()).isEqualTo(JsonReader.Token.END_DOCUMENT) val os = ByteArrayOutputStream() val writer = JsonWriter.of(os.sink().buffer()) writer.beginArray() trueAction.writeIdAndData(writer) writer.endArray() writer.flush() assertThat(os.toString()).isEqualTo("""[0,{"0":2}]""") } }
apache-2.0
4b5ee514dbc33b2e4984d37aef51a6f9
32.194444
103
0.697781
4.327899
false
true
false
false
EMResearch/EvoMaster
core/src/main/kotlin/org/evomaster/core/search/gene/datetime/TimeGene.kt
1
8220
package org.evomaster.core.search.gene.datetime import org.evomaster.core.logging.LoggingUtil import org.evomaster.core.output.OutputFormat import org.evomaster.core.search.gene.* import org.evomaster.core.search.gene.numeric.IntegerGene import org.evomaster.core.search.gene.root.CompositeFixedGene import org.evomaster.core.search.gene.string.StringGene import org.evomaster.core.search.gene.utils.GeneUtils import org.evomaster.core.search.impact.impactinfocollection.GeneImpact import org.evomaster.core.search.impact.impactinfocollection.value.date.TimeGeneImpact import org.evomaster.core.search.service.Randomness import org.evomaster.core.search.service.mutator.MutationWeightControl import org.evomaster.core.search.service.mutator.genemutation.AdditionalGeneMutationInfo import org.evomaster.core.search.service.mutator.genemutation.SubsetGeneMutationSelectionStrategy import org.slf4j.Logger import org.slf4j.LoggerFactory /** * Using RFC3339 * * https://xml2rfc.tools.ietf.org/public/rfc/html/rfc3339.html#anchor14 */ class TimeGene( name: String, //note: ranges deliberately include wrong values. val hour: IntegerGene = IntegerGene("hour", 0, MIN_HOUR, MAX_HOUR), val minute: IntegerGene = IntegerGene("minute", 0, MIN_MINUTE, MAX_MINUTE), val second: IntegerGene = IntegerGene("second", 0, MIN_SECOND, MAX_SECOND), val timeGeneFormat: TimeGeneFormat = TimeGeneFormat.TIME_WITH_MILLISECONDS ) : Comparable<TimeGene>, CompositeFixedGene(name, listOf(hour, minute, second)) { companion object { val log: Logger = LoggerFactory.getLogger(TimeGene::class.java) const val MAX_HOUR = 25 const val MIN_HOUR = -1 const val MAX_MINUTE = 60 const val MIN_MINUTE = -1 const val MAX_SECOND = 60 const val MIN_SECOND = -1 val TIME_GENE_COMPARATOR: Comparator<TimeGene> = Comparator .comparing(TimeGene::hour) .thenBy(TimeGene::minute) .thenBy(TimeGene::second) } enum class TimeGeneFormat { // format HH:MM:SS ISO_LOCAL_DATE_FORMAT, // HH:MM:SS.000Z TIME_WITH_MILLISECONDS } override fun isLocallyValid() : Boolean{ return getViewOfChildren().all { it.isLocallyValid() } } /* Note: would need to handle timezone and second fractions, but not sure how important for testing purposes */ override fun copyContent(): Gene = TimeGene( name, hour.copy() as IntegerGene, minute.copy() as IntegerGene, second.copy() as IntegerGene, timeGeneFormat = this.timeGeneFormat ) override fun randomize(randomness: Randomness, tryToForceNewValue: Boolean) { hour.randomize(randomness, tryToForceNewValue) minute.randomize(randomness, tryToForceNewValue) second.randomize(randomness, tryToForceNewValue) } override fun adaptiveSelectSubsetToMutate( randomness: Randomness, internalGenes: List<Gene>, mwc: MutationWeightControl, additionalGeneMutationInfo: AdditionalGeneMutationInfo ): List<Pair<Gene, AdditionalGeneMutationInfo?>> { if (additionalGeneMutationInfo.impact != null && additionalGeneMutationInfo.impact is TimeGeneImpact) { val maps = mapOf<Gene, GeneImpact>( hour to additionalGeneMutationInfo.impact.hourGeneImpact, minute to additionalGeneMutationInfo.impact.minuteGeneImpact, second to additionalGeneMutationInfo.impact.secondGeneImpact ) return mwc.selectSubGene( internalGenes, adaptiveWeight = true, targets = additionalGeneMutationInfo.targets, impacts = internalGenes.map { i -> maps.getValue(i) }, individual = null, evi = additionalGeneMutationInfo.evi ) .map { it to additionalGeneMutationInfo.copyFoInnerGene(maps.getValue(it), it) } } throw IllegalArgumentException("impact is null or not TimeGeneImpact") } override fun getValueAsPrintableString( previousGenes: List<Gene>, mode: GeneUtils.EscapeMode?, targetFormat: OutputFormat?, extraCheck: Boolean ): String { return "\"${getValueAsRawString()}\"" } override fun getValueAsRawString(): String { return when (timeGeneFormat) { TimeGeneFormat.ISO_LOCAL_DATE_FORMAT -> { GeneUtils.let { "${GeneUtils.padded(hour.value, 2)}:${ GeneUtils.padded( minute.value, 2 ) }:${GeneUtils.padded(second.value, 2)}" } } TimeGeneFormat.TIME_WITH_MILLISECONDS -> { GeneUtils.let { "${GeneUtils.padded(hour.value, 2)}:${ GeneUtils.padded( minute.value, 2 ) }:${GeneUtils.padded(second.value, 2)}.000Z" } } } } override fun copyValueFrom(other: Gene) { if (other !is TimeGene) { throw IllegalArgumentException("Invalid gene type ${other.javaClass}") } this.hour.copyValueFrom(other.hour) this.minute.copyValueFrom(other.minute) this.second.copyValueFrom(other.second) } override fun containsSameValueAs(other: Gene): Boolean { if (other !is TimeGene) { throw IllegalArgumentException("Invalid gene type ${other.javaClass}") } return this.hour.containsSameValueAs(other.hour) && this.minute.containsSameValueAs(other.minute) && this.second.containsSameValueAs(other.second) } private fun isValidHourRange(gene: IntegerGene): Boolean { return gene.min == 0 && gene.max == 23 } private fun isValidMinuteRange(gene: IntegerGene): Boolean { return gene.min == 0 && gene.max == 59 } private fun isValidSecondRange(gene: IntegerGene): Boolean { return gene.min == 0 && gene.max == 59 } /** * Queries the time gent to know if it can * store only valid hours (i.e. range 00:00:00 to 23:59:59) */ val onlyValidHours: Boolean get() = isValidHourRange(this.hour) && isValidMinuteRange(this.minute) && isValidSecondRange(this.second) override fun bindValueBasedOn(gene: Gene): Boolean { return when { gene is TimeGene -> { hour.bindValueBasedOn(gene.hour) && second.bindValueBasedOn(gene.minute) && minute.bindValueBasedOn(gene.second) } gene is DateTimeGene -> bindValueBasedOn(gene.time) gene is StringGene && gene.getSpecializationGene() != null -> bindValueBasedOn(gene.getSpecializationGene()!!) gene is SeededGene<*> -> this.bindValueBasedOn(gene.getPhenotype() as Gene) else -> { LoggingUtil.uniqueWarn(log, "cannot bind TimeGene with ${gene::class.java.simpleName}") false } } } override fun repair() { if (hour.value < 0) { hour.value = 0 } else if (hour.value > 23) { hour.value = 23 } if (minute.value < 0) { minute.value = 0 } else if (minute.value > 59) { minute.value = 59 } if (second.value < 0) { second.value = 0 } else if (second.value > 59) { second.value = 59 } } override fun compareTo(other: TimeGene): Int { return TIME_GENE_COMPARATOR.compare(this, other) } override fun customShouldApplyShallowMutation( randomness: Randomness, selectionStrategy: SubsetGeneMutationSelectionStrategy, enableAdaptiveGeneMutation: Boolean, additionalGeneMutationInfo: AdditionalGeneMutationInfo? ): Boolean { return false } }
lgpl-3.0
bb3a23d3e54de3748a8444a81cf4d0c7
33.687764
122
0.616423
4.829612
false
false
false
false
EMResearch/EvoMaster
core/src/main/kotlin/org/evomaster/core/problem/rpc/RPCIndividual.kt
1
4742
package org.evomaster.core.problem.rpc import org.evomaster.core.Lazy import org.evomaster.core.database.DbAction import org.evomaster.core.database.DbActionUtils import org.evomaster.core.problem.api.service.ApiWsIndividual import org.evomaster.core.problem.enterprise.EnterpriseActionGroup import org.evomaster.core.problem.external.service.ApiExternalServiceAction import org.evomaster.core.search.* import org.evomaster.core.search.gene.Gene import org.evomaster.core.search.tracer.TrackOperator import kotlin.math.max /** * individual for RPC service */ class RPCIndividual( trackOperator: TrackOperator? = null, index: Int = -1, allActions: MutableList<ActionComponent>, mainSize: Int = allActions.size, dbSize: Int = 0, groups: GroupsOfChildren<StructuralElement> = getEnterpriseTopGroups(allActions, mainSize, dbSize) ) : ApiWsIndividual( trackOperator, index, allActions, childTypeVerifier = { EnterpriseActionGroup::class.java.isAssignableFrom(it) || DbAction::class.java.isAssignableFrom(it) }, groups ) { constructor( actions: MutableList<RPCCallAction>, externalServicesActions: MutableList<List<ApiExternalServiceAction>> = mutableListOf(), /* TODO might add sample type here as REST (check later) */ dbInitialization: MutableList<DbAction> = mutableListOf(), trackOperator: TrackOperator? = null, index: Int = -1 ) : this( trackOperator = trackOperator, index = index, allActions = mutableListOf<ActionComponent>().apply { addAll(dbInitialization); addAll(actions.mapIndexed { index, rpcCallAction -> if (externalServicesActions.isNotEmpty()) Lazy.assert { actions.size == externalServicesActions.size } EnterpriseActionGroup(mutableListOf(rpcCallAction), RPCCallAction::class.java).apply { addChildrenToGroup( externalServicesActions[index], GroupsOfChildren.EXTERNAL_SERVICES ) }}) }, mainSize = actions.size, dbSize = dbInitialization.size) /** * TODO: Verify the implementation */ override fun seeGenes(filter: GeneFilter): List<out Gene> { return when (filter) { GeneFilter.ALL -> seeAllActions().flatMap(Action::seeTopGenes) GeneFilter.NO_SQL -> seeActions(ActionFilter.NO_SQL).flatMap(Action::seeTopGenes) GeneFilter.ONLY_SQL -> seeDbActions().flatMap(DbAction::seeTopGenes) GeneFilter.ONLY_EXTERNAL_SERVICE -> seeExternalServiceActions().flatMap(ApiExternalServiceAction::seeTopGenes) } } override fun size(): Int { return seeMainExecutableActions().size } override fun canMutateStructure(): Boolean = true fun seeIndexedRPCCalls(): Map<Int, RPCCallAction> = getIndexedChildren(RPCCallAction::class.java) override fun verifyInitializationActions(): Boolean { return DbActionUtils.verifyActions(seeInitializingActions().filterIsInstance<DbAction>()) } /** * add an action (ie, [action]) into [actions] at [position] */ fun addAction(relativePosition: Int = -1, action: RPCCallAction) { val main = GroupsOfChildren.MAIN val g = EnterpriseActionGroup(mutableListOf(action), RPCCallAction::class.java) if (relativePosition == -1) { addChildToGroup(g, main) } else{ val base = groupsView()!!.startIndexForGroupInsertionInclusive(main) val position = base + relativePosition addChildToGroup(position, action, main) } } /** * remove an action from [actions] at [position] */ fun removeAction(position: Int) { val removed = (killChildByIndex(getFirstIndexOfEnterpriseActionGroup() + position) as EnterpriseActionGroup).getMainAction() removed.removeThisFromItsBindingGenes() } private fun getFirstIndexOfEnterpriseActionGroup() = max(0, max(children.indexOfLast { it is DbAction }+1, children.indexOfFirst { it is EnterpriseActionGroup })) override fun copyContent(): Individual { return RPCIndividual( trackOperator, index, children.map { it.copy() }.toMutableList() as MutableList<ActionComponent>, mainSize = groupsView()!!.sizeOfGroup(GroupsOfChildren.MAIN), dbSize = groupsView()!!.sizeOfGroup(GroupsOfChildren.INITIALIZATION_SQL) ) } override fun seeMainExecutableActions(): List<RPCCallAction> { return super.seeMainExecutableActions() as List<RPCCallAction> } }
lgpl-3.0
04d48571573415c9cffe9d2c11f58ba5
36.944
166
0.671236
4.780242
false
false
false
false
kpspemu/kpspemu
src/commonMain/kotlin/com/soywiz/dynarek2/target/x64/X64.kt
1
11115
package com.soywiz.dynarek2.target.x64 import com.soywiz.dynarek2.* // typealias D2KFunc = (regs: D2Memory?, mem: D2Memory?, temps: D2Memory?, external: Any?) -> Int // RAX: <result> ///////////////////////// class X64ABI( val windows: Boolean, val args: Array<Reg64>, val xmmArgs: Array<RegXmm>, val preserved: Array<Reg64>, val xmmPreserved: Array<RegXmm> ) { companion object { // Microsoft x64 ABI (Windows) // https://en.wikipedia.org/wiki/X86_calling_conventions#Microsoft_x64_calling_convention val Microsoft = X64ABI( windows = true, args = arrayOf(Reg64.RCX, Reg64.RDX, Reg64.R8, Reg64.R9), xmmArgs = arrayOf(RegXmm.XMM0, RegXmm.XMM1, RegXmm.XMM2, RegXmm.XMM3), preserved = arrayOf(Reg64.RBX, Reg64.RBP, Reg64.RDI, Reg64.RSI, Reg64.RSP), xmmPreserved = arrayOf(RegXmm.XMM6, RegXmm.XMM7) ) // System V AMD64 ABI (Solaris, Linux, FreeBSD, macOS) // https://en.wikipedia.org/wiki/X86_calling_conventions#System_V_AMD64_ABI val SystemV = X64ABI( windows = false, args = arrayOf(Reg64.RDI, Reg64.RSI, Reg64.RDX, Reg64.RCX), xmmArgs = arrayOf(RegXmm.XMM0, RegXmm.XMM1, RegXmm.XMM2, RegXmm.XMM3), preserved = arrayOf(Reg64.RBP, Reg64.RBX), xmmPreserved = arrayOf() ) } } class Dynarek2X64Gen( val context: D2Context, val name: String?, val debug: Boolean, val abi: X64ABI = if (isNativeWindows) X64ABI.Microsoft else X64ABI.SystemV ) : X64Builder() { val REGS_IDX = 0 val MEM_IDX = 1 val TEMPS_IDX = 2 val EXT_IDX = 3 val ABI_ARGS get() = abi.args val PRESERVED_ARGS get() = abi.preserved val REGS_ARG = ABI_ARGS[0] val MEM_ARG = ABI_ARGS[1] val TEMP_ARG = ABI_ARGS[2] val EXT_ARG = ABI_ARGS[3] var allocatedFrame = 0 var frameStackPos = 0 fun pushRegisterInFrame(reg: Reg64): Int { writeMem(reg, Reg64.RBP, -8 - (frameStackPos * 8)) frameStackPos++ if (frameStackPos >= allocatedFrame) error("FRAME TOO BIG") return frameStackPos - 1 } fun pushRegisterInFrame(reg: RegXmm): Int { writeMem(reg, Reg64.RBP, -8 - (frameStackPos * 8)) frameStackPos++ if (frameStackPos >= allocatedFrame) error("FRAME TOO BIG") return frameStackPos - 1 } fun popRegisterInFrame(reg: Reg64) { frameStackPos-- readMem(reg, Reg64.RBP, -8 - (frameStackPos * 8)) } fun popRegisterInFrame(reg: RegXmm) { frameStackPos-- readMem(reg, Reg64.RBP, -8 - (frameStackPos * 8)) } fun getFrameItem(reg: Reg64, index: Int) { readMem(reg, Reg64.RBP, -8 - (index * 8)) } fun getFrameItem(reg: RegXmm, index: Int) { readMem(reg, Reg64.RBP, -8 - (index * 8)) } fun setFrameItem(reg: Reg64, index: Int) { writeMem(reg, Reg64.RBP, -8 - (index * 8)) } fun setFrameItem(reg: RegXmm, index: Int) { writeMem(reg, Reg64.RBP, -8 - (index * 8)) } fun restoreArgs() { for ((index, reg) in ABI_ARGS.withIndex()) getFrameItem(reg, index) } fun restoreArg(reg: Reg64, index: Int) { getFrameItem(reg, index) } // @TODO: Support different ABIs private var rbxIndex = -1 private var rsiIndex = -1 private var rdiIndex = -1 private fun prefix() { push(Reg64.RBP) mov(Reg64.RBP, Reg64.RSP) sub(Reg64.RSP, 512) allocatedFrame = 512 for (reg in ABI_ARGS) pushRegisterInFrame(reg) // This should support both supported ABIs rbxIndex = pushRegisterInFrame(Reg64.RBX) if (abi.windows) { rsiIndex = pushRegisterInFrame(Reg64.RSI) rdiIndex = pushRegisterInFrame(Reg64.RDI) } } private fun doReturn() { // This should support both supported ABIs restoreArg(Reg64.RBX, rbxIndex) if (abi.windows) { restoreArg(Reg64.RSI, rsiIndex) restoreArg(Reg64.RDI, rdiIndex) } mov(Reg64.RSP, Reg64.RBP) pop(Reg64.RBP) retn() } fun generateDummy(): ByteArray { mov(Reg32.EAX, 123456) retn() return getBytes() } fun generate(func: D2Func): ByteArray { prefix() func.body.generate() doReturn() // GUARD in the case a return is missing return getBytes() } fun D2Expr.Ref<*>.loadAddress(): Int { offset.generate() popRegisterInFrame(Reg64.RDX) movEax(size.bytes) mul(Reg32.EDX) restoreArg(Reg64.RDX, memSlot.index) add(Reg64.RAX, Reg64.RDX) return pushRegisterInFrame(Reg64.RAX) } fun D2Stm.generate(): Unit { subframe { when (this) { is D2Stm.Stms -> { for (child in children) child.generate() } is D2Stm.BExpr -> { subframe { expr.generate() popRegisterInFrame(Reg64.RAX) if (this is D2Stm.Return) { doReturn() } } } is D2Stm.Set<*> -> { val memSlot = ref.memSlot val offset = ref.offset val size = ref.size val foffset = if (offset is D2Expr.ILit) { val valueIndex = value.generate() getFrameItem(Reg64.RDX, valueIndex) restoreArg(Reg64.RDI, memSlot.index) offset.lit * size.bytes } else { val offsetIndex = ref.loadAddress() val valueIndex = value.generate() restoreArg(Reg64.RDI, offsetIndex) restoreArg(Reg64.RDX, valueIndex) 0 } when (size) { D2Size.BYTE -> writeMem(Reg8.DL, Reg64.RDI, foffset) D2Size.SHORT -> writeMem(Reg16.DX, Reg64.RDI, foffset) D2Size.INT, D2Size.FLOAT -> writeMem(Reg32.EDX, Reg64.RDI, foffset) D2Size.LONG -> TODO("$size") } } is D2Stm.If -> { if (sfalse == null) { // IF val endLabel = Label() generateJumpFalse(cond, endLabel) strue.generate() place(endLabel) } else { // IF+ELSE val elseLabel = Label() val endLabel = Label() generateJumpFalse(cond, elseLabel) strue.generate() generateJumpAlways(endLabel) place(elseLabel) sfalse?.generate() place(endLabel) } } is D2Stm.While -> { val startLabel = Label() val endLabel = Label() place(startLabel) generateJumpFalse(cond, endLabel) body.generate() generateJumpAlways(startLabel) place(endLabel) } } } } //companion object { // val SHL_NAME = D2FuncName("shl") // val SHR_NAME = D2FuncName("shr") // val USHR_NAME = D2FuncName("ushr") //} fun D2Expr<*>.generate(): Int { when (this) { is D2Expr.ILit -> { mov(Reg32.EAX, this.lit) } is D2Expr.FLit -> { mov(Reg32.EAX, this.lit.toRawBits()) } is D2Expr.IBinOp -> { generate(l to Reg64.RAX, r to Reg64.RCX) when (this.op) { D2IBinOp.ADD -> add(Reg32.EAX, Reg32.ECX) D2IBinOp.SUB -> sub(Reg32.EAX, Reg32.ECX) D2IBinOp.MUL -> imul(Reg32.ECX) D2IBinOp.DIV -> idiv(Reg32.ECX) D2IBinOp.REM -> { idiv(Reg32.ECX) mov(Reg64.RAX, Reg64.RDX) } D2IBinOp.SHL -> shl(Reg32.EAX, Reg8.CL) D2IBinOp.SHR -> shr(Reg32.EAX, Reg8.CL) D2IBinOp.USHR -> ushr(Reg32.EAX, Reg8.CL) D2IBinOp.AND -> and(Reg32.EAX, Reg32.ECX) D2IBinOp.OR -> or(Reg32.EAX, Reg32.ECX) D2IBinOp.XOR -> xor(Reg32.EAX, Reg32.ECX) } } is D2Expr.FBinOp -> { generateXmm(l to RegXmm.XMM0, r to RegXmm.XMM1) when (this.op) { D2FBinOp.ADD -> addss(RegXmm.XMM0, RegXmm.XMM1) D2FBinOp.SUB -> subss(RegXmm.XMM0, RegXmm.XMM1) D2FBinOp.MUL -> mulss(RegXmm.XMM0, RegXmm.XMM1) D2FBinOp.DIV -> divss(RegXmm.XMM0, RegXmm.XMM1) //D2FBinOp.REM -> TODO("frem") } return pushRegisterInFrame(RegXmm.XMM0) } is D2Expr.IComOp -> { val label1 = Label() val label2 = Label() generateJump2(this, label1, isTrue = true) mov(Reg32.EAX, 0) jmp(label2) place(label1) mov(Reg32.EAX, 1) place(label2) } is D2Expr.Ref-> { val foffset = if (offset is D2Expr.ILit) { restoreArg(Reg64.RDX, memSlot.index) offset.lit * size.bytes } else { this.loadAddress() popRegisterInFrame(Reg64.RDX) 0 } // @TODO: MOVZX (mov zero extension) http://faydoc.tripod.com/cpu/movzx.htm when (size) { D2Size.BYTE -> { mov(Reg32.EAX, 0) readMem(Reg8.AL, Reg64.RDX, foffset) } D2Size.SHORT -> { mov(Reg32.EAX, 0) readMem(Reg16.AX, Reg64.RDX, foffset) } D2Size.INT, D2Size.FLOAT -> readMem(Reg32.EAX, Reg64.RDX, foffset) D2Size.LONG -> TODO("LONG") } } is D2Expr.Invoke<*> -> { val func = context.getFunc(func) subframe { val frameIndices = args.map { it.generate() } val param = ParamsReader(abi) for (n in 0 until args.size) { val frameIndex = frameIndices[n] val type = func.args.getOrElse(0) { D2INT } if (type == D2FLOAT) { getFrameItem(param.getXmm(), frameIndex) } else { getFrameItem(param.getInt(), frameIndex) } } } callAbsolute(func.address) return if (func.rettype == D2FLOAT) { pushRegisterInFrame(RegXmm.XMM0) } else { pushRegisterInFrame(Reg64.RAX) } } is D2Expr.External -> { restoreArg(Reg64.RAX, EXT_IDX) } else -> TODO("$this") } return pushRegisterInFrame(Reg64.RAX) } class ParamsReader(val abi: X64ABI) { var ipos = 0 var fpos = 0 fun reset() { ipos = 0 fpos = 0 } fun getInt(): Reg64 = abi.args[ipos++] fun getXmm(): RegXmm = abi.xmmArgs[ipos++] } fun generate(vararg items: Pair<D2Expr<*>, Reg64>) { subframe { val indices = items.map { (expr, _) -> when { expr is D2Expr.ILit -> -1 else -> expr.generate() } } for ((it, index) in items.zip(indices)) { val expr = it.first val reg = it.second when { expr is D2Expr.ILit -> mov(reg.to32(), expr.lit) else -> getFrameItem(reg, index) } } } } fun generateXmm(vararg items: Pair<D2Expr<*>, RegXmm>) { subframe { val indices = items.map { (expr, _) -> expr.generate() } for ((it, index) in items.zip(indices)) { val expr = it.first val reg = it.second getFrameItem(reg, index) } } } fun generateJumpComp(l: D2ExprI, op: D2CompOp, r: D2ExprI, label: Label, isTrue: Boolean) { generate(l to Reg64.RBX, r to Reg64.RCX) cmp(Reg32.EBX, Reg32.ECX) when (if (isTrue) op else op.negated) { D2CompOp.EQ -> je(label) D2CompOp.NE -> jne(label) D2CompOp.LT -> jl(label) D2CompOp.LE -> jle(label) D2CompOp.GT -> jg(label) D2CompOp.GE -> jge(label) } } fun generateJump2(e: D2Expr.IComOp, label: Label, isTrue: Boolean) { generateJumpComp(e.l, e.op, e.r, label, isTrue) } fun generateJump(e: D2Expr<*>, label: Label, isTrue: Boolean) { when (e) { is D2Expr.IComOp -> generateJump2(e, label, isTrue) else -> { e.generate() popRegisterInFrame(Reg64.RAX) cmp(Reg32.EAX, 0) if (isTrue) jne(label) else je(label) } } } fun generateJumpFalse(e: D2Expr<*>, label: Label): Unit = generateJump(e, label, false) fun generateJumpTrue(e: D2Expr<*>, label: Label): Unit = generateJump(e, label, true) fun generateJumpAlways(label: Label): Unit = jmp(label) inline fun subframe(callback: () -> Unit) { val current = this.frameStackPos try { callback() } finally { this.frameStackPos = current } } } inline class RegContent(val type: Int) { companion object { fun temp(index: Int) = RegContent(0x0000 + index) fun arg(index: Int) = RegContent(0x1000 + index) } }
mit
d2af1da6162f59ac1d6c90f4f86e1037
24.261364
97
0.62987
2.646429
false
false
false
false
jmiecz/YelpBusinessExample
dal/src/main/java/net/mieczkowski/dal/cache/models/PreviousSearch.kt
1
1141
package net.mieczkowski.dal.cache.models import com.raizlabs.android.dbflow.annotation.Column import com.raizlabs.android.dbflow.annotation.PrimaryKey import com.raizlabs.android.dbflow.annotation.Table import com.raizlabs.android.dbflow.sql.language.SQLite import com.raizlabs.android.dbflow.structure.BaseModel import net.mieczkowski.dal.cache.LocalDatabase import com.raizlabs.android.dbflow.annotation.ConflictAction import java.util.* /** * Created by Josh Mieczkowski on 9/11/2018. */ @Table(database = LocalDatabase::class, updateConflict = ConflictAction.REPLACE, insertConflict = ConflictAction.REPLACE) class PreviousSearch : BaseModel(){ companion object { private const val SEARCH_LIMIT = 10 fun getPreviousSearches(): List<PreviousSearch> { return SQLite.select() .from(PreviousSearch::class.java) .orderBy(PreviousSearch_Table.timeStamp, false) .limit(SEARCH_LIMIT) .queryList() } } @PrimaryKey @Column lateinit var searchTerm: String @Column var timeStamp = Date().time }
apache-2.0
801c0c6d4d35d5861725900334e36309
28.282051
121
0.704645
4.439689
false
false
false
false
proxer/ProxerLibAndroid
library/src/test/kotlin/me/proxer/library/ProxerCallTest.kt
2
8703
package me.proxer.library import io.mockk.every import io.mockk.mockk import me.proxer.library.ProxerException.ErrorType import me.proxer.library.ProxerException.ServerErrorType import me.proxer.library.entity.notifications.NewsArticle import me.proxer.library.internal.ProxerResponse import net.jodah.concurrentunit.Waiter import okhttp3.mockwebserver.MockResponse import okhttp3.mockwebserver.SocketPolicy import org.amshove.kluent.invoking import org.amshove.kluent.shouldBe import org.amshove.kluent.shouldBeEqualTo import org.amshove.kluent.shouldBeInstanceOf import org.amshove.kluent.shouldNotBeNull import org.amshove.kluent.shouldThrow import org.junit.jupiter.api.Test import retrofit2.Call import retrofit2.Response import java.io.IOException /** * @author Ruben Gees */ class ProxerCallTest : ProxerTest() { @Test fun testTimeoutError() { val body = MockResponse().setBody(fromResource("news.json")) val response = body.apply { body.socketPolicy = SocketPolicy.NO_RESPONSE } server.runRequest(response) { val result = invoking { api.notifications.news().build().execute() } shouldThrow ProxerException::class result.exception.errorType shouldBe ErrorType.TIMEOUT } } @Test fun testIOError() { server.runRequest(MockResponse().setResponseCode(404)) { val result = invoking { api.notifications.news().build().execute() } shouldThrow ProxerException::class result.exception.errorType shouldBe ErrorType.IO result.exceptionMessage shouldBeEqualTo "Unsuccessful request: 404" } } @Test fun testIOErrorWithBody() { server.runRequest(MockResponse().setBody("Error!").setResponseCode(404)) { val result = invoking { api.notifications.news().build().execute() } shouldThrow ProxerException::class result.exception.errorType shouldBe ErrorType.IO result.exceptionMessage shouldBeEqualTo "Unsuccessful request: 404" } } @Test fun testInternalServerError() { server.runRequest(MockResponse().setResponseCode(500)) { val result = invoking { api.notifications.news().build().execute() } shouldThrow ProxerException::class result.exception.errorType shouldBe ErrorType.SERVER result.exception.serverErrorType shouldBe ServerErrorType.INTERNAL } } @Test fun testInvalidEncodingError() { val response = MockResponse().setBody(fromResource("news.json").replace(":", "invalid")) server.runRequest(response) { val result = invoking { api.notifications.news().build().execute() } shouldThrow ProxerException::class result.exception.errorType shouldBe ErrorType.IO } } @Test fun testInvalidDataError() { val response = MockResponse().setBody(fromResource("news.json").replace("256", "invalid")) server.runRequest(response) { val result = invoking { api.notifications.news().build().execute() } shouldThrow ProxerException::class result.exception.errorType shouldBe ErrorType.PARSING } } @Test fun testServerError() { server.runRequest("conferences_error.json") { val result = invoking { api.messenger.conferences().build().execute() } shouldThrow ProxerException::class result.exception.errorType shouldBe ErrorType.SERVER result.exception.serverErrorType shouldBe ServerErrorType.MESSAGES_LOGIN_REQUIRED result.exceptionMessage shouldBeEqualTo "Du bist nicht eingeloggt." } } @Test fun testServerErrorWithMessage() { server.runRequest("ucp_settings_error.json") { val result = invoking { api.ucp.setSettings().build().execute() } shouldThrow ProxerException::class result.exception.errorType shouldBe ErrorType.SERVER result.exception.serverErrorType shouldBe ServerErrorType.UCP_INVALID_SETTINGS result.exceptionMessage shouldBeEqualTo "Ungültige Eingabe für Felder.\n[profil]" } } @Test fun testUnknownError() { val internalCall = mockk<Call<ProxerResponse<String>>>() val call = ProxerCall(internalCall) val error = IllegalStateException() every { internalCall.execute() } throws error val result = invoking { call.execute() } shouldThrow ProxerException::class result.exception.errorType shouldBe ErrorType.UNKNOWN result.exceptionCause.shouldBe(error) } @Test fun testSafeExecute() { val response = mockk<ProxerResponse<List<NewsArticle>>>().apply { every { isSuccessful } returns true every { data } returns emptyList() } val internalResponse = mockk<Response<ProxerResponse<List<NewsArticle>>>>().apply { every { isSuccessful } returns true every { body() } returns response } val internalCall = mockk<Call<ProxerResponse<List<NewsArticle>>>>() val call = ProxerCall(internalCall) every { internalCall.execute() } returns internalResponse call.execute().shouldNotBeNull() } @Test fun testSafeExecuteNull() { val response = mockk<ProxerResponse<List<NewsArticle>>>().apply { every { isSuccessful } returns true every { data } returns null } val internalResponse = mockk<Response<ProxerResponse<List<NewsArticle>>>>().apply { every { isSuccessful } returns true every { body() } returns response } val internalCall = mockk<Call<ProxerResponse<List<NewsArticle>>>>() val call = ProxerCall(internalCall) every { internalCall.execute() } returns internalResponse val result = invoking { call.safeExecute() } shouldThrow ProxerException::class result.exception.errorType shouldBe ErrorType.UNKNOWN result.exceptionCause shouldBeInstanceOf NullPointerException::class } @Test fun testEnqueue() { val waiter = Waiter() server.runRequest("news.json") { api.notifications.news().build().enqueue( { waiter.assertTrue(it != null && it.isNotEmpty()) waiter.resume() }, { waiter.fail(it) } ) } waiter.await(1_000) } @Test fun testEnqueueError() { val waiter = Waiter() server.runRequest(MockResponse().setBody(fromResource("news.json")).setResponseCode(404)) { api.notifications.news().build().enqueue( { waiter.fail("Expected error") }, { exception -> waiter.assertEquals(ErrorType.IO, exception.errorType) waiter.resume() } ) } waiter.await(1_000) } @Test fun testIsExecuted() { server.runRequest("news.json") { val call = api.notifications.news().build().apply { execute() } call.isExecuted shouldBe true } } @Test fun testCancel() { val waiter = Waiter() val call = api.notifications.news().build() call.enqueue( { waiter.fail("Expected error") }, { exception -> waiter.assertEquals(ErrorType.CANCELLED, exception.errorType) waiter.resume() } ) call.cancel() waiter.await(1_000) call.isCanceled shouldBe true } @Test fun testClone() { val call = api.notifications.news().build() server.runRequest("news.json") { call.execute() } val (result, _) = server.runRequest("news.json") { call.clone().execute() } result.shouldNotBeNull() } @Test fun testRequest() { api.notifications.news().build().request().shouldNotBeNull() } @Test fun testRequestThrowingErrorWithoutMessage() { val internalCall = mockk<Call<ProxerResponse<String>>>() val call = ProxerCall(internalCall) val error = IOException() every { internalCall.execute() } throws error val result = invoking { call.execute() } shouldThrow ProxerException::class result.exception.errorType shouldBe ErrorType.IO result.exceptionCause shouldBe error } }
gpl-3.0
d9074879528cf721bc9404530f4c1808
29.964413
99
0.622457
5.08533
false
true
false
false
tmarsteel/kotlin-prolog
stdlib/src/main/kotlin/com/github/prologdb/runtime/stdlib/dicts/get_dict__3.kt
1
1782
package com.github.prologdb.runtime.stdlib.dicts import com.github.prologdb.async.LazySequence import com.github.prologdb.async.mapRemainingNotNull import com.github.prologdb.runtime.ArgumentTypeError import com.github.prologdb.runtime.stdlib.nativeRule import com.github.prologdb.runtime.term.Atom import com.github.prologdb.runtime.term.PrologDictionary import com.github.prologdb.runtime.term.Variable val BuiltinGetDict3 = nativeRule("get_dict", 3) { args, ctxt -> val keyArg = args[0] val dictArg = args.getTyped<PrologDictionary>(1) val valueArg = args[2] if (keyArg !is Atom && keyArg !is Variable) { throw ArgumentTypeError(0, keyArg, Atom::class.java, Variable::class.java) } if (keyArg is Variable) { return@nativeRule yieldAllFinal(LazySequence.ofIterable(dictArg.pairs.entries, principal).mapRemainingNotNull { (dictKey, dictValue) -> val valueUnification = valueArg.unify(dictValue, ctxt.randomVariableScope) if (valueUnification != null) { if (valueUnification.variableValues.isInstantiated(keyArg)) { if (valueUnification.variableValues[keyArg] == dictKey) { return@mapRemainingNotNull valueUnification } } else { valueUnification.variableValues.instantiate(keyArg, dictKey) return@mapRemainingNotNull valueUnification } } return@mapRemainingNotNull null }) } else { keyArg as Atom val valueForArg = dictArg.pairs[keyArg] return@nativeRule if (valueForArg != null) { valueArg.unify(valueForArg, ctxt.randomVariableScope) } else { null } } }
mit
da73deae5137b0a64896ce1098fa554c
37.73913
143
0.65881
4.325243
false
false
false
false
davinkevin/Podcast-Server
backend/src/main/kotlin/com/github/davinkevin/podcastserver/find/finders/dailymotion/DailymotionFinder.kt
1
2606
package com.github.davinkevin.podcastserver.find.finders.dailymotion import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.fasterxml.jackson.annotation.JsonProperty import com.github.davinkevin.podcastserver.extension.java.util.orNull import com.github.davinkevin.podcastserver.find.FindPodcastInformation import com.github.davinkevin.podcastserver.find.finders.fetchCoverInformationOrOption import com.github.davinkevin.podcastserver.find.finders.Finder import com.github.davinkevin.podcastserver.utils.MatcherExtractor import org.springframework.web.reactive.function.client.WebClient import org.springframework.web.reactive.function.client.bodyToMono import reactor.core.publisher.Mono import reactor.kotlin.core.publisher.toMono import reactor.kotlin.core.util.function.component1 import reactor.kotlin.core.util.function.component2 import java.net.URI import com.github.davinkevin.podcastserver.service.image.ImageService /** * Created by kevin on 01/11/2019 */ class DailymotionFinder( private val wc: WebClient, private val image: ImageService ): Finder { override fun findInformation(url: String): Mono<FindPodcastInformation> { val userName = USER_NAME_EXTRACTOR.on(url).group(1) ?: return RuntimeException("username not found int url $url").toMono() return wc.get() .uri { it .pathSegment("user") .path(userName) .queryParam("fields", "avatar_720_url,description,username") .build() } .retrieve() .bodyToMono<DailymotionUserDetail>() .flatMap { p -> image .fetchCoverInformationOrOption(URI(p.avatar)) .zipWith(p.toMono()) } .map { (cover, podcast) -> FindPodcastInformation( title = podcast.username, url = URI(url), description = podcast.description ?: "", type = "Dailymotion", cover = cover.orNull() ) } } override fun compatibility(url: String): Int = when { "www.dailymotion.com" in url -> 1 else -> Int.MAX_VALUE } } private val USER_NAME_EXTRACTOR = MatcherExtractor.from("^.+dailymotion.com/(.*)") @JsonIgnoreProperties(ignoreUnknown = true) private class DailymotionUserDetail( @JsonProperty("avatar_720_url") val avatar: String, val username: String, val description: String? )
apache-2.0
39e87f1056889dd3cd2a71b353c6a2ea
39.092308
130
0.65119
4.670251
false
false
false
false
j-selby/kotgb
core/src/main/kotlin/net/jselby/kotgb/cpu/interpreter/instructions/alu/Increments.kt
1
2936
package net.jselby.kotgb.cpu.interpreter.instructions.alu import net.jselby.kotgb.Gameboy import net.jselby.kotgb.cpu.CPU import net.jselby.kotgb.cpu.Registers import kotlin.experimental.and import kotlin.reflect.KMutableProperty1 /** * Increments increase the value of a register, and decrements decrease them. */ /** * -- 8 bit increments. -- **/ // TODO: Check flag H output. /** * **0x04 ~ 0x3C** - *INC X* - Increment register X */ val x_INC : (CPU, Registers, Gameboy, KMutableProperty1<Registers, Short>) -> (Int) = { _, registers, _, target -> val prevValue = target.get(registers) val newValue = (prevValue + 1).toShort() target.set(registers, newValue) registers.flagZ = target.get(registers) == 0.toShort() registers.flagN = false registers.flagH = newValue and 0xf == 0.toShort() /*Cycles: */ 4 } /** * **0x05 ~ 0x3D** - *DEC X* - Decrement register X */ val x_DEC : (CPU, Registers, Gameboy, KMutableProperty1<Registers, Short>) -> (Int) = { _, registers, _, target -> val prevValue = target.get(registers) val newValue = (prevValue - 1).toShort() target.set(registers, newValue) registers.flagZ = target.get(registers) == 0.toShort() registers.flagN = true registers.flagH = (target.get(registers).toInt() and 0x0f) == 0x0f /*Cycles: */ 4 } /** * **0x34** - *INC (hl)* - Increment register \*hl */ val x34 : (CPU, Registers, Gameboy) -> (Int) = { _, registers, gb -> val prevValue = gb.ram.readByte(registers.hl.toLong() and 0xFFFF) and 0xFF val newValue = (prevValue + 1).toShort() gb.ram.writeByte(registers.hl.toLong() and 0xFFFF, newValue) registers.flagZ = newValue.toByte() == 0.toByte() registers.flagN = false registers.flagH = newValue and 0xf == 0.toShort() /*Cycles: */ 12 } /** * **0x35** - *DEC (hl)* - Decrement register \*hl */ val x35 : (CPU, Registers, Gameboy) -> (Int) = { _, registers, gb -> val prevValue = gb.ram.readByte(registers.hl.toLong() and 0xFFFF) val newValue = prevValue - 1 gb.ram.writeByte(registers.hl.toLong() and 0xFFFF, newValue.toShort()) registers.flagZ = newValue == 0 registers.flagN = true registers.flagH = (newValue and 0x0f) == 0x0f /*Cycles: */ 12 } /** * -- 16 bit increments. -- */ /** * **0x04 ~ 0x3C** - *INC XX* - Increment register XX */ val x_INC16 : (CPU, Registers, Gameboy, KMutableProperty1<Registers, Int>) -> (Int) = { _, registers, _, target -> val prevValue = target.get(registers) val newValue = prevValue + 1 target.set(registers, newValue) /*Cycles: */ 8 } /** * **0x04 ~ 0x3C** - *INC XX* - Decrement register XX */ val x_DEC16 : (CPU, Registers, Gameboy, KMutableProperty1<Registers, Int>) -> (Int) = { _, registers, _, target -> val prevValue = target.get(registers) val newValue = prevValue - 1 target.set(registers, newValue) /*Cycles: */ 8 }
mit
1a9f554be9069a59ceb2f2e5d8753b60
25.45045
87
0.633174
3.298876
false
false
false
false
itachi1706/CheesecakeUtilities
app/src/main/java/com/itachi1706/cheesecakeutilities/util/FirebaseUtils.kt
1
2218
package com.itachi1706.cheesecakeutilities.util import com.google.firebase.database.DatabaseReference import com.google.firebase.database.FirebaseDatabase import com.google.firebase.database.ValueEventListener import java.text.SimpleDateFormat import java.util.* /** * Created by Kenneth on 3/6/2019. * for com.itachi1706.cheesecakeutilities.Util in CheesecakeUtilities */ abstract class FirebaseUtils { companion object { private var firebaseDatabase: FirebaseDatabase? = null fun removeListener(listener: ValueEventListener) { getFirebaseDatabase().reference.removeEventListener(listener) } fun getFirebaseDatabase(): FirebaseDatabase { if (firebaseDatabase == null) { firebaseDatabase = FirebaseDatabase.getInstance() firebaseDatabase!!.setPersistenceEnabled(true) } return firebaseDatabase!! } fun getDatabaseReference(tag: String): DatabaseReference { val database = getFirebaseDatabase() return getDatabaseReference(tag, database) } fun getDatabaseReference(tag: String, database: FirebaseDatabase): DatabaseReference { return database.reference.child(tag) } fun formatTime(time: Long): String { return formatTime(time, "dd MMMM yyyy HH:mm") } fun formatTime(time: Long, format: String): String { val sdf = SimpleDateFormat(format, Locale.US) val dt = Date() dt.time = time return sdf.format(dt) } fun formatTimeDuration(start: Long, end: Long): String { val sdf = SimpleDateFormat("dd/MM/yy HHmm", Locale.US) val dt = Date() dt.time = start var timeString = sdf.format(dt) sdf.applyPattern("dd/MM/yy HHmm zzz") dt.time = end timeString += " - " + sdf.format(dt) return timeString } fun parseData(d: Double, decimal: Boolean): String { return if (decimal) String.format(Locale.getDefault(), "%.1f", d) else String.format(Locale.getDefault(), "%d", Math.round(d)) } } }
mit
48057c0d8e8d09a3c0449e588a4df8e7
32.606061
138
0.625338
4.928889
false
false
false
false
McGars/Zoomimage
zoomimage/src/main/java/mcgars/com/zoomimage/ZoomImageController.kt
1
3319
package mcgars.com.zoomimage import androidx.viewpager.widget.ViewPager import com.alexvasilkov.gestures.animation.ViewPositionAnimator import mcgars.com.zoomimage.adapter.ZoomPhotoPagerAdapter import mcgars.com.zoomimage.fabric.AMBuilder import mcgars.com.zoomimage.model.IPhoto import mcgars.com.zoomimage.ui.Displayer import mcgars.com.zoomimage.ui.UiContainer class ZoomImageController( private val uiContainer: UiContainer, private val displayer: Displayer, private val titleTransformer: ((Int, Int, IPhoto?) -> CharSequence)? = null ) : ViewPositionAnimator.PositionUpdateListener, ViewPager.OnPageChangeListener { private val zoomAdapter: ZoomPhotoPagerAdapter by lazy { ZoomPhotoPagerAdapter(uiContainer.zoomPager, displayer, this) } init { uiContainer.zoomPager.addOnPageChangeListener(this) uiContainer.zoomToolbar.setNavigationOnClickListener { onBackPressed() } } /** * Animate cosmetics views (ViewPager, Toolbar, Background) * @param state float * @param isLeaving boolean */ override fun onPositionUpdate(state: Float, isLeaving: Boolean) { uiContainer.show(invisible = state == 0f, alpha = (255 * state).toInt()) if (isLeaving && state == 0f) { zoomAdapter.setActivated(false) } } fun onDestroy() { uiContainer.zoomPager.removeOnPageChangeListener(this) zoomAdapter.removePositionAnimation() } /** * If image is full size closed it * @return if image is open true else false */ fun onBackPressed(): Boolean { return zoomAdapter.exit(true) } /** * Before [.show] need set data and builder * * @param builder set from views * @param data images * @return this */ fun setPhotos(builder: AMBuilder, data: List<IPhoto>): ZoomImageController { zoomAdapter.from(builder) setPhotos(data) return this } private fun setPhotos(data: List<IPhoto>) { uiContainer.zoomPager.adapter = zoomAdapter zoomAdapter.setPhotos(data) } /** * Zoom image to front * * @param position by */ fun show(position: Int = 0) { zoomAdapter.setActivated(true) zoomAdapter.enter(position, true) // fixed, if firs page onPageSelected not trigger if (position == 0) setTitle(position) } override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) { } override fun onPageSelected(position: Int) { setTitle(position) } private fun setTitle(position: Int) { val item = zoomAdapter.getPhoto(position) val title = titleTransformer?.invoke(position, zoomAdapter.count, item) ?: when { zoomAdapter.count <= 1 -> item?.text else -> createDefaultTitle(position, item) } uiContainer.zoomToolbar.title = title } private fun createDefaultTitle(position: Int, item: IPhoto?): String { val text = (position + 1).toString() + " / " + zoomAdapter.count return when { item?.text.isNullOrEmpty().not() -> "(" + text + ") " + item?.text else -> text } } override fun onPageScrollStateChanged(state: Int) { } }
apache-2.0
0891e40ba659bb4ec606ae344b7218e1
28.633929
98
0.652606
4.401857
false
false
false
false
luhaoaimama1/AndroidZone
JavaTest_Zone/src/kt/KtMain2.kt
2
1515
package kt import org.apache.commons.lang.ObjectUtils import java.io.File /** * Created by fuzhipeng on 2018/7/7. * * todo let方法?value?.let { transformValue(it) } ?: defaultValueIfValueIsNull */ /** *[2018] by Zone */ //val 一次赋值(只读) val a = 1; // var 变量 var count: Long = 0; //设置的话 会自动推断 var count2 = 0; class Gaga{ fun gogo(){ print("我是类中地方") } } fun printSum(a: Int, b: Int) { //字符串中 美元符号 取值 println("sum of $a and $b is ${a + b}") // var a = 1; // when (a) { // in 1..10 -> print("1-10"); // else -> print("1-10"); // } } //推断函数 fun addSum(var1: Int, var2: Int) = var1 + var2; fun main(args: Array<String>) { // printSum(1, 2); // val files = File("Test").listFiles() val files = emptyArray<String>(); println(files?.elementAtOrNull(0)?:"空啊") var file2:String?="ab" ; file2?.let { println("${it}干啊") } } //? 表示 可控 没有?则不能return null; fun getStringLength(obj: Any): Int? { // `obj` 在 `&&` 右边自动转换成 `String` 类型 if (obj is String && obj.length > 0) { return obj.length } return null } fun main2(args: Array<String>) { val items = listOf("apple", "banana", "kiwifruit") //相当于for for (item in items) { println(item) } // 相当于 fori for (index in items.indices) { println("item at $index is ${items[index]}") } }
epl-1.0
a1feb711f14acde3ee83ca65bd4715a3
15.938272
76
0.55434
2.742
false
false
false
false
Anizoptera/Aza-Kotlin-CSS
main/azagroup/kotlin/css/Selector.kt
1
2188
package azagroup.kotlin.css import java.util.ArrayList class Selector( var stylesheet: Stylesheet ) : ASelector { var rows = ArrayList<Row>(1) operator fun invoke(body: Stylesheet.()->Unit): Stylesheet { stylesheet.body() return stylesheet } override fun custom(selector: String, _spaceBefore: Boolean, _spaceAfter: Boolean, body: (Stylesheet.() -> Unit)?): Selector { if (rows.isEmpty()) rows.add(Row(selector, _spaceBefore, _spaceAfter)) else for (row in rows) row.append(selector, _spaceBefore, _spaceAfter) body?.invoke(stylesheet) return this } fun append(obj: ASelector): Selector { when (obj) { is Selector -> { val newRows = ArrayList<Row>(rows.size * obj.rows.size) for (r1 in rows) for (r2 in obj.rows) { val r = Row(r1.sb, r1.spaceBefore, r1.spaceAfter) r.append(r2.sb, r2.spaceBefore, r2.spaceAfter) newRows.add(r) } rows = newRows obj.stylesheet.moveDataTo(stylesheet) } is Stylesheet -> { append(obj.selector!!) obj.moveDataTo(stylesheet) } } return this } fun toList(selectorPrefix: CharSequence, _spaceBefore: Boolean) = rows.map { it.toString(selectorPrefix, _spaceBefore) } fun toString(selectorPrefix: CharSequence, _spaceBefore: Boolean) = toList(selectorPrefix, _spaceBefore).joinToString(",") override fun toString() = toString("", true) class Row( str: CharSequence, var spaceBefore: Boolean = true, var spaceAfter: Boolean = true ) { val sb = StringBuilder(str) fun append(str: CharSequence, _spaceBefore: Boolean, _spaceAfter: Boolean) { if (sb.isEmpty()) spaceBefore = _spaceBefore else if (_spaceBefore && spaceAfter) sb.append(' ') sb.append(str) spaceAfter = _spaceAfter } fun toString(selectorPrefix: CharSequence, _spaceBefore: Boolean): String { return buildString { if (selectorPrefix.isNotEmpty()) { append(selectorPrefix) if (_spaceBefore && spaceBefore) append(' ') } append(sb) } } override fun toString() = sb.toString() } companion object { fun createEmpty(stylesheet: Stylesheet) = Selector(stylesheet).apply { rows.add(Row("", false, true)) } } }
mit
b6399d6db03cf551c783ba8d5634ff79
22.031579
127
0.673218
3.440252
false
false
false
false
signed/intellij-community
python/src/com/jetbrains/extenstions/QualifiedNameExt.kt
1
4200
/* * 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.extenstions import com.intellij.openapi.module.Module import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiDirectory import com.intellij.psi.PsiElement import com.intellij.psi.PsiManager import com.intellij.psi.util.QualifiedName import com.jetbrains.extensions.getSdk import com.jetbrains.python.PyNames import com.jetbrains.python.psi.PyClass import com.jetbrains.python.psi.resolve.fromModule import com.jetbrains.python.psi.resolve.resolveModuleAt import com.jetbrains.python.psi.resolve.resolveQualifiedName import com.jetbrains.python.psi.stubs.PyModuleNameIndex import com.jetbrains.python.psi.types.TypeEvalContext import com.jetbrains.python.sdk.PythonSdkType data class QNameResolveContext( val module: Module, /** * Used for language level etc */ val sdk: Sdk? = module.getSdk(), val evalContext: TypeEvalContext, /** * If not provided resolves against roots only. Resolved also against this folder otherwise */ val folderToStart: VirtualFile? = null, /** * Use index, plain dirs with Py2 and so on. May resolve names unresolvable in other cases, but may return false results. */ val allowInaccurateResult:Boolean = false ) /** * @return qname part relative to root */ fun QualifiedName.getRelativeNameTo(root: QualifiedName): QualifiedName? { if (!toString().startsWith(root.toString())) { return null } return subQualifiedName(root.componentCount, componentCount) } /** * Resolves qname of any symbol to appropriate PSI element. */ fun QualifiedName.resolveToElement(context: QNameResolveContext): PsiElement? { var currentName = QualifiedName.fromComponents(this.components) var element: PsiElement? = null var lastElement: String? = null var psiDirectory: PsiDirectory? = null var resolveContext = fromModule(context.module).copyWithMembers() if (PythonSdkType.getLanguageLevelForSdk(context.sdk).isPy3K || context.allowInaccurateResult) { resolveContext = resolveContext.copyWithPlainDirectories() } if (context.folderToStart != null) { psiDirectory = PsiManager.getInstance(context.module.project).findDirectory(context.folderToStart) } // Drill as deep, as we can while (currentName.componentCount > 0 && element == null) { if (psiDirectory != null) { // Resolve against folder element = resolveModuleAt(currentName, psiDirectory, resolveContext).firstOrNull() } if (element == null) { // Resolve against roots element = resolveQualifiedName(currentName, resolveContext).firstOrNull() } if (element != null) { break } lastElement = currentName.lastComponent!! currentName = currentName.removeLastComponent() } if (lastElement != null && element is PyClass) { // Drill in class //TODO: Support nested classes val method = element.findMethodByName(lastElement, true, context.evalContext) if (method != null) { return method } } if (element == null && this.firstComponent != null && context.allowInaccurateResult) { // If name starts with file which is not in root nor in folders -- use index. val nameToFind = this.firstComponent!! val pyFile = PyModuleNameIndex.find(nameToFind, context.module.project, false).firstOrNull() ?: return element val folder = if (pyFile.name == PyNames.INIT_DOT_PY) { // We are in folder pyFile.virtualFile.parent.parent } else { pyFile.virtualFile.parent } return resolveToElement(context.copy(folderToStart = folder)) } return element }
apache-2.0
4fbe9b54c44f7949b4a1d52e6ad2b3d1
31.820313
123
0.74119
4.416404
false
false
false
false
dfernandez79/swtlin
builder/src/main/kotlin/swtlin/Resource.kt
1
924
package swtlin import org.eclipse.swt.graphics.Color import org.eclipse.swt.graphics.Resource import org.eclipse.swt.widgets.Control import org.eclipse.swt.widgets.Display private val emptyHandler: (Any) -> Unit = {} class ResourceDisposeHandler<out R : Resource>(val resource: R, private val disposeHandler: (R) -> Unit) { fun dispose() = disposeHandler(resource) fun disposeWith(control: Control) { if (disposeHandler != emptyHandler) { control.addDisposeListener({ _ -> dispose()}) } } } class ResourceFactory<out R : Resource>( private val factory: (Display) -> R, private val disposeHandler: (R) -> Unit = emptyHandler) { fun create(display: Display = Display.getDefault()) = ResourceDisposeHandler(factory(display), disposeHandler) } fun systemColor(value: Int): ResourceFactory<Color> = ResourceFactory({ display -> display.getSystemColor(value) })
apache-2.0
9be5131ccda54196eb66b676caa0a063
32
115
0.70671
4
false
false
false
false
vincentvalenlee/XCRM
src/main/kotlin/org/rocfish/IDSpecs.kt
1
1328
package org.rocfish import io.vertx.core.json.JsonObject /** * 所有领域对象都需要具有ID,且需要获取Field的值(不支持嵌套)。 * <p>所有的领域对象中,自定义属性中所有以"__"开头的属性为关联冗余属性(魔术属性),这些属性都不会进行持久化, * 而只提供给上层应用进行使用(例如从持久存储的冗余关联文档中获取的信息,就放在这个属性中,以便mongo上层对象使用) */ interface IDSpecs { companion object { /** * 双下划线标识的魔术属性前缀 */ const val MAGIC_PROPS_PREFIX = "__" /** * 子文档、子属性分隔符 */ const val SUB_DOC_SPLIT = "." } fun getId():String /** * 获取模型领域对象字段的值 */ fun getField(field:String):Comparable<*> } /** * 过滤魔术属性 */ fun Map<String,*>.filtMagic():Map<String,*> = this.filter { !it.key.startsWith(IDSpecs.MAGIC_PROPS_PREFIX) } fun JsonObject.filtMagic():JsonObject = JsonObject(this.map.filtMagic()) /** * 获取魔术属性 */ fun Map<String, *>.getMagic():Map<String, *> = this.filter { it.key.startsWith(IDSpecs.MAGIC_PROPS_PREFIX) } fun JsonObject.getMagic():JsonObject = JsonObject(this.map.getMagic())
apache-2.0
34f081748cf2a413fa3d8c52f966e2ff
19.291667
72
0.629363
2.61126
false
false
false
false
YounesRahimi/java-utils
src/main/java/ir/iais/utilities/javautils/validators/annotations/Pattern.kt
2
2141
//package ir.iais.utilities.javautils.validators.annotations // //import ir.iais.utilities.javautils.IQ //import javax.validation.Constraint //import javax.validation.ConstraintValidator //import javax.validation.ConstraintValidatorContext //import kotlin.reflect.KClass // ///** // * Validation annotation to globalValidate that 2 fields have the same value. An array of fields and // * their matching confirmation fields can be supplied. // * // * // * Example, compare 1 pair of fields: @FieldMatch(first = "password", second = "confirmPassword", // * message = "The password fields must match") // * // * // * Example, compare more than 1 pair of fields: @FieldMatch.List({ @FieldMatch(first = // * "password", second = "confirmPassword", message = "The password fields must // * match"), @FieldMatch(first = "email", second = "confirmEmail", message = "The email fields must // * match")}) // */ //@Target() //@kotlin.annotation.Retention ////@Repeatable(List::class) //@Repeatable //@Constraint(validatedBy = arrayOf(PatternValidator::class)) //@MustBeDocumented //annotation class Pattern( // val value: String, // val message: String = PatternValidator.message, // val groups: Array<KClass<*>> = arrayOf() //) // //class PatternValidator : ConstraintValidator<Pattern, Any>, IQ { // private lateinit var regex: java.util.regex.Pattern // // constructor() {} // // constructor(regex: String) { // this.regex = java.util.regex.Pattern.compile(regex) // } // // override fun initialize(constraintAnnotation: Pattern) { // regex = java.util.regex.Pattern.compile(constraintAnnotation.value) // } // // fun isValid(obj: String?): Boolean = if (obj == null || obj.isEmpty()) true else regex.matcher(obj).matches() // // override fun isValid(value: Any, context: ConstraintValidatorContext): Boolean { // if (value !is String) { // logger.warn("value $value is not an String for pattern matching.") // return true // } // return isValid(value) // } // // companion object { // const val message = "error.pattern" // } //}
gpl-3.0
f13d16be0d78f610467061f786b8c332
34.098361
115
0.666978
3.885662
false
false
false
false
pronghorn-tech/server
src/main/kotlin/tech/pronghorn/util/ServerUtils.kt
1
1364
/* * Copyright 2017 Pronghorn Technology 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 tech.pronghorn.util import java.nio.ByteBuffer import java.nio.channels.SocketChannel import java.nio.charset.StandardCharsets public fun SocketChannel.write(string: String) { val byteArray = string.toByteArray(StandardCharsets.UTF_8) if (byteArray.size > 4096) { throw Exception("SocketChannel.write(String) is strictly for short strings.") } val buffer = ByteBuffer.wrap(byteArray) assert(write(buffer) == byteArray.size) } public fun ByteBuffer.sliceToArray(start: Int, length: Int): ByteArray { val slice = ByteArray(length) val prePosition = position() if (prePosition != start) { position(start) } get(slice) position(prePosition) return slice }
apache-2.0
0fe1e65cb0ccd8e1f5895b6971215362
31.47619
85
0.711877
4.236025
false
false
false
false
danrien/projectBlue
projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/client/playback/file/exoplayer/GivenAPlayingFile/WhenPlaybackCompletes.kt
1
1854
package com.lasthopesoftware.bluewater.client.playback.file.exoplayer.GivenAPlayingFile import com.annimon.stream.Stream import com.google.android.exoplayer2.Player import com.lasthopesoftware.any import com.lasthopesoftware.bluewater.client.playback.exoplayer.PromisingExoPlayer import com.lasthopesoftware.bluewater.client.playback.file.PlayedFile import com.lasthopesoftware.bluewater.client.playback.file.exoplayer.ExoPlayerPlaybackHandler import com.lasthopesoftware.bluewater.shared.promises.extensions.toFuture import com.lasthopesoftware.bluewater.shared.promises.extensions.toPromise import org.assertj.core.api.AssertionsForClassTypes import org.junit.BeforeClass import org.junit.Test import org.mockito.ArgumentMatchers.anyBoolean import org.mockito.Mockito.* import java.util.* import java.util.concurrent.TimeUnit class WhenPlaybackCompletes { companion object { private val eventListeners: MutableList<Player.EventListener> = ArrayList() private var playedFile: PlayedFile? = null @BeforeClass @JvmStatic fun context() { val mockExoPlayer = mock(PromisingExoPlayer::class.java) `when`(mockExoPlayer.setPlayWhenReady(anyBoolean())).thenReturn(mockExoPlayer.toPromise()) doAnswer { invocation -> eventListeners.add(invocation.getArgument(0)) mockExoPlayer.toPromise() }.`when`(mockExoPlayer).addListener(any()) val playbackHandler = ExoPlayerPlaybackHandler(mockExoPlayer) val playedFileFuture = playbackHandler .promisePlayback() .eventually { obj -> obj.promisePlayedFile() } .toFuture() Stream.of(eventListeners).forEach { e: Player.EventListener -> e.onPlayerStateChanged(false, Player.STATE_ENDED) } playedFile = playedFileFuture[1, TimeUnit.SECONDS] } } @Test fun thenThePlayedFileIsReturned() { AssertionsForClassTypes.assertThat(playedFile).isNotNull } }
lgpl-3.0
d4e56a828bc3f6b2e768f94fe6265c67
34.653846
117
0.804746
4.281755
false
false
false
false
simonorono/pradera_baja
asistencia/src/main/kotlin/pb/asistencia/window/PasswordForm.kt
1
1214
/* * Copyright 2016 Simón Oroñ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 pb.asistencia.window import javafx.fxml.FXMLLoader import javafx.scene.Parent import javafx.scene.Scene import javafx.stage.Stage class PasswordForm { val stage = Stage() init { stage.isResizable = false val root: Parent = FXMLLoader.load( javaClass .classLoader .getResource("fxml/password_form.fxml")) val scene = Scene(root, 350.0, 120.0) stage.scene = scene stage.title = "Cambiar contraseña" } fun showAndWait() = stage.showAndWait() }
apache-2.0
1e0d5db92c7474e8206c2c47affcdb93
27.833333
75
0.649876
4.279152
false
false
false
false
jitsi/jitsi-videobridge
jitsi-media-transform/src/main/kotlin/org/jitsi/nlj/util/BitrateTracker.kt
1
1597
/* * Copyright @ 2020 - Present, 8x8 Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jitsi.nlj.util import org.jitsi.utils.ms import org.jitsi.utils.stats.RateTracker import java.time.Clock import java.time.Duration open class BitrateTracker @JvmOverloads constructor( private val windowSize: Duration, private val bucketSize: Duration = 1.ms, private val clock: Clock = Clock.systemUTC() ) { // Use composition to expose functions with the data types we want ([DataSize], [Bandwidth]) and not the raw types // that RateTracker uses. private val tracker = RateTracker(windowSize, bucketSize, clock) open fun getRate(nowMs: Long = clock.millis()): Bandwidth = tracker.getRate(nowMs).bps @JvmOverloads open fun getRateBps(nowMs: Long = clock.millis()): Long = tracker.getRate(nowMs) val rate: Bandwidth get() = getRate() fun update(dataSize: DataSize, now: Long = clock.millis()) = tracker.update(dataSize.bits, now) fun getAccumulatedSize(now: Long = clock.millis()) = tracker.getAccumulatedCount(now).bits }
apache-2.0
d7e172cf16b1004802c6cb8ebe349c71
41.026316
118
0.729493
3.962779
false
false
false
false
JLLeitschuh/ktlint-gradle
plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/GitHook.kt
1
7743
package org.jlleitschuh.gradle.ktlint import org.eclipse.jgit.lib.RepositoryBuilder import org.gradle.api.DefaultTask import org.gradle.api.file.DirectoryProperty import org.gradle.api.file.ProjectLayout import org.gradle.api.model.ObjectFactory import org.gradle.api.provider.Property import org.gradle.api.tasks.Input import org.gradle.api.tasks.InputDirectory import org.gradle.api.tasks.TaskAction import org.intellij.lang.annotations.Language import org.jlleitschuh.gradle.ktlint.tasks.BaseKtLintCheckTask import javax.inject.Inject internal const val FILTER_INCLUDE_PROPERTY_NAME = "internalKtlintGitFilter" @Language("Bash") internal val shShebang = """ #!/bin/sh """.trimIndent() internal const val startHookSection = "######## KTLINT-GRADLE HOOK START ########\n" internal const val endHookSection = "######## KTLINT-GRADLE HOOK END ########\n" private fun generateGradleCommand( taskName: String, gradleRootDirPrefix: String ): String { val gradleCommand = if (gradleRootDirPrefix.isNotEmpty()) { "./$gradleRootDirPrefix/gradlew -p ./$gradleRootDirPrefix" } else { "./gradlew" } return "$gradleCommand --quiet $taskName -P$FILTER_INCLUDE_PROPERTY_NAME=\"${'$'}CHANGED_FILES\"" } private fun generateGitCommand( gradleRootDirPrefix: String ): String = if (gradleRootDirPrefix.isEmpty()) { "git --no-pager diff --name-status --no-color --cached" } else { "git --no-pager diff --name-status --no-color --cached -- $gradleRootDirPrefix/" } private fun postCheck( shouldUpdateCommit: Boolean ): String = if (shouldUpdateCommit) { """ echo "${'$'}CHANGED_FILES" | while read -r file; do if [ -f ${'$'}file ]; then git add ${'$'}file fi done """ } else { "" } internal const val NF = "\$NF" @Language("Sh") internal fun generateGitHook( taskName: String, shouldUpdateCommit: Boolean, gradleRootDirPrefix: String ) = """ CHANGED_FILES="${'$'}(${generateGitCommand(gradleRootDirPrefix)} | awk '$1 != "D" && $NF ~ /\.kts?$/ { print $NF }')" if [ -z "${'$'}CHANGED_FILES" ]; then echo "No Kotlin staged files." exit 0 fi; echo "Running ktlint over these files:" echo "${'$'}CHANGED_FILES" diff=.git/unstaged-ktlint-git-hook.diff git diff --color=never > ${'$'}diff if [ -s ${'$'}diff ]; then git apply -R ${'$'}diff fi ${generateGradleCommand(taskName, gradleRootDirPrefix)} gradle_command_exit_code=${'$'}? echo "Completed ktlint run." ${postCheck(shouldUpdateCommit)} if [ -s ${'$'}diff ]; then git apply --ignore-whitespace ${'$'}diff fi rm ${'$'}diff unset diff echo "Completed ktlint hook." exit ${'$'}gradle_command_exit_code """.trimIndent() internal fun KtlintPlugin.PluginHolder.addGitHookTasks() { if (target.rootProject == target) { addInstallGitHookFormatTask() addInstallGitHookCheckTask() } } private fun KtlintPlugin.PluginHolder.addInstallGitHookFormatTask() { target.tasks.register( INSTALL_GIT_HOOK_FORMAT_TASK, KtlintInstallGitHookTask::class.java ) { it.description = "Adds git hook to run ktlintFormat on changed files" it.group = HELP_GROUP it.taskName.set(FORMAT_PARENT_TASK_NAME) // Format git hook will automatically add back updated files to git commit it.shouldUpdateCommit.set(true) it.hookName.set("pre-commit") } } private fun KtlintPlugin.PluginHolder.addInstallGitHookCheckTask() { target.tasks.register( INSTALL_GIT_HOOK_CHECK_TASK, KtlintInstallGitHookTask::class.java ) { it.description = "Adds git hook to run ktlintCheck on changed files" it.group = HELP_GROUP it.taskName.set(CHECK_PARENT_TASK_NAME) it.shouldUpdateCommit.set(false) it.hookName.set("pre-commit") } } open class KtlintInstallGitHookTask @Inject constructor( objectFactory: ObjectFactory, projectLayout: ProjectLayout ) : DefaultTask() { @get:Input internal val taskName: Property<String> = objectFactory.property(String::class.java) @get:Input internal val shouldUpdateCommit: Property<Boolean> = objectFactory.property(Boolean::class.java).convention(false) @get:Input internal val hookName: Property<String> = objectFactory.property(String::class.java) @get:InputDirectory internal val projectDir: DirectoryProperty = objectFactory.directoryProperty().apply { set(projectLayout.projectDirectory) } @get:InputDirectory internal val rootDirectory: DirectoryProperty = objectFactory.directoryProperty().apply { set(project.rootDir) } @TaskAction fun installHook() { val repo = RepositoryBuilder().findGitDir(projectDir.get().asFile).setMustExist(false).build() if (!repo.objectDatabase.exists()) { logger.warn("No git folder was found!") return } logger.info(".git directory path: ${repo.directory}") val gitHookDirectory = repo.directory.resolve("hooks") if (!gitHookDirectory.exists()) { logger.info("git hooks directory doesn't exist, creating one") gitHookDirectory.mkdir() } val gitHookFile = repo.directory.resolve("hooks/${hookName.get()}") logger.info("Hook file: $gitHookFile") if (!gitHookFile.exists()) { gitHookFile.createNewFile() gitHookFile.setExecutable(true) } val gradleRootDirPrefix = rootDirectory.get().asFile.relativeTo(repo.workTree).path if (gitHookFile.length() == 0L) { gitHookFile.writeText( "$shShebang$startHookSection${generateGitHook( taskName.get(), shouldUpdateCommit.get(), gradleRootDirPrefix )}$endHookSection" ) return } var hookContent = gitHookFile.readText() if (hookContent.contains(startHookSection)) { val startTagIndex = hookContent.indexOf(startHookSection) val endTagIndex = hookContent.indexOf(endHookSection) hookContent = hookContent.replaceRange( startTagIndex, endTagIndex, "$startHookSection${generateGitHook( taskName.get(), shouldUpdateCommit.get(), gradleRootDirPrefix )}" ) gitHookFile.writeText(hookContent) } else { gitHookFile.appendText( "$startHookSection${generateGitHook( taskName.get(), shouldUpdateCommit.get(), gradleRootDirPrefix )}$endHookSection" ) } } } internal fun BaseKtLintCheckTask.applyGitFilter() { val projectRelativePath = project.rootDir.toPath() .relativize(project.projectDir.toPath()) .toString() val filesToInclude = (project.property(FILTER_INCLUDE_PROPERTY_NAME) as String) .split('\n') .filter { it.startsWith(projectRelativePath) } .map { it.replace("\\", "/") } if (filesToInclude.isNotEmpty()) { include { fileTreeElement -> if (fileTreeElement.isDirectory) { true } else { filesToInclude.any { fileTreeElement .file .absolutePath .replace("\\", "/") .endsWith(it) } } } } else { exclude("*") } }
mit
a991d24a5cb8a1bf9302934d42e63c4c
30.221774
121
0.617332
4.35
false
false
false
false
alxnns1/MobHunter
src/main/kotlin/com/alxnns1/mobhunter/entity/herbivore/model/KelbiModel.kt
1
3350
package com.alxnns1.mobhunter.entity.herbivore.model import com.alxnns1.mobhunter.entity.herbivore.KelbiEntity import com.google.common.collect.ImmutableList import net.minecraft.client.renderer.entity.model.AgeableModel import net.minecraft.client.renderer.model.ModelRenderer import net.minecraft.util.math.MathHelper import kotlin.math.PI import kotlin.math.abs class KelbiModel : AgeableModel<KelbiEntity>() { init { textureHeight = 64 textureWidth = 64 } private var body = ModelRenderer(this, 0, 0).apply { addBox(-4f, -8f, -15f, 8f, 8f, 15f) setRotationPoint(0f, 14f, 7.5f) } private var neck = ModelRenderer(this, 0, 23).apply { addBox(-2f, -2f, -4f, 4f, 4f, 6f) setRotationPoint(0f, 6f, -7.5f) } private var head = ModelRenderer(this, 31, 0).apply { addBox(-2f, -2f, -4f, 4f, 8f, 4f) setRotationPoint(0f, 0f, -4f) setTextureOffset(0, 23).addBox(-2f, 0f, -6f, 1f, 2f, 2f) setTextureOffset(0, 23).addBox(1f, 0f, -6f, 1f, 2f, 2f) setTextureOffset(9, 0).addBox(-2f, 0f, -8f, 1f, 1f, 2f) setTextureOffset(9, 0).addBox(1f, 0f, -8f, 1f, 1f, 2f) neck.addChild(this) } private var earRight = ModelRenderer(this, 31, 12).apply { addBox(-3f, 0f, -1f, 3f, 1f, 2f) setRotationPoint(-2f, -1f, -3f) head.addChild(this) } private var earLeft = ModelRenderer(this, 31, 12).apply { mirror = true addBox(0f, 0f, -1f, 3f, 1f, 2f) setRotationPoint(2f, -1f, -3f) head.addChild(this) } private var legFrontRight = ModelRenderer(this, 0, 0).apply { addBox(-1.5f, 0f, -1.5f, 3f, 10f, 3f) setRotationPoint(-2.5f, 0f, -13.5f) body.addChild(this) } private var legFrontLeft = ModelRenderer(this, 0, 0).apply { mirror = true addBox(-1.5f, 0f, -1.5f, 3f, 10f, 3f) setRotationPoint(2.5f, 0f, -13.5f) body.addChild(this) } private var legBackRight = ModelRenderer(this, 0, 0).apply { addBox(-1.5f, 0f, -1.5f, 3f, 10f, 3f) setRotationPoint(-2.5f, 0f, -1.5f) body.addChild(this) } private var legBackLeft = ModelRenderer(this, 0, 0).apply { mirror = true addBox(-1.5f, 0f, -1.5f, 3f, 10f, 3f) setRotationPoint(2.5f, 0f, -1.5f) body.addChild(this) } private var tail = ModelRenderer(this, 20, 23).apply { addBox(-1.5f, 0f, -1f, 3f, 7f, 1f) setRotationPoint(0f, -8f, 0f) body.addChild(this) } override fun setRotationAngles(entityIn: KelbiEntity, limbSwing: Float, limbSwingAmount: Float, ageInTicks: Float, netHeadYaw: Float, headPitch: Float) { head.rotateAngleX = headPitch * PI.toFloat() / 180f earRight.rotateAngleX = PI.toFloat() / 4 earLeft.rotateAngleX = PI.toFloat() / 4 neck.rotateAngleY = netHeadYaw * PI.toFloat() / 180f neck.rotateAngleX = -PI.toFloat() / 4 legFrontRight.rotateAngleX = MathHelper.cos(limbSwing * 0.6662f) * 1.4f * limbSwingAmount legFrontLeft.rotateAngleX = MathHelper.cos(limbSwing * 0.6662f + PI.toFloat()) * 1.4f * limbSwingAmount legBackRight.rotateAngleX = MathHelper.cos(limbSwing * 0.6662f + PI.toFloat()) * 1.4f * limbSwingAmount legBackLeft.rotateAngleX = MathHelper.cos(limbSwing * 0.6662f) * 1.4f * limbSwingAmount tail.rotateAngleX = abs(MathHelper.cos(limbSwing * 0.6662f) * 1.4f * limbSwingAmount) / 2 + PI.toFloat() / 6 } override fun getHeadParts(): MutableIterable<ModelRenderer> = ImmutableList.of() override fun getBodyParts(): MutableIterable<ModelRenderer> = ImmutableList.of(neck, body) }
gpl-2.0
19b04088ce9af51de2323475621078de
32.848485
154
0.700597
2.457814
false
false
false
false
episode6/mockspresso
mockspresso-reflect/src/test/java/com/episode6/hackit/mockspresso/reflect/TypeTokenKotlinTest.kt
1
3559
package com.episode6.hackit.mockspresso.reflect import com.episode6.hackit.mockspresso.reflect.testobject.JavaTokens import com.episode6.hackit.mockspresso.reflect.testobject.TestGenericKtInterface import com.episode6.hackit.mockspresso.reflect.testobject.TestJavaObjectWithKtGeneric import org.fest.assertions.api.Assertions.assertThat import org.junit.Test import java.util.* /** * Tests the TypeToken class */ class TypeTokenKotlinTest { @Test fun testStringToken() { val token = typeToken<String>() assertThat(token).isEqualTo(JavaTokens.stringToken) } @Test fun testIntToken() { val token = typeToken<Int>() assertThat(token).isEqualTo(JavaTokens.intToken) } @Test fun testStringListToken() { val token = typeToken<List<String>>() assertThat(token).isEqualTo(JavaTokens.stringListToken) } @Test fun testStringIntMapToken() { val token = typeToken<Map<String, Int>>() assertThat(token).isEqualTo(JavaTokens.stringIntMapToken) } @Test fun testStringMutableListToken() { val token = typeToken<MutableList<String>>() assertThat(token).isEqualTo(JavaTokens.stringMutableListToken) } @Test fun testStringIntMutableMapToken() { val token = typeToken<MutableMap<String, Int>>() assertThat(token).isEqualTo(JavaTokens.stringIntMutableMapToken) } @Test fun testStringLinkedListToken() { val token = typeToken<LinkedList<String>>() assertThat(token).isEqualTo(JavaTokens.stringLinkedListToken) } @Test fun testStringIntHashMapToken() { val token = typeToken<HashMap<String, Int>>() assertThat(token).isEqualTo(JavaTokens.stringIntHashMapToken) } /** * This test basically documents a kind of broken pattern in kotlin/java interop * where mockspresso is concerned. We're parsing the TypeToken from a java class, but * the field type is a generic Kotlin interface, and the declaration of the field ignores * the `out` keyword on the type variable (i.e. it doesn't include `? extends` like * generated kotlin code would). * * As a result these two tokens that *should* match, don't. We test just so we can have signal * if/when this behavior changes, and to document it. */ @Test fun testKotlinGenericWithOutTypeFails() { // the `out` keyword on `TestGenericKtInterface's TypeVariable, means this token actually // looks like `TestGenericKtInterface<? extends String>` val manualToken = typeToken<TestGenericKtInterface<String>>() // this class (written in java) delclares a field that *should* match the token above, // but doesn't because its missing `? extends` val testObj = TestJavaObjectWithKtGeneric() val fieldToken = TypeToken.of(testObj.genericIfaceField.genericType) // we test this just so we can know if/when this behavior ever changes // ideally we actually want these two tokens to be equal. assertThat(fieldToken).isNotEqualTo(manualToken) } /** * This test just demonstrates that we can use typeTokens defined in java to work * around the issue described in the above test. */ @Test fun testKotlinGenericWithoutTypeMatchesJavaToken() { // if we create the the TypeToken in a java file in the same incorrect way the // TestJavaObjectWithKtGeneric defines it's field, the tokens now match. val manualJavaToken = JavaTokens.genericInterfaceIllegalToken val testObj = TestJavaObjectWithKtGeneric() val fieldToken = TypeToken.of(testObj.genericIfaceField.genericType) assertThat(fieldToken).isEqualTo(manualJavaToken) } }
mit
13da32bbb1db8f3f9f8681a447568024
34.237624
96
0.745996
4.308717
false
true
false
false
Shynixn/PetBlocks
petblocks-bukkit-plugin/petblocks-bukkit-nms-117R1/src/main/java/com/github/shynixn/petblocks/bukkit/logic/business/nms/v1_17_R1/NMSPetBat.kt
1
5048
package com.github.shynixn.petblocks.bukkit.logic.business.nms.v1_17_R1 import com.github.shynixn.petblocks.api.PetBlocksApi import com.github.shynixn.petblocks.api.business.proxy.PathfinderProxy import com.github.shynixn.petblocks.api.business.service.ConcurrencyService import com.github.shynixn.petblocks.api.persistence.entity.AIFlying import net.minecraft.core.BlockPosition import net.minecraft.world.entity.Entity import net.minecraft.world.entity.EntityTypes import net.minecraft.world.entity.ai.attributes.GenericAttributes import net.minecraft.world.entity.ai.goal.PathfinderGoal import net.minecraft.world.entity.ai.goal.PathfinderGoalSelector import net.minecraft.world.entity.animal.EntityParrot import net.minecraft.world.level.block.state.IBlockData import org.bukkit.Bukkit import org.bukkit.Location import org.bukkit.craftbukkit.v1_17_R1.CraftServer import org.bukkit.craftbukkit.v1_17_R1.CraftWorld import org.bukkit.event.entity.CreatureSpawnEvent /** * NMS implementation of the Parrot pet backend. */ class NMSPetBat(petDesign: NMSPetArmorstand, location: Location) : EntityParrot(EntityTypes.al, (location.world as CraftWorld).handle) { // NMSPetBee might be instantiated from another source. private var petDesign: NMSPetArmorstand? = null // Pathfinders need to be self cached for Paper. private var initialClear = true private var pathfinderCounter = 0 private var cachedPathfinders = HashSet<PathfinderGoal>() // BukkitEntity has to be self cached since 1.14. private var entityBukkit: Any? = null init { this.petDesign = petDesign this.isSilent = true clearAIGoals() // NMS can sometimes instantiate this object without petDesign. if (this.petDesign != null) { val flyingAI = this.petDesign!!.proxy.meta.aiGoals.firstOrNull { a -> a is AIFlying } as AIFlying? if (flyingAI != null) { this.getAttributeInstance(GenericAttributes.d)!!.value = 0.30000001192092896 * 0.75 this.getAttributeInstance(GenericAttributes.e)!!.value = 0.30000001192092896 * flyingAI.movementSpeed this.O = flyingAI.climbingHeight.toFloat() } } val mcWorld = (location.world as CraftWorld).handle this.setPosition(location.x, location.y - 200, location.z) mcWorld.addEntity(this, CreatureSpawnEvent.SpawnReason.CUSTOM) val targetLocation = location.clone() PetBlocksApi.resolve(ConcurrencyService::class.java).runTaskSync(20L) { // Only fix location if it is not already fixed. if (this.bukkitEntity.location.distance(targetLocation) > 20) { this.setPosition(targetLocation.x, targetLocation.y + 1.0, targetLocation.z) } } } /** * Applies pathfinders to the entity. */ fun applyPathfinders(pathfinders: List<Any>) { clearAIGoals() pathfinderCounter = 0 val proxies = HashMap<PathfinderProxy, CombinedPathfinder.Cache>() val hyperPathfinder = CombinedPathfinder(proxies) for (pathfinder in pathfinders) { if (pathfinder is PathfinderProxy) { val wrappedPathfinder = Pathfinder(pathfinder) this.cachedPathfinders.add(wrappedPathfinder) proxies[pathfinder] = CombinedPathfinder.Cache() } else { this.bP.a(pathfinderCounter++, pathfinder as PathfinderGoal) this.cachedPathfinders.add(pathfinder) } } this.bP.a(pathfinderCounter++, hyperPathfinder) this.cachedPathfinders.add(hyperPathfinder) } /** * Gets called on move to play sounds. */ override fun b(blockposition: BlockPosition, iblockdata: IBlockData) { if (petDesign == null) { return } if (!this.isInWater) { petDesign!!.proxy.playMovementEffects() } } /** * Disable health. */ override fun setHealth(f: Float) { } /** * Gets the bukkit entity. */ override fun getBukkitEntity(): CraftPet { if (this.entityBukkit == null) { entityBukkit = CraftPet(Bukkit.getServer() as CraftServer, this) val field = Entity::class.java.getDeclaredField("bukkitEntity") field.isAccessible = true field.set(this, entityBukkit) } return this.entityBukkit as CraftPet } /** * Clears all entity aiGoals. */ private fun clearAIGoals() { if (initialClear) { val dField = PathfinderGoalSelector::class.java.getDeclaredField("d") dField.isAccessible = true (dField.get(this.bP) as MutableSet<*>).clear() (dField.get(this.bQ) as MutableSet<*>).clear() initialClear = false } for (pathfinder in cachedPathfinders) { this.bP.a(pathfinder) } this.cachedPathfinders.clear() } }
apache-2.0
b41b4cc91442e970e3bcdf7d578d2d71
34.300699
136
0.659865
4.424189
false
false
false
false
koesie10/AdventOfCode-Solutions-Kotlin
2016/src/main/kotlin/com/koenv/adventofcode/Day9.kt
1
2347
package com.koenv.adventofcode import java.util.regex.Pattern object Day9 { fun decompressPart1(input: String): String { var pos = 0 val result = StringBuilder() val matcher = numberRegex.matcher(input) while (pos < input.length) { val char = input[pos] if (char == '(') { pos++ // parentheses if (!matcher.find(pos) || matcher.start() != pos) { throw IllegalArgumentException("Invalid input at $pos: Cannot find the input") } val length = matcher.group(1).toInt() val count = matcher.group(2).toInt() pos += matcher.group(0).length val repeated = input.substring(pos, pos + length) pos += length for (i in 1..count) { result.append(repeated) } } else { result.append(char) pos++ } } return result.toString() } fun decompressPart2(input: String): Long { var pos = 0 var result = 0L while (pos < input.length) { val char = input[pos] if (char == '(') { pos++ // parentheses val (length, lengthPos) = getInt(input, pos) pos = lengthPos val (count, countPos) = getInt(input, pos) pos = countPos val repeated = input.substring(pos, pos + length) pos += length result += count * decompressPart2(repeated) } else if (char == ' ' || char == '\n' || char == '\r') { pos++ } else { result++ pos++ } } return result } fun getInt(input: String, pos: Int): Pair<Int, Int> { var char = input[pos] var newPos = pos + 1 val result = StringBuilder() while (char.isDigit()) { result.append(char) char = input[newPos++] } return result.toString().toInt() to newPos } fun countCharacters(input: String): Int { return input.replace("\\s", "").trim().length } val numberRegex: Pattern = Pattern.compile("(\\d+)x(\\d+)\\)") }
mit
5f87950b58afc43ce3c08ff08b0a1804
24.802198
98
0.463571
4.620079
false
false
false
false
spark/photon-tinker-android
mesh/src/main/java/io/particle/mesh/setup/utils/Toasts.kt
1
1045
package io.particle.mesh.setup.utils import android.app.Activity import android.content.Context import android.util.Log import android.view.Gravity import android.view.ViewGroup import android.widget.Toast import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch enum class ToastDuration(val length: Int) { SHORT(Toast.LENGTH_SHORT), LONG(Toast.LENGTH_LONG) } enum class ToastGravity(val asGravityInt: Int) { TOP(Gravity.TOP), CENTER(Gravity.CENTER), BOTTOM(Gravity.BOTTOM) } fun Context?.safeToast( text: CharSequence?, duration: ToastDuration = ToastDuration.SHORT, gravity: ToastGravity = ToastGravity.BOTTOM ) { if (this == null) { return } if (text == null) { Log.w("safeToast", "No text specified!") return } GlobalScope.launch(Dispatchers.Main) { val toast = Toast.makeText(this@safeToast, text, duration.length) toast.setGravity(gravity.asGravityInt, 0, 0) toast.show() } }
apache-2.0
30b911286d73d18112e8ad45d7c2bd5e
22.75
73
0.705263
3.87037
false
false
false
false
wireapp/wire-android
storage/src/androidTest/kotlin/com/waz/zclient/storage/userdatabase/folders/FoldersTableTestHelper.kt
1
904
package com.waz.zclient.storage.userdatabase.folders import android.content.ContentValues import com.waz.zclient.storage.DbSQLiteOpenHelper class FoldersTableTestHelper private constructor() { companion object { private const val FOLDERS_TABLE_NAME = "Folders" private const val FOLDERS_ID_COL = "_id" private const val FOLDERS_NAME_COL = "name" private const val FOLDERS_TYPE_COL = "type" fun insertFolder(id: String, name: String, type: Int, openHelper: DbSQLiteOpenHelper) { val contentValues = ContentValues().also { it.put(FOLDERS_ID_COL, id) it.put(FOLDERS_NAME_COL, name) it.put(FOLDERS_TYPE_COL, type) } openHelper.insertWithOnConflict( tableName = FOLDERS_TABLE_NAME, contentValues = contentValues ) } } }
gpl-3.0
1a8f4dc6a4c1fb620db6a904c93e6f49
32.481481
95
0.622788
4.475248
false
false
false
false
inorichi/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/data/track/anilist/AnilistModels.kt
1
3414
package eu.kanade.tachiyomi.data.track.anilist import eu.kanade.tachiyomi.data.database.models.Track import eu.kanade.tachiyomi.data.preference.PreferencesHelper import eu.kanade.tachiyomi.data.track.TrackManager import eu.kanade.tachiyomi.data.track.model.TrackSearch import uy.kohesive.injekt.injectLazy import java.text.SimpleDateFormat import java.util.Locale data class ALManga( val media_id: Int, val title_user_pref: String, val image_url_lge: String, val description: String?, val format: String, val publishing_status: String, val start_date_fuzzy: Long, val total_chapters: Int ) { fun toTrack() = TrackSearch.create(TrackManager.ANILIST).apply { media_id = [email protected]_id title = title_user_pref total_chapters = [email protected]_chapters cover_url = image_url_lge summary = description ?: "" tracking_url = AnilistApi.mangaUrl(media_id) publishing_status = [email protected]_status publishing_type = format if (start_date_fuzzy != 0L) { start_date = try { val outputDf = SimpleDateFormat("yyyy-MM-dd", Locale.US) outputDf.format(start_date_fuzzy) } catch (e: Exception) { "" } } } } data class ALUserManga( val library_id: Long, val list_status: String, val score_raw: Int, val chapters_read: Int, val start_date_fuzzy: Long, val completed_date_fuzzy: Long, val manga: ALManga ) { fun toTrack() = Track.create(TrackManager.ANILIST).apply { media_id = manga.media_id title = manga.title_user_pref status = toTrackStatus() score = score_raw.toFloat() started_reading_date = start_date_fuzzy finished_reading_date = completed_date_fuzzy last_chapter_read = chapters_read.toFloat() library_id = [email protected]_id total_chapters = manga.total_chapters } fun toTrackStatus() = when (list_status) { "CURRENT" -> Anilist.READING "COMPLETED" -> Anilist.COMPLETED "PAUSED" -> Anilist.PAUSED "DROPPED" -> Anilist.DROPPED "PLANNING" -> Anilist.PLANNING "REPEATING" -> Anilist.REPEATING else -> throw NotImplementedError("Unknown status: $list_status") } } fun Track.toAnilistStatus() = when (status) { Anilist.READING -> "CURRENT" Anilist.COMPLETED -> "COMPLETED" Anilist.PAUSED -> "PAUSED" Anilist.DROPPED -> "DROPPED" Anilist.PLANNING -> "PLANNING" Anilist.REPEATING -> "REPEATING" else -> throw NotImplementedError("Unknown status: $status") } private val preferences: PreferencesHelper by injectLazy() fun Track.toAnilistScore(): String = when (preferences.anilistScoreType().get()) { // 10 point "POINT_10" -> (score.toInt() / 10).toString() // 100 point "POINT_100" -> score.toInt().toString() // 5 stars "POINT_5" -> when { score == 0f -> "0" score < 30 -> "1" score < 50 -> "2" score < 70 -> "3" score < 90 -> "4" else -> "5" } // Smiley "POINT_3" -> when { score == 0f -> "0" score <= 35 -> ":(" score <= 60 -> ":|" else -> ":)" } // 10 point decimal "POINT_10_DECIMAL" -> (score / 10).toString() else -> throw NotImplementedError("Unknown score type") }
apache-2.0
a301522acefcc89e32af8bfc8644773d
29.756757
82
0.617458
3.83165
false
false
false
false
fython/PackageTracker
mobile/src/main/kotlin/info/papdt/express/helper/ui/ImportExportActivity.kt
1
4598
package info.papdt.express.helper.ui import android.app.Activity import android.app.ProgressDialog import android.content.Intent import android.os.Bundle import com.google.android.material.snackbar.Snackbar import androidx.core.app.ShareCompat import android.view.View import java.text.SimpleDateFormat import info.papdt.express.helper.R import info.papdt.express.helper.dao.PackageDatabase import info.papdt.express.helper.ui.common.AbsActivity import moe.feng.kotlinyan.common.* import java.util.* class ImportExportActivity : AbsActivity() { private val database: PackageDatabase by lazy { PackageDatabase.getInstance(applicationContext) } private val BackupApi by lazy { info.papdt.express.helper.api.BackupApi(this@ImportExportActivity) } private var progressDialog: ProgressDialog? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_import_export) } override fun setUpViews() { findViewById<View>(R.id.action_backup_all_data).setOnClickListener { val intent = Intent(Intent.ACTION_CREATE_DOCUMENT) intent.addCategory(Intent.CATEGORY_OPENABLE) intent.type = "text/*" val date = Calendar.getInstance().time val format = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()) intent[Intent.EXTRA_TITLE] = String.format(BACKUP_FILE_NAME, format.format(date)) startActivityForResult(intent, REQUEST_WRITE_BACKUP_FILE) } findViewById<View>(R.id.action_export_list).setOnClickListener { if (database.size() == 0) { Snackbar.make(findViewById(R.id.coordinator_layout)!!, R.string.toast_list_empty, Snackbar.LENGTH_SHORT) .show() } else { ui { val intent = Intent(Intent.ACTION_SEND) intent.type = "text/plain" intent.putExtra(Intent.EXTRA_TEXT, BackupApi.share()) startActivity(Intent.createChooser( intent, getString(R.string.dialog_share_title))) } } } findViewById<View>(R.id.action_restore_all_data).setOnClickListener { val intent = Intent(Intent.ACTION_OPEN_DOCUMENT) intent.addCategory(Intent.CATEGORY_OPENABLE) intent.type = "*/*" startActivityForResult(intent, REQUEST_OPEN_FILE_RESTORE) } } public override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (requestCode == REQUEST_WRITE_BACKUP_FILE && resultCode == Activity.RESULT_OK && data != null) { ui { progressDialog = ProgressDialog(this@ImportExportActivity).apply { setMessage(getString(R.string.dialog_backup_title)) setCancelable(false) } progressDialog?.show() if (BackupApi.backup(data.data!!)) { Snackbar.make( findViewById(R.id.coordinator_layout)!!, R.string.toast_backup_succeed, Snackbar.LENGTH_LONG ).setAction(R.string.toast_backup_send_action) { ShareCompat.IntentBuilder.from(this@ImportExportActivity) .addStream(data.data) .setType("text/*") .startChooser() }.show() } else { Snackbar.make( findViewById(R.id.coordinator_layout)!!, R.string.toast_backup_failed, Snackbar.LENGTH_LONG ).show() } progressDialog?.dismiss() } } if (requestCode == REQUEST_OPEN_FILE_RESTORE && resultCode == Activity.RESULT_OK && data != null) { ui { progressDialog = ProgressDialog(this@ImportExportActivity).apply { setMessage(getString(R.string.dialog_restoring_title)) setCancelable(false) } progressDialog?.show() if (BackupApi.restore(data.data!!)) { buildAlertDialog { titleRes = R.string.dialog_restored_title messageRes = R.string.dialog_restored_message isCancelable = false positiveButton(R.string.dialog_restored_restart_button) { _, _ -> val intent = packageManager .getLaunchIntentForPackage(packageName) val componentName = intent!!.component val i = Intent.makeRestartActivityTask(componentName) startActivity(i) System.exit(0) } }.show() } else { Snackbar.make( findViewById(R.id.coordinator_layout)!!, R.string.toast_restore_failed, Snackbar.LENGTH_LONG ).show() } progressDialog?.dismiss() } } } companion object { private const val BACKUP_FILE_NAME = "PackageTrackerBackup_%s.json" const val REQUEST_WRITE_BACKUP_FILE = 10001 const val REQUEST_OPEN_FILE_RESTORE = 10002 fun launch(activity: Activity) { val intent = Intent(activity, ImportExportActivity::class.java) intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) activity.startActivity(intent) } } }
gpl-3.0
e7ccb4160404735d259b9ce327a43059
30.710345
108
0.709656
3.696141
false
false
false
false
vsch/idea-multimarkdown
src/main/java/com/vladsch/md/nav/inspections/PlantUmlParserExtensionNotificationProvider.kt
1
2218
// Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.vladsch.md.nav.inspections import com.intellij.openapi.util.Key import com.intellij.ui.EditorNotificationPanel import com.vladsch.md.nav.MdBundle import com.vladsch.md.nav.parser.flexmark.MdFencedCodeImageConversionManager import com.vladsch.md.nav.parser.flexmark.MdFencedCodePlantUmlConverter import com.vladsch.md.nav.settings.MdApplicationSettings import com.vladsch.md.nav.settings.MdRenderingProfile import com.vladsch.md.nav.settings.ParserOptions class PlantUmlParserExtensionNotificationProvider : FencedCodeRenderingExtensionNotificationProviderBase() { override fun getKey(): Key<EditorNotificationPanel> { return KEY } override fun getPanelText(): String = MdBundle.message("editor.have-plantuml-references.name") override fun getPanelLabel(): String = MdBundle.message("editor.have-plantuml-references.enable") override var wasShown: Boolean get() = MdApplicationSettings.instance.wasShownSettings.plantUmlExtensionAvailable set(value) { MdApplicationSettings.instance.wasShownSettings.plantUmlExtensionAvailable = value } // override fun haveNeededParserSettings(parserSettings: MdParserSettings): Boolean = parserSettings.anyExtensions(PegdownExtensions.FENCED_CODE_BLOCKS) override fun getDefaultVariant(info: String): String = MdFencedCodePlantUmlConverter.EMBEDDED override fun getInfoStrings(): Array<String> = MdFencedCodePlantUmlConverter.INFO_STRINGS override fun adjustRenderingProfile(conversionManager: MdFencedCodeImageConversionManager, renderingProfile: MdRenderingProfile, fencedCodeTypes: Set<String>) { val newParserSettings = renderingProfile.parserSettings newParserSettings.optionsFlags = newParserSettings.optionsFlags or ParserOptions.GITLAB_MATH_EXT.flags super.adjustRenderingProfile(conversionManager, renderingProfile, fencedCodeTypes) } companion object { private val KEY = Key.create<EditorNotificationPanel>("editor.have-plantuml-references.name") } }
apache-2.0
80a5687c27c311c38c040356217d850c
50.581395
177
0.800721
4.592133
false
false
false
false
jtransc/jtransc
jtransc-core/src/com/jtransc/plugin/JTranscPlugin.kt
1
3875
package com.jtransc.plugin import com.jtransc.ast.* import com.jtransc.ast.dependency.AstDependencyAnalyzer import com.jtransc.ast.treeshaking.TreeShakingApi import com.jtransc.gen.TargetName import com.jtransc.injector.Injector abstract class JTranscPlugin { open val priority: Int = 0 lateinit var injector: Injector; private set lateinit var targetName: TargetName; private set fun initialize(injector: Injector) { this.injector = injector this.targetName = injector.get() } open fun onStartBuilding(program: AstProgram): Unit { } open fun onAfterAllClassDiscovered(program: AstProgram): Unit { } open fun onAfterClassDiscovered(clazz: AstType.REF, program: AstProgram): Unit { } open fun processAfterTreeShaking(program: AstProgram): Unit { } open fun processBeforeTreeShaking(programBase: AstProgram): Unit { } open fun onTreeShakingAddBasicClass(treeShaking: TreeShakingApi, fqname: FqName, oldclass: AstClass, newclass: AstClass): Unit { } open fun onTreeShakingAddField(treeShakingApi: TreeShakingApi, oldfield: AstField, newfield: AstField) { } open fun onTreeShakingAddMethod(treeShakingApi: TreeShakingApi, oldmethod: AstMethod, newmethod: AstMethod) { } open fun onStaticInitHandleMethodCall(program: AstProgram, ast: AstExpr.CALL_BASE, body: AstBody?, da: AstDependencyAnalyzer.AstDependencyAnalyzerGen) { } open fun onAfterAppliedClassFeatures(program: AstProgram) { } open fun onAfterAppliedMethodBodyFeature(method: AstMethod, transformedBody: AstBody) { } fun TreeShakingApi.addMethod(methodRef: AstMethodRef) = addMethod(methodRef, this.javaClass.name) fun TreeShakingApi.addClassFull(fqname: FqName) = addFullClass(fqname, this.javaClass.name) } class JTranscPluginGroup(val plugins: Iterable<JTranscPlugin>) : JTranscPlugin() { override fun onStartBuilding(program: AstProgram) { for (plugin in plugins) plugin.onStartBuilding(program) } override fun onAfterAllClassDiscovered(program: AstProgram) { for (plugin in plugins) plugin.onAfterAllClassDiscovered(program) } override fun onAfterClassDiscovered(clazz: AstType.REF, program: AstProgram) { for (plugin in plugins) plugin.onAfterClassDiscovered(clazz, program) } override fun processAfterTreeShaking(program: AstProgram) { for (plugin in plugins) plugin.processAfterTreeShaking(program) } override fun processBeforeTreeShaking(programBase: AstProgram) { for (plugin in plugins) plugin.processBeforeTreeShaking(programBase) } override fun onTreeShakingAddBasicClass(treeShaking: TreeShakingApi, fqname: FqName, oldclass: AstClass, newclass: AstClass) { for (plugin in plugins) plugin.onTreeShakingAddBasicClass(treeShaking, fqname, oldclass, newclass) } override fun onTreeShakingAddField(treeShakingApi: TreeShakingApi, oldfield: AstField, newfield: AstField) { for (plugin in plugins) plugin.onTreeShakingAddField(treeShakingApi, oldfield, newfield) } override fun onTreeShakingAddMethod(treeShakingApi: TreeShakingApi, oldmethod: AstMethod, newmethod: AstMethod) { for (plugin in plugins) plugin.onTreeShakingAddMethod(treeShakingApi, oldmethod, newmethod) } override fun onStaticInitHandleMethodCall(program: AstProgram, ast: AstExpr.CALL_BASE, body: AstBody?, da: AstDependencyAnalyzer.AstDependencyAnalyzerGen) { for (plugin in plugins) plugin.onStaticInitHandleMethodCall(program, ast, body, da) } override fun onAfterAppliedClassFeatures(program: AstProgram) { for (plugin in plugins) plugin.onAfterAppliedClassFeatures(program) } override fun onAfterAppliedMethodBodyFeature(method: AstMethod, transformedBody: AstBody) { for (plugin in plugins) plugin.onAfterAppliedMethodBodyFeature(method, transformedBody) } } fun Iterable<JTranscPlugin>.toGroup(injector: Injector) = JTranscPluginGroup(this).apply { initialize(injector) for (plugin in this@toGroup) plugin.initialize(injector) }
apache-2.0
38e72bdb14d39ecac0d090fb922939e1
35.566038
157
0.801548
3.871129
false
false
false
false
AM5800/polyglot
app/src/main/kotlin/com/am5800/polyglot/app/sentenceGeneration/content/KnownWords.kt
1
9024
package com.am5800.polyglot.app.sentenceGeneration.content import com.am5800.polyglot.app.sentenceGeneration.Word import com.am5800.polyglot.app.sentenceGeneration.commonAttributes.Gender import com.am5800.polyglot.app.sentenceGeneration.commonAttributes.Number import com.am5800.polyglot.app.sentenceGeneration.commonAttributes.Person import com.am5800.polyglot.app.sentenceGeneration.english.EnglishVerb import com.am5800.polyglot.app.sentenceGeneration.english.EnglishWeakVerb import com.am5800.polyglot.app.sentenceGeneration.english.Pronoun import com.am5800.polyglot.app.sentenceGeneration.russian.RussianVerb data class WordPair(val russian: Word, val english: Word) class KnownWords { val words = mutableListOf<WordPair>() init { addPronouns() addVerbs() } private fun addVerbs() { val giveRussian = RussianVerb.define { infinitive("давать") present("даю, даешь, даем, даете, дает, дают") past("давал, давали, давала, давало") } val giveEnglish = EnglishVerb("give", "gave", "gives") val takeRussian = RussianVerb.define { infinitive("брать") present("беру, берешь, берем, даете, дает, дают") past("брал, брали, брала, брало") } val takeEnglish = EnglishVerb("take", "took", "takes") val seeRussian = RussianVerb.define { infinitive("видеть") present("вижу, видишь, видим, видите, видит, видят") past("видел, видели, видела, видело") } val seeEnglish = EnglishVerb("see", "saw", "sees") val comeRussian = RussianVerb.define { infinitive("приходить") present("прихожу, приходишь, приходим, приходите, приходит, приходят") past("приходил, приходили, приходила, приходило") } val comeEnglish = EnglishVerb("come", "came", "comes") val goRussian = RussianVerb.define { infinitive("идти") present("иду, идешь, идем, идете, идет, идут") past("шел, шли, шла, шло") } val goEnglish = EnglishVerb("go", "went", "goes") val knowRussian = RussianVerb.define { infinitive("знать") present("знаю, знаешь, знаем, знаете, знает, знают") past("знал, знали, знала, знало") } val knowEnglish = EnglishVerb("know", "knew", "knows") val speakRussian = RussianVerb.define { infinitive("говорить") present("говорю, говоришь, говорим, говорите, говорит, говорят") past("говорил, говорили, говорила, говорило") } val speakEnglish = EnglishVerb("speak", "spoke", "speaks") val eatRussian = RussianVerb.define { infinitive("есть") present("ем, ешь, едим, едите, ест, едят") past("ел, ели, ела, ело") } val eatEnglish = EnglishVerb("eat", "ate", "eats") val workRussian = RussianVerb.define { infinitive("работать") present("работаю, работаешь, работаем, работаете, работает, работают") past("работал, работали, работала, работало") } val workEnglish = EnglishWeakVerb("work") val openRussian = RussianVerb.define { infinitive("открывать") present("открываю, открываешь, открываем, открываете, открывает, открывают") past("открывал, открывали, открывала, открывало") } val openEnglish = EnglishWeakVerb("open") val closeRussian = RussianVerb.define { infinitive("закрывать") present("закрываю, закрываешь, закрываем, закрываете, закрывает, закрывают") past("закрывал, закрывали, закрывала, закрывало") } val closeEnglish = EnglishVerb("close", "closed", "closes") val finishRussian = RussianVerb.define { infinitive("заканчивать") present("заканчиваю, заканчиваешь, заканчиваем, заканчиваете, заканчивает, заканчивают") past("заканчивал, заканчивали, заканчивала, заканчивало") } val finishEnglish = EnglishVerb("finish", "finished", "finishes") val travelRussian = RussianVerb.define { infinitive("путешествовать") present("путешествую, путешествуешь, путешествуем, путешествуете, путешестует, путешествуют") past("путешествовал, путешествовали, путешествовала, путешествовало") } val travelEnglish = EnglishWeakVerb("travel") val askRussian = RussianVerb.define { infinitive("спрашивать") present("спрашиваю, спрашиваешь, спрашиваем, спрашиваете, спрашивает, спрашивают") past("спрашивал, спрашивали, спрашивала, спрашивало") } val askEnglish = EnglishWeakVerb("ask") val answerRussian = RussianVerb.define { infinitive("отвечать") present("отвечаю, отвечаешь, отвечаем, отвечаете, отвечает, отвечают") past("отвечал, отвечали, отвечала, отвечало") } val answerEnglish = EnglishWeakVerb("answer") val helpRussian = RussianVerb.define { infinitive("помогать") present("помогаю, помогаешь, помогаем, помогаете, помогает, помогают") past("помогал, помогали, помогала, помогало") } val helpEnglish = EnglishWeakVerb("help") val loveRussian = RussianVerb.define { infinitive("любить") present("люблю, любишь, любим, любите, любит, любят") past("любил, любили, любила, любило") } val loveEnglish = EnglishWeakVerb("love") words.add(WordPair(giveRussian, giveEnglish)) words.add(WordPair(takeRussian, takeEnglish)) words.add(WordPair(seeRussian, seeEnglish)) words.add(WordPair(comeRussian, comeEnglish)) words.add(WordPair(goRussian, goEnglish)) words.add(WordPair(knowRussian, knowEnglish)) words.add(WordPair(speakRussian, speakEnglish)) words.add(WordPair(eatRussian, eatEnglish)) words.add(WordPair(workRussian, workEnglish)) words.add(WordPair(openRussian, openEnglish)) words.add(WordPair(closeRussian, closeEnglish)) words.add(WordPair(finishRussian, finishEnglish)) words.add(WordPair(travelRussian, travelEnglish)) words.add(WordPair(askRussian, askEnglish)) words.add(WordPair(answerRussian, answerEnglish)) words.add(WordPair(helpRussian, helpEnglish)) words.add(WordPair(loveRussian, loveEnglish)) } private fun addPronouns() { val iRussian = Pronoun("я", Person.First, Number.Singular, null) val iEnglish = Pronoun("I", Person.First, Number.Singular, null) val thouRussian = Pronoun("ты", Person.Second, Number.Singular, null) val thouEnglish = Pronoun("you", Person.Second, Number.Singular, null) val weRussian = Pronoun("мы", Person.First, Number.Plural, null) val weEnglish = Pronoun("we", Person.First, Number.Plural, null) val youRussian = Pronoun("вы", Person.Second, Number.Plural, null) val youEnglish = Pronoun("you", Person.Second, Number.Plural, null) val heRussian = Pronoun("он", Person.Third, Number.Singular, Gender.Masculine) val heEnglish = Pronoun("he", Person.Third, Number.Singular, Gender.Masculine) val sheRussian = Pronoun("она", Person.Third, Number.Singular, Gender.Feminine) val sheEnglish = Pronoun("she", Person.Third, Number.Singular, Gender.Feminine) val itRussian = Pronoun("оно", Person.Third, Number.Singular, Gender.Neuter) val itEnglish = Pronoun("it", Person.Third, Number.Singular, Gender.Neuter) val theyRussian = Pronoun("они", Person.Third, Number.Plural, null) val theyEnglish = Pronoun("they", Person.Third, Number.Plural, null) words.add(WordPair(iRussian, iEnglish)) words.add(WordPair(thouRussian, thouEnglish)) words.add(WordPair(weRussian, weEnglish)) words.add(WordPair(youRussian, youEnglish)) words.add(WordPair(heRussian, heEnglish)) words.add(WordPair(sheRussian, sheEnglish)) words.add(WordPair(itRussian, itEnglish)) words.add(WordPair(theyRussian, theyEnglish)) } }
gpl-3.0
1616a723ca7b1e393149e0eed90fc6bf
37.97449
99
0.703849
2.955882
false
false
false
false
http4k/http4k
http4k-realtime-core/src/main/kotlin/org/http4k/sse/sse.kt
1
1548
package org.http4k.sse import org.http4k.core.Request import org.http4k.routing.RoutingSseHandler import java.io.InputStream import java.time.Duration import java.util.Base64.getEncoder interface Sse { val connectRequest: Request fun send(message: SseMessage) fun close() fun onClose(fn: () -> Unit) } typealias SseConsumer = (Sse) -> Unit typealias SseHandler = (Request) -> SseConsumer sealed class SseMessage { data class Data(val data: String) : SseMessage() { constructor(data: ByteArray) : this(getEncoder().encodeToString(data)) constructor(data: InputStream) : this(data.readAllBytes()) } data class Event(val event: String, val data: String, val id: String? = null) : SseMessage() { constructor(event: String, data: ByteArray, id: String? = null) : this( event, getEncoder().encodeToString(data), id ) constructor(event: String, data: InputStream, id: String? = null) : this(event, data.readAllBytes(), id) } data class Retry(val backoff: Duration) : SseMessage() companion object } fun interface SseFilter : (SseConsumer) -> SseConsumer { companion object } val SseFilter.Companion.NoOp: SseFilter get() = SseFilter { next -> { next(it) } } fun SseFilter.then(next: SseFilter): SseFilter = SseFilter { this(next(it)) } fun SseFilter.then(next: SseConsumer): SseConsumer = { this(next)(it) } fun SseFilter.then(routingSseHandler: RoutingSseHandler): RoutingSseHandler = routingSseHandler.withFilter(this)
apache-2.0
a1e6f956388931509cde9575be2a5306
29.352941
112
0.692506
3.518182
false
false
false
false
msebire/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/parser/parserUtils.kt
1
16565
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. @file:JvmName("GroovyParserUtils") @file:Suppress("UNUSED_PARAMETER", "LiftReturnOrAssignment") package org.jetbrains.plugins.groovy.lang.parser import com.intellij.codeInsight.completion.CompletionUtilCore.DUMMY_IDENTIFIER_TRIMMED import com.intellij.lang.PsiBuilder import com.intellij.lang.PsiBuilder.Marker import com.intellij.lang.PsiBuilderUtil.parseBlockLazy import com.intellij.lang.parser.GeneratedParserUtilBase.* import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.util.Key import com.intellij.openapi.util.KeyWithDefaultValue import com.intellij.openapi.util.text.StringUtil.contains import com.intellij.psi.tree.IElementType import com.intellij.psi.tree.TokenSet import org.jetbrains.plugins.groovy.GroovyBundle import org.jetbrains.plugins.groovy.lang.lexer.GroovyLexer import org.jetbrains.plugins.groovy.lang.parser.GroovyGeneratedParser.closure_header_with_arrow import org.jetbrains.plugins.groovy.lang.parser.GroovyGeneratedParser.parenthesized_lambda_expression_head import org.jetbrains.plugins.groovy.lang.psi.GroovyElementTypes.* import org.jetbrains.plugins.groovy.lang.psi.GroovyTokenSets.* import org.jetbrains.plugins.groovy.util.get import org.jetbrains.plugins.groovy.util.set import org.jetbrains.plugins.groovy.util.withKey import java.util.* private val PsiBuilder.groovyParser: GroovyParser get() = (this as Builder).parser as GroovyParser private val collapseHook = Hook<IElementType> { _, marker: Marker?, elementType: IElementType -> marker ?: return@Hook null val newMarker = marker.precede() marker.drop() newMarker.collapse(elementType) newMarker } fun parseBlockLazy(builder: PsiBuilder, level: Int, deepParser: Parser, elementType: IElementType): Boolean { return if (builder.groovyParser.parseDeep()) { deepParser.parse(builder, level + 1) } else { register_hook_(builder, collapseHook, elementType) parseBlockLazy(builder, T_LBRACE, T_RBRACE, elementType) != null } } fun extendedStatement(builder: PsiBuilder, level: Int): Boolean = builder.groovyParser.parseExtendedStatement(builder) fun extendedSeparator(builder: PsiBuilder, level: Int): Boolean = builder.advanceIf { builder.groovyParser.isExtendedSeparator(tokenType) } private val currentClassNames: Key<Deque<String>> = KeyWithDefaultValue.create("groovy.parse.class.name") { LinkedList<String>() } private val parseDiamonds: Key<Boolean> = Key.create("groovy.parse.diamonds") private val parseArguments: Key<Boolean> = Key.create("groovy.parse.arguments") private val parseApplicationArguments: Key<Boolean> = Key.create("groovy.parse.application.arguments") private val parseAnyTypeElement: Key<Boolean> = Key.create("groovy.parse.any.type.element") private val parseQualifiedName: Key<Boolean> = Key.create("groovy.parse.qualified.name") private val parseCapitalizedCodeReference: Key<Boolean> = Key.create("groovy.parse.capitalized") private val parseDefinitelyTypeElement: Key<Boolean> = Key.create("groovy.parse.definitely.type.element") private val referenceWasCapitalized: Key<Boolean> = Key.create("groovy.parse.ref.was.capitalized") private val typeWasPrimitive: Key<Boolean> = Key.create("groovy.parse.type.was.primitive") private val referenceHadTypeArguments: Key<Boolean> = Key.create("groovy.parse.ref.had.type.arguments") private val referenceWasQualified: Key<Boolean> = Key.create("groovy.parse.ref.was.qualified") fun classIdentifier(builder: PsiBuilder, level: Int): Boolean { if (builder.tokenType === IDENTIFIER) { builder[currentClassNames]!!.push(builder.tokenText) builder.advanceLexer() return true } else { return false } } fun popClassIdentifier(builder: PsiBuilder, level: Int): Boolean { builder[currentClassNames]!!.pop() return true } fun constructorIdentifier(builder: PsiBuilder, level: Int): Boolean { return builder.advanceIf { tokenType === IDENTIFIER && tokenText == this[currentClassNames]!!.peek() } } fun allowDiamond(builder: PsiBuilder, level: Int, parser: Parser): Boolean { return builder.withKey(parseDiamonds, true) { parser.parse(builder, level) } } fun isDiamondAllowed(builder: PsiBuilder, level: Int): Boolean = builder[parseDiamonds] fun anyTypeElement(builder: PsiBuilder, level: Int, typeElement: Parser): Boolean { return builder.withKey(parseAnyTypeElement, true) { typeElement.parse(builder, level + 1) } } private val PsiBuilder.anyTypeElementParsing get() = this[parseAnyTypeElement] fun qualifiedName(builder: PsiBuilder, level: Int, parser: Parser): Boolean { return builder.withKey(parseQualifiedName, true) { parser.parse(builder, level) } } fun isQualifiedName(builder: PsiBuilder, level: Int): Boolean = builder[parseQualifiedName] fun capitalizedTypeElement(builder: PsiBuilder, level: Int, typeElement: Parser, check: Parser): Boolean { try { return builder.withKey(parseCapitalizedCodeReference, true) { typeElement.parse(builder, level) && check.parse(builder, level) } } finally { builder[referenceWasCapitalized] = null } } private val PsiBuilder.capitalizedReferenceParsing get() = this[parseCapitalizedCodeReference] && !anyTypeElementParsing fun refWasCapitalized(builder: PsiBuilder, level: Int): Boolean = builder[referenceWasCapitalized] fun codeReferenceIdentifier(builder: PsiBuilder, level: Int, identifier: Parser): Boolean { if (builder.capitalizedReferenceParsing) { val capitalized = builder.isNextTokenCapitalized() val result = identifier.parse(builder, level) if (result) { builder[referenceWasCapitalized] = capitalized } else { builder[referenceWasCapitalized] = null } return result } return identifier.parse(builder, level) } private fun PsiBuilder.isNextTokenCapitalized(): Boolean { val text = tokenText return text != null && text.isNotEmpty() && text != DUMMY_IDENTIFIER_TRIMMED && text.first().isUpperCase() } fun definitelyTypeElement(builder: PsiBuilder, level: Int, typeElement: Parser, check: Parser): Boolean { val result = builder.withKey(parseDefinitelyTypeElement, true) { typeElement.parse(builder, level) } && (builder.wasDefinitelyTypeElement() || check.parse(builder, level)) builder.clearTypeInfo() return result } private val PsiBuilder.definitelyTypeElementParsing get() = this[parseDefinitelyTypeElement] && !anyTypeElementParsing private fun PsiBuilder.wasDefinitelyTypeElement(): Boolean { return this[typeWasPrimitive] || this[referenceHadTypeArguments] || this[referenceWasQualified] } private fun PsiBuilder.clearTypeInfo() { this[typeWasPrimitive] = null this[referenceHadTypeArguments] = null this[referenceWasQualified] = null } fun setTypeWasPrimitive(builder: PsiBuilder, level: Int): Boolean { if (builder.definitelyTypeElementParsing) { builder[typeWasPrimitive] = true } return true } fun setRefWasQualified(builder: PsiBuilder, level: Int): Boolean { if (builder.definitelyTypeElementParsing) { builder[referenceWasQualified] = true } return true } fun setRefHadTypeArguments(builder: PsiBuilder, level: Int): Boolean { if (builder.definitelyTypeElementParsing) { builder[referenceHadTypeArguments] = true } return true } fun parseArgument(builder: PsiBuilder, level: Int, argumentParser: Parser): Boolean { return builder.withKey(parseArguments, true) { argumentParser.parse(builder, level) } } fun isArguments(builder: PsiBuilder, level: Int): Boolean = builder[parseArguments] fun applicationArguments(builder: PsiBuilder, level: Int, parser: Parser): Boolean { return builder.withKey(parseApplicationArguments, true) { parser.parse(builder, level) } } fun notApplicationArguments(builder: PsiBuilder, level: Int, parser: Parser): Boolean { return builder.withKey(parseApplicationArguments, null) { parser.parse(builder, level) } } fun isApplicationArguments(builder: PsiBuilder, level: Int): Boolean = builder[parseApplicationArguments] fun closureArgumentSeparator(builder: PsiBuilder, level: Int, closureArguments: Parser): Boolean { if (builder.tokenType === NL) { if (isApplicationArguments(builder, level)) { return false } builder.advanceLexer() } return closureArguments.parse(builder, level) } /** *``` * foo a // ref <- application * foo a ref // application <- ref * foo a(ref) * foo a.ref * foo a[ref] * foo a ref c // ref <- application * foo a ref(c) // ref <- call * foo a ref[c] // ref <- index * foo a ref[c] ref // index <- ref * foo a ref[c] (a) // index <- call * foo a ref[c] {} // index <- call * foo a ref(c) ref // call <- ref * foo a ref(c)(c) // call <- call * foo a ref(c)[c] // call <- index *``` */ fun parseApplication(builder: PsiBuilder, level: Int, refParser: Parser, applicationParser: Parser, callParser: Parser, indexParser: Parser): Boolean { val wrappee = builder.latestDoneMarker ?: return false val nextLevel = level + 1 return when (wrappee.tokenType) { APPLICATION_EXPRESSION -> { refParser.parse(builder, nextLevel) } METHOD_CALL_EXPRESSION -> { indexParser.parse(builder, nextLevel) || callParser.parse(builder, nextLevel) || refParser.parse(builder, nextLevel) } REFERENCE_EXPRESSION -> { indexParser.parse(builder, nextLevel) || callParser.parse(builder, nextLevel) || applicationParser.parse(builder, nextLevel) } APPLICATION_INDEX -> { callParser.parse(builder, nextLevel) || refParser.parse(builder, nextLevel) } else -> applicationParser.parse(builder, nextLevel) } } fun parseKeyword(builder: PsiBuilder, level: Int): Boolean = builder.advanceIf(KEYWORDS) fun parsePrimitiveType(builder: PsiBuilder, level: Int): Boolean = builder.advanceIf(primitiveTypes) fun assignmentOperator(builder: PsiBuilder, level: Int): Boolean = builder.advanceIf(ASSIGNMENTS) fun equalityOperator(builder: PsiBuilder, level: Int): Boolean = builder.advanceIf(EQUALITY_OPERATORS) fun error(builder: PsiBuilder, level: Int, key: String): Boolean { val marker = builder.latestDoneMarker ?: return false val elementType = marker.tokenType val newMarker = (marker as Marker).precede() marker.drop() builder.error(GroovyBundle.message(key)) newMarker.done(elementType) return true } fun unexpected(builder: PsiBuilder, level: Int, key: String): Boolean { return unexpected(builder, level, Parser { b, _ -> b.any() }, key) } fun unexpected(builder: PsiBuilder, level: Int, parser: Parser, key: String): Boolean { val marker = builder.mark() if (parser.parse(builder, level)) { marker.error(GroovyBundle.message(key)) } else { marker.drop() } return true } fun parseTailLeftFlat(builder: PsiBuilder, level: Int, head: Parser, tail: Parser): Boolean { val marker = builder.mark() if (!head.parse(builder, level)) { marker.drop() return false } else { if (!tail.parse(builder, level)) { marker.drop() report_error_(builder, false) } else { val tailMarker = builder.latestDoneMarker!! val elementType = tailMarker.tokenType (tailMarker as Marker).drop() marker.done(elementType) } return true } } private fun <T> PsiBuilder.lookahead(action: PsiBuilder.() -> T): T { val marker = mark() val result = action() marker.rollbackTo() return result } private fun PsiBuilder.any(): Boolean = advanceIf { true } private fun PsiBuilder.advanceIf(tokenSet: TokenSet): Boolean = advanceIf { tokenType in tokenSet } private inline fun PsiBuilder.advanceIf(crossinline condition: PsiBuilder.() -> Boolean): Boolean { if (condition()) { advanceLexer() return true } else { return false } } fun noMatch(builder: PsiBuilder, level: Int): Boolean = false fun addVariant(builder: PsiBuilder, level: Int, variant: String): Boolean { addVariant(builder, "<$variant>") return true } fun clearVariants(builder: PsiBuilder, level: Int): Boolean { val state = builder.state state.clearVariants(state.currentFrame) return true } fun replaceVariants(builder: PsiBuilder, level: Int, variant: String): Boolean { return clearVariants(builder, level) && addVariant(builder, level, variant) } fun clearError(builder: PsiBuilder, level: Int): Boolean { builder.state.currentFrame.errorReportedAt = -1 return true } fun withProtectedLastVariantPos(builder: PsiBuilder, level: Int, parser: Parser): Boolean { val state = builder.state val prev = state.currentFrame.lastVariantAt if (parser.parse(builder, level)) { return true } else { state.currentFrame.lastVariantAt = prev return false } } private val PsiBuilder.state: ErrorState get() = ErrorState.get(this) fun newLine(builder: PsiBuilder, level: Int): Boolean { builder.eof() // force skip whitespaces val prevStart = builder.rawTokenTypeStart(-1) val currentStart = builder.rawTokenTypeStart(0) return contains(builder.originalText, prevStart, currentStart, '\n') } fun noNewLine(builder: PsiBuilder, level: Int): Boolean = !newLine(builder, level) fun castOperandCheck(builder: PsiBuilder, level: Int): Boolean { return builder.tokenType !== T_LPAREN || builder.lookahead { castOperandCheckInner(this) } } private fun castOperandCheckInner(builder: PsiBuilder): Boolean { var parenCount = 0 while (!builder.eof()) { builder.advanceLexer() val tokenType = builder.tokenType when { tokenType === T_LPAREN -> { parenCount++ } tokenType === T_RPAREN -> { if (parenCount == 0) { // we discovered closing parenthesis and didn't find any commas return true } parenCount-- } tokenType === T_COMMA -> { if (parenCount == 0) { // comma on the same level of parentheses means we are in argument list return false } } } } return false } fun isParameterizedClosure(builder: PsiBuilder, level: Int): Boolean { return builder.lookahead { isParameterizedClosureInner(this, level) } } private fun isParameterizedClosureInner(builder: PsiBuilder, level: Int): Boolean { if (!consumeTokenFast(builder, T_LBRACE)) return false GroovyGeneratedParser.mb_nl(builder, level) return closure_header_with_arrow(builder, level) } fun isParameterizedLambda(builder: PsiBuilder, level: Int): Boolean { return builder.lookahead { parenthesized_lambda_expression_head(builder, level) } } private val explicitLeftMarker = Key.create<Marker>("groovy.parse.left.marker") /** * Stores [PsiBuilder.getLatestDoneMarker] in user data to be able to use it later in [wrapLeft]. */ fun markLeft(builder: PsiBuilder, level: Int): Boolean { builder[explicitLeftMarker] = builder.latestDoneMarker as? Marker return true } /** * Let sequence `a b c d` result in the following tree: `(a) (b) (c) (d)`. * Then `a b <<markLeft>> c d <<wrapLeft>>` will result in: `(a) ((b) (c) d)` */ fun wrapLeft(builder: PsiBuilder, level: Int): Boolean { val explicitLeft = builder[explicitLeftMarker] ?: return false val latest = builder.latestDoneMarker ?: return false explicitLeft.precede().done(latest.tokenType) (latest as? Marker)?.drop() return true } fun choice(builder: PsiBuilder, level: Int, vararg parsers: Parser): Boolean { assert(parsers.size > 1) for (parser in parsers) { if (parser.parse(builder, level)) return true } return false } fun isBlockParseable(text: CharSequence): Boolean { val lexer = GroovyLexer().apply { start(text) } if (lexer.tokenType !== T_LBRACE) return false lexer.advance() val leftStack = LinkedList<IElementType>().apply { push(T_LBRACE) } while (true) { ProgressManager.checkCanceled() val type = lexer.tokenType ?: return leftStack.isEmpty() if (leftStack.isEmpty()) { return false } when (type) { T_LBRACE, T_LPAREN -> leftStack.push(type) T_RBRACE -> { if (leftStack.isEmpty() || leftStack.pop() != T_LBRACE) { return false } } T_RPAREN -> { if (leftStack.isEmpty() || leftStack.pop() != T_LPAREN) { return false } } } lexer.advance() } }
apache-2.0
88a994a42e49f21b6a062f62cfc73a04
32.063872
140
0.716873
3.978146
false
false
false
false
danfma/kodando
kodando-rxjs/src/test/kotlin/kodando/rxjs/tests/ObservableCreateSpec.kt
1
2203
package kodando.rxjs.tests import kodando.jest.Spec import kodando.jest.expect import kodando.runtime.async.await import kodando.rxjs.Observable import kodando.rxjs.observable.fromEvent import kodando.rxjs.observable.of import kodando.rxjs.operators.combineAll import kodando.rxjs.operators.take import kodando.rxjs.operators.toArray import org.w3c.dom.events.Event import kotlin.browser.document /** * Created by danfma on 03/05/17. */ object ObservableCreateSpec : Spec() { init { describe("Observable") { it("should be able to produce elements") byCheckingAfter { val observable = Observable<Int> { observer -> observer.next(1) observer.next(2) observer.complete() null } val produced = await(observable.toArray().toPromise()) val expected = arrayOf(1, 2) expect(produced).toEqual(expected) } } describe("createWithSubscription") { it("should be able to produce and unsubscribe after") byCheckingAfter { val source = of(1) val observable = Observable<Int> { observer -> source.subscribe(observer) } val produced = await(observable.toArray().toPromise()) val expected = arrayOf(1) expect(produced).toEqual(expected) } } describe("fromEvent") { it("should return the events of this target") byCheckingAfter { val click = document.createEvent("Event") click.initEvent("click", true, true) val source = document.createElement("div") val observable = fromEvent<Event>(source, "click") val promise = observable.take(1).toPromise() source.dispatchEvent(click) val produced = await(promise) val expected = click expect(produced).toBe(expected) } } describe("combineAll") { it("should combine the observables into all") byCheckingAfter { val one = of(1) val two = of(2) val combined = of(one, two).combineAll() val produced = await(combined.toArray().toPromise()) val expected = arrayOf(arrayOf(1, 2)) expect(produced).toEqual(expected) } } } }
mit
f5a5972ddf95cc90afdc9f3d00b11947
24.616279
77
0.64049
4.261122
false
false
false
false
EPadronU/balin
src/main/kotlin/com/github/epadronu/balin/core/Page.kt
1
4630
/****************************************************************************** * Copyright 2016 Edinson E. Padrón Urdaneta * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /* ***************************************************************************/ package com.github.epadronu.balin.core /* ***************************************************************************/ /* ***************************************************************************/ import org.openqa.selenium.SearchContext import org.openqa.selenium.WebElement /* ***************************************************************************/ /* ***************************************************************************/ /** * This class is the corner stone for Balin's implementation of the * _Page Object Design Pattern_. All classes that model a Web page/view most * extend this one. * * @sample com.github.epadronu.balin.core.PageTests.model_a_page_into_a_page_object_navigate_and_interact_with * * @param browser the browser used by the page in order to interact with the underlying web content. * @constructor Create a new instance with the given browser as its bridge with the web content the page care about. */ abstract class Page(val browser: Browser) : ClickAndNavigateSupport, ComponentMappingSupport, JavaScriptSupport by browser, SearchContext by browser, WaitingSupport by browser { companion object { /** * This method eases the definition of a page's _implicit at verification_. * * @sample com.github.epadronu.balin.core.PageTests.model_a_page_into_a_page_object_navigate_and_interact_with * * @param block context within which you can interact with the browser. * @return The [block] unchanged. */ @JvmStatic fun at(block: Browser.() -> Any): Browser.() -> Any = block } /** * Defines an optional _implicit verification_ to be checked as soon as the * browser navigates to the page. * * Useful for performing early failure. * * @sample com.github.epadronu.balin.core.PageTests.model_a_page_into_a_page_object_navigate_and_interact_with */ open val at: Browser.() -> Any = { true } /** * Defines an optional URL, which will be used when invoking * [Browser.to] with a page factory. * * @sample com.github.epadronu.balin.core.PageTests.model_a_page_into_a_page_object_navigate_and_interact_with */ open val url: String? = null /** * Click on an element and tells the browser it will navigate to the given * page as consequence of such action. * * @sample com.github.epadronu.balin.core.PageTests.use_WebElement_click_in_a_page_to_place_the_browser_at_a_different_page * * @receiver the [WebElement][org.openqa.selenium.WebElement] to be clicked on. * @param factory provides an instance of the page given the driver being used by the browser. * @Returns An instance of the page the browser will navigate to. * @throws PageImplicitAtVerificationException if the page has an _implicit at verification_ which have failed. */ override fun <T : Page> WebElement.click(factory: (Browser) -> T): T { this.click() return browser.at(factory) } override fun <T : Component> WebElement.component(factory: (Page, WebElement) -> T): T = factory(this@Page, this) override fun <T : Component> List<WebElement>.component(factory: (Page, WebElement) -> T): List<T> = this.map { factory(this@Page, it) } /** * Evaluate the page's _implicit at verification_. * * @return true if the verification passed, false otherwise. */ internal fun verifyAt(): Boolean = when (val result = at(browser)) { is Boolean -> result is Unit -> true else -> throw Error("Expressions of type `${result.javaClass.canonicalName}` are not allowed.") } } /* ***************************************************************************/
apache-2.0
199bb9f6cee38ad8b5d27d8614bb032b
41.861111
127
0.589544
4.61976
false
false
false
false
matkoniecz/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/quests/cycleway/AddCyclewayForm.kt
1
12993
package de.westnordost.streetcomplete.quests.cycleway import android.os.Bundle import androidx.annotation.AnyThread import android.view.View import androidx.appcompat.app.AlertDialog import androidx.core.view.isGone import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.data.osm.geometry.ElementPolylinesGeometry import de.westnordost.streetcomplete.data.elementfilter.toElementFilterExpression import de.westnordost.streetcomplete.databinding.QuestStreetSidePuzzleWithLastAnswerButtonBinding import de.westnordost.streetcomplete.quests.AbstractQuestFormAnswerFragment import de.westnordost.streetcomplete.quests.AnswerItem import de.westnordost.streetcomplete.quests.StreetSideRotater import de.westnordost.streetcomplete.util.normalizeDegrees import de.westnordost.streetcomplete.view.ResImage import de.westnordost.streetcomplete.view.image_select.ImageListPickerDialog import kotlin.math.absoluteValue class AddCyclewayForm : AbstractQuestFormAnswerFragment<CyclewayAnswer>() { override val contentLayoutResId = R.layout.quest_street_side_puzzle_with_last_answer_button private val binding by contentViewBinding(QuestStreetSidePuzzleWithLastAnswerButtonBinding::bind) override val buttonPanelAnswers get() = if(isDisplayingPreviousCycleway) listOf( AnswerItem(R.string.quest_generic_hasFeature_no) { setAsResurvey(false) }, AnswerItem(R.string.quest_generic_hasFeature_yes) { onClickOk() } ) else emptyList() override val otherAnswers: List<AnswerItem> get() { val isNoRoundabout = osmElement!!.tags["junction"] != "roundabout" val result = mutableListOf<AnswerItem>() if (!isDefiningBothSides && isNoRoundabout) { result.add(AnswerItem(R.string.quest_cycleway_answer_contraflow_cycleway) { showBothSides() }) } result.add(AnswerItem(R.string.quest_cycleway_answer_no_bicycle_infrastructure) { noCyclewayHereHint() }) return result } override val contentPadding = false private var isDisplayingPreviousCycleway: Boolean = false private fun noCyclewayHereHint() { activity?.let { AlertDialog.Builder(it) .setTitle(R.string.quest_cycleway_answer_no_bicycle_infrastructure_title) .setMessage(R.string.quest_cycleway_answer_no_bicycle_infrastructure_explanation) .setPositiveButton(android.R.string.ok, null) .show() } } private val likelyNoBicycleContraflow = """ ways with oneway:bicycle != no and ( oneway ~ yes|-1 and highway ~ primary|primary_link|secondary|secondary_link|tertiary|tertiary_link|unclassified or junction = roundabout ) """.toElementFilterExpression() private var streetSideRotater: StreetSideRotater? = null private var isDefiningBothSides: Boolean = false private var leftSide: Cycleway? = null private var rightSide: Cycleway? = null /** returns whether the side that goes into the opposite direction of the driving direction of a * one-way is on the right side of the way */ private val isReverseSideRight get() = isReversedOneway xor isLeftHandTraffic private val isOneway get() = isForwardOneway || isReversedOneway private val isForwardOneway get() = osmElement!!.tags["oneway"] == "yes" private val isReversedOneway get() = osmElement!!.tags["oneway"] == "-1" // just a shortcut private val isLeftHandTraffic get() = countryInfo.isLeftHandTraffic override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) if (savedInstanceState == null) { initStateFromTags() } else { onLoadInstanceState(savedInstanceState) } binding.puzzleView.onClickSideListener = { isRight -> showCyclewaySelectionDialog(isRight) } streetSideRotater = StreetSideRotater( binding.puzzleView, binding.littleCompass.root, elementGeometry as ElementPolylinesGeometry ) if (!isDefiningBothSides) { if (isLeftHandTraffic) binding.puzzleView.showOnlyLeftSide() else binding.puzzleView.showOnlyRightSide() } val defaultResId = if (isLeftHandTraffic) R.drawable.ic_cycleway_unknown_l else R.drawable.ic_cycleway_unknown binding.puzzleView.setLeftSideImage(ResImage(leftSide?.getIconResId(isLeftHandTraffic) ?: defaultResId)) binding.puzzleView.setRightSideImage(ResImage(rightSide?.getIconResId(isLeftHandTraffic) ?: defaultResId)) binding.puzzleView.setLeftSideText(leftSide?.getTitleResId()?.let { resources.getString(it) }) binding.puzzleView.setRightSideText(rightSide?.getTitleResId()?.let { resources.getString(it) }) if ((leftSide == null || rightSide == null) && !HAS_SHOWN_TAP_HINT) { if (leftSide == null) binding.puzzleView.showLeftSideTapHint() if (rightSide == null) binding.puzzleView.showRightSideTapHint() HAS_SHOWN_TAP_HINT = true } updateLastAnswerButtonVisibility() lastSelection?.let { binding.lastAnswerButton.leftSideImageView.setImageResource(it.left.getDialogIconResId(isLeftHandTraffic)) binding.lastAnswerButton.rightSideImageView.setImageResource(it.right.getDialogIconResId(isLeftHandTraffic)) } binding.lastAnswerButton.root.setOnClickListener { applyLastSelection() } checkIsFormComplete() } private fun initStateFromTags() { val countryCode = countryInfo.countryCode val sides = createCyclewaySides(osmElement!!.tags, isLeftHandTraffic) val left = sides?.left?.takeIf { it.isAvailableAsSelection(countryCode) } val right = sides?.right?.takeIf { it.isAvailableAsSelection(countryCode) } val bothSidesWereDefinedBefore = sides?.left != null && sides.right != null leftSide = left rightSide = right isDefiningBothSides = bothSidesWereDefinedBefore || !likelyNoBicycleContraflow.matches(osmElement!!) // only show as re-survey (yes/no button) if the previous tagging was complete setAsResurvey(isFormComplete()) } private fun onLoadInstanceState(savedInstanceState: Bundle) { isDefiningBothSides = savedInstanceState.getBoolean(DEFINE_BOTH_SIDES) savedInstanceState.getString(CYCLEWAY_RIGHT)?.let { rightSide = Cycleway.valueOf(it) } savedInstanceState.getString(CYCLEWAY_LEFT)?.let { leftSide = Cycleway.valueOf(it) } setAsResurvey(savedInstanceState.getBoolean(IS_DISPLAYING_PREVIOUS_CYCLEWAY)) } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) rightSide?.let { outState.putString(CYCLEWAY_RIGHT, it.name) } leftSide?.let { outState.putString(CYCLEWAY_LEFT, it.name) } outState.putBoolean(DEFINE_BOTH_SIDES, isDefiningBothSides) outState.putBoolean(IS_DISPLAYING_PREVIOUS_CYCLEWAY, isDisplayingPreviousCycleway) } private fun setAsResurvey(resurvey: Boolean) { isDisplayingPreviousCycleway = resurvey binding.puzzleView.isEnabled = !resurvey updateButtonPanel() } @AnyThread override fun onMapOrientation(rotation: Float, tilt: Float) { streetSideRotater?.onMapOrientation(rotation, tilt) } override fun onClickOk() { val leftSide = leftSide val rightSide = rightSide // a cycleway that goes into opposite direction of a oneway street needs special tagging var leftSideDir = 0 var rightSideDir = 0 var isOnewayNotForCyclists = false if (isOneway && leftSide != null && rightSide != null) { // if the road is oneway=-1, a cycleway that goes opposite to it would be cycleway:oneway=yes val reverseDir = if (isReversedOneway) 1 else -1 if (isReverseSideRight) { if (rightSide.isSingleTrackOrLane()) { rightSideDir = reverseDir } } else { if (leftSide.isSingleTrackOrLane()) { leftSideDir = reverseDir } } isOnewayNotForCyclists = leftSide.isDualTrackOrLane() || rightSide.isDualTrackOrLane() || (if(isReverseSideRight) rightSide else leftSide) !== Cycleway.NONE } val answer = CyclewayAnswer( left = leftSide?.let { CyclewaySide(it, leftSideDir) }, right = rightSide?.let { CyclewaySide(it, rightSideDir) }, isOnewayNotForCyclists = isOnewayNotForCyclists ) applyAnswer(answer) if (leftSide != null && rightSide != null) { lastSelection = if (isRoadDisplayedUpsideDown()) LastCyclewaySelection(rightSide, leftSide) else LastCyclewaySelection(leftSide, rightSide) } } private fun applyLastSelection() { val lastSelection = lastSelection ?: return if (isRoadDisplayedUpsideDown()) { onSelectedSide(lastSelection.right, false) onSelectedSide(lastSelection.left, true) } else { onSelectedSide(lastSelection.left, false) onSelectedSide(lastSelection.right, true) } } private fun isRoadDisplayedUpsideDown(): Boolean { val roadDisplayRotation = binding.puzzleView.streetRotation return roadDisplayRotation.normalizeDegrees(-180f).absoluteValue > 90f } private fun updateLastAnswerButtonVisibility() { val formIsPrefilled = leftSide != null || rightSide != null val lastAnswerWasForBothSides = (lastSelection?.left != null && lastSelection?.right != null) val isDefiningBothSides = isDefiningBothSides && lastAnswerWasForBothSides binding.lastAnswerButton.root.isGone = lastSelection == null || formIsPrefilled || !isDefiningBothSides } private fun Cycleway.isSingleTrackOrLane() = this === Cycleway.TRACK || this === Cycleway.EXCLUSIVE_LANE private fun Cycleway.isDualTrackOrLane() = this === Cycleway.DUAL_TRACK || this === Cycleway.DUAL_LANE override fun isFormComplete() = !isDisplayingPreviousCycleway && ( if (isDefiningBothSides) leftSide != null && rightSide != null else leftSide != null || rightSide != null ) override fun isRejectingClose() = !isDisplayingPreviousCycleway && (leftSide != null || rightSide != null) private fun showCyclewaySelectionDialog(isRight: Boolean) { val ctx = context ?: return val items = getCyclewayItems(isRight).map { it.asItem(isLeftHandTraffic) } ImageListPickerDialog(ctx, items, R.layout.labeled_icon_button_cell, 2) { onSelectedSide(it.value!!, isRight) }.show() } private fun onSelectedSide(cycleway: Cycleway, isRight: Boolean) { val iconResId = cycleway.getIconResId(isLeftHandTraffic) val titleResId = resources.getString(cycleway.getTitleResId()) if (isRight) { binding.puzzleView.replaceRightSideImage(ResImage(iconResId)) binding.puzzleView.setRightSideText(titleResId) rightSide = cycleway } else { binding.puzzleView.replaceLeftSideImage(ResImage(iconResId)) binding.puzzleView.setLeftSideText(titleResId) leftSide = cycleway } updateLastAnswerButtonVisibility() checkIsFormComplete() } private fun getCyclewayItems(isRight: Boolean): List<Cycleway> { val country = countryInfo.countryCode val values = DISPLAYED_CYCLEWAY_ITEMS.filter { it.isAvailableAsSelection(country) }.toMutableList() // different wording for a contraflow lane that is marked like a "shared" lane (just bicycle pictogram) if (isOneway && isReverseSideRight == isRight) { values.remove(Cycleway.PICTOGRAMS) values.add(values.indexOf(Cycleway.NONE) + 1, Cycleway.NONE_NO_ONEWAY) } return values } private fun showBothSides() { isDefiningBothSides = true binding.puzzleView.showBothSides() updateLastAnswerButtonVisibility() checkIsFormComplete() } companion object { private const val CYCLEWAY_LEFT = "cycleway_left" private const val CYCLEWAY_RIGHT = "cycleway_right" private const val DEFINE_BOTH_SIDES = "define_both_sides" private const val IS_DISPLAYING_PREVIOUS_CYCLEWAY = "is_displaying_previous_cycleway" private var HAS_SHOWN_TAP_HINT = false private var lastSelection: LastCyclewaySelection? = null } } private data class LastCyclewaySelection( val left: Cycleway, val right: Cycleway )
gpl-3.0
bc0a2f71218e082fd2ff33e9b64e5c7f
40.378981
127
0.682598
4.817575
false
false
false
false
pdvrieze/ProcessManager
ProcessEngine/core/src/jvmTest/kotlin/nl/adaptivity/process/engine/ProcessTestingSupport.kt
1
7758
/* * Copyright (c) 2017. * * This file is part of ProcessManager. * * ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the * GNU Lesser General Public License as published by the Free Software Foundation. * * ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not, * see <http://www.gnu.org/licenses/>. */ package nl.adaptivity.process.engine import net.devrieze.util.Handle import net.devrieze.util.security.SecureObject import nl.adaptivity.process.engine.processModel.CompositeInstance import nl.adaptivity.process.engine.processModel.JoinInstance import nl.adaptivity.process.engine.processModel.NodeInstanceState import nl.adaptivity.process.engine.processModel.ProcessNodeInstance import nl.adaptivity.process.engine.spek.InstanceSupport import nl.adaptivity.process.processModel.Split import nl.adaptivity.process.processModel.engine.ExecutableCondition import nl.adaptivity.process.processModel.engine.ExecutableProcessModel import nl.adaptivity.process.processModel.engine.ExecutableProcessNode import nl.adaptivity.process.util.Identified import org.junit.jupiter.api.Assertions.* import java.io.ByteArrayOutputStream import java.io.PrintStream @Retention(AnnotationRetention.SOURCE) @DslMarker annotation class ProcessTestingDslMarker typealias PNIHandle = Handle<SecureObject<ProcessNodeInstance<*>>> fun ExecutableProcessModel.findNode(nodeIdentified: Identified): ExecutableProcessNode? { val nodeId = nodeIdentified.id return modelNodes.firstOrNull { it.id == nodeId } ?: childModels.asSequence().flatMap { it.modelNodes.asSequence() } .firstOrNull { it.id == nodeId } } @Throws(ProcessTestingException::class) fun InstanceSupport.testTraceExceptionThrowing( hProcessInstance: Handle<SecureObject<ProcessInstance>>, trace: Trace ) { try { transaction.readableEngineData.instance(hProcessInstance).withPermission().assertTracePossible(trace) } catch (e: AssertionError) { throw ProcessTestingException(e) } for (traceElement in trace) { run { val nodeInstance = traceElement.getNodeInstance(hProcessInstance) ?: throw ProcessTestingException("The node instance (${traceElement}) should exist") if (nodeInstance.state != NodeInstanceState.Complete) { if (nodeInstance is JoinInstance) { transaction.writableEngineData.updateNodeInstance(nodeInstance.handle) { startTask(transaction.writableEngineData) } } else if (nodeInstance.node !is Split) { if (nodeInstance is CompositeInstance) { val childInstance = transaction.readableEngineData.instance(nodeInstance.hChildInstance).withPermission() if (childInstance.state != ProcessInstance.State.FINISHED && nodeInstance.state != NodeInstanceState.Complete) { try { transaction.writableEngineData.updateNodeInstance(nodeInstance.handle) { finishTask(transaction.writableEngineData, null) } } catch (e: ProcessException) { if (e.message?.startsWith( "A Composite task cannot be finished until its child process is. The child state is:" ) == true ) { throw ProcessTestingException("The composite instance cannot be finished yet") } else throw e } } } else if (nodeInstance.state.isFinal && nodeInstance.state != NodeInstanceState.Complete) { try { transaction.writableEngineData.updateNodeInstance(nodeInstance.handle) { finishTask(transaction.writableEngineData, null) } engine.processTickleQueue(transaction) } catch (e: ProcessException) { assertNotNull(e.message) assertTrue( e.message!!.startsWith("instance ${nodeInstance.node.id}") && e.message!!.endsWith(" cannot be finished as it is already in a final state.") ) } throw ProcessTestingException("The node is final but not complete (failed, skipped): ${nodeInstance}") } try { transaction.writableEngineData.updateNodeInstance(nodeInstance.handle) { finishTask(transaction.writableEngineData, traceElement.resultPayload) } } catch (e: ProcessException) { throw ProcessTestingException(e) } } } try { transaction.readableEngineData.instance(hProcessInstance).withPermission().assertTracePossible(trace) } catch (e: AssertionError) { throw ProcessTestingException(e) } } try { val oldErr = System.err; System.setErr(PrintStream(ByteArrayOutputStream())) engine.processTickleQueue(transaction) System.setErr(oldErr) } catch (e: ProcessException) { throw ProcessTestingException(e) } val nodeInstance = traceElement.getNodeInstance(hProcessInstance) ?: throw ProcessTestingException("The node instance should exist") if (nodeInstance.state != NodeInstanceState.Complete) { val instance = transaction.readableEngineData.instance(hProcessInstance).withPermission() throw ProcessTestingException( "At trace $traceElement - State of node $nodeInstance not complete but ${nodeInstance.state} ${instance.toDebugString()}" ) } } } internal class ProcessTestingException(message: String? = null, cause: Throwable? = null) : Exception(message, cause) { constructor(cause: Throwable) : this(cause.message, cause) } /* @ProcessTestingDslMarker fun Dsl.givenProcess(engine: ProcessEngine<StubProcessTransaction>, processModel: ExecutableProcessModel, principal: Principal, payload: Node? = null, description: String="Given a process instance", body: ProcessTestingDsl.() -> Unit) { val transaction = engine.startTransaction() val instance = with(transaction) { engine.testProcess(processModel, principal, payload) } group(description, body = { ProcessTestingDsl(this, transaction, instance.instanceHandle).body() }) } */ fun kfail(message: String): Nothing { fail<Any?>(message) throw UnsupportedOperationException("This code should not be reachable") } internal fun Boolean.toXPath() = if (this) "true()" else "false()" internal fun Boolean.toCondition() = if (this) ExecutableCondition.TRUE else ExecutableCondition.FALSE operator fun ProcessTransaction.get(handle: Handle<SecureObject<ProcessInstance>>): ProcessInstance { return this.readableEngineData.instance(handle).withPermission() }
lgpl-3.0
6cc28d8e9f8a68803d5f104b5d420e55
46.595092
236
0.641145
5.410042
false
true
false
false
JetBrains/anko
anko/library/static/commons/src/main/java/collections/Collections.kt
2
2378
/* * Copyright 2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("unused", "NOTHING_TO_INLINE") package org.jetbrains.anko.collections /** * Iterate the receiver [List] using an index. * * @f an action to invoke on each list element. */ inline fun <T> List<T>.forEachByIndex(f: (T) -> Unit) { val lastIndex = size - 1 for (i in 0..lastIndex) { f(get(i)) } } /** * Iterate the receiver [List] using an index. * * @f an action to invoke on each list element (index, element). */ inline fun <T> List<T>.forEachWithIndex(f: (Int, T) -> Unit) { val lastIndex = size - 1 for (i in 0..lastIndex) { f(i, get(i)) } } /** * Iterate the receiver [List] backwards using an index. * * @f an action to invoke on each list element. */ inline fun <T> List<T>.forEachReversedByIndex(f: (T) -> Unit) { var i = size - 1 while (i >= 0) { f(get(i)) i-- } } /** * Iterate the receiver [List] backwards using an index. * * @f an action to invoke on each list element (index, element). */ inline fun <T> List<T>.forEachReversedWithIndex(f: (Int, T) -> Unit) { var i = size - 1 while (i >= 0) { f(i, get(i)) i-- } } /** * Convert the Android pair to a Kotlin one. * * @see [toAndroidPair]. */ @Deprecated(message = "Use the Android KTX version", replaceWith = ReplaceWith("toKotlinPair()", "androidx.core.util.toKotlinPair")) inline fun <F, S> android.util.Pair<F, S>.toKotlinPair(): Pair<F, S> = first to second /** * Convert the Kotlin pair to an Android one. * * @see [toKotlinPair]. */ @Deprecated(message = "Use the Android KTX version", replaceWith = ReplaceWith("toAndroidPair()", "androidx.core.util.toAndroidPair")) inline fun <F, S> Pair<F, S>.toAndroidPair(): android.util.Pair<F, S> = android.util.Pair(first, second)
apache-2.0
4ebd85f1ca082a5d5c5a2f577aee711d
27.309524
134
0.650126
3.382646
false
false
false
false
devulex/eventorage
frontend/src/com/devulex/eventorage/rpc/IndicesService.kt
1
1784
package com.devulex.eventorage.rpc import com.devulex.eventorage.model.IndexInfo import com.devulex.eventorage.model.IndicesResponse import com.devulex.eventorage.model.LocalDate suspend fun getIndices(pattern: String): IndicesResponse = getAndParseResult("/indices?pattern=$pattern", null, ::parseIndicesResponse) private fun parseIndicesResponse(json: dynamic): IndicesResponse { if (json.error != null) { throw IndexGroupPatternException(json.error.toString()) } return IndicesResponse(json.indices) } class IndexGroupPatternException(message: String) : Throwable(message) /** * Get a list of indexes * * @param groupId id index group * @return list of [IndexInfo] */ suspend fun getIndicesList(groupId: String): MutableList<IndexInfo> = getAndParseResult("/indices.list?groupId=$groupId", null, ::parseGetIndicesList) private fun parseGetIndicesList(json: dynamic): MutableList<IndexInfo> { if (json.ok == true) { val indices: Array<IndexInfo> = json.indices val indicesList: MutableList<IndexInfo> = mutableListOf() indices.forEach { val index = IndexInfo(it.name, it.uuid, it.state) if (it.date != null) { index.date = LocalDate(it.date!!.year, it.date!!.month, it.date!!.day) } index.numShards = it.numShards index.numReplicas = it.numReplicas index.docsCount = it.docsCount index.docsDeleted = it.docsDeleted index.size = it.size index.status = it.status indicesList.add(index) } return indicesList } else { throw GetIndicesListException(json.error.toString()) } } class GetIndicesListException(message: String) : Throwable(message)
mit
ecaf0d2ab32c7669159f7549a20e8f64
34
88
0.677691
4.073059
false
false
false
false
daverix/urlforwarder
app/src/main/java/net/daverix/urlforward/EditFilterViewModel.kt
1
2439
package net.daverix.urlforward import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import net.daverix.urlforward.db.FilterDao import javax.inject.Inject @HiltViewModel class EditFilterViewModel( private val filterDao: FilterDao, private val savedStateHandle: SavedStateHandle, private val _state: MutableStateFlow<SaveFilterState> ) : ViewModel(), EditableFields by DefaultEditableFields(_state) { val state: StateFlow<SaveFilterState> = _state @Inject constructor(filterDao: FilterDao, savedStateHandle: SavedStateHandle) : this( filterDao, savedStateHandle, MutableStateFlow(SaveFilterState.Loading) ) init { viewModelScope.launch { val filterId = savedStateHandle.get<Long>("filterId") ?: error("filterId not set") val filter = filterDao.queryFilter(filterId) if (filter != null) { _state.value = SaveFilterState.Editing( filter = filter, editingState = EditingState.EDITING ) } } } fun save() { viewModelScope.launch { val currentState = state.value if (currentState is SaveFilterState.Editing) { _state.value = currentState.copy(editingState = EditingState.SAVING) viewModelScope.launch { withContext(Dispatchers.IO) { filterDao.update(currentState.filter) } _state.emit(currentState.copy(editingState = EditingState.SAVED)) } } } } fun delete() { val currentState = state.value if (currentState is SaveFilterState.Editing) { _state.value = currentState.copy(editingState = EditingState.DELETING) viewModelScope.launch { withContext(Dispatchers.IO) { filterDao.delete(currentState.filter.id) } _state.emit(currentState.copy(editingState = EditingState.DELETED)) } } } }
gpl-3.0
6cb3deca93ab31e7d7d4538ad0e2a15f
32.875
85
0.632226
5.091858
false
false
false
false
i7c/cfm
server/recorder/src/main/kotlin/org/rliz/cfm/recorder/fingerprint/data/Fingerprint.kt
1
1414
package org.rliz.cfm.recorder.fingerprint.data import org.rliz.cfm.recorder.common.data.AbstractModel import org.rliz.cfm.recorder.user.data.User import java.util.UUID import javax.persistence.Entity import javax.persistence.ForeignKey import javax.persistence.Index import javax.persistence.JoinColumn import javax.persistence.ManyToOne import javax.persistence.Table import javax.validation.constraints.NotNull import javax.validation.constraints.Size @Entity @Table( indexes = [ Index( name = "IX_Fingerprint_fingerprint", columnList = "fingerprint" ), Index( name = "IX_Fingerprint_user_fingerprint", columnList = "user_oid, fingerprint" ) ] ) class Fingerprint : AbstractModel { @NotNull @ManyToOne @JoinColumn(foreignKey = ForeignKey(name = "FK_Fingerprint_User"), nullable = false) var user: User? = null @Size(min = 128, max = 128) var fingerprint: String? = null var recordingUuid: UUID? = null var releaseGroupUuid: UUID? = null constructor( uuid: UUID, user: User, fingerprint: String, recordingUuid: UUID? = null, releaseGroupUuid: UUID? = null ) : super(uuid) { this.user = user this.fingerprint = fingerprint this.recordingUuid = recordingUuid this.releaseGroupUuid = releaseGroupUuid } }
gpl-3.0
97dbfe843ac9cd5138d6728f36d939dd
25.185185
88
0.669731
4.183432
false
false
false
false
SuperAwesomeLTD/sa-mobile-sdk-android
superawesome-base/src/main/java/tv/superawesome/sdk/publisher/videoPlayer/VideoPlayerController.kt
1
5528
package tv.superawesome.sdk.publisher.videoPlayer import android.content.Context import android.media.MediaPlayer import android.media.MediaPlayer.* import android.net.Uri import android.os.CountDownTimer class VideoPlayerController : MediaPlayer(), IVideoPlayerController, OnPreparedListener, OnErrorListener, OnCompletionListener, OnSeekCompleteListener { private var listener: IVideoPlayerController.Listener? = null private var countDownTimer: CountDownTimer? = null private var completed: Boolean = false override val isIVideoPlaying: Boolean = false override val iVideoDuration: Int = 10 override val currentIVideoPosition: Int = 0 override var videoIVideoWidth: Int = 100 private set override var videoIVideoHeight: Int = 100 private set override var isMuted: Boolean = false private set // ////////////////////////////////////////////////////////////////////////////////////////////// // Custom safe play & prepare method // ////////////////////////////////////////////////////////////////////////////////////////////// override fun play(context: Context, uri: Uri) { try { setDataSource(context, uri) prepare() } catch (e: Exception) { listener?.onError(this, e, 0, 0) } } override fun playAsync(context: Context, uri: Uri) { try { setDataSource(context, uri) prepareAsync() } catch (e: Exception) { listener?.onError(this, e, 0, 0) } } override fun start() { if (completed) { // if the video is completed then show the last frame only seekTo(currentPosition) return } super.start() createTimer() } override fun pause() { super.pause() removeTimer() } // ////////////////////////////////////////////////////////////////////////////////////////////// // Safe Media Player overrides // ////////////////////////////////////////////////////////////////////////////////////////////// override fun destroy() { try { stop() setDisplay(null) release() removeTimer() } catch (ignored: Throwable) { } } override fun reset() { completed = false try { removeTimer() super.reset() } catch (ignored: Exception) { } } override fun seekTo(position: Int) { /* * re-create timer if it has been destroyed */ createTimer() super.seekTo(position) } override fun setMuted(muted: Boolean) { val volume = if (muted) 0f else 1f setVolume(volume, volume) isMuted = muted } // ////////////////////////////////////////////////////////////////////////////////////////////// // Media Constrol setters & getters for the listeners // ////////////////////////////////////////////////////////////////////////////////////////////// override fun setListener(listener: IVideoPlayerController.Listener) { this.listener = listener } // ////////////////////////////////////////////////////////////////////////////////////////////// // Media Player listeners // ////////////////////////////////////////////////////////////////////////////////////////////// override fun onPrepared(mediaPlayer: MediaPlayer) { createTimer() listener?.onPrepared(this) } override fun onSeekComplete(mediaPlayer: MediaPlayer) { listener?.onSeekComplete(this) } override fun onCompletion(mediaPlayer: MediaPlayer) { completed = true removeTimer() // todo: add a "reset" here and see how it goes listener?.onMediaComplete(this, currentPosition, duration) } // todo: why doesn't the video player stop at the error? override fun onError(mediaPlayer: MediaPlayer, error: Int, payload: Int): Boolean { removeTimer() reset() listener?.onError(this, Throwable(), 0, 0) return false } // ////////////////////////////////////////////////////////////////////////////////////////////// // Timer // ////////////////////////////////////////////////////////////////////////////////////////////// override fun createTimer() { if (completed) return if (countDownTimer == null) { countDownTimer = object : CountDownTimer(duration.toLong(), 500) { override fun onTick(remainingTime: Long) { listener?.onTimeUpdated( this@VideoPlayerController, currentPosition, duration ) } override fun onFinish() { // not needed } } countDownTimer?.start() } } override fun removeTimer() { countDownTimer?.cancel() countDownTimer = null } private fun onVideoSizeChanged(width: Int, height: Int) { videoIVideoWidth = width videoIVideoHeight = height } init { setOnPreparedListener(this) setOnCompletionListener(this) setOnErrorListener(this) setOnSeekCompleteListener(this) setOnVideoSizeChangedListener { _, width, height -> onVideoSizeChanged(width, height) } } }
lgpl-3.0
a08843caed89e49926da0b8afa278bc5
29.711111
101
0.474313
6.04153
false
false
false
false
RanKKI/PSNine
app/src/main/java/xyz/rankki/psnine/ui/topic/TopicActivity.kt
1
4927
package xyz.rankki.psnine.ui.topic import android.content.Context import android.os.Bundle import android.support.v4.widget.SwipeRefreshLayout import android.support.v7.app.AppCompatActivity import android.support.v7.widget.DividerItemDecoration import android.view.View import android.widget.Toolbar import com.blankj.utilcode.util.ScreenUtils import com.blankj.utilcode.util.ToastUtils import org.jetbrains.anko.backgroundColorResource import org.jetbrains.anko.find import org.jetbrains.anko.recyclerview.v7.recyclerView import org.jetbrains.anko.support.v4.onRefresh import org.jetbrains.anko.support.v4.swipeRefreshLayout import org.jetbrains.anko.toolbar import org.jetbrains.anko.verticalLayout import xyz.rankki.psnine.R import xyz.rankki.psnine.common.config.RefreshColors import xyz.rankki.psnine.common.listener.RecyclerViewScrollListener import xyz.rankki.psnine.data.http.HttpManager import xyz.rankki.psnine.model.topic.Gene import xyz.rankki.psnine.model.topic.Home import xyz.rankki.psnine.ui.topics.TopicsFragment import xyz.rankki.psnine.utils.ExtraSpaceLinearLayoutManager class TopicActivity : AppCompatActivity(), RecyclerViewScrollListener.LoadingListener { companion object { const val ID_SwipeRefreshLayout: Int = 1 const val ID_RecyclerView: Int = 2 const val ID_Toolbar = 3 } private val mContext: Context = this private lateinit var mAdapter: TopicAdapter private lateinit var clz: Class<*> private lateinit var path: String private var repliesPage = 1 private var maxRepliesPage = 1 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) mAdapter = TopicAdapter(mContext) verticalLayout { toolbar { id = ID_Toolbar backgroundColorResource = R.color.colorAppBarBackground setTitleTextColor(resources.getColor(R.color.colorAppBarText)) } swipeRefreshLayout { id = ID_SwipeRefreshLayout setColorSchemeColors(RefreshColors.ColorA, RefreshColors.ColorB, RefreshColors.ColorC) onRefresh { initData() } recyclerView { id = ID_RecyclerView val lm = ExtraSpaceLinearLayoutManager(mContext) lm.addExtraSpace(ScreenUtils.getScreenHeight()) layoutManager = lm adapter = mAdapter setItemViewCacheSize(60) isDrawingCacheEnabled = true drawingCacheQuality = View.DRAWING_CACHE_QUALITY_HIGH addItemDecoration(DividerItemDecoration(mContext, DividerItemDecoration.VERTICAL)) addOnScrollListener(RecyclerViewScrollListener(mContext, this@TopicActivity)) } } } path = intent.extras.getString("url") .replace("http://psnine.com/", "") find<Toolbar>(ID_Toolbar).title = path.split("/")[1] clz = when (path.split("/")[0]) { //topic type "gene" -> Gene::class.java "topic" -> Home::class.java else -> { ToastUtils.showShort("Invalid Url") finish() return } } initData() } private fun initData() { getTopic() getTopicReplies() } private var topicLoadedFlag: Boolean = false private var topicRepliesLoadedFlag: Boolean = false private fun getTopic() { setRefreshing(true) topicLoadedFlag = false HttpManager.get() .getTopic(path, clz) .subscribe { mAdapter.updateTopic(it) topicLoadedFlag = true if (topicRepliesLoadedFlag) { setRefreshing(false) } } } private fun getTopicReplies() { setRefreshing(true) topicRepliesLoadedFlag = false HttpManager.get() .getReplies(path, repliesPage) .subscribe { topicRepliesLoadedFlag = true mAdapter.updateReplies(it.replies) maxRepliesPage = it.getMaxPage() if (topicLoadedFlag) { setRefreshing(false) } } } private fun setRefreshing(isRefreshing: Boolean) { find<SwipeRefreshLayout>(TopicsFragment.ID_SwipeRefreshLayout).isRefreshing = isRefreshing } override fun isLoading(): Boolean = find<SwipeRefreshLayout>(TopicsFragment.ID_SwipeRefreshLayout).isRefreshing override fun loadMore() { if (maxRepliesPage != 1 && repliesPage < maxRepliesPage) { repliesPage += 1 getTopicReplies() } } }
apache-2.0
fb11311af404d2c487f7178967e317ce
34.446043
115
0.622285
5.159162
false
false
false
false
didi/DoraemonKit
Android/dokit-mc/src/main/java/com/didichuxing/doraemonkit/kit/mc/utils/ActivityStatusUtil.kt
1
1164
package com.didichuxing.doraemonkit.kit.mc.utils import android.app.Activity import android.view.View import com.didichuxing.doraemonkit.extension.tagName /** * ================================================ * 作 者:jint(金台) * 版 本:1.0 * 创建日期:2020/12/3-20:14 * 描 述: * 修订历史: * ================================================ */ object ActivityStatusUtil { const val ACTIVITY_STATUS_UNKNOWN = -1 const val ACTIVITY_STATUS_ONCREATE = 0 const val ACTIVITY_STATUS_ONSTART = 1 const val ACTIVITY_STATUS_ONRESUME = 2 const val ACTIVITY_STATUS_ONPAUSE = 3 const val ACTIVITY_STATUS_ONSTOP = 4 const val ACTIVITY_STATUS_ONDESTROY = 5 val activityStatus: MutableMap<String, Int> by lazy { mutableMapOf<String, Int>() } fun isActivityOnResume(view: View): Boolean { if (view.context is Activity) { val activity = view.context as Activity val status = activityStatus[activity::class.tagName] if (status == ACTIVITY_STATUS_ONRESUME) { return true } } return false } }
apache-2.0
0ec40201ca1c04768e61cf3936449efc
26.268293
64
0.583184
4.171642
false
false
false
false
tasks/tasks
app/src/main/java/com/todoroo/astrid/adapter/FilterViewHolder.kt
1
3696
package com.todoroo.astrid.adapter import android.content.Context import android.view.View import android.widget.CheckedTextView import android.widget.ImageView import android.widget.TextView import androidx.core.view.isVisible import androidx.recyclerview.widget.RecyclerView import com.todoroo.astrid.api.* import org.tasks.R import org.tasks.billing.Inventory import org.tasks.databinding.FilterAdapterRowBinding import org.tasks.extensions.formatNumber import org.tasks.filters.PlaceFilter import org.tasks.themes.ColorProvider import org.tasks.themes.CustomIcons.getIconResId import org.tasks.themes.DrawableUtil import java.util.* class FilterViewHolder internal constructor( itemView: View, private val navigationDrawer: Boolean, private val locale: Locale, private val context: Context, private val inventory: Inventory, private val colorProvider: ColorProvider, private val onClick: ((FilterListItem?) -> Unit)? ) : RecyclerView.ViewHolder(itemView) { private val row: View private val text: CheckedTextView private val icon: ImageView private val size: TextView private val shareIndicator: ImageView lateinit var filter: FilterListItem init { FilterAdapterRowBinding.bind(itemView).let { row = it.row text = it.text icon = it.icon size = it.size shareIndicator = it.shareIndicator } if (navigationDrawer) { text.checkMarkDrawable = null } } fun setMoving(moving: Boolean) { itemView.isSelected = moving } fun bind(filter: FilterListItem, selected: Boolean, count: Int?) { this.filter = filter if (navigationDrawer) { itemView.isSelected = selected } else { text.isChecked = selected } val icon = getIcon(filter) this.icon.setImageDrawable(DrawableUtil.getWrapped(context, icon)) this.icon.drawable.setTint(getColor(filter)) text.text = filter.listingTitle if (count == null || count == 0) { size.visibility = View.INVISIBLE } else { size.text = locale.formatNumber(count) size.visibility = View.VISIBLE } shareIndicator.apply { isVisible = filter.principals > 0 setImageResource(when { filter.principals <= 0 -> 0 filter.principals == 1 -> R.drawable.ic_outline_perm_identity_24px else -> R.drawable.ic_outline_people_outline_24 }) } if (onClick != null) { row.setOnClickListener { onClick.invoke(filter) } } } private fun getColor(filter: FilterListItem): Int { if (filter.tint != 0) { val color = colorProvider.getThemeColor(filter.tint, true) if (color.isFree || inventory.purchasedThemes()) { return color.primaryColor } } return context.getColor(R.color.text_primary) } private fun getIcon(filter: FilterListItem): Int { if (filter.icon < 1000 || inventory.hasPro) { val icon = getIconResId(filter.icon) if (icon != null) { return icon } } return when (filter) { is TagFilter -> R.drawable.ic_outline_label_24px is GtasksFilter -> R.drawable.ic_list_24px is CaldavFilter -> R.drawable.ic_list_24px is CustomFilter -> R.drawable.ic_outline_filter_list_24px is PlaceFilter -> R.drawable.ic_outline_place_24px else -> filter.icon } } }
gpl-3.0
dc3e48ade5aa8d288e4b48ad48e68b19
31.429825
82
0.625
4.529412
false
false
false
false
NextFaze/dev-fun
demo/src/debug/java/com/nextfaze/devfun/demo/devfun/ActivityDebugging.kt
1
5372
package com.nextfaze.devfun.demo.devfun import android.app.Activity import android.content.Intent import android.os.Build import androidx.annotation.RequiresApi import com.nextfaze.devfun.category.CategoryDefinition import com.nextfaze.devfun.category.DeveloperCategory import com.nextfaze.devfun.function.DeveloperFunction import com.nextfaze.devfun.function.FunctionDefinition import com.nextfaze.devfun.function.FunctionItem import com.nextfaze.devfun.function.FunctionTransformer import com.nextfaze.devfun.function.SimpleFunctionItem import com.nextfaze.devfun.inject.Constructable import com.nextfaze.devfun.invoke.view.From import com.nextfaze.devfun.invoke.view.ValueSource @DeveloperCategory("Debugging") object ActivityDebugging { /** TODO Consider checking for [RequiresApi] instead of using [DeveloperFunction.requiresApi]? */ @RequiresApi(Build.VERSION_CODES.KITKAT) @DeveloperFunction( "Start ACTION_CREATE_DOCUMENT intent", requiresApi = Build.VERSION_CODES.KITKAT, category = DeveloperCategory(group = "Intents") ) fun startCreateDocumentIntent(activity: Activity) { val intent = Intent(Intent.ACTION_CREATE_DOCUMENT).apply { addCategory(Intent.CATEGORY_OPENABLE) type = "text/plain" putExtra(Intent.EXTRA_TITLE, "foobar.txt") } activity.startActivityForResult(intent, 1234) } @DeveloperFunction("Start ACTION_SEND intent", category = DeveloperCategory(group = "Intents")) fun startSendIntent(activity: Activity) { val intent = Intent(Intent.ACTION_SEND).apply { type = "text/plain" putExtra(Intent.EXTRA_STREAM, "content://com/blah/qwerty") } activity.startActivity(Intent.createChooser(intent, "Save something to")) } @DeveloperFunction(transformer = OrientationTransformer::class, category = DeveloperCategory("Screen Orientation")) fun setOrientation(activity: Activity, orientation: Int) { activity.requestedOrientation = orientation } @DeveloperFunction(category = DeveloperCategory("Screen Orientation", group = "Enum List UI")) fun chooseOrientation2(activity: Activity, @From(CurrentOrientation::class) orientation: ScreenOrientations) { activity.requestedOrientation = orientation.value } } enum class ScreenOrientations(val value: Int) { SCREEN_ORIENTATION_UNSPECIFIED(-1), SCREEN_ORIENTATION_LANDSCAPE(0), SCREEN_ORIENTATION_PORTRAIT(1), SCREEN_ORIENTATION_USER(2), SCREEN_ORIENTATION_BEHIND(3), SCREEN_ORIENTATION_SENSOR(4), SCREEN_ORIENTATION_NO_SENSOR(5), SCREEN_ORIENTATION_SENSOR_LANDSCAPE(6), SCREEN_ORIENTATION_SENSOR_PORTRAIT(7), SCREEN_ORIENTATION_REVERSE_LANDSCAPE(8), SCREEN_ORIENTATION_REVERSE_PORTRAIT(9), SCREEN_ORIENTATION_FULL_SENSOR(10), SCREEN_ORIENTATION_USER_LANDSCAPE(11), SCREEN_ORIENTATION_USER_PORTRAIT(12), SCREEN_ORIENTATION_FULL_USER(13), SCREEN_ORIENTATION_LOCKED(14); companion object { private val values = values().associateBy { it.value } fun fromValue(value: Int): ScreenOrientations { return values[value] ?: SCREEN_ORIENTATION_UNSPECIFIED } } } /** * Provides the current orientation for use with @[From]. * * @param activity This will be injected upon construction. */ @Constructable class CurrentOrientation(private val activity: Activity) : ValueSource<ScreenOrientations> { override val value get() = ScreenOrientations.fromValue(activity.requestedOrientation) } /** * Function -> Item transformer for [ActivityDebugging.setOrientation]. * * This class is not handled by Dagger (though DevFun will check Dagger for it). * Thus it will be constructed upon request (i.e. `OrientationTransformer::class.constructors.single().call(...)`). * * Arguments will then also injected/constructed. * * @param currentOrientation This will be injected upon construction. */ @Constructable class OrientationTransformer(currentOrientation: CurrentOrientation) : FunctionTransformer { private val currentOrientation = currentOrientation.value.value /** * Maps the the available screen orientations to function items that will invoke [ActivityDebugging.setOrientation]. * * Since the first argument is the current activity, the [SimpleFunctionItem.args] value uses [Unit] for the first value. * * i.e. * ``` * listOf(Unit, orientation.value) * ``` * * NB: If the orientation was first then `listOf(orientation.value)` would suffice. */ override fun apply(functionDefinition: FunctionDefinition, categoryDefinition: CategoryDefinition): Collection<FunctionItem>? = ScreenOrientations.values().map { orientation -> object : SimpleFunctionItem(functionDefinition, categoryDefinition) { override val name by lazy { val shortName = orientation.toString().substringAfter("SCREEN_ORIENTATION_") val selected = if (currentOrientation == orientation.value) "****" else "" "$selected $shortName (${orientation.value}) $selected".trim() } override val args = listOf(Unit /* Unit means inject */, orientation.value) override val group = "Set Orientation" } } }
apache-2.0
90fb35b220bc1be63933418e19a4b5ac
40.323077
131
0.714073
4.631034
false
false
false
false
cwoolner/flex-poker
src/main/kotlin/com/flexpoker/table/command/aggregate/eventproducers/hand/PlayerActionEventProducer.kt
1
2861
package com.flexpoker.table.command.aggregate.eventproducers.hand import com.flexpoker.table.command.PlayerAction import com.flexpoker.table.command.aggregate.HandState import com.flexpoker.table.command.events.AutoMoveHandForwardEvent import com.flexpoker.table.command.events.PlayerCalledEvent import com.flexpoker.table.command.events.PlayerCheckedEvent import com.flexpoker.table.command.events.PlayerFoldedEvent import com.flexpoker.table.command.events.PlayerForceCheckedEvent import com.flexpoker.table.command.events.PlayerForceFoldedEvent import com.flexpoker.table.command.events.PlayerRaisedEvent import com.flexpoker.table.command.events.TableEvent import java.util.UUID fun autoMoveHandForward(state: HandState): List<TableEvent> { return if (state.chipsInBackMap.values.all { it == 0 }) listOf(AutoMoveHandForwardEvent(state.tableId, state.gameId, state.entityId)) else emptyList() } fun expireActionOn(state: HandState, playerId: UUID): List<TableEvent> { return if (state.callAmountsMap[playerId]!! == 0) check(state, playerId, true) else fold(state, playerId, true) } fun fold(state: HandState, playerId: UUID, forced: Boolean): List<TableEvent> { checkActionOnPlayer(state, playerId) checkPerformAction(state, playerId, PlayerAction.FOLD) return if (forced) listOf(PlayerForceFoldedEvent(state.tableId, state.gameId, state.entityId, playerId)) else listOf(PlayerFoldedEvent(state.tableId, state.gameId, state.entityId, playerId)) } fun check(state: HandState, playerId: UUID, forced: Boolean): List<TableEvent> { checkActionOnPlayer(state, playerId) checkPerformAction(state, playerId, PlayerAction.CHECK) return if (forced) listOf(PlayerForceCheckedEvent(state.tableId, state.gameId, state.entityId, playerId)) else listOf(PlayerCheckedEvent(state.tableId, state.gameId, state.entityId, playerId)) } fun call(state: HandState, playerId: UUID): List<TableEvent> { checkActionOnPlayer(state, playerId) checkPerformAction(state, playerId, PlayerAction.CALL) return listOf(PlayerCalledEvent(state.tableId, state.gameId, state.entityId, playerId)) } fun raise(state: HandState, playerId: UUID, raiseToAmount: Int): List<TableEvent> { checkActionOnPlayer(state, playerId) checkPerformAction(state, playerId, PlayerAction.RAISE) checkRaiseAmountValue(state, playerId, raiseToAmount) return listOf(PlayerRaisedEvent(state.tableId, state.gameId, state.entityId, playerId, raiseToAmount)) } private fun checkRaiseAmountValue(state: HandState, playerId: UUID, raiseToAmount: Int) { val playersTotalChips = state.chipsInBackMap[playerId]!! + state.chipsInFrontMap[playerId]!! require(!(raiseToAmount < state.raiseToAmountsMap[playerId]!! || raiseToAmount > playersTotalChips)) { "Raise amount must be between the minimum and maximum values." } }
gpl-2.0
227cd56d6987520f5e37ef59264e3fb5
49.192982
171
0.789934
4.087143
false
false
false
false
nemerosa/ontrack
ontrack-extension-indicators/src/main/java/net/nemerosa/ontrack/extension/indicators/model/IndicatorServiceImpl.kt
1
6572
package net.nemerosa.ontrack.extension.indicators.model import com.fasterxml.jackson.databind.JsonNode import com.fasterxml.jackson.databind.node.NullNode import com.fasterxml.jackson.databind.node.ObjectNode import net.nemerosa.ontrack.extension.indicators.acl.IndicatorEdit import net.nemerosa.ontrack.extension.indicators.metrics.IndicatorMetricsService import net.nemerosa.ontrack.extension.indicators.store.IndicatorStore import net.nemerosa.ontrack.extension.indicators.store.StoredIndicator import net.nemerosa.ontrack.model.Ack import net.nemerosa.ontrack.model.security.SecurityService import net.nemerosa.ontrack.model.structure.Project import net.nemerosa.ontrack.model.structure.Signature import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional import java.time.Duration import java.time.LocalDateTime @Service @Transactional class IndicatorServiceImpl( private val securityService: SecurityService, private val indicatorStore: IndicatorStore, private val indicatorTypeService: IndicatorTypeService, private val indicatorMetricsService: IndicatorMetricsService ) : IndicatorService, IndicatorTypeListener { init { indicatorTypeService.registerTypeListener(this) } override fun onTypeDeleted(type: IndicatorType<*, *>) { indicatorStore.deleteIndicatorByType(type.id) } override fun getProjectIndicators(project: Project, all: Boolean): List<Indicator<*>> { // Gets all the types val types = indicatorTypeService.findAll() // Gets the values return types.map { loadIndicator(project, it) }.filter { all || it.value != null } } override fun getAllProjectIndicators(project: Project): List<Indicator<*>> { // Gets all the types val types = indicatorTypeService.findAll() // Gets the values return types.flatMap { type -> indicatorStore.loadIndicatorHistory(project, type.id).map { stored -> toIndicator(stored, type) } } } override fun <T> getProjectIndicatorHistory(project: Project, type: IndicatorType<T, *>, offset: Int, size: Int): IndicatorHistory<T> { val indicators = indicatorStore.loadIndicatorHistory(project, type.id, offset, size).map { stored -> toIndicator(stored, type) } val total = indicatorStore.getCountIndicatorHistory(project, type.id) return IndicatorHistory( items = indicators, offset = offset, total = total ) } override fun getProjectIndicator(project: Project, typeId: String): Indicator<*> { val type = indicatorTypeService.getTypeById(typeId) return loadIndicator(project, type) } override fun <T> getProjectIndicator(project: Project, type: IndicatorType<T, *>, previous: Duration?): Indicator<T> { return loadIndicator(project, type, previous) } override fun <T> updateProjectIndicator(project: Project, typeId: String, input: JsonNode): Indicator<T> { securityService.checkProjectFunction(project, IndicatorEdit::class.java) @Suppress("UNCHECKED_CAST") val type = indicatorTypeService.getTypeById(typeId) as IndicatorType<T, *> // Parsing val value = type.fromClientJson(input) // Comment extraction val comment = if (input is ObjectNode && input.has(FIELD_COMMENT)) { val commentNode = input.get(FIELD_COMMENT) input.remove(FIELD_COMMENT) if (commentNode.isNull) { null } else { val comment = commentNode.asText() comment } } else { null } // OK return updateProjectIndicator(project, type, value, comment) } override fun <T> updateProjectIndicator(project: Project, type: IndicatorType<T, *>, value: T?, comment: String?, time: LocalDateTime?): Indicator<T> { // Signature val signature = if (time != null) { securityService.currentSignature.withTime(time) } else { securityService.currentSignature } // Storing the indicator indicatorStore.storeIndicator(project, type.id, StoredIndicator( value = value?.run { type.toStoredJson(this) } ?: NullNode.instance, comment = comment, signature = signature )) val indicator = loadIndicator(project, type) // Metrics indicatorMetricsService.saveMetrics(project, indicator) // OK return indicator } override fun deleteProjectIndicator(project: Project, typeId: String): Ack { return indicatorStore.deleteIndicator(project, typeId) } override fun <T> getPreviousProjectIndicator(project: Project, type: IndicatorType<T, *>): Indicator<T> { val stored = indicatorStore.loadPreviousIndicator(project, type.id) return toIndicator(stored, type) } private fun <T, C> loadIndicator(project: Project, type: IndicatorType<T, C>, previous: Duration? = null): Indicator<T> { val stored = indicatorStore.loadIndicator(project, type.id, previous) return toIndicator(stored, type) } private fun <C, T> toIndicator(stored: StoredIndicator?, type: IndicatorType<T, C>): Indicator<T> { return if (stored != null) { if (stored.value != null && !stored.value.isNull) { val value = type.fromStoredJson(stored.value) Indicator( type = type, value = value, compliance = value?.let { type.getStatus(it) }, comment = stored.comment, signature = stored.signature ) } else { Indicator( type = type, value = null, compliance = null, comment = stored.comment, signature = stored.signature ) } } else { Indicator( type = type, value = null, compliance = null, comment = null, signature = Signature.anonymous() ) } } companion object { private const val FIELD_COMMENT = "comment" } }
mit
6bcc612399ddf75dd59863bf45250e4e
37.664706
155
0.621729
4.948795
false
false
false
false
coconautti/sequel
src/main/kotlin/coconautti/sql/Operation.kt
1
2403
package coconautti.sql interface Operation { fun values(): List<Value> } abstract class Op(internal val lh: Column, internal val rh: Value) : Operation { infix fun and(other: Op) = And(this, other) infix fun or(other: Op) = Or(this, other) override fun values(): List<Value> = listOf(rh) } class Equal(lh: Column, rh: Value) : Op(lh, rh) { override fun toString(): String = "$lh = ?" } class NotEqual(lh: Column, rh: Value) : Op(lh, rh) { override fun toString(): String = "$lh != ?" } class GreaterThan(lh: Column, rh: Value) : Op(lh, rh) { override fun toString(): String = "$lh > ?" } class GreaterThanOrEqual(lh: Column, rh: Value) : Op(lh, rh) { override fun toString(): String = "$lh >= ?" } class LessThan(lh: Column, rh: Value) : Op(lh, rh) { override fun toString(): String = "$lh < ?" } class LessThanOrEqual(lh: Column, rh: Value) : Op(lh, rh) { override fun toString(): String = "$lh <= ?" } abstract class CompositeOp(internal val lh: Op, internal val rh: Op) : Operation { override fun values(): List<Value> = listOf(lh.values().first(), rh.values().first()) } class And(lh: Op, rh: Op) : CompositeOp(lh, rh) { override fun toString(): String = "$lh AND $rh" } class Or(lh: Op, rh: Op) : CompositeOp(lh, rh) { override fun toString(): String = "$lh OR $rh" } infix fun String.eq(value: String): Op = Equal(Column(this), Value(value)) infix fun String.eq(value: Long): Op = Equal(Column(this), Value(value)) infix fun String.eq(value: Value): Op = Equal(Column(this), value) infix fun String.ne(value: String): Op = NotEqual(Column(this), Value(value)) infix fun String.ne(value: Long): Op = NotEqual(Column(this), Value(value)) infix fun String.ne(value: Value): Op = NotEqual(Column(this), value) infix fun String.lt(value: Long): Op = LessThan(Column(this), Value(value)) infix fun String.lt(value: Value): Op = LessThan(Column(this), value) infix fun String.lte(value: Long): Op = LessThanOrEqual(Column(this), Value(value)) infix fun String.lte(value: Value): Op = LessThanOrEqual(Column(this), value) infix fun String.gt(value: Long): Op = GreaterThan(Column(this), Value(value)) infix fun String.gt(value: Value): Op = GreaterThan(Column(this), value) infix fun String.gte(value: Long): Op = GreaterThanOrEqual(Column(this), Value(value)) infix fun String.gte(value: Value): Op = GreaterThanOrEqual(Column(this), value)
apache-2.0
690d479ccf7acd279233faad25b3fbda
38.393443
89
0.67499
3.256098
false
false
false
false
nemerosa/ontrack
ontrack-extension-indicators/src/main/java/net/nemerosa/ontrack/extension/indicators/ui/graphql/GQLTypeProjectIndicator.kt
1
7787
package net.nemerosa.ontrack.extension.indicators.ui.graphql import graphql.Scalars.GraphQLInt import graphql.Scalars.GraphQLString import graphql.schema.GraphQLObjectType import graphql.schema.GraphQLTypeReference import net.nemerosa.ontrack.common.Time import net.nemerosa.ontrack.extension.indicators.model.Rating import net.nemerosa.ontrack.extension.indicators.stats.trendBetween import net.nemerosa.ontrack.extension.indicators.ui.ProjectIndicator import net.nemerosa.ontrack.extension.indicators.ui.ProjectIndicatorService import net.nemerosa.ontrack.graphql.schema.* import net.nemerosa.ontrack.graphql.support.GQLScalarJSON import net.nemerosa.ontrack.graphql.support.pagination.GQLPaginatedListFactory import net.nemerosa.ontrack.graphql.support.toTypeRef import net.nemerosa.ontrack.model.pagination.PaginatedList import net.nemerosa.ontrack.model.structure.Project import net.nemerosa.ontrack.model.support.FreeTextAnnotatorContributor import net.nemerosa.ontrack.model.support.MessageAnnotationUtils import org.springframework.stereotype.Component import java.time.Duration @Component class GQLTypeProjectIndicator( private val projectIndicatorType: GQLTypeProjectIndicatorType, private val signature: GQLTypeCreation, private val paginatedListFactory: GQLPaginatedListFactory, private val projectIndicatorHistoryItem: GQLTypeProjectIndicatorHistoryItem, private val fieldContributors: List<GQLFieldContributor>, private val freeTextAnnotatorContributors: List<FreeTextAnnotatorContributor>, private val projectIndicatorService: ProjectIndicatorService ) : GQLType { override fun createType(cache: GQLTypeCache): GraphQLObjectType = GraphQLObjectType.newObject() .name(typeName) .description("Project indicator") .field { it.name(ProjectIndicator::project.name) .description("Associated project") .type(Project::class.toTypeRef()) } .field { it.name(ProjectIndicator::type.name) .description("Type of indicator") .type(projectIndicatorType.typeRef) } .field { it.name(ProjectIndicator::value.name) .description("Value for the indicator") .type(GQLScalarJSON.INSTANCE) } .field { it.name(ProjectIndicator::compliance.name) .description("Compliance for the indicator") .type(GraphQLInt) .dataFetcher { env -> env.getSource<ProjectIndicator>().compliance?.value } } .field { it.name(ProjectIndicator::comment.name) .description("Comment for the indicator") .type(GraphQLString) } .field { it.name("annotatedComment") .type(GraphQLString) .description("Comment with links.") .dataFetcher { env -> val projectIndicator = env.getSource<ProjectIndicator>() val comment = projectIndicator.comment if (comment.isNullOrBlank()) { comment } else { annotatedDescription(projectIndicator.project, comment) } } } .field { it.name(ProjectIndicator::signature.name) .description("Signature for the indicator") .type(signature.typeRef) .dataFetcher(GQLTypeCreation.dataFetcher(ProjectIndicator::signature)) } // Duration since .field { it.name("durationSecondsSince") .description("Time elapsed (in seconds) since the indicator value was set.") .type(GraphQLInt) .dataFetcher { env -> val projectIndicator = env.getSource<ProjectIndicator>() val time = projectIndicator.signature.time (Duration.between(time, Time.now()).toMillis() / 1000).toInt() } } // Rating .field { it.name("rating") .description("Rating for this indicator") .type(GraphQLString) .dataFetcher { env -> env.getSource<ProjectIndicator>().compliance?.let { compliance -> Rating.asRating(compliance.value) } } } // Previous indicator value .field { it.name("previousValue") .description("Previous value for this indicator") .type(GraphQLTypeReference(typeName)) .dataFetcher { env -> val projectIndicator = env.getSource<ProjectIndicator>() projectIndicatorService.getPreviousIndicator(projectIndicator) } } // Previous value trend .field { it.name("trendSincePrevious") .description("Trend since the previous value (if any)") .type(GraphQLString) .dataFetcher { env -> val projectIndicator = env.getSource<ProjectIndicator>() val previousIndicator = projectIndicatorService.getPreviousIndicator(projectIndicator) trendBetween( previousIndicator.compliance, projectIndicator.compliance ) } } // History of this indicator .field( paginatedListFactory.createPaginatedField<ProjectIndicator, ProjectIndicator>( cache = cache, fieldName = "history", fieldDescription = "History of this indicator", itemType = projectIndicatorHistoryItem, itemPaginatedListProvider = { _, source, offset, size -> history(source, offset, size) } ) ) // Links .fields(ProjectIndicator::class.java.graphQLFieldContributions(fieldContributors)) .build() private fun history(projectIndicator: ProjectIndicator, offset: Int, size: Int): PaginatedList<ProjectIndicator> { val results = projectIndicatorService.getHistory(projectIndicator, offset, size) return PaginatedList.create( items = results.items, offset = offset, pageSize = size, total = results.total ) } private fun annotatedDescription(project: Project, comment: String): String { // Gets the list of message annotators to use val annotators = freeTextAnnotatorContributors.flatMap { it.getMessageAnnotators(project) } // Annotates the message return MessageAnnotationUtils.annotate(comment, annotators) } override fun getTypeName(): String = ProjectIndicator::class.java.simpleName }
mit
7ca1f127bdcff636bb67b17bdaf4c720
46.2
118
0.552844
6.219649
false
false
false
false
gameofbombs/kt-postgresql-async
postgresql-async/src/main/kotlin/com/github/mauricio/async/db/postgresql/codec/MessageDecoder.kt
2
3069
/* * Copyright 2013 Maurício Linhares * * Maurício Linhares licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.github.mauricio.async.db.postgresql.codec import com.github.mauricio.async.db.postgresql.exceptions.MessageTooLongException import com.github.mauricio.async.db.postgresql.messages.backend.ServerMessage import com.github.mauricio.async.db.postgresql.messages.backend.SSLResponseMessage import com.github.mauricio.async.db.postgresql.parsers.AuthenticationStartupParser import com.github.mauricio.async.db.postgresql.parsers.MessageParsersRegistry import com.github.mauricio.async.db.util.BufferDumper import java.nio.charset.Charset import com.github.mauricio.async.db.exceptions.NegativeMessageSizeException import io.netty.handler.codec.ByteToMessageDecoder import io.netty.channel.ChannelHandlerContext import io.netty.buffer.ByteBuf import mu.KLogging class MessageDecoder(val sslEnabled: Boolean, charset: Charset, val maximumMessageSize: Int = MessageDecoder.DefaultMaximumSize) : ByteToMessageDecoder() { companion object : KLogging() { val DefaultMaximumSize = 16777216 } private val parser = MessageParsersRegistry(charset) private var sslChecked = false override fun decode(ctx: ChannelHandlerContext, b: ByteBuf, out: MutableList<Any>) { if (sslEnabled && !sslChecked) { val code = b.readByte() sslChecked = true out.add(SSLResponseMessage(code == 'S'.toByte())) } else if (b.readableBytes() >= 5) { b.markReaderIndex() val code = b.readByte() val lengthWithSelf = b.readInt() val length = lengthWithSelf - 4 if (length < 0) { throw NegativeMessageSizeException(code, length) } if (length > maximumMessageSize) { throw MessageTooLongException(code, length, maximumMessageSize) } if (b.readableBytes() >= length) { // if (log.isTraceEnabled) { // log.trace(s"Received buffer ${code}\n${BufferDumper.dumpAsHex(b)}") // } val result = when (code.toInt()) { ServerMessage.Authentication -> AuthenticationStartupParser.parseMessage(b) else -> parser.parse(code, b.readSlice(length)) } out.add(result) } else { b.resetReaderIndex() } } } }
apache-2.0
4b934a8c8bfa9fd271a563a558d2c33c
34.662791
155
0.663189
4.510294
false
false
false
false
apycazo/codex
codex-kotlin/src/main/kotlin/apycazo/codex/kotlin/basic/ControlStructures.kt
1
1825
package apycazo.codex.kotlin.basic class ControlStructures { /** * If structure demonstrator 1 */ fun returnGreaterOf(a:Int, b:Int): Int { return if (a >= b) a else b } /** * If structure: this one warns us that the 'return' should be lifted. */ fun returnGreaterPlusDelta(a:Int, b:Int, delta:Int): Int { if (a >= b) { return a + delta } else { return b + delta } } /** * While structure */ fun whileOddSumValue(values:List<Int>):Int { if (values.isEmpty()) return 0 var isOdd = true var index = 0 var accumulator = 0 while (isOdd && index <= values.size) { val value = values[index] isOdd = value % 2 == 0 if (isOdd) accumulator += value index++ } return accumulator } /** * For structure. The 'value' can include type, like 'for(value:Int in values)' */ fun forAllElements(values:List<Int>):Int { var accumulator = 0 for (value in values) { accumulator += value } return accumulator } /** * For structure, including index on each pass. */ fun forWithIndex(values:List<Int>):Int { var accumulator = 0 for ((i,v) in values.withIndex()) { if (i % 2 == 0) accumulator += v } return accumulator } /** * Iterate over the value indexes only. */ fun forIteratingIndex(values:List<Int>):Int { var accumulator = 0 for (i in values.indices) { accumulator += i } return accumulator } /** * When structure. Each case can use a block '{}' structure too. */ fun whenExpressions(value:Any?):String { return when(value) { null -> "value is null" is String -> "value was '$value'" 1 -> "one" 2 -> "two" in 10..20 -> "between 10 and 20" else -> "unknown" } } }
apache-2.0
e333a356edf80e854b7007fb1cbcfa4a
20.232558
81
0.572603
3.694332
false
false
false
false
panpf/sketch
sketch/src/androidTest/java/com/github/panpf/sketch/test/request/internal/MemoryCacheRequestInterceptorTest.kt
1
13082
/* * Copyright (C) 2022 panpf <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.panpf.sketch.test.request.internal import android.graphics.Bitmap import android.graphics.Bitmap.Config.ARGB_8888 import android.graphics.drawable.BitmapDrawable import androidx.test.ext.junit.runners.AndroidJUnit4 import com.github.panpf.sketch.cache.CachePolicy.DISABLED import com.github.panpf.sketch.cache.CachePolicy.ENABLED import com.github.panpf.sketch.cache.CachePolicy.READ_ONLY import com.github.panpf.sketch.cache.CachePolicy.WRITE_ONLY import com.github.panpf.sketch.cache.CountBitmap import com.github.panpf.sketch.cache.MemoryCache import com.github.panpf.sketch.datasource.DataFrom import com.github.panpf.sketch.decode.ImageInfo import com.github.panpf.sketch.drawable.SketchCountBitmapDrawable import com.github.panpf.sketch.request.Depth.MEMORY import com.github.panpf.sketch.request.DepthException import com.github.panpf.sketch.request.DisplayData import com.github.panpf.sketch.request.DisplayRequest import com.github.panpf.sketch.request.DownloadData import com.github.panpf.sketch.request.DownloadRequest import com.github.panpf.sketch.request.ImageData import com.github.panpf.sketch.request.ImageRequest import com.github.panpf.sketch.request.LoadData import com.github.panpf.sketch.request.LoadRequest import com.github.panpf.sketch.request.RequestInterceptor import com.github.panpf.sketch.request.RequestInterceptor.Chain import com.github.panpf.sketch.request.internal.MemoryCacheRequestInterceptor import com.github.panpf.sketch.request.internal.RequestInterceptorChain import com.github.panpf.sketch.test.utils.TestAssets import com.github.panpf.sketch.test.utils.getTestContextAndNewSketch import com.github.panpf.sketch.test.utils.toRequestContext import com.github.panpf.sketch.util.asOrThrow import com.github.panpf.tools4j.test.ktx.assertThrow import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.runBlocking import org.junit.Assert import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class MemoryCacheRequestInterceptorTest { @Test fun testIntercept() { val (context, sketch) = getTestContextAndNewSketch() val memoryCache = sketch.memoryCache val requestInterceptorList = listOf(MemoryCacheRequestInterceptor(), FakeRequestInterceptor()) val executeRequest: (ImageRequest) -> ImageData = { request -> runBlocking(Dispatchers.Main) { RequestInterceptorChain( sketch = sketch, initialRequest = request, request = request, requestContext = request.toRequestContext(), interceptors = requestInterceptorList, index = 0, ).proceed(request) } } memoryCache.clear() Assert.assertEquals(0, memoryCache.size) /* DownloadRequest */ executeRequest(DownloadRequest(context, TestAssets.SAMPLE_JPEG_URI) { memoryCachePolicy(ENABLED) }).asOrThrow<DownloadData>() Assert.assertEquals(0, memoryCache.size) executeRequest(DownloadRequest(context, TestAssets.SAMPLE_JPEG_URI) { memoryCachePolicy(ENABLED) }).asOrThrow<DownloadData>() Assert.assertEquals(0, memoryCache.size) /* LoadRequest */ executeRequest(LoadRequest(context, TestAssets.SAMPLE_JPEG_URI) { memoryCachePolicy(ENABLED) }).asOrThrow<LoadData>() Assert.assertEquals(0, memoryCache.size) executeRequest(LoadRequest(context, TestAssets.SAMPLE_JPEG_URI) { memoryCachePolicy(ENABLED) }).asOrThrow<LoadData>() Assert.assertEquals(0, memoryCache.size) /* DisplayRequest - ENABLED */ val displayRequest = DisplayRequest(context, TestAssets.SAMPLE_JPEG_URI) val countBitmapDrawable: SketchCountBitmapDrawable memoryCache.clear() Assert.assertEquals(0, memoryCache.size) executeRequest(displayRequest.newDisplayRequest { memoryCachePolicy(ENABLED) }).asOrThrow<DisplayData>().apply { Assert.assertEquals(DataFrom.LOCAL, dataFrom) countBitmapDrawable = drawable.asOrThrow() } Assert.assertEquals(40000, memoryCache.size) executeRequest(displayRequest.newDisplayRequest { memoryCachePolicy(ENABLED) }).asOrThrow<DisplayData>().apply { Assert.assertEquals(DataFrom.MEMORY_CACHE, dataFrom) } Assert.assertEquals(40000, memoryCache.size) /* DisplayRequest - DISABLED */ memoryCache.clear() Assert.assertEquals(0, memoryCache.size) executeRequest(displayRequest.newDisplayRequest { memoryCachePolicy(DISABLED) }).asOrThrow<DisplayData>().apply { Assert.assertEquals(DataFrom.LOCAL, dataFrom) } Assert.assertEquals(0, memoryCache.size) memoryCache.put( displayRequest.toRequestContext().cacheKey, MemoryCache.Value( countBitmapDrawable.countBitmap, imageUri = countBitmapDrawable.imageUri, requestKey = countBitmapDrawable.requestKey, requestCacheKey = countBitmapDrawable.requestCacheKey, imageInfo = countBitmapDrawable.imageInfo, transformedList = countBitmapDrawable.transformedList, extras = countBitmapDrawable.extras, ) ) Assert.assertEquals(40000, memoryCache.size) executeRequest(displayRequest.newDisplayRequest { memoryCachePolicy(DISABLED) }).asOrThrow<DisplayData>().apply { Assert.assertEquals(DataFrom.LOCAL, dataFrom) } Assert.assertEquals(40000, memoryCache.size) /* DisplayRequest - READ_ONLY */ memoryCache.clear() Assert.assertEquals(0, memoryCache.size) executeRequest(displayRequest.newDisplayRequest { memoryCachePolicy(READ_ONLY) }).asOrThrow<DisplayData>().apply { Assert.assertEquals(DataFrom.LOCAL, dataFrom) } Assert.assertEquals(0, memoryCache.size) memoryCache.put( displayRequest.toRequestContext().cacheKey, MemoryCache.Value( countBitmapDrawable.countBitmap, imageUri = countBitmapDrawable.imageUri, requestKey = countBitmapDrawable.requestKey, requestCacheKey = countBitmapDrawable.requestCacheKey, imageInfo = countBitmapDrawable.imageInfo, transformedList = countBitmapDrawable.transformedList, extras = countBitmapDrawable.extras, ) ) Assert.assertEquals(40000, memoryCache.size) executeRequest(displayRequest.newDisplayRequest { memoryCachePolicy(READ_ONLY) }).asOrThrow<DisplayData>().apply { Assert.assertEquals(DataFrom.MEMORY_CACHE, dataFrom) } Assert.assertEquals(40000, memoryCache.size) /* DisplayRequest - WRITE_ONLY */ memoryCache.clear() Assert.assertEquals(0, memoryCache.size) executeRequest(displayRequest.newDisplayRequest { memoryCachePolicy(WRITE_ONLY) }).asOrThrow<DisplayData>().apply { Assert.assertEquals(DataFrom.LOCAL, dataFrom) } Assert.assertEquals(40000, memoryCache.size) executeRequest(displayRequest.newDisplayRequest { memoryCachePolicy(WRITE_ONLY) }).asOrThrow<DisplayData>().apply { Assert.assertEquals(DataFrom.LOCAL, dataFrom) } Assert.assertEquals(40000, memoryCache.size) /* Non SketchCountBitmapDrawable */ val displayRequest1 = DisplayRequest(context, TestAssets.SAMPLE_PNG_URI) memoryCache.clear() Assert.assertEquals(0, memoryCache.size) executeRequest(displayRequest1.newDisplayRequest { memoryCachePolicy(ENABLED) }).asOrThrow<DisplayData>().apply { Assert.assertEquals(DataFrom.LOCAL, dataFrom) } Assert.assertEquals(0, memoryCache.size) executeRequest(displayRequest1.newDisplayRequest { memoryCachePolicy(ENABLED) }).asOrThrow<DisplayData>().apply { Assert.assertEquals(DataFrom.LOCAL, dataFrom) } Assert.assertEquals(0, memoryCache.size) /* Depth.MEMORY */ memoryCache.clear() Assert.assertEquals(0, memoryCache.size) assertThrow(DepthException::class) { executeRequest(displayRequest.newDisplayRequest { memoryCachePolicy(ENABLED) depth(MEMORY) }) } } @Test fun testEqualsAndHashCode() { val element1 = MemoryCacheRequestInterceptor() val element11 = MemoryCacheRequestInterceptor() val element2 = MemoryCacheRequestInterceptor() Assert.assertNotSame(element1, element11) Assert.assertNotSame(element1, element2) Assert.assertNotSame(element2, element11) Assert.assertEquals(element1, element1) Assert.assertEquals(element1, element11) Assert.assertEquals(element1, element2) Assert.assertEquals(element2, element11) Assert.assertNotEquals(element1, null) Assert.assertNotEquals(element1, Any()) Assert.assertEquals(element1.hashCode(), element1.hashCode()) Assert.assertEquals(element1.hashCode(), element11.hashCode()) Assert.assertEquals(element1.hashCode(), element2.hashCode()) Assert.assertEquals(element2.hashCode(), element11.hashCode()) } @Test fun testSortWeight() { MemoryCacheRequestInterceptor().apply { Assert.assertEquals(90, sortWeight) } } @Test fun testToString() { Assert.assertEquals( "MemoryCacheRequestInterceptor(sortWeight=90)", MemoryCacheRequestInterceptor().toString() ) } class FakeRequestInterceptor : RequestInterceptor { override val key: String? = null override val sortWeight: Int = 0 override suspend fun intercept(chain: Chain): ImageData { return when (chain.request) { is DisplayRequest -> { val bitmap = Bitmap.createBitmap(100, 100, ARGB_8888) val imageInfo: ImageInfo val drawable = if (chain.request.uriString.contains(".jpeg")) { imageInfo = ImageInfo(100, 100, "image/jpeg", 0) val countBitmap = CountBitmap( cacheKey = chain.request.toRequestContext().cacheKey, bitmap = bitmap, bitmapPool = chain.sketch.bitmapPool, disallowReuseBitmap = false, ) SketchCountBitmapDrawable( resources = chain.sketch.context.resources, countBitmap = countBitmap, imageUri = chain.request.uriString, requestKey = chain.request.toRequestContext().key, requestCacheKey = chain.request.toRequestContext().cacheKey, imageInfo = imageInfo, transformedList = null, extras = null, dataFrom = DataFrom.LOCAL ) } else { imageInfo = ImageInfo(100, 100, "image/png", 0) BitmapDrawable(chain.sketch.context.resources, bitmap) } DisplayData(drawable, imageInfo, DataFrom.LOCAL, null, null) } is LoadRequest -> { val bitmap = Bitmap.createBitmap(100, 100, ARGB_8888) val imageInfo = ImageInfo(100, 100, "image/jpeg", 0) LoadData(bitmap, imageInfo, DataFrom.LOCAL, null, null) } is DownloadRequest -> { DownloadData(byteArrayOf(), DataFrom.NETWORK) } else -> { throw UnsupportedOperationException("Unsupported ImageRequest: ${chain.request::class.java}") } } } } }
apache-2.0
471235159128fcf7868037ad193d4e96
40.533333
113
0.644703
5.239087
false
true
false
false
AndroidX/androidx
privacysandbox/tools/tools-apicompiler/src/test/java/androidx/privacysandbox/tools/apicompiler/FullFeaturedSdkTest.kt
3
3235
/* * 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.privacysandbox.tools.apicompiler import androidx.privacysandbox.tools.testing.CompilationTestHelper.assertThat import androidx.privacysandbox.tools.testing.loadSourcesFromDirectory import java.io.File import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 /** Test the Privacy Sandbox API Compiler with an SDK that uses all available features. */ @RunWith(JUnit4::class) class FullFeaturedSdkTest { @Test fun compileServiceInterface_ok() { val inputTestDataDir = File("src/test/test-data/fullfeaturedsdk/input") val outputTestDataDir = File("src/test/test-data/fullfeaturedsdk/output") val inputSources = loadSourcesFromDirectory(inputTestDataDir) val expectedKotlinSources = loadSourcesFromDirectory(outputTestDataDir) val result = compileWithPrivacySandboxKspCompiler( inputSources, platformStubs = PlatformStubs.API_33, extraProcessorOptions = mapOf("skip_sdk_runtime_compat_library" to "true") ) assertThat(result).succeeds() val expectedAidlFilepath = listOf( "com/mysdk/ICancellationSignal.java", "com/mysdk/IMyCallback.java", "com/mysdk/IMyInterface.java", "com/mysdk/IMyInterfaceTransactionCallback.java", "com/mysdk/IMySdk.java", "com/mysdk/IMySecondInterface.java", "com/mysdk/IMySecondInterfaceTransactionCallback.java", "com/mysdk/IResponseTransactionCallback.java", "com/mysdk/IStringTransactionCallback.java", "com/mysdk/IUnitTransactionCallback.java", "com/mysdk/IListResponseTransactionCallback.java", "com/mysdk/IListIntTransactionCallback.java", "com/mysdk/IListLongTransactionCallback.java", "com/mysdk/IListDoubleTransactionCallback.java", "com/mysdk/IListStringTransactionCallback.java", "com/mysdk/IListBooleanTransactionCallback.java", "com/mysdk/IListFloatTransactionCallback.java", "com/mysdk/IListCharTransactionCallback.java", "com/mysdk/IListShortTransactionCallback.java", "com/mysdk/ParcelableRequest.java", "com/mysdk/ParcelableResponse.java", "com/mysdk/ParcelableStackFrame.java", "com/mysdk/ParcelableInnerValue.java", "com/mysdk/PrivacySandboxThrowableParcel.java", ) assertThat(result).hasAllExpectedGeneratedSourceFilesAndContent( expectedKotlinSources, expectedAidlFilepath ) } }
apache-2.0
07498a8882f3386121082d2d153fedb7
42.146667
90
0.702937
4.493056
false
true
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/cargo/toolchain/CommandLine.kt
2
9032
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.cargo.toolchain import com.intellij.execution.Executor import com.intellij.execution.ProgramRunnerUtil import com.intellij.execution.RunManagerEx import com.intellij.execution.RunnerAndConfigurationSettings import com.intellij.execution.configuration.EnvironmentVariablesData import com.intellij.execution.executors.DefaultRunExecutor import com.intellij.execution.runners.ProgramRunner import com.intellij.notification.NotificationType import org.rust.RsBundle import org.rust.cargo.project.model.CargoProject import org.rust.cargo.project.model.cargoProjects import org.rust.cargo.project.workspace.CargoWorkspace import org.rust.cargo.runconfig.command.CargoCommandConfiguration.Companion.emulateTerminalDefault import org.rust.cargo.runconfig.command.workingDirectory import org.rust.cargo.runconfig.createCargoCommandRunConfiguration import org.rust.cargo.runconfig.wasmpack.WasmPackCommandConfiguration import org.rust.cargo.runconfig.wasmpack.WasmPackCommandConfigurationType import org.rust.ide.notifications.RsNotifications import org.rust.stdext.buildList import java.io.File import java.nio.file.Path abstract class RsCommandLineBase { abstract val command: String abstract val workingDirectory: Path abstract val redirectInputFrom: File? abstract val additionalArguments: List<String> protected abstract val executableName: String protected abstract fun createRunConfiguration(runManager: RunManagerEx, name: String? = null): RunnerAndConfigurationSettings fun run( cargoProject: CargoProject, presentableName: String = command, saveConfiguration: Boolean = true, executor: Executor = DefaultRunExecutor.getRunExecutorInstance() ) { val project = cargoProject.project val configurationName = when { project.cargoProjects.allProjects.size > 1 -> "$presentableName [${cargoProject.presentableName}]" else -> presentableName } val runManager = RunManagerEx.getInstanceEx(project) val configuration = createRunConfiguration(runManager, configurationName).apply { if (saveConfiguration) { runManager.setTemporaryConfiguration(this) } } val runner = ProgramRunner.getRunner(executor.id, configuration.configuration) val finalExecutor = if (runner == null) { RsNotifications.pluginNotifications() .createNotification(RsBundle.message("notification.0.action.is.not.available.for.1.command", executor.actionName, "$executableName $command"), NotificationType.WARNING) .notify(project) DefaultRunExecutor.getRunExecutorInstance() } else { executor } ProgramRunnerUtil.executeConfiguration(configuration, finalExecutor) } } data class CargoCommandLine( override val command: String, // Can't be `enum` because of custom subcommands override val workingDirectory: Path, // Note that working directory selects Cargo project as well override val additionalArguments: List<String> = emptyList(), override val redirectInputFrom: File? = null, val backtraceMode: BacktraceMode = BacktraceMode.DEFAULT, val toolchain: String? = null, val channel: RustChannel = RustChannel.DEFAULT, val environmentVariables: EnvironmentVariablesData = EnvironmentVariablesData.DEFAULT, val requiredFeatures: Boolean = true, val allFeatures: Boolean = false, val emulateTerminal: Boolean = emulateTerminalDefault, val withSudo: Boolean = false ) : RsCommandLineBase() { override val executableName: String get() = "cargo" override fun createRunConfiguration(runManager: RunManagerEx, name: String?): RunnerAndConfigurationSettings = runManager.createCargoCommandRunConfiguration(this, name) /** * Adds [arg] to [additionalArguments] as an positional argument, in other words, inserts [arg] right after * `--` argument in [additionalArguments]. * */ fun withPositionalArgument(arg: String): CargoCommandLine { val (pre, post) = splitOnDoubleDash() if (arg in post) return this return copy(additionalArguments = pre + "--" + arg + post) } /** * Splits [additionalArguments] into parts before and after `--`. * For `cargo run --release -- foo bar`, returns (["--release"], ["foo", "bar"]) */ fun splitOnDoubleDash(): Pair<List<String>, List<String>> = org.rust.cargo.util.splitOnDoubleDash(additionalArguments) fun prependArgument(arg: String): CargoCommandLine = copy(additionalArguments = listOf(arg) + additionalArguments) companion object { fun forTargets( targets: List<CargoWorkspace.Target>, command: String, additionalArguments: List<String> = emptyList(), usePackageOption: Boolean = true, isDoctest: Boolean = false ): CargoCommandLine { val pkgs = targets.map { it.pkg } // Make sure the selection does not span more than one package. assert(pkgs.map { it.rootDirectory }.distinct().size == 1) val pkg = pkgs.first() val targetArgs = targets.distinctBy { it.name }.flatMap { target -> when (target.kind) { CargoWorkspace.TargetKind.Bin -> listOf("--bin", target.name) CargoWorkspace.TargetKind.Test -> listOf("--test", target.name) CargoWorkspace.TargetKind.ExampleBin, is CargoWorkspace.TargetKind.ExampleLib -> listOf("--example", target.name) CargoWorkspace.TargetKind.Bench -> listOf("--bench", target.name) is CargoWorkspace.TargetKind.Lib -> { if (isDoctest) { listOf("--doc") } else { listOf("--lib") } } CargoWorkspace.TargetKind.CustomBuild, CargoWorkspace.TargetKind.Unknown -> emptyList() } } val workingDirectory = if (usePackageOption) { pkg.workspace.contentRoot } else { pkg.rootDirectory } val commandLineArguments = buildList<String> { if (usePackageOption) { add("--package") add(pkg.name) } addAll(targetArgs) addAll(additionalArguments) } return CargoCommandLine(command, workingDirectory, commandLineArguments) } fun forTarget( target: CargoWorkspace.Target, command: String, additionalArguments: List<String> = emptyList(), usePackageOption: Boolean = true ): CargoCommandLine = forTargets(listOf(target), command, additionalArguments, usePackageOption) fun forProject( cargoProject: CargoProject, command: String, additionalArguments: List<String> = emptyList(), toolchain: String? = null, channel: RustChannel = RustChannel.DEFAULT, environmentVariables: EnvironmentVariablesData = EnvironmentVariablesData.DEFAULT ): CargoCommandLine = CargoCommandLine( command, workingDirectory = cargoProject.workingDirectory, additionalArguments = additionalArguments, toolchain = toolchain, channel = channel, environmentVariables = environmentVariables ) fun forPackage( cargoPackage: CargoWorkspace.Package, command: String, additionalArguments: List<String> = emptyList() ): CargoCommandLine = CargoCommandLine( command, workingDirectory = cargoPackage.workspace.manifestPath.parent, additionalArguments = listOf("--package", cargoPackage.name) + additionalArguments ) } } data class WasmPackCommandLine( override val command: String, override val workingDirectory: Path, override val additionalArguments: List<String> = emptyList() ) : RsCommandLineBase() { override val executableName: String get() = "wasm-pack" override val redirectInputFrom: File? = null override fun createRunConfiguration(runManager: RunManagerEx, name: String?): RunnerAndConfigurationSettings { val runnerAndConfigurationSettings = runManager.createConfiguration( name ?: command, WasmPackCommandConfigurationType.getInstance().factory ) val configuration = runnerAndConfigurationSettings.configuration as WasmPackCommandConfiguration configuration.setFromCmd(this) return runnerAndConfigurationSettings } }
mit
f336cb319dcb94044d06ed17a00e10da
40.431193
184
0.664194
5.450815
false
true
false
false
mhsjlw/AndroidSnap
app/src/main/java/me/keegan/snap/ImageResizer.kt
1
3178
package me.keegan.snap import android.graphics.Bitmap import android.graphics.BitmapFactory import android.util.Pair object ImageResizer { /* * Call this static method to resize an image to a specified width and height. * * @param targetWidth The width to resize to. * @param targetHeight The height to resize to. * @returns The resized image as a Bitmap. */ fun resizeImage(imageData: ByteArray, targetWidth: Int, targetHeight: Int): Bitmap { // Use BitmapFactory to decode the image val options = BitmapFactory.Options() // inSampleSize is used to sample smaller versions of the image options.inSampleSize = calculateInSampleSize(options, targetWidth, targetHeight) // Decode bitmap with inSampleSize and target dimensions set options.inJustDecodeBounds = false val reducedBitmap = BitmapFactory.decodeByteArray(imageData, 0, imageData.size, options) return Bitmap.createScaledBitmap(reducedBitmap, targetWidth, targetHeight, false) } fun resizeImageMaintainAspectRatio(imageData: ByteArray, shorterSideTarget: Int): Bitmap { val dimensions = getDimensions(imageData) // Determine the aspect ratio (width/height) of the image val imageWidth = dimensions.first val imageHeight = dimensions.second val ratio = dimensions.first as Float / dimensions.second val targetWidth: Int val targetHeight: Int // Determine portrait or landscape if (imageWidth > imageHeight) { // Landscape image. ratio (width/height) is > 1 targetHeight = shorterSideTarget targetWidth = Math.round(shorterSideTarget * ratio) } else { // Portrait image. ratio (width/height) is < 1 targetWidth = shorterSideTarget targetHeight = Math.round(shorterSideTarget / ratio) } return resizeImage(imageData, targetWidth, targetHeight) } fun getDimensions(imageData: ByteArray): Pair<Int, Int> { // Use BitmapFactory to decode the image val options = BitmapFactory.Options() // Only decode the bounds of the image, not the whole image, to get the dimensions options.inJustDecodeBounds = true BitmapFactory.decodeByteArray(imageData, 0, imageData.size, options) return Pair(options.outWidth, options.outHeight) } fun calculateInSampleSize(options: BitmapFactory.Options, reqWidth: Int, reqHeight: Int): Int { // Raw height and width of image val height = options.outHeight val width = options.outWidth var inSampleSize = 1 if (height > reqHeight || width > reqWidth) { val halfHeight = height / 2 val halfWidth = width / 2 // Calculate the largest inSampleSize value that is a power of 2 and keeps both // height and width larger than the requested height and width. while (halfHeight / inSampleSize > reqHeight && halfWidth / inSampleSize > reqWidth) { inSampleSize *= 2 } } return inSampleSize } }
mit
2fbd734fe787aad017e20dc374e29701
35.528736
99
0.661108
5.125806
false
false
false
false
androidx/androidx
compose/foundation/foundation/integration-tests/foundation-demos/src/main/java/androidx/compose/foundation/demos/text/TextFieldCursorBlinkingDemo.kt
3
6124
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.foundation.demos.text import androidx.compose.animation.Animatable import androidx.compose.animation.core.TweenSpec import androidx.compose.foundation.layout.Column import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.text.BasicText import androidx.compose.foundation.text.BasicTextField import androidx.compose.foundation.verticalScroll import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.focus.onFocusChanged import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.text.TextRange import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.input.TextFieldValue import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.sp import kotlinx.coroutines.delay @Preview @Composable fun TextFieldCursorBlinkingDemo() { Column(Modifier.verticalScroll(rememberScrollState())) { BasicText("Focus on any of the text fields below to observe cursor behavior.") BasicText("All fields are not editable, with a fixed selection position") Item("Default cursor") { DefaultCursor() } Item("Color cursor") { ColorCursor() } Item("Color changing cursor") { RainbowCursor() } Item("Gradient Cursor") { GradientCursor() } Item("Cursors don't blink when typing (fake typing)") { TypingCursorNeverBlinks() } Item("Changing selection shows cursor") { ChangingSelectionShowsCursor() } } } @Composable private fun Item(title: String, content: @Composable () -> Unit) { Column { BasicText(title, style = TextStyle.Default.copy( color = Color(0xFFAAAAAA), fontSize = 20.sp )) content() } } @Composable private fun DefaultCursor() { val textFieldValue = TextFieldValue( text = "Normal blink", selection = TextRange(3) ) BasicTextField(value = textFieldValue, modifier = demoTextFieldModifiers, onValueChange = {}) } @Composable private fun ColorCursor() { val textFieldValue = TextFieldValue( text = "Red cursor", selection = TextRange(3) ) BasicTextField( value = textFieldValue, modifier = demoTextFieldModifiers, onValueChange = {}, cursorBrush = SolidColor(Color.Red) ) } private val Red = Color(0xffE13C56) private val Orange = Color(0xffE16D3C) private val Yellow = Color(0xffE0AE04) private val Green = Color(0xff78AA04) private val Blue = Color(0xff4A7DCF) private val Purple = Color(0xff7B4397) private val Rainbow = listOf(Orange, Yellow, Green, Blue, Purple, Red) @Composable private fun RainbowCursor() { val textFieldValue = TextFieldValue( text = "Rainbow cursor", selection = TextRange(3) ) val color = remember { Animatable(Red) } var shouldAnimate by remember { mutableStateOf(false) } LaunchedEffect(shouldAnimate) { while (shouldAnimate) { Rainbow.forEach { color.animateTo(it, TweenSpec(1_800)) } } } BasicTextField( value = textFieldValue, onValueChange = {}, cursorBrush = SolidColor(color.value), modifier = demoTextFieldModifiers.onFocusChanged { shouldAnimate = it.isFocused } ) } @Composable private fun GradientCursor() { val textFieldValue = TextFieldValue( text = "Gradient cursor", selection = TextRange(3) ) BasicTextField( value = textFieldValue, modifier = demoTextFieldModifiers, onValueChange = {}, cursorBrush = Brush.verticalGradient(colors = Rainbow), ) } @Composable fun TypingCursorNeverBlinks() { var text by remember { mutableStateOf("") } var animate by remember { mutableStateOf(false) } LaunchedEffect(animate) { while (animate) { text = "" listOf("Lorem ", "ipsum ", "was ", "here.").forEach { word -> text += word delay(500) } } } val textFieldValue = TextFieldValue( text = text, selection = TextRange(text.length), ) BasicTextField( value = textFieldValue, onValueChange = {}, modifier = demoTextFieldModifiers.onFocusChanged { animate = it.isFocused } ) } @Composable @Preview fun ChangingSelectionShowsCursor() { val text = "Some longer text that takes a while to cursor through" var selection by remember { mutableStateOf(TextRange(0)) } LaunchedEffect(text) { while (true) { selection = TextRange((selection.start + 1) % text.length) delay(500) } } val textFieldValue = TextFieldValue( text = text, selection = selection ) Column { BasicTextField( value = textFieldValue, modifier = demoTextFieldModifiers, onValueChange = {}, textStyle = TextStyle.Default.copy(fontFamily = FontFamily.Monospace) ) } }
apache-2.0
c2513ed4331544394fcb6db23a9ce0a9
29.625
97
0.67162
4.512896
false
false
false
false
actions-on-google/appactions-common-biis-kotlin
app/src/sharedTest/java/com/example/android/architecture/blueprints/todoapp/util/DataBindingIdlingResource.kt
1
4045
/* * Copyright (C) 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.architecture.blueprints.todoapp.util import android.view.View import androidx.databinding.DataBindingUtil import androidx.databinding.ViewDataBinding import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentActivity import androidx.fragment.app.testing.FragmentScenario import androidx.test.core.app.ActivityScenario import androidx.test.espresso.IdlingResource import java.util.UUID /** * An espresso idling resource implementation that reports idle status for all data binding * layouts. Data Binding uses a mechanism to post messages which Espresso doesn't track yet. * * Since this application only uses fragments, the resource only checks the fragments and their * children instead of the whole view tree. */ class DataBindingIdlingResource : IdlingResource { // list of registered callbacks private val idlingCallbacks = mutableListOf<IdlingResource.ResourceCallback>() // give it a unique id to workaround an espresso bug where you cannot register/unregister // an idling resource w/ the same name. private val id = UUID.randomUUID().toString() // holds whether isIdle is called and the result was false. We track this to avoid calling // onTransitionToIdle callbacks if Espresso never thought we were idle in the first place. private var wasNotIdle = false lateinit var activity: FragmentActivity override fun getName() = "DataBinding $id" override fun isIdleNow(): Boolean { val idle = !getBindings().any { it.hasPendingBindings() } @Suppress("LiftReturnOrAssignment") if (idle) { if (wasNotIdle) { // notify observers to avoid espresso race detector idlingCallbacks.forEach { it.onTransitionToIdle() } } wasNotIdle = false } else { wasNotIdle = true // check next frame activity.findViewById<View>(android.R.id.content).postDelayed({ isIdleNow }, 16) } return idle } override fun registerIdleTransitionCallback(callback: IdlingResource.ResourceCallback) { idlingCallbacks.add(callback) } /** * Find all binding classes in all currently available fragments. */ private fun getBindings(): List<ViewDataBinding> { val fragments = (activity as? FragmentActivity) ?.supportFragmentManager ?.fragments val bindings = fragments?.mapNotNull { it.view?.getBinding() } ?: emptyList() val childrenBindings = fragments?.flatMap { it.childFragmentManager.fragments } ?.mapNotNull { it.view?.getBinding() } ?: emptyList() return bindings + childrenBindings } } private fun View.getBinding(): ViewDataBinding? = DataBindingUtil.getBinding(this) /** * Sets the activity from an [ActivityScenario] to be used from [DataBindingIdlingResource]. */ fun DataBindingIdlingResource.monitorActivity( activityScenario: ActivityScenario<out FragmentActivity> ) { activityScenario.onActivity { this.activity = it } } /** * Sets the fragment from a [FragmentScenario] to be used from [DataBindingIdlingResource]. */ fun DataBindingIdlingResource.monitorFragment(fragmentScenario: FragmentScenario<out Fragment>) { fragmentScenario.onFragment { this.activity = it.requireActivity() } }
apache-2.0
79a86b2759aee4cfd4cce8a3e4def2c3
35.116071
97
0.704079
5
false
false
false
false
bsmr-java/lwjgl3
modules/templates/src/main/kotlin/org/lwjgl/opengl/templates/EXT_gpu_shader4.kt
1
14102
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package org.lwjgl.opengl.templates import org.lwjgl.generator.* import org.lwjgl.opengl.* val EXT_gpu_shader4 = "EXTGPUShader4".nativeClassGL("EXT_gpu_shader4", postfix = EXT) { documentation = """ Native bindings to the $registryLink extension. This extension provides a set of new features to the OpenGL Shading Language and related APIs to support capabilities of new hardware. In particular, this extension provides the following functionality: ${ul( """ New texture lookup functions are provided that allow shaders to access individual texels using integer coordinates referring to the texel location and level of detail. No filtering is performed. These functions allow applications to use textures as one-, two-, and three-dimensional arrays. """, "New texture lookup functions are provided that allow shaders to query the dimensions of a specific level-of-detail image of a texture object.", """ New texture lookup functions variants are provided that allow shaders to pass a constant integer vector used to offset the texel locations used during the lookup to assist in custom texture filtering operations. """, """ New texture lookup functions are provided that allow shaders to access one- and two-dimensional array textures. The second, or third, coordinate is used to select the layer of the array to access. """, """ New "Grad" texture lookup functions are provided that allow shaders to explicitely pass in derivative values which are used by the GL to compute the level-of-detail when performing a texture lookup. """, "A new texture lookup function is provided to access a buffer texture.", "The existing absolute LOD texture lookup functions are no longer restricted to the vertex shader only.", """ The ability to specify and use cubemap textures with a DEPTH_COMPONENT internal format. This also enables shadow mapping on cubemaps. The 'q' coordinate is used as the reference value for comparisons. A set of new texture lookup functions is provided to lookup into shadow cubemaps. """, """ The ability to specify if varying variables are interpolated in a non-perspective correct manner, if they are flat shaded or, if multi-sampling, if centroid sampling should be performed. """, """ Full signed integer and unsigned integer support in the OpenGL Shading Language: ${ul( "Integers are defined as 32 bit values using two's complement.", "Unsigned integers and vectors thereof are added.", """ New texture lookup functions are provided that return integer values. These functions are to be used in conjunction with new texture formats whose components are actual integers, rather than integers that encode a floating-point value. To support these lookup functions, new integer and unsigned-integer sampler types are introduced. """, "Integer bitwise operators are now enabled.", "Several built-in functions and operators now operate on integers or vectors of integers.", "New vertex attribute functions are added that load integer attribute data and can be referenced in a vertex shader as integer data.", "New uniform loading commands are added to load unsigned integer data.", "Varying variables can now be (unsigned) integers. If declared as such, they have to be flat shaded.", """ Fragment shaders can define their own output variables, and declare them to be of type floating-point, integer or unsigned integer. These variables are bound to a fragment color index with the new API command BindFragDataLocationEXT(), and directed to buffers using the existing DrawBuffer or DrawBuffers API commands. """ )} """, "Added new built-in functions truncate() and round() to the shading language.", """ A new built-in variable accessible from within vertex shaders that holds the index <i> implicitly passed to ArrayElement to specify the vertex. This is called the vertex ID. """, """ A new built-in variable accessible from within fragment and geometry shaders that hold the index of the currently processed primitive. This is called the primitive ID. """ )} This extension also briefly mentions a new shader type, called a geometry shader. A geometry shader is run after vertices are transformed, but before clipping. A geometry shader begins with a single primitive (point, line, triangle. It can read the attributes of any of the vertices in the primitive and use them to generate new primitives. A geometry shader has a fixed output primitive type (point, line strip, or triangle strip) and emits vertices to define a new primitive. Geometry shaders are discussed in detail in the GL_EXT_geometry_shader4 specification. Requires ${GL20.core}. """ IntConstant( """ Accepted by the {@code pname} parameters of GetVertexAttribdv, GetVertexAttribfv, GetVertexAttribiv, GetVertexAttribIuivEXT and GetVertexAttribIivEXT. """, "VERTEX_ATTRIB_ARRAY_INTEGER_EXT"..0x88FD ) IntConstant( "Returned by the {@code type} parameter of GetActiveUniform.", "SAMPLER_1D_ARRAY_EXT"..0x8DC0, "SAMPLER_2D_ARRAY_EXT"..0x8DC1, "SAMPLER_BUFFER_EXT"..0x8DC2, "SAMPLER_1D_ARRAY_SHADOW_EXT"..0x8DC3, "SAMPLER_2D_ARRAY_SHADOW_EXT"..0x8DC4, "SAMPLER_CUBE_SHADOW_EXT"..0x8DC5, "UNSIGNED_INT_VEC2_EXT"..0x8DC6, "UNSIGNED_INT_VEC3_EXT"..0x8DC7, "UNSIGNED_INT_VEC4_EXT"..0x8DC8, "INT_SAMPLER_1D_EXT"..0x8DC9, "INT_SAMPLER_2D_EXT"..0x8DCA, "INT_SAMPLER_3D_EXT"..0x8DCB, "INT_SAMPLER_CUBE_EXT"..0x8DCC, "INT_SAMPLER_2D_RECT_EXT"..0x8DCD, "INT_SAMPLER_1D_ARRAY_EXT"..0x8DCE, "INT_SAMPLER_2D_ARRAY_EXT"..0x8DCF, "INT_SAMPLER_BUFFER_EXT"..0x8DD0, "UNSIGNED_INT_SAMPLER_1D_EXT"..0x8DD1, "UNSIGNED_INT_SAMPLER_2D_EXT"..0x8DD2, "UNSIGNED_INT_SAMPLER_3D_EXT"..0x8DD3, "UNSIGNED_INT_SAMPLER_CUBE_EXT"..0x8DD4, "UNSIGNED_INT_SAMPLER_2D_RECT_EXT"..0x8DD5, "UNSIGNED_INT_SAMPLER_1D_ARRAY_EXT"..0x8DD6, "UNSIGNED_INT_SAMPLER_2D_ARRAY_EXT"..0x8DD7, "UNSIGNED_INT_SAMPLER_BUFFER_EXT"..0x8DD8 ) IntConstant( "Accepted by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetFloatv, and GetDoublev.", "MIN_PROGRAM_TEXEL_OFFSET_EXT"..0x8904, "MAX_PROGRAM_TEXEL_OFFSET_EXT"..0x8905 ) // Vertex attrib functions javadoc val vertexAttribIndex = "the index of the pure integer generic vertex attribute to be modified" val vertexAttribX = "the vertex attribute x component" val vertexAttribY = "the vertex attribute y component" val vertexAttribZ = "the vertex attribute z component" val vertexAttribW = "the vertex attribute w component" val vertexAttribBuffer = "the pure integer vertex attribute buffer" void("VertexAttribI1iEXT", "Specifies the value of a pure integer generic vertex attribute. The y and z components are implicitly set to 0 and w to 1.", GLuint.IN("index", vertexAttribIndex), GLint.IN("x", vertexAttribX)) void("VertexAttribI2iEXT", "Specifies the value of a pure integer generic vertex attribute. The z component is implicitly set to 0 and w to 1.", GLuint.IN("index", vertexAttribIndex), GLint.IN("x", vertexAttribX), GLint.IN("y", vertexAttribY)) void("VertexAttribI3iEXT", "Specifies the value of a pure integer generic vertex attribute. The w component is implicitly set to 1.", GLuint.IN("index", vertexAttribIndex), GLint.IN("x", vertexAttribX), GLint.IN("y", vertexAttribY), GLint.IN("z", vertexAttribZ)) void("VertexAttribI4iEXT", "Specifies the value of a pure integer generic vertex attribute.", GLuint.IN("index", vertexAttribIndex), GLint.IN("x", vertexAttribX), GLint.IN("y", vertexAttribY), GLint.IN("z", vertexAttribZ), GLint.IN("w", vertexAttribW)) void("VertexAttribI1uiEXT", "Specifies the value of an unsigned pure integer generic vertex attribute. The y and z components are implicitly set to 0 and w to 1.", GLuint.IN("index", vertexAttribIndex), GLuint.IN("x", vertexAttribX)) void("VertexAttribI2uiEXT", "Specifies the value of an unsigned pure integer generic vertex attribute. The z component is implicitly set to 0 and w to 1.", GLuint.IN("index", vertexAttribIndex), GLuint.IN("x", vertexAttribX), GLuint.IN("y", vertexAttribY)) void("VertexAttribI3uiEXT", "Specifies the value of an unsigned pure integer generic vertex attribute. The w component is implicitly set to 1.", GLuint.IN("index", vertexAttribIndex), GLint.IN("x", vertexAttribX), GLint.IN("y", vertexAttribY), GLint.IN("z", vertexAttribZ)) void("VertexAttribI4uiEXT", "Specifies the value of an unsigned pure integer generic vertex attribute.", GLuint.IN("index", vertexAttribIndex), GLint.IN("x", vertexAttribX), GLint.IN("y", vertexAttribY), GLint.IN("z", vertexAttribZ), GLint.IN("w", vertexAttribW)) void("VertexAttribI1ivEXT", "Pointer version of #VertexAttribI1iEXT().", GLuint.IN("index", vertexAttribIndex), Check(1)..const..GLint_p.IN("v", vertexAttribBuffer)) void("VertexAttribI2ivEXT", "Pointer version of #VertexAttribI2iEXT().", GLuint.IN("index", vertexAttribIndex), Check(2)..const..GLint_p.IN("v", vertexAttribBuffer)) void("VertexAttribI3ivEXT", "Pointer version of #VertexAttribI3iEXT().", GLuint.IN("index", vertexAttribIndex), Check(3)..const..GLint_p.IN("v", vertexAttribBuffer)) void("VertexAttribI4ivEXT", "Pointer version of #VertexAttribI4iEXT().", GLuint.IN("index", vertexAttribIndex), Check(4)..const..GLint_p.IN("v", vertexAttribBuffer)) void("VertexAttribI1uivEXT", "Pointer version of #VertexAttribI1uiEXT().", GLuint.IN("index", vertexAttribIndex), Check(1)..const..GLuint_p.IN("v", vertexAttribBuffer)) void("VertexAttribI2uivEXT", "Pointer version of #VertexAttribI2uiEXT().", GLuint.IN("index", vertexAttribIndex), Check(2)..const..GLuint_p.IN("v", vertexAttribBuffer)) void("VertexAttribI3uivEXT", "Pointer version of #VertexAttribI3uiEXT().", GLuint.IN("index", vertexAttribIndex), Check(3)..const..GLuint_p.IN("v", vertexAttribBuffer)) void("VertexAttribI4uivEXT", "Pointer version of #VertexAttribI4uiEXT().", GLuint.IN("index", vertexAttribIndex), Check(4)..const..GLuint_p.IN("v", vertexAttribBuffer)) void("VertexAttribI4bvEXT", "Byte version of #VertexAttribI4ivEXT().", GLuint.IN("index", vertexAttribIndex), Check(4)..const..GLbyte_p.IN("v", vertexAttribBuffer)) void("VertexAttribI4svEXT", "Short version of #VertexAttribI4ivEXT().", GLuint.IN("index", vertexAttribIndex), Check(4)..const..GLshort_p.IN("v", vertexAttribBuffer)) void("VertexAttribI4ubvEXT", "Byte version of #VertexAttribI4uivEXT().", GLuint.IN("index", vertexAttribIndex), Check(4)..const..GLbyte_p.IN("v", vertexAttribBuffer)) void("VertexAttribI4usvEXT", "Short version of #VertexAttribI4uivEXT().", GLuint.IN("index", vertexAttribIndex), Check(4)..const..GLshort_p.IN("v", vertexAttribBuffer)) void( "VertexAttribIPointerEXT", "Specifies the location and organization of a pure integer vertex attribute array.", GLuint.IN("index", vertexAttribIndex), GLint.IN("size", "the number of values per vertex that are stored in the array. The initial value is 4", "1 2 3 4 GL12#BGRA"), GLenum.IN( "type", "the data type of each component in the array", "GL11#BYTE GL11#UNSIGNED_BYTE GL11#SHORT GL11#UNSIGNED_SHORT GL11#INT GL11#UNSIGNED_INT" ), GLsizei.IN( "stride", """ the byte offset between consecutive generic vertex attributes. If stride is 0, the generic vertex attributes are understood to be tightly packed in the array. The initial value is 0. """), MultiType( PointerMapping.DATA_SHORT, PointerMapping.DATA_INT )..ARRAY_BUFFER..const..void_p.IN( "pointer", """ the vertex attribute data or the offset of the first component of the first generic vertex attribute in the array in the data store of the buffer currently bound to the GL15#ARRAY_BUFFER target. The initial value is 0. """ ) ) void( "GetVertexAttribIivEXT", "Returns the value of a pure integer generic vertex attribute parameter.", GLuint.IN("index", vertexAttribIndex), GLenum.IN("pname", "the symbolic name of the vertex attribute parameter to be queried"), Check(4)..ReturnParam..GLint_p.OUT("params", "returns the requested data") ) void( "GetVertexAttribIuivEXT", "Unsigned version of #GetVertexAttribIivEXT().", GLuint.IN("index", vertexAttribIndex), GLenum.IN("pname", "the symbolic name of the vertex attribute parameter to be queried"), Check(4)..ReturnParam..GLuint_p.OUT("params", "returns the requested data") ) void( "GetUniformuivEXT", "", GLuint.IN("program", ""), GLint.IN("location", ""), Check(1)..ReturnParam..GLuint_p.OUT("params", "") ) void( "BindFragDataLocationEXT", "", GLuint.IN("program", ""), GLuint.IN("color", ""), const..GLcharASCII_p.IN("name", "") ) GLint( "GetFragDataLocationEXT", "", GLuint.IN("program", ""), const..GLcharASCII_p.IN("name", "") ) void( "Uniform1uiEXT", "", GLint.IN("location", ""), GLuint.IN("v0", "") ) void( "Uniform2uiEXT", "", GLint.IN("location", ""), GLuint.IN("v0", ""), GLuint.IN("v1", "") ) void( "Uniform3uiEXT", "", GLint.IN("location", ""), GLuint.IN("v0", ""), GLuint.IN("v1", ""), GLuint.IN("v2", "") ) void( "Uniform4uiEXT", "", GLint.IN("location", ""), GLuint.IN("v0", ""), GLuint.IN("v1", ""), GLuint.IN("v2", ""), GLuint.IN("v3", "") ) void( "Uniform1uivEXT", "", GLint.IN("location", ""), AutoSize("value")..GLsizei.IN("count", ""), const..GLuint_p.IN("value", "") ) void( "Uniform2uivEXT", "", GLint.IN("location", ""), AutoSize(2, "value")..GLsizei.IN("count", ""), const..GLuint_p.IN("value", "") ) void( "Uniform3uivEXT", "", GLint.IN("location", ""), AutoSize(3, "value")..GLsizei.IN("count", ""), const..GLuint_p.IN("value", "") ) void( "Uniform4uivEXT", "", GLint.IN("location", ""), AutoSize(4, "value")..GLsizei.IN("count", ""), const..GLuint_p.IN("value", "") ) }
bsd-3-clause
4a603718a07a7457aa20b9e813b26793
44.640777
274
0.716565
3.634536
false
false
false
false
minecraft-dev/MinecraftDev
src/main/kotlin/inspection/IsCancelledInspection.kt
1
1624
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2022 minecraft-dev * * MIT License */ package com.demonwav.mcdev.inspection import com.demonwav.mcdev.facet.MinecraftFacet import com.demonwav.mcdev.util.mapFirstNotNull import com.intellij.openapi.module.ModuleUtilCore import com.intellij.psi.PsiMethodCallExpression import com.siyeh.ig.BaseInspection import com.siyeh.ig.BaseInspectionVisitor import com.siyeh.ig.InspectionGadgetsFix import org.jetbrains.annotations.Nls class IsCancelledInspection : BaseInspection() { @Nls override fun getDisplayName() = "Useless event isCancelled check" override fun getStaticDescription(): String = "Reports useless event cancellation checks" override fun buildErrorString(vararg infos: Any): String { val useless = infos[0] as IsCancelled return useless.errorString } override fun buildFix(vararg infos: Any): InspectionGadgetsFix? { val useless = infos[0] as? IsCancelled return useless?.buildFix } override fun buildVisitor(): BaseInspectionVisitor { return object : BaseInspectionVisitor() { override fun visitMethodCallExpression(expression: PsiMethodCallExpression) { val module = ModuleUtilCore.findModuleForPsiElement(expression) ?: return val instance = MinecraftFacet.getInstance(module) ?: return val useless = instance.modules.mapFirstNotNull { m -> m.checkUselessCancelCheck(expression) } ?: return registerMethodCallError(expression, useless) } } } }
mit
68ae031801572cd2baf95eb46ab0ff94
30.843137
119
0.71798
5.027864
false
false
false
false
codetoart/FolioReader-Android
folioreader/src/main/java/com/folioreader/ui/activity/SearchActivity.kt
2
12402
package com.folioreader.ui.activity import android.app.SearchManager import android.content.Intent import android.graphics.drawable.Drawable import android.net.Uri import android.os.Bundle import android.os.Parcelable import android.text.TextUtils import android.util.Log import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.ImageButton import androidx.appcompat.app.ActionBar import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.SearchView import androidx.appcompat.widget.Toolbar import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import androidx.localbroadcastmanager.content.LocalBroadcastManager import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.folioreader.Config import com.folioreader.R import com.folioreader.model.locators.SearchLocator import com.folioreader.ui.adapter.ListViewType import com.folioreader.ui.adapter.OnItemClickListener import com.folioreader.ui.adapter.SearchAdapter import com.folioreader.ui.view.FolioSearchView import com.folioreader.util.AppUtil import com.folioreader.util.UiUtil import com.folioreader.viewmodels.SearchViewModel import kotlinx.android.synthetic.main.activity_search.* import java.lang.reflect.Field class SearchActivity : AppCompatActivity(), OnItemClickListener { companion object { @JvmField val LOG_TAG: String = SearchActivity::class.java.simpleName const val BUNDLE_SPINE_SIZE = "BUNDLE_SPINE_SIZE" const val BUNDLE_SEARCH_URI = "BUNDLE_SEARCH_URI" const val BUNDLE_SAVE_SEARCH_QUERY = "BUNDLE_SAVE_SEARCH_QUERY" const val BUNDLE_IS_SOFT_KEYBOARD_VISIBLE = "BUNDLE_IS_SOFT_KEYBOARD_VISIBLE" const val BUNDLE_FIRST_VISIBLE_ITEM_INDEX = "BUNDLE_FIRST_VISIBLE_ITEM_INDEX" } enum class ResultCode(val value: Int) { ITEM_SELECTED(2), BACK_BUTTON_PRESSED(3) } private var spineSize: Int = 0 private lateinit var searchUri: Uri private lateinit var searchView: FolioSearchView private lateinit var actionBar: ActionBar private var collapseButtonView: ImageButton? = null private lateinit var linearLayoutManager: LinearLayoutManager private lateinit var searchAdapter: SearchAdapter private lateinit var searchAdapterDataBundle: Bundle private var savedInstanceState: Bundle? = null private var softKeyboardVisible: Boolean = true private lateinit var searchViewModel: SearchViewModel // To get collapseButtonView from toolbar for any click events private val toolbarOnLayoutChangeListener: View.OnLayoutChangeListener = object : View.OnLayoutChangeListener { override fun onLayoutChange( v: View?, left: Int, top: Int, right: Int, bottom: Int, oldLeft: Int, oldTop: Int, oldRight: Int, oldBottom: Int ) { for (i in 0 until toolbar.childCount) { val view: View = toolbar.getChildAt(i) val contentDescription: String? = view.contentDescription as String? if (TextUtils.isEmpty(contentDescription)) continue if (contentDescription == "Collapse") { Log.v(LOG_TAG, "-> initActionBar -> mCollapseButtonView found") collapseButtonView = view as ImageButton collapseButtonView?.setOnClickListener { Log.v(LOG_TAG, "-> onClick -> collapseButtonView") navigateBack() } toolbar.removeOnLayoutChangeListener(this) return } } } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Log.v(LOG_TAG, "-> onCreate") val config: Config = AppUtil.getSavedConfig(this)!! if (config.isNightMode) { setTheme(R.style.FolioNightTheme) } else { setTheme(R.style.FolioDayTheme) } setContentView(R.layout.activity_search) init(config) } private fun init(config: Config) { Log.v(LOG_TAG, "-> init") setSupportActionBar(toolbar) toolbar.addOnLayoutChangeListener(toolbarOnLayoutChangeListener) actionBar = supportActionBar!! actionBar.setDisplayHomeAsUpEnabled(true) actionBar.setDisplayShowTitleEnabled(false) try { val fieldCollapseIcon: Field = Toolbar::class.java.getDeclaredField("mCollapseIcon") fieldCollapseIcon.isAccessible = true val collapseIcon: Drawable = fieldCollapseIcon.get(toolbar) as Drawable UiUtil.setColorIntToDrawable(config.themeColor, collapseIcon) } catch (e: Exception) { Log.e(LOG_TAG, "-> ", e) } spineSize = intent.getIntExtra(BUNDLE_SPINE_SIZE, 0) searchUri = intent.getParcelableExtra(BUNDLE_SEARCH_URI) searchAdapter = SearchAdapter(this) searchAdapter.onItemClickListener = this linearLayoutManager = LinearLayoutManager(this) recyclerView.layoutManager = linearLayoutManager recyclerView.adapter = searchAdapter searchViewModel = ViewModelProviders.of(this).get(SearchViewModel::class.java) searchAdapterDataBundle = searchViewModel.liveAdapterDataBundle.value!! val bundleFromFolioActivity = intent.getBundleExtra(SearchAdapter.DATA_BUNDLE) if (bundleFromFolioActivity != null) { searchViewModel.liveAdapterDataBundle.value = bundleFromFolioActivity searchAdapterDataBundle = bundleFromFolioActivity searchAdapter.changeDataBundle(bundleFromFolioActivity) val position = bundleFromFolioActivity.getInt(BUNDLE_FIRST_VISIBLE_ITEM_INDEX) Log.d(LOG_TAG, "-> onCreate -> scroll to previous position $position") recyclerView.scrollToPosition(position) } searchViewModel.liveAdapterDataBundle.observe(this, Observer<Bundle> { dataBundle -> searchAdapterDataBundle = dataBundle searchAdapter.changeDataBundle(dataBundle) }) } override fun onNewIntent(intent: Intent) { Log.v(LOG_TAG, "-> onNewIntent") if (intent.hasExtra(BUNDLE_SEARCH_URI)) { searchUri = intent.getParcelableExtra(BUNDLE_SEARCH_URI) } else { intent.putExtra(BUNDLE_SEARCH_URI, searchUri) intent.putExtra(BUNDLE_SPINE_SIZE, spineSize) } setIntent(intent) if (Intent.ACTION_SEARCH == intent.action) handleSearch() } private fun handleSearch() { Log.v(LOG_TAG, "-> handleSearch") val query: String = intent.getStringExtra(SearchManager.QUERY) val newDataBundle = Bundle() newDataBundle.putString(ListViewType.KEY, ListViewType.PAGINATION_IN_PROGRESS_VIEW.toString()) newDataBundle.putParcelableArrayList("DATA", ArrayList<SearchLocator>()) searchViewModel.liveAdapterDataBundle.value = newDataBundle searchViewModel.search(spineSize, query) } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) Log.v(LOG_TAG, "-> onSaveInstanceState") outState.putCharSequence(BUNDLE_SAVE_SEARCH_QUERY, searchView.query) outState.putBoolean(BUNDLE_IS_SOFT_KEYBOARD_VISIBLE, softKeyboardVisible) } override fun onRestoreInstanceState(savedInstanceState: Bundle) { super.onRestoreInstanceState(savedInstanceState) Log.v(LOG_TAG, "-> onRestoreInstanceState") this.savedInstanceState = savedInstanceState } private fun navigateBack() { Log.v(LOG_TAG, "-> navigateBack") val intent = Intent() searchAdapterDataBundle.putInt( BUNDLE_FIRST_VISIBLE_ITEM_INDEX, linearLayoutManager.findFirstVisibleItemPosition() ) intent.putExtra(SearchAdapter.DATA_BUNDLE, searchAdapterDataBundle) intent.putExtra(BUNDLE_SAVE_SEARCH_QUERY, searchView.query) setResult(ResultCode.BACK_BUTTON_PRESSED.value, intent) finish() } override fun onBackPressed() { Log.v(LOG_TAG, "-> onBackPressed") } override fun onCreateOptionsMenu(menu: Menu?): Boolean { Log.v(LOG_TAG, "-> onCreateOptionsMenu") menuInflater.inflate(R.menu.menu_search, menu!!) val config: Config = AppUtil.getSavedConfig(applicationContext)!! val itemSearch: MenuItem = menu.findItem(R.id.itemSearch) UiUtil.setColorIntToDrawable(config.themeColor, itemSearch.icon) searchView = itemSearch.actionView as FolioSearchView searchView.init(componentName, config) itemSearch.expandActionView() if (savedInstanceState != null) { searchView.setQuery( savedInstanceState!!.getCharSequence(BUNDLE_SAVE_SEARCH_QUERY), false ) softKeyboardVisible = savedInstanceState!!.getBoolean(BUNDLE_IS_SOFT_KEYBOARD_VISIBLE) if (!softKeyboardVisible) AppUtil.hideKeyboard(this) } else { val searchQuery: CharSequence? = intent.getCharSequenceExtra(BUNDLE_SAVE_SEARCH_QUERY) if (!TextUtils.isEmpty(searchQuery)) { searchView.setQuery(searchQuery, false) AppUtil.hideKeyboard(this) softKeyboardVisible = false } } searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextSubmit(query: String?): Boolean { softKeyboardVisible = false searchView.clearFocus() return false } override fun onQueryTextChange(newText: String?): Boolean { if (TextUtils.isEmpty(newText)) { Log.v(LOG_TAG, "-> onQueryTextChange -> Empty Query") //supportLoaderManager.restartLoader(SEARCH_LOADER, null, this@SearchActivity) searchViewModel.cancelAllSearchCalls() searchViewModel.init() val intent = Intent(FolioActivity.ACTION_SEARCH_CLEAR) LocalBroadcastManager.getInstance(this@SearchActivity).sendBroadcast(intent) } return false } }) itemSearch.setOnActionExpandListener(object : MenuItem.OnActionExpandListener { override fun onMenuItemActionExpand(item: MenuItem?): Boolean { return true } override fun onMenuItemActionCollapse(item: MenuItem?): Boolean { Log.v(LOG_TAG, "-> onMenuItemActionCollapse") navigateBack() return false } }) searchView.setOnQueryTextFocusChangeListener { _, hasFocus -> if (hasFocus) softKeyboardVisible = true } return true } override fun onOptionsItemSelected(item: MenuItem?): Boolean { val itemId = item?.itemId if (itemId == R.id.itemSearch) { Log.v(LOG_TAG, "-> onOptionsItemSelected -> ${item.title}") //onSearchRequested() return true } return super.onOptionsItemSelected(item) } override fun onItemClick( adapter: RecyclerView.Adapter<RecyclerView.ViewHolder>, viewHolder: RecyclerView.ViewHolder, position: Int, id: Long ) { if (adapter is SearchAdapter) { if (viewHolder is SearchAdapter.NormalViewHolder) { Log.v(LOG_TAG, "-> onItemClick -> " + viewHolder.searchLocator) val intent = Intent() searchAdapterDataBundle.putInt( BUNDLE_FIRST_VISIBLE_ITEM_INDEX, linearLayoutManager.findFirstVisibleItemPosition() ) intent.putExtra(SearchAdapter.DATA_BUNDLE, searchAdapterDataBundle) intent.putExtra(FolioActivity.EXTRA_SEARCH_ITEM, viewHolder.searchLocator as Parcelable) intent.putExtra(BUNDLE_SAVE_SEARCH_QUERY, searchView.query) setResult(ResultCode.ITEM_SELECTED.value, intent) finish() } } } }
bsd-3-clause
96363cbdfb78a706fffd1ad2d4246531
37.042945
115
0.661103
5.197821
false
false
false
false
wordpress-mobile/AztecEditor-Android
aztec/src/main/kotlin/org/wordpress/aztec/spans/ParagraphSpan.kt
1
4091
package org.wordpress.aztec.spans import android.graphics.Paint import android.text.Layout import android.text.Spanned import android.text.style.LineHeightSpan import org.wordpress.aztec.AlignmentRendering import org.wordpress.aztec.AztecAttributes import org.wordpress.aztec.AztecTextFormat import org.wordpress.aztec.ITextFormat import org.wordpress.aztec.formatting.BlockFormatter fun createParagraphSpan(nestingLevel: Int, alignmentRendering: AlignmentRendering, attributes: AztecAttributes = AztecAttributes(), paragraphStyle: BlockFormatter.ParagraphStyle = BlockFormatter.ParagraphStyle(0)): IAztecBlockSpan = when (alignmentRendering) { AlignmentRendering.SPAN_LEVEL -> ParagraphSpanAligned(nestingLevel, attributes, null, paragraphStyle) AlignmentRendering.VIEW_LEVEL -> ParagraphSpan(nestingLevel, attributes, paragraphStyle) } fun createParagraphSpan(nestingLevel: Int, align: Layout.Alignment?, attributes: AztecAttributes = AztecAttributes(), paragraphStyle: BlockFormatter.ParagraphStyle = BlockFormatter.ParagraphStyle(0)): IAztecBlockSpan = ParagraphSpanAligned(nestingLevel, attributes, align, paragraphStyle) /** * We need to have two classes for handling alignment at either the Span-level (ParagraphSpanAligned) * or the View-level (ParagraphSpan). IAztecAlignment implements AlignmentSpan, which has a * getAlignment method that returns a non-null Layout.Alignment. The Android system checks for * AlignmentSpans and, if present, overrides the view's gravity with their value. Having a class * that does not implement AlignmentSpan allows the view's gravity to control. These classes should * be created using the createParagraphSpan(...) methods. */ open class ParagraphSpan( override var nestingLevel: Int, override var attributes: AztecAttributes, var paragraphStyle: BlockFormatter.ParagraphStyle = BlockFormatter.ParagraphStyle(0)) : IAztecBlockSpan, LineHeightSpan { private var removeTopPadding = false override fun chooseHeight(text: CharSequence, start: Int, end: Int, spanstartv: Int, lineHeight: Int, fm: Paint.FontMetricsInt) { val spanned = text as Spanned val spanStart = spanned.getSpanStart(this) val spanEnd = spanned.getSpanEnd(this) val previousLineBreak = if (start > 1) { text.substring(start-1, start) == "\n" } else { false } val followingLineBreak = if (end < text.length) { text.substring(end, end + 1) == "\n" } else { false } val isFirstLine = start <= spanStart || previousLineBreak val isLastLine = spanEnd <= end || followingLineBreak if (isFirstLine) { removeTopPadding = true fm.ascent -= paragraphStyle.verticalMargin fm.top -= paragraphStyle.verticalMargin } if (isLastLine) { fm.descent += paragraphStyle.verticalMargin fm.bottom += paragraphStyle.verticalMargin removeTopPadding = false } if (!isFirstLine && !isLastLine && removeTopPadding) { removeTopPadding = false if (fm.ascent + paragraphStyle.verticalMargin < 0) { fm.ascent += paragraphStyle.verticalMargin } if (fm.top + paragraphStyle.verticalMargin < 0) { fm.top += paragraphStyle.verticalMargin } } } override var TAG: String = "p" override var endBeforeBleed: Int = -1 override var startBeforeCollapse: Int = -1 override val textFormat: ITextFormat = AztecTextFormat.FORMAT_PARAGRAPH } class ParagraphSpanAligned( nestingLevel: Int, attributes: AztecAttributes, override var align: Layout.Alignment?, paragraphStyle: BlockFormatter.ParagraphStyle) : ParagraphSpan(nestingLevel, attributes, paragraphStyle), IAztecAlignmentSpan
mpl-2.0
830c1fd6ea66c247179a9e7a810f3da4
43.467391
133
0.680029
5.075682
false
false
false
false
Notifique/Notifique
notifique/src/main/java/com/nathanrassi/notifique/NotifiqueListView.kt
1
16062
package com.nathanrassi.notifique import android.app.PendingIntent import android.content.Context import android.content.pm.PackageManager import android.content.res.Configuration import android.graphics.Canvas import android.graphics.Rect import android.graphics.drawable.ColorDrawable import android.graphics.drawable.Drawable import android.os.Build.VERSION.SDK_INT import android.os.Bundle import android.os.Parcelable import android.text.format.DateFormat import android.util.AttributeSet import android.view.LayoutInflater import android.view.MotionEvent import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.LinearLayout import android.widget.TextView import androidx.appcompat.content.res.AppCompatResources import androidx.paging.InvalidatingPagingSourceFactory import androidx.paging.Pager import androidx.paging.PagingConfig import androidx.paging.PagingDataAdapter import androidx.paging.cachedIn import androidx.recyclerview.selection.ItemDetailsLookup import androidx.recyclerview.selection.ItemKeyProvider import androidx.recyclerview.selection.MutableSelection import androidx.recyclerview.selection.SelectionTracker import androidx.recyclerview.selection.StorageStrategy import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.ItemTouchHelper.LEFT import androidx.recyclerview.widget.ItemTouchHelper.RIGHT import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView.ItemDecoration import androidx.recyclerview.widget.RecyclerView.State import com.nathanrassi.notifique.Notifique.CREATOR.asNotifique import java.util.Date import java.util.Locale import java.util.TimeZone import javax.inject.Inject import kotlin.math.roundToInt import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.MainScope import kotlinx.coroutines.cancel import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.launch import kotlinx.coroutines.withContext internal class NotifiqueListView( context: Context, attributeSet: AttributeSet ) : RecyclerView(context, attributeSet) { @Inject lateinit var savedNotifiqueQueries: SavedNotifiqueQueries lateinit var onSelectionStateChangedListener: OnSelectionStateChangedListener private var deleteIcon = AppCompatResources.getDrawable(context, R.drawable.toolbar_delete)!! private val listAdapter: Adapter private val selectionTracker: SelectionTracker<Long> private val swipeBackground = ColorDrawable(context.getColor(R.color.list_item_swipe_background)) private val pagingSourceFactory: InvalidatingPagingSourceFactory<Int, Notifique> private var searchText: String? = null // Consider "now" check from time of this list view's creation. private val dateFormatter = DateFormatter( TimeZone.getDefault(), resources.configuration.primaryLocale, DateFormat.is24HourFormat(context) ) private lateinit var scope: CoroutineScope interface OnSelectionStateChangedListener { fun onSelectionStateChanged(selected: Boolean) } fun deleteSelected() { val selection = MutableSelection<Long>().also { selectionTracker.copySelection(it) } GlobalScope.launch { savedNotifiqueQueries.transaction { for (id in selection.iterator()) { savedNotifiqueQueries.delete(id) } } withContext(Dispatchers.Main) { selectionTracker.clearSelection() } } } fun deselectAll() { selectionTracker.clearSelection() } init { context.appComponent.inject(this) val inflater = LayoutInflater.from(context) layoutManager = LinearLayoutManager(context) listAdapter = Adapter(inflater, dateFormatter).apply { registerAdapterDataObserver(object : AdapterDataObserver() { override fun onItemRangeInserted( positionStart: Int, itemCount: Int ) { if (!canScrollVertically(-1) && positionStart == 0) { scrollToPosition(0) } } }) } adapter = listAdapter addItemDecoration( DividerItemDecoration( AppCompatResources.getDrawable( context, R.drawable.divider )!! ) ) val queryProvider = { limit: Long, offset: Long -> val searchText = searchText if (searchText == null) { savedNotifiqueQueries.notifiques(limit, offset) } else { savedNotifiqueQueries.notifiquesSearch(searchText, limit, offset) } } val countQueryProvider = { val searchText = searchText if (searchText == null) { savedNotifiqueQueries.count() } else { savedNotifiqueQueries.countSearch(searchText) } } val transacter = savedNotifiqueQueries val notificationContentIntents = mapOf<String, PendingIntent>() pagingSourceFactory = InvalidatingPagingSourceFactory( AdaptingPagingSourceFactory( LegacyQueryDataSourceFactory( queryProvider, countQueryProvider, transacter ).asPagingSourceFactory(Dispatchers.IO) ) { it.asNotifique(notificationContentIntents) } ) selectionTracker = SelectionTracker.Builder( "list-selection-id", this, object : ItemKeyProvider<Long>(SCOPE_MAPPED) { override fun getKey(position: Int): Long? { return listAdapter.getNotifiqueId(position) } override fun getPosition(key: Long): Int { val list = listAdapter.snapshot() val index = list.indexOfFirst { // Notifique object is null during deletion. it != null && key == it.savedId } return if (index == -1) NO_POSITION else index } }, object : ItemDetailsLookup<Long>() { override fun getItemDetails(e: MotionEvent): ItemDetails<Long>? { val childView = findChildViewUnder(e.x, e.y) ?: return null val viewHolder = getChildViewHolder(childView) val position = viewHolder.bindingAdapterPosition return object : ItemDetails<Long>() { override fun getSelectionKey(): Long? { return listAdapter.getNotifiqueId(position) } override fun getPosition(): Int { return position } } } }, StorageStrategy.createLongStorage() ) .build() selectionTracker.addObserver(object : SelectionTracker.SelectionObserver<Long>() { var hasSelection = false override fun onSelectionChanged() { if (selectionTracker.hasSelection()) { if (!hasSelection) { hasSelection = true onSelectionStateChangedListener.onSelectionStateChanged(true) } } else if (hasSelection) { hasSelection = false onSelectionStateChangedListener.onSelectionStateChanged(false) } } }) listAdapter.selectionTracker = selectionTracker ItemTouchHelper(object : ItemTouchHelper.SimpleCallback(0, LEFT or RIGHT) { override fun getSwipeDirs( recyclerView: RecyclerView, viewHolder: ViewHolder ): Int { if (listAdapter.getNotifiqueId(viewHolder.bindingAdapterPosition) == null) { // Placeholder. return 0 } return LEFT or RIGHT } override fun onMove( recyclerView: RecyclerView, viewHolder: ViewHolder, target: ViewHolder ): Boolean { return false } override fun onSwiped( viewHolder: ViewHolder, direction: Int ) { GlobalScope.launch { savedNotifiqueQueries.delete(listAdapter.getNotifiqueId(viewHolder.bindingAdapterPosition)!!) } } override fun onChildDraw( c: Canvas, recyclerView: RecyclerView, viewHolder: ViewHolder, dX: Float, dY: Float, actionState: Int, isCurrentlyActive: Boolean ) { val itemView = viewHolder.itemView val iconMargin = (itemView.height - deleteIcon.intrinsicHeight) / 2 if (dX > 0) { swipeBackground.setBounds(itemView.left, itemView.top, dX.toInt(), itemView.bottom) deleteIcon.setBounds( itemView.left + (iconMargin / 2), itemView.top + iconMargin, itemView.left + (iconMargin / 2) + deleteIcon.intrinsicWidth, itemView.bottom - iconMargin ) } else { swipeBackground.setBounds( itemView.right + dX.toInt(), itemView.top, itemView.right, itemView.bottom ) deleteIcon.setBounds( itemView.right - (iconMargin / 2) - deleteIcon.intrinsicWidth, itemView.top + iconMargin, itemView.right - (iconMargin / 2), itemView.bottom - iconMargin ) } swipeBackground.draw(c) if (dX > 0) { c.clipRect(itemView.left, itemView.top, dX.toInt(), itemView.bottom) } else { c.clipRect(itemView.right + dX.toInt(), itemView.top, itemView.right, itemView.bottom) } deleteIcon.draw(c) super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive) } }).apply { attachToRecyclerView(this@NotifiqueListView) } } override fun onAttachedToWindow() { super.onAttachedToWindow() scope = MainScope() val flow = Pager( PagingConfig( pageSize = 15, enablePlaceholders = true ), initialKey = null, pagingSourceFactory ).flow.cachedIn(scope) scope.launch(Dispatchers.IO) { flow.collectLatest { listAdapter.submitData(it) } } } override fun onDetachedFromWindow() { super.onDetachedFromWindow() // Invalidate to make the PagingSource remove the query listener from the query. pagingSourceFactory.invalidate() scope.cancel() } override fun onSaveInstanceState(): Parcelable { val savedState = super.onSaveInstanceState() return Bundle(2).apply { putParcelable("savedState", savedState) selectionTracker.onSaveInstanceState(this) } } override fun onRestoreInstanceState(state: Parcelable) { super.onRestoreInstanceState((state as Bundle).getParcelable("savedState")) selectionTracker.onRestoreInstanceState(state) } private val Configuration.primaryLocale: Locale get() = if (SDK_INT >= 24) { locales[0]!! } else { @Suppress("Deprecation") locale } private class ItemView( context: Context, attributeSet: AttributeSet ) : LinearLayout(context, attributeSet) { private val appName: TextView private val timestamp: TextView private val title: TextView private val message: TextView private val appPicture: ImageView private val date = Date() init { orientation = VERTICAL foreground = AppCompatResources.getDrawable(context, R.drawable.item_view_foreground) val inflater = LayoutInflater.from(context) inflater.inflate(R.layout.list_item_children, this, true) appName = findViewById(R.id.app_name) timestamp = findViewById(R.id.timestamp) title = findViewById(R.id.title) message = findViewById(R.id.message) appPicture = findViewById(R.id.icon_picture) } fun setNotifique( notifique: Notifique, dateFormatter: DateFormatter ) { appName.visibility = VISIBLE timestamp.visibility = VISIBLE title.visibility = VISIBLE message.visibility = VISIBLE appPicture.visibility = VISIBLE appName.text = notifique.app timestamp.text = dateFormatter.format(date.apply { time = notifique.timestamp }) title.text = notifique.title message.text = notifique.message try { appPicture.setImageDrawable( context.packageManager.getApplicationIcon( notifique.packageName ) ) } catch (e: PackageManager.NameNotFoundException) { appPicture.setImageResource(R.drawable.toolbar_delete) } } fun setPlaceholder() { appName.visibility = INVISIBLE timestamp.visibility = INVISIBLE title.visibility = INVISIBLE message.visibility = INVISIBLE appPicture.visibility = INVISIBLE } } private class Adapter( private val inflater: LayoutInflater, private val dateFormatter: DateFormatter ) : PagingDataAdapter<Notifique, Adapter.ViewHolder>( NotifiqueDiffCallback ) { lateinit var selectionTracker: SelectionTracker<Long> override fun onCreateViewHolder( parent: ViewGroup, viewType: Int ) = ViewHolder( inflater.inflate(R.layout.list_item, parent, false) as ItemView ) fun getNotifiqueId(position: Int): Long? { return getItem(position)?.savedId } override fun onBindViewHolder( holder: ViewHolder, position: Int ) { val notifique = getItem(position) if (notifique == null) { holder.root.setPlaceholder() holder.root.isSelected = false } else { holder.root.setNotifique(notifique, dateFormatter) holder.root.isSelected = selectionTracker.isSelected(notifique.savedId) } } override fun onBindViewHolder( holder: ViewHolder, position: Int, payloads: List<Any> ) { if (payloads.isEmpty()) { onBindViewHolder(holder, position) return } if (payloads.contains(SelectionTracker.SELECTION_CHANGED_MARKER)) { val notifique = getItem(position)!! holder.root.isSelected = selectionTracker.isSelected(notifique.savedId) } // The paging library sometimes inserts DiffingChangePayload values into payloads. } private class ViewHolder(val root: ItemView) : RecyclerView.ViewHolder(root) object NotifiqueDiffCallback : DiffUtil.ItemCallback<Notifique>() { override fun areItemsTheSame( oldItem: Notifique, newItem: Notifique ) = oldItem.savedId == newItem.savedId override fun areContentsTheSame( oldItem: Notifique, newItem: Notifique ) = oldItem == newItem } } } /** * Copied from [androidx.recyclerview.widget.DividerItemDecoration]. * <p>Shows the divider under every item except the last one. */ private class DividerItemDecoration( private val divider: Drawable ) : ItemDecoration() { private val bounds = Rect() override fun onDraw( c: Canvas, parent: RecyclerView, state: State ) { drawVertical(c, parent) } private fun drawVertical( canvas: Canvas, parent: RecyclerView ) { canvas.save() val left: Int val right: Int if (parent.clipToPadding) { left = parent.paddingLeft right = parent.width - parent.paddingRight canvas.clipRect( left, parent.paddingTop, right, parent.height - parent.paddingBottom ) } else { left = 0 right = parent.width } val childCount = parent.childCount for (i in 0 until childCount) { val child = parent.getChildAt(i) if (parent.getChildAdapterPosition(child) != parent.adapter!!.itemCount - 1) { parent.getDecoratedBoundsWithMargins(child, bounds) val bottom = bounds.bottom + child.translationY.roundToInt() val top = bottom - divider.intrinsicHeight divider.setBounds(left, top, right, bottom) divider.draw(canvas) } } canvas.restore() } override fun getItemOffsets( outRect: Rect, view: View, parent: RecyclerView, state: State ) { val dividerHeight = if (parent.getChildAdapterPosition( view ) == parent.adapter!!.itemCount - 1 ) 0 else divider.intrinsicHeight outRect[0, 0, 0] = dividerHeight } }
apache-2.0
2ae7b6a62a7187b719fc49f767f57c5b
30.067698
103
0.678122
4.833584
false
false
false
false
ligee/kotlin-jupyter
jupyter-lib/shared-compiler/src/main/kotlin/org/jetbrains/kotlinx/jupyter/compiler/util/serializedCompiledScript.kt
1
904
package org.jetbrains.kotlinx.jupyter.compiler.util import kotlinx.serialization.Serializable typealias Classpath = List<String> @Serializable data class SerializedCompiledScript( val fileName: String, val data: String, val isImplicitReceiver: Boolean, ) @Serializable data class SerializedCompiledScriptsData( val scripts: List<SerializedCompiledScript> ) { companion object { val EMPTY = SerializedCompiledScriptsData(emptyList()) } } @Serializable class EvaluatedSnippetMetadata( val newClasspath: Classpath = emptyList(), val newSources: Classpath = emptyList(), val compiledData: SerializedCompiledScriptsData = SerializedCompiledScriptsData.EMPTY, val newImports: List<String> = emptyList(), val evaluatedVariablesState: Map<String, String?> = mutableMapOf() ) { companion object { val EMPTY = EvaluatedSnippetMetadata() } }
apache-2.0
7227a85c5c50b4e228814260d9101679
25.588235
90
0.75
4.635897
false
false
false
false
HabitRPG/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/receivers/LocalNotificationActionReceiver.kt
1
5736
package com.habitrpg.android.habitica.receivers import android.app.NotificationManager import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.text.Spannable import android.widget.Toast import androidx.core.app.NotificationManagerCompat import androidx.core.app.RemoteInput import com.habitrpg.android.habitica.HabiticaBaseApplication import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.data.ApiClient import com.habitrpg.android.habitica.data.SocialRepository import com.habitrpg.android.habitica.data.TaskRepository import com.habitrpg.android.habitica.data.UserRepository import com.habitrpg.android.habitica.helpers.ExceptionHandler import com.habitrpg.android.habitica.interactors.NotifyUserUseCase import com.habitrpg.android.habitica.models.user.User import kotlinx.coroutines.MainScope import kotlinx.coroutines.launch import javax.inject.Inject class LocalNotificationActionReceiver : BroadcastReceiver() { @Inject lateinit var userRepository: UserRepository @Inject lateinit var socialRepository: SocialRepository @Inject lateinit var taskRepository: TaskRepository @Inject lateinit var apiClient: ApiClient private var user: User? = null private val groupID: String? get() = intent?.extras?.getString("groupID") private val senderID: String? get() = intent?.extras?.getString("senderID") private val taskID: String? get() = intent?.extras?.getString("taskID") private var context: Context? = null private var intent: Intent? = null override fun onReceive(context: Context, intent: Intent) { HabiticaBaseApplication.userComponent?.inject(this) this.intent = intent this.context = context handleLocalNotificationAction(intent.action) } private fun handleLocalNotificationAction(action: String?) { val notificationManager = this.context?.getSystemService(Context.NOTIFICATION_SERVICE) as? NotificationManager notificationManager?.cancel(intent?.extras?.getInt("NOTIFICATION_ID") ?: -1) when (action) { context?.getString(R.string.accept_party_invite) -> { groupID?.let { MainScope().launch(ExceptionHandler.coroutine()) { socialRepository.joinGroup(it) } } } context?.getString(R.string.reject_party_invite) -> { groupID?.let { socialRepository.rejectGroupInvite(it) .subscribe({ }, ExceptionHandler.rx()) } } context?.getString(R.string.accept_quest_invite) -> { socialRepository.acceptQuest(user).subscribe({ }, ExceptionHandler.rx()) } context?.getString(R.string.reject_quest_invite) -> { socialRepository.rejectQuest(user).subscribe({ }, ExceptionHandler.rx()) } context?.getString(R.string.accept_guild_invite) -> { groupID?.let { MainScope().launch(ExceptionHandler.coroutine()) { socialRepository.joinGroup(it) } } } context?.getString(R.string.reject_guild_invite) -> { groupID?.let { socialRepository.rejectGroupInvite(it) .subscribe({ }, ExceptionHandler.rx()) } } context?.getString(R.string.group_message_reply) -> { groupID?.let { getMessageText(context?.getString(R.string.group_message_reply))?.let { message -> socialRepository.postGroupChat(it, message).subscribe( { context?.let { c -> NotificationManagerCompat.from(c).cancel(it.hashCode()) } }, ExceptionHandler.rx() ) } } } context?.getString(R.string.inbox_message_reply) -> { senderID?.let { getMessageText(context?.getString(R.string.inbox_message_reply))?.let { message -> MainScope().launch(ExceptionHandler.coroutine()) { socialRepository.postPrivateMessage(it, message) } } } } context?.getString(R.string.complete_task_action) -> { taskID?.let { taskRepository.taskChecked(null, it, up = true, force = false) { }.subscribe({ val pair = NotifyUserUseCase.getNotificationAndAddStatsToUserAsText( it.experienceDelta, it.healthDelta, it.goldDelta, it.manaDelta ) showToast(pair.first) }, ExceptionHandler.rx()) } } } } private fun showToast(text: Spannable) { val toast = Toast.makeText(context, text, Toast.LENGTH_LONG) toast.show() } private fun getMessageText(key: String?): String? { return intent?.let { RemoteInput.getResultsFromIntent(it)?.getCharSequence(key)?.toString() } } }
gpl-3.0
3d2272e6e9eb142811e24792a139ca0b
39.266187
102
0.560844
5.431818
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/remote/catalog/deserializers/CatalogBlockDeserializer.kt
2
1562
package org.stepik.android.remote.catalog.deserializers import com.google.gson.JsonDeserializationContext import com.google.gson.JsonDeserializer import com.google.gson.JsonElement import com.google.gson.JsonParseException import com.google.gson.JsonObject import org.stepik.android.cache.catalog.mapper.CatalogBlockContentSerializer import org.stepik.android.domain.catalog.model.CatalogBlock import java.lang.reflect.Type class CatalogBlockDeserializer : JsonDeserializer<CatalogBlock> { private val catalogBlockContentSerializer = CatalogBlockContentSerializer() @Throws(JsonParseException::class) override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): CatalogBlock { val jsonObject = json.asJsonObject val toMapperJson = JsonObject() val kind = jsonObject.get("kind") val contentField = jsonObject.get("content") toMapperJson.add("kind", kind) toMapperJson.add("content", contentField) val content = catalogBlockContentSerializer.mapToDomainEntity(toMapperJson.toString()) return CatalogBlock( id = jsonObject["id"].asLong, position = jsonObject["position"].asInt, title = jsonObject["title"].asString, description = jsonObject["description"].asString, language = jsonObject["language"].asString, appearance = jsonObject["appearance"].asString, isTitleVisible = jsonObject["is_title_visible"].asBoolean, content = content ) } }
apache-2.0
3836c6cdb2092d27e8c64485296b3463
41.243243
115
0.725992
4.990415
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/presentation/in_app_web_view/InAppWebViewPresenter.kt
2
2083
package org.stepik.android.presentation.in_app_web_view import io.reactivex.Scheduler import io.reactivex.rxkotlin.plusAssign import io.reactivex.rxkotlin.subscribeBy import org.stepic.droid.di.qualifiers.BackgroundScheduler import org.stepic.droid.di.qualifiers.MainScheduler import org.stepik.android.domain.magic_links.interactor.MagicLinkInteractor import ru.nobird.android.presentation.base.PresenterBase import javax.inject.Inject class InAppWebViewPresenter @Inject constructor( private val magicLinkInteractor: MagicLinkInteractor, @BackgroundScheduler private val backgroundScheduler: Scheduler, @MainScheduler private val mainScheduler: Scheduler ) : PresenterBase<InAppWebViewView>() { private var state: InAppWebViewView.State = InAppWebViewView.State.Idle set(value) { field = value view?.setState(value) } override fun attachView(view: InAppWebViewView) { super.attachView(view) view.setState(state) } fun onData(url: String, isProvideAuth: Boolean, forceUpdate: Boolean = false) { if (state != InAppWebViewView.State.Idle && !(state is InAppWebViewView.State.Error && forceUpdate)) { return } if (isProvideAuth) { compositeDisposable += magicLinkInteractor .createMagicLink(url) .observeOn(mainScheduler) .subscribeOn(backgroundScheduler) .subscribeBy( onSuccess = { state = InAppWebViewView.State.WebLoading(it.url) }, onError = { state = InAppWebViewView.State.Error } ) } else { state = InAppWebViewView.State.WebLoading(url) } } fun onSuccess() { if (state !is InAppWebViewView.State.WebLoading) { return } state = InAppWebViewView.State.Success } fun onError() { if (state !is InAppWebViewView.State.WebLoading) { return } state = InAppWebViewView.State.Error } }
apache-2.0
fcfea096cdd132deb2d7944444f4e24a
30.575758
86
0.653385
4.670404
false
false
false
false
NerdNumber9/TachiyomiEH
app/src/main/java/eu/kanade/tachiyomi/util/DiskUtil.kt
2
3612
package eu.kanade.tachiyomi.util import android.content.Context import android.content.Intent import android.net.Uri import android.os.Build import android.os.Environment import android.support.v4.content.ContextCompat import android.support.v4.os.EnvironmentCompat import java.io.File object DiskUtil { fun hashKeyForDisk(key: String): String { return Hash.md5(key) } fun getDirectorySize(f: File): Long { var size: Long = 0 if (f.isDirectory) { for (file in f.listFiles()) { size += getDirectorySize(file) } } else { size = f.length() } return size } /** * Returns the root folders of all the available external storages. */ fun getExternalStorages(context: Context): Collection<File> { val directories = mutableSetOf<File>() directories += ContextCompat.getExternalFilesDirs(context, null) .filterNotNull() .mapNotNull { val file = File(it.absolutePath.substringBefore("/Android/")) val state = EnvironmentCompat.getStorageState(file) if (state == Environment.MEDIA_MOUNTED || state == Environment.MEDIA_MOUNTED_READ_ONLY) { file } else { null } } if (Build.VERSION.SDK_INT < 21) { val extStorages = System.getenv("SECONDARY_STORAGE") if (extStorages != null) { directories += extStorages.split(":").map(::File) } } return directories } /** * Scans the given file so that it can be shown in gallery apps, for example. */ fun scanMedia(context: Context, file: File) { scanMedia(context, Uri.fromFile(file)) } /** * Scans the given file so that it can be shown in gallery apps, for example. */ fun scanMedia(context: Context, uri: Uri) { val action = if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { Intent.ACTION_MEDIA_MOUNTED } else { Intent.ACTION_MEDIA_SCANNER_SCAN_FILE } val mediaScanIntent = Intent(action) mediaScanIntent.data = uri context.sendBroadcast(mediaScanIntent) } /** * Mutate the given filename to make it valid for a FAT filesystem, * replacing any invalid characters with "_". This method doesn't allow hidden files (starting * with a dot), but you can manually add it later. */ fun buildValidFilename(origName: String): String { val name = origName.trim('.', ' ') if (name.isNullOrEmpty()) { return "(invalid)" } val sb = StringBuilder(name.length) name.forEach { c -> if (isValidFatFilenameChar(c)) { sb.append(c) } else { sb.append('_') } } // Even though vfat allows 255 UCS-2 chars, we might eventually write to // ext4 through a FUSE layer, so use that limit minus 15 reserved characters. return sb.toString().take(240) } /** * Returns true if the given character is a valid filename character, false otherwise. */ private fun isValidFatFilenameChar(c: Char): Boolean { if (0x00.toChar() <= c && c <= 0x1f.toChar()) { return false } return when (c) { '"', '*', '/', ':', '<', '>', '?', '\\', '|', 0x7f.toChar() -> false else -> true } } }
apache-2.0
edc47ce1486793d489f0329d9b65cfdd
30.684211
109
0.557309
4.503741
false
false
false
false
Commit451/GitLabAndroid
app/src/main/java/com/commit451/gitlab/activity/ProjectActivity.kt
2
9558
package com.commit451.gitlab.activity import android.app.Activity import android.content.ClipData import android.content.ClipboardManager import android.content.Context import android.content.Intent import android.net.Uri import android.os.Bundle import android.view.View import android.widget.Toast import androidx.appcompat.widget.Toolbar import com.commit451.addendum.extraOrNull import com.commit451.alakazam.fadeOut import com.commit451.gitlab.App import com.commit451.gitlab.R import com.commit451.gitlab.adapter.ProjectPagerAdapter import com.commit451.gitlab.data.Prefs import com.commit451.gitlab.event.ProjectReloadEvent import com.commit451.gitlab.extension.with import com.commit451.gitlab.fragment.BaseFragment import com.commit451.gitlab.model.Ref import com.commit451.gitlab.model.api.Project import com.commit451.gitlab.navigation.DeepLinker import com.commit451.gitlab.navigation.Navigator import com.commit451.gitlab.util.IntentUtil import com.google.android.material.snackbar.Snackbar import io.reactivex.rxjava3.core.Single import kotlinx.android.synthetic.main.activity_project.* import kotlinx.android.synthetic.main.progress_fullscreen.* import timber.log.Timber class ProjectActivity : BaseActivity() { companion object { private const val EXTRA_PROJECT = "extra_project" private const val EXTRA_PROJECT_ID = "extra_project_id" private const val EXTRA_PROJECT_NAMESPACE = "extra_project_namespace" private const val EXTRA_PROJECT_NAME = "extra_project_name" private const val EXTRA_PROJECT_SELECTION = "extra_project_selection" private const val STATE_REF = "ref" private const val STATE_PROJECT = "project" private const val REQUEST_BRANCH_OR_TAG = 1 fun newIntent(context: Context, project: Project): Intent { val intent = Intent(context, ProjectActivity::class.java) intent.putExtra(EXTRA_PROJECT, project) return intent } fun newIntent(context: Context, projectId: String): Intent { val intent = Intent(context, ProjectActivity::class.java) intent.putExtra(EXTRA_PROJECT_ID, projectId) return intent } fun newIntent(context: Context, projectNamespace: String, projectName: String, projectSelection: DeepLinker.ProjectSelection): Intent { val intent = Intent(context, ProjectActivity::class.java) intent.putExtra(EXTRA_PROJECT_NAMESPACE, projectNamespace) intent.putExtra(EXTRA_PROJECT_NAME, projectName) intent.putExtra(EXTRA_PROJECT_SELECTION, projectSelection) return intent } } var project: Project? = null private var ref: Ref? = null private var adapter: ProjectPagerAdapter? = null private val projectSelection by extraOrNull<DeepLinker.ProjectSelection>(EXTRA_PROJECT_SELECTION) private val onMenuItemClickListener = Toolbar.OnMenuItemClickListener { item -> when (item.itemId) { R.id.action_branch -> { if (project != null) { Navigator.navigateToPickBranchOrTag(this@ProjectActivity, project!!.id, ref, REQUEST_BRANCH_OR_TAG) } return@OnMenuItemClickListener true } R.id.action_share -> { if (project != null) { IntentUtil.share(root, Uri.parse(project!!.webUrl)) } return@OnMenuItemClickListener true } R.id.action_copy_git_https -> { val url = project?.httpUrlToRepo if (url == null) { Toast.makeText(this@ProjectActivity, R.string.failed_to_copy_to_clipboard, Toast.LENGTH_SHORT) .show() } else { copyToClipboard(url) } return@OnMenuItemClickListener true } R.id.action_copy_git_ssh -> { val url = project?.sshUrlToRepo if (url == null) { Toast.makeText(this@ProjectActivity, R.string.failed_to_copy_to_clipboard, Toast.LENGTH_SHORT) .show() } else { copyToClipboard(url) } return@OnMenuItemClickListener true } } false } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Prefs.startingView = Prefs.STARTING_VIEW_PROJECTS setContentView(R.layout.activity_project) var project: Project? = intent.getParcelableExtra(EXTRA_PROJECT) if (savedInstanceState != null) { project = savedInstanceState.getParcelable(STATE_PROJECT) ref = savedInstanceState.getParcelable(STATE_REF) } toolbar.setNavigationIcon(R.drawable.ic_back_24dp) toolbar.setNavigationOnClickListener { finish() } toolbar.inflateMenu(R.menu.menu_project) toolbar.setOnMenuItemClickListener(onMenuItemClickListener) if (project == null) { val projectId = intent.getStringExtra(EXTRA_PROJECT_ID) val projectNamespace = intent.getStringExtra(EXTRA_PROJECT_NAMESPACE) when { projectId != null -> { loadProject(projectId) } projectNamespace != null -> { val projectName = intent.getStringExtra(EXTRA_PROJECT_NAME)!! loadProject(projectNamespace, projectName) } else -> { throw IllegalStateException("You did something wrong and now we don't know what project to load. :(") } } } else { bindProject(project) } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) when (requestCode) { REQUEST_BRANCH_OR_TAG -> if (resultCode == Activity.RESULT_OK) { ref = data?.getParcelableExtra(PickBranchOrTagActivity.EXTRA_REF) broadcastLoad() } } } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putParcelable(STATE_REF, ref) outState.putParcelable(STATE_PROJECT, project) } override fun onBackPressed() { val fragment = supportFragmentManager.findFragmentByTag("android:switcher:" + R.id.viewPager + ":" + viewPager.currentItem) if (fragment is BaseFragment) { if (fragment.onBackPressed()) { return } } super.onBackPressed() } override fun hasBrowsableLinks(): Boolean { return true } override fun onNewIntent(intent: Intent?) { super.onNewIntent(intent) val selection = intent?.getSerializableExtra(EXTRA_PROJECT_SELECTION) as? DeepLinker.ProjectSelection selection?.let { val index = adapter?.indexForSelection(it) if (index != null) { viewPager.setCurrentItem(index, false) } } } private fun loadProject(projectId: String) { showProgress() loadProject(App.get().gitLab.getProject(projectId)) } private fun loadProject(projectNamespace: String, projectName: String) { showProgress() loadProject(App.get().gitLab.getProject(projectNamespace, projectName)) } private fun loadProject(observable: Single<Project>) { observable.with(this) .subscribe({ fullscreenProgress.fadeOut() bindProject(it) }, { Timber.e(it) fullscreenProgress.fadeOut() Snackbar.make(root, getString(R.string.connection_error), Snackbar.LENGTH_INDEFINITE) .show() }) } private fun showProgress() { fullscreenProgress.alpha = 0.0f fullscreenProgress.visibility = View.VISIBLE fullscreenProgress.animate().alpha(1.0f) } private fun broadcastLoad() { App.bus().post(ProjectReloadEvent(project!!, ref!!.ref!!)) } fun getRefRef(): String? { if (ref == null) { return null } return ref!!.ref } private fun bindProject(project: Project) { this.project = project if (ref == null) { ref = Ref(Ref.TYPE_BRANCH, project.defaultBranch) } toolbar.title = project.name toolbar.subtitle = project.namespace?.name setupTabs() } private fun setupTabs() { val adapter = ProjectPagerAdapter(this, supportFragmentManager) this.adapter = adapter viewPager.adapter = adapter tabLayout.setupWithViewPager(viewPager) projectSelection?.let { val index = adapter.indexForSelection(it) viewPager.setCurrentItem(index, false) } } private fun copyToClipboard(url: String) { val clipboard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager // Creates a new text clip to put on the clipboard val clip = ClipData.newPlainText(project!!.name, url) clipboard.setPrimaryClip(clip) Snackbar.make(root, R.string.copied_to_clipboard, Snackbar.LENGTH_SHORT) .show() } }
apache-2.0
f3baa93f4ec9d32998b2a9085051ea05
35.62069
143
0.622829
4.891505
false
false
false
false
savvasdalkitsis/gameframe
control/src/main/java/com/savvasdalkitsis/gameframe/feature/control/view/ControlFragment.kt
1
6222
/** * Copyright 2017 Savvas Dalkitsis * 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. * * 'Game Frame' is a registered trademark of LEDSEQ */ package com.savvasdalkitsis.gameframe.feature.control.view import android.os.Bundle import android.support.annotation.ArrayRes import android.support.design.widget.FloatingActionButton import android.util.Log import android.view.View import android.widget.Adapter import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.SeekBar import com.savvasdalkitsis.gameframe.feature.control.R import com.savvasdalkitsis.gameframe.feature.control.injector.ControlInjector import com.savvasdalkitsis.gameframe.feature.control.presenter.ControlPresenter import com.savvasdalkitsis.gameframe.feature.device.model.* import com.savvasdalkitsis.gameframe.feature.message.Snackbars import com.savvasdalkitsis.gameframe.feature.networking.model.IpAddress import com.savvasdalkitsis.gameframe.infra.android.BaseFragment import com.savvasdalkitsis.gameframe.infra.android.FragmentSelectedListener import com.savvasdalkitsis.gameframe.kotlin.gone import com.savvasdalkitsis.gameframe.kotlin.visible import kotlinx.android.synthetic.main.fragment_control.* class ControlFragment : BaseFragment<ControlView, ControlPresenter>(), ControlView, FragmentSelectedListener { override val presenter = ControlInjector.controlPresenter() override val view = this private lateinit var fab: FloatingActionButton private val coordinator: View get() = activity!!.findViewById(R.id.view_coordinator) override val layoutId: Int get() = R.layout.fragment_control override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) fab = activity!!.findViewById(R.id.view_fab_control) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) view_brightness.setOnSeekBarChangeListener(BrightnessChangedListener()) view_playback_mode.adapter = adapter(R.array.playback_mode) view_cycle_interval.adapter = adapter(R.array.cycle_interval) view_display_mode.adapter = adapter(R.array.display_mode) view_clock_face.adapter = adapter(R.array.clock_face) view_menu.setOnClickListener { presenter.menu() } view_next.setOnClickListener { presenter.next() } view_control_setup.setOnClickListener { presenter.setup() } view_brightness_low.setOnClickListener { view_brightness.incrementProgressBy(-1) } view_brightness_high.setOnClickListener { view_brightness.incrementProgressBy(1) } view_playback_mode.onItemSelected { position -> presenter.changePlaybackMode(PlaybackMode.from(position)) } view_cycle_interval.onItemSelected { position -> presenter.changeCycleInterval(CycleInterval.from(position)) } view_display_mode.onItemSelected { position -> presenter.changeDisplayMode(DisplayMode.from(position)) } view_clock_face.onItemSelected { position -> presenter.changeClockFace(ClockFace.from(position)) } } override fun onResume() { super.onResume() if (isVisible) { presenter.loadIpAddress() } } override fun onFragmentSelected() { presenter.loadIpAddress() } override fun onFragmentUnselected() { fab.gone() } override fun operationSuccess() = Snackbars.success(coordinator, R.string.success) override fun operationFailure(e: Throwable) { Log.e(ControlFragment::class.java.name, "Operation failure", e) Snackbars.error(coordinator, R.string.operation_failed) } override fun wifiNotEnabledError(e: Throwable) { Log.e(ControlFragment::class.java.name, "Operation failure", e) Snackbars.actionError(coordinator, R.string.wifi_not_enabled, R.string.enable) { presenter.enableWifi() } } override fun ipAddressLoaded(ipAddress: IpAddress) { view_ip.text = getString(R.string.game_frame_ip, ipAddress.toString()) view_control_error.gone() view_control_content.visible() fab.visible() fab.setOnClickListener { presenter.togglePower() } } override fun ipCouldNotBeFound(throwable: Throwable) { Log.e(ControlFragment::class.java.name, "Could not find ip", throwable) view_control_error.visible() view_control_content.gone() fab.gone() } private fun adapter(@ArrayRes data: Int) = ArrayAdapter.createFromResource(context, data, android.R.layout.simple_spinner_item).apply { setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) } private fun <T: Adapter> AdapterView<T>.onItemSelected(action : (position: Int) -> Unit) { onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onNothingSelected(parent: AdapterView<*>?) {} override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { action(position) } } } private inner class BrightnessChangedListener : SeekBar.OnSeekBarChangeListener { override fun onProgressChanged(seekBar: SeekBar, level: Int, b: Boolean) { presenter.changeBrightness(Brightness.from(level)) } override fun onStartTrackingTouch(seekBar: SeekBar) {} override fun onStopTrackingTouch(seekBar: SeekBar) {} } }
apache-2.0
04f2347184c5642913b22c596073e724
37.645963
110
0.706204
4.695849
false
false
false
false
ShadwLink/Shadow-Mapper
src/main/java/nl/shadowlink/tools/shadowlib/ide/ItemCars.kt
1
1885
package nl.shadowlink.tools.shadowlib.ide import nl.shadowlink.tools.shadowlib.utils.GameType import java.io.BufferedWriter import java.io.IOException import java.util.logging.Level import java.util.logging.Logger /** * @author Shadow-Link */ class ItemCars(private val gameType: GameType) : IdeItem() { lateinit var modelName: String var textureName: String? = null var type: String? = null var handlingID: String? = null override fun read(line: String) { var line = line line = line.replace("\t".toRegex(), "") line = line.replace(" ".toRegex(), "") println("Car: $line") val split = line.split(",".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() modelName = split[0] textureName = split[1] type = split[2] handlingID = split[3] println("Model Name: " + split[0]) println("Texture Name: " + split[1]) println("Type: " + split[2]) println("HandLingID: " + split[3]) println("Game Name: " + split[4]) println("Anims: " + split[5]) println("Anims2: " + split[6]) println("Frq: " + split[7]) println("MaxNum: " + split[8]) println("Wheel Radius Front: " + split[9]) println("Wheel Radius Rear: " + split[10]) println("DefDirtLevel: " + split[11]) println("Swankness: " + split[12]) println("lodMult: " + split[13]) println("Flags: " + split[14]) //System.out.println("Extra stuff?: " + split[15]); } fun save(output: BufferedWriter) { try { val line = "" output.write( """ $line """.trimIndent() ) println("Line: $line") } catch (ex: IOException) { Logger.getLogger(ItemObject::class.java.name).log(Level.SEVERE, null, ex) } } }
gpl-2.0
56b3e2218701b645813c0cc3843b27db
30.966102
91
0.561273
3.800403
false
false
false
false
jsocle/jscole-hibernate
src/test/kotlin/com/github/jsocle/hibernate/HibernatePropertiesTest.kt
1
1490
package com.github.jsocle.hibernate import org.hibernate.cfg.AvailableSettings import org.junit.Assert import org.junit.Test class HibernatePropertiesTest { @Test fun test() { val properties = HibernateProperties(connectionUrl = "url") Assert.assertEquals(mapOf(AvailableSettings.URL to "url"), properties.javaProperties) } @Test fun testForward() { val properties = HibernateProperties() properties[AvailableSettings.URL] = "url" Assert.assertEquals("url", properties[AvailableSettings.URL]) Assert.assertEquals(mapOf(AvailableSettings.URL to "url"), properties.javaProperties) } @Test fun testPropertyDelegate() { val properties = HibernateProperties() Assert.assertNull(properties.connectionUrl) properties.connectionUrl = "url" Assert.assertEquals("url", properties.connectionUrl) Assert.assertEquals(mapOf(AvailableSettings.URL to "url"), properties.javaProperties) properties.connectionUrl = null Assert.assertNull(properties.connectionUrl) } @Test fun testEnumPropertyDelegate() { val properties = HibernateProperties() Assert.assertNull(properties.hbm2ddlAuto) properties.hbm2ddlAuto = Hbm2ddlAuto.CreateDrop Assert.assertEquals(Hbm2ddlAuto.CreateDrop, properties.hbm2ddlAuto) Assert.assertEquals(mapOf(AvailableSettings.HBM2DDL_AUTO to "create-drop"), properties.javaProperties) } }
mit
cb34ae357e136ded0b37f18349d3b991
33.674419
110
0.716107
4.487952
false
true
false
false
CarlosEsco/tachiyomi
app/src/main/java/eu/kanade/presentation/history/components/HistoryItem.kt
1
3345
package eu.kanade.presentation.history.components import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.Delete import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import eu.kanade.domain.history.model.HistoryWithRelations import eu.kanade.presentation.components.MangaCover import eu.kanade.presentation.util.horizontalPadding import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.util.lang.toTimestampString import java.text.DecimalFormat import java.text.DecimalFormatSymbols private val HISTORY_ITEM_HEIGHT = 96.dp @Composable fun HistoryItem( modifier: Modifier = Modifier, history: HistoryWithRelations, onClickCover: () -> Unit, onClickResume: () -> Unit, onClickDelete: () -> Unit, ) { Row( modifier = modifier .clickable(onClick = onClickResume) .height(HISTORY_ITEM_HEIGHT) .padding(horizontal = horizontalPadding, vertical = 8.dp), verticalAlignment = Alignment.CenterVertically, ) { MangaCover.Book( modifier = Modifier.fillMaxHeight(), data = history.coverData, onClick = onClickCover, ) Column( modifier = Modifier .weight(1f) .padding(start = horizontalPadding, end = 8.dp), ) { val textStyle = MaterialTheme.typography.bodyMedium Text( text = history.title, fontWeight = FontWeight.SemiBold, maxLines = 2, overflow = TextOverflow.Ellipsis, style = textStyle, ) val readAt = remember { history.readAt?.toTimestampString() ?: "" } Text( text = if (history.chapterNumber > -1) { stringResource( R.string.recent_manga_time, chapterFormatter.format(history.chapterNumber), readAt, ) } else { readAt }, modifier = Modifier.padding(top = 4.dp), style = textStyle, ) } IconButton(onClick = onClickDelete) { Icon( imageVector = Icons.Outlined.Delete, contentDescription = stringResource(R.string.action_delete), tint = MaterialTheme.colorScheme.onSurface, ) } } } private val chapterFormatter = DecimalFormat( "#.###", DecimalFormatSymbols().apply { decimalSeparator = '.' }, )
apache-2.0
afdfb7b3df92586df0cde0f18e453a56
34.210526
79
0.646637
4.84081
false
false
false
false
apollostack/apollo-android
composite/samples/kotlin-sample/src/main/java/com/apollographql/apollo3/kotlinsample/data/GitHubDataSource.kt
1
2259
package com.apollographql.apollo3.kotlinsample.data import com.apollographql.apollo3.ApolloClient import com.apollographql.apollo3.api.ApolloResponse import com.apollographql.apollo3.kotlinsample.GithubRepositoriesQuery import com.apollographql.apollo3.kotlinsample.GithubRepositoryCommitsQuery import com.apollographql.apollo3.kotlinsample.GithubRepositoryDetailQuery import com.apollographql.apollo3.kotlinsample.fragment.RepositoryFragment import io.reactivex.Observable import io.reactivex.subjects.PublishSubject /** * This is a base class defining the required behavior for a data source of GitHub information. We don't care if that data * is fetched via RxJava, coroutines, etc. Any implementations of this can fetch data however they want, and post that result * to the public Observables that activities can subscribe to for information. */ abstract class GitHubDataSource(protected val apolloClient: ApolloClient) { protected val repositoriesSubject: PublishSubject<List<RepositoryFragment>> = PublishSubject.create() protected val repositoryDetailSubject: PublishSubject<ApolloResponse<GithubRepositoryDetailQuery.Data>> = PublishSubject.create() protected val commitsSubject: PublishSubject<List<GithubRepositoryCommitsQuery.Data.Viewer.Repository.Ref.CommitTarget.History.Edge>> = PublishSubject.create() protected val exceptionSubject: PublishSubject<Throwable> = PublishSubject.create() val repositories: Observable<List<RepositoryFragment>> = repositoriesSubject.hide() val repositoryDetail: Observable<ApolloResponse<GithubRepositoryDetailQuery.Data>> = repositoryDetailSubject.hide() val commits: Observable<List<GithubRepositoryCommitsQuery.Data.Viewer.Repository.Ref.CommitTarget.History.Edge>> = commitsSubject.hide() val error: Observable<Throwable> = exceptionSubject.hide() abstract fun fetchRepositories() abstract fun fetchRepositoryDetail(repositoryName: String) abstract fun fetchCommits(repositoryName: String) abstract fun cancelFetching() protected fun mapRepositoriesResponseToRepositories(response: ApolloResponse<GithubRepositoriesQuery.Data>): List<RepositoryFragment> { return response.data?.viewer?.repositories?.nodes?.mapNotNull { it as RepositoryFragment? } ?: emptyList() } }
mit
9395a163e68ecf2e7bce6d895cd2d781
61.75
161
0.83444
5.02
false
false
false
false
apollostack/apollo-android
apollo-gradle-plugin/src/test/kotlin/com/apollographql/apollo3/gradle/test/LazyTests.kt
1
1900
package com.apollographql.apollo3.gradle.test import com.apollographql.apollo3.gradle.util.TestUtils import org.gradle.testkit.runner.TaskOutcome import org.junit.Assert import org.junit.Test class LazyTests { @Test fun `properties are not called during configuration`() { val apolloConfiguration = """ configure<ApolloExtension> { useSemanticNaming.set(project.provider { throw IllegalArgumentException("this should not be called during configuration") }) } """.trimIndent() TestUtils.withProject( usesKotlinDsl = true, plugins = listOf(TestUtils.kotlinJvmPlugin, TestUtils.apolloPlugin), apolloConfiguration = apolloConfiguration ) { dir -> TestUtils.executeGradle(dir, "tasks", "--all") } } @Test fun `graphql files can be generated by another task`() { val apolloConfiguration = """ abstract class InstallGraphQLFilesTask: DefaultTask() { @get:OutputDirectory abstract val outputDir: DirectoryProperty @TaskAction fun taskAction() { println("installing graphql files") project.file( "src/main/graphql/com/example").copyRecursively(outputDir.asFile.get()) } } val installTask = tasks.register("installTask", InstallGraphQLFilesTask::class.java) { outputDir.set(project.file("build/toto")) } configure<ApolloExtension> { println("adding default toto") addGraphqlDirectory(installTask.flatMap { it.outputDir }) } """.trimIndent() TestUtils.withProject( usesKotlinDsl = true, plugins = listOf(TestUtils.kotlinJvmPlugin, TestUtils.apolloPlugin), apolloConfiguration = apolloConfiguration ) { dir -> val result = TestUtils.executeTask("generateApolloSources", dir) Assert.assertEquals(TaskOutcome.SUCCESS, result.task(":generateApolloSources")!!.outcome) Assert.assertEquals(TaskOutcome.SUCCESS, result.task(":installTask")?.outcome) } } }
mit
fb41bd8d485405406b326f2112be2b4d
29.645161
95
0.726842
4.545455
false
true
false
false
Zackratos/PureMusic
app/src/main/kotlin/org/zack/music/tools/CleanLeakUtils.kt
1
1912
package org.zack.music.tools import android.content.Context import android.os.Build import android.view.View import android.view.inputmethod.InputMethodManager import java.lang.reflect.Field /** * @author : Zhangwenchao * @e-mail : [email protected] * @time : 2018/5/19 */ object CleanLeakUtils { fun fixInputMethodManagerLeak(destContext: Context?) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1 || Build.VERSION.SDK_INT > Build.VERSION_CODES.M) { return } if (destContext == null) { return } val inputMethodManager = destContext.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager val viewArray = arrayOf("mCurRootView", "mServedView", "mNextServedView") var filed: Field var filedObject: Any? for (view in viewArray) { try { filed = inputMethodManager.javaClass.getDeclaredField(view) if (!filed.isAccessible) { filed.isAccessible = true } filedObject = filed.get(inputMethodManager) if (filedObject != null && filedObject is View) { val fileView = filedObject as View? if (fileView!!.context === destContext) { // 被InputMethodManager持有引用的context是想要目标销毁的 filed.set(inputMethodManager, null) // 置空,破坏掉path to gc节点 } else { break// 不是想要目标销毁的,即为又进了另一层界面了,不要处理,避免影响原逻辑,也就不用继续for循环了 } } } catch (t: Throwable) { t.printStackTrace() } } } }
apache-2.0
1a03430ccfc973409d9d079c8e9e5f4a
29.821429
113
0.557239
4.153846
false
false
false
false
google/where-am-i
app/src/main/java/com/google/wear/whereami/data/LocationViewModel.kt
1
1903
// Copyright 2021 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.wear.whereami.data import android.Manifest import android.content.Context import android.content.pm.PackageManager import com.google.android.gms.location.LocationRequest import com.patloew.colocation.CoGeocoder import com.patloew.colocation.CoLocation import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext class LocationViewModel(private val applicationContext: Context) { private val coGeocoder = CoGeocoder.from(applicationContext) private val coLocation = CoLocation.from(applicationContext) suspend fun readLocationResult(): LocationResult { if (applicationContext.checkCallingOrSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { return PermissionError } return withContext(Dispatchers.IO) { val location = coLocation.getCurrentLocation(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY) if (location == null) { NoLocation } else { val address = coGeocoder.getAddressFromLocation(location) if (address == null) { Unknown } else { ResolvedLocation(location, address) } } } } }
apache-2.0
8f2f8348be1e1c22489bfc99eda2945a
36.333333
141
0.69732
4.817722
false
false
false
false
unbroken-dome/gradle-xjc-plugin
src/test/kotlin/org/unbrokendome/gradle/plugins/xjc/spek/GradleSpekUtils.kt
1
2570
package org.unbrokendome.gradle.plugins.xjc.spek import org.gradle.api.Action import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.api.Task import org.gradle.testfixtures.ProjectBuilder import org.spekframework.spek2.dsl.LifecycleAware import org.spekframework.spek2.lifecycle.MemoizedValue import kotlin.properties.ReadOnlyProperty import kotlin.reflect.KClass import kotlin.reflect.KProperty interface MemoizedGradleProject : MemoizedValue<Project> { var projectName: String fun initializer(initializer: Project.() -> Unit) fun applyPlugin(pluginType: KClass<out Plugin<out Project>>) = initializer { plugins.apply(pluginType.java) } } inline fun <reified T : Plugin<out Project>> MemoizedGradleProject.applyPlugin() = applyPlugin(T::class) private data class DefaultMemoizedGradleProject( private val lifecycleAware: LifecycleAware ) : MemoizedGradleProject { override var projectName: String = "" private val initializers = mutableListOf<Project.() -> Unit>() override fun initializer(initializer: Project.() -> Unit) { initializers.add(initializer) } override fun provideDelegate(thisRef: Any?, property: KProperty<*>): ReadOnlyProperty<Any?, Project> { val memoized = lifecycleAware.memoized( factory = { ProjectBuilder.builder().run { projectName.takeUnless { it.isEmpty() }?.let { withName(it) } build() }.also { project -> initializers.forEach { initializer -> initializer(project) } } }, destructor = { project -> project.projectDir.deleteRecursively() } ) return memoized.provideDelegate(thisRef, property) } } fun LifecycleAware.gradleProject(): MemoizedGradleProject = DefaultMemoizedGradleProject(this) fun LifecycleAware.setupGradleProject(block: MemoizedGradleProject.() -> Unit): MemoizedValue<Project> { @Suppress("UNUSED_VARIABLE") val project: Project by gradleProject().also(block) return memoized() } fun <T : Task> LifecycleAware.gradleTask( taskType: KClass<T>, name: String? = null, config: T.() -> Unit = {} ): MemoizedValue<T> { val project: Project by memoized() val actualName = name ?: taskType.simpleName?.decapitalize() ?: "task" return memoized<T> { project.tasks.create(actualName, taskType.java, Action(config)) } }
mit
fcaae63d87ddcaee9ae8202903d23f6c
27.876404
106
0.663035
4.698355
false
false
false
false
Maccimo/intellij-community
plugins/kotlin/maven/src/org/jetbrains/kotlin/idea/maven/inspections/DifferentKotlinMavenVersionInspection.kt
3
2927
// 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.maven.inspections import com.intellij.lang.annotation.HighlightSeverity import com.intellij.util.xml.DomFileElement import com.intellij.util.xml.highlighting.DomElementAnnotationHolder import com.intellij.util.xml.highlighting.DomElementsInspection import org.jetbrains.annotations.TestOnly import org.jetbrains.idea.maven.dom.model.MavenDomPlugin import org.jetbrains.idea.maven.dom.model.MavenDomProjectModel import org.jetbrains.idea.maven.project.MavenProjectsManager import org.jetbrains.kotlin.config.LanguageVersion import org.jetbrains.kotlin.idea.compiler.configuration.IdeKotlinVersion import org.jetbrains.kotlin.idea.compiler.configuration.KotlinPluginLayout import org.jetbrains.kotlin.idea.inspections.PluginVersionDependentInspection import org.jetbrains.kotlin.idea.maven.KotlinMavenBundle import org.jetbrains.kotlin.idea.maven.PomFile class DifferentKotlinMavenVersionInspection : DomElementsInspection<MavenDomProjectModel>(MavenDomProjectModel::class.java), PluginVersionDependentInspection { private val idePluginVersion by lazy { KotlinPluginLayout.ideCompilerVersion.languageVersion } override var testVersionMessage: String? = null @TestOnly set override fun checkFileElement(domFileElement: DomFileElement<MavenDomProjectModel>?, holder: DomElementAnnotationHolder?) { if (domFileElement == null || holder == null) { return } val project = domFileElement.module?.project ?: return val mavenManager = MavenProjectsManager.getInstance(project) ?: return if (!mavenManager.isMavenizedProject || !mavenManager.isManagedFile(domFileElement.file.virtualFile)) { return } val pomFile = PomFile.forFileOrNull(domFileElement.file) ?: return for (plugin in pomFile.findKotlinPlugins()) { if (!plugin.version.exists()) continue val mavenPluginVersion = IdeKotlinVersion.parse(plugin.version.stringValue ?: continue) val mavenPluginLanguageVersion = mavenPluginVersion.getOrNull()?.languageVersion ?: continue if (idePluginVersion < mavenPluginLanguageVersion || mavenPluginLanguageVersion < LanguageVersion.FIRST_SUPPORTED) { createProblem(holder, plugin) } } } private fun createProblem(holder: DomElementAnnotationHolder, plugin: MavenDomPlugin) { val versionFromMaven = plugin.version.stringValue val versionFromIde = testVersionMessage ?: idePluginVersion holder.createProblem( plugin.version, HighlightSeverity.WARNING, KotlinMavenBundle.message("version.different.maven.ide", versionFromMaven.toString(), versionFromIde) ) } }
apache-2.0
2dbd392a35ac66ca1b87d4ec399d2c35
46.225806
158
0.760506
5.171378
false
true
false
false