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
KotlinNLP/SimpleDNN
src/test/kotlin/deeplearning/attention/HANSpec.kt
1
4355
/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at http://mozilla.org/MPL/2.0/. * ------------------------------------------------------------------*/ package deeplearning.attention import com.kotlinnlp.simplednn.core.functionalities.activations.Softmax import com.kotlinnlp.simplednn.core.functionalities.activations.Tanh import com.kotlinnlp.simplednn.core.layers.LayerType import com.kotlinnlp.simplednn.deeplearning.attention.han.HAN import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe import kotlin.test.assertEquals import kotlin.test.assertTrue /** * */ class HANSpec : Spek({ describe("a HAN") { context("initialization") { val han = HAN( hierarchySize = 3, inputSize = 10, biRNNsActivation = Tanh, biRNNsConnectionType = LayerType.Connection.GRU, attentionSize = 5, outputSize = 30, outputActivation = Softmax(), gainFactors = listOf(1.5, 2.0, 1.0)) it("should have a BiRNN with the expected input size in the level 2") { assertEquals(10, han.biRNNs[2].inputSize) } it("should have a BiRNN with the expected output size in the level 2") { assertEquals(16, han.biRNNs[2].outputSize) } it("should have a BiRNN with the expected activation function in the level 2") { assertTrue { han.biRNNs[2].hiddenActivation is Tanh } } it("should have AttentionNetworkParams with the expected input size in the level 2") { assertEquals(16, han.attentionNetworksParams[2].inputSize) } it("should have AttentionNetworkParams with the expected output size in the level 2") { assertEquals(16, han.attentionNetworksParams[2].outputSize) } it("should have AttentionNetworkParams with the expected attention size in the level 2") { assertEquals(5, han.attentionNetworksParams[2].attentionSize) } it("should have a BiRNN with the expected input size in the level 1") { assertEquals(16, han.biRNNs[1].inputSize) } it("should have a BiRNN with the expected output size in the level 1") { assertEquals(32, han.biRNNs[1].outputSize) } it("should have a BiRNN with the expected activation function in the level 1") { assertTrue { han.biRNNs[1].hiddenActivation is Tanh } } it("should have AttentionNetworkParams with the expected input size in the level 1") { assertEquals(32, han.attentionNetworksParams[1].inputSize) } it("should have AttentionNetworkParams with the expected output size in the level 1") { assertEquals(32, han.attentionNetworksParams[1].outputSize) } it("should have AttentionNetworkParams with the expected attention size in the level 1") { assertEquals(5, han.attentionNetworksParams[1].attentionSize) } it("should have a BiRNN with the expected input size in the level 0") { assertEquals(32, han.biRNNs[0].inputSize) } it("should have a BiRNN with the expected output size in the level 0") { assertEquals(32, han.biRNNs[0].outputSize) } it("should have a BiRNN with the expected activation function in the level 0") { assertTrue { han.biRNNs[0].hiddenActivation is Tanh } } it("should have AttentionNetworkParams with the expected input size in the level 0") { assertEquals(32, han.attentionNetworksParams[0].inputSize) } it("should have AttentionNetworkParams with the expected output size in the level 0") { assertEquals(32, han.attentionNetworksParams[0].outputSize) } it("should have AttentionNetworkParams with the expected attention size in the level 0") { assertEquals(5, han.attentionNetworksParams[0].attentionSize) } it("should have an output network with the expected input size") { assertEquals(32, han.outputNetwork.layersConfiguration[0].size) } it("should have an output network with the expected output size") { assertEquals(30, han.outputNetwork.layersConfiguration[1].size) } } } })
mpl-2.0
2d3dfb2be083cae877223990cb5153d9
35.596639
96
0.677842
4.19153
false
false
false
false
MarcBob/StickMan
StickMan/app/src/main/kotlin/marmor/com/stickman/Limb.kt
1
2491
package marmor.com.stickman import android.graphics.PointF import android.util.Log import java.util.* public class Limb(start: PointF, length: Float, angle: Float, var name: String) { private val FULL_CIRCLE = -2 * Math.PI public val recordedAngles: LinkedList<RecordedAngle> = LinkedList() private lateinit var _start: PointF public var start: PointF get() = _start set(value){ _start = value calculateEndPoint() } private lateinit var _end: PointF public val end: PointF get() = _end private var _angle: Double = 0.0 public var angle: Double set(value){ recordAngles(value) _angle = value calculateEndPoint() } get() = _angle private var _length: Float = 0f public var length: Float set(value){ _length = value calculateEndPoint() } get() = _length public lateinit var startJoint: Joint public lateinit var endJoint: Joint init { _start = start _end = PointF() _angle = degreeToRadial(angle) _length = length; calculateEndPoint() } public fun update(start: PointF?, length: Float?, angle: Float?) { if (start != null) { _start = start } if (length != null) { _length = length } if (angle != null) { _angle = angle.toDouble() } calculateEndPoint() } private fun recordAngles(newAngle: Double) { var difference = newAngle - _angle recordedAngles.add(RecordedAngle(difference, System.currentTimeMillis())) Log.d("lalaland", "# Angles: " + recordedAngles.size + " Timestamp: " + System.currentTimeMillis()) } public fun setAngleInDegree(angle: Float) { _angle = degreeToRadial(angle) calculateEndPoint() } public fun pull(destination: PointF, limbs: MutableList<Limb>) { limbs.add(this) startJoint.pull(destination, limbs) } private fun degreeToRadial(angle: Float): Double { return (angle / 360) * FULL_CIRCLE + Math.PI } private fun calculateEndPoint() { Log.d("Limb calcEndPoint: ", "angle: " + angle) val diffX = Math.sin(this.angle).toFloat() * length val diffY = Math.cos(this.angle).toFloat() * length _end.x = start.x + diffX _end.y = start.y + diffY } }
apache-2.0
69f32517327a3fe2f89ec84ebb2b3322
24.680412
109
0.574067
4.186555
false
false
false
false
GunoH/intellij-community
platform/platform-impl/src/com/intellij/execution/wsl/WslExecution.kt
2
5132
// 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. @file:JvmName("WslExecution") package com.intellij.execution.wsl import com.intellij.execution.CommandLineUtil import com.intellij.execution.ExecutionException import com.intellij.execution.configurations.GeneralCommandLine import com.intellij.execution.process.CapturingProcessHandler import com.intellij.execution.process.ProcessHandler import com.intellij.execution.process.ProcessOutput import com.intellij.execution.wsl.WSLUtil.LOG import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.util.text.StringUtil import com.intellij.util.EnvironmentUtil import com.intellij.util.LineSeparator import com.intellij.util.containers.ContainerUtil import java.util.function.Consumer @JvmOverloads @Throws(ExecutionException::class) fun WSLDistribution.executeInShellAndGetCommandOnlyStdout(commandLine: GeneralCommandLine, options: WSLCommandLineOptions, timeout: Int, processHandlerCustomizer: Consumer<ProcessHandler> = Consumer {}): ProcessOutput { if (!options.isExecuteCommandInShell) { throw AssertionError("Execution in shell is expected") } // When command is executed in interactive/login shell, the result stdout may contain additional output // produced by shell configuration files, for example, "Message Of The Day". // Let's print some unique message before executing the command to know where command output begins in the result output. val prefixText = "intellij: executing command..." options.addInitCommand("echo " + CommandLineUtil.posixQuote(prefixText)) if (options.isExecuteCommandInInteractiveShell) { // Disable oh-my-zsh auto update on shell initialization commandLine.environment[EnvironmentUtil.DISABLE_OMZ_AUTO_UPDATE] = "true" options.isPassEnvVarsUsingInterop = true } val output: ProcessOutput = executeOnWsl(commandLine, options, timeout, processHandlerCustomizer) val stdout = output.stdout val markerText = prefixText + LineSeparator.LF.separatorString val index = stdout.indexOf(markerText) if (index < 0) { val application = ApplicationManager.getApplication() if (application == null || application.isInternal || application.isUnitTestMode) { LOG.error("Cannot find '$prefixText' in stdout: $output, command: ${commandLine.commandLineString}") } else { if (LOG.isDebugEnabled) { LOG.debug("Cannot find '$prefixText' in stdout: $output, command: ${commandLine.commandLineString}") } else { LOG.info("Cannot find '$prefixText' in stdout") } } return output } return ProcessOutput(stdout.substring(index + markerText.length), output.stderr, output.exitCode, output.isTimeout, output.isCancelled) } fun WSLDistribution.executeInShellAndGetCommandOnlyStdout(commandLine: GeneralCommandLine, options: WSLCommandLineOptions, timeout: Int, expectOneLineStdout: Boolean): String? { try { val output: ProcessOutput = executeInShellAndGetCommandOnlyStdout(commandLine, options, timeout) val stdout = output.stdout if (!output.isTimeout && output.exitCode == 0) { return if (expectOneLineStdout) expectOneLineOutput(commandLine, stdout) else stdout } LOG.info("Failed to execute $commandLine for $msId: exitCode=${output.exitCode}, timeout=${output.isTimeout}," + " stdout=$stdout, stderr=${output.stderr}") } catch (e: ExecutionException) { LOG.info("Failed to execute $commandLine for $msId", e) } return null } private fun WSLDistribution.expectOneLineOutput(commandLine: GeneralCommandLine, stdout: String): String { val converted = StringUtil.convertLineSeparators(stdout, LineSeparator.LF.separatorString) val lines = StringUtil.split(converted, LineSeparator.LF.separatorString, true, true) if (lines.size != 1) { LOG.info("One line stdout expected: " + msId + ", command=" + commandLine + ", stdout=" + stdout + ", lines=" + lines.size) } return StringUtil.notNullize(ContainerUtil.getFirstItem(lines), stdout) } @Throws(ExecutionException::class) private fun WSLDistribution.executeOnWsl(commandLine: GeneralCommandLine, options: WSLCommandLineOptions, timeout: Int, processHandlerCustomizer: Consumer<ProcessHandler>): ProcessOutput { patchCommandLine<GeneralCommandLine>(commandLine, null, options) val processHandler = CapturingProcessHandler(commandLine) processHandlerCustomizer.accept(processHandler) return processHandler.runProcess(timeout) }
apache-2.0
c0de7483d4a4f190921298caab72f7fb
49.323529
158
0.691348
5.142285
false
false
false
false
GunoH/intellij-community
java/debugger/impl/src/com/intellij/debugger/actions/RunToolbarHotSwapAction.kt
3
2890
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.debugger.actions import com.intellij.openapi.util.registry.RegistryManager import com.intellij.debugger.DebuggerManagerEx import com.intellij.debugger.impl.DebuggerSession import com.intellij.debugger.settings.DebuggerSettings import com.intellij.debugger.ui.HotSwapUI import com.intellij.debugger.ui.HotSwapUIImpl import com.intellij.execution.runToolbar.* import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.ShortcutSet import com.intellij.openapi.diagnostic.Logger import com.intellij.xdebugger.XDebuggerManager import com.intellij.xdebugger.impl.XDebugSessionImpl import java.util.* class RunToolbarHotSwapAction : AnAction(), RTBarAction { companion object { private val LOG = Logger.getInstance(RunToolbarHotSwapAction::class.java) } override fun getRightSideType(): RTBarAction.Type = RTBarAction.Type.RIGHT_FLEXIBLE override fun actionPerformed(e: AnActionEvent) { val project = e.project val session = getSession(e) if (session != null && session.isAttached) { HotSwapUI.getInstance(project).reloadChangedClasses(session, DebuggerSettings.getInstance().COMPILE_BEFORE_HOTSWAP) } } override fun checkMainSlotVisibility(state: RunToolbarMainSlotState): Boolean { return state == RunToolbarMainSlotState.PROCESS } override fun setShortcutSet(shortcutSet: ShortcutSet) {} private fun getSession(e: AnActionEvent): DebuggerSession? { return e.environment()?.let { environment -> e.project?.let { project -> val xDebugSession = XDebuggerManager.getInstance(project) ?.debugSessions ?.filter { it.runContentDescriptor == environment.contentToReuse } ?.filterIsInstance<XDebugSessionImpl>()?.firstOrNull { !it.isStopped } DebuggerManagerEx.getInstanceEx(project).sessions.firstOrNull{session -> Objects.equals(session.getXDebugSession(), xDebugSession)} } } } override fun update(e: AnActionEvent) { val session = getSession(e) e.presentation.isVisible = session != null && HotSwapUIImpl.canHotSwap(session) && RegistryManager.getInstance().`is`("ide.widget.toolbar.hotswap") if(e.presentation.isVisible) { e.presentation.isEnabled = !e.isProcessTerminating() } if (!RunToolbarProcess.isExperimentalUpdatingEnabled) { e.mainState()?.let { e.presentation.isVisible = e.presentation.isVisible && checkMainSlotVisibility(it) } } //LOG.info(getLog(e)) } override fun getActionUpdateThread(): ActionUpdateThread { return ActionUpdateThread.BGT } }
apache-2.0
d3399997e7948fcd1fe0fc8f91d4d059
36.545455
158
0.757093
4.66129
false
false
false
false
AsamK/TextSecure
app/src/main/java/org/thoughtcrime/securesms/components/settings/conversation/GroupCapacityResult.kt
3
1390
package org.thoughtcrime.securesms.components.settings.conversation import org.thoughtcrime.securesms.ContactSelectionListFragment import org.thoughtcrime.securesms.groups.SelectionLimits import org.thoughtcrime.securesms.recipients.RecipientId class GroupCapacityResult( private val selfId: RecipientId, private val members: List<RecipientId>, private val selectionLimits: SelectionLimits, val isAnnouncementGroup: Boolean ) { fun getMembers(): List<RecipientId?> { return members } fun getSelectionLimit(): Int { if (!selectionLimits.hasHardLimit()) { return ContactSelectionListFragment.NO_LIMIT } val containsSelf = members.indexOf(selfId) != -1 return selectionLimits.hardLimit - if (containsSelf) 1 else 0 } fun getSelectionWarning(): Int { if (!selectionLimits.hasRecommendedLimit()) { return ContactSelectionListFragment.NO_LIMIT } val containsSelf = members.indexOf(selfId) != -1 return selectionLimits.recommendedLimit - if (containsSelf) 1 else 0 } fun getRemainingCapacity(): Int { return selectionLimits.hardLimit - members.size } fun getMembersWithoutSelf(): List<RecipientId> { val recipientIds = ArrayList<RecipientId>(members.size) for (recipientId in members) { if (recipientId != selfId) { recipientIds.add(recipientId) } } return recipientIds } }
gpl-3.0
f1b9ccdb43914c9bf1d8a1b7748b8544
28.574468
72
0.738129
4.542484
false
false
false
false
inorichi/mangafeed
app/src/main/java/eu/kanade/tachiyomi/extension/model/InstallStep.kt
3
240
package eu.kanade.tachiyomi.extension.model enum class InstallStep { Idle, Pending, Downloading, Installing, Installed, Error; fun isCompleted(): Boolean { return this == Installed || this == Error || this == Idle } }
apache-2.0
5263b9fd8b626eb9ee1d224c5e175a6e
25.666667
65
0.670833
4.444444
false
false
false
false
DemonWav/MinecraftDev
src/main/kotlin/com/demonwav/mcdev/MinecraftSettings.kt
1
3097
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2018 minecraft-dev * * MIT License */ package com.demonwav.mcdev import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.openapi.editor.markup.EffectType import org.jetbrains.annotations.Contract @State(name = "MinecraftSettings", storages = [Storage("minecraft_dev.xml")]) class MinecraftSettings : PersistentStateComponent<MinecraftSettings.State> { data class State( var isShowProjectPlatformIcons: Boolean = true, var isShowEventListenerGutterIcons: Boolean = true, var isShowChatColorGutterIcons: Boolean = true, var isShowChatColorUnderlines: Boolean = false, var underlineType: MinecraftSettings.UnderlineType = MinecraftSettings.UnderlineType.DOTTED ) private var state = State() override fun getState(): State { return state } override fun loadState(state: State) { this.state = state } // State mappings var isShowProjectPlatformIcons: Boolean get() = state.isShowProjectPlatformIcons set(showProjectPlatformIcons) { state.isShowProjectPlatformIcons = showProjectPlatformIcons } var isShowEventListenerGutterIcons: Boolean get() = state.isShowEventListenerGutterIcons set(showEventListenerGutterIcons) { state.isShowEventListenerGutterIcons = showEventListenerGutterIcons } var isShowChatColorGutterIcons: Boolean get() = state.isShowChatColorGutterIcons set(showChatColorGutterIcons) { state.isShowChatColorGutterIcons = showChatColorGutterIcons } var isShowChatColorUnderlines: Boolean get() = state.isShowChatColorUnderlines set(showChatColorUnderlines) { state.isShowChatColorUnderlines = showChatColorUnderlines } var underlineType: UnderlineType get() = state.underlineType set(underlineType) { state.underlineType = underlineType } val underlineTypeIndex: Int get() { val type = underlineType return (0 until UnderlineType.values().size).firstOrNull { type == UnderlineType.values()[it] } ?: 0 } enum class UnderlineType(private val regular: String, val effectType: EffectType) { NORMAL("Normal", EffectType.LINE_UNDERSCORE), BOLD("Bold", EffectType.BOLD_LINE_UNDERSCORE), DOTTED("Dotted", EffectType.BOLD_DOTTED_LINE), BOXED("Boxed", EffectType.BOXED), ROUNDED_BOXED("Rounded Boxed", EffectType.ROUNDED_BOX), WAVED("Waved", EffectType.WAVE_UNDERSCORE); @Contract(pure = true) override fun toString(): String { return regular } } companion object { val instance: MinecraftSettings get() = ServiceManager.getService(MinecraftSettings::class.java) } }
mit
f059c3ee934efd9f2bd37083f8e21be1
30.927835
112
0.689377
5.267007
false
false
false
false
code-disaster/lwjgl3
modules/lwjgl/glfw/src/templates/kotlin/glfw/templates/GLFWNativeNSGL.kt
4
2626
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package glfw.templates import org.lwjgl.generator.* import glfw.* import core.macos.* val GLFWNativeNSGL = "GLFWNativeNSGL".nativeClass(Module.GLFW, nativeSubPath = "macos", prefix = "GLFW", binding = GLFW_BINDING_DELEGATE) { javaImport( "javax.annotation.*", "org.lwjgl.opengl.GL", "org.lwjgl.system.macosx.*", "static org.lwjgl.system.MemoryUtil.*" ) documentation = "Native bindings to the GLFW library's NSGL native access functions." id( "GetNSGLContext", """ Returns the {@code NSOpenGLContext} of the specified GLFW window. Note: This function may be called from any thread. Access is not synchronized. """, GLFWwindow.p("window", "the GLFW window"), returnDoc = """ the {@code NSOpenGLContext} of the specified window, or nil if an error occurred. Possible errors include #NO_WINDOW_CONTEXT and #NOT_INITIALIZED. """, since = "version 3.0" ) customMethod(""" /** Calls {@link #setFramework(String)} with the OpenGL framework loaded by LWJGL. */ public static void setFrameworkLWJGL() { FunctionProvider fp = GL.getFunctionProvider(); if (!(fp instanceof MacOSXLibraryBundle)) { apiLog("GLFW OpenGL path override not set: OpenGL function provider is not a framework."); return; } setFramework(((MacOSXLibraryBundle)fp).getName()); } /** * Overrides the OpenGL framework that GLFW loads internally. * * <p>This is useful when there's a mismatch between the frameworks loaded by LWJGL and GLFW.</p> * * <p>This method must be called before GLFW initializes OpenGL. The override is available only in the default GLFW build bundled with LWJGL. Using the * override with a custom GLFW build will produce a warning in {@code DEBUG} mode (but not an error).</p> * * @param path the OpenGL framework, or {@code null} to remove the override. */ public static void setFramework(@Nullable String path) { long override = GLFW.getLibrary().getFunctionAddress("_glfw_opengl_library"); if (override == NULL) { apiLog("GLFW OpenGL path override not set: Could not resolve override symbol."); return; } long a = memGetAddress(override); if (a != NULL) { nmemFree(a); } memPutAddress(override, path == null ? NULL : memAddress(memUTF8(path))); }""") }
bsd-3-clause
1f0141000408929d3177461086499f21
33.565789
155
0.63214
4.527586
false
false
false
false
mre/the-coding-interview
problems/byte-format/byte-format.kt
1
841
import java.text.NumberFormat import kotlin.test.assertEquals private val metricPrefixes = listOf("K", "M", "G", "T", "P", "E", "Z", "Y") fun <T> T.byteFormat(maximumFractionDigits: Int = 2): String where T : Number, T : Comparable<T> { var n = toDouble() var metricPrefix = "" for (prefix in metricPrefixes) { val x = n / 1024 if (x < 1) break n = x metricPrefix = prefix } val nf = NumberFormat.getInstance() nf.maximumFractionDigits = maximumFractionDigits return "${nf.format(n)} ${metricPrefix}B" } fun main(args: Array<String>) { assertEquals("1 B", 1.byteFormat()) assertEquals("12.5 B", 12.5.byteFormat()) assertEquals("7.91 KB", 8101.byteFormat()) assertEquals("12.042 KB", 12331.byteFormat(3)) assertEquals("149.57 MB", 156833213.byteFormat()) }
mit
8e37bda76e036cfeb8f147bff2539212
29.035714
98
0.63258
3.418699
false
false
false
false
android/project-replicator
code/codegen/src/main/kotlin/com/android/gradle/replicator/resgen/RawResourceGenerator.kt
1
2452
package com.android.gradle.replicator.resgen import com.android.gradle.replicator.model.internal.filedata.AbstractAndroidResourceProperties import com.android.gradle.replicator.model.internal.filedata.DefaultAndroidResourceProperties import com.android.gradle.replicator.model.internal.filedata.ResourcePropertyType import com.android.gradle.replicator.resgen.resourceModel.ResourceData import com.android.gradle.replicator.resgen.util.copyResourceFile import com.android.gradle.replicator.resgen.util.getFileType import com.android.gradle.replicator.resgen.util.getResourceClosestToSize import java.io.File class RawResourceGenerator (params: ResourceGenerationParams): ResourceGenerator(params) { override fun generateResource( properties: AbstractAndroidResourceProperties, outputFolder: File ) { // Sanity check. This should not happen unless there is a bug in the metadata reader. if (properties.propertyType != ResourcePropertyType.DEFAULT) { throw RuntimeException ("Unexpected property type. Got ${properties.propertyType} instead of ${ResourcePropertyType.DEFAULT}") } if (getFileType(properties.extension) == null) { println("Unsupported file type $properties.extension") return } (properties as DefaultAndroidResourceProperties).fileData.forEach { fileSize -> val fileName = "raw_${params.uniqueIdGenerator.genIdByCategory("raw.fileName.${properties.qualifiers}")}" val outputFile = File(outputFolder, "$fileName.${properties.extension}") println("Generating ${outputFile.absolutePath}") generateRawResource(outputFile, properties.extension, fileSize) params.resourceModel.resourceList.add( ResourceData( pkg = "", name = fileName, type = "raw", extension = properties.extension, qualifiers = properties.splitQualifiers) ) } } // TODO: generate random bytes for unknown resource types private fun generateRawResource ( outputFile: File, resourceExtension: String, fileSize: Long ) { val fileType = getFileType(resourceExtension)!! val resourcePath = getResourceClosestToSize(fileType, fileSize) ?: return copyResourceFile(resourcePath, outputFile) } }
apache-2.0
a672b142e7e212d94787ad1a3157ec2f
44.425926
138
0.695351
5.284483
false
false
false
false
Tickaroo/tikxml
processor/src/test/java/com/tickaroo/tikxml/processor/converter/ConverterCheckerByTypeMirrorTest.kt
1
10776
/* * Copyright (C) 2015 Hannes Dorfmann * Copyright (C) 2015 Tickaroo, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.tickaroo.tikxml.processor.converter import com.tickaroo.tikxml.TypeConverter import com.tickaroo.tikxml.annotation.Attribute import com.tickaroo.tikxml.processor.ProcessingException import org.junit.Test import org.mockito.Mockito import javax.lang.model.element.ElementKind import javax.lang.model.element.ExecutableElement import javax.lang.model.element.Modifier import javax.lang.model.element.TypeElement import javax.lang.model.element.VariableElement import javax.lang.model.type.DeclaredType import javax.lang.model.type.MirroredTypeException import javax.lang.model.type.TypeKind import javax.lang.model.type.TypeMirror import kotlin.test.assertEquals import kotlin.test.fail /** * * @author Hannes Dorfmann */ class ConverterCheckerByTypeMirrorTest { @Test fun interfaceConverter() { val attributeConverterChecker = AttributeConverterChecker() val element = Mockito.mock(VariableElement::class.java) val annotation = Mockito.mock(Attribute::class.java) for (kind in TypeKind.values()) { if (kind == TypeKind.DECLARED) continue // Skip declared, because declared is the expected behaviour val typeMirror = Mockito.mock(TypeMirror::class.java) Mockito.doReturn(kind).`when`(typeMirror).kind Mockito.doAnswer { throw MirroredTypeException(typeMirror) }.`when`(annotation).converter try { attributeConverterChecker.getQualifiedConverterName(element, annotation) fail("Processing Exception expected for type $kind") } catch (e: ProcessingException) { assertEquals("TypeConverter must be a class", e.message) } } } @Test fun notClassElement() { val attributeConverterChecker = AttributeConverterChecker() val element = Mockito.mock(VariableElement::class.java) val annotation = Mockito.mock(Attribute::class.java) for (kind in ElementKind.values()) { if (kind == ElementKind.CLASS) { continue } // Element val typeElement = Mockito.mock(TypeElement::class.java) Mockito.doReturn(kind).`when`(typeElement).kind Mockito.doReturn(AbstractTypeConverter::class.java.canonicalName).`when`(typeElement).toString() // Type Mirror val typeMirror = Mockito.mock(DeclaredType::class.java) Mockito.doReturn(TypeKind.DECLARED).`when`(typeMirror).kind Mockito.doReturn(typeElement).`when`(typeMirror).asElement() Mockito.doReturn(AbstractTypeConverter::class.java.canonicalName).`when`(typeMirror).toString() Mockito.doAnswer { throw MirroredTypeException(typeMirror) }.`when`(annotation).converter try { attributeConverterChecker.getQualifiedConverterName(element, annotation) fail("Processing Exception expected") } catch (e: ProcessingException) { assertEquals("TypeConverter com.tickaroo.tikxml.processor.converter.AbstractTypeConverter must be a public class!", e.message) } } } @Test fun abstractClassConverter() { val attributeConverterChecker = AttributeConverterChecker() val element = Mockito.mock(VariableElement::class.java) val annotation = Mockito.mock(Attribute::class.java) // Element val typeElement = Mockito.mock(TypeElement::class.java) Mockito.doReturn(ElementKind.CLASS).`when`(typeElement).kind Mockito.doReturn(hashSetOf(Modifier.ABSTRACT)).`when`(typeElement).modifiers Mockito.doReturn(AbstractTypeConverter::class.java.canonicalName).`when`(typeElement).toString() // Type Mirror val typeMirror = Mockito.mock(DeclaredType::class.java) Mockito.doReturn(TypeKind.DECLARED).`when`(typeMirror).kind Mockito.doReturn(typeElement).`when`(typeMirror).asElement() Mockito.doReturn(AbstractTypeConverter::class.java.canonicalName).`when`(typeMirror).toString() Mockito.doAnswer { throw MirroredTypeException(typeMirror) }.`when`(annotation).converter try { attributeConverterChecker.getQualifiedConverterName(element, annotation) fail("Processing Exception expected") } catch (e: ProcessingException) { assertEquals("TypeConverter com.tickaroo.tikxml.processor.converter.AbstractTypeConverter class is not public!", e.message) } } @Test fun defaultVisibiltiyConverter() { val attributeConverterChecker = AttributeConverterChecker() val element = Mockito.mock(VariableElement::class.java) val annotation = Mockito.mock(Attribute::class.java) // Element val typeElement = Mockito.mock(TypeElement::class.java) Mockito.doReturn(ElementKind.CLASS).`when`(typeElement).kind Mockito.doReturn(hashSetOf(Modifier.STATIC)).`when`(typeElement).modifiers Mockito.doReturn(DefaultVisibilityTypeConverter::class.qualifiedName).`when`(typeElement).toString() // Type Mirror val typeMirror = Mockito.mock(DeclaredType::class.java) Mockito.doReturn(TypeKind.DECLARED).`when`(typeMirror).kind Mockito.doReturn(typeElement).`when`(typeMirror).asElement() Mockito.doAnswer { throw MirroredTypeException(typeMirror) }.`when`(annotation).converter try { attributeConverterChecker.getQualifiedConverterName(element, annotation) fail("Processing Exception expected") } catch (e: ProcessingException) { assertEquals("TypeConverter com.tickaroo.tikxml.processor.converter.DefaultVisibilityTypeConverter class is not public!", e.message) } } @Test fun privateVisibiltiyConverter() { val attributeConverterChecker = AttributeConverterChecker() val element = Mockito.mock(VariableElement::class.java) val annotation = Mockito.mock(Attribute::class.java) // Element val typeElement = Mockito.mock(TypeElement::class.java) Mockito.doReturn(ElementKind.CLASS).`when`(typeElement).kind Mockito.doReturn(hashSetOf(Modifier.PRIVATE)).`when`(typeElement).modifiers Mockito.doReturn(PrivateVisibilityTypeConverter::class.qualifiedName).`when`(typeElement).toString() // Type Mirror val typeMirror = Mockito.mock(DeclaredType::class.java) Mockito.doReturn(TypeKind.DECLARED).`when`(typeMirror).kind Mockito.doReturn(typeElement).`when`(typeMirror).asElement() Mockito.doAnswer { throw MirroredTypeException(typeMirror) }.`when`(annotation).converter try { attributeConverterChecker.getQualifiedConverterName(element, annotation) fail("Processing Exception expected") } catch (e: ProcessingException) { assertEquals( "TypeConverter com.tickaroo.tikxml.processor.converter.ConverterCheckerByTypeMirrorTest.PrivateVisibilityTypeConverter class is not public!", e.message) } } @Test fun onlyPrivateConstructorConverter() { val attributeConverterChecker = AttributeConverterChecker() val element = Mockito.mock(VariableElement::class.java) val annotation = Mockito.mock(Attribute::class.java) // Private Constructor val constructor = Mockito.mock(ExecutableElement::class.java) Mockito.doReturn(hashSetOf(Modifier.PRIVATE)).`when`(constructor).modifiers // Element val typeElement = Mockito.mock(TypeElement::class.java) Mockito.doReturn(ElementKind.CLASS).`when`(typeElement).kind Mockito.doReturn(hashSetOf(Modifier.PUBLIC)).`when`(typeElement).modifiers Mockito.doReturn(arrayListOf(constructor)).`when`(typeElement).enclosedElements // Type Mirror val typeMirror = Mockito.mock(DeclaredType::class.java) Mockito.doReturn(TypeKind.DECLARED).`when`(typeMirror).kind Mockito.doReturn(typeElement).`when`(typeMirror).asElement() Mockito.doReturn(PrivateConstructorTypeConverter::class.qualifiedName).`when`(typeMirror).toString() Mockito.doAnswer { throw MirroredTypeException(typeMirror) }.`when`(annotation).converter try { attributeConverterChecker.getQualifiedConverterName(element, annotation) fail("Processing Exception expected") } catch (e: ProcessingException) { assertEquals( "TypeConverter class com.tickaroo.tikxml.processor.converter.PrivateConstructorTypeConverter must provide an empty (parameter-less) public constructor", e.message) } } @Test fun noEmptyConstructorConverter() { val attributeConverterChecker = AttributeConverterChecker() val element = Mockito.mock(VariableElement::class.java) val annotation = Mockito.mock(Attribute::class.java) // Constructor val constructor = Mockito.mock(ExecutableElement::class.java) Mockito.doReturn(hashSetOf(Modifier.PUBLIC)).`when`(constructor).modifiers Mockito.doReturn(arrayListOf(Mockito.mock(VariableElement::class.java))).`when`(constructor).parameters // Element val typeElement = Mockito.mock(TypeElement::class.java) Mockito.doReturn(ElementKind.CLASS).`when`(typeElement).kind Mockito.doReturn(hashSetOf(Modifier.PUBLIC)).`when`(typeElement).modifiers Mockito.doReturn(arrayListOf(constructor)).`when`(typeElement).enclosedElements // Type Mirror val typeMirror = Mockito.mock(DeclaredType::class.java) Mockito.doReturn(TypeKind.DECLARED).`when`(typeMirror).kind Mockito.doReturn(typeElement).`when`(typeMirror).asElement() Mockito.doReturn(NoParameterLessConstructorTypeConverter::class.qualifiedName).`when`(typeMirror).toString() Mockito.doAnswer { throw MirroredTypeException(typeMirror) }.`when`(annotation).converter try { attributeConverterChecker.getQualifiedConverterName(element, annotation) fail("Processing Exception expected") } catch (e: ProcessingException) { assertEquals( "TypeConverter class com.tickaroo.tikxml.processor.converter.NoParameterLessConstructorTypeConverter must provide an empty (parameter-less) public constructor", e.message) } } private class PrivateVisibilityTypeConverter : TypeConverter<Any> { @Throws(Exception::class) override fun read(value: String): Any? { return null } @Throws(Exception::class) override fun write(value: Any): String? { return null } } }
apache-2.0
7a3ca5a1c497f3657356e1355d8aff3c
34.567657
168
0.738864
4.772365
false
false
false
false
McMoonLakeDev/MoonLake
API/src/main/kotlin/com/mcmoonlake/api/reflect/ClassSource.kt
1
2551
/* * ProtocolLib - Bukkit server library that allows access to the Minecraft protocol. * Copyright (C) 2012 Kristian S. Stangeland * * This program is free software; you can redistribute it and/or modify it under the terms of the * GNU General Public License as published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program; * if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA * 02111-1307 USA */ /* * Copyright (C) 2016-Present The MoonLake ([email protected]) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.mcmoonlake.api.reflect abstract class ClassSource { /** api */ @Throws(ClassNotFoundException::class) abstract fun loadClass(name: String): Class<*> /** static */ companion object { @JvmStatic @JvmName("fromClassLoader") fun fromClassLoader(): ClassSource = fromClassLoader(ClassSource::class.java.classLoader) @JvmStatic @JvmName("fromClassLoader") fun fromClassLoader(classLoader: ClassLoader): ClassSource = object: ClassSource() { override fun loadClass(name: String): Class<*> = classLoader.loadClass(name) } @JvmStatic @JvmName("fromMap") fun fromMap(map: Map<String, Class<*>>): ClassSource = object: ClassSource() { override fun loadClass(name: String): Class<*> = map[name] ?: throw ClassNotFoundException("指定类没有存在此 Map 中.") } } }
gpl-3.0
0e8173c38a1bcf4259800f441ff184b0
36.80597
98
0.689301
4.436077
false
false
false
false
dahlstrom-g/intellij-community
platform/workspaceModel/storage/testEntities/testSrc/com/intellij/workspaceModel/storage/entities/test/api/TreeEntity.kt
3
1682
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.workspaceModel.storage.entities.test.api import com.intellij.workspaceModel.storage.WorkspaceEntity import org.jetbrains.deft.annotations.Child import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity import com.intellij.workspaceModel.storage.MutableEntityStorage import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type interface TreeEntity : WorkspaceEntity { val data: String val children: List<@Child TreeEntity> val parentEntity: TreeEntity //region generated code //@formatter:off @GeneratedCodeApiVersion(1) interface Builder: TreeEntity, ModifiableWorkspaceEntity<TreeEntity>, ObjBuilder<TreeEntity> { override var data: String override var entitySource: EntitySource override var children: List<TreeEntity> override var parentEntity: TreeEntity } companion object: Type<TreeEntity, Builder>() { operator fun invoke(data: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): TreeEntity { val builder = builder() builder.data = data builder.entitySource = entitySource init?.invoke(builder) return builder } } //@formatter:on //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: TreeEntity, modification: TreeEntity.Builder.() -> Unit) = modifyEntity(TreeEntity.Builder::class.java, entity, modification) //endregion
apache-2.0
07bcc89657aae084691b7a06ecce0981
36.4
171
0.763971
4.976331
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/extractionEngine/extractableAnalysisUtil.kt
2
40442
// 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.refactoring.introduce.extractionEngine import com.intellij.psi.PsiElement import com.intellij.psi.PsiNamedElement import com.intellij.psi.util.PsiTreeUtil import com.intellij.refactoring.util.RefactoringUIUtil import com.intellij.util.containers.MultiMap import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.cfg.containingDeclarationForPseudocode import org.jetbrains.kotlin.cfg.pseudocode.* import org.jetbrains.kotlin.cfg.pseudocode.instructions.Instruction import org.jetbrains.kotlin.cfg.pseudocode.instructions.InstructionVisitorWithResult import org.jetbrains.kotlin.cfg.pseudocode.instructions.InstructionWithNext import org.jetbrains.kotlin.cfg.pseudocode.instructions.KtElementInstruction import org.jetbrains.kotlin.cfg.pseudocode.instructions.eval.* import org.jetbrains.kotlin.cfg.pseudocode.instructions.jumps.* import org.jetbrains.kotlin.cfg.pseudocode.instructions.special.LocalFunctionDeclarationInstruction import org.jetbrains.kotlin.cfg.pseudocode.instructions.special.MarkInstruction import org.jetbrains.kotlin.cfg.pseudocodeTraverser.TraversalOrder import org.jetbrains.kotlin.cfg.pseudocodeTraverser.TraverseInstructionResult import org.jetbrains.kotlin.cfg.pseudocodeTraverser.traverse import org.jetbrains.kotlin.cfg.pseudocodeTraverser.traverseFollowingInstructions import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.descriptors.annotations.AnnotationDescriptor import org.jetbrains.kotlin.descriptors.impl.LocalVariableDescriptor import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.base.codeInsight.KotlinNameSuggestionProvider import org.jetbrains.kotlin.idea.base.fe10.codeInsight.newDeclaration.Fe10KotlinNameSuggester import org.jetbrains.kotlin.idea.base.fe10.codeInsight.newDeclaration.Fe10KotlinNewDeclarationNameValidator import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithContent import org.jetbrains.kotlin.idea.caches.resolve.findModuleDescriptor import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde import org.jetbrains.kotlin.idea.core.compareDescriptors import org.jetbrains.kotlin.idea.refactoring.createTempCopy import org.jetbrains.kotlin.idea.refactoring.introduce.extractionEngine.AnalysisResult.ErrorMessage import org.jetbrains.kotlin.idea.refactoring.introduce.extractionEngine.AnalysisResult.Status import org.jetbrains.kotlin.idea.refactoring.introduce.extractionEngine.OutputValue.* import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.idea.util.* import org.jetbrains.kotlin.lexer.KtModifierKeywordToken import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.renderer.DescriptorRenderer import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsStatement import org.jetbrains.kotlin.resolve.calls.util.getCalleeExpressionIfAny import org.jetbrains.kotlin.resolve.checkers.OptInNames import org.jetbrains.kotlin.resolve.descriptorUtil.annotationClass import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe import org.jetbrains.kotlin.resolve.descriptorUtil.getImportableDescriptor import org.jetbrains.kotlin.resolve.scopes.LexicalScope import org.jetbrains.kotlin.types.* import org.jetbrains.kotlin.types.error.ErrorUtils import org.jetbrains.kotlin.types.typeUtil.makeNullable import org.jetbrains.kotlin.util.capitalizeDecapitalize.capitalizeAsciiOnly import org.jetbrains.kotlin.utils.DFS.* import org.jetbrains.kotlin.utils.addToStdlib.safeAs import java.util.* internal val KotlinBuiltIns.defaultReturnType: KotlinType get() = unitType internal val KotlinBuiltIns.defaultParameterType: KotlinType get() = nullableAnyType private fun DeclarationDescriptor.renderForMessage(): String { return IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.render(this) } private val TYPE_RENDERER = DescriptorRenderer.FQ_NAMES_IN_TYPES.withOptions { typeNormalizer = IdeDescriptorRenderers.APPROXIMATE_FLEXIBLE_TYPES } private fun KotlinType.renderForMessage(): String = TYPE_RENDERER.renderType(this) private fun KtDeclaration.renderForMessage(bindingContext: BindingContext): String? = bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, this]?.renderForMessage() private fun List<Instruction>.getModifiedVarDescriptors(bindingContext: BindingContext): Map<VariableDescriptor, List<KtExpression>> { val result = HashMap<VariableDescriptor, MutableList<KtExpression>>() for (instruction in filterIsInstance<WriteValueInstruction>()) { val expression = instruction.element as? KtExpression val descriptor = PseudocodeUtil.extractVariableDescriptorIfAny(instruction, bindingContext) if (expression != null && descriptor != null) { result.getOrPut(descriptor) { ArrayList() }.add(expression) } } return result } private fun List<Instruction>.getVarDescriptorsAccessedAfterwards(bindingContext: BindingContext): Set<VariableDescriptor> { val accessedAfterwards = HashSet<VariableDescriptor>() val visitedInstructions = HashSet<Instruction>() fun doTraversal(instruction: Instruction) { traverseFollowingInstructions(instruction, visitedInstructions) { when { it is AccessValueInstruction && it !in this -> PseudocodeUtil.extractVariableDescriptorIfAny( it, bindingContext )?.let { descriptor -> accessedAfterwards.add(descriptor) } it is LocalFunctionDeclarationInstruction -> doTraversal(it.body.enterInstruction) } TraverseInstructionResult.CONTINUE } } forEach(::doTraversal) return accessedAfterwards } private fun List<Instruction>.getExitPoints(): List<Instruction> = filter { localInstruction -> localInstruction.nextInstructions.any { it !in this } } private fun ExtractionData.getResultTypeAndExpressions( instructions: List<Instruction>, bindingContext: BindingContext, targetScope: LexicalScope?, options: ExtractionOptions, module: ModuleDescriptor ): Pair<KotlinType, List<KtExpression>> { fun instructionToExpression(instruction: Instruction, unwrapReturn: Boolean): KtExpression? { return when (instruction) { is ReturnValueInstruction -> (if (unwrapReturn) null else instruction.returnExpressionIfAny) ?: instruction.returnedValue.element as? KtExpression is InstructionWithValue -> instruction.outputValue?.element as? KtExpression else -> null } } fun instructionToType(instruction: Instruction): KotlinType? { val expression = instructionToExpression(instruction, true) ?: return null substringInfo?.let { if (it.template == expression) return it.type } if (options.inferUnitTypeForUnusedValues && expression.isUsedAsStatement(bindingContext)) return null return bindingContext.getType(expression) ?: (expression as? KtReferenceExpression)?.let { (bindingContext[BindingContext.REFERENCE_TARGET, it] as? CallableDescriptor)?.returnType } } val resultTypes = instructions.mapNotNull(::instructionToType) val commonSupertype = if (resultTypes.isNotEmpty()) CommonSupertypes.commonSupertype(resultTypes) else module.builtIns.defaultReturnType val resultType = commonSupertype.approximateWithResolvableType(targetScope, false) val expressions = instructions.mapNotNull { instructionToExpression(it, false) } return resultType to expressions } private fun getCommonNonTrivialSuccessorIfAny(instructions: List<Instruction>): Instruction? { val singleSuccessorCheckingVisitor = object : InstructionVisitorWithResult<Boolean>() { var target: Instruction? = null override fun visitInstructionWithNext(instruction: InstructionWithNext): Boolean { return when (instruction) { is LoadUnitValueInstruction, is MergeInstruction, is MarkInstruction -> { instruction.next?.accept(this) ?: true } else -> visitInstruction(instruction) } } override fun visitJump(instruction: AbstractJumpInstruction): Boolean { return when (instruction) { is ConditionalJumpInstruction -> visitInstruction(instruction) else -> instruction.resolvedTarget?.accept(this) ?: true } } override fun visitInstruction(instruction: Instruction): Boolean { if (target != null && target != instruction) return false target = instruction return true } } if (instructions.flatMap { it.nextInstructions }.any { !it.accept(singleSuccessorCheckingVisitor) }) return null return singleSuccessorCheckingVisitor.target ?: instructions.firstOrNull()?.owner?.sinkInstruction } private fun KotlinType.isMeaningful(): Boolean { return !KotlinBuiltIns.isUnit(this) && !KotlinBuiltIns.isNothing(this) } private fun ExtractionData.getLocalDeclarationsWithNonLocalUsages( pseudocode: Pseudocode, localInstructions: List<Instruction>, bindingContext: BindingContext ): List<KtNamedDeclaration> { val declarations = HashSet<KtNamedDeclaration>() pseudocode.traverse(TraversalOrder.FORWARD) { instruction -> if (instruction !in localInstructions) { instruction.getPrimaryDeclarationDescriptorIfAny(bindingContext)?.let { descriptor -> val declaration = DescriptorToSourceUtilsIde.getAnyDeclaration(project, descriptor) if (declaration is KtNamedDeclaration && declaration.isInsideOf(physicalElements)) { declarations.add(declaration) } } } } return declarations.sortedBy { it.textRange!!.startOffset } } private fun ExtractionData.analyzeControlFlow( localInstructions: List<Instruction>, pseudocode: Pseudocode, module: ModuleDescriptor, bindingContext: BindingContext, modifiedVarDescriptors: Map<VariableDescriptor, List<KtExpression>>, options: ExtractionOptions, targetScope: LexicalScope?, parameters: Set<Parameter> ): Pair<ControlFlow, ErrorMessage?> { val exitPoints = localInstructions.getExitPoints() val valuedReturnExits = ArrayList<ReturnValueInstruction>() val defaultExits = ArrayList<Instruction>() val jumpExits = ArrayList<AbstractJumpInstruction>() exitPoints.forEach { val e = (it as? UnconditionalJumpInstruction)?.element when (val inst = when { it !is ReturnValueInstruction && it !is ReturnNoValueInstruction && it.owner != pseudocode -> null it is UnconditionalJumpInstruction && it.targetLabel.isJumpToError -> it e != null && e !is KtBreakExpression && e !is KtContinueExpression -> it.previousInstructions.firstOrNull() else -> it }) { is ReturnValueInstruction -> if (inst.owner == pseudocode) { if (inst.returnExpressionIfAny == null) { defaultExits.add(inst) } else { valuedReturnExits.add(inst) } } is AbstractJumpInstruction -> { val element = inst.element if ((element is KtReturnExpression && inst.owner == pseudocode) || element is KtBreakExpression || element is KtContinueExpression ) jumpExits.add(inst) else if (element !is KtThrowExpression && !inst.targetLabel.isJumpToError) defaultExits.add(inst) } else -> if (inst != null && inst !is LocalFunctionDeclarationInstruction) defaultExits.add(inst) } } val nonLocallyUsedDeclarations = getLocalDeclarationsWithNonLocalUsages(pseudocode, localInstructions, bindingContext) val (declarationsToCopy, declarationsToReport) = nonLocallyUsedDeclarations.partition { it is KtProperty && it.isLocal } val (typeOfDefaultFlow, defaultResultExpressions) = getResultTypeAndExpressions( defaultExits, bindingContext, targetScope, options, module ) val (returnValueType, valuedReturnExpressions) = getResultTypeAndExpressions( valuedReturnExits, bindingContext, targetScope, options, module ) val emptyControlFlow = ControlFlow(Collections.emptyList(), { OutputValueBoxer.AsTuple(it, module) }, declarationsToCopy) val defaultReturnType = if (returnValueType.isMeaningful()) returnValueType else typeOfDefaultFlow if (defaultReturnType.isError) return emptyControlFlow to ErrorMessage.ERROR_TYPES val controlFlow = if (defaultReturnType.isMeaningful()) { emptyControlFlow.copy(outputValues = Collections.singletonList(ExpressionValue(false, defaultResultExpressions, defaultReturnType))) } else emptyControlFlow if (declarationsToReport.isNotEmpty()) { val localVarStr = declarationsToReport.map { it.renderForMessage(bindingContext)!! }.distinct().sorted() return controlFlow to ErrorMessage.DECLARATIONS_ARE_USED_OUTSIDE.addAdditionalInfo(localVarStr) } val outParameters = parameters.filter { it.mirrorVarName != null && modifiedVarDescriptors[it.originalDescriptor] != null }.sortedBy { it.nameForRef } val outDeclarations = declarationsToCopy.filter { modifiedVarDescriptors[bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, it]] != null } val modifiedValueCount = outParameters.size + outDeclarations.size val outputValues = ArrayList<OutputValue>() val multipleExitsError = controlFlow to ErrorMessage.MULTIPLE_EXIT_POINTS val outputAndExitsError = controlFlow to ErrorMessage.OUTPUT_AND_EXIT_POINT if (typeOfDefaultFlow.isMeaningful()) { if (valuedReturnExits.isNotEmpty() || jumpExits.isNotEmpty()) return multipleExitsError outputValues.add(ExpressionValue(false, defaultResultExpressions, typeOfDefaultFlow)) } else if (valuedReturnExits.isNotEmpty()) { if (jumpExits.isNotEmpty()) return multipleExitsError if (defaultExits.isNotEmpty()) { if (modifiedValueCount != 0) return outputAndExitsError if (valuedReturnExits.size != 1) return multipleExitsError val element = valuedReturnExits.first().element as KtExpression return controlFlow.copy(outputValues = Collections.singletonList(Jump(listOf(element), element, true, module.builtIns))) to null } if (getCommonNonTrivialSuccessorIfAny(valuedReturnExits) == null) return multipleExitsError outputValues.add(ExpressionValue(true, valuedReturnExpressions, returnValueType)) } outDeclarations.mapTo(outputValues) { val descriptor = bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, it] as? CallableDescriptor Initializer(it as KtProperty, descriptor?.returnType ?: module.builtIns.defaultParameterType) } outParameters.mapTo(outputValues) { ParameterUpdate(it, modifiedVarDescriptors[it.originalDescriptor]!!) } if (outputValues.isNotEmpty()) { if (jumpExits.isNotEmpty()) return outputAndExitsError val boxerFactory: (List<OutputValue>) -> OutputValueBoxer = when { outputValues.size > 3 -> { if (!options.enableListBoxing) { val outValuesStr = (outParameters.map { it.originalDescriptor.renderForMessage() } + outDeclarations.map { it.renderForMessage(bindingContext)!! }).sorted() return controlFlow to ErrorMessage.MULTIPLE_OUTPUT.addAdditionalInfo(outValuesStr) } { values -> OutputValueBoxer.AsList(values) } } else -> controlFlow.boxerFactory } return controlFlow.copy(outputValues = outputValues, boxerFactory = boxerFactory) to null } if (jumpExits.isNotEmpty()) { val jumpTarget = getCommonNonTrivialSuccessorIfAny(jumpExits) ?: return multipleExitsError val singleExit = getCommonNonTrivialSuccessorIfAny(defaultExits) == jumpTarget val conditional = !singleExit && defaultExits.isNotEmpty() val elements = jumpExits.map { it.element as KtExpression } val elementToInsertAfterCall = if (singleExit) null else elements.first() return controlFlow.copy( outputValues = Collections.singletonList( Jump( elements, elementToInsertAfterCall, conditional, module.builtIns ) ) ) to null } return controlFlow to null } fun ExtractionData.createTemporaryDeclaration(pattern: String): KtNamedDeclaration { val targetSiblingMarker = Any() PsiTreeUtil.mark(targetSibling, targetSiblingMarker) val tmpFile = originalFile.createTempCopy("") tmpFile.deleteChildRange(tmpFile.firstChild, tmpFile.lastChild) tmpFile.addRange(originalFile.firstChild, originalFile.lastChild) val newTargetSibling = PsiTreeUtil.releaseMark(tmpFile, targetSiblingMarker)!! val newTargetParent = newTargetSibling.parent val declaration = KtPsiFactory(originalFile).createDeclarationByPattern<KtNamedDeclaration>( pattern, PsiChildRange(originalElements.firstOrNull(), originalElements.lastOrNull()) ) return if (insertBefore) { newTargetParent.addBefore(declaration, newTargetSibling) as KtNamedDeclaration } else { newTargetParent.addAfter(declaration, newTargetSibling) as KtNamedDeclaration } } internal fun ExtractionData.createTemporaryCodeBlock(): KtBlockExpression { if (options.extractAsProperty) { return ((createTemporaryDeclaration("val = {\n$0\n}\n") as KtProperty).initializer as KtLambdaExpression).bodyExpression!! } return (createTemporaryDeclaration("fun() {\n$0\n}\n") as KtNamedFunction).bodyBlockExpression!! } private fun KotlinType.collectReferencedTypes(processTypeArguments: Boolean): List<KotlinType> { if (!processTypeArguments) return Collections.singletonList(this) return dfsFromNode( this, Neighbors<KotlinType> { current -> current.arguments.map { it.type } }, VisitedWithSet(), object : CollectingNodeHandler<KotlinType, KotlinType, ArrayList<KotlinType>>(ArrayList()) { override fun afterChildren(current: KotlinType) { result.add(current) } } )!! } fun KtTypeParameter.collectRelevantConstraints(): List<KtTypeConstraint> { val typeConstraints = getNonStrictParentOfType<KtTypeParameterListOwner>()?.typeConstraints ?: return Collections.emptyList() return typeConstraints.filter { it.subjectTypeParameterName?.mainReference?.resolve() == this } } fun TypeParameter.collectReferencedTypes(bindingContext: BindingContext): List<KotlinType> { val typeRefs = ArrayList<KtTypeReference>() originalDeclaration.extendsBound?.let { typeRefs.add(it) } originalConstraints.mapNotNullTo(typeRefs) { it.boundTypeReference } return typeRefs.mapNotNull { bindingContext[BindingContext.TYPE, it] } } private fun KotlinType.isExtractable(targetScope: LexicalScope?): Boolean { return collectReferencedTypes(true).fold(true) { extractable, typeToCheck -> val parameterTypeDescriptor = typeToCheck.constructor.declarationDescriptor as? TypeParameterDescriptor val typeParameter = parameterTypeDescriptor?.let { DescriptorToSourceUtils.descriptorToDeclaration(it) } as? KtTypeParameter extractable && (typeParameter != null || typeToCheck.isResolvableInScope(targetScope, false)) } } internal fun KotlinType.processTypeIfExtractable( typeParameters: MutableSet<TypeParameter>, nonDenotableTypes: MutableSet<KotlinType>, options: ExtractionOptions, targetScope: LexicalScope?, processTypeArguments: Boolean = true ): Boolean { return collectReferencedTypes(processTypeArguments).fold(true) { extractable, typeToCheck -> val parameterTypeDescriptor = typeToCheck.constructor.declarationDescriptor as? TypeParameterDescriptor val typeParameter = parameterTypeDescriptor?.let { DescriptorToSourceUtils.descriptorToDeclaration(it) } as? KtTypeParameter when { typeToCheck.isResolvableInScope(targetScope, true) -> extractable typeParameter != null -> { typeParameters.add(TypeParameter(typeParameter, typeParameter.collectRelevantConstraints())) extractable } typeToCheck.isError -> false else -> { nonDenotableTypes.add(typeToCheck) false } } } } internal class MutableParameter( override val argumentText: String, override val originalDescriptor: DeclarationDescriptor, override val receiverCandidate: Boolean, private val targetScope: LexicalScope?, private val originalType: KotlinType, private val possibleTypes: Set<KotlinType> ) : Parameter { // All modifications happen in the same thread private var writable: Boolean = true private val defaultTypes = LinkedHashSet<KotlinType>() private val typePredicates = HashSet<TypePredicate>() var refCount: Int = 0 fun addDefaultType(kotlinType: KotlinType) { assert(writable) { "Can't add type to non-writable parameter $currentName" } if (kotlinType in possibleTypes) { defaultTypes.add(kotlinType) } } fun addTypePredicate(predicate: TypePredicate) { assert(writable) { "Can't add type predicate to non-writable parameter $currentName" } typePredicates.add(predicate) } var currentName: String? = null override val name: String get() = currentName!! override var mirrorVarName: String? = null private val defaultType: KotlinType by lazy { writable = false if (defaultTypes.isNotEmpty()) { TypeIntersector.intersectTypes(defaultTypes)!! } else originalType } private val allParameterTypeCandidates: List<KotlinType> by lazy { writable = false val typePredicate = and(typePredicates) val typeSet = if (defaultType.isFlexible()) { val bounds = defaultType.asFlexibleType() LinkedHashSet<KotlinType>().apply { if (typePredicate(bounds.upperBound)) add(bounds.upperBound) if (typePredicate(bounds.lowerBound)) add(bounds.lowerBound) } } else linkedSetOf(defaultType) val addNullableTypes = defaultType.isNullabilityFlexible() && typeSet.size > 1 val superTypes = TypeUtils.getAllSupertypes(defaultType).filter(typePredicate) for (superType in superTypes) { if (addNullableTypes) { typeSet.add(superType.makeNullable()) } typeSet.add(superType) } typeSet.toList() } override fun getParameterTypeCandidates(): List<KotlinType> { return allParameterTypeCandidates.filter { it.isExtractable(targetScope) } } override val parameterType: KotlinType get() = getParameterTypeCandidates().firstOrNull() ?: defaultType override fun copy(name: String, parameterType: KotlinType): Parameter = DelegatingParameter(this, name, parameterType) } private class DelegatingParameter( val original: Parameter, override val name: String, override val parameterType: KotlinType ) : Parameter by original { override fun copy(name: String, parameterType: KotlinType): Parameter = DelegatingParameter(original, name, parameterType) } private fun ExtractionData.checkDeclarationsMovingOutOfScope( enclosingDeclaration: KtDeclaration, controlFlow: ControlFlow, bindingContext: BindingContext ): ErrorMessage? { val declarationsOutOfScope = HashSet<KtNamedDeclaration>() controlFlow.jumpOutputValue?.elementToInsertAfterCall?.accept( object : KtTreeVisitorVoid() { override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) { val target = expression.mainReference.resolve() if (target is KtNamedDeclaration && target.isInsideOf(physicalElements) && target.getStrictParentOfType<KtDeclaration>() == enclosingDeclaration ) { declarationsOutOfScope.add(target) } } } ) if (declarationsOutOfScope.isNotEmpty()) { val declStr = declarationsOutOfScope.map { it.renderForMessage(bindingContext)!! }.sorted() return ErrorMessage.DECLARATIONS_OUT_OF_SCOPE.addAdditionalInfo(declStr) } return null } private fun ExtractionData.getLocalInstructions(pseudocode: Pseudocode): List<Instruction> { val instructions = ArrayList<Instruction>() pseudocode.traverse(TraversalOrder.FORWARD) { if (it is KtElementInstruction && it.element.isInsideOf(physicalElements)) { instructions.add(it) } } return instructions } fun ExtractionData.isLocal(): Boolean { val parent = targetSibling.parent return parent !is KtClassBody && (parent !is KtFile || parent.isScript()) } fun ExtractionData.isVisibilityApplicable(): Boolean { if (isLocal()) return false if (commonParent.parentsWithSelf.any { it is KtNamedFunction && it.hasModifier(KtTokens.INLINE_KEYWORD) && it.isPublic }) return false return true } fun ExtractionData.getDefaultVisibility(): KtModifierKeywordToken? { if (!isVisibilityApplicable()) return null val parent = targetSibling.getStrictParentOfType<KtDeclaration>() if (parent is KtClass) { if (parent.isInterface()) return null if (parent.isEnum() && commonParent.getNonStrictParentOfType<KtEnumEntry>()?.getStrictParentOfType<KtClass>() == parent) return null } return KtTokens.PRIVATE_KEYWORD } private data class ExperimentalMarkers( val propagatingMarkerDescriptors: List<AnnotationDescriptor>, val optInMarkers: List<FqName> ) { companion object { val empty = ExperimentalMarkers(emptyList(), emptyList()) } } private fun ExtractionData.getExperimentalMarkers(): ExperimentalMarkers { fun AnnotationDescriptor.isExperimentalMarker(): Boolean { if (fqName == null) return false val annotations = annotationClass?.annotations ?: return false return annotations.hasAnnotation(OptInNames.REQUIRES_OPT_IN_FQ_NAME) || annotations.hasAnnotation(OptInNames.OLD_EXPERIMENTAL_FQ_NAME) } val bindingContext = bindingContext ?: return ExperimentalMarkers.empty val container = commonParent.getStrictParentOfType<KtNamedFunction>() ?: return ExperimentalMarkers.empty val propagatingMarkerDescriptors = mutableListOf<AnnotationDescriptor>() val optInMarkerNames = mutableListOf<FqName>() for (annotationEntry in container.annotationEntries) { val annotationDescriptor = bindingContext[BindingContext.ANNOTATION, annotationEntry] ?: continue val fqName = annotationDescriptor.fqName ?: continue if (fqName in OptInNames.USE_EXPERIMENTAL_FQ_NAMES) { for (argument in annotationEntry.valueArguments) { val argumentExpression = argument.getArgumentExpression()?.safeAs<KtClassLiteralExpression>() ?: continue val markerFqName = bindingContext[ BindingContext.REFERENCE_TARGET, argumentExpression.lhs?.safeAs<KtNameReferenceExpression>() ]?.fqNameSafe ?: continue optInMarkerNames.add(markerFqName) } } else if (annotationDescriptor.isExperimentalMarker()) { propagatingMarkerDescriptors.add(annotationDescriptor) } } val requiredMarkers = mutableSetOf<FqName>() if (propagatingMarkerDescriptors.isNotEmpty() || optInMarkerNames.isNotEmpty()) { originalElements.forEach { element -> element.accept(object : KtTreeVisitorVoid() { override fun visitReferenceExpression(expression: KtReferenceExpression) { val descriptor = bindingContext[BindingContext.REFERENCE_TARGET, expression] if (descriptor != null) { for (descr in setOf(descriptor, descriptor.getImportableDescriptor())) { for (ann in descr.annotations) { val fqName = ann.fqName ?: continue if (ann.isExperimentalMarker()) { requiredMarkers.add(fqName) } } } } super.visitReferenceExpression(expression) } }) } } return ExperimentalMarkers( propagatingMarkerDescriptors.filter { it.fqName in requiredMarkers }, optInMarkerNames.filter { it in requiredMarkers } ) } fun ExtractionData.performAnalysis(): AnalysisResult { if (originalElements.isEmpty()) return AnalysisResult(null, Status.CRITICAL_ERROR, listOf(ErrorMessage.NO_EXPRESSION)) val noContainerError = AnalysisResult(null, Status.CRITICAL_ERROR, listOf(ErrorMessage.NO_CONTAINER)) val bindingContext = bindingContext ?: return noContainerError val declaration = commonParent.containingDeclarationForPseudocode ?: return noContainerError val pseudocode = declaration.getContainingPseudocode(bindingContext) ?: return AnalysisResult(null, Status.CRITICAL_ERROR, listOf(ErrorMessage.SYNTAX_ERRORS)) val localInstructions = getLocalInstructions(pseudocode) val modifiedVarDescriptorsWithExpressions = localInstructions.getModifiedVarDescriptors(bindingContext) val virtualBlock = createTemporaryCodeBlock() val targetScope = targetSibling.getResolutionScope(bindingContext, commonParent.getResolutionFacade()) val paramsInfo = inferParametersInfo( virtualBlock, commonParent, pseudocode, bindingContext, targetScope, modifiedVarDescriptorsWithExpressions.keys ) if (paramsInfo.errorMessage != null) { return AnalysisResult(null, Status.CRITICAL_ERROR, listOf(paramsInfo.errorMessage!!)) } val messages = ArrayList<ErrorMessage>() val modifiedVarDescriptorsForControlFlow = HashMap(modifiedVarDescriptorsWithExpressions) modifiedVarDescriptorsForControlFlow.keys.retainAll(localInstructions.getVarDescriptorsAccessedAfterwards(bindingContext)) val (controlFlow, controlFlowMessage) = analyzeControlFlow( localInstructions, pseudocode, originalFile.findModuleDescriptor(), bindingContext, modifiedVarDescriptorsForControlFlow, options, targetScope, paramsInfo.parameters ) controlFlowMessage?.let { messages.add(it) } val returnType = controlFlow.outputValueBoxer.returnType returnType.processTypeIfExtractable(paramsInfo.typeParameters, paramsInfo.nonDenotableTypes, options, targetScope) if (paramsInfo.nonDenotableTypes.isNotEmpty()) { val typeStr = paramsInfo.nonDenotableTypes.map { it.renderForMessage() }.sorted() return AnalysisResult( null, Status.CRITICAL_ERROR, listOf(ErrorMessage.DENOTABLE_TYPES.addAdditionalInfo(typeStr)) ) } val enclosingDeclaration = commonParent.getStrictParentOfType<KtDeclaration>()!! checkDeclarationsMovingOutOfScope(enclosingDeclaration, controlFlow, bindingContext)?.let { messages.add(it) } controlFlow.jumpOutputValue?.elementToInsertAfterCall?.accept( object : KtTreeVisitorVoid() { override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) { paramsInfo.originalRefToParameter[expression].firstOrNull()?.let { it.refCount-- } } } ) val adjustedParameters = paramsInfo.parameters.filterTo(LinkedHashSet<Parameter>()) { it.refCount > 0 } val receiverCandidates = adjustedParameters.filterTo(hashSetOf()) { it.receiverCandidate } val receiverParameter = if (receiverCandidates.size == 1 && !options.canWrapInWith) receiverCandidates.first() else null receiverParameter?.let { adjustedParameters.remove(it) } val experimentalMarkers = getExperimentalMarkers() var descriptor = ExtractableCodeDescriptor( this, bindingContext, suggestFunctionNames(returnType), getDefaultVisibility(), adjustedParameters.toList(), receiverParameter, paramsInfo.typeParameters.sortedBy { it.originalDeclaration.name!! }, paramsInfo.replacementMap, if (messages.isEmpty()) controlFlow else controlFlow.toDefault(), returnType, emptyList(), annotations = experimentalMarkers.propagatingMarkerDescriptors, optInMarkers = experimentalMarkers.optInMarkers ) val generatedDeclaration = ExtractionGeneratorConfiguration( descriptor, ExtractionGeneratorOptions(inTempFile = true, allowExpressionBody = false) ).generateDeclaration().declaration val virtualContext = generatedDeclaration.analyzeWithContent() if (virtualContext.diagnostics.all() .any { it.factory == Errors.ILLEGAL_SUSPEND_FUNCTION_CALL || it.factory == Errors.ILLEGAL_SUSPEND_PROPERTY_ACCESS } ) { descriptor = descriptor.copy(modifiers = listOf(KtTokens.SUSPEND_KEYWORD)) } for (analyser in AdditionalExtractableAnalyser.EP_NAME.extensions) { descriptor = analyser.amendDescriptor(descriptor) } return AnalysisResult( descriptor, if (messages.isEmpty()) Status.SUCCESS else Status.NON_CRITICAL_ERROR, messages ) } private fun ExtractionData.suggestFunctionNames(returnType: KotlinType): List<String> { val functionNames = LinkedHashSet<String>() val validator = Fe10KotlinNewDeclarationNameValidator( targetSibling.parent, if (targetSibling is KtAnonymousInitializer) targetSibling.parent else targetSibling, when { options.extractAsProperty -> KotlinNameSuggestionProvider.ValidatorTarget.VARIABLE else -> KotlinNameSuggestionProvider.ValidatorTarget.FUNCTION } ) if (!KotlinBuiltIns.isUnit(returnType)) { functionNames.addAll(Fe10KotlinNameSuggester.suggestNamesByType(returnType, validator)) } expressions.singleOrNull()?.let { expr -> val property = expr.getStrictParentOfType<KtProperty>() if (property?.initializer == expr) { property.name?.let { functionNames.add(Fe10KotlinNameSuggester.suggestNameByName("get" + it.capitalizeAsciiOnly(), validator)) } } } return functionNames.toList() } internal fun KtNamedDeclaration.getGeneratedBody() = when (this) { is KtNamedFunction -> bodyExpression else -> { val property = this as KtProperty property.getter?.bodyExpression?.let { return it } property.initializer?.let { return it } // We assume lazy property here with delegate expression 'by Delegates.lazy { body }' property.delegateExpression?.let { val call = it.getCalleeExpressionIfAny()?.parent as? KtCallExpression call?.lambdaArguments?.singleOrNull()?.getLambdaExpression()?.bodyExpression } } } ?: throw AssertionError("Couldn't get block body for this declaration: ${getElementTextWithContext()}") @JvmOverloads fun ExtractableCodeDescriptor.validate(target: ExtractionTarget = ExtractionTarget.FUNCTION): ExtractableCodeDescriptorWithConflicts { fun getDeclarationMessage(declaration: PsiElement, messageKey: String, capitalize: Boolean = true): String { val declarationStr = RefactoringUIUtil.getDescription(declaration, true) val message = KotlinBundle.message(messageKey, declarationStr) return if (capitalize) message.capitalize() else message } val conflicts = MultiMap<PsiElement, String>() val result = ExtractionGeneratorConfiguration( this, ExtractionGeneratorOptions(inTempFile = true, allowExpressionBody = false, target = target) ).generateDeclaration() val valueParameterList = (result.declaration as? KtNamedFunction)?.valueParameterList val typeParameterList = (result.declaration as? KtNamedFunction)?.typeParameterList val generatedDeclaration = result.declaration val bindingContext = generatedDeclaration.analyzeWithContent() fun processReference(currentRefExpr: KtSimpleNameExpression) { val resolveResult = currentRefExpr.resolveResult ?: return if (currentRefExpr.parent is KtThisExpression) return val diagnostics = bindingContext.diagnostics.forElement(currentRefExpr) val currentDescriptor = bindingContext[BindingContext.REFERENCE_TARGET, currentRefExpr] val currentTarget = currentDescriptor?.let { DescriptorToSourceUtilsIde.getAnyDeclaration(extractionData.project, it) } as? PsiNamedElement if (currentTarget is KtParameter && currentTarget.parent == valueParameterList) return if (currentTarget is KtTypeParameter && currentTarget.parent == typeParameterList) return if (currentDescriptor is LocalVariableDescriptor && parameters.any { it.mirrorVarName == currentDescriptor.name.asString() } ) return if (diagnostics.any { it.factory in Errors.UNRESOLVED_REFERENCE_DIAGNOSTICS } || (currentDescriptor != null && !ErrorUtils.isError(currentDescriptor) && !compareDescriptors(extractionData.project, currentDescriptor, resolveResult.descriptor))) { conflicts.putValue( resolveResult.originalRefExpr, getDeclarationMessage(resolveResult.declaration, "0.will.no.longer.be.accessible.after.extraction") ) return } diagnostics.firstOrNull { it.factory in Errors.INVISIBLE_REFERENCE_DIAGNOSTICS }?.let { val message = when (it.factory) { Errors.INVISIBLE_SETTER -> getDeclarationMessage(resolveResult.declaration, "setter.of.0.will.become.invisible.after.extraction", false) else -> getDeclarationMessage(resolveResult.declaration, "0.will.become.invisible.after.extraction") } conflicts.putValue(resolveResult.originalRefExpr, message) } } result.declaration.accept( object : KtTreeVisitorVoid() { override fun visitUserType(userType: KtUserType) { val refExpr = userType.referenceExpression ?: return val diagnostics = bindingContext.diagnostics.forElement(refExpr) diagnostics.firstOrNull { it.factory == Errors.INVISIBLE_REFERENCE }?.let { val declaration = refExpr.mainReference.resolve() as? PsiNamedElement ?: return conflicts.putValue(declaration, getDeclarationMessage(declaration, "0.will.become.invisible.after.extraction")) } } override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) { processReference(expression) } } ) return ExtractableCodeDescriptorWithConflicts(this, conflicts) }
apache-2.0
1096fec9ef85c0904814a079f6202ba3
43.198907
158
0.710004
5.414647
false
false
false
false
dahlstrom-g/intellij-community
plugins/evaluation-plugin/src/com/intellij/cce/dialog/EvaluateHereSettingsDialog.kt
4
1983
package com.intellij.cce.dialog import com.intellij.cce.EvaluationPluginBundle import com.intellij.cce.workspace.Config import com.intellij.cce.workspace.ConfigFactory import com.intellij.ide.util.PropertiesComponent import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogWrapper import com.intellij.util.EventDispatcher import javax.swing.BoxLayout import javax.swing.JComponent import javax.swing.JPanel class EvaluateHereSettingsDialog( private val project: Project, private val language: String, private val path: String ) : DialogWrapper(true) { companion object { const val configStateKey = "com.intellij.cce.config.evaluate_here" } private val dispatcher = EventDispatcher.create(SettingsListener::class.java) private val properties = PropertiesComponent.getInstance(project) private val configurators: List<EvaluationConfigurable> = listOf( CompletionTypeConfigurable(), ContextConfigurable(), PrefixConfigurable(), FiltersConfigurable(dispatcher, language), FilteringOnInterpretationConfigurable() ) init { init() title = EvaluationPluginBundle.message("evaluation.settings.title") } override fun createCenterPanel(): JComponent { return JPanel().apply { layout = BoxLayout(this, BoxLayout.Y_AXIS) val value = properties.getValue(configStateKey) val previousState = try { if (value == null) ConfigFactory.defaultConfig(project.basePath!!) else ConfigFactory.deserialize(value) } catch (e: Throwable) { ConfigFactory.defaultConfig(project.basePath!!) } configurators.forEach { add(it.createPanel(previousState)) } } } fun buildConfig(): Config { val config = Config.build(project.basePath!!, language) { configurators.forEach { it.configure(this) } evaluationRoots = mutableListOf(path) } properties.setValue(configStateKey, ConfigFactory.serialize(config)) return config } }
apache-2.0
fbe12e6597fd5a2c90c24ff74a91eb70
29.984375
79
0.74584
4.676887
false
true
false
false
github/codeql
java/ql/test/kotlin/library-tests/exprs/funcExprs.kt
1
4184
fun functionExpression0a(f: () -> Int) { f() } fun functionExpression0b(f: () -> Any?) { f() } fun functionExpression0c(f: () -> Any) { f() } fun functionExpression1a(x: Int, f: (Int) -> Int) { f(x) } fun functionExpression1b(x: Int, f: (Any?) -> Any?) { f(x) } fun functionExpression1c(x: Int, f: (FuncRef, Int) -> Int) { f(FuncRef(), x) } fun functionExpression2(x: Int, f: (Int, Int) -> Int) { f(x, x) } fun functionExpression3(x: Int, f: Int.(Int) -> Int) { x.f(x) } fun functionExpression4(x: Int, f: (Int) -> ((Int) -> Double)) { f(x)(x) } fun functionExpression22(x: Int, f: (Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int) -> Unit) { f(x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x) } fun functionExpression23(x: Int, f: (Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int) -> String) { f(x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x) } fun functionExpression23c(x: Int, f: (FuncRef, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int) -> String) { f(FuncRef(),x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x) } fun call() { functionExpression0a { -> 5 } functionExpression0b { -> 5 } functionExpression0c { -> 5 } functionExpression1a(5) { a -> 5 } functionExpression1a(5) { it } functionExpression1a(5, fun(_:Int) = 5) functionExpression1a(5, MyLambda()) functionExpression1b(5) { a -> a} functionExpression2(5, fun(_: Int, _: Int) = 5) functionExpression2(5) { _, _ -> 5 } functionExpression3(5) { a -> this + a } functionExpression4(5) { a -> ( { b -> 5.0} ) } functionExpression22(5) {a0,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15,a16,a17,a18,a19,a20,a21 -> 5} functionExpression23(5) {a0,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15,a16,a17,a18,a19,a20,a21,a22 -> ""} functionExpression0a(FuncRef()::f0) functionExpression0a(FuncRef::f0) functionExpression1a(5, FuncRef()::f1) functionExpression1c(5, FuncRef::f1) functionExpression1a(5, 3::f3) functionExpression3(5, Int::f3) functionExpression22(5, FuncRef()::f22) functionExpression23(5, FuncRef()::f23) functionExpression23c(5, FuncRef::f23) fun local(): Int = 5 functionExpression0a(::local) fn(::FuncRef) } class MyLambda: (Int) -> Int { override operator fun invoke(x: Int): Int = 5 } fun <T> fn(l: () -> T) {} fun Int.f3(a: Int) = 5 class FuncRef { companion object { fun f0(): Int = 5 } fun f0(): Int = 5 fun f1(a: Int): Int = 5 fun f22(a0: Int, a1: Int, a2: Int, a3: Int, a4: Int, a5: Int, a6: Int, a7: Int, a8: Int, a9: Int, a10: Int, a11: Int, a12: Int, a13: Int, a14: Int, a15: Int, a16:Int, a17: Int, a18: Int, a19: Int, a20: Int, a21: Int) {} fun f23(a0: Int, a1: Int, a2: Int, a3: Int, a4: Int, a5: Int, a6: Int, a7: Int, a8: Int, a9: Int, a10: Int, a11: Int, a12: Int, a13: Int, a14: Int, a15: Int, a16:Int, a17: Int, a18: Int, a19: Int, a20: Int, a21: Int, a22: Int) = "" } class Class3 { fun call() { fn { a -> "a"} } private fun fn(f: (Generic<Generic<Int>>) -> String) { } class Generic<T> { } } suspend fun fn() { val l1: (Int) -> String = { i -> i.toString() } l1.invoke(5) // calls kotlin/jvm/functions/Function1.invoke val l2: suspend (Int) -> String = { i -> i.toString() } l2.invoke(5) // calls kotlin/jvm/functions/Function2.invoke val l3: (Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int) -> String = { _,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_ -> ""} l3.invoke(1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3) // 23 args, calls kotlin/jvm/functions/FunctionN.invoke val l4: suspend (Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int) -> String = { _,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_ -> ""} l4.invoke(1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2) // 22 args, calls kotlin/jvm/functions/FunctionN.invoke }
mit
ea64882ee275c8f7378e9fca7154a48c
42.583333
174
0.577438
2.334821
false
false
false
false
millross/pac4j-async
vertx-pac4j-async-demo/src/test/kotlin/org/pac4j/async/vertx/profile/direct/TestProfile.kt
1
881
package org.pac4j.async.vertx.profile.direct import org.pac4j.async.vertx.FIELD_EMAIL import org.pac4j.async.vertx.FIELD_USER_ID import org.pac4j.core.profile.CommonProfile /** * */ class TestProfile(userId: String, email: String): CommonProfile() { companion object { fun from(credentials: TestCredentials): TestProfile { return TestProfile(credentials.userId, credentials.email) } } init { super.setId(userId) super.addAttribute(FIELD_EMAIL, email) } override fun equals(that: Any?): Boolean { if (that !is TestProfile) return false val other = that as TestProfile? return this.id === other!!.id && this.getAttribute(FIELD_EMAIL) === other!!.getAttribute(FIELD_EMAIL) && this.getAttribute(FIELD_USER_ID) === other!!.getAttribute(FIELD_USER_ID) } }
apache-2.0
07e8010f3ec96552a70fb311501e9b46
27.451613
91
0.648127
3.864035
false
true
false
false
zbeboy/ISY
src/main/java/top/zbeboy/isy/service/data/OrganizeServiceImpl.kt
1
19478
package top.zbeboy.isy.service.data import org.jooq.* import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Propagation import org.springframework.transaction.annotation.Transactional import org.springframework.util.ObjectUtils import org.springframework.util.StringUtils import top.zbeboy.isy.domain.Tables.* import top.zbeboy.isy.domain.tables.daos.OrganizeDao import top.zbeboy.isy.domain.tables.pojos.Organize import top.zbeboy.isy.domain.tables.records.OrganizeRecord import top.zbeboy.isy.service.common.MethodServiceCommon import top.zbeboy.isy.service.plugin.DataTablesPlugin import top.zbeboy.isy.service.util.SQLQueryUtils import top.zbeboy.isy.web.bean.data.organize.OrganizeBean import top.zbeboy.isy.web.util.DataTablesUtils import java.util.* import javax.annotation.Resource /** * Created by zbeboy 2017-12-03 . **/ @Service("organizeService") @Transactional(propagation = Propagation.SUPPORTS, readOnly = true) open class OrganizeServiceImpl @Autowired constructor(dslContext: DSLContext) : DataTablesPlugin<OrganizeBean>(), OrganizeService { private val create: DSLContext = dslContext @Resource open lateinit var organizeDao: OrganizeDao @Resource open lateinit var methodServiceCommon: MethodServiceCommon override fun findByScienceIdAndDistinctGradeAndIsDel(scienceId: Int, b: Byte?): Result<Record1<String>> { return create.selectDistinct<String>(ORGANIZE.GRADE) .from(ORGANIZE) .where(ORGANIZE.SCIENCE_ID.eq(scienceId).and(ORGANIZE.ORGANIZE_IS_DEL.eq(b))) .orderBy(ORGANIZE.ORGANIZE_ID.desc()) .limit(0, 6) .fetch() } override fun findInScienceIdsAndGradeAndIsDel(scienceIds: List<Int>, grade: String, b: Byte?): Result<OrganizeRecord> { return create.selectFrom<OrganizeRecord>(ORGANIZE) .where(ORGANIZE.SCIENCE_ID.`in`(scienceIds).and(ORGANIZE.GRADE.eq(grade)).and(ORGANIZE.ORGANIZE_IS_DEL.eq(b))) .fetch() } override fun findByScienceIdAndGradeAndIsDel(scienceId: Int, grade: String, b: Byte?): Result<OrganizeRecord> { return create.selectFrom<OrganizeRecord>(ORGANIZE) .where(ORGANIZE.SCIENCE_ID.eq(scienceId).and(ORGANIZE.GRADE.eq(grade)).and(ORGANIZE.ORGANIZE_IS_DEL.eq(b))) .fetch() } override fun findByScienceId(scienceId: Int): List<Organize> { return organizeDao.fetchByScienceId(scienceId) } override fun findByDepartmentIdAndDistinctGrade(departmentId: Int): Result<Record1<String>> { return create.selectDistinct<String>(ORGANIZE.GRADE) .from(ORGANIZE) .join(SCIENCE) .on(ORGANIZE.SCIENCE_ID.eq(SCIENCE.SCIENCE_ID)) .join(DEPARTMENT) .on(SCIENCE.DEPARTMENT_ID.eq(DEPARTMENT.DEPARTMENT_ID)) .where(DEPARTMENT.DEPARTMENT_ID.eq(departmentId).and(ORGANIZE.ORGANIZE_IS_DEL.eq(0))) .orderBy(ORGANIZE.GRADE.desc()) .limit(0, 6) .fetch() } override fun findByOrganizeNameAndScienceIdNeOrganizeId(organizeName: String, organizeId: Int, scienceId: Int): Result<OrganizeRecord> { return create.selectFrom<OrganizeRecord>(ORGANIZE) .where(ORGANIZE.ORGANIZE_NAME.eq(organizeName).and(ORGANIZE.SCIENCE_ID.eq(scienceId)).and(ORGANIZE.ORGANIZE_ID.ne(organizeId))) .fetch() } override fun findByGradeAndScienceId(grade: String, scienceId: Int): Result<OrganizeRecord> { return create.selectFrom<OrganizeRecord>(ORGANIZE) .where(ORGANIZE.ORGANIZE_IS_DEL.eq(0).and(ORGANIZE.GRADE.eq(grade)).and(ORGANIZE.SCIENCE_ID.eq(scienceId))) .fetch() } override fun findByGradeAndScienceIdNotIsDel(grade: String, scienceId: Int): Result<OrganizeRecord> { return create.selectFrom<OrganizeRecord>(ORGANIZE) .where(ORGANIZE.GRADE.eq(grade).and(ORGANIZE.SCIENCE_ID.eq(scienceId))) .fetch() } @Transactional(propagation = Propagation.REQUIRED, readOnly = false) override fun save(organize: Organize) { organizeDao.insert(organize) } override fun update(organize: Organize) { organizeDao.update(organize) } override fun updateIsDel(ids: List<Int>, isDel: Byte?) { ids.forEach { id -> create.update<OrganizeRecord>(ORGANIZE).set<Byte>(ORGANIZE.ORGANIZE_IS_DEL, isDel).where(ORGANIZE.ORGANIZE_ID.eq(id)).execute() } } override fun findByIdRelation(id: Int): Optional<Record> { return create.select() .from(ORGANIZE) .join(SCIENCE) .on(ORGANIZE.SCIENCE_ID.eq(SCIENCE.SCIENCE_ID)) .join(DEPARTMENT) .on(SCIENCE.DEPARTMENT_ID.eq(DEPARTMENT.DEPARTMENT_ID)) .join(COLLEGE) .on(DEPARTMENT.COLLEGE_ID.eq(COLLEGE.COLLEGE_ID)) .join(SCHOOL) .on(COLLEGE.SCHOOL_ID.eq(SCHOOL.SCHOOL_ID)) .where(ORGANIZE.ORGANIZE_ID.eq(id)) .fetchOptional() } override fun findById(id: Int): Organize { return organizeDao.findById(id) } override fun findAllByPage(dataTablesUtils: DataTablesUtils<OrganizeBean>): Result<Record> { val a = searchCondition(dataTablesUtils) val roleCondition = buildOrganizeCondition() return if (ObjectUtils.isEmpty(a)) { if (ObjectUtils.isEmpty(roleCondition)) { val selectJoinStep = create.select() .from(ORGANIZE) .join(SCIENCE) .on(ORGANIZE.SCIENCE_ID.eq(SCIENCE.SCIENCE_ID)) .join(DEPARTMENT) .on(SCIENCE.DEPARTMENT_ID.eq(DEPARTMENT.DEPARTMENT_ID)) .join(COLLEGE) .on(DEPARTMENT.COLLEGE_ID.eq(COLLEGE.COLLEGE_ID)) .join(SCHOOL) .on(COLLEGE.SCHOOL_ID.eq(SCHOOL.SCHOOL_ID)) sortCondition(dataTablesUtils, null, selectJoinStep, DataTablesPlugin.JOIN_TYPE) pagination(dataTablesUtils, null, selectJoinStep, DataTablesPlugin.JOIN_TYPE) selectJoinStep.fetch() } else { val selectConditionStep = create.select() .from(ORGANIZE) .join(SCIENCE) .on(ORGANIZE.SCIENCE_ID.eq(SCIENCE.SCIENCE_ID)) .join(DEPARTMENT) .on(SCIENCE.DEPARTMENT_ID.eq(DEPARTMENT.DEPARTMENT_ID)) .join(COLLEGE) .on(DEPARTMENT.COLLEGE_ID.eq(COLLEGE.COLLEGE_ID)) .join(SCHOOL) .on(COLLEGE.SCHOOL_ID.eq(SCHOOL.SCHOOL_ID)) .where(roleCondition) sortCondition(dataTablesUtils, selectConditionStep, null, DataTablesPlugin.CONDITION_TYPE) pagination(dataTablesUtils, selectConditionStep, null, DataTablesPlugin.CONDITION_TYPE) selectConditionStep.fetch() } } else { if (ObjectUtils.isEmpty(roleCondition)) { val selectConditionStep = create.select() .from(ORGANIZE) .join(SCIENCE) .on(ORGANIZE.SCIENCE_ID.eq(SCIENCE.SCIENCE_ID)) .join(DEPARTMENT) .on(SCIENCE.DEPARTMENT_ID.eq(DEPARTMENT.DEPARTMENT_ID)) .join(COLLEGE) .on(DEPARTMENT.COLLEGE_ID.eq(COLLEGE.COLLEGE_ID)) .join(SCHOOL) .on(COLLEGE.SCHOOL_ID.eq(SCHOOL.SCHOOL_ID)) .where(a) sortCondition(dataTablesUtils, selectConditionStep, null, DataTablesPlugin.CONDITION_TYPE) pagination(dataTablesUtils, selectConditionStep, null, DataTablesPlugin.CONDITION_TYPE) selectConditionStep.fetch() } else { val selectConditionStep = create.select() .from(ORGANIZE) .join(SCIENCE) .on(ORGANIZE.SCIENCE_ID.eq(SCIENCE.SCIENCE_ID)) .join(DEPARTMENT) .on(SCIENCE.DEPARTMENT_ID.eq(DEPARTMENT.DEPARTMENT_ID)) .join(COLLEGE) .on(DEPARTMENT.COLLEGE_ID.eq(COLLEGE.COLLEGE_ID)) .join(SCHOOL) .on(COLLEGE.SCHOOL_ID.eq(SCHOOL.SCHOOL_ID)) .where(roleCondition!!.and(a)) sortCondition(dataTablesUtils, selectConditionStep, null, DataTablesPlugin.CONDITION_TYPE) pagination(dataTablesUtils, selectConditionStep, null, DataTablesPlugin.CONDITION_TYPE) selectConditionStep.fetch() } } } override fun countAll(): Int { val roleCondition = buildOrganizeCondition() return if (ObjectUtils.isEmpty(roleCondition)) { statisticsAll(create, ORGANIZE) } else { create.selectCount() .from(ORGANIZE) .join(SCIENCE) .on(ORGANIZE.SCIENCE_ID.eq(SCIENCE.SCIENCE_ID)) .join(DEPARTMENT) .on(SCIENCE.DEPARTMENT_ID.eq(DEPARTMENT.DEPARTMENT_ID)) .join(COLLEGE) .on(DEPARTMENT.COLLEGE_ID.eq(COLLEGE.COLLEGE_ID)) .where(roleCondition) .fetchOne().value1() } } override fun countByCondition(dataTablesUtils: DataTablesUtils<OrganizeBean>): Int { val count: Record1<Int> val a = searchCondition(dataTablesUtils) val roleCondition = buildOrganizeCondition() count = if (ObjectUtils.isEmpty(a)) { if (ObjectUtils.isEmpty(roleCondition)) { create.selectCount() .from(ORGANIZE).fetchOne() } else { create.selectCount() .from(ORGANIZE) .join(SCIENCE) .on(ORGANIZE.SCIENCE_ID.eq(SCIENCE.SCIENCE_ID)) .join(DEPARTMENT) .on(SCIENCE.DEPARTMENT_ID.eq(DEPARTMENT.DEPARTMENT_ID)) .join(COLLEGE) .on(DEPARTMENT.COLLEGE_ID.eq(COLLEGE.COLLEGE_ID)) .where(roleCondition).fetchOne() } } else { if (ObjectUtils.isEmpty(roleCondition)) { create.selectCount() .from(ORGANIZE) .join(SCIENCE) .on(ORGANIZE.SCIENCE_ID.eq(SCIENCE.SCIENCE_ID)) .join(DEPARTMENT) .on(SCIENCE.DEPARTMENT_ID.eq(DEPARTMENT.DEPARTMENT_ID)) .join(COLLEGE) .on(DEPARTMENT.COLLEGE_ID.eq(COLLEGE.COLLEGE_ID)) .join(SCHOOL) .on(COLLEGE.SCHOOL_ID.eq(SCHOOL.SCHOOL_ID)) .where(a).fetchOne() } else { create.selectCount() .from(ORGANIZE) .join(SCIENCE) .on(ORGANIZE.SCIENCE_ID.eq(SCIENCE.SCIENCE_ID)) .join(DEPARTMENT) .on(SCIENCE.DEPARTMENT_ID.eq(DEPARTMENT.DEPARTMENT_ID)) .join(COLLEGE) .on(DEPARTMENT.COLLEGE_ID.eq(COLLEGE.COLLEGE_ID)) .join(SCHOOL) .on(COLLEGE.SCHOOL_ID.eq(SCHOOL.SCHOOL_ID)) .where(roleCondition!!.and(a)).fetchOne() } } return count.value1() } override fun findByOrganizeNameAndScienceId(organizeName: String, scienceId: Int): Result<OrganizeRecord> { return create.selectFrom<OrganizeRecord>(ORGANIZE) .where(ORGANIZE.ORGANIZE_NAME.eq(organizeName).and(ORGANIZE.SCIENCE_ID.eq(scienceId))) .fetch() } /** * 班级数据全局搜索条件 * * @param dataTablesUtils datatables工具类 * @return 搜索条件 */ override fun searchCondition(dataTablesUtils: DataTablesUtils<OrganizeBean>): Condition? { var a: Condition? = null val search = dataTablesUtils.search if (!ObjectUtils.isEmpty(search)) { val schoolName = StringUtils.trimWhitespace(search!!.getString("schoolName")) val collegeName = StringUtils.trimWhitespace(search.getString("collegeName")) val departmentName = StringUtils.trimWhitespace(search.getString("departmentName")) val scienceName = StringUtils.trimWhitespace(search.getString("scienceName")) val grade = StringUtils.trimWhitespace(search.getString("grade")) val organizeName = StringUtils.trimWhitespace(search.getString("organizeName")) if (StringUtils.hasLength(schoolName)) { a = SCHOOL.SCHOOL_NAME.like(SQLQueryUtils.likeAllParam(schoolName)) } if (StringUtils.hasLength(collegeName)) { a = if (ObjectUtils.isEmpty(a)) { COLLEGE.COLLEGE_NAME.like(SQLQueryUtils.likeAllParam(collegeName)) } else { a!!.and(COLLEGE.COLLEGE_NAME.like(SQLQueryUtils.likeAllParam(collegeName))) } } if (StringUtils.hasLength(departmentName)) { a = if (ObjectUtils.isEmpty(a)) { DEPARTMENT.DEPARTMENT_NAME.like(SQLQueryUtils.likeAllParam(departmentName)) } else { a!!.and(DEPARTMENT.DEPARTMENT_NAME.like(SQLQueryUtils.likeAllParam(departmentName))) } } if (StringUtils.hasLength(scienceName)) { a = if (ObjectUtils.isEmpty(a)) { SCIENCE.SCIENCE_NAME.like(SQLQueryUtils.likeAllParam(scienceName)) } else { a!!.and(SCIENCE.SCIENCE_NAME.like(SQLQueryUtils.likeAllParam(scienceName))) } } if (StringUtils.hasLength(grade)) { a = if (ObjectUtils.isEmpty(a)) { ORGANIZE.GRADE.like(SQLQueryUtils.likeAllParam(grade)) } else { a!!.and(ORGANIZE.GRADE.like(SQLQueryUtils.likeAllParam(grade))) } } if (StringUtils.hasLength(organizeName)) { a = if (ObjectUtils.isEmpty(a)) { ORGANIZE.ORGANIZE_NAME.like(SQLQueryUtils.likeAllParam(organizeName)) } else { a!!.and(ORGANIZE.ORGANIZE_NAME.like(SQLQueryUtils.likeAllParam(organizeName))) } } } return a } /** * 班级数据排序 * * @param dataTablesUtils datatables工具类 * @param selectConditionStep 条件 */ override fun sortCondition(dataTablesUtils: DataTablesUtils<OrganizeBean>, selectConditionStep: SelectConditionStep<Record>?, selectJoinStep: SelectJoinStep<Record>?, type: Int) { val orderColumnName = dataTablesUtils.orderColumnName val orderDir = dataTablesUtils.orderDir val isAsc = "asc".equals(orderDir, ignoreCase = true) var sortField: Array<SortField<*>?>? = null if (StringUtils.hasLength(orderColumnName)) { if ("organize_id".equals(orderColumnName!!, ignoreCase = true)) { sortField = arrayOfNulls(1) if (isAsc) { sortField[0] = ORGANIZE.ORGANIZE_ID.asc() } else { sortField[0] = ORGANIZE.ORGANIZE_ID.desc() } } if ("school_name".equals(orderColumnName, ignoreCase = true)) { sortField = arrayOfNulls(2) if (isAsc) { sortField[0] = SCHOOL.SCHOOL_NAME.asc() sortField[1] = ORGANIZE.ORGANIZE_ID.asc() } else { sortField[0] = SCHOOL.SCHOOL_NAME.desc() sortField[1] = ORGANIZE.ORGANIZE_ID.desc() } } if ("college_name".equals(orderColumnName, ignoreCase = true)) { sortField = arrayOfNulls(2) if (isAsc) { sortField[0] = COLLEGE.COLLEGE_NAME.asc() sortField[1] = ORGANIZE.ORGANIZE_ID.asc() } else { sortField[0] = COLLEGE.COLLEGE_NAME.desc() sortField[1] = ORGANIZE.ORGANIZE_ID.desc() } } if ("department_name".equals(orderColumnName, ignoreCase = true)) { sortField = arrayOfNulls(2) if (isAsc) { sortField[0] = DEPARTMENT.DEPARTMENT_NAME.asc() sortField[1] = ORGANIZE.ORGANIZE_ID.asc() } else { sortField[0] = DEPARTMENT.DEPARTMENT_NAME.desc() sortField[1] = ORGANIZE.ORGANIZE_ID.desc() } } if ("science_name".equals(orderColumnName, ignoreCase = true)) { sortField = arrayOfNulls(2) if (isAsc) { sortField[0] = SCIENCE.SCIENCE_NAME.asc() sortField[1] = ORGANIZE.ORGANIZE_ID.asc() } else { sortField[0] = SCIENCE.SCIENCE_NAME.desc() sortField[1] = ORGANIZE.ORGANIZE_ID.desc() } } if ("grade".equals(orderColumnName, ignoreCase = true)) { sortField = arrayOfNulls(2) if (isAsc) { sortField[0] = ORGANIZE.GRADE.asc() sortField[1] = ORGANIZE.ORGANIZE_ID.asc() } else { sortField[0] = ORGANIZE.GRADE.desc() sortField[1] = ORGANIZE.ORGANIZE_ID.desc() } } if ("organize_name".equals(orderColumnName, ignoreCase = true)) { sortField = arrayOfNulls(1) if (isAsc) { sortField[0] = ORGANIZE.ORGANIZE_NAME.asc() } else { sortField[0] = ORGANIZE.ORGANIZE_NAME.desc() } } if ("organize_is_del".equals(orderColumnName, ignoreCase = true)) { sortField = arrayOfNulls(2) if (isAsc) { sortField[0] = ORGANIZE.ORGANIZE_IS_DEL.asc() sortField[1] = ORGANIZE.ORGANIZE_ID.asc() } else { sortField[0] = ORGANIZE.ORGANIZE_IS_DEL.desc() sortField[1] = ORGANIZE.ORGANIZE_ID.desc() } } } sortToFinish(selectConditionStep, selectJoinStep, type, *sortField!!) } /** * 构建该角色查询条件 */ private fun buildOrganizeCondition(): Condition? { return methodServiceCommon.buildDepartmentCondition() } }
mit
d6df0e49b7f986d6150a33242b525993
42.902715
183
0.560142
4.471998
false
false
false
false
seratch/jslack
slack-api-model-kotlin-extension/src/main/kotlin/com/slack/api/model/kotlin_extension/block/element/RadioButtonsElementBuilder.kt
1
3026
package com.slack.api.model.kotlin_extension.block.element import com.slack.api.model.block.composition.ConfirmationDialogObject import com.slack.api.model.block.composition.OptionObject import com.slack.api.model.block.element.RadioButtonsElement import com.slack.api.model.kotlin_extension.block.BlockLayoutBuilder import com.slack.api.model.kotlin_extension.block.Builder import com.slack.api.model.kotlin_extension.block.composition.ConfirmationDialogObjectBuilder import com.slack.api.model.kotlin_extension.block.composition.OptionObjectBuilder import com.slack.api.model.kotlin_extension.block.composition.container.MultiOptionContainer import com.slack.api.model.kotlin_extension.block.composition.dsl.OptionObjectDsl @BlockLayoutBuilder class RadioButtonsElementBuilder : Builder<RadioButtonsElement> { private var actionId: String? = null private var options: List<OptionObject>? = null private var initialOption: OptionObject? = null private var confirm: ConfirmationDialogObject? = null /** * An identifier for the action triggered when the radio button group is changed. You can use this when you * receive an interaction payload to identify the source of the action. Should be unique among all other * action_ids used elsewhere by your app. Maximum length for this field is 255 characters. * * @see <a href="https://api.slack.com/reference/block-kit/block-elements#radio">Radio buttons element documentation</a> */ fun actionId(id: String) { actionId = id } /** * An array of option objects. * * @see <a href="https://api.slack.com/reference/block-kit/block-elements#radio">Radio buttons element documentation</a> */ fun options(builder: OptionObjectDsl.() -> Unit) { options = MultiOptionContainer().apply(builder).underlying } /** * An option object that exactly matches one of the options within options. This option will be selected when the * radio button group initially loads. * * @see <a href="https://api.slack.com/reference/block-kit/block-elements#radio">Radio buttons element documentation</a> */ fun initialOption(builder: OptionObjectBuilder.() -> Unit) { initialOption = OptionObjectBuilder().apply(builder).build() } /** * A confirm object that defines an optional confirmation dialog that appears after clicking one of the radio * buttons in this element. * * @see <a href="https://api.slack.com/reference/block-kit/block-elements#radio">Radio buttons element documentation</a> */ fun confirm(builder: ConfirmationDialogObjectBuilder.() -> Unit) { confirm = ConfirmationDialogObjectBuilder().apply(builder).build() } override fun build(): RadioButtonsElement { return RadioButtonsElement.builder() .actionId(actionId) .options(options) .initialOption(initialOption) .confirm(confirm) .build() } }
mit
f6fb06e47331b9397f05a334ed22cf4a
43.514706
124
0.719101
4.366522
false
false
false
false
google/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/checkin/CodeCleanupCheckinHandler.kt
1
5772
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.vcs.checkin import com.intellij.analysis.AnalysisScope import com.intellij.codeInsight.FileModificationService import com.intellij.codeInspection.CommonProblemDescriptor import com.intellij.codeInspection.InspectionManager import com.intellij.codeInspection.InspectionProfile import com.intellij.codeInspection.actions.PerformFixesTask import com.intellij.codeInspection.ex.CleanupProblems import com.intellij.codeInspection.ex.GlobalInspectionContextImpl import com.intellij.lang.LangBundle import com.intellij.openapi.command.CommandProcessor import com.intellij.openapi.command.CommandProcessorEx import com.intellij.openapi.command.UndoConfirmationPolicy import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.ProgressSink import com.intellij.openapi.progress.progressSink import com.intellij.openapi.progress.runUnderIndicator import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.CheckinProjectPanel import com.intellij.openapi.vcs.VcsBundle.message import com.intellij.openapi.vcs.VcsConfiguration import com.intellij.openapi.vcs.changes.CommitContext import com.intellij.openapi.vcs.checkin.CheckinHandlerUtil.filterOutGeneratedAndExcludedFiles import com.intellij.openapi.vcs.ui.RefreshableOnComponent import com.intellij.profile.codeInspection.InspectionProfileManager import com.intellij.profile.codeInspection.InspectionProjectProfileManager import com.intellij.util.SequentialModalProgressTask import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import kotlin.coroutines.coroutineContext class CodeCleanupCheckinHandlerFactory : CheckinHandlerFactory() { override fun createHandler(panel: CheckinProjectPanel, commitContext: CommitContext): CheckinHandler = CodeCleanupCheckinHandler(panel) } private class CodeCleanupCheckinHandler(private val panel: CheckinProjectPanel) : CheckinHandler(), CommitCheck { private val project = panel.project private val settings get() = VcsConfiguration.getInstance(project) override fun getBeforeCheckinConfigurationPanel(): RefreshableOnComponent = ProfileChooser(panel, settings::CHECK_CODE_CLEANUP_BEFORE_PROJECT_COMMIT, settings::CHECK_CODE_CLEANUP_BEFORE_PROJECT_COMMIT_LOCAL, settings::CHECK_CODE_CLEANUP_BEFORE_PROJECT_COMMIT_PROFILE, "before.checkin.cleanup.code", "before.checkin.cleanup.code.profile") override fun getExecutionOrder(): CommitCheck.ExecutionOrder = CommitCheck.ExecutionOrder.MODIFICATION override fun isEnabled(): Boolean = settings.CHECK_CODE_CLEANUP_BEFORE_PROJECT_COMMIT override suspend fun runCheck(): CommitProblem? { val sink = coroutineContext.progressSink sink?.text(message("progress.text.inspecting.code")) val cleanupProblems = findProblems() sink?.text(message("progress.text.applying.fixes")) sink?.details("") applyFixes(cleanupProblems) return null } private suspend fun findProblems(): CleanupProblems { val files = filterOutGeneratedAndExcludedFiles(panel.virtualFiles, project) val globalContext = InspectionManager.getInstance(project).createNewGlobalContext() as GlobalInspectionContextImpl val profile = getProfile() val scope = AnalysisScope(project, files) return withContext(Dispatchers.Default + textToDetailsSinkContext(coroutineContext.progressSink)) { runUnderIndicator { val indicator = ProgressManager.getGlobalProgressIndicator() globalContext.findProblems(scope, profile, indicator) { true } } } } private fun getProfile(): InspectionProfile { val cleanupProfile = settings.CHECK_CODE_CLEANUP_BEFORE_PROJECT_COMMIT_PROFILE if (cleanupProfile != null) { val profileManager = if (settings.CHECK_CODE_CLEANUP_BEFORE_PROJECT_COMMIT_LOCAL) InspectionProfileManager.getInstance() else InspectionProjectProfileManager.getInstance(project) return profileManager.getProfile(cleanupProfile) } return InspectionProjectProfileManager.getInstance(project).currentProfile } private suspend fun applyFixes(cleanupProblems: CleanupProblems) { if (cleanupProblems.files.isEmpty()) return if (!FileModificationService.getInstance().preparePsiElementsForWrite(cleanupProblems.files)) return val commandProcessor = CommandProcessor.getInstance() as CommandProcessorEx commandProcessor.executeCommand { if (cleanupProblems.isGlobalScope) commandProcessor.markCurrentCommandAsGlobal(project) val sink = coroutineContext.progressSink val runner = SequentialModalProgressTask(project, "", true) runner.setMinIterationTime(200) runner.setTask(ApplyFixesTask(project, cleanupProblems.problemDescriptors, sink)) withContext(Dispatchers.IO + noTextSinkContext(sink)) { runUnderIndicator { // TODO get rid of SequentialModalProgressTask runner.doRun(ProgressManager.getGlobalProgressIndicator()) } } } } private suspend fun CommandProcessorEx.executeCommand(block: suspend () -> Unit) { val commandToken = startCommand(project, LangBundle.message("code.cleanup"), null, UndoConfirmationPolicy.DEFAULT)!! try { block() } finally { finishCommand(commandToken, null) } } } private class ApplyFixesTask(project: Project, descriptors: List<CommonProblemDescriptor>, private val sink: ProgressSink?) : PerformFixesTask(project, descriptors, null) { override fun beforeProcessing(descriptor: CommonProblemDescriptor) { sink?.update(details = getPresentableText(descriptor)) } }
apache-2.0
736cd62f8e2a234eb69e1804e226850b
42.734848
137
0.790887
5.049869
false
false
false
false
RuneSuite/client
updater-mapper/src/main/java/org/runestar/client/updater/mapper/std/classes/LoginProt.kt
1
750
package org.runestar.client.updater.mapper.std.classes import org.runestar.client.updater.mapper.IdentityMapper import org.runestar.client.updater.mapper.DependsOn import org.runestar.client.updater.mapper.and import org.runestar.client.updater.mapper.predicateOf import org.runestar.client.updater.mapper.Class2 import org.runestar.client.updater.mapper.Field2 import org.objectweb.asm.Type.* @DependsOn(ClientProt0::class) class LoginProt : IdentityMapper.Class() { override val predicate = predicateOf<Class2> { it.interfaces.contains(type<ClientProt0>()) } .and { it.instanceFields.size == 1 } class id : IdentityMapper.InstanceField() { override val predicate = predicateOf<Field2> { it.type == INT_TYPE } } }
mit
d1b6c141995b26de28868086cded8ecb
36.55
96
0.766667
3.865979
false
false
false
false
google/intellij-community
platform/platform-impl/src/com/intellij/ui/dsl/builder/textField.kt
1
5020
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ui.dsl.builder import com.intellij.openapi.Disposable import com.intellij.openapi.observable.properties.GraphProperty import com.intellij.openapi.observable.properties.ObservableMutableProperty import com.intellij.openapi.observable.util.lockOrSkip import com.intellij.openapi.observable.util.transform import com.intellij.openapi.observable.util.whenTextChanged import com.intellij.openapi.ui.validation.DialogValidation import com.intellij.openapi.ui.validation.forTextComponent import com.intellij.openapi.ui.validation.trimParameter import com.intellij.ui.dsl.ValidationException import com.intellij.ui.dsl.builder.impl.CellImpl.Companion.installValidationRequestor import com.intellij.ui.dsl.catchValidationException import com.intellij.ui.dsl.stringToInt import com.intellij.ui.dsl.validateIntInRange import com.intellij.ui.layout.* import com.intellij.util.containers.map2Array import org.jetbrains.annotations.ApiStatus import java.util.concurrent.atomic.AtomicBoolean import javax.swing.JTextField import javax.swing.text.JTextComponent import kotlin.reflect.KMutableProperty0 import com.intellij.openapi.observable.util.whenTextChangedFromUi as whenTextChangedFromUiImpl /** * Columns for text components with tiny width. Used for [Row.intTextField] by default */ const val COLUMNS_TINY = 6 /** * Columns for text components with short width (used instead of deprecated [GrowPolicy.SHORT_TEXT]) */ const val COLUMNS_SHORT = 18 /** * Columns for text components with medium width (used instead of deprecated [GrowPolicy.MEDIUM_TEXT]) */ const val COLUMNS_MEDIUM = 25 const val COLUMNS_LARGE = 36 fun <T : JTextComponent> Cell<T>.bindText(property: ObservableMutableProperty<String>): Cell<T> { installValidationRequestor(property) return applyToComponent { bind(property) } } fun <T : JTextComponent> Cell<T>.bindText(prop: KMutableProperty0<String>): Cell<T> { return bindText(prop.toMutableProperty()) } fun <T : JTextComponent> Cell<T>.bindText(getter: () -> String, setter: (String) -> Unit): Cell<T> { return bindText(MutableProperty(getter, setter)) } fun <T : JTextComponent> Cell<T>.bindText(prop: MutableProperty<String>): Cell<T> { return bind(JTextComponent::getText, JTextComponent::setText, prop) } fun <T : JTextComponent> Cell<T>.bindIntText(property: ObservableMutableProperty<Int>): Cell<T> { installValidationRequestor(property) return applyToComponent { bind(property.transform({ it.toString() }, { component.getValidatedIntValue(it) })) } } fun <T : JTextComponent> Cell<T>.bindIntText(prop: KMutableProperty0<Int>): Cell<T> { return bindIntText(prop.toMutableProperty()) } fun <T : JTextComponent> Cell<T>.bindIntText(getter: () -> Int, setter: (Int) -> Unit): Cell<T> { return bindIntText(MutableProperty(getter, setter)) } fun <T : JTextComponent> Cell<T>.text(text: String): Cell<T> { component.text = text return this } /** * Minimal width of text field in chars * * @see COLUMNS_TINY * @see COLUMNS_SHORT * @see COLUMNS_MEDIUM * @see COLUMNS_LARGE */ fun <T : JTextField> Cell<T>.columns(columns: Int) = apply { component.columns(columns) } fun <T : JTextField> T.columns(columns: Int) = apply { this.columns = columns } @Throws(ValidationException::class) private fun JTextComponent.getValidatedIntValue(value: String): Int { val result = stringToInt(value) val range = getClientProperty(DSL_INT_TEXT_RANGE_PROPERTY) as? IntRange range?.let { validateIntInRange(result, it) } return result } private fun JTextComponent.bind(property: ObservableMutableProperty<String>) { text = property.get() // See: IDEA-238573 removed cyclic update of UI components that bound with properties val mutex = AtomicBoolean() property.afterChange { mutex.lockOrSkip { text = it } } whenTextChanged { mutex.lockOrSkip { // Catch transformed GraphProperties, e.g. for intTextField catchValidationException { property.set(text) } } } } private fun <T : JTextComponent> Cell<T>.bindIntText(prop: MutableProperty<Int>): Cell<T> { return bindText({ prop.get().toString() }, { value -> catchValidationException { prop.set(component.getValidatedIntValue(value)) } }) } fun <T : JTextComponent> Cell<T>.trimmedTextValidation(vararg validations: DialogValidation.WithParameter<() -> String>) = textValidation(*validations.map2Array { it.trimParameter() }) fun <T : JTextComponent> Cell<T>.textValidation(vararg validations: DialogValidation.WithParameter<() -> String>) = validation(*validations.map2Array { it.forTextComponent() }) @ApiStatus.Experimental fun <T: JTextComponent> Cell<T>.whenTextChangedFromUi(parentDisposable: Disposable? = null, listener: (String) -> Unit): Cell<T> { return applyToComponent { whenTextChangedFromUiImpl(parentDisposable, listener) } }
apache-2.0
4ac7b3f1c1e4ac65f58daaf785731ffa
35.384058
158
0.760757
3.974663
false
false
false
false
google/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/AbstractPullPushMembersHandler.kt
2
4224
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.refactoring import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.ScrollType import com.intellij.openapi.project.Project import com.intellij.openapi.util.NlsContexts import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.refactoring.RefactoringActionHandler import com.intellij.refactoring.RefactoringBundle import com.intellij.refactoring.lang.ElementsHandler import com.intellij.refactoring.util.CommonRefactoringUtil import org.jetbrains.annotations.Nls import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf abstract class AbstractPullPushMembersHandler( @Nls private val refactoringName: String, private val helpId: String, @NlsContexts.DialogMessage private val wrongPositionMessage: String ) : RefactoringActionHandler, ElementsHandler { private fun reportWrongPosition(project: Project, editor: Editor?) { val message = RefactoringBundle.getCannotRefactorMessage(wrongPositionMessage) CommonRefactoringUtil.showErrorHint(project, editor, message, refactoringName, helpId) } private fun KtParameter.getContainingClass() = if (hasValOrVar()) (ownerFunction as? KtPrimaryConstructor)?.containingClassOrObject else null protected fun reportWrongContext(project: Project, editor: Editor?) { val message = RefactoringBundle.getCannotRefactorMessage( RefactoringBundle.message("is.not.supported.in.the.current.context", refactoringName) ) CommonRefactoringUtil.showErrorHint(project, editor, message, refactoringName, helpId) } protected abstract operator fun invoke( project: Project, editor: Editor?, classOrObject: KtClassOrObject?, member: KtNamedDeclaration?, dataContext: DataContext? ) override fun invoke(project: Project, editor: Editor, file: PsiFile, dataContext: DataContext?) { val offset = editor.caretModel.offset editor.scrollingModel.scrollToCaret(ScrollType.MAKE_VISIBLE) val target = (file.findElementAt(offset) ?: return).parentsWithSelf.firstOrNull { it is KtClassOrObject || ((it is KtNamedFunction || it is KtProperty) && it.parent is KtClassBody) || it is KtParameter && it.hasValOrVar() && it.ownerFunction is KtPrimaryConstructor } if (target == null) { reportWrongPosition(project, editor) return } if (!target.canRefactor()) return invoke(project, arrayOf(target), dataContext) } override fun invoke(project: Project, elements: Array<out PsiElement>, dataContext: DataContext?) { val element = elements.singleOrNull() ?: return val editor = dataContext?.let { CommonDataKeys.EDITOR.getData(it) } val (classOrObject, member) = when (element) { is KtNamedFunction, is KtProperty -> element.getStrictParentOfType<KtClassOrObject>() to element as KtNamedDeclaration? is KtParameter -> element.getContainingClass() to element is KtClassOrObject -> element to null else -> { reportWrongPosition(project, editor) return } } invoke(project, editor, classOrObject, member, dataContext) } override fun isEnabledOnElements(elements: Array<out PsiElement>): Boolean { return elements.mapTo(HashSet<PsiElement>()) { when (it) { is KtNamedFunction, is KtProperty -> (it.parent as? KtClassBody)?.parent as? KtClassOrObject is KtParameter -> it.getContainingClass() is KtClassOrObject -> it else -> null } ?: return false }.size == 1 } }
apache-2.0
556c6682e82a89ceec36648642355405
42.102041
158
0.70786
5.195572
false
false
false
false
Leifzhang/AndroidRouter
RouterLib/src/main/java/com/kronos/router/interceptor/LaunchInterceptor.kt
2
1593
package com.kronos.router.interceptor import android.content.Context import android.content.Intent import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.kronos.router.KRequest import com.kronos.router.RouterContext import com.kronos.router.model.RouterParams import com.kronos.router.utils.IntentUtils import com.kronos.router.utils.startForResult import java.lang.NullPointerException class LaunchInterceptor(private val params: RouterParams) : Interceptor { override fun intercept(chain: Interceptor.Chain) { val request = chain.url process(request, request.bundle, chain.context) } private fun process(request: KRequest, extras: Bundle?, context: Context) { val options = params.routerOptions if (options?.callback != null) { RouterContext(params.openParams, extras, context).apply { options.callback?.run(this) } return } val intent: Intent = IntentUtils.intentFor(context, params) ?: return extras?.apply { intent.putExtras(this) } if (request.activityResultCode == 0 || context !is AppCompatActivity) { context.startActivity(intent) request.onSuccess.invoke() } else { options?.openClass?.apply { context.startForResult(request.activityResultCode, this, extras, onSuccess = request.onSuccess, onFail = { request.onFail.invoke(NullPointerException("")) }) } } } }
mit
84d835ec85bbd79a3386bec0f79b21e4
32.914894
80
0.653484
4.769461
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/ir/buildsystem/SourcesetIR.kt
1
2775
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem import kotlinx.collections.immutable.PersistentList import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.gradle.GradleIR import org.jetbrains.kotlin.tools.projectWizard.plugins.printer.BuildFilePrinter import org.jetbrains.kotlin.tools.projectWizard.plugins.printer.GradlePrinter import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.Sourceset import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.SourcesetType import java.nio.file.Path import java.util.* sealed class SourcesetIR : BuildSystemIR { abstract val sourcesetType: SourcesetType abstract val path: Path? abstract val original: Sourceset } data class SingleplatformSourcesetIR( override val sourcesetType: SourcesetType, override val path: Path?, override val irs: PersistentList<BuildSystemIR>, override val original: Sourceset ) : SourcesetIR(), IrsOwner { override fun withReplacedIrs(irs: PersistentList<BuildSystemIR>): SingleplatformSourcesetIR = copy(irs = irs) override fun BuildFilePrinter.render() = Unit } data class MultiplatformSourcesetIR( override val sourcesetType: SourcesetType, override val path: Path?, val targetName: String, override val irs: PersistentList<BuildSystemIR>, override val original: Sourceset ) : SourcesetIR(), IrsOwner, GradleIR { override fun withReplacedIrs(irs: PersistentList<BuildSystemIR>): MultiplatformSourcesetIR = copy(irs = irs) override fun GradlePrinter.renderGradle() { getting(sourcesetName, prefix = null) { val dependencies = irsOfType<DependencyIR>() val needBody = dependencies.isNotEmpty() || dsl == GradlePrinter.GradleDsl.GROOVY if (needBody) { +" " inBrackets { if (dependencies.isNotEmpty()) { indent() sectionCall("dependencies", dependencies) } } } } for (dependsOn in original.dependsOnModules) { if (dependsOn.sourceSets.any { it.sourcesetType == sourcesetType }) { nl() indent() val capitalSuffix = sourcesetType.name.capitalize(Locale.US) // for example: "Main" or "Test" sourcesetName.dependsOn(dependsOn.name + capitalSuffix) // for example: iosSimulatorArm64Main.dependsOn(iosMain) } } } } val MultiplatformSourcesetIR.sourcesetName get() = targetName + sourcesetType.name.capitalize(Locale.US)
apache-2.0
29e4849de66e0c499c6875e36213c19b
41.045455
158
0.698018
4.679595
false
false
false
false
allotria/intellij-community
java/java-tests/testSrc/com/intellij/java/propertyBased/ProjectProblemsViewPropertyTest.kt
2
20638
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.java.propertyBased import com.intellij.codeInsight.daemon.impl.HighlightInfo import com.intellij.codeInsight.daemon.problems.MemberCollector import com.intellij.codeInsight.daemon.problems.MemberUsageCollector import com.intellij.codeInsight.daemon.problems.Problem import com.intellij.codeInsight.daemon.problems.pass.ProjectProblemUtils import com.intellij.codeInsight.javadoc.JavaDocUtil import com.intellij.lang.annotation.HighlightSeverity import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileEditor.OpenFileDescriptor import com.intellij.openapi.fileEditor.TextEditor import com.intellij.openapi.module.ModuleUtilCore import com.intellij.openapi.project.Project import com.intellij.openapi.util.RecursionManager import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.* import com.intellij.psi.impl.search.JavaOverridingMethodsSearcher import com.intellij.psi.impl.source.resolve.JavaResolveUtil import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.search.PsiSearchHelper import com.intellij.psi.search.PsiSearchHelper.SearchCostResult.TOO_MANY_OCCURRENCES import com.intellij.psi.search.SearchScope import com.intellij.psi.search.searches.ReferencesSearch import com.intellij.psi.util.PsiTreeUtil import com.intellij.psi.util.PsiUtil import com.intellij.testFramework.SkipSlowTestLocally import com.intellij.testFramework.fixtures.impl.CodeInsightTestFixtureImpl import com.intellij.testFramework.propertyBased.MadTestingUtil import com.intellij.util.ArrayUtilRt import com.siyeh.ig.psiutils.TypeUtils import junit.framework.TestCase import one.util.streamex.StreamEx import org.jetbrains.jetCheck.Generator import org.jetbrains.jetCheck.ImperativeCommand import org.jetbrains.jetCheck.PropertyChecker import kotlin.math.absoluteValue @SkipSlowTestLocally class ProjectProblemsViewPropertyTest : BaseUnivocityTest() { fun testAllFilesWithMemberNameReported() { RecursionManager.disableMissedCacheAssertions(testRootDisposable) PropertyChecker.customized() .withIterationCount(50) .checkScenarios { ImperativeCommand(this::doTestAllFilesWithMemberNameReported) } } private fun doTestAllFilesWithMemberNameReported(env: ImperativeCommand.Environment) { val changedFiles = mutableMapOf<VirtualFile, Set<VirtualFile>>() MadTestingUtil.changeAndRevert(myProject) { val nFilesToChange = env.generateValue(Generator.integers(1, 3), "Files to change: %s") var i = 0 while (i < nFilesToChange) { val fileToChange = env.generateValue(psiJavaFiles(), null) val relatedFiles = findRelatedFiles(fileToChange) if (relatedFiles.isEmpty()) continue val members = findMembers(fileToChange) if (members.isEmpty()) continue val editor = openEditor(fileToChange.virtualFile) rehighlight(fileToChange, editor) if (getFilesReportedByProblemSearch(editor).isNotEmpty()) continue env.logMessage("Selected file: ${fileToChange.name}") val actual = changeSelectedFile(env, members, fileToChange) if (actual == null) break changedFiles[fileToChange.virtualFile] = relatedFiles val expected = findFilesWithProblems(relatedFiles, members) assertContainsElements(actual, expected) i++ } } // check that all problems disappeared after revert val psiManager = PsiManager.getInstance(myProject) for ((changedFile, relatedFiles) in changedFiles) { val psiFile = psiManager.findFile(changedFile)!! val editor = openEditor(changedFile) rehighlight(psiFile, editor) val problems: Map<PsiMember, Set<Problem>> = ProjectProblemUtils.getReportedProblems(editor) if (problems.isNotEmpty()) { val relatedProblems = findRelatedProblems(problems, relatedFiles) if (relatedProblems.isNotEmpty()) { TestCase.fail(""" Problems are still reported even after the fix. File: ${changedFile.name}, ${relatedProblems.map { (member, memberProblems) -> extractMemberProblems(member, memberProblems) }} """.trimIndent()) } } } } private data class ScopedMember(val psiMember: PsiMember, var scope: SearchScope) private fun changeSelectedFile(env: ImperativeCommand.Environment, members: List<ScopedMember>, fileToChange: PsiJavaFile): Set<VirtualFile>? { val reportedFiles = mutableSetOf<VirtualFile>() val nChanges = env.generateValue(Generator.integers(1, 5), "Changes to make: %s") for (j in 0 until nChanges) { val editor = (FileEditorManager.getInstance(myProject).selectedEditor as TextEditor).editor val member = env.generateValue(Generator.sampledFrom(members), null) val psiMember = member.psiMember val prevScope = psiMember.useScope env.logMessage("Changing member: ${JavaDocUtil.getReferenceText(myProject, psiMember)}") val usages = findUsages(psiMember) if (usages == null || usages.isEmpty()) { env.logMessage("Member has no usages (or too many). Skipping.") continue } env.logMessage("Found ${usages.size} usages of member and its parents") val modifications = Modification.getPossibleModifications(psiMember, env) if (modifications.isEmpty()) { env.logMessage("Don't know how to modify this member, skipping it.") continue } val modification = env.generateValue(Generator.sampledFrom(modifications), "Applying modification: %s") val membersToSearch = getMembersToSearch(member, modification, members) if (membersToSearch == null) { env.logMessage("Too costly to analyse change, skipping") continue } rehighlight(fileToChange, editor) WriteCommandAction.runWriteCommandAction(myProject) { modification.apply(myProject) } env.logMessage("Modification applied") rehighlight(fileToChange, editor) if (!isCheapToSearch(psiMember)) { env.logMessage("Too costly to analyze element after change, skipping all iteration") return null } reportedFiles.addAll(getFilesReportedByProblemSearch(editor)) val curScope = psiMember.useScope member.scope = prevScope.union(curScope) } return reportedFiles } private fun getMembersToSearch(member: ScopedMember, modification: Modification, members: List<ScopedMember>): List<ScopedMember>? { if (!modification.searchAllMembers()) return listOf(member) if (members.any { !isCheapToSearch(it.psiMember) }) return null return members } private fun rehighlight(psiFile: PsiFile, editor: Editor): List<HighlightInfo> { PsiDocumentManager.getInstance(myProject).commitAllDocuments() return CodeInsightTestFixtureImpl.instantiateAndRun(psiFile, editor, ArrayUtilRt.EMPTY_INT_ARRAY, false) } private fun openEditor(virtualFile: VirtualFile) = FileEditorManager.getInstance(myProject).openTextEditor(OpenFileDescriptor(myProject, virtualFile), true)!! private fun findRelatedFiles(psiFile: PsiFile): Set<VirtualFile> { val targetFile = psiFile.virtualFile if (psiFile !is PsiClassOwner) return mutableSetOf() return psiFile.classes.asSequence() .flatMap { ReferencesSearch.search(it).findAll().asSequence() } .map { it.element } .filter { !JavaResolveUtil.isInJavaDoc(it) } .mapNotNull { it.containingFile } .distinctBy { it.virtualFile } .mapNotNullTo(mutableSetOf()) { val virtualFile = it.virtualFile if (virtualFile == targetFile || hasErrors(it)) null else virtualFile } } private fun findMembers(psiFile: PsiClassOwner): List<ScopedMember> { return MemberCollector.collectMembers(psiFile) { member -> if (member is PsiMethod && member.isConstructor) return@collectMembers false val modifiers = member.modifierList ?: return@collectMembers true return@collectMembers !modifiers.hasExplicitModifier(PsiModifier.PRIVATE) }.map { ScopedMember(it, it.useScope) } } private fun findUsages(target: PsiMember): List<PsiElement>? { if (!isCheapToSearch(target)) return null val members = PsiTreeUtil.collectParents(target, PsiMember::class.java, true) { false } val usages = mutableListOf<PsiElement>() for (member in members) { val name = member.name ?: return null val scope = member.useScope as? GlobalSearchScope ?: return null val usageExtractor: (PsiFile, Int) -> PsiElement? = lambda@{ psiFile, index -> val identifier = psiFile.findElementAt(index) as? PsiIdentifier ?: return@lambda null return@lambda when (val parent = identifier.parent) { is PsiReference -> if (parent.isReferenceTo(member)) parent else null is PsiMethod -> if (isOverride(parent, member)) parent else null else -> null } } val memberUsages = MemberUsageCollector.collect(name, member.containingFile, scope, usageExtractor) ?: return null usages.addAll(memberUsages) } return usages } private fun isCheapToSearch(member: PsiMember): Boolean { val name = member.name ?: return false val module = ModuleUtilCore.findModuleForPsiElement(member) ?: return false val scope = GlobalSearchScope.moduleScope(module) val memberFile = member.containingFile return PsiSearchHelper.getInstance(myProject).isCheapEnoughToSearch(name, scope, memberFile, null) != TOO_MANY_OCCURRENCES } private fun isOverride(possibleOverride: PsiMethod, target: PsiMember): Boolean { val targetMethod = target as? PsiMethod ?: return false val overrideClass = possibleOverride.containingClass ?: return false val targetClass = targetMethod.containingClass ?: return false if (!overrideClass.isInheritor(targetClass, true)) return false return possibleOverride == JavaOverridingMethodsSearcher.findOverridingMethod(overrideClass, target, targetClass) } private fun findFilesWithProblems(relatedFiles: Set<VirtualFile>, members: List<ScopedMember>): Set<VirtualFile> { val psiManager = PsiManager.getInstance(myProject) val filesWithErrors = mutableSetOf<VirtualFile>() for (file in relatedFiles) { val psiFile = psiManager.findFile(file) ?: continue if (hasErrors(psiFile, members)) filesWithErrors.add(file) } return filesWithErrors } private fun hasErrors(psiFile: PsiFile, members: List<ScopedMember>? = null): Boolean { val infos = rehighlight(psiFile, openEditor(psiFile.virtualFile)) return infos.any { info -> if (info.severity != HighlightSeverity.ERROR) return@any false if (members == null) return@any true val startElement = psiFile.findElementAt(info.actualStartOffset) ?: return@any false val endElement = psiFile.findElementAt(info.actualEndOffset - 1) ?: return@any false val reported = PsiTreeUtil.findCommonParent(startElement, endElement) ?: return@any false if (JavaResolveUtil.isInJavaDoc(reported)) return@any false val context = PsiTreeUtil.getNonStrictParentOfType(reported, PsiStatement::class.java, PsiClass::class.java, PsiMethod::class.java, PsiField::class.java, PsiReferenceList::class.java) ?: return@any false return@any StreamEx.ofTree(context, { StreamEx.of(*it.children) }) .anyMatch { el -> el is PsiReference && members.any { m -> el.isReferenceTo(m.psiMember) && inScope(el.containingFile, m.scope) } } } } private fun inScope(psiFile: PsiFile, scope: SearchScope): Boolean = scope.contains(psiFile.virtualFile) private fun findRelatedProblems(problems: Map<PsiMember, Set<Problem>>, relatedFiles: Set<VirtualFile>): Map<PsiMember, Set<Problem>> { val relatedProblems = mutableMapOf<PsiMember, Set<Problem>>() for ((member, memberProblems) in problems) { val memberRelatedProblems = mutableSetOf<Problem>() for (memberProblem in memberProblems) { val problemFile = memberProblem.reportedElement.containingFile if (problemFile.virtualFile in relatedFiles) memberRelatedProblems.add(memberProblem) } if (memberRelatedProblems.isNotEmpty()) relatedProblems[member] = memberRelatedProblems } return relatedProblems } private fun extractMemberProblems(member: PsiMember, memberProblems: Set<Problem>): String { data class ProblemData(val fileName: String, val offset: Int, val reportedElement: String, val context: String?, val fileErrors: List<HighlightInfo>) fun getProblemData(problem: Problem): ProblemData { val context = problem.context val reportedElement = problem.reportedElement val psiFile = reportedElement.containingFile val fileName = psiFile.name val offset = reportedElement.textOffset val textEditor = FileEditorManager.getInstance(myProject).openFile(psiFile.virtualFile, true)[0] as TextEditor val fileErrors = rehighlight(psiFile, textEditor.editor).filter { it.severity == HighlightSeverity.ERROR } return ProblemData(fileName, offset, reportedElement.text, context.text, fileErrors) } return "Member: ${JavaDocUtil.getReferenceText(member.project, member)}," + " Problems: ${memberProblems.map { getProblemData(it) }}\n" } private fun getFilesReportedByProblemSearch(editor: Editor): Set<VirtualFile> = ProjectProblemUtils.getReportedProblems(editor).asSequence() .flatMap { it.value.asSequence() } .map { it.reportedElement.containingFile } .mapTo(mutableSetOf()) { it.virtualFile } private sealed class Modification(protected val member: PsiMember, env: ImperativeCommand.Environment) { abstract fun apply(project: Project) abstract override fun toString(): String open fun searchAllMembers(): Boolean = false companion object { val classModifications = arrayOf(::ChangeName, ::ExplicitModifierModification, ::ChangeExtendsList, ::MakeClassInterface) val methodModifications = arrayOf(::ChangeName, ::ExplicitModifierModification, ::ChangeType, ::AddParam) val fieldModifications = arrayOf(::ChangeName, ::ExplicitModifierModification, ::ChangeType) fun getPossibleModifications(member: PsiMember, env: ImperativeCommand.Environment) = when (member) { is PsiClass -> classModifications.map { it(member, env) } is PsiMethod -> methodModifications.map { it(member, env) } is PsiField -> if (member is PsiEnumConstant) emptyList() else fieldModifications.map { it(member, env) } else -> emptyList() } private fun String.absHash(): Int { val hash = hashCode() return if (hash == Int.MIN_VALUE) Int.MAX_VALUE else hash.absoluteValue } } private class ChangeName(member: PsiMember, env: ImperativeCommand.Environment) : Modification(member, env) { private val newName: String init { val namedMember = member as PsiNameIdentifierOwner val identifier = namedMember.nameIdentifier!! val oldName = identifier.text newName = oldName + oldName.absHash() } override fun apply(project: Project) { val factory = JavaPsiFacade.getElementFactory(project) (member as PsiNameIdentifierOwner).nameIdentifier!!.replace(factory.createIdentifier(newName)) } override fun toString(): String = "ChangeName: new name is '$newName'" } private class ExplicitModifierModification(member: PsiMember, env: ImperativeCommand.Environment) : Modification(member, env) { private val modifier: String = env.generateValue(Generator.sampledFrom(*MODIFIERS), null) override fun apply(project: Project) { val modifiers = member.modifierList ?: return val hasModifier = modifiers.hasExplicitModifier(modifier) if (!hasModifier && isAccessModifier(modifier)) { val curAccessModifier = getAccessModifier(modifiers) if (curAccessModifier != null) modifiers.setModifierProperty(curAccessModifier, false) } modifiers.setModifierProperty(modifier, !hasModifier) } companion object { private val MODIFIERS = arrayOf(PsiModifier.PUBLIC, PsiModifier.PROTECTED, PsiModifier.PRIVATE, PsiModifier.STATIC, PsiModifier.ABSTRACT, PsiModifier.FINAL) private val ACCESS_MODIFIERS = arrayOf(PsiModifier.PRIVATE, PsiModifier.PUBLIC, PsiModifier.PROTECTED) private fun isAccessModifier(modifier: String) = modifier in ACCESS_MODIFIERS private fun getAccessModifier(modifiers: PsiModifierList): String? = sequenceOf(*ACCESS_MODIFIERS).firstOrNull { modifiers.hasExplicitModifier(it) } } override fun toString(): String = "ExplicitModifierModification: tweaking modifier '$modifier'" } private class ChangeType(member: PsiMember, env: ImperativeCommand.Environment) : Modification(member, env) { private val typeElement = env.generateValue(Generator.sampledFrom(findTypeElements(member)), null) private val newType = if (typeElement.type == PsiPrimitiveType.INT) TypeUtils.getStringType(typeElement) else PsiPrimitiveType.INT override fun apply(project: Project) { val factory = JavaPsiFacade.getElementFactory(project) typeElement.replace(factory.createTypeElement(newType)) } private fun findTypeElements(member: PsiMember): List<PsiTypeElement> { return StreamEx.ofTree(member as PsiElement) { el -> if (el is PsiCodeBlock || el is PsiComment) StreamEx.empty() else StreamEx.of(*el.children) }.filterIsInstance<PsiTypeElement>() } override fun toString(): String = "ChangeType: '${typeElement.type.canonicalText}' is changed to '${newType.canonicalText}'" } private class AddParam(method: PsiMethod, env: ImperativeCommand.Environment) : Modification(method, env) { val paramName: String init { val methodName = method.name paramName = methodName + methodName.absHash() } override fun apply(project: Project) { val factory = JavaPsiFacade.getElementFactory(project) val param = factory.createParameter(paramName, PsiType.INT) (member as PsiMethod).parameterList.add(param) } override fun toString(): String = "AddParam: param '$paramName' added" } private class ChangeExtendsList(psiClass: PsiClass, env: ImperativeCommand.Environment) : Modification(psiClass, env) { private val parentRef: PsiElement? init { val refs = psiClass.extendsList?.referenceElements parentRef = if (refs == null || refs.size != 1) null else refs[0].element } override fun apply(project: Project) { if (parentRef == null) return val factory = JavaPsiFacade.getElementFactory(project) parentRef.replace(factory.createTypeElement(TypeUtils.getObjectType(parentRef))) } override fun searchAllMembers() = true override fun toString(): String = if (parentRef != null) "ChangeExtendsList: change '${parentRef.text}' to 'java.lang.Object'" else "ChangeExtendsList: class doesn't extend anything, do nothing" } private class MakeClassInterface(psiClass: PsiClass, env: ImperativeCommand.Environment) : Modification(psiClass, env) { override fun apply(project: Project) { val psiClass = member as PsiClass if (psiClass.isEnum || psiClass.isInterface || psiClass.isAnnotationType) return val classKeyword = PsiTreeUtil.getPrevSiblingOfType(psiClass.nameIdentifier!!, PsiKeyword::class.java) ?: return val factory = JavaPsiFacade.getElementFactory(project) val newTypeKeyword = factory.createKeyword(PsiKeyword.INTERFACE) PsiUtil.setModifierProperty(psiClass, PsiModifier.ABSTRACT, false) PsiUtil.setModifierProperty(psiClass, PsiModifier.FINAL, false) classKeyword.replace(newTypeKeyword) } override fun searchAllMembers() = true override fun toString(): String = "MakeClassInterface: type changed to 'interface'" } } }
apache-2.0
4d4d6594c8574032192d06ce0e5da3f8
44.966592
140
0.718287
4.920839
false
false
false
false
ursjoss/sipamato
common/common-persistence-api/src/test/kotlin/ch/difty/scipamato/common/persistence/paging/PaginationRequestTest.kt
2
4745
package ch.difty.scipamato.common.persistence.paging import ch.difty.scipamato.common.persistence.paging.Sort.Direction import org.amshove.kluent.invoking import org.amshove.kluent.shouldBeEqualTo import org.amshove.kluent.shouldBeFalse import org.amshove.kluent.shouldBeNull import org.amshove.kluent.shouldBeTrue import org.amshove.kluent.shouldNotBe import org.amshove.kluent.shouldNotBeEqualTo import org.amshove.kluent.shouldThrow import org.junit.jupiter.api.Test internal class PaginationRequestTest { private lateinit var pr: PaginationRequest private lateinit var sort: String @Test fun degenerateConstruction_withInvalidOffset() { invoking { PaginationRequest(-1, 1) } shouldThrow IllegalArgumentException::class } @Test fun degenerateConstruction_withInvalidPageSize() { invoking { PaginationRequest(0, 0) } shouldThrow IllegalArgumentException::class } private fun assertPaginationRequest(pc: PaginationContext, offSet: Int, pageSize: Int, sort: String?) { pc.offset shouldBeEqualTo offSet pc.pageSize shouldBeEqualTo pageSize if (sort != null) { val s = pc.sort s.getSortPropertyFor("foo").toString() shouldBeEqualTo sort s.getSortPropertyFor("bar").shouldBeNull() } else { pc.sort.iterator().hasNext().shouldBeFalse() } } @Test fun paginationContextWithSortButNoPaging() { sort = "foo: DESC" pr = PaginationRequest(Direction.DESC, "foo") assertPaginationRequest(pr, 0, Integer.MAX_VALUE, sort) pr.toString() shouldBeEqualTo "PaginationRequest(offset=0, pageSize=2147483647, sort=foo: DESC)" } @Test fun paginationContextWithSort_withOffset0_andPageSize10() { sort = "foo: DESC" pr = PaginationRequest(0, 10, Direction.DESC, "foo") assertPaginationRequest(pr, 0, 10, sort) pr.toString() shouldBeEqualTo "PaginationRequest(offset=0, pageSize=10, sort=foo: DESC)" } @Test fun paginationContextWithSort_withOffset24_andPageSize12() { sort = "foo: ASC" pr = PaginationRequest(24, 12, Direction.ASC, "foo") assertPaginationRequest(pr, 24, 12, sort) pr.toString() shouldBeEqualTo "PaginationRequest(offset=24, pageSize=12, sort=foo: ASC)" } @Test fun paginationContextWithoutSort_withOffset6_andPageSize2() { pr = PaginationRequest(6, 2) assertPaginationRequest(pr, 6, 2, null) pr.toString() shouldBeEqualTo "PaginationRequest(offset=6, pageSize=2, sort=)" } @Test fun equality_ofSameObjectInstance() { pr = PaginationRequest(5, 5) assertEquality(pr, pr) } private fun assertEquality(pr1: PaginationRequest, pr2: PaginationRequest) { (pr1 == pr2).shouldBeTrue() pr1.hashCode() shouldBeEqualTo pr2.hashCode() } @Test fun inequality_ofPaginationRequestWithDifferentSorts() { pr = PaginationRequest(5, 5) assertInequality(pr, PaginationRequest(5, 5, Direction.ASC, "foo")) } private fun assertInequality(pr1: PaginationRequest, pr2: PaginationRequest) { (pr1 == pr2).shouldBeFalse() pr1.hashCode() shouldNotBe pr2.hashCode() } @Test fun inequality_ofPaginationRequestWithDifferentSorts2() { pr = PaginationRequest(5, 6, Direction.ASC, "bar") assertInequality(pr, PaginationRequest(5, 6, Direction.ASC, "foo")) } @Test fun inequality_ofPaginationRequestWithDifferentSorts3() { pr = PaginationRequest(5, 6, Direction.DESC, "foo") assertInequality(pr, PaginationRequest(5, 6, Direction.ASC, "foo")) } @Test fun inequality_ofPaginationRequestWithNonSortAttributes1() { pr = PaginationRequest(5, 6, Direction.ASC, "foo") assertInequality(pr, PaginationRequest(6, 6, Direction.ASC, "foo")) } @Test fun inequality_ofPaginationRequestWithNonSortAttributes2() { pr = PaginationRequest(5, 6, Direction.ASC, "foo") assertInequality(pr, PaginationRequest(5, 7, Direction.ASC, "foo")) } @Test fun equality_ofPaginationRequestWithSameAttributes_withSort() { pr = PaginationRequest(5, 6, Direction.ASC, "foo") assertEquality(pr, PaginationRequest(5, 6, Direction.ASC, "foo")) } @Test fun equality_ofPaginationRequestWithSameAttributes_withoutSort() { pr = PaginationRequest(5, 6) val pr2 = PaginationRequest(5, 6) assertEquality(pr, pr2) } @Test fun inequality_ofPaginationRequestWithNonPaginationRequest() { pr = PaginationRequest(5, 6) val pr2 = "" pr.hashCode() shouldNotBeEqualTo pr2.hashCode() } }
gpl-3.0
0c8bbf6f4fb10258cdafd3575dc8cf25
32.652482
107
0.681981
4.176937
false
true
false
false
Kotlin/kotlinx.coroutines
kotlinx-coroutines-core/common/test/flow/NamedDispatchers.kt
1
1931
/* * Copyright 2016-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.coroutines import kotlin.coroutines.* import kotlin.native.concurrent.* /** * Test dispatchers that emulate multiplatform context tracking. */ @ThreadLocal public object NamedDispatchers { private val stack = ArrayStack() public fun name(): String = stack.peek() ?: error("No names on stack") public fun nameOr(defaultValue: String): String = stack.peek() ?: defaultValue public operator fun invoke(name: String) = named(name) private fun named(name: String): CoroutineDispatcher = object : CoroutineDispatcher() { override fun dispatch(context: CoroutineContext, block: Runnable) { stack.push(name) try { block.run() } finally { val last = stack.pop() ?: error("No names on stack") require(last == name) { "Inconsistent stack: expected $name, but had $last" } } } } } private class ArrayStack { private var elements = arrayOfNulls<String>(16) private var head = 0 public fun push(value: String) { if (elements.size == head - 1) ensureCapacity() elements[head++] = value } public fun peek(): String? = elements.getOrNull(head - 1) public fun pop(): String? { if (head == 0) return null return elements[--head] } private fun ensureCapacity() { val currentSize = elements.size val newCapacity = currentSize shl 1 val newElements = arrayOfNulls<String>(newCapacity) elements.copyInto( destination = newElements, startIndex = head ) elements.copyInto( destination = newElements, destinationOffset = elements.size - head, endIndex = head ) elements = newElements } }
apache-2.0
173031a378720aceedafcdf6bf30202d
27.397059
102
0.6116
4.732843
false
false
false
false
romannurik/muzei
wearable/src/main/java/com/google/android/apps/muzei/ChooseProviderViewModel.kt
2
2930
/* * Copyright 2018 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.muzei import android.app.Application import android.content.ComponentName import android.content.pm.PackageManager import android.graphics.drawable.Drawable import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope import com.google.android.apps.muzei.room.getInstalledProviders import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.shareIn import net.nurik.roman.muzei.BuildConfig.DATA_LAYER_AUTHORITY data class ProviderInfo( val authority: String, val packageName: String, val title: String, val icon: Drawable, val setupActivity: ComponentName? ) { constructor( packageManager: PackageManager, providerInfo: android.content.pm.ProviderInfo ) : this( providerInfo.authority, providerInfo.packageName, providerInfo.loadLabel(packageManager).toString(), providerInfo.loadIcon(packageManager), providerInfo.metaData?.getString("setupActivity")?.run { ComponentName(providerInfo.packageName, this) }) } class ChooseProviderViewModel(application: Application) : AndroidViewModel(application) { private val comparator = Comparator<ProviderInfo> { p1, p2 -> // The DataLayerArtProvider should always the first provider listed if (p1.authority == DATA_LAYER_AUTHORITY) { return@Comparator -1 } else if (p2.authority == DATA_LAYER_AUTHORITY) { return@Comparator 1 } // Then put providers from Muzei on top val pn1 = p1.packageName val pn2 = p2.packageName if (pn1 != pn2) { if (application.packageName == pn1) { return@Comparator -1 } else if (application.packageName == pn2) { return@Comparator 1 } } // Finally, sort providers by their title p1.title.compareTo(p2.title) } val providers = getInstalledProviders(application).map { providerInfos -> providerInfos.map { providerInfo -> ProviderInfo(application.packageManager, providerInfo) }.sortedWith(comparator) }.shareIn(viewModelScope, SharingStarted.WhileSubscribed(5000L), 1) }
apache-2.0
b61dbfe5b865c839b201ea066f25d326
36.088608
89
0.687713
4.748784
false
false
false
false
leafclick/intellij-community
platform/testFramework/extensions/src/com/intellij/testFramework/assertions/JdomAssert.kt
1
2682
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.testFramework.assertions import com.intellij.configurationStore.deserialize import com.intellij.configurationStore.serialize import com.intellij.openapi.util.JDOMUtil import com.intellij.openapi.util.text.StringUtilRt import com.intellij.rt.execution.junit.FileComparisonFailure import com.intellij.util.io.readText import com.intellij.util.isEmpty import org.assertj.core.api.AbstractAssert import org.assertj.core.internal.Objects import org.intellij.lang.annotations.Language import org.jdom.Element import java.io.File import java.nio.file.Path class JdomAssert(actual: Element?) : AbstractAssert<JdomAssert, Element?>(actual, JdomAssert::class.java) { fun isEmpty(): JdomAssert { isNotNull if (!actual.isEmpty()) { failWithMessage("Expected to be empty but was\n${JDOMUtil.writeElement(actual!!)}") } return this } @Deprecated("isEqualTo(file: Path)", ReplaceWith("isEqualTo(file.toPath())")) fun isEqualTo(file: File) = isEqualTo(file.toPath()) fun isEqualTo(file: Path): JdomAssert { isNotNull val expected = JDOMUtil.load(file) if (!JDOMUtil.areElementsEqual(actual, expected)) { throw FileComparisonFailure(null, StringUtilRt.convertLineSeparators(file.readText()), JDOMUtil.writeElement(actual!!), file.toString()) } return this } fun isEqualTo(element: Element?): JdomAssert { if (actual == element) { return this } isNotNull if (!JDOMUtil.areElementsEqual(actual, element)) { isEqualTo(JDOMUtil.writeElement(element!!)) } return this } fun isEqualTo(@Language("xml") expected: String): JdomAssert { isNotNull Objects.instance().assertEqual( info, JDOMUtil.writeElement(actual!!), expected.trimIndent().removePrefix("""<?xml version="1.0" encoding="UTF-8"?>""").trimStart()) return this } } fun <T : Any> doSerializerTest(@Language("XML") expectedText: String, bean: T): T { // test deserializer val expectedTrimmed = expectedText.trimIndent() val element = assertSerializer(bean, expectedTrimmed) // test deserializer val o = (element ?: Element("state")).deserialize(bean.javaClass) assertSerializer(o, expectedTrimmed, "Deserialization failure") return o } private fun assertSerializer(bean: Any, expected: String, description: String = "Serialization failure"): Element? { val element = serialize(bean) Assertions.assertThat(element?.let { JDOMUtil.writeElement(element).trim() }).`as`(description).isEqualTo(expected) return element }
apache-2.0
6b38290cac4bc12a80f03f002e333b89
31.719512
142
0.734526
4.236967
false
false
false
false
bitsydarel/DBWeather
dbweatherdata/src/main/java/com/dbeginc/dbweatherdata/implementations/repositories/WeatherRepositoryImpl.kt
1
5386
/* * Copyright (C) 2017 Darel Bitsy * 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.dbeginc.dbweatherdata.implementations.repositories import android.content.Context import android.util.Log import com.dbeginc.dbweatherdata.BuildConfig import com.dbeginc.dbweatherdata.CrashlyticsLogger import com.dbeginc.dbweatherdata.RxThreadProvider import com.dbeginc.dbweatherdata.TAG import com.dbeginc.dbweatherdata.implementations.datasources.local.LocalWeatherDataSource import com.dbeginc.dbweatherdata.implementations.datasources.local.weather.RoomWeatherDataSource import com.dbeginc.dbweatherdata.implementations.datasources.remote.RemoteWeatherDataSource import com.dbeginc.dbweatherdata.implementations.datasources.remote.weather.HttpApiWeatherDataSource import com.dbeginc.dbweatherdomain.Logger import com.dbeginc.dbweatherdomain.entities.requests.weather.WeatherRequest import com.dbeginc.dbweatherdomain.entities.weather.Location import com.dbeginc.dbweatherdomain.entities.weather.Weather import com.dbeginc.dbweatherdomain.repositories.WeatherRepository import io.reactivex.Completable import io.reactivex.Flowable import io.reactivex.Single import io.reactivex.disposables.CompositeDisposable import io.reactivex.observers.DisposableCompletableObserver /** * Created by darel on 15.09.17. * * Weather Repository Implementation */ class WeatherRepositoryImpl private constructor(private val local: LocalWeatherDataSource, private val remote: RemoteWeatherDataSource, private val logger: Logger, private val thread: RxThreadProvider) : WeatherRepository { companion object { fun create(context: Context) : WeatherRepository { return WeatherRepositoryImpl( RoomWeatherDataSource.create(context), HttpApiWeatherDataSource.create(context), CrashlyticsLogger, RxThreadProvider ) } } private val subscriptions = CompositeDisposable() override fun getWeather(request: WeatherRequest<String>): Flowable<Weather> { // Remote request to api val remoteRequest = remote.getWeather(WeatherRequest("", request.latitude, request.longitude, Unit)) .subscribeOn(thread.IO) // If requested location is empty // we need to go to the network to get weather info by lat and long return if (request.arg.isEmpty()) remoteRequest.doAfterSuccess(this::addWeather).toFlowable() else local.getWeather(request) .subscribeOn(thread.CP) .doOnSubscribe { // keep updating the weather from the api remoteRequest.subscribe(this::addWeather, logger::logError) } } override fun getWeatherForLocation(request: WeatherRequest<String>): Flowable<Weather> { return local.getWeatherForLocation(locationName = request.city, countryCode = request.arg) .subscribeOn(thread.CP) .doOnSubscribe { remote.getWeather(WeatherRequest("", request.latitude, request.longitude, Unit)) .subscribeOn(thread.IO) .subscribe(this::addWeatherForLocation, logger::logError) } } override fun getLocations(name: String): Single<List<Location>> { return remote.getLocations(name) .subscribeOn(thread.IO) } override fun getAllUserLocations(): Flowable<List<Location>> { return local.getUserLocations() .subscribeOn(thread.CP) } override fun deleteWeatherForLocation(name: String): Completable { return local.deleteWeatherForLocation(name) .subscribeOn(thread.CP) } override fun clean() = subscriptions.clear() private fun addWeather(weather: Weather) { subscriptions.add( local.updateWeather(weather) .subscribeOn(thread.CP) .subscribeWith(UpdateObserver()) ) } private fun addWeatherForLocation(weather: Weather) { subscriptions.add( local.updateWeatherLocation(weather) .subscribeOn(thread.CP) .subscribeWith(UpdateObserver()) ) } private inner class UpdateObserver : DisposableCompletableObserver() { override fun onComplete() { if (BuildConfig.DEBUG) { Log.i(TAG, "Update of data done in ${WeatherRepository::class.java.simpleName}") } } override fun onError(e: Throwable) { Log.e(TAG, "Error: ${WeatherRepository::class.java.simpleName}", e) } } }
gpl-3.0
61418cc840232af59299f66f8cd1c017
39.503759
108
0.668771
5.139313
false
false
false
false
leafclick/intellij-community
platform/lang-impl/src/com/intellij/navigation/JBProtocolNavigateCommand.kt
1
8254
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.navigation import com.intellij.ide.IdeBundle import com.intellij.ide.RecentProjectListActionProvider import com.intellij.ide.RecentProjectsManagerBase import com.intellij.ide.ReopenProjectAction import com.intellij.ide.actions.searcheverywhere.SymbolSearchEverywhereContributor import com.intellij.ide.impl.OpenProjectTask import com.intellij.ide.impl.ProjectUtil import com.intellij.openapi.actionSystem.ActionPlaces import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.impl.SimpleDataContext import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.JBProtocolCommand import com.intellij.openapi.application.JetBrainsProtocolHandler.FRAGMENT_PARAM_NAME import com.intellij.openapi.application.ModalityState import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.editor.LogicalPosition import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileEditor.TextEditor import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.Task import com.intellij.openapi.progress.util.StatusBarProgress import com.intellij.openapi.project.Project import com.intellij.openapi.startup.StartupManager import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.psi.PsiElement import com.intellij.util.PsiNavigateUtil import java.io.File import java.nio.file.Paths import java.util.regex.Pattern open class JBProtocolNavigateCommand : JBProtocolCommand(NAVIGATE_COMMAND) { override fun perform(target: String, parameters: Map<String, String>) { /** * The handler parses the following 'navigate' command parameters: * * navigate/reference * \\?project=(?<project>[\\w]+) * (&fqn[\\d]*=(?<fqn>[\\w.\\-#]+))* * (&path[\\d]*=(?<path>[\\w-_/\\\\.]+) * (:(?<lineNumber>[\\d]+))? * (:(?<columnNumber>[\\d]+))?)* * (&selection[\\d]*= * (?<line1>[\\d]+):(?<column1>[\\d]+) * -(?<line2>[\\d]+):(?<column2>[\\d]+))* */ val projectName = parameters[PROJECT_NAME_KEY] if (projectName.isNullOrEmpty()) { return } if (target != REFERENCE_TARGET) { LOG.warn("JB navigate action supports only reference target, got $target") return } for (recentProjectAction in RecentProjectListActionProvider.getInstance().getActions()) { if (recentProjectAction !is ReopenProjectAction || recentProjectAction.projectName != projectName) { continue } val project = ProjectUtil.getOpenProjects().find { project -> project.name == projectName } if (project != null) { findAndNavigateToReference(project, parameters) return } ApplicationManager.getApplication().invokeLater(Runnable { RecentProjectsManagerBase.instanceEx.openProject(Paths.get(recentProjectAction.projectPath), OpenProjectTask())?.let { StartupManager.getInstance(it).registerPostStartupActivity { findAndNavigateToReference(it, parameters) } } }, ModalityState.NON_MODAL) } } companion object { private val LOG = logger<JBProtocolNavigateCommand>() const val NAVIGATE_COMMAND = "navigate" const val PROJECT_NAME_KEY = "project" const val REFERENCE_TARGET = "reference" const val PATH_KEY = "path" const val FQN_KEY = "fqn" const val SELECTION = "selection" const val FILE_PROTOCOL = "file://" private const val PATH_GROUP = "path" private const val LINE_GROUP = "line" private const val COLUMN_GROUP = "column" private val PATH_WITH_LOCATION = Pattern.compile("(?<$PATH_GROUP>[^:]*)(:(?<$LINE_GROUP>[\\d]+))?(:(?<$COLUMN_GROUP>[\\d]+))?") private fun findAndNavigateToReference(project: Project, parameters: Map<String, String>) { for (it in parameters) { if (it.key.startsWith(FQN_KEY)) { navigateByFqn(project, parameters, it.value) } } for (it in parameters) { if (it.key.startsWith(PATH_KEY)) { navigateByPath(project, parameters, it.value) } } } private fun navigateByPath(project: Project, parameters: Map<String, String>, pathText: String) { val matcher = PATH_WITH_LOCATION.matcher(pathText) if (!matcher.matches()) { return } var path: String? = matcher.group(PATH_GROUP) val line: String? = matcher.group(LINE_GROUP) val column: String? = matcher.group(COLUMN_GROUP) if (path == null) { return } path = FileUtil.expandUserHome(path) if (!FileUtil.isAbsolute(path)) { path = File(project.basePath, path).absolutePath } val virtualFile = VirtualFileManager.getInstance().findFileByUrl(FILE_PROTOCOL + path) ?: return FileEditorManager.getInstance(project).openFile(virtualFile, true) .filterIsInstance<TextEditor>().first().let { textEditor -> val editor = textEditor.editor editor.caretModel.moveToOffset(editor.logicalPositionToOffset(LogicalPosition(line?.toInt() ?: 0, column?.toInt() ?: 0))) setSelections(parameters, project) } } private fun navigateByFqn(project: Project, parameters: Map<String, String>, reference: String) { // handle single reference to method: com.intellij.navigation.JBProtocolNavigateCommand#perform // multiple references are encoded and decoded properly val fqn = parameters[FRAGMENT_PARAM_NAME]?.let { "$reference#$it" } ?: reference ProgressManager.getInstance().run( object : Task.Backgroundable(project, IdeBundle.message("navigate.command.search.reference.progress.title", fqn), true) { override fun run(indicator: ProgressIndicator) { val dataContext = SimpleDataContext.getProjectContext(project) SymbolSearchEverywhereContributor(AnActionEvent.createFromDataContext(ActionPlaces.UNKNOWN, null, dataContext)) .search(fqn, ProgressManager.getInstance().progressIndicator ?: StatusBarProgress()) .filterIsInstance<PsiElement>() .forEach { ApplicationManager.getApplication().invokeLater { PsiNavigateUtil.navigate(it) setSelections(parameters, project) } } } override fun shouldStartInBackground(): Boolean = !ApplicationManager.getApplication().isUnitTestMode override fun isConditionalModal(): Boolean = !ApplicationManager.getApplication().isUnitTestMode }) } private fun setSelections(parameters: Map<String, String>, project: Project) { parseSelections(parameters).forEach { selection -> setSelection(project, selection) } } private fun setSelection(project: Project, selection: Pair<LogicalPosition, LogicalPosition>) { val editor = FileEditorManager.getInstance(project).selectedTextEditor editor?.selectionModel?.setSelection(editor.logicalPositionToOffset(selection.first), editor.logicalPositionToOffset(selection.second)) } private fun parseSelections(parameters: Map<String, String>): List<Pair<LogicalPosition, LogicalPosition>> { return parameters.filterKeys { it.startsWith(SELECTION) }.values.mapNotNull { val split = it.split('-') if (split.size != 2) return@mapNotNull null val position1 = parsePosition(split[0]) val position2 = parsePosition(split[1]) if (position1 != null && position2 != null) { return@mapNotNull Pair(position1, position1) } return@mapNotNull null } } private fun parsePosition(range: String): LogicalPosition? { val position = range.split(':') if (position.size != 2) return null try { return LogicalPosition(Integer.parseInt(position[0]), Integer.parseInt(position[1])) } catch (e: Exception) { return null } } } }
apache-2.0
88770e08bb7ccde82ed4ea8dd710290e
40.691919
140
0.689847
4.639685
false
false
false
false
Raizlabs/DBFlow
lib/src/main/kotlin/com/dbflow5/query/property/Property.kt
1
10316
package com.dbflow5.query.property import com.dbflow5.config.FlowManager import com.dbflow5.query.BaseModelQueriable import com.dbflow5.query.IConditional import com.dbflow5.query.IOperator import com.dbflow5.query.NameAlias import com.dbflow5.query.Operator import com.dbflow5.query.OrderBy /** * Description: The main, immutable property class that gets generated from a table definition. * * * This class delegates all of its [IOperator] methods to a new [Operator] that's used * in the SQLite query language. * * * This ensures that the language is strictly type-safe and only declared * columns get used. Also any calls on the methods return a new [Property]. * * * This is type parametrized so that all values passed to this class remain properly typed. */ open class Property<T>(override val table: Class<*>?, override val nameAlias: NameAlias) : IProperty<Property<T>>, IOperator<T> { val definition: String get() = nameAlias.fullQuery /** * @return helper method to construct it in a [.distinct] call. */ private val distinctAliasName: NameAlias get() = nameAlias .newBuilder() .distinct() .build() protected open val operator: Operator<T> get() = Operator.op(nameAlias) constructor(table: Class<*>?, columnName: String) : this(table, NameAlias.Builder(columnName).build()) constructor(table: Class<*>?, columnName: String, aliasName: String) : this(table, NameAlias.builder(columnName).`as`(aliasName).build()) override fun withTable(): Property<T> = Property(table, nameAlias .newBuilder() .withTable(FlowManager.getTableName(table!!)) .build()) override val query: String get() = nameAlias.query override fun toString(): String = nameAlias.toString() override fun `is`(conditional: IConditional): Operator<*> = operator.`is`(conditional) override fun eq(conditional: IConditional): Operator<*> = operator.eq(conditional) override fun isNot(conditional: IConditional): Operator<*> = operator.isNot(conditional) override fun notEq(conditional: IConditional): Operator<*> = operator.notEq(conditional) override fun like(conditional: IConditional): Operator<*> = operator.like(conditional) override fun glob(conditional: IConditional): Operator<*> = operator.glob(conditional) override fun like(value: String): Operator<T> = operator.like(value) override fun match(value: String): Operator<*> = operator.match(value) override fun notLike(value: String): Operator<T> = operator.notLike(value) override fun glob(value: String): Operator<T> = operator.glob(value) override fun greaterThan(conditional: IConditional): Operator<*> = operator.greaterThan(conditional) override fun greaterThanOrEq(conditional: IConditional): Operator<*> = operator.greaterThanOrEq(conditional) override fun lessThan(conditional: IConditional): Operator<*> = operator.lessThan(conditional) override fun lessThanOrEq(conditional: IConditional): Operator<*> = operator.lessThanOrEq(conditional) override fun between(conditional: IConditional): Operator.Between<*> = operator.between(conditional) override fun `in`(firstConditional: IConditional, vararg conditionals: IConditional): Operator.In<*> = operator.`in`(firstConditional, *conditionals) override fun notIn(firstConditional: IConditional, vararg conditionals: IConditional): Operator.In<*> = operator.notIn(firstConditional, *conditionals) override fun `is`(baseModelQueriable: BaseModelQueriable<*>): Operator<*> = operator.`is`(baseModelQueriable) override fun isNull(): Operator<*> = operator.isNull() override fun eq(baseModelQueriable: BaseModelQueriable<*>): Operator<*> = operator.eq(baseModelQueriable) override fun isNot(baseModelQueriable: BaseModelQueriable<*>): Operator<*> = operator.isNot(baseModelQueriable) override fun isNotNull(): Operator<*> = operator.isNotNull() override fun notEq(baseModelQueriable: BaseModelQueriable<*>): Operator<*> = operator.notEq(baseModelQueriable) override fun like(baseModelQueriable: BaseModelQueriable<*>): Operator<*> = operator.like(baseModelQueriable) override fun notLike(conditional: IConditional): Operator<*> = operator.notLike(conditional) override fun notLike(baseModelQueriable: BaseModelQueriable<*>): Operator<*> = operator.notLike(baseModelQueriable) override fun glob(baseModelQueriable: BaseModelQueriable<*>): Operator<*> = operator.glob(baseModelQueriable) override fun greaterThan(baseModelQueriable: BaseModelQueriable<*>): Operator<*> = operator.greaterThan(baseModelQueriable) override fun greaterThanOrEq(baseModelQueriable: BaseModelQueriable<*>): Operator<*> = operator.greaterThanOrEq(baseModelQueriable) override fun lessThan(baseModelQueriable: BaseModelQueriable<*>): Operator<*> = operator.lessThan(baseModelQueriable) override fun lessThanOrEq(baseModelQueriable: BaseModelQueriable<*>): Operator<*> = operator.lessThanOrEq(baseModelQueriable) override fun between(baseModelQueriable: BaseModelQueriable<*>): Operator.Between<*> = operator.between(baseModelQueriable) override fun `in`(firstBaseModelQueriable: BaseModelQueriable<*>, vararg baseModelQueriables: BaseModelQueriable<*>): Operator.In<*> = operator.`in`(firstBaseModelQueriable, *baseModelQueriables) override fun notIn(firstBaseModelQueriable: BaseModelQueriable<*>, vararg baseModelQueriables: BaseModelQueriable<*>): Operator.In<*> = operator.notIn(firstBaseModelQueriable, *baseModelQueriables) override fun concatenate(conditional: IConditional): Operator<*> = operator.concatenate(conditional) override fun plus(value: BaseModelQueriable<*>): Operator<*> = operator.plus(value) override fun minus(value: BaseModelQueriable<*>): Operator<*> = operator.minus(value) override fun div(value: BaseModelQueriable<*>): Operator<*> = operator.div(value) override fun times(value: BaseModelQueriable<*>): Operator<*> = operator.times(value) override fun rem(value: BaseModelQueriable<*>): Operator<*> = operator.rem(value) override fun plus(property: IProperty<*>): Property<T> { return Property(table, NameAlias.joinNames(Operator.Operation.PLUS, nameAlias.fullName(), property.toString())) } override fun minus(property: IProperty<*>): Property<T> { return Property(table, NameAlias.joinNames(Operator.Operation.MINUS, nameAlias.fullName(), property.toString())) } override fun div(property: IProperty<*>): Property<T> { return Property(table, NameAlias.joinNames(Operator.Operation.DIVISION, nameAlias.fullName(), property.toString())) } override fun times(property: IProperty<*>): Property<T> { return Property(table, NameAlias.joinNames(Operator.Operation.MULTIPLY, nameAlias.fullName(), property.toString())) } override fun rem(property: IProperty<*>): Property<T> { return Property(table, NameAlias.joinNames(Operator.Operation.MOD, nameAlias.fullName(), property.toString())) } override fun concatenate(property: IProperty<*>): Property<T> { return Property(table, NameAlias.joinNames(Operator.Operation.CONCATENATE, nameAlias.fullName(), property.toString())) } override fun `as`(aliasName: String): Property<T> { return Property(table, nameAlias .newBuilder() .`as`(aliasName) .build()) } override fun distinct(): Property<T> = Property(table, distinctAliasName) override fun withTable(tableNameAlias: NameAlias): Property<T> { return Property(table, nameAlias .newBuilder() .withTable(tableNameAlias.tableName) .build()) } override fun `is`(value: T?): Operator<T> = operator.`is`(value) override fun eq(value: T?): Operator<T> = operator.eq(value) override fun isNot(value: T?): Operator<T> = operator.isNot(value) override fun notEq(value: T?): Operator<T> = operator.notEq(value) override fun greaterThan(value: T): Operator<T> = operator.greaterThan(value) override fun greaterThanOrEq(value: T): Operator<T> = operator.greaterThanOrEq(value) override fun lessThan(value: T): Operator<T> = operator.lessThan(value) override fun lessThanOrEq(value: T): Operator<T> = operator.lessThanOrEq(value) override fun between(value: T): Operator.Between<T> = operator.between(value) override fun `in`(firstValue: T, vararg values: T): Operator.In<T> = operator.`in`(firstValue, *values) override fun notIn(firstValue: T, vararg values: T): Operator.In<T> = operator.notIn(firstValue, *values) override fun `in`(values: Collection<T>): Operator.In<T> = operator.`in`(values) override fun notIn(values: Collection<T>): Operator.In<T> = operator.notIn(values) override fun concatenate(value: Any?): Operator<T> = operator.concatenate(value) override fun plus(value: T): Operator<T> = operator.plus(value) override fun minus(value: T): Operator<T> = operator.minus(value) override fun div(value: T): Operator<T> = operator.div(value) override fun times(value: T): Operator<T> = operator.times(value) override fun rem(value: T): Operator<T> = operator.rem(value) override fun asc(): OrderBy = OrderBy.fromProperty(this).ascending() override fun desc(): OrderBy = OrderBy.fromProperty(this).descending() companion object { @JvmStatic val ALL_PROPERTY = Property<String>(null, NameAlias.rawBuilder("*").build()) @JvmStatic val NO_PROPERTY = Property<String>(null, NameAlias.rawBuilder("").build()) @JvmStatic val WILDCARD: Property<*> = Property<Any>(null, NameAlias.rawBuilder("?").build()) @JvmStatic fun allProperty(table: Class<*>): Property<String> = Property<String>(table, NameAlias.rawBuilder("*").build()).withTable() } }
mit
1702661b6278e915391a9e89c8a89989
37.349442
107
0.694164
4.504803
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/coroutines/suspendFunctionAsCoroutine/inline.kt
2
678
// WITH_RUNTIME // WITH_COROUTINES import helpers.* import kotlin.coroutines.experimental.* import kotlin.coroutines.experimental.intrinsics.* suspend fun suspendThere(v: String): String = suspendCoroutineOrReturn { x -> x.resume(v) COROUTINE_SUSPENDED } suspend inline fun suspendHere(crossinline block: () -> String): String { return suspendThere(block()) + suspendThere(block()) } fun builder(c: suspend () -> Unit) { c.startCoroutine(EmptyContinuation) } fun box(): String { var result = "" builder { var q = "O" result = suspendHere { val r = q q = "K" r } } return result }
apache-2.0
43684e810618e9bf61d68af71f73d6dc
19.545455
77
0.620944
4.134146
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/boxInline/callableReference/bound/filter.kt
2
293
// WITH_RUNTIME // FILE: 1.kt package test inline fun stub(f: () -> String): String = f() // FILE: 2.kt import test.* class A(val z: String) { fun filter(s: String) = z == s } fun box(): String { val a = A("OK") val s = arrayOf("OK") return s.filter(a::filter).first() }
apache-2.0
d01d62d007a8227893744c200d48de72
13
46
0.559727
2.764151
false
true
false
false
smmribeiro/intellij-community
plugins/kotlin/jvm-debugger/util/src/org/jetbrains/kotlin/idea/debugger/evaluate/KotlinDebuggerEvaluator.kt
3
2745
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.debugger.evaluate import com.intellij.debugger.engine.DebugProcessImpl import com.intellij.debugger.engine.JavaDebuggerEvaluator import com.intellij.debugger.engine.JavaStackFrame import com.intellij.debugger.engine.evaluation.TextWithImports import com.intellij.openapi.util.text.StringUtil import com.intellij.xdebugger.XExpression import com.intellij.xdebugger.XSourcePosition import com.intellij.xdebugger.frame.XValue import com.intellij.xdebugger.impl.evaluate.quick.XValueHint import com.intellij.xdebugger.impl.ui.tree.nodes.EvaluatingExpressionRootNode import com.intellij.xdebugger.impl.ui.tree.nodes.WatchNodeImpl import java.util.* private data class Key(val text: String, val imports: String) { constructor(expr: XExpression) : this(expr.expression, StringUtil.notNullize(expr.customInfo)) constructor(text: TextWithImports) : this(text.text, text.imports) } class KotlinDebuggerEvaluator( debugProcess: DebugProcessImpl?, stackFrame: JavaStackFrame? ) : JavaDebuggerEvaluator(debugProcess, stackFrame) { private val types = HashMap<Key, EvaluationType>() fun getType(text: TextWithImports): EvaluationType { return types[Key(text)] ?: EvaluationType.UNKNOWN } override fun evaluate(expression: XExpression, callback: XEvaluationCallback, expressionPosition: XSourcePosition?) { val key = Key(expression) val type = getType(callback) if (type != null) { types[key] = type } val wrappedCallback = object : XEvaluationCallback { override fun errorOccurred(errorMessage: String) { types.remove(key) callback.errorOccurred(errorMessage) } override fun evaluated(result: XValue) { types.remove(key) callback.evaluated(result) } } super.evaluate(expression, wrappedCallback, expressionPosition) } private fun getType(callback: XEvaluationCallback): EvaluationType? { val name = callback.javaClass.name for (value in EvaluationType.values()) { val clazz = value.clazz ?: continue if (name.startsWith(clazz.name)) { return value } } return null } @Suppress("unused") enum class EvaluationType(val clazz: Class<*>?) { WATCH(WatchNodeImpl::class.java), WINDOW(EvaluatingExpressionRootNode::class.java), POPUP(XValueHint::class.java), FROM_JAVA(null), UNKNOWN(null); } }
apache-2.0
785a212f293f433e5c6190e207172723
35.613333
158
0.696903
4.582638
false
false
false
false
kickstarter/android-oss
app/src/main/java/com/kickstarter/libs/utils/extensions/StringExt.kt
1
4167
@file:JvmName("StringExt") package com.kickstarter.libs.utils.extensions import android.util.Patterns import com.kickstarter.R import org.jsoup.Jsoup import java.util.Locale import java.util.regex.Matcher import java.util.regex.Pattern const val MINIMUM_PASSWORD_LENGTH = 6 /** * Returns a boolean that reflects if the string is an email address */ fun String.isEmail(): Boolean { return Patterns.EMAIL_ADDRESS.matcher(this).matches() } /** * Returns a boolean that reflects if the string url contains a valid MP3 format */ fun String.isMP3Url(): Boolean { val regex = "^https?://\\S+\\.mp3" val pattern: Pattern = Pattern.compile(regex) val matcher: Matcher = pattern.matcher(this) return matcher.find() } /** * Returns a boolean that reflects if the string is empty or the length is zero when white space * characters are trimmed */ fun String.isTrimmedEmpty(): Boolean { return this.trimAllWhitespace().length == 0 } /** * Returns a boolean of if the string is not empty */ fun String.isPresent() = !this.isTrimmedEmpty() /** * Returns a boolean of if the string is not empty and has more than 5 characters */ fun String.isValidPassword(): Boolean { return !this.isTrimmedEmpty() && this.length >= MINIMUM_PASSWORD_LENGTH } /** * Returns a string with only the first character capitalized. */ fun String.sentenceCase(): String { return if (this.length <= 1) this.uppercase(Locale.getDefault()) else this.substring(0, 1).uppercase(Locale.getDefault()) + this.substring(1) .lowercase(Locale.getDefault()) } /** * Returns a string with no leading or trailing whitespace. Takes all the unicode and replaces it with * whiteSpace character, them trims the start of the string and the end. */ fun String.trimAllWhitespace(): String { return this.replace('\u00A0', ' ').trimStart().trim() } /** * Returns a string wrapped in parentheses. */ fun String.wrapInParentheses() = "($this)" fun String.parseHtmlTag(): String { return Jsoup.parse(this).text() } /** * Takes an optional String and returns a Double * NOTE: NumberUtils.parse(String, Locale) * - Depending on the Locale the decimal separator 0.99 or 0,99 * - Depending on the Locale the Character used for thousand separator can change 9.999 or 9,999 * * We've compiled several Regex to account for use cases as not all the languages are listed as Default Locale * as example Spanish or Polish, take a look at * @see <a href="https://github.com/frohoff/jdk8u-jdk/blob/da0da73ab82ed714dc5be94acd2f0d00fbdfe2e9/src/share/classes/java/util/Locale.java#L484">Locale.java</a> * * The Strings will be modified to use "." as a decimal separator, and "" as the thousand separator * * - In case something wrong, it will return 0.0 */ fun String?.parseToDouble(): Double { val numToParse = this?.let { numToParse -> return@let when { "[0-9]+,[0-9]+".toRegex().matches(numToParse) -> numToParse.replace(",", ".") "[0-9]+.[0-9]{3}".toRegex().matches(numToParse) -> numToParse.replace(".", "") "[0-9]+.[0-9]{3},[0-9]+".toRegex().matches(numToParse) -> numToParse.replace(".", "").replace(",", ".") else -> numToParse } } return numToParse?.toDoubleOrNull() ?: 0.0 } /** * Returns a boolean that reflects if the string is an email address */ fun String.isGif(): Boolean { val gifPattern = "(?:\\/\\/.*\\.(?:gif))" return gifPattern.toRegex().find(this) != null } /** * Mask Email */ fun String.maskEmail(): String { val regex = """(.{1,4}@)""".toRegex() return this.replace(regex, "****@") } /** * validate password isNotEmptyAndAtLeast6Chars */ fun String.isNotEmptyAndAtLeast6Chars() = this.isNotEmpty() && this.length >= MINIMUM_PASSWORD_LENGTH /** * new Password Validation Warnings message */ fun String.newPasswordValidationWarnings(confirmPassword: String): Int? { return if (this.isNotEmpty() && this.length in 1 until MINIMUM_PASSWORD_LENGTH) R.string.Password_min_length_message else if (confirmPassword.isNotEmpty() && confirmPassword != this) R.string.Passwords_matching_message else null }
apache-2.0
3737b4118abd01645711bc65551f9032
30.568182
161
0.687545
3.687611
false
false
false
false
fabmax/kool
kool-core/src/jsMain/kotlin/de/fabmax/kool/modules/audio/AudioOutput.kt
1
1979
package de.fabmax.kool.modules.audio import de.fabmax.kool.util.Float32BufferImpl import de.fabmax.kool.util.createFloat32Buffer /** * @author fabmax */ @Suppress("UnsafeCastFromDynamic", "CanBeParameter") actual class AudioOutput actual constructor(actual val bufSize: Int) { private val audioCtx = js("new AudioContext();") actual val sampleRate: Float = audioCtx.sampleRate actual var isPaused: Boolean = false set(value) { if (field != value) { field = value if (value) { source.stop() } else { source.start() } } } actual val mixer = MixNode() actual var onBufferUpdate: (Double) -> Unit = { } private val source: dynamic private val scriptNode: dynamic private var analyserNode: dynamic private var powerSpectrum: Float32BufferImpl = createFloat32Buffer(1) as Float32BufferImpl private val dt = 1f / sampleRate private var t = 0.0 init { scriptNode = audioCtx.createScriptProcessor(bufSize, 1, 1) val buffer = audioCtx.createBuffer(1, scriptNode.bufferSize, sampleRate) scriptNode.onaudioprocess = { ev: dynamic -> val outputBuffer = ev.outputBuffer val data = outputBuffer.getChannelData(0) val bufSamples: Int = outputBuffer.length onBufferUpdate(t) t += (dt * bufSamples) for (i in 0 until bufSamples) { data[i] = mixer.nextSample(dt) } } analyserNode = null source = audioCtx.createBufferSource() source.buffer = buffer source.loop = true source.connect(scriptNode) scriptNode.connect(audioCtx.destination) source.start() } actual fun close() { scriptNode.disconnect() source.loop = false source.disconnect() source.stop() } }
apache-2.0
6567a13ffdc23e35cdf3a39bb4eb62f0
26.109589
94
0.596261
4.397778
false
false
false
false
ingokegel/intellij-community
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/ChildWpidSampleEntityImpl.kt
1
9189
package com.intellij.workspaceModel.storage.entities.test.api import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.EntityLink import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.UsedClassesCollector import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList import com.intellij.workspaceModel.storage.impl.extractOneToManyParent import com.intellij.workspaceModel.storage.impl.updateOneToManyParentOfChild import com.intellij.workspaceModel.storage.url.VirtualFileUrl import java.util.* import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Child @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class ChildWpidSampleEntityImpl : ChildWpidSampleEntity, WorkspaceEntityBase() { companion object { internal val PARENTENTITY_CONNECTION_ID: ConnectionId = ConnectionId.create(SampleWithPersistentIdEntity::class.java, ChildWpidSampleEntity::class.java, ConnectionId.ConnectionType.ONE_TO_MANY, true) val connections = listOf<ConnectionId>( PARENTENTITY_CONNECTION_ID, ) } @JvmField var _data: String? = null override val data: String get() = _data!! override val parentEntity: SampleWithPersistentIdEntity? get() = snapshot.extractOneToManyParent(PARENTENTITY_CONNECTION_ID, this) override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(val result: ChildWpidSampleEntityData?) : ModifiableWorkspaceEntityBase<ChildWpidSampleEntity>(), ChildWpidSampleEntity.Builder { constructor() : this(ChildWpidSampleEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity ChildWpidSampleEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isEntitySourceInitialized()) { error("Field WorkspaceEntity#entitySource should be initialized") } if (!getEntityData().isDataInitialized()) { error("Field ChildWpidSampleEntity#data should be initialized") } } override fun connectionIdList(): List<ConnectionId> { return connections } // Relabeling code, move information from dataSource to this builder override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) { dataSource as ChildWpidSampleEntity this.entitySource = dataSource.entitySource this.data = dataSource.data if (parents != null) { this.parentEntity = parents.filterIsInstance<SampleWithPersistentIdEntity>().singleOrNull() } } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData().entitySource = value changedProperty.add("entitySource") } override var data: String get() = getEntityData().data set(value) { checkModificationAllowed() getEntityData().data = value changedProperty.add("data") } override var parentEntity: SampleWithPersistentIdEntity? get() { val _diff = diff return if (_diff != null) { _diff.extractOneToManyParent(PARENTENTITY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] as? SampleWithPersistentIdEntity } else { this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] as? SampleWithPersistentIdEntity } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) { // Setting backref of the list if (value is ModifiableWorkspaceEntityBase<*>) { val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(value) } if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) { _diff.updateOneToManyParentOfChild(PARENTENTITY_CONNECTION_ID, this, value) } else { // Setting backref of the list if (value is ModifiableWorkspaceEntityBase<*>) { val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data } // else you're attaching a new entity to an existing entity that is not modifiable this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] = value } changedProperty.add("parentEntity") } override fun getEntityData(): ChildWpidSampleEntityData = result ?: super.getEntityData() as ChildWpidSampleEntityData override fun getEntityClass(): Class<ChildWpidSampleEntity> = ChildWpidSampleEntity::class.java } } class ChildWpidSampleEntityData : WorkspaceEntityData<ChildWpidSampleEntity>() { lateinit var data: String fun isDataInitialized(): Boolean = ::data.isInitialized override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<ChildWpidSampleEntity> { val modifiable = ChildWpidSampleEntityImpl.Builder(null) modifiable.allowModifications { modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() modifiable.entitySource = this.entitySource } modifiable.changedProperty.clear() return modifiable } override fun createEntity(snapshot: EntityStorage): ChildWpidSampleEntity { val entity = ChildWpidSampleEntityImpl() entity._data = data entity.entitySource = entitySource entity.snapshot = snapshot entity.id = createEntityId() return entity } override fun getEntityInterface(): Class<out WorkspaceEntity> { return ChildWpidSampleEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity { return ChildWpidSampleEntity(data, entitySource) { this.parentEntity = parents.filterIsInstance<SampleWithPersistentIdEntity>().singleOrNull() } } override fun getRequiredParents(): List<Class<out WorkspaceEntity>> { val res = mutableListOf<Class<out WorkspaceEntity>>() return res } override fun equals(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as ChildWpidSampleEntityData if (this.entitySource != other.entitySource) return false if (this.data != other.data) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as ChildWpidSampleEntityData if (this.data != other.data) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + data.hashCode() return result } override fun hashCodeIgnoringEntitySource(): Int { var result = javaClass.hashCode() result = 31 * result + data.hashCode() return result } override fun collectClassUsagesData(collector: UsedClassesCollector) { collector.sameForAllEntities = true } }
apache-2.0
ead7bbcc9a7790988389f8969a4d10d5
36.202429
165
0.703014
5.281034
false
false
false
false
kivensolo/UiUsingListView
app-Kotlin-Coroutines-Examples/src/main/java/com/kingz/coroutines/learn/errorhandling/supervisor/IgnoreErrorAndContinueActivity.kt
1
3374
package com.kingz.coroutines.learn.errorhandling.supervisor import android.os.Bundle import android.view.View import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.LinearLayoutManager import com.kingz.base.response.Status import com.kingz.coroutines.data.api.ApiHelperImpl import com.kingz.coroutines.data.api.RetrofitBuilder import com.kingz.coroutines.data.local.DatabaseBuilder import com.kingz.coroutines.data.local.DatabaseHelperImpl import com.kingz.coroutines.data.model.ApiUser import com.kingz.coroutines.learn.base.ApiUserAdapter import com.kingz.coroutines.utils.ViewModelFactory import com.zeke.example.coroutines.R import kotlinx.android.synthetic.main.activity_recycler_view.* /** * Learn how to use supervisorScope to ignore error of a task and continue with other task. * In other words, if more than two child jobs are running in parallel under a supervisor, * one child job gets failed, we can continue with other. * 任务错误后,Scope不终止的例子 */ class IgnoreErrorAndContinueActivity : AppCompatActivity() { private lateinit var viewModel: IgnoreErrorAndContinueViewModel private lateinit var adapter: ApiUserAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_recycler_view) setupUI() setupViewModel() setupObserver() } private fun setupUI() { recyclerView.layoutManager = LinearLayoutManager(this) adapter = ApiUserAdapter( arrayListOf() ) recyclerView.addItemDecoration( DividerItemDecoration( recyclerView.context, (recyclerView.layoutManager as LinearLayoutManager).orientation ) ) recyclerView.adapter = adapter } private fun setupObserver() { viewModel.getUsers().observe(this, Observer { when (it.status) { Status.SUCCESS -> { progressBar.visibility = View.GONE it.data?.let { users -> renderList(users) } recyclerView.visibility = View.VISIBLE } Status.LOADING -> { progressBar.visibility = View.VISIBLE recyclerView.visibility = View.GONE } Status.ERROR -> { //Handle Error progressBar.visibility = View.GONE Toast.makeText(this, it.message, Toast.LENGTH_LONG).show() } } }) } private fun renderList(users: List<ApiUser>) { adapter.addData(users) adapter.notifyDataSetChanged() } private fun setupViewModel() { viewModel = ViewModelProvider( this, ViewModelFactory.build { IgnoreErrorAndContinueViewModel( ApiHelperImpl(RetrofitBuilder.USER_SERVICE_API), DatabaseHelperImpl(DatabaseBuilder.getInstance(applicationContext)) ) } ).get(IgnoreErrorAndContinueViewModel::class.java) } }
gpl-2.0
ad3f643e870515c92027f372e51daa97
35.021505
92
0.657612
5.161787
false
false
false
false
siosio/intellij-community
platform/statistics/src/com/intellij/internal/statistic/local/ActionsLocalSummary.kt
1
3878
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.internal.statistic.local import com.intellij.internal.statistic.utils.getPluginInfo import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.ex.AnActionListener import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.* import com.intellij.openapi.extensions.ExtensionNotApplicableException import com.intellij.openapi.util.SimpleModificationTracker import com.intellij.util.xmlb.annotations.Attribute import com.intellij.util.xmlb.annotations.Property import com.intellij.util.xmlb.annotations.Tag import com.intellij.util.xmlb.annotations.XMap import kotlin.math.max import kotlin.math.min @State(name = "ActionsLocalSummary", storages = [Storage("actionSummary.xml", roamingType = RoamingType.DISABLED)], reportStatistic = false) @Service class ActionsLocalSummary : PersistentStateComponent<ActionsLocalSummaryState>, SimpleModificationTracker() { @Volatile private var state = ActionsLocalSummaryState() @Volatile private var totalSummary: ActionsTotalSummary = ActionsTotalSummary() override fun getState() = state override fun loadState(state: ActionsLocalSummaryState) { this.state = state this.totalSummary = calculateTotalSummary(state) } private fun calculateTotalSummary(state: ActionsLocalSummaryState): ActionsTotalSummary { var maxUsageCount = 0 var minUsageCount = Integer.MAX_VALUE for (value in state.data.values) { maxUsageCount = max(maxUsageCount, value.usageCount) minUsageCount = min(minUsageCount, value.usageCount) } return ActionsTotalSummary(maxUsageCount, minUsageCount) } @Synchronized fun getTotalStats(): ActionsTotalSummary = totalSummary @Synchronized fun getActionsStats(): Map<String, ActionSummary> = if (state.data.isEmpty()) emptyMap() else HashMap(state.data) @Synchronized fun getActionStatsById(actionId: String): ActionSummary? = state.data[actionId] @Synchronized internal fun updateActionsSummary(actionId: String) { val summary = state.data.computeIfAbsent(actionId) { ActionSummary() } summary.lastUsedTimestamp = System.currentTimeMillis() summary.usageCount++ totalSummary.maxUsageCount = max(summary.usageCount, totalSummary.maxUsageCount) totalSummary.minUsageCount = min(summary.usageCount, totalSummary.minUsageCount) incModificationCount() } } @Tag("i") class ActionSummary { @Attribute("c") @JvmField var usageCount = 0 @Attribute("l") @JvmField var lastUsedTimestamp = System.currentTimeMillis() override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as ActionSummary return usageCount == other.usageCount && lastUsedTimestamp == other.lastUsedTimestamp } override fun hashCode() = (31 * usageCount) + lastUsedTimestamp.hashCode() } data class ActionsLocalSummaryState(@get:XMap(entryTagName = "e", keyAttributeName = "n") @get:Property(surroundWithTag = false) internal val data: MutableMap<String, ActionSummary> = HashMap()) data class ActionsTotalSummary(var maxUsageCount: Int = 0, var minUsageCount: Int = 0) private class ActionsLocalSummaryListener : AnActionListener { private val service = ApplicationManager.getApplication().getService(ActionsLocalSummary::class.java) ?: throw ExtensionNotApplicableException.INSTANCE override fun beforeActionPerformed(action: AnAction, event: AnActionEvent) { if (getPluginInfo(action::class.java).isSafeToReport()) { service.updateActionsSummary(event.actionManager.getId(action) ?: action.javaClass.name) } } }
apache-2.0
071c352770ef028f4ad68eb4c63576b9
38.181818
194
0.777463
4.859649
false
false
false
false
siosio/intellij-community
plugins/markdown/src/org/intellij/plugins/markdown/fileActions/importFrom/docx/MarkdownImportFromDocxAction.kt
1
1915
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.intellij.plugins.markdown.fileActions.importFrom.docx import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.fileChooser.FileChooser import com.intellij.openapi.fileChooser.FileChooserDescriptor import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory import com.intellij.openapi.fileChooser.PathChooserDialog import com.intellij.openapi.vfs.VirtualFile import org.intellij.plugins.markdown.MarkdownBundle import org.intellij.plugins.markdown.fileActions.export.MarkdownDocxExportProvider import org.intellij.plugins.markdown.fileActions.utils.MarkdownImportExportUtils internal class MarkdownImportFromDocxAction : AnAction() { override fun actionPerformed(event: AnActionEvent) { val project = event.project ?: return val descriptor = DocxFileChooserDescriptor().apply { putUserData(PathChooserDialog.PREFER_LAST_OVER_EXPLICIT, null) } FileChooser.chooseFiles(descriptor, project, null) { files: List<VirtualFile> -> for (vFileToImport in files) { if (descriptor.isFileSelectable(vFileToImport)) { val suggestedFilePath = MarkdownImportExportUtils.suggestFileNameToCreate(project, vFileToImport, event.dataContext) val importTaskTitle = MarkdownBundle.message("markdown.import.docx.convert.task.title") MarkdownImportDocxDialog(vFileToImport, importTaskTitle, project, suggestedFilePath).show() } } } } private class DocxFileChooserDescriptor : FileChooserDescriptor(FileChooserDescriptorFactory.createSingleFileNoJarsDescriptor()) { override fun isFileSelectable(file: VirtualFile): Boolean { return file.extension == MarkdownDocxExportProvider.format.extension } } }
apache-2.0
d38ad38ce4ff1b85ee8895b3568be406
50.756757
140
0.802611
4.94832
false
false
false
false
siosio/intellij-community
plugins/kotlin/frontend-fir/test/org/jetbrains/kotlin/idea/fir/AbstractKtDeclarationAndFirDeclarationEqualityChecker.kt
2
1850
/* * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.fir import com.intellij.openapi.util.io.FileUtil import com.intellij.rt.execution.junit.FileComparisonFailure import org.jetbrains.kotlin.fir.declarations.FirFunction import org.jetbrains.kotlin.idea.fir.low.level.api.api.getOrBuildFirOfType import org.jetbrains.kotlin.idea.fir.low.level.api.api.getResolveState import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtFunction import org.jetbrains.kotlin.psi.psiUtil.forEachDescendantOfType import java.io.File abstract class AbstractKtDeclarationAndFirDeclarationEqualityChecker : KotlinLightCodeInsightFixtureTestCase() { protected fun doTest(path: String) { val file = File(path) val ktFile = myFixture.configureByText(file.name, FileUtil.loadFile(file)) as KtFile val resolveState = ktFile.getResolveState() ktFile.forEachDescendantOfType<KtFunction> { ktFunction -> val firFunction = ktFunction.getOrBuildFirOfType<FirFunction<*>>(resolveState) if (!KtDeclarationAndFirDeclarationEqualityChecker.representsTheSameDeclaration(ktFunction, firFunction)) { throw FileComparisonFailure( /* message= */ null, KtDeclarationAndFirDeclarationEqualityChecker.renderPsi(ktFunction, firFunction.session), KtDeclarationAndFirDeclarationEqualityChecker.renderFir(firFunction), /* expectedFilePath= */ null ) } } } }
apache-2.0
5f8922aa22525a5c1321dc1cb392790a
50.388889
133
0.721081
4.907162
false
true
false
false
BijoySingh/Quick-Note-Android
markdown/src/main/java/com/maubis/markdown/spans/CustomTypefaceSpan.kt
1
790
package com.maubis.markdown.spans import android.graphics.Paint import android.graphics.Typeface import android.text.TextPaint import android.text.style.TypefaceSpan class CustomTypefaceSpan(val tface: Typeface) : TypefaceSpan("san-serif"), ICustomSpan { override fun updateDrawState(paint: TextPaint) { applyTypeFace(paint, tface) } override fun updateMeasureState(paint: TextPaint) { applyTypeFace(paint, tface) } private fun applyTypeFace(paint: Paint, typeface: Typeface) { val oldStyle = paint.typeface?.style ?: 0 val isFake = oldStyle and tface.style.inv() if (isFake and Typeface.BOLD != 0) { paint.isFakeBoldText = true } if (isFake and Typeface.ITALIC != 0) { paint.textSkewX = -0.25f } paint.typeface = tface } }
gpl-3.0
078c3b1acf9973c79dd8bb989579a17d
24.516129
88
0.713924
3.726415
false
false
false
false
JetBrains/kotlin-native
runtime/src/main/kotlin/kotlin/native/internal/Cleaner.kt
1
4617
/* * Copyright 2010-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE file. */ package kotlin.native.internal import kotlin.native.concurrent.* import kotlinx.cinterop.NativePtr public interface Cleaner /** * Creates an object with a cleanup associated. * * After the resulting object ("cleaner") gets deallocated by memory manager, * [block] is eventually called once with [argument]. * * Example of usage: * ``` * class ResourceWrapper { * private val resource = Resource() * * private val cleaner = createCleaner(resource) { it.dispose() } * } * ``` * * When `ResourceWrapper` becomes unused and gets deallocated, its `cleaner` * is also deallocated, and the resource is disposed later. * * It is not specified which thread runs [block], as well as whether two or more * blocks from different cleaners can be run in parallel. * * Note: if [argument] refers (directly or indirectly) the cleaner, then both * might leak, and the [block] will not be called in this case. * For example, the code below has a leak: * ``` * class LeakingResourceWrapper { * private val resource = Resource() * private val cleaner = createCleaner(this) { it.resource.dispose() } * } * ``` * In this case cleaner's argument (`LeakingResourceWrapper`) can't be deallocated * until cleaner's block is executed, which can happen only strictly after * the cleaner is deallocated, which can't happen until `LeakingResourceWrapper` * is deallocated. So the requirements on object deallocations are contradictory * in this case, which can't be handled gracefully. The cleaner's block * is not executed then, and cleaner and its argument might leak * (depending on the implementation). * * [block] should not use `@ThreadLocal` globals, because it may * be executed on a different thread. * * If [block] throws an exception, the behavior is unspecified. * * Cleaners should not be kept in globals, because if cleaner is not deallocated * before exiting main(), it'll never get executed. * Use `Platform.isCleanersLeakCheckerActive` to warn about unexecuted cleaners. * * If cleaners are not GC'd before main() exits, then it's not guaranteed that * they will be run. Moreover, it depends on `Platform.isCleanersLeakCheckerActive`. * With the checker enabled, cleaners will be run (and therefore not reported as * unexecuted cleaners); with the checker disabled - they might not get run. * * @param argument must be shareable * @param block must not capture anything */ // TODO: Consider just annotating the lambda argument rather than hardcoding checking // by function name in the compiler. @ExperimentalStdlibApi @ExportForCompiler fun <T> createCleaner(argument: T, block: (T) -> Unit): Cleaner { if (!argument.isShareable()) throw IllegalArgumentException("$argument must be shareable") val clean = { // TODO: Maybe if this fails with exception, it should be (optionally) reported. block(argument) }.freeze() // Make sure there's an extra reference to clean, so it's definitely alive when CleanerImpl is destroyed. val cleanPtr = createStablePointer(clean) // Make sure cleaner worker is initialized. getCleanerWorker() return CleanerImpl(cleanPtr).freeze() } /** * Perform GC on a worker that executes Cleaner blocks. */ @InternalForKotlinNative fun performGCOnCleanerWorker() = getCleanerWorker().execute(TransferMode.SAFE, {}) { GC.collect() }.result /** * Wait for a worker that executes Cleaner blocks to complete its scheduled tasks. */ @InternalForKotlinNative fun waitCleanerWorker() = getCleanerWorker().execute(TransferMode.SAFE, {}) { Unit }.result @SymbolName("Kotlin_CleanerImpl_getCleanerWorker") external private fun getCleanerWorker(): Worker @ExportForCppRuntime("Kotlin_CleanerImpl_shutdownCleanerWorker") private fun shutdownCleanerWorker(worker: Worker, executeScheduledCleaners: Boolean) { worker.requestTermination(executeScheduledCleaners).result } @ExportForCppRuntime("Kotlin_CleanerImpl_createCleanerWorker") private fun createCleanerWorker(): Worker { return Worker.start(errorReporting = false, name = "Cleaner worker") } @NoReorderFields @ExportTypeInfo("theCleanerImplTypeInfo") @HasFinalizer private class CleanerImpl( private val cleanPtr: NativePtr, ): Cleaner {} @SymbolName("Kotlin_Any_isShareable") external private fun Any?.isShareable(): Boolean @SymbolName("CreateStablePointer") external private fun createStablePointer(obj: Any): NativePtr
apache-2.0
50b3b36eb109281505fdd10fdbc635a0
33.977273
109
0.739874
4.208751
false
false
false
false
androidx/androidx
compose/ui/ui-text/src/androidMain/kotlin/androidx/compose/ui/text/platform/extensions/SpannableExtensions.android.kt
3
18471
/* * 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.ui.text.platform.extensions import android.graphics.Typeface import android.os.Build import android.text.Spannable import android.text.Spanned import android.text.style.AbsoluteSizeSpan import android.text.style.BackgroundColorSpan import android.text.style.ForegroundColorSpan import android.text.style.LeadingMarginSpan import android.text.style.LocaleSpan import android.text.style.MetricAffectingSpan import android.text.style.RelativeSizeSpan import android.text.style.ScaleXSpan import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.ShaderBrush import androidx.compose.ui.graphics.Shadow import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.drawscope.DrawStyle import androidx.compose.ui.graphics.isSpecified import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.ExperimentalTextApi import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.android.InternalPlatformTextApi import androidx.compose.ui.text.android.style.BaselineShiftSpan import androidx.compose.ui.text.android.style.FontFeatureSpan import androidx.compose.ui.text.android.style.LetterSpacingSpanEm import androidx.compose.ui.text.android.style.LetterSpacingSpanPx import androidx.compose.ui.text.android.style.LineHeightSpan import androidx.compose.ui.text.android.style.LineHeightStyleSpan import androidx.compose.ui.text.android.style.ShadowSpan import androidx.compose.ui.text.android.style.SkewXSpan import androidx.compose.ui.text.android.style.TextDecorationSpan import androidx.compose.ui.text.android.style.TypefaceSpan import androidx.compose.ui.text.fastFilter import androidx.compose.ui.text.font.Font import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontStyle import androidx.compose.ui.text.font.FontSynthesis import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.intersect import androidx.compose.ui.text.intl.Locale import androidx.compose.ui.text.intl.LocaleList import androidx.compose.ui.text.platform.style.DrawStyleSpan import androidx.compose.ui.text.platform.style.ShaderBrushSpan import androidx.compose.ui.text.style.BaselineShift import androidx.compose.ui.text.style.LineHeightStyle import androidx.compose.ui.text.style.TextDecoration import androidx.compose.ui.text.style.TextGeometricTransform import androidx.compose.ui.text.style.TextIndent import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.TextUnit import androidx.compose.ui.unit.TextUnitType import androidx.compose.ui.unit.isUnspecified import androidx.compose.ui.unit.sp import androidx.compose.ui.util.fastForEach import androidx.compose.ui.util.fastForEachIndexed import kotlin.math.ceil import kotlin.math.roundToInt private data class SpanRange( val span: Any, val start: Int, val end: Int ) internal fun Spannable.setSpan(span: Any, start: Int, end: Int) { setSpan(span, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) } @Suppress("DEPRECATION") internal fun Spannable.setTextIndent( textIndent: TextIndent?, contextFontSize: Float, density: Density ) { textIndent?.let { indent -> if (indent.firstLine == 0.sp && indent.restLine == 0.sp) return@let if (indent.firstLine.isUnspecified || indent.restLine.isUnspecified) return@let with(density) { val firstLine = when (indent.firstLine.type) { TextUnitType.Sp -> indent.firstLine.toPx() TextUnitType.Em -> indent.firstLine.value * contextFontSize else -> 0f } val restLine = when (indent.restLine.type) { TextUnitType.Sp -> indent.restLine.toPx() TextUnitType.Em -> indent.restLine.value * contextFontSize else -> 0f } setSpan( LeadingMarginSpan.Standard( ceil(firstLine).toInt(), ceil(restLine).toInt() ), 0, length ) } } } @OptIn(InternalPlatformTextApi::class, ExperimentalTextApi::class) internal fun Spannable.setLineHeight( lineHeight: TextUnit, contextFontSize: Float, density: Density, lineHeightStyle: LineHeightStyle ) { val resolvedLineHeight = resolveLineHeightInPx(lineHeight, contextFontSize, density) if (!resolvedLineHeight.isNaN()) { // in order to handle empty lines (including empty text) better, change endIndex so that // it won't apply trimLastLineBottom rule val endIndex = if (isEmpty() || last() == '\n') length + 1 else length setSpan( span = LineHeightStyleSpan( lineHeight = resolvedLineHeight, startIndex = 0, endIndex = endIndex, trimFirstLineTop = lineHeightStyle.trim.isTrimFirstLineTop(), trimLastLineBottom = lineHeightStyle.trim.isTrimLastLineBottom(), topRatio = lineHeightStyle.alignment.topRatio ), start = 0, end = length ) } } @OptIn(InternalPlatformTextApi::class) internal fun Spannable.setLineHeight( lineHeight: TextUnit, contextFontSize: Float, density: Density ) { val resolvedLineHeight = resolveLineHeightInPx(lineHeight, contextFontSize, density) if (!resolvedLineHeight.isNaN()) { setSpan( span = LineHeightSpan(lineHeight = resolvedLineHeight), start = 0, end = length ) } } private fun resolveLineHeightInPx( lineHeight: TextUnit, contextFontSize: Float, density: Density ): Float { return when (lineHeight.type) { TextUnitType.Sp -> with(density) { lineHeight.toPx() } TextUnitType.Em -> lineHeight.value * contextFontSize else -> Float.NaN } } internal fun Spannable.setSpanStyles( contextTextStyle: TextStyle, spanStyles: List<AnnotatedString.Range<SpanStyle>>, density: Density, resolveTypeface: (FontFamily?, FontWeight, FontStyle, FontSynthesis) -> Typeface, ) { setFontAttributes(contextTextStyle, spanStyles, resolveTypeface) // LetterSpacingSpanPx/LetterSpacingSpanSP has lower priority than normal spans. Because // letterSpacing relies on the fontSize on [Paint] to compute Px/Sp from Em. So it must be // applied after all spans that changes the fontSize. val lowPrioritySpans = ArrayList<SpanRange>() for (i in spanStyles.indices) { val spanStyleRange = spanStyles[i] val start = spanStyleRange.start val end = spanStyleRange.end if (start < 0 || start >= length || end <= start || end > length) continue setSpanStyle( spanStyleRange, density, lowPrioritySpans ) } lowPrioritySpans.fastForEach { (span, start, end) -> setSpan(span, start, end) } } @OptIn(ExperimentalTextApi::class) private fun Spannable.setSpanStyle( spanStyleRange: AnnotatedString.Range<SpanStyle>, density: Density, lowPrioritySpans: ArrayList<SpanRange> ) { val start = spanStyleRange.start val end = spanStyleRange.end val style = spanStyleRange.item // Be aware that SuperscriptSpan needs to be applied before all other spans which // affect FontMetrics setBaselineShift(style.baselineShift, start, end) setColor(style.color, start, end) setBrush(style.brush, style.alpha, start, end) setTextDecoration(style.textDecoration, start, end) setFontSize(style.fontSize, density, start, end) setFontFeatureSettings(style.fontFeatureSettings, start, end) setGeometricTransform(style.textGeometricTransform, start, end) setLocaleList(style.localeList, start, end) setBackground(style.background, start, end) setShadow(style.shadow, start, end) setDrawStyle(style.drawStyle, start, end) createLetterSpacingSpan(style.letterSpacing, density)?.let { lowPrioritySpans.add( SpanRange(it, start, end) ) } } /** * Set font related [SpanStyle]s to this [Spannable]. * * Different from other styles, font related styles needs to be flattened first and then applied. * This is required because on certain API levels the [FontWeight] is not supported by framework, * and we have to resolve font settings and create typeface first and then set it directly on * TextPaint. * * Notice that a [contextTextStyle] is also required when we flatten the font related styles. * For example: * the entire text has the TextStyle(fontFamily = Sans-serif) * Hi Hello World * [ bold ] * FontWeight.Bold is set in range [0, 8). * The resolved TypefaceSpan should be TypefaceSpan("Sans-serif", "bold") in range [0, 8). * As demonstrated above, the fontFamily information is from [contextTextStyle]. * * @see flattenFontStylesAndApply * * @param contextTextStyle the global [TextStyle] for the entire string. * @param spanStyles the [spanStyles] to be applied, this function will first filter out the font * related [SpanStyle]s and then apply them to this [Spannable]. * @param fontFamilyResolver the [Font.ResourceLoader] used to resolve font. */ @OptIn(InternalPlatformTextApi::class) private fun Spannable.setFontAttributes( contextTextStyle: TextStyle, spanStyles: List<AnnotatedString.Range<SpanStyle>>, resolveTypeface: (FontFamily?, FontWeight, FontStyle, FontSynthesis) -> Typeface, ) { val fontRelatedSpanStyles = spanStyles.fastFilter { it.item.hasFontAttributes() || it.item.fontSynthesis != null } // Create a SpanStyle if contextTextStyle has font related attributes, otherwise use // null to avoid unnecessary object creation. val contextFontSpanStyle = if (contextTextStyle.hasFontAttributes()) { SpanStyle( fontFamily = contextTextStyle.fontFamily, fontWeight = contextTextStyle.fontWeight, fontStyle = contextTextStyle.fontStyle, fontSynthesis = contextTextStyle.fontSynthesis ) } else { null } flattenFontStylesAndApply( contextFontSpanStyle, fontRelatedSpanStyles ) { spanStyle, start, end -> setSpan( TypefaceSpan( resolveTypeface( spanStyle.fontFamily, spanStyle.fontWeight ?: FontWeight.Normal, spanStyle.fontStyle ?: FontStyle.Normal, spanStyle.fontSynthesis ?: FontSynthesis.All ) ), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE ) } } /** * Flatten styles in the [spanStyles], so that overlapping styles are merged, and then apply the * [block] on the merged [SpanStyle]. * * @param contextFontSpanStyle the global [SpanStyle]. It act as if every [spanStyles] is applied * on top of it. This parameter is nullable. A null value is exactly the same as a default * SpanStyle, but avoids unnecessary object creation. * @param spanStyles the input [SpanStyle] ranges to be flattened. * @param block the function to be applied on the merged [SpanStyle]. */ internal fun flattenFontStylesAndApply( contextFontSpanStyle: SpanStyle?, spanStyles: List<AnnotatedString.Range<SpanStyle>>, block: (SpanStyle, Int, Int) -> Unit ) { // quick way out for single SpanStyle or empty list. if (spanStyles.size <= 1) { if (spanStyles.isNotEmpty()) { block( contextFontSpanStyle.merge(spanStyles[0].item), spanStyles[0].start, spanStyles[0].end ) } return } // Sort all span start and end points. // S1--S2--E1--S3--E3--E2 val spanCount = spanStyles.size val transitionOffsets = Array(spanCount * 2) { 0 } spanStyles.fastForEachIndexed { idx, spanStyle -> transitionOffsets[idx] = spanStyle.start transitionOffsets[idx + spanCount] = spanStyle.end } transitionOffsets.sort() // S1--S2--E1--S3--E3--E2 // - Go through all minimum intervals // - Find Spans that intersect with the given interval // - Merge all spans in order, starting from contextFontSpanStyle // - Apply the merged SpanStyle to the minimal interval var lastTransitionOffsets = transitionOffsets.first() for (transitionOffset in transitionOffsets) { // There might be duplicated transition offsets, we skip them here. if (transitionOffset == lastTransitionOffsets) { continue } // Check all spans that intersects with this transition range. var mergedSpanStyle = contextFontSpanStyle spanStyles.fastForEach { spanStyle -> // Empty spans do not intersect with anything, skip them. if ( spanStyle.start != spanStyle.end && intersect(lastTransitionOffsets, transitionOffset, spanStyle.start, spanStyle.end) ) { mergedSpanStyle = mergedSpanStyle.merge(spanStyle.item) } } mergedSpanStyle?.let { block(it, lastTransitionOffsets, transitionOffset) } lastTransitionOffsets = transitionOffset } } @OptIn(InternalPlatformTextApi::class) @Suppress("DEPRECATION") private fun createLetterSpacingSpan( letterSpacing: TextUnit, density: Density ): MetricAffectingSpan? { return when (letterSpacing.type) { TextUnitType.Sp -> with(density) { LetterSpacingSpanPx(letterSpacing.toPx()) } TextUnitType.Em -> { LetterSpacingSpanEm(letterSpacing.value) } else -> { null } } } @OptIn(InternalPlatformTextApi::class) private fun Spannable.setShadow(shadow: Shadow?, start: Int, end: Int) { shadow?.let { setSpan( ShadowSpan( it.color.toArgb(), it.offset.x, it.offset.y, correctBlurRadius(it.blurRadius) ), start, end ) } } @OptIn(InternalPlatformTextApi::class) private fun Spannable.setDrawStyle(drawStyle: DrawStyle?, start: Int, end: Int) { drawStyle?.let { setSpan(DrawStyleSpan(it), start, end) } } internal fun Spannable.setBackground(color: Color, start: Int, end: Int) { if (color.isSpecified) { setSpan( BackgroundColorSpan(color.toArgb()), start, end ) } } internal fun Spannable.setLocaleList(localeList: LocaleList?, start: Int, end: Int) { localeList?.let { setSpan( if (Build.VERSION.SDK_INT >= 24) { LocaleListHelperMethods.localeSpan(it) } else { val locale = if (it.isEmpty()) Locale.current else it[0] LocaleSpan(locale.toJavaLocale()) }, start, end ) } } @OptIn(InternalPlatformTextApi::class) private fun Spannable.setGeometricTransform( textGeometricTransform: TextGeometricTransform?, start: Int, end: Int ) { textGeometricTransform?.let { setSpan(ScaleXSpan(it.scaleX), start, end) setSpan(SkewXSpan(it.skewX), start, end) } } @OptIn(InternalPlatformTextApi::class) private fun Spannable.setFontFeatureSettings(fontFeatureSettings: String?, start: Int, end: Int) { fontFeatureSettings?.let { setSpan(FontFeatureSpan(it), start, end) } } @Suppress("DEPRECATION") internal fun Spannable.setFontSize(fontSize: TextUnit, density: Density, start: Int, end: Int) { when (fontSize.type) { TextUnitType.Sp -> with(density) { setSpan( AbsoluteSizeSpan(/* size */ fontSize.toPx().roundToInt(), /* dip */ false), start, end ) } TextUnitType.Em -> { setSpan(RelativeSizeSpan(fontSize.value), start, end) } else -> { } // Do nothing } } @OptIn(InternalPlatformTextApi::class) internal fun Spannable.setTextDecoration(textDecoration: TextDecoration?, start: Int, end: Int) { textDecoration?.let { val textDecorationSpan = TextDecorationSpan( isUnderlineText = TextDecoration.Underline in it, isStrikethroughText = TextDecoration.LineThrough in it ) setSpan(textDecorationSpan, start, end) } } internal fun Spannable.setColor(color: Color, start: Int, end: Int) { if (color.isSpecified) { setSpan(ForegroundColorSpan(color.toArgb()), start, end) } } @OptIn(InternalPlatformTextApi::class) private fun Spannable.setBaselineShift(baselineShift: BaselineShift?, start: Int, end: Int) { baselineShift?.let { setSpan(BaselineShiftSpan(it.multiplier), start, end) } } private fun Spannable.setBrush( brush: Brush?, alpha: Float, start: Int, end: Int ) { brush?.let { when (brush) { is SolidColor -> { setColor(brush.value, start, end) } is ShaderBrush -> { setSpan(ShaderBrushSpan(brush, alpha), start, end) } } } } /** * Returns true if there is any font settings on this [TextStyle]. * @see hasFontAttributes */ private fun TextStyle.hasFontAttributes(): Boolean { return toSpanStyle().hasFontAttributes() || fontSynthesis != null } /** * Helper function that merges a nullable [SpanStyle] with another [SpanStyle]. */ private fun SpanStyle?.merge(spanStyle: SpanStyle): SpanStyle { if (this == null) return spanStyle return this.merge(spanStyle) }
apache-2.0
422e55371d905e7101b61e3bfe9ca565
32.767824
98
0.677549
4.425252
false
false
false
false
djkovrik/YapTalker
data/src/main/java/com/sedsoftware/yaptalker/data/parsed/SearchTopicsPageParsed.kt
1
467
package com.sedsoftware.yaptalker.data.parsed import pl.droidsonroids.jspoon.annotation.Selector class SearchTopicsPageParsed { @Selector(value = "a:matchesOwn(\\d+)", defValue = "") lateinit var hasNextPage: String @Selector(value = "a[href~=searchid]", attr = "href", regex = "searchid=([\\d\\w]+)", defValue = "") lateinit var searchId: String @Selector(value = "table tr:has(td.row4)") lateinit var topics: List<SearchTopicItemParsed> }
apache-2.0
b0126f69586c939f1a8458e04d963d13
37.916667
104
0.698073
3.620155
false
false
false
false
androidx/androidx
camera/camera-camera2-pipe-integration/src/test/java/androidx/camera/camera2/pipe/integration/adapter/FocusMeteringControlTest.kt
3
7529
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.camera.camera2.pipe.integration.adapter import android.graphics.Rect import android.hardware.camera2.params.MeteringRectangle import android.os.Build import android.util.Rational import androidx.camera.camera2.pipe.integration.impl.FocusMeteringControl import com.google.common.truth.Truth.assertThat import org.junit.Test import org.junit.runner.RunWith import org.robolectric.annotation.Config import org.robolectric.annotation.internal.DoNotInstrument @RunWith(RobolectricCameraPipeTestRunner::class) @Config(minSdk = Build.VERSION_CODES.LOLLIPOP) @DoNotInstrument public class FocusMeteringControlTest { @Test public fun meteringRegionsFromMeteringPoint_fovAspectRatioEqualToCropAspectRatio() { val meteringPoint = FakeMeteringPointFactory().createPoint(0.0f, 0.0f) val meteringRectangles = FocusMeteringControl.meteringRegionsFromMeteringPoints( listOf(meteringPoint), Rect(0, 0, 800, 600), Rational(4, 3) ) assertThat(meteringRectangles.size).isEqualTo(1) // Aspect ratio of crop region is same as default aspect ratio. So no padding is needed // along width or height. However only the bottom right quadrant of the metering rectangle // will fit inside the crop region. val expectedMeteringRectangle = MeteringRectangle( 0, 0, 60, 45, FocusMeteringControl.METERING_WEIGHT_DEFAULT ) assertThat(meteringRectangles[0]).isEqualTo(expectedMeteringRectangle) val meteringPoint1 = FakeMeteringPointFactory().createPoint(0.5f, 0.5f) val meteringRectangles1 = FocusMeteringControl.meteringRegionsFromMeteringPoints( listOf(meteringPoint1), Rect(0, 0, 800, 600), Rational(4, 3) ) assertThat(meteringRectangles1.size).isEqualTo(1) // Aspect ratio of crop region is same as default aspect ratio. So no padding is needed // along width or height. The metering region will completely fit inside the crop region. val expectedMeteringRectangle1 = MeteringRectangle( 340, 255, 120, 90, FocusMeteringControl.METERING_WEIGHT_DEFAULT ) assertThat(meteringRectangles1[0]).isEqualTo(expectedMeteringRectangle1) val meteringPoint2 = FakeMeteringPointFactory().createPoint(1f, 1f) val meteringRectangles2 = FocusMeteringControl.meteringRegionsFromMeteringPoints( listOf(meteringPoint2), Rect(0, 0, 800, 600), Rational(4, 3) ) assertThat(meteringRectangles2.size).isEqualTo(1) // Aspect ratio of crop region is same as default aspect ratio. So no padding is needed // along width or height. However only the top left quadrant of the metering rectangle // will fit inside the crop region. val expectedMeteringRectangle2 = MeteringRectangle( 740, 555, 60, 45, FocusMeteringControl.METERING_WEIGHT_DEFAULT ) assertThat(meteringRectangles2[0]).isEqualTo(expectedMeteringRectangle2) } @Test public fun meteringRegionsFromMeteringPoint_fovAspectRatioGreaterThanCropAspectRatio() { val meteringPoint = FakeMeteringPointFactory().createPoint(0.0f, 0.0f) val meteringRectangles = FocusMeteringControl.meteringRegionsFromMeteringPoints( listOf(meteringPoint), Rect(0, 0, 400, 400), Rational(4, 3) ) assertThat(meteringRectangles.size).isEqualTo(1) // Default aspect ratio is greater than the aspect ratio of the crop region. So we need // to add some padding at the top. val expectedMeteringRectangle = MeteringRectangle( 0, 20, 30, 60, FocusMeteringControl.METERING_WEIGHT_DEFAULT ) assertThat(meteringRectangles[0]).isEqualTo(expectedMeteringRectangle) val meteringPoint1 = FakeMeteringPointFactory().createPoint(0.5f, 0.5f) val meteringRectangles1 = FocusMeteringControl.meteringRegionsFromMeteringPoints( listOf(meteringPoint1), Rect(0, 0, 400, 400), Rational(4, 3) ) assertThat(meteringRectangles1.size).isEqualTo(1) val expectedMeteringRectangle1 = MeteringRectangle( 170, 170, 60, 60, FocusMeteringControl.METERING_WEIGHT_DEFAULT ) assertThat(meteringRectangles1[0]).isEqualTo(expectedMeteringRectangle1) val meteringPoint2 = FakeMeteringPointFactory().createPoint(1f, 1f) val meteringRectangles2 = FocusMeteringControl.meteringRegionsFromMeteringPoints( listOf(meteringPoint2), Rect(0, 0, 400, 400), Rational(4, 3) ) assertThat(meteringRectangles2.size).isEqualTo(1) // Default aspect ratio is greater than the aspect ratio of the crop region. So we need // to add some padding at the bottom. val expectedMeteringRectangle2 = MeteringRectangle( 370, 320, 30, 60, FocusMeteringControl.METERING_WEIGHT_DEFAULT ) assertThat(meteringRectangles2[0]).isEqualTo(expectedMeteringRectangle2) } @Test public fun meteringRegionsFromMeteringPoint_fovAspectRatioLessThanCropAspectRatio() { val meteringPoint = FakeMeteringPointFactory().createPoint(0.0f, 0.0f) val meteringRectangles = FocusMeteringControl.meteringRegionsFromMeteringPoints( listOf(meteringPoint), Rect(0, 0, 400, 400), Rational(3, 4) ) assertThat(meteringRectangles.size).isEqualTo(1) val expectedMeteringRectangle = MeteringRectangle( 20, 0, 60, 30, FocusMeteringControl.METERING_WEIGHT_DEFAULT ) assertThat(meteringRectangles[0]).isEqualTo(expectedMeteringRectangle) val meteringPoint1 = FakeMeteringPointFactory().createPoint(0.5f, 0.5f) val meteringRectangles1 = FocusMeteringControl.meteringRegionsFromMeteringPoints( listOf(meteringPoint1), Rect(0, 0, 400, 400), Rational(3, 4) ) assertThat(meteringRectangles1.size).isEqualTo(1) val expectedMeteringRectangle1 = MeteringRectangle( 170, 170, 60, 60, FocusMeteringControl.METERING_WEIGHT_DEFAULT ) assertThat(meteringRectangles1[0]).isEqualTo(expectedMeteringRectangle1) val meteringPoint2 = FakeMeteringPointFactory().createPoint(1f, 1f) val meteringRectangles2 = FocusMeteringControl.meteringRegionsFromMeteringPoints( listOf(meteringPoint2), Rect(0, 0, 400, 400), Rational(3, 4) ) assertThat(meteringRectangles2.size).isEqualTo(1) val expectedMeteringRectangle2 = MeteringRectangle( 320, 370, 60, 30, FocusMeteringControl.METERING_WEIGHT_DEFAULT ) assertThat(meteringRectangles2[0]).isEqualTo(expectedMeteringRectangle2) } }
apache-2.0
1bbb8d0a90e585c770330d6b046fc201
45.481481
98
0.702085
4.462952
false
false
false
false
google/playhvz
Android/ghvzApp/app/src/main/java/com/app/playhvz/screens/quiz/QuizDashboardFragment.kt
1
6795
/* * Copyright 2020 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.app.playhvz.screens.quiz import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.appcompat.app.AppCompatActivity import androidx.fragment.app.Fragment import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.app.playhvz.R import com.app.playhvz.app.EspressoIdlingResource import com.app.playhvz.common.globals.SharedPreferencesConstants import com.app.playhvz.firebase.classmodels.Game import com.app.playhvz.firebase.classmodels.Player import com.app.playhvz.firebase.classmodels.QuizQuestion import com.app.playhvz.firebase.operations.QuizQuestionDatabaseOperations import com.app.playhvz.firebase.viewmodels.GameViewModel import com.app.playhvz.firebase.viewmodels.QuizQuestionListViewModel import com.app.playhvz.navigation.NavigationUtil import com.google.android.material.floatingactionbutton.FloatingActionButton import kotlinx.coroutines.runBlocking /** Fragment for showing a list of rewards.*/ class QuizDashboardFragment : Fragment() { companion object { val TAG = QuizDashboardFragment::class.qualifiedName } lateinit var gameViewModel: GameViewModel lateinit var questionViewModel: QuizQuestionListViewModel lateinit var fab: FloatingActionButton lateinit var recyclerView: RecyclerView lateinit var adapter: QuizDashboardAdapter var gameId: String? = null var playerId: String? = null var game: Game? = null var player: Player? = null var questions: List<QuizQuestion> = listOf() private val onChangeAnswerOrder = { position: Int, modification: OrderingController.OrderModification -> val currentOrdering = questions[position].index!! if (modification == OrderingController.OrderModification.MOVE_UP) { val targetOrdering = currentOrdering - 1 swapQuestions(position, targetOrdering) } else if (modification == OrderingController.OrderModification.MOVE_DOWN) { val targetOrdering = currentOrdering + 1 swapQuestions(position, targetOrdering) } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val sharedPrefs = activity?.getSharedPreferences( SharedPreferencesConstants.PREFS_FILENAME, 0 )!! gameViewModel = GameViewModel() questionViewModel = QuizQuestionListViewModel() gameId = sharedPrefs.getString(SharedPreferencesConstants.CURRENT_GAME_ID, null) playerId = sharedPrefs.getString(SharedPreferencesConstants.CURRENT_PLAYER_ID, null) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { val view = inflater.inflate(R.layout.fragment_quiz_question_dashboard, container, false) fab = activity?.findViewById(R.id.floating_action_button)!! recyclerView = view.findViewById(R.id.question_list) adapter = QuizDashboardAdapter( listOf(), requireContext(), findNavController(), onChangeAnswerOrder ) recyclerView.layoutManager = LinearLayoutManager(context) recyclerView.adapter = adapter setupObservers() setupToolbar() return view } fun setupToolbar() { val toolbar = (activity as AppCompatActivity).supportActionBar if (toolbar != null) { toolbar.title = requireContext().getString(R.string.quiz_dashboard_title) } } private fun setupFab(isAdmin: Boolean) { if (!isAdmin) { fab.visibility = View.GONE return } fab.visibility = View.VISIBLE fab.setOnClickListener { selectQuestionType() } fab.visibility = View.VISIBLE } private fun setupObservers() { if (gameId == null || playerId == null) { return } gameViewModel.getGameAndAdminObserver(this, gameId!!, playerId!!) .observe(viewLifecycleOwner, androidx.lifecycle.Observer { serverGameAndAdminStatus -> updateGame(serverGameAndAdminStatus) }) questionViewModel.getGameQuizQuestions(gameId!!) .observe(viewLifecycleOwner, androidx.lifecycle.Observer { questionList -> updateQuestionList(questionList) }) } private fun updateGame(serverUpdate: GameViewModel.GameWithAdminStatus?) { if (serverUpdate == null) { NavigationUtil.navigateToGameList(findNavController(), requireActivity()) } game = serverUpdate!!.game setupFab(serverUpdate.isAdmin) adapter.setIsAdmin(serverUpdate.isAdmin) adapter.notifyDataSetChanged() } private fun updateQuestionList(questions: List<QuizQuestion?>) { val clean = mutableListOf<QuizQuestion>() for (question in questions) { if (question != null) { clean.add(question) } } clean.sortBy { question -> question.index } this.questions = clean.toList() adapter.setData(this.questions) adapter.notifyDataSetChanged() } private fun selectQuestionType() { val dialog = QuestionTypeSelectorDialog(gameId!!, adapter.itemCount) activity?.supportFragmentManager?.let { dialog.show(it, TAG) } } private fun swapQuestions(currentPostion: Int, endingOrder: Int) { for ((index, value) in questions.withIndex()) { if (value.index == endingOrder) { runBlocking { EspressoIdlingResource.increment() QuizQuestionDatabaseOperations.swapQuestionIndexes( gameId!!, questions[currentPostion], questions[index] ) EspressoIdlingResource.decrement() } return } } } }
apache-2.0
ef52518e21c957bb3ed6254563f83721
36.546961
98
0.671229
5.15163
false
false
false
false
nrizzio/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/jobs/LeaveGroupV2Job.kt
2
1827
package org.thoughtcrime.securesms.jobs import org.thoughtcrime.securesms.dependencies.ApplicationDependencies import org.thoughtcrime.securesms.groups.GroupId import org.thoughtcrime.securesms.jobmanager.Data import org.thoughtcrime.securesms.jobmanager.Job import org.thoughtcrime.securesms.jobmanager.impl.DecryptionsDrainedConstraint /** * During group state processing we sometimes detect situations where we should auto-leave. For example, * being added to a group by someone we've blocked. This job functions similarly to other GV2 related * jobs in that it waits for all decryptions to occur and then enqueues the actual [LeaveGroupV2Job] as * part of the group's message processing queue. */ class LeaveGroupV2Job(parameters: Parameters, private val groupId: GroupId.V2) : BaseJob(parameters) { constructor(groupId: GroupId.V2) : this( parameters = Parameters.Builder() .setQueue("LeaveGroupV2Job") .addConstraint(DecryptionsDrainedConstraint.KEY) .setMaxAttempts(Parameters.UNLIMITED) .build(), groupId = groupId ) override fun serialize(): Data { return Data.Builder() .putString(KEY_GROUP_ID, groupId.toString()) .build() } override fun getFactoryKey(): String { return KEY } override fun onRun() { ApplicationDependencies.getJobManager().add(LeaveGroupV2WorkerJob(groupId)) } override fun onShouldRetry(e: Exception): Boolean = false override fun onFailure() = Unit class Factory : Job.Factory<LeaveGroupV2Job> { override fun create(parameters: Parameters, data: Data): LeaveGroupV2Job { return LeaveGroupV2Job(parameters, GroupId.parseOrThrow(data.getString(KEY_GROUP_ID)).requireV2()) } } companion object { const val KEY = "LeaveGroupV2Job" private const val KEY_GROUP_ID = "group_id" } }
gpl-3.0
b54cd8290d7afb79e32a09870f7e4500
32.218182
104
0.749863
4.105618
false
false
false
false
androidx/androidx
compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/text/ValidatingOffsetMapping.kt
3
2968
/* * 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.compose.foundation.text import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.input.OffsetMapping import androidx.compose.ui.text.input.TransformedText import androidx.compose.ui.text.input.VisualTransformation internal val ValidatingEmptyOffsetMappingIdentity: OffsetMapping = ValidatingOffsetMapping( delegate = OffsetMapping.Identity, originalLength = 0, transformedLength = 0 ) internal fun VisualTransformation.filterWithValidation(text: AnnotatedString): TransformedText { return filter(text).let { transformed -> TransformedText( transformed.text, ValidatingOffsetMapping( delegate = transformed.offsetMapping, originalLength = text.length, transformedLength = transformed.text.length ) ) } } private class ValidatingOffsetMapping( private val delegate: OffsetMapping, private val originalLength: Int, private val transformedLength: Int ) : OffsetMapping { /** * Calls [originalToTransformed][OffsetMapping.originalToTransformed] and throws a detailed * exception if the returned value is outside the range of indices [0, [transformedLength]]. */ override fun originalToTransformed(offset: Int): Int { return delegate.originalToTransformed(offset).also { transformedOffset -> check(transformedOffset in 0..transformedLength) { "OffsetMapping.originalToTransformed returned invalid mapping: " + "$offset -> $transformedOffset is not in range of transformed text " + "[0, $transformedLength]" } } } /** * Calls [transformedToOriginal][OffsetMapping.transformedToOriginal] and throws a detailed * exception if the returned value is outside the range of indices [0, [originalLength]]. */ override fun transformedToOriginal(offset: Int): Int { return delegate.transformedToOriginal(offset).also { originalOffset -> check(originalOffset in 0..originalLength) { "OffsetMapping.transformedToOriginal returned invalid mapping: " + "$offset -> $originalOffset is not in range of original text " + "[0, $originalLength]" } } } }
apache-2.0
0e62873c84bb6ff9593166ea323376ec
38.065789
96
0.689353
4.988235
false
false
false
false
GunoH/intellij-community
platform/script-debugger/backend/src/debugger/sourcemap/SourceMap.kt
8
4975
// 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.debugger.sourcemap import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.Url // sources - is not originally specified, but canonicalized/normalized // lines and columns are zero-based according to specification interface SourceMap { val outFile: String? /** * note: Nested map returns only parent sources */ val sources: Array<Url> val generatedMappings: Mappings val hasNameMappings: Boolean val sourceResolver: SourceResolver fun findSourceMappings(sourceIndex: Int): Mappings fun findSourceIndex(sourceUrl: Url, sourceFile: VirtualFile?, resolver: Lazy<SourceFileResolver?>?, localFileUrlOnly: Boolean): Int fun findSourceMappings(sourceUrl: Url, sourceFile: VirtualFile?, resolver: Lazy<SourceFileResolver?>?, localFileUrlOnly: Boolean): Mappings? { val sourceIndex = findSourceIndex(sourceUrl, sourceFile, resolver, localFileUrlOnly) return if (sourceIndex >= 0) findSourceMappings(sourceIndex) else null } fun getSourceLineByRawLocation(rawLine: Int, rawColumn: Int): Int = generatedMappings.get(rawLine, rawColumn)?.sourceLine ?: -1 fun findSourceIndex(sourceFile: VirtualFile, localFileUrlOnly: Boolean): Int fun getSourceMappingsInLine(sourceIndex: Int, sourceLine: Int): Iterable<MappingEntry> fun processSourceMappingsInLine(sourceIndex: Int, sourceLine: Int, mappingProcessor: MappingsProcessorInLine): Boolean { return mappingProcessor.processIterable(getSourceMappingsInLine(sourceIndex, sourceLine)) } fun getSourceMappingsInLine(sourceUrl: Url, sourceLine: Int, sourceFile: VirtualFile?, resolver: Lazy<SourceFileResolver?>?, localFileUrlOnly: Boolean): Iterable<MappingEntry> { val sourceIndex = findSourceIndex(sourceUrl, sourceFile, resolver, localFileUrlOnly) return if (sourceIndex >= 0) getSourceMappingsInLine(sourceIndex, sourceLine) else emptyList() } fun getRawSource(entry: MappingEntry): String? fun getSourceContent(entry: MappingEntry): String? fun getSourceContent(sourceIndex: Int): String? } abstract class SourceMapBase(protected val sourceMapData: SourceMapData, override val sourceResolver: SourceResolver) : SourceMap { override val outFile: String? get() = sourceMapData.file override val hasNameMappings: Boolean get() = sourceMapData.hasNameMappings protected abstract val sourceIndexToMappings: Array<MappingList?> override val sources: Array<Url> get() = sourceResolver.canonicalizedUrls override fun findSourceIndex(sourceUrl: Url, sourceFile: VirtualFile?, resolver: Lazy<SourceFileResolver?>?, localFileUrlOnly: Boolean): Int { val index = sourceResolver.findSourceIndex(sourceUrl, sourceFile, localFileUrlOnly) if (index == -1 && resolver != null) { return resolver.value?.let { sourceResolver.findSourceIndex(it) } ?: -1 } return index } // returns SourceMappingList override fun findSourceMappings(sourceIndex: Int): MappingList = sourceIndexToMappings[sourceIndex]!! override fun findSourceIndex(sourceFile: VirtualFile, localFileUrlOnly: Boolean): Int = sourceResolver.findSourceIndexByFile(sourceFile, localFileUrlOnly) override fun getSourceMappingsInLine(sourceIndex: Int, sourceLine: Int): Iterable<MappingEntry> { return findSourceMappings(sourceIndex).getMappingsInLine(sourceLine) } override fun processSourceMappingsInLine(sourceIndex: Int, sourceLine: Int, mappingProcessor: MappingsProcessorInLine): Boolean { return findSourceMappings(sourceIndex).processMappingsInLine(sourceLine, mappingProcessor) } override fun getRawSource(entry: MappingEntry): String? { val index = entry.source return if (index < 0) null else sourceMapData.sources[index] } override fun getSourceContent(entry: MappingEntry): String? { val sourcesContent = sourceMapData.sourcesContent if (sourcesContent.isNullOrEmpty()) { return null } val index = entry.source return if (index < 0 || index >= sourcesContent.size) null else sourcesContent[index] } override fun getSourceContent(sourceIndex: Int): String? { val sourcesContent = sourceMapData.sourcesContent if (sourcesContent.isNullOrEmpty()) { return null } return if (sourceIndex < 0 || sourceIndex >= sourcesContent.size) null else sourcesContent[sourceIndex] } } class OneLevelSourceMap(sourceMapDataEx: SourceMapDataEx, sourceResolver: SourceResolver) : SourceMapBase(sourceMapDataEx.sourceMapData, sourceResolver) { override val sourceIndexToMappings: Array<MappingList?> = sourceMapDataEx.sourceIndexToMappings override val generatedMappings: Mappings = sourceMapDataEx.generatedMappings }
apache-2.0
4908dce66d8fc8e033651956b5531f78
39.786885
156
0.750352
5.01007
false
false
false
false
GunoH/intellij-community
platform/lang-impl/src/com/intellij/ide/navbar/ui/NavBarItemComponent.kt
2
10759
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ide.navbar.ui import com.intellij.icons.AllIcons import com.intellij.ide.navbar.NavBarItemPresentation import com.intellij.ide.navbar.vm.NavBarItemVm import com.intellij.ide.navigationToolbar.ui.AbstractNavBarUI import com.intellij.ide.navigationToolbar.ui.AbstractNavBarUI.getDecorationOffset import com.intellij.ide.navigationToolbar.ui.AbstractNavBarUI.getFirstElementLeftOffset import com.intellij.ide.navigationToolbar.ui.ImageType import com.intellij.ide.ui.UISettings import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.actionSystem.ActionPlaces import com.intellij.openapi.application.EDT import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.wm.IdeFocusManager import com.intellij.ui.* import com.intellij.ui.scale.JBUIScale import com.intellij.ui.scale.ScaleContext import com.intellij.util.ui.JBInsets import com.intellij.util.ui.JBUI import com.intellij.util.ui.JBUI.CurrentTheme.StatusBar.Breadcrumbs import com.intellij.util.ui.StartupUiUtil import com.intellij.util.ui.accessibility.ScreenReader import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import org.jetbrains.annotations.Nls import java.awt.* import java.awt.event.MouseAdapter import java.awt.event.MouseEvent import java.awt.image.BufferedImage import java.util.* import javax.accessibility.AccessibleAction import javax.accessibility.AccessibleContext import javax.accessibility.AccessibleRole import javax.swing.Icon import javax.swing.JComponent import javax.swing.UIManager internal class NavBarItemComponent( cs: CoroutineScope, private val vm: NavBarItemVm, private val panel: NewNavBarPanel, ) : SimpleColoredComponent() { init { isOpaque = false ipad = navBarItemInsets() if (ExperimentalUI.isNewUI()) { iconTextGap = JBUIScale.scale(4) } myBorder = null border = null if (isItemComponentFocusable()) { // Take ownership of Tab/Shift-Tab navigation (to move focus out of nav bar panel), as // navigation between items is handled by the Left/Right cursor keys. This is similar // to the behavior a JRadioButton contained inside a GroupBox. isFocusable = true focusTraversalKeysEnabled = false addKeyListener(NavBarItemComponentTabKeyListener(panel)) if (isFloating) { addFocusListener(NavBarDialogFocusListener(panel)) } } else { isFocusable = false } font = RelativeFont.NORMAL.fromResource("NavBar.fontSizeOffset", 0).derive(font) cs.launch(Dispatchers.EDT, CoroutineStart.UNDISPATCHED) { vm.selected.collect { update() } } addMouseListener(ItemPopupHandler()) addMouseListener(ItemMouseListener()) } private inner class ItemPopupHandler : PopupHandler() { override fun invokePopup(comp: Component?, x: Int, y: Int) { focusItem() vm.select() ActionManager.getInstance() .createActionPopupMenu(ActionPlaces.NAVIGATION_BAR_POPUP, NavBarContextMenuActionGroup()) .also { it.setTargetComponent(panel) } .component .show(panel, [email protected] + x, [email protected] + y) } } private inner class ItemMouseListener : MouseAdapter() { override fun mousePressed(e: MouseEvent) { if (!SystemInfo.isWindows) { click(e) } } override fun mouseReleased(e: MouseEvent) { if (SystemInfo.isWindows) { click(e) } } private fun click(e: MouseEvent) { if (e.isConsumed) { return } if (e.isPopupTrigger) { return } if (e.clickCount == 1) { focusItem() vm.select() vm.showPopup() e.consume() } else if (e.clickCount == 2 && e.button == MouseEvent.BUTTON1) { vm.activate() e.consume() } } override fun mouseEntered(e: MouseEvent) { if (e.isConsumed || !ExperimentalUI.isNewUI()) { return } isHovered = true update() e.consume() } override fun mouseExited(e: MouseEvent) { if (e.isConsumed || !ExperimentalUI.isNewUI()) { return } isHovered = false update() e.consume() } } val text: @Nls String get() = vm.presentation.text private val isFloating: Boolean get() = panel.isFloating private val isSelected: Boolean get() = vm.selected.value private val isFocused: Boolean get() = panel.isItemFocused() private var isHovered: Boolean = false override fun getFont(): Font? = navBarItemFont() override fun setOpaque(isOpaque: Boolean): Unit = super.setOpaque(false) override fun getMinimumSize(): Dimension = preferredSize override fun getPreferredSize(): Dimension { val size = super.getPreferredSize() val offsets = Dimension() JBInsets.addTo(offsets, navBarItemPadding(isFloating)) val newUI = ExperimentalUI.isNewUI() if (newUI) { offsets.width += if (vm.isFirst) 0 else CHEVRON_ICON.iconWidth + Breadcrumbs.CHEVRON_INSET.get() } else { offsets.width += getDecorationOffset() + if (vm.isFirst) getFirstElementLeftOffset() else 0 } return Dimension(size.width + offsets.width, size.height + offsets.height) } fun focusItem() { val focusComponent: JComponent = if (isFocusable) this@NavBarItemComponent else panel IdeFocusManager.getInstance(panel.project).requestFocus(focusComponent, true) } fun update() { clear() val selected = isSelected val focused = isFocused val presentation = vm.presentation val attributes = presentation.textAttributes val fg: Color? = when { !ExperimentalUI.isNewUI() -> navBarItemForeground(selected, focused, vm.isInactive()) ?: attributes.fgColor isHovered -> Breadcrumbs.HOVER_FOREGROUND selected -> if (focused) Breadcrumbs.SELECTION_FOREGROUND else Breadcrumbs.SELECTION_INACTIVE_FOREGROUND else -> if (isFloating) Breadcrumbs.FLOATING_FOREGROUND else Breadcrumbs.FOREGROUND } val bg = navBarItemBackground(selected, focused) val waveColor = if (ExperimentalUI.isNewUI()) null else attributes.waveColor val style = if (ExperimentalUI.isNewUI()) SimpleTextAttributes.STYLE_PLAIN else attributes.style icon = effectiveIcon(presentation) background = bg append(presentation.text, SimpleTextAttributes(bg, fg, waveColor, style)) } private fun effectiveIcon(presentation: NavBarItemPresentation): Icon? { return when { ExperimentalUI.isNewUI() && vm.isModuleContentRoot -> MODULE_ICON Registry.`is`("navBar.show.icons") || vm.isLast || presentation.hasContainingFile -> presentation.icon else -> null } } override fun shouldDrawBackground(): Boolean { return isSelected && isFocused } private val cache: MutableMap<ImageType, ScaleContext.Cache<BufferedImage>> = EnumMap(ImageType::class.java) override fun doPaint(g: Graphics2D) { val paddings = JBInsets.create(navBarItemPadding(isFloating)) val isFirst = vm.isFirst if (ExperimentalUI.isNewUI()) { val rect = Rectangle(size) JBInsets.removeFrom(rect, paddings) var offset = rect.x if (!isFirst) { CHEVRON_ICON.paintIcon(this, g, offset, rect.y + (rect.height - CHEVRON_ICON.iconHeight) / 2) val delta = CHEVRON_ICON.iconWidth + Breadcrumbs.CHEVRON_INSET.get() offset += delta rect.width -= delta } val highlightColor = highlightColor() if (highlightColor != null) { AbstractNavBarUI.paintHighlight(g, Rectangle(offset, rect.y, rect.width, rect.height), highlightColor) } val icon = icon if (icon == null) { offset += ipad.left } else { offset += ipad.left icon.paintIcon(this, g, offset, rect.y + (rect.height - icon.iconHeight) / 2 + if (icon == MODULE_ICON) JBUI.scale(1) else 0) offset += icon.iconWidth offset += iconTextGap } doPaintText(g, offset, false) } else { val toolbarVisible = UISettings.getInstance().showMainToolbar val selected = isSelected && isFocused val nextSelected = vm.isNextSelected() && isFocused val type = ImageType.from(isFloating, toolbarVisible, selected, nextSelected) // see: https://github.com/JetBrains/intellij-community/pull/1111 val imageCache = cache.computeIfAbsent(type) { ScaleContext.Cache { ctx: ScaleContext -> AbstractNavBarUI.drawToBuffer(this, ctx, isFloating, toolbarVisible, selected, nextSelected, vm.isLast) } } val image = imageCache.getOrProvide(ScaleContext.create(g)) ?: return StartupUiUtil.drawImage(g, image, 0, 0, null) val offset = if (isFirst) getFirstElementLeftOffset() else 0 var textOffset = paddings.width() + offset val icon = icon if (icon != null) { val iconOffset = paddings.left + offset icon.paintIcon(this, g, iconOffset, (height - icon.iconHeight) / 2) textOffset += icon.iconWidth } doPaintText(g, textOffset, false) } } private fun highlightColor(): Color? { return when { isHovered -> Breadcrumbs.HOVER_BACKGROUND isSelected -> if (isFocused) Breadcrumbs.SELECTION_BACKGROUND else Breadcrumbs.SELECTION_INACTIVE_BACKGROUND else -> null } } override fun getAccessibleContext(): AccessibleContext { if (accessibleContext == null) { accessibleContext = AccessibleNavBarItem() } return accessibleContext } private inner class AccessibleNavBarItem : AccessibleSimpleColoredComponent(), AccessibleAction { override fun getAccessibleRole(): AccessibleRole = AccessibleRole.PUSH_BUTTON override fun getAccessibleAction(): AccessibleAction = this override fun getAccessibleActionCount(): Int = 1 override fun getAccessibleActionDescription(i: Int): String? { if (i == 0) { return UIManager.getString("AbstractButton.clickText") } return null } override fun doAccessibleAction(i: Int): Boolean { if (i == 0) { vm.select() return true } return false } } companion object { private val CHEVRON_ICON = AllIcons.General.ChevronRight private val MODULE_ICON = IconManager.getInstance().getIcon("expui/nodes/module8x8.svg", AllIcons::class.java) internal fun isItemComponentFocusable(): Boolean = ScreenReader.isActive() } }
apache-2.0
01b7b7ff8418f9875c6f67c0d68ba9bc
32.003067
133
0.696161
4.41848
false
false
false
false
GunoH/intellij-community
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/AttachedEntityListImpl.kt
2
8853
package com.intellij.workspaceModel.storage.entities.test.api import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.EntityLink import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.UsedClassesCollector import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.impl.extractOneToManyParent import com.intellij.workspaceModel.storage.impl.updateOneToManyParentOfChild import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Child @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class AttachedEntityListImpl(val dataSource: AttachedEntityListData) : AttachedEntityList, WorkspaceEntityBase() { companion object { internal val REF_CONNECTION_ID: ConnectionId = ConnectionId.create(MainEntityList::class.java, AttachedEntityList::class.java, ConnectionId.ConnectionType.ONE_TO_MANY, true) val connections = listOf<ConnectionId>( REF_CONNECTION_ID, ) } override val ref: MainEntityList? get() = snapshot.extractOneToManyParent(REF_CONNECTION_ID, this) override val data: String get() = dataSource.data override val entitySource: EntitySource get() = dataSource.entitySource override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(result: AttachedEntityListData?) : ModifiableWorkspaceEntityBase<AttachedEntityList, AttachedEntityListData>( result), AttachedEntityList.Builder { constructor() : this(AttachedEntityListData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity AttachedEntityList is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // After adding entity data to the builder, we need to unbind it and move the control over entity data to builder // Builder may switch to snapshot at any moment and lock entity data to modification this.currentEntityData = null // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isEntitySourceInitialized()) { error("Field WorkspaceEntity#entitySource should be initialized") } if (!getEntityData().isDataInitialized()) { error("Field AttachedEntityList#data should be initialized") } } override fun connectionIdList(): List<ConnectionId> { return connections } // Relabeling code, move information from dataSource to this builder override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) { dataSource as AttachedEntityList if (this.entitySource != dataSource.entitySource) this.entitySource = dataSource.entitySource if (this.data != dataSource.data) this.data = dataSource.data if (parents != null) { val refNew = parents.filterIsInstance<MainEntityList?>().singleOrNull() if ((refNew == null && this.ref != null) || (refNew != null && this.ref == null) || (refNew != null && this.ref != null && (this.ref as WorkspaceEntityBase).id != (refNew as WorkspaceEntityBase).id)) { this.ref = refNew } } } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData(true).entitySource = value changedProperty.add("entitySource") } override var ref: MainEntityList? get() { val _diff = diff return if (_diff != null) { _diff.extractOneToManyParent(REF_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, REF_CONNECTION_ID)] as? MainEntityList } else { this.entityLinks[EntityLink(false, REF_CONNECTION_ID)] as? MainEntityList } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*, *> && value.diff == null) { // Setting backref of the list if (value is ModifiableWorkspaceEntityBase<*, *>) { val data = (value.entityLinks[EntityLink(true, REF_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this value.entityLinks[EntityLink(true, REF_CONNECTION_ID)] = data } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(value) } if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*, *> || value.diff != null)) { _diff.updateOneToManyParentOfChild(REF_CONNECTION_ID, this, value) } else { // Setting backref of the list if (value is ModifiableWorkspaceEntityBase<*, *>) { val data = (value.entityLinks[EntityLink(true, REF_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this value.entityLinks[EntityLink(true, REF_CONNECTION_ID)] = data } // else you're attaching a new entity to an existing entity that is not modifiable this.entityLinks[EntityLink(false, REF_CONNECTION_ID)] = value } changedProperty.add("ref") } override var data: String get() = getEntityData().data set(value) { checkModificationAllowed() getEntityData(true).data = value changedProperty.add("data") } override fun getEntityClass(): Class<AttachedEntityList> = AttachedEntityList::class.java } } class AttachedEntityListData : WorkspaceEntityData<AttachedEntityList>() { lateinit var data: String fun isDataInitialized(): Boolean = ::data.isInitialized override fun wrapAsModifiable(diff: MutableEntityStorage): WorkspaceEntity.Builder<AttachedEntityList> { val modifiable = AttachedEntityListImpl.Builder(null) modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() return modifiable } override fun createEntity(snapshot: EntityStorage): AttachedEntityList { return getCached(snapshot) { val entity = AttachedEntityListImpl(this) entity.snapshot = snapshot entity.id = createEntityId() entity } } override fun getEntityInterface(): Class<out WorkspaceEntity> { return AttachedEntityList::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity { return AttachedEntityList(data, entitySource) { this.ref = parents.filterIsInstance<MainEntityList>().singleOrNull() } } override fun getRequiredParents(): List<Class<out WorkspaceEntity>> { val res = mutableListOf<Class<out WorkspaceEntity>>() return res } override fun equals(other: Any?): Boolean { if (other == null) return false if (this.javaClass != other.javaClass) return false other as AttachedEntityListData if (this.entitySource != other.entitySource) return false if (this.data != other.data) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this.javaClass != other.javaClass) return false other as AttachedEntityListData if (this.data != other.data) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + data.hashCode() return result } override fun hashCodeIgnoringEntitySource(): Int { var result = javaClass.hashCode() result = 31 * result + data.hashCode() return result } override fun collectClassUsagesData(collector: UsedClassesCollector) { collector.sameForAllEntities = true } }
apache-2.0
d17e2c0ca93805ee8a87ea8d8d7c91d3
35.432099
209
0.699311
5.171145
false
false
false
false
kivensolo/UiUsingListView
library/hlscache/src/main/java/com/kingz/mobile/libhlscache/bean/MasterInfo.kt
1
1273
package com.kingz.mobile.libhlscache.bean import com.iheartradio.m3u8.data.PlaylistData import com.kingz.mobile.libhlscache.utils.Tools import java.util.* /** * 多路流顶层信息 */ data class MasterInfo(val id: String, private val url: String, val config: CacheVideoConfig) { private val subInfos: MutableList<SubInfo> = ArrayList() /** * 当前正在播放/缓存的流index */ var curPlayIndex = 0 /** * 当前播放的SubInfo */ val curPlaySubInfo: SubInfo get() = subInfos[curPlayIndex] fun addSubInfos(playlists: List<PlaylistData>) { for (data in playlists) { addSubInfo(data.uri, data.streamInfo.bandwidth) } } private fun addSubInfo(url: String, bandWidth: Int) { val subInfo = SubInfo() subInfo.rawUrl = url subInfo.bandWidth = bandWidth subInfo.id = "${id}_____${bandWidth}" subInfos.add(subInfo) } fun getSubInfos(): List<SubInfo> { return subInfos } inner class SubInfo { var bandWidth = 0 var id: String? = null var rawUrl: String? = null val absoluteUrl: String get() = Tools.getAbsoluteUrl(url, rawUrl) } }
gpl-2.0
4a4617671bd674891f9dccff4e8d4d19
22.207547
60
0.598047
3.625369
false
false
false
false
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveMethod/MoveKotlinMethodProcessor.kt
2
18643
// 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.refactoring.move.moveMethod import com.intellij.ide.util.EditorHelper import com.intellij.java.JavaBundle import com.intellij.openapi.util.Ref import com.intellij.psi.JavaPsiFacade import com.intellij.psi.PsiElement import com.intellij.psi.PsiMethodCallExpression import com.intellij.psi.PsiReferenceExpression import com.intellij.psi.search.searches.ReferencesSearch import com.intellij.refactoring.BaseRefactoringProcessor import com.intellij.refactoring.move.MoveMultipleElementsViewDescriptor import com.intellij.refactoring.util.MoveRenameUsageInfo import com.intellij.usageView.UsageInfo import com.intellij.usageView.UsageViewDescriptor import com.intellij.util.IncorrectOperationException import com.intellij.util.containers.MultiMap import org.jetbrains.kotlin.config.LanguageVersionSettings import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.* import org.jetbrains.kotlin.idea.core.setVisibility import org.jetbrains.kotlin.idea.refactoring.move.* import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.KotlinMoveTargetForExistingElement import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.MoveConflictChecker import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.Mover import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.idea.resolve.languageVersionSettings import org.jetbrains.kotlin.idea.search.projectScope import org.jetbrains.kotlin.idea.util.getFactoryForImplicitReceiverWithSubtypeOf import org.jetbrains.kotlin.idea.util.getResolutionScope import org.jetbrains.kotlin.js.resolve.diagnostics.findPsi import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.tail import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.descriptorUtil.isAncestorOf import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitReceiver import org.jetbrains.kotlin.resolve.scopes.utils.getImplicitReceiversHierarchy import org.jetbrains.kotlin.util.capitalizeDecapitalize.capitalizeAsciiOnly import org.jetbrains.kotlin.util.containingNonLocalDeclaration class MoveKotlinMethodProcessor( private val method: KtNamedFunction, private val targetVariable: KtNamedDeclaration, private val oldClassParameterNames: Map<KtClass, String>, private val openInEditor: Boolean = false ) : BaseRefactoringProcessor(method.project) { private val targetClassOrObject: KtClassOrObject = if (targetVariable is KtObjectDeclaration) targetVariable else (targetVariable.resolveToDescriptorIfAny() as? CallableDescriptor)?.returnType?.constructor?.declarationDescriptor?.findPsi() as KtClass private val factory = KtPsiFactory(myProject) private val conflicts = MultiMap<PsiElement, String>() override fun createUsageViewDescriptor(usages: Array<out UsageInfo>): UsageViewDescriptor { return MoveMultipleElementsViewDescriptor( arrayOf(method), (targetClassOrObject.fqName ?: JavaBundle.message("default.package.presentable.name")).toString() ) } override fun preprocessUsages(refUsages: Ref<Array<UsageInfo>>): Boolean { return showConflicts(conflicts, refUsages.get()) } override fun findUsages(): Array<UsageInfo> { val changeInfo = ContainerChangeInfo( ContainerInfo.Class(method.containingClassOrObject!!.fqName!!), ContainerInfo.Class(targetClassOrObject.fqName!!) ) val conflictChecker = MoveConflictChecker(myProject, listOf(method), KotlinMoveTargetForExistingElement(targetClassOrObject), method) val searchScope = myProject.projectScope() val internalUsages = mutableSetOf<UsageInfo>() val methodCallUsages = mutableSetOf<UsageInfo>() methodCallUsages += ReferencesSearch.search(method, searchScope).mapNotNull { ref -> createMoveUsageInfoIfPossible(ref, method, addImportToOriginalFile = true, isInternal = method.isAncestor(ref.element)) } if (targetVariableIsMethodParameter()) { internalUsages += ReferencesSearch.search(targetVariable, searchScope).mapNotNull { ref -> createMoveUsageInfoIfPossible(ref, targetVariable, addImportToOriginalFile = false, isInternal = true) } } internalUsages += method.getInternalReferencesToUpdateOnPackageNameChange(changeInfo) traverseOuterInstanceReferences(method) { internalUsages += it } conflictChecker.checkAllConflicts( methodCallUsages.filter { it is KotlinMoveUsage && !it.isInternal }.toMutableSet(), internalUsages, conflicts ) if (oldClassParameterNames.size > 1) { for (usage in methodCallUsages.filter { it.element is KtNameReferenceExpression || it.element is PsiReferenceExpression }) { conflicts.putValue(usage.element, KotlinBundle.message("text.references.to.outer.classes.have.to.be.added.manually")) } } return (internalUsages + methodCallUsages).toTypedArray() } override fun performRefactoring(usages: Array<out UsageInfo>) { val usagesToProcess = mutableListOf<UsageInfo>() fun changeMethodSignature() { if (targetVariableIsMethodParameter()) { val parameterIndex = method.valueParameters.indexOf(targetVariable as KtParameter) method.valueParameterList?.removeParameter(parameterIndex) } for ((ktClass, parameterName) in oldClassParameterNames) { method.valueParameterList?.addParameterBefore( factory.createParameter("$parameterName: ${ktClass.nameAsSafeName.identifier}"), method.valueParameters.firstOrNull() ) } } fun KtNameReferenceExpression.getImplicitReceiver(): KtExpression? { val scope = getResolutionScope(this.analyze()) ?: return null val descriptor = this.resolveToCall()?.resultingDescriptor ?: return null val receiverDescriptor = descriptor.extensionReceiverParameter ?: descriptor.dispatchReceiverParameter ?: return null val expressionFactory = scope.getFactoryForImplicitReceiverWithSubtypeOf(receiverDescriptor.type) ?: return null val receiverText = if (expressionFactory.isImmediate) "this" else expressionFactory.expressionText return factory.createExpression(receiverText) } fun escalateTargetVariableVisibilityIfNeeded(where: DeclarationDescriptor?, languageVersionSettings: LanguageVersionSettings) { if (where == null || targetVariableIsMethodParameter()) return val targetDescriptor = targetVariable.resolveToDescriptorIfAny() as? DeclarationDescriptorWithVisibility ?: return if (!DescriptorVisibilityUtils.isVisibleIgnoringReceiver(targetDescriptor, where, languageVersionSettings) && method.manager.isInProject(targetVariable)) { targetVariable.setVisibility(KtTokens.PUBLIC_KEYWORD) } } fun correctMethodCall(expression: PsiElement) { when (expression) { is KtNameReferenceExpression -> { val callExpression = expression.parent as? KtCallExpression ?: return escalateTargetVariableVisibilityIfNeeded( callExpression.containingNonLocalDeclaration()?.resolveToDescriptorIfAny(), callExpression.getResolutionFacade().languageVersionSettings ) val oldReceiver = callExpression.getQualifiedExpressionForSelector()?.receiverExpression ?: expression.getImplicitReceiver() ?: return val newReceiver = if (targetVariable is KtObjectDeclaration) { factory.createExpression(targetVariable.nameAsSafeName.identifier) } else if (targetVariableIsMethodParameter()) { val parameterIndex = method.valueParameters.indexOf(targetVariable as KtParameter) if (parameterIndex in callExpression.valueArguments.indices) { val argumentExpression = callExpression.valueArguments[parameterIndex].getArgumentExpression() ?: return callExpression.valueArgumentList?.removeArgument(parameterIndex) argumentExpression } else targetVariable.defaultValue } else { factory.createExpression("${oldReceiver.text}.${targetVariable.nameAsSafeName.identifier}") } ?: return if (method.containingClassOrObject in oldClassParameterNames) { callExpression.valueArgumentList?.addArgumentBefore( factory.createArgument(oldReceiver), callExpression.valueArguments.firstOrNull() ) } val resultingExpression = callExpression.getQualifiedExpressionForSelectorOrThis() .replace(factory.createExpressionByPattern("$0.$1", newReceiver.text, callExpression)) if (targetVariable is KtObjectDeclaration) { val ref = (resultingExpression as? KtQualifiedExpression)?.receiverExpression?.mainReference ?: return createMoveUsageInfoIfPossible( ref, targetClassOrObject, addImportToOriginalFile = true, isInternal = targetClassOrObject.isAncestor(ref.element) )?.let { usagesToProcess += it } } } is PsiReferenceExpression -> { val callExpression = expression.parent as? PsiMethodCallExpression ?: return val oldReceiver = callExpression.methodExpression.qualifierExpression ?: return val newReceiver = if (targetVariable is KtObjectDeclaration) { // todo: fix usage of target object (import might be needed) val targetObjectName = targetVariable.fqName?.tail(targetVariable.containingKtFile.packageFqName)?.toString() ?: targetVariable.nameAsSafeName.identifier JavaPsiFacade.getElementFactory(myProject).createExpressionFromText("$targetObjectName.INSTANCE", null) } else if (targetVariableIsMethodParameter()) { val parameterIndex = method.valueParameters.indexOf(targetVariable as KtParameter) val arguments = callExpression.argumentList.expressions if (parameterIndex in arguments.indices) { val argumentExpression = arguments[parameterIndex].copy() ?: return arguments[parameterIndex].delete() argumentExpression } else return } else { val getterName = "get${targetVariable.nameAsSafeName.identifier.capitalizeAsciiOnly()}" JavaPsiFacade.getElementFactory(myProject).createExpressionFromText("${oldReceiver.text}.$getterName()", null) } if (method.containingClassOrObject in oldClassParameterNames) { callExpression.argumentList.addBefore(oldReceiver, callExpression.argumentList.expressions.firstOrNull()) } oldReceiver.replace(newReceiver) } } } fun replaceReferenceToTargetWithThis(element: KtExpression) { val scope = element.getResolutionScope(element.analyze()) ?: return val receivers = scope.getImplicitReceiversHierarchy() val receiverText = if (receivers.isEmpty() || receivers[0].containingDeclaration == method.containingClassOrObject?.resolveToDescriptorIfAny()) "this" else "this@${targetClassOrObject.nameAsSafeName.identifier}" element.replace(factory.createExpression(receiverText)) } val (methodCallUsages, internalUsages) = usages.partition { it is MoveRenameUsageInfo && it.referencedElement == method } val newInternalUsages = mutableListOf<UsageInfo>() val oldInternalUsages = mutableListOf<UsageInfo>() try { for (usage in methodCallUsages) { usage.element?.let { element -> correctMethodCall(element) } } for (usage in internalUsages) { val element = usage.element ?: continue if (usage is MoveRenameUsageInfo) { if (usage.referencedElement == targetVariable && element is KtNameReferenceExpression) { replaceReferenceToTargetWithThis(element) } else { oldInternalUsages += usage } } if (usage is SourceInstanceReferenceUsageInfo) { if (usage.member == targetVariable && element is KtNameReferenceExpression) { replaceReferenceToTargetWithThis( (element as? KtThisExpression)?.getQualifiedExpressionForReceiver() ?: element ) } else { val receiverText = oldClassParameterNames[usage.sourceOrOuter] ?: continue when (element) { is KtThisExpression -> element.replace(factory.createExpression(receiverText)) is KtNameReferenceExpression -> { val elementToReplace = (element.parent as? KtCallExpression) ?: element elementToReplace.replace(factory.createExpressionByPattern("$0.$1", receiverText, elementToReplace)) } } } } } changeMethodSignature() markInternalUsages(oldInternalUsages) val movedMethod = Mover.Default(method, targetClassOrObject) val oldToNewMethodMap = mapOf<PsiElement, PsiElement>(method to movedMethod) newInternalUsages += restoreInternalUsages(movedMethod, oldToNewMethodMap) usagesToProcess += newInternalUsages postProcessMoveUsages(usagesToProcess, oldToNewMethodMap) if (openInEditor) EditorHelper.openInEditor(movedMethod) } catch (e: IncorrectOperationException) { } finally { cleanUpInternalUsages(oldInternalUsages + newInternalUsages) } } private fun targetVariableIsMethodParameter(): Boolean = targetVariable is KtParameter && !targetVariable.hasValOrVar() override fun getCommandName(): String = KotlinBundle.message("title.move.method") } internal fun getThisClassesToMembers(method: KtNamedFunction) = traverseOuterInstanceReferences(method) internal fun KtNamedDeclaration.type() = (resolveToDescriptorIfAny() as? CallableDescriptor)?.returnType internal fun KtClass.defaultType() = resolveToDescriptorIfAny()?.defaultType private fun traverseOuterInstanceReferences( method: KtNamedFunction, body: (SourceInstanceReferenceUsageInfo) -> Unit = {} ): Map<KtClass, MutableSet<KtNamedDeclaration>> { val context = method.analyzeWithContent() val containingClassOrObject = method.containingClassOrObject ?: return emptyMap() val descriptor = containingClassOrObject.unsafeResolveToDescriptor() fun getClassOrObjectAndMemberReferencedBy(reference: KtExpression): Pair<DeclarationDescriptor?, CallableDescriptor?> { var classOrObjectDescriptor: DeclarationDescriptor? = null var memberDescriptor: CallableDescriptor? = null if (reference is KtThisExpression) { classOrObjectDescriptor = context[BindingContext.REFERENCE_TARGET, reference.instanceReference] if (classOrObjectDescriptor?.isAncestorOf(descriptor, false) == true) { memberDescriptor = reference.getQualifiedExpressionForReceiver()?.selectorExpression?.getResolvedCall(context)?.resultingDescriptor } } if (reference is KtNameReferenceExpression) { val dispatchReceiver = reference.getResolvedCall(context)?.dispatchReceiver as? ImplicitReceiver classOrObjectDescriptor = dispatchReceiver?.declarationDescriptor if (classOrObjectDescriptor?.isAncestorOf(descriptor, false) == true) { memberDescriptor = reference.getResolvedCall(context)?.resultingDescriptor } } return classOrObjectDescriptor to memberDescriptor } val thisClassesToMembers = mutableMapOf<KtClass, MutableSet<KtNamedDeclaration>>() method.bodyExpression?.forEachDescendantOfType<KtExpression> { reference -> val (classOrObjectDescriptor, memberDescriptor) = getClassOrObjectAndMemberReferencedBy(reference) (classOrObjectDescriptor?.findPsi() as? KtClassOrObject)?.let { resolvedClassOrObject -> val resolvedMember = memberDescriptor?.findPsi() as? KtNamedDeclaration if (resolvedClassOrObject is KtClass) { if (resolvedClassOrObject in thisClassesToMembers) thisClassesToMembers[resolvedClassOrObject]?.add( resolvedMember ?: resolvedClassOrObject ) else thisClassesToMembers[resolvedClassOrObject] = mutableSetOf(resolvedMember ?: resolvedClassOrObject) } body(SourceInstanceReferenceUsageInfo(reference, resolvedClassOrObject, resolvedMember)) } } return thisClassesToMembers } internal class SourceInstanceReferenceUsageInfo( reference: KtExpression, val sourceOrOuter: KtClassOrObject, val member: KtNamedDeclaration? ) : UsageInfo(reference)
apache-2.0
8597322c7b36c21f43f388530dcc2320
53.511696
167
0.675481
6.279219
false
false
false
false
jwren/intellij-community
plugins/kotlin/core/src/org/jetbrains/kotlin/idea/core/script/ucache/ScriptSdksBuilder.kt
2
4811
// 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.core.script.ucache import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.JavaSdkType import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.roots.ModuleRootManager import com.intellij.openapi.roots.OrderRootType import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import org.jetbrains.kotlin.idea.caches.project.getAllProjectSdks import org.jetbrains.kotlin.idea.core.script.configuration.utils.ScriptClassRootsStorage import org.jetbrains.kotlin.idea.core.script.scriptingWarnLog import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.idea.util.getProjectJdkTableSafe import java.nio.file.Path class ScriptSdksBuilder( val project: Project, private val sdks: MutableMap<SdkId, Sdk?> = mutableMapOf(), private val remove: Sdk? = null ) { private val defaultSdk by lazy { getScriptDefaultSdk() } fun build(): ScriptSdks { val nonIndexedClassRoots = mutableSetOf<VirtualFile>() val nonIndexedSourceRoots = mutableSetOf<VirtualFile>() val nonIndexedSdks = sdks.values.filterNotNullTo(mutableSetOf()) runReadAction { for (module in ModuleManager.getInstance(project).modules.filter { !it.isDisposed }) { ProgressManager.checkCanceled() if (nonIndexedSdks.isEmpty()) break nonIndexedSdks.remove(ModuleRootManager.getInstance(module).sdk) } nonIndexedSdks.forEach { nonIndexedClassRoots.addAll(it.rootProvider.getFiles(OrderRootType.CLASSES)) nonIndexedSourceRoots.addAll(it.rootProvider.getFiles(OrderRootType.SOURCES)) } } return ScriptSdks(sdks, nonIndexedClassRoots, nonIndexedSourceRoots) } @Deprecated("Don't use, used only from DefaultScriptingSupport for saving to storage") fun addAll(other: ScriptSdksBuilder) { sdks.putAll(other.sdks) } fun addAll(other: ScriptSdks) { sdks.putAll(other.sdks) } // add sdk by home path with checking for removed sdk fun addSdk(sdkId: SdkId): Sdk? { val canonicalPath = sdkId.homeDirectory ?: return addDefaultSdk() return addSdk(Path.of(canonicalPath)) } fun addSdk(javaHome: Path?): Sdk? { if (javaHome == null) return addDefaultSdk() return sdks.getOrPut(SdkId(javaHome)) { getScriptSdkByJavaHome(javaHome) ?: defaultSdk } } private fun getScriptSdkByJavaHome(javaHome: Path): Sdk? { // workaround for mismatched gradle wrapper and plugin version val javaHomeVF = try { VfsUtil.findFile(javaHome, true) } catch (e: Throwable) { null } ?: return null return getProjectJdkTableSafe().allJdks.find { it.homeDirectory == javaHomeVF } ?.takeIf { it.canBeUsedForScript() } } fun addDefaultSdk(): Sdk? = sdks.getOrPut(SdkId.default) { defaultSdk } fun addSdkByName(sdkName: String) { val sdk = getProjectJdkTableSafe().allJdks .find { it.name == sdkName } ?.takeIf { it.canBeUsedForScript() } ?: defaultSdk ?: return val homePath = sdk.homePath ?: return sdks[SdkId(homePath)] = sdk } private fun getScriptDefaultSdk(): Sdk? { val projectSdk = ProjectRootManager.getInstance(project).projectSdk?.takeIf { it.canBeUsedForScript() } if (projectSdk != null) return projectSdk val anyJavaSdk = getAllProjectSdks().find { it.canBeUsedForScript() } if (anyJavaSdk != null) { return anyJavaSdk } scriptingWarnLog( "Default Script SDK is null: " + "projectSdk = ${ProjectRootManager.getInstance(project).projectSdk}, " + "all sdks = ${getAllProjectSdks().joinToString("\n")}" ) return null } private fun Sdk.canBeUsedForScript() = this != remove && sdkType is JavaSdkType fun toStorage(storage: ScriptClassRootsStorage) { storage.sdks = sdks.values.mapNotNullTo(mutableSetOf()) { it?.name } storage.defaultSdkUsed = sdks.containsKey(SdkId.default) } fun fromStorage(storage: ScriptClassRootsStorage) { storage.sdks.forEach { addSdkByName(it) } if (storage.defaultSdkUsed) { addDefaultSdk() } } }
apache-2.0
fed3a32dee5eef0ef78c6ca704b9ea92
35.725191
158
0.675743
4.753953
false
false
false
false
GunoH/intellij-community
java/java-impl/src/com/intellij/codeInsight/hints/JavaHintUtils.kt
8
14076
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInsight.hints import com.intellij.codeInsight.completion.CompletionMemory import com.intellij.codeInsight.completion.JavaMethodCallElement import com.intellij.openapi.util.registry.Registry import com.intellij.psi.* import com.intellij.psi.impl.source.resolve.graphInference.PsiPolyExpressionUtil import com.intellij.psi.impl.source.tree.java.PsiEmptyExpressionImpl import com.intellij.psi.impl.source.tree.java.PsiMethodCallExpressionImpl import com.intellij.psi.impl.source.tree.java.PsiNewExpressionImpl import com.intellij.psi.util.TypeConversionUtil import com.intellij.util.IncorrectOperationException import com.siyeh.ig.callMatcher.CallMatcher import java.util.* internal object JavaInlayHintsProvider { fun hints(callExpression: PsiCall): Set<InlayInfo> { if (JavaMethodCallElement.isCompletionMode(callExpression)) { val argumentList = callExpression.argumentList ?: return emptySet() val text = argumentList.text if (text == null || !text.startsWith('(') || !text.endsWith(')')) return emptySet() val method = CompletionMemory.getChosenMethod(callExpression) ?: return emptySet() val params = method.parameterList.parameters val arguments = argumentList.expressions val limit = JavaMethodCallElement.getCompletionHintsLimit() val trailingOffset = argumentList.textRange.endOffset - 1 val infos = ArrayList<InlayInfo>() var lastIndex = 0 (if (arguments.isEmpty()) listOf(trailingOffset) else arguments.map { inlayOffset(it) }).forEachIndexed { i, offset -> if (i < params.size) { params[i].name.let { infos.add(InlayInfo(it, offset, false, params.size == 1, false)) } lastIndex = i } } if (Registry.`is`("editor.completion.hints.virtual.comma")) { for (i in lastIndex + 1 until minOf(params.size, limit)) { params[i].name.let { infos.add(createHintWithComma(it, trailingOffset)) } lastIndex = i } } if (method.isVarArgs && (arguments.isEmpty() && params.size == 2 || arguments.isNotEmpty() && arguments.size == params.size - 1)) { params[params.size - 1].name.let { infos.add(createHintWithComma(it, trailingOffset)) } } else if (Registry.`is`("editor.completion.hints.virtual.comma") && lastIndex < (params.size - 1) || limit == 1 && arguments.isEmpty() && params.size > 1 || limit <= arguments.size && arguments.size < params.size) { infos.add(InlayInfo("...more", trailingOffset, false, false, true)) } return infos.toSet() } if (!isParameterHintsEnabledForLanguage(callExpression.language)) return emptySet() val resolveResult = callExpression.resolveMethodGenerics() val hints = methodHints(callExpression, resolveResult) if (hints.isNotEmpty()) return hints return when (callExpression) { is PsiMethodCallExpressionImpl -> mergedHints(callExpression, callExpression.methodExpression.multiResolve(false)) is PsiNewExpressionImpl -> mergedHints(callExpression, callExpression.constructorFakeReference.multiResolve(false)) else -> emptySet() } } private fun createHintWithComma(parameterName: String, offset: Int): InlayInfo { return InlayInfo(",$parameterName", offset, false, false, true, HintWidthAdjustment(", ", parameterName, 1)) } private fun mergedHints(callExpression: PsiCallExpression, results: Array<out ResolveResult>): Set<InlayInfo> { val resultSet = results .filter { it.element != null } .map { methodHints(callExpression, it) } if (resultSet.isEmpty()) return emptySet() if (resultSet.size == 1) { return resultSet.first() } val chosenMethod: PsiMethod? = CompletionMemory.getChosenMethod(callExpression) if (chosenMethod != null) { val callInfo = callInfo(callExpression, chosenMethod) return hintSet(callInfo, PsiSubstitutor.EMPTY) } //we can show hints for same named parameters of overloaded methods, even if you don't know exact method return resultSet.reduce { left, right -> left.intersect(right) } .map { InlayInfo(it.text, it.offset, isShowOnlyIfExistedBefore = true) } .toSet() } private fun methodHints(callExpression: PsiCall, resolveResult: ResolveResult): Set<InlayInfo> { val element = resolveResult.element val substitutor = (resolveResult as? JavaResolveResult)?.substitutor ?: PsiSubstitutor.EMPTY if (element is PsiMethod && isMethodToShow(element)) { val info = callInfo(callExpression, element) if (isCallInfoToShow(info)) { return hintSet(info, substitutor) } } return emptySet() } private fun isCallInfoToShow(info: CallInfo): Boolean { val hintsProvider = JavaInlayParameterHintsProvider.getInstance() if (!hintsProvider.ignoreOneCharOneDigitHints.get() && info.allParamsSequential()) { return false } return true } private fun String.decomposeOrderedParams(): Pair<String, Int>? { val firstDigit = indexOfFirst { it.isDigit() } if (firstDigit < 0) return null val prefix = substring(0, firstDigit) try { val number = substring(firstDigit, length).toInt() return prefix to number } catch (e: NumberFormatException) { return null } } private fun CallInfo.allParamsSequential(): Boolean { val paramNames = regularArgs.mapNotNull { it.parameter.name.decomposeOrderedParams() } if (paramNames.size > 1 && paramNames.size == regularArgs.size) { val prefixes = paramNames.map { it.first } if (prefixes.toSet().size != 1) return false val numbers = paramNames.map { it.second } val first = numbers.first() if (first == 0 || first == 1) { return numbers.areSequential() } } return false } private fun hintSet(info: CallInfo, substitutor: PsiSubstitutor): Set<InlayInfo> { val resultSet = mutableSetOf<InlayInfo>() val varargInlay = info.varargsInlay(substitutor) if (varargInlay != null) { resultSet.add(varargInlay) } if (isShowForParamsWithSameType()) { resultSet.addAll(info.sameTypeInlays()) } resultSet.addAll(info.unclearInlays(substitutor)) return resultSet } private fun isShowForParamsWithSameType() = JavaInlayParameterHintsProvider.getInstance().showForParamsWithSameType.get() private fun isMethodToShow(method: PsiMethod): Boolean { val params = method.parameterList.parameters if (params.isEmpty()) return false if (params.size == 1) { val hintsProvider = JavaInlayParameterHintsProvider.getInstance() if (!hintsProvider.showIfMethodNameContainsParameterName.get() && isParamNameContainedInMethodName(params[0], method)) { return false } } return true } private fun isParamNameContainedInMethodName(parameter: PsiParameter, method: PsiMethod): Boolean { val parameterName = parameter.name if (parameterName.length > 1) { return method.name.contains(parameterName, ignoreCase = true) } return false } private fun callInfo(callExpression: PsiCall, method: PsiMethod): CallInfo { val params = method.parameterList.parameters val hasVarArg = params.lastOrNull()?.isVarArgs ?: false val regularParamsCount = if (hasVarArg) params.size - 1 else params.size val arguments = callExpression.argumentList?.expressions ?: emptyArray() val regularArgInfos = params .take(regularParamsCount) .zip(arguments) .map { CallArgumentInfo(it.first, it.second) } val varargParam = if (hasVarArg) params.last() else null val varargExpressions = arguments.drop(regularParamsCount) return CallInfo(regularArgInfos, varargParam, varargExpressions) } } private fun List<Int>.areSequential(): Boolean { if (isEmpty()) throw IncorrectOperationException("List is empty") val ordered = (first() until first() + size).toList() if (ordered.size == size) { return zip(ordered).all { it.first == it.second } } return false } private fun inlayInfo(info: CallArgumentInfo, showOnlyIfExistedBefore: Boolean = false): InlayInfo { return inlayInfo(info.argument, info.parameter, showOnlyIfExistedBefore) } private fun inlayInfo(callArgument: PsiExpression, methodParam: PsiParameter, showOnlyIfExistedBefore: Boolean = false): InlayInfo { val paramName = methodParam.name val paramToShow = (if (methodParam.type is PsiEllipsisType) "..." else "") + paramName val offset = inlayOffset(callArgument) return InlayInfo(paramToShow, offset, showOnlyIfExistedBefore) } fun inlayOffset(callArgument: PsiExpression): Int = inlayOffset(callArgument, false) fun inlayOffset(callArgument: PsiExpression, atEnd: Boolean): Int { if (callArgument.textRange.isEmpty) { val next = callArgument.nextSibling as? PsiWhiteSpace if (next != null) return next.textRange.endOffset } return if (atEnd) callArgument.textRange.endOffset else callArgument.textRange.startOffset } private val OPTIONAL_EMPTY: CallMatcher = CallMatcher.staticCall(CommonClassNames.JAVA_UTIL_OPTIONAL, "empty") .parameterCount(0) private fun shouldShowHintsForExpression(callArgument: PsiElement): Boolean { if (JavaInlayParameterHintsProvider.getInstance().isShowHintWhenExpressionTypeIsClear.get()) return true return when (callArgument) { is PsiLiteralExpression -> true is PsiThisExpression -> true is PsiBinaryExpression -> true is PsiPolyadicExpression -> true is PsiPrefixExpression -> { val tokenType = callArgument.operationTokenType val isLiteral = callArgument.operand is PsiLiteralExpression isLiteral && (JavaTokenType.MINUS == tokenType || JavaTokenType.PLUS == tokenType) } is PsiMethodCallExpression -> OPTIONAL_EMPTY.matches(callArgument) else -> false } } private const val MIN_REASONABLE_PARAM_NAME_SIZE = 3 private class CallInfo(val regularArgs: List<CallArgumentInfo>, val varArg: PsiParameter?, val varArgExpressions: List<PsiExpression>) { fun unclearInlays(substitutor: PsiSubstitutor): List<InlayInfo> { val inlays = mutableListOf<InlayInfo>() for (callInfo in regularArgs) { val inlay = when { shouldHideArgument(callInfo) -> null shouldShowHintsForExpression(callInfo.argument) -> inlayInfo(callInfo) !callInfo.isAssignable(substitutor) -> inlayInfo(callInfo, showOnlyIfExistedBefore = true) else -> null } inlay?.let { inlays.add(inlay) } } return inlays } fun sameTypeInlays(): List<InlayInfo> { val all = regularArgs.map { it.parameter.typeText() } val duplicated = all.toMutableList() all.distinct().forEach { duplicated.remove(it) } return regularArgs .filterNot { shouldHideArgument(it) } .filter { duplicated.contains(it.parameter.typeText()) && it.argument.text != it.parameter.name } .map { inlayInfo(it) } } private fun shouldHideArgument(callInfo: CallArgumentInfo) = isErroneousArg(callInfo) || isArgWithComment(callInfo) || argIfNamedHasSameNameAsParameter(callInfo) private fun isErroneousArg(arg : CallArgumentInfo): Boolean { return arg.argument is PsiEmptyExpressionImpl || arg.argument.prevSibling is PsiEmptyExpressionImpl } private fun isArgWithComment(arg : CallArgumentInfo): Boolean { return hasComment(arg.argument, PsiElement::getNextSibling) || hasComment(arg.argument, PsiElement::getPrevSibling) } private fun argIfNamedHasSameNameAsParameter(arg : CallArgumentInfo): Boolean { val argName = when (val argExpr = arg.argument) { is PsiReferenceExpression -> argExpr.referenceName is PsiMethodCallExpression -> argExpr.methodExpression.referenceName else -> null }?.lowercase(Locale.getDefault()) ?: return false val paramName = arg.parameter.name.lowercase(Locale.getDefault()) if (paramName.length < MIN_REASONABLE_PARAM_NAME_SIZE || argName.length < MIN_REASONABLE_PARAM_NAME_SIZE) { return false } return argName.contains(paramName) || paramName.contains(argName) } private fun hasComment(e: PsiElement, next: (PsiElement) -> PsiElement?) : Boolean { var current = next(e) while (current != null) { if (current is PsiComment) { return true } if (current !is PsiWhiteSpace) { break } current = next(current) } return false } fun varargsInlay(substitutor: PsiSubstitutor): InlayInfo? { if (varArg == null) return null var hasNonassignable = false for (expr in varArgExpressions) { if (shouldShowHintsForExpression(expr)) { return inlayInfo(varArgExpressions.first(), varArg) } hasNonassignable = hasNonassignable || !varArg.isAssignable(expr, substitutor) } return if (hasNonassignable) inlayInfo(varArgExpressions.first(), varArg, showOnlyIfExistedBefore = true) else null } } private class CallArgumentInfo(val parameter: PsiParameter, val argument: PsiExpression) { fun isAssignable(substitutor: PsiSubstitutor): Boolean { return parameter.isAssignable(argument, substitutor) } } private fun PsiParameter.isAssignable(argument: PsiExpression, substitutor: PsiSubstitutor = PsiSubstitutor.EMPTY): Boolean { val substitutedType = substitutor.substitute(type) ?: return false if (PsiPolyExpressionUtil.isPolyExpression(argument)) return true return argument.type?.isAssignableTo(substitutedType) ?: false } private fun PsiType.isAssignableTo(parameterType: PsiType): Boolean { return TypeConversionUtil.isAssignable(parameterType, this) } private fun PsiParameter.typeText() = type.canonicalText
apache-2.0
8907ce7ac90a646140f787f845e6d2b8
35.947507
140
0.705385
4.58054
false
false
false
false
klaplume/lesseract
src/main/kotlin/main/Camera.kt
1
4372
package main import math.Bounds2f import math.Bounds2i import math.Point2f import math.Point2i import sampler.CameraSample import java.awt.Color import java.awt.image.BufferedImage import java.io.File import javax.imageio.ImageIO /** * Created by klaplume on 15/07/17. */ class Camera { val film = Film(Defaults.DEFALUT_RESOLUTION, Bounds2f(0f, 1f, 0f, 1f), 30f, "/home/klaplume/Pictures/default.png", 1f) fun generateRayDifferential(cameraSample: CameraSample): RayDifferentialData { //TODO return RayDifferentialData(RayDifferential(), 1f) } } class Film(val resolution: Point2i, var cropWindow: Bounds2f, val diagonal: Float, val fileName: String, val scale: Float) { val pixels = Array<Pixel>(resolution.x*resolution.y) { i -> Pixel() } val tileSize = Defaults.DEFAULT_TILE_SIZE val croppedPixelBounds = Bounds2i( Math.ceil(((resolution.x-1) * cropWindow.xMin).toDouble()).toInt(), Math.ceil(((resolution.x-1) * cropWindow.xMax).toDouble()).toInt(), Math.ceil(((resolution.y-1) * cropWindow.yMin).toDouble()).toInt(), Math.ceil(((resolution.y-1) * cropWindow.yMax).toDouble()).toInt() ) fun computeTileBounds(tile: Point2i, sampleBounds: Bounds2i): Bounds2i { val x0 = sampleBounds.xMin + tile.x * tileSize val x1 = Math.min(x0 + tileSize -1, sampleBounds.xMax) val y0 = sampleBounds.yMin + tile.y * tileSize val y1 = Math.min(y0 + tileSize -1, sampleBounds.yMax) return Bounds2i(x0, x1, y0, y1) } fun getFilmTile(tileBounds: Bounds2i, frac: Float): FilmTile { var tile = FilmTile(tileBounds, frac) return tile } fun getSampleBounds(): Bounds2i { //TODO incorrect, needs to extends a little further return croppedPixelBounds } fun mergeFilmTile(filmTile: FilmTile) { //TODO val tileBounds = filmTile.pixelBounds for(y in tileBounds.yMin..tileBounds.yMax){ for(x in tileBounds.xMin..tileBounds.xMax){ if(y == 350 && x == 20){ println() } val pixel = getPixel(x, y) val tilePixel = filmTile.getPixel(x, y) //Merge var xyzColor = tilePixel.contribSum.toXYZ() pixel.x = xyzColor.x pixel.y = xyzColor.y pixel.z = xyzColor.z } } } private fun getPixel(x: Int, y: Int): Pixel { return pixels[y * resolution.x + x] } fun writeImage() { //TODO var image = BufferedImage(resolution.x, resolution.y, BufferedImage.TYPE_INT_RGB) for(y in 0..resolution.y-1){ for(x in 0..resolution.x-1){ val p = pixels[y * resolution.x + x] val r = p.x*255 val g = p.y*255 val b = p.z*255 val color = Color(r.toInt(), g.toInt(), b.toInt()) image.setRGB(x, y, color.rgb) } } var res = ImageIO.write(image, "png", File(fileName)) } } class FilmTile(val pixelBounds: Bounds2i, frac: Float) { //class FilmTile(val pixelBounds: Bounds2i) { var pixels = Array<Point2i>((pixelBounds.xMax+1 - pixelBounds.xMin) * (pixelBounds.yMax+1 - pixelBounds.yMin)){ i -> Point2i(0, 0) } var pixels2 = Array((pixelBounds.xMax+1 - pixelBounds.xMin) * (pixelBounds.yMax+1 - pixelBounds.yMin)){ val p = FilmTilePixel() p.contribSum.x = frac p.contribSum.y = frac p.contribSum.z = frac p } //var pxCol = 0f fun addSample(pFilm: Point2f, L: Spectrum, rayWeight: Float){ //TODO needs to be implemented /*for(i in pixels2){ i.contribSum.x = pxCol i.contribSum.y = pxCol i.contribSum.z = pxCol }*/ } fun getPixel(x: Int, y: Int): FilmTilePixel { val width = pixelBounds.xMax - pixelBounds.xMin val offset = (x - pixelBounds.xMin) + (y - pixelBounds.yMin) * width return pixels2[offset] } } class Pixel { var x: Float = 0f var y: Float = 0f var z: Float = 0f } class FilmTilePixel { var contribSum: Spectrum = Spectrum() var filterWeightedSum: Float = 0.0f }
apache-2.0
e84e022e470b8a4819fcee1f409be79a
30.919708
136
0.583028
3.598354
false
false
false
false
smmribeiro/intellij-community
platform/platform-impl/src/com/intellij/internal/ui/uiDslTestAction/OthersPanel.kt
1
1160
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.internal.ui.uiDslTestAction import com.intellij.openapi.ui.Messages import com.intellij.ui.dsl.builder.COLUMNS_LARGE import com.intellij.ui.dsl.builder.columns import com.intellij.ui.dsl.builder.panel import com.intellij.ui.dsl.builder.text import org.jetbrains.annotations.ApiStatus import javax.swing.JEditorPane @Suppress("DialogTitleCapitalization") @ApiStatus.Internal internal class OthersPanel { val panel = panel { group("DslLabel text update") { lateinit var dslText: JEditorPane row { dslText = text("Initial text with a <a href='link'>link</a>", action = { Messages.showMessageDialog("Link '${it.description}' is clicked", "Message", null) }) .component } row { val textField = textField() .text("New text with <a href='another link'>another link</a><br>Second line") .columns(COLUMNS_LARGE) .component button("Update") { dslText.text = textField.text } } } } }
apache-2.0
1e0ce9535b1eff6e8f08d8135ee1ca7f
30.378378
120
0.674138
4.070175
false
false
false
false
blhps/lifeograph-android
app/src/main/java/net/sourceforge/lifeograph/GridCalAdapter.kt
1
5705
/* ********************************************************************************* Copyright (C) 2012-2021 Ahmet Öztürk ([email protected]) This file is part of Lifeograph. Lifeograph is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Lifeograph is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Lifeograph. If not, see <http://www.gnu.org/licenses/>. ***********************************************************************************/ package net.sourceforge.lifeograph import android.content.Context import android.graphics.Color import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.BaseAdapter import android.widget.TextView import androidx.core.content.ContextCompat import androidx.core.widget.TextViewCompat import java.util.* // Days in Current Month internal class GridCalAdapter(context: Context, date: Date) : BaseAdapter() { private val mContext: Context = context private var mDaysInMonth = 0 val mDateCurrent = Date(date.m_date) var mListDays: MutableList<Long> = ArrayList() init { showMonth(date) } override fun getItem(position: Int): String { return mListDays[position].toString() } override fun getCount(): Int { return mListDays.size } fun showMonth(date: Date) { mDateCurrent.m_date = date.m_date mListDays.clear() notifyDataSetChanged() // HEADER for(i in 0..6) { mListDays.add(0L) } mDaysInMonth = date._days_in_month val date2 = Date(date.m_date) date2._day = 1 val numSlotBefore = date2._weekday val prevMonth = Date(date.m_date) prevMonth.backward_months(1) val prevMonthLength = prevMonth._days_in_month val nextMonth = Date(date2.m_date) nextMonth.forward_months(1) // Prev Month days for(i in (prevMonthLength - numSlotBefore + 1)..prevMonthLength) { mListDays.add(Date.make(prevMonth._year, prevMonth._month, i, 1)) } // Current Month Days for(i in 0 until mDaysInMonth) { mListDays.add(Date.make(date._year, date._month, i + 1, 1)) } // Next Month days //final int numSlotAfter = 7 - ( ( numSlotBefore + mDaysInMonth ) % 7 ); // always use 6 rows: val numSlotAfter = (42 - numSlotBefore - mDaysInMonth) for(i in 1..numSlotAfter) { mListDays.add(Date.make(nextMonth._year, nextMonth._month, i, 1)) } } override fun getItemId(position: Int): Long { return position.toLong() } override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { val row: View = if(convertView == null) { val inflater = mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater inflater.inflate(R.layout.cal_day, parent, false) } else convertView val tvDayNo = row.findViewById<TextView>(R.id.calendar_day_gridcell) //TextView num_events_per_day = ( TextView ) row.findViewById( R.id.num_events_per_day ); //num_events_per_day.setTextColor( Color.GREEN ); if(position < 7) { tvDayNo.text = Date.WEEKDAYSSHORT[position + 1] tvDayNo.setTextColor(ContextCompat.getColor(mContext, R.color.t_mid)) tvDayNo.textScaleX = 0.65f } else { val date = Date(mListDays[position] + 1) tvDayNo.text = date._day.toString() val flagWithinMonth = date._month == mDateCurrent._month val flagWeekDay = date._weekday > 0 when { Diary.d.get_entry_count_on_day(date) > 0 -> { TextViewCompat.setTextAppearance(tvDayNo, R.style.boldText) tvDayNo.setTextColor( if(flagWithinMonth) ContextCompat.getColor(mContext, R.color.t_darker) else Color.DKGRAY) } else -> { TextViewCompat.setTextAppearance(tvDayNo, R.style.normalText) tvDayNo.setTextColor( when { flagWithinMonth && flagWeekDay -> // weekdays within month ContextCompat.getColor(mContext, R.color.t_mid) flagWithinMonth -> // weekends within month ContextCompat.getColor(mContext, R.color.t_light) else -> Color.GRAY } ) } } tvDayNo.setBackgroundColor( when { date._pure == mDateCurrent._pure -> ContextCompat.getColor(mContext, R.color.t_lighter) Diary.d.is_open && Diary.d.m_p2chapter_ctg_cur.mMap.containsKey(date._pure) -> ContextCompat.getColor(mContext, R.color.t_lightest) else -> Color.TRANSPARENT } ) } return row } }
gpl-3.0
456b468cee8ef254c1233773de5b68d0
36.519737
98
0.566719
4.511867
false
false
false
false
gradle/gradle
subprojects/kotlin-dsl/src/test/kotlin/org/gradle/kotlin/dsl/execution/ProgramParserTest.kt
3
8306
/* * Copyright 2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.kotlin.dsl.execution import org.hamcrest.CoreMatchers.equalTo import org.hamcrest.MatcherAssert.assertThat import org.junit.Test class ProgramParserTest { @Test fun `empty source parses to empty program`() { assertEmptyProgram("") assertEmptyProgram(" // An empty program\n") assertEmptyProgram(" \r\n// foo\r\n/* block comment */ ") } @Test fun `empty Stage 1 with empty Stage 2 parse to empty program`() { assertEmptyProgram("pluginManagement {}", programTarget = ProgramTarget.Settings) assertEmptyProgram("plugins {}", programTarget = ProgramTarget.Settings) assertEmptyProgram("initscript {}", programTarget = ProgramTarget.Gradle) assertEmptyProgram("buildscript {}") assertEmptyProgram("plugins {}") assertEmptyProgram("buildscript {}\r\nplugins {}") assertEmptyProgram(" /* before */buildscript { /* within */ }/* after */ ") } @Test fun `empty Stage 1 with non-empty Stage 2 parse to Stage 2 with Stage 1 fragments erased`() { val scriptOnlySource = programSourceWith("println(\"Stage 2\")") assertProgramOf( scriptOnlySource, Program.Script(scriptOnlySource) ) val emptyBuildscriptSource = programSourceWith("buildscript { }\nprintln(\"Stage 2\")") assertProgramOf( emptyBuildscriptSource, Program.Script( emptyBuildscriptSource.map { text(" \nprintln(\"Stage 2\")") } ) ) } @Test fun `non-empty Stage 1 with empty Stage 2 parse to Stage 1`() { val source = programSourceWith(" buildscript { println(\"Stage 1\") } ") assertProgramOf( source, Program.Buildscript(source.fragment(1..11, 13..34)) ) } @Test fun `non-empty Stage 1 with non-empty Stage 2 parse to Stage 1 followed by Stage 2`() { val source = ProgramSource( "/src/fragment.gradle.kts", "\r\n\r\nplugins {\r\n java\r\n}\r\nprintln(\"Stage 2\")\r\n\r\n" ) assertProgramOf( source, Program.Staged( Program.Plugins(source.fragment(2..8, 10..19)), Program.Script(source.map { text("\n\n \n \n \nprintln(\"Stage 2\")") }) ) ) } @Test fun `buildscript followed by plugins block followed by script body`() { val source = ProgramSource( "build.gradle.kts", """ buildscript { println("stage 1 buildscript") } plugins { println("stage 1 plugins") } print("stage 2") """.replaceIndent() ) val expectedScript = "" + " \n" + " \n" + "print(\"stage 2\")" assertProgramOf( source, Program.Staged( Program.Stage1Sequence( null, Program.Buildscript(source.fragment(0..10, 12..45)), Program.Plugins(source.fragment(47..53, 55..84)) ), Program.Script(source.map { text(expectedScript) }) ) ) } @Test fun `non-empty init script Stage 1 with empty Stage 2 parse to Stage 1`() { val source = programSourceWith(" initscript { println(\"Stage 1\") } ") assertProgramOf( source, Program.Buildscript(source.fragment(1..10, 12..33)), programTarget = ProgramTarget.Gradle ) } @Test fun `non empty Gradle script with initscript block`() { val source = programSourceWith(" initscript { println(\"Stage 1\") }; println(\"stage 2\")") val scriptText = text(" ; println(\"stage 2\")") assertProgramOf( source, Program.Staged( Program.Buildscript(source.fragment(1..10, 12..33)), Program.Script(source.map { scriptText }) ), programTarget = ProgramTarget.Gradle ) } @Test fun `buildscript followed by pluginManagement block followed by plugins block followed by script body`() { val source = ProgramSource( "settings.gradle.kts", """ pluginManagement { println("stage 1 pluginManagement") } buildscript { println("stage 1 buildscript") } plugins { println("stage 1 plugins") } print("stage 2") """.replaceIndent() ) val expectedScript = "" + " \n" + " \n" + " \n" + "print(\"stage 2\")" assertProgramOf( source, Program.Staged( Program.Stage1Sequence( Program.PluginManagement(source.fragment(0..15, 17..55)), Program.Buildscript(source.fragment(57..67, 69..102)), Program.Plugins(source.fragment(104..110, 112..141)) ), Program.Script(source.map { text(expectedScript) }) ), programTarget = ProgramTarget.Settings ) } @Test fun `buildscript block after plugins block`() { val source = programSourceWith( """ plugins { `kotlin-dsl` } buildscript { dependencies { classpath("org.acme:plugin:1.0") } } dependencies { implementation("org.acme:lib:1.0") } """ ) val expectedScriptSource = programSourceWith( "\n " + "\n " + "\n " + "\n\n " + "\n " + "\n " + "\n " + "\n " + "\n\n dependencies {" + "\n implementation(\"org.acme:lib:1.0\")" + "\n }" ) assertProgramOf( source, Program.Staged( Program.Stage1Sequence( null, Program.Buildscript(source.fragment(79..89, 91..207)), Program.Plugins(source.fragment(13..19, 21..64)) ), Program.Script(expectedScriptSource) ) ) } private fun assertEmptyProgram(contents: String, programTarget: ProgramTarget = ProgramTarget.Project) { assertProgramOf(programSourceWith(contents), Program.Empty, programTarget = programTarget) } private fun assertProgramOf( source: ProgramSource, expected: Program, programKind: ProgramKind = ProgramKind.TopLevel, programTarget: ProgramTarget = ProgramTarget.Project ) { val program = ProgramParser.parse(source, programKind, programTarget) assertThat(program.document, equalTo(expected)) } private fun programSourceWith(contents: String) = ProgramSource("/src/build.gradle.kts", contents) }
apache-2.0
5a1ebadbc1e5d4be382f74044d95b277
30.946154
110
0.504816
5.283715
false
false
false
false
FirebaseExtended/make-it-so-android
app/src/main/java/com/example/makeitso/screens/sign_up/SignUpScreen.kt
1
1979
/* Copyright 2022 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.example.makeitso.screens.sign_up import androidx.compose.foundation.layout.* import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.hilt.navigation.compose.hiltViewModel import com.example.makeitso.R.string as AppText import com.example.makeitso.common.composable.* import com.example.makeitso.common.ext.basicButton import com.example.makeitso.common.ext.fieldModifier @Composable fun SignUpScreen( openAndPopUp: (String, String) -> Unit, modifier: Modifier = Modifier, viewModel: SignUpViewModel = hiltViewModel() ) { val uiState by viewModel.uiState val fieldModifier = Modifier.fieldModifier() BasicToolbar(AppText.create_account) Column( modifier = modifier.fillMaxWidth().fillMaxHeight().verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { EmailField(uiState.email, viewModel::onEmailChange, fieldModifier) PasswordField(uiState.password, viewModel::onPasswordChange, fieldModifier) RepeatPasswordField(uiState.repeatPassword, viewModel::onRepeatPasswordChange, fieldModifier) BasicButton(AppText.create_account, Modifier.basicButton()) { viewModel.onSignUpClick(openAndPopUp) } } }
apache-2.0
fd95d7ce54aabb6c0124396ce8d8e284
34.981818
97
0.799394
4.417411
false
false
false
false
thomasnield/RxKotlinFX
src/main/kotlin/com/github/thomasnield/rxkotlinfx/Subscribers.kt
1
4046
package com.github.thomasnield.rxkotlinfx import io.reactivex.Flowable import io.reactivex.FlowableTransformer import io.reactivex.Observable import io.reactivex.ObservableTransformer import io.reactivex.rxjavafx.subscriptions.CompositeBinding import javafx.beans.binding.Binding import javafx.beans.property.Property /** * Binds the `Property` to an RxJava `Observable`, * meaning it will be bounded to show the latest emissions of that `Observable`. * The `Binding` is also returned so caller can be dispose it later if needed * @return `Binding` */ fun <T> Property<T>.bind(observable: Observable<T>, actionOp: (ObservableBindingSideEffects<T>.() -> Unit)? = null): Binding<T> { val transformer = actionOp?.let { val sideEffects = ObservableBindingSideEffects<T>() it.invoke(sideEffects) sideEffects.transformer } val binding = (transformer?.let { observable.compose(it) }?:observable).toBinding() bind(binding) return binding } /** * Binds the `Property` to an RxJava `Flowable`, * meaning it will be bounded to show the latest emissions of that `Flowable`. * The `Binding` is also returned so caller can be dispose it later if needed * @return `Binding` */ fun <T> Property<T>.bind(flowable: Flowable<T>, actionOp: (FlowableBindingSideEffects<T>.() -> Unit)? = null): Binding<T> { val transformer = actionOp?.let { val sideEffects = FlowableBindingSideEffects<T>() it.invoke(sideEffects) sideEffects.transformer } val binding = (transformer?.let { flowable.compose(it) }?:flowable).toBinding() bind(binding) return binding } fun <T> Binding<T>.addTo(compositeBinding: CompositeBinding): Binding<T> { compositeBinding.add(this) return this } operator fun <T> CompositeBinding.plusAssign(binding: Binding<T>) = add(binding) operator fun CompositeBinding.plusAssign(compositeBinding: CompositeBinding) = add(compositeBinding) operator fun <T> CompositeBinding.minusAssign(binding: Binding<T>) = remove(binding) operator fun CompositeBinding.minusAssign(compositeBinding: CompositeBinding) = remove(compositeBinding) class ObservableBindingSideEffects<T> { private var onNextAction: ((T) -> Unit)? = null private var onCompleteAction: (() -> Unit)? = null private var onErrorAction: ((ex: Throwable) -> Unit)? = null fun onNext(onNext: (T) -> Unit): Unit { onNextAction = onNext } fun onComplete(onComplete: () -> Unit): Unit { onCompleteAction = onComplete } fun onError(onError: (ex: Throwable) -> Unit): Unit { onErrorAction = onError } internal val transformer: ObservableTransformer<T, T> get() = ObservableTransformer<T, T> { obs -> var withActions: Observable<T> = obs withActions = onNextAction?.let { withActions.doOnNext(onNextAction) } ?: withActions withActions = onCompleteAction?.let { withActions.doOnComplete(onCompleteAction) } ?: withActions withActions = onErrorAction?.let { withActions.doOnError(onErrorAction) } ?: withActions withActions } } class FlowableBindingSideEffects<T> { private var onNextAction: ((T) -> Unit)? = null private var onCompleteAction: (() -> Unit)? = null private var onErrorAction: ((ex: Throwable) -> Unit)? = null fun onNext(onNext: (T) -> Unit): Unit { onNextAction = onNext } fun onComplete(onComplete: () -> Unit): Unit { onCompleteAction = onComplete } fun onError(onError: (ex: Throwable) -> Unit): Unit { onErrorAction = onError } internal val transformer: FlowableTransformer<T, T> get() = FlowableTransformer<T, T> { obs -> var withActions: Flowable<T> = obs withActions = onNextAction?.let { withActions.doOnNext(onNextAction) } ?: withActions withActions = onCompleteAction?.let { withActions.doOnComplete(onCompleteAction) } ?: withActions withActions = onErrorAction?.let { withActions.doOnError(onErrorAction) } ?: withActions withActions } }
apache-2.0
73b562603437064035bec14b1676ab7d
36.12844
129
0.69822
4.24109
false
false
false
false
AsynkronIT/protoactor-kotlin
proto-actor/src/main/kotlin/actor/proto/RestartStatistics.kt
1
540
package actor.proto import java.lang.System.currentTimeMillis import java.time.Duration class RestartStatistics(var failureCount: Int, private var lastFailureTimeMillis: Long) { fun fail() { failureCount++ lastFailureTimeMillis = now() } fun reset() { failureCount = 0 } fun restart() { lastFailureTimeMillis = now() } private fun now(): Long = currentTimeMillis() fun isWithinDuration(within: Duration): Boolean = (now() - lastFailureTimeMillis) < within.toMillis() }
apache-2.0
7be31f90d798b883eac91c932c11c749
21.5
105
0.668519
4.42623
false
false
false
false
ethauvin/kobalt
src/test/kotlin/com/beust/kobalt/internal/DependencyTest.kt
2
2632
package com.beust.kobalt.internal import com.beust.kobalt.BaseTest import com.beust.kobalt.TestConfig import com.beust.kobalt.api.ITestJvmFlagContributor import com.beust.kobalt.api.ITestJvmFlagInterceptor import com.beust.kobalt.api.KobaltContext import com.beust.kobalt.api.Project import com.beust.kobalt.maven.dependency.FileDependency import com.beust.kobalt.project import org.assertj.core.api.Assertions.assertThat import org.testng.annotations.Test import javax.inject.Inject /** * Test ITestJvmFlagContributor and ITestJvmFlagInterceptor. */ class DependencyTest @Inject constructor(val context: KobaltContext) : BaseTest() { private fun isWindows() = System.getProperty("os.name").toLowerCase().contains("ndows") private val A_JAR = if (isWindows()) "c:\\tmp\\a.jar" else "/tmp/a.jar" private val B_JAR = if (isWindows()) "c:\\tmp\\b.jar" else "/tmp/b.jar" private val project : Project get() = project { name = "dummy" } private val classpath = listOf(FileDependency(A_JAR)) private val contributor = object : ITestJvmFlagContributor { override fun testJvmFlagsFor(project: Project, context: KobaltContext, currentFlags: List<String>): List<String> { return listOf("-agent", "foo") } } private val interceptor = object : ITestJvmFlagInterceptor { override fun testJvmFlagsFor(project: Project, context: KobaltContext, currentFlags: List<String>): List<String> { return currentFlags.map { if (it == A_JAR) B_JAR else it } } } private fun runTest(pluginInfo: IPluginInfo, expected: List<String>) { val result = TestNgRunner().calculateAllJvmArgs(project, context, TestConfig(project), classpath, pluginInfo) assertThat(result).isEqualTo(expected) } @Test fun noContributorsNoInterceptors() { runTest(BasePluginInfo(), listOf("-ea", "-classpath", A_JAR)) } @Test fun contributorOnly() { runTest(BasePluginInfo().apply { testJvmFlagContributors.add(contributor) }, listOf("-ea", "-classpath", A_JAR, "-agent", "foo")) } @Test fun interceptorOnly() { runTest(BasePluginInfo().apply { testJvmFlagInterceptors.add(interceptor) }, listOf("-ea", "-classpath", B_JAR)) } @Test fun contributorAndInterceptor() { runTest(BasePluginInfo().apply { testJvmFlagContributors.add(contributor) testJvmFlagInterceptors.add(interceptor) }, listOf("-ea", "-classpath", B_JAR, "-agent", "foo")) } }
apache-2.0
14206b9192976c2924556eb8acfb322b
35.555556
94
0.667553
4.231511
false
true
false
false
ujpv/intellij-rust
src/main/kotlin/org/rust/lang/core/types/visitors/impl/RustTypificationEngine.kt
1
9370
package org.rust.lang.core.types.visitors.impl import com.intellij.psi.PsiElement import com.intellij.psi.util.PsiTreeUtil import org.rust.lang.core.psi.* import org.rust.lang.core.psi.impl.mixin.asRustPath import org.rust.lang.core.psi.impl.mixin.parentEnum import org.rust.lang.core.psi.util.parentOfType import org.rust.lang.core.psi.visitors.RustComputingVisitor import org.rust.lang.core.symbols.RustPath import org.rust.lang.core.types.* import org.rust.lang.core.types.unresolved.RustUnresolvedPathType import org.rust.lang.core.types.unresolved.RustUnresolvedReferenceType import org.rust.lang.core.types.unresolved.RustUnresolvedTupleType import org.rust.lang.core.types.unresolved.RustUnresolvedType import org.rust.lang.core.types.util.resolvedType import org.rust.lang.core.types.util.type object RustTypificationEngine { fun typifyType(type: RustTypeElement): RustUnresolvedType = RustTypeTypificationVisitor().compute(type) fun typifyExpr(expr: RustExprElement): RustType = RustExprTypificationVisitor().compute(expr) fun typifyItem(item: RustItemElement): RustType = RustItemTypificationVisitor().compute(item) fun typify(named: RustNamedElement): RustType { return when (named) { is RustItemElement -> typifyItem(named) is RustSelfArgumentElement -> deviseSelfType(named) is RustPatBindingElement -> deviseBoundPatType(named) is RustEnumVariantElement -> deviseEnumType(named) is RustFnElement -> deviseFunctionType(named) is RustTypeParamElement -> RustTypeParameterType(named) else -> RustUnknownType } } } private class RustExprTypificationVisitor : RustComputingVisitor<RustType>() { override fun visitExpr(o: RustExprElement) = set { // Default until we handle all the cases explicitly RustUnknownType } override fun visitUnaryExpr(o: RustUnaryExprElement) = set { if (o.box != null) RustUnknownType else o.expr?.resolvedType?.let { if (o.and != null) RustReferenceType(it, o.mut != null) else it } ?: RustUnknownType } override fun visitPathExpr(o: RustPathExprElement) = set { val resolve = o.path.reference.resolve() as? RustNamedElement resolve?.let { RustTypificationEngine.typify(it) } ?: RustUnknownType } override fun visitStructExpr(o: RustStructExprElement) = set { val base = o.path.reference.resolve() when (base) { is RustStructItemElement -> base.resolvedType is RustEnumVariantElement -> base.parentEnum.resolvedType else -> RustUnknownType } } override fun visitTupleExpr(o: RustTupleExprElement) = set { RustTupleType(o.exprList.map { RustTypificationEngine.typifyExpr(it) }) } override fun visitUnitExpr(o: RustUnitExprElement) = set { RustUnitType } override fun visitCallExpr(o: RustCallExprElement) = set { val fn = o.expr if (fn is RustPathExprElement) { val variant = fn.path.reference.resolve() if (variant is RustEnumVariantElement) { return@set variant.parentEnum.resolvedType } } val calleeType = fn.resolvedType (calleeType as? RustFunctionType)?.retType ?: RustUnknownType } override fun visitMethodCallExpr(o: RustMethodCallExprElement) = set { val method = o.reference.resolve() as? RustFnElement method?.let { deviseFunctionType(it).retType } ?: RustUnknownType } override fun visitFieldExpr(o: RustFieldExprElement) = set { val field = o.reference.resolve() when (field) { is RustFieldDeclElement -> field.type?.resolvedType is RustTupleFieldDeclElement -> field.type.resolvedType else -> null } ?: RustUnknownType } override fun visitLitExpr(o: RustLitExprElement) = set { when { o.integerLiteral != null -> RustIntegerType.fromLiteral(o.integerLiteral!!) o.floatLiteral != null -> RustFloatType.fromLiteral(o.floatLiteral!!) o.stringLiteral != null -> RustStringSliceType o.charLiteral != null -> RustCharacterType o.`true` != null || o.`false` != null -> RustBooleanType else -> RustUnknownType } } override fun visitBlockExpr(o: RustBlockExprElement) = set { o.block?.resolvedType ?: RustUnknownType } override fun visitIfExpr(o: RustIfExprElement) = set { if (o.elseBranch == null) RustUnitType else o.block?.resolvedType ?: RustUnknownType } override fun visitWhileExpr(o: RustWhileExprElement) = set { RustUnitType } override fun visitLoopExpr(o: RustLoopExprElement) = set { RustUnitType } override fun visitForExpr(o: RustForExprElement) = set { RustUnitType } override fun visitParenExpr(o: RustParenExprElement) = set { o.expr.resolvedType } override fun visitBinaryExpr(o: RustBinaryExprElement) = set { when (o.operatorType) { RustTokenElementTypes.ANDAND, RustTokenElementTypes.OROR, RustTokenElementTypes.EQEQ, RustTokenElementTypes.EXCLEQ, RustTokenElementTypes.LT, RustTokenElementTypes.GT, RustTokenElementTypes.GTEQ, RustTokenElementTypes.LTEQ -> RustBooleanType else -> RustUnknownType } } private val RustBlockElement.resolvedType: RustType get() = expr?.resolvedType ?: RustUnitType } private class RustItemTypificationVisitor : RustComputingVisitor<RustType>() { override fun visitElement(element: PsiElement) = set { check(element is RustItemElement) { "Panic! Should not be used with anything except the inheritors of `RustItemElement` hierarchy!" } RustUnknownType } override fun visitStructItem(o: RustStructItemElement) = set { RustStructType(o) } override fun visitEnumItem(o: RustEnumItemElement) = set { RustEnumType(o) } override fun visitTypeItem(o: RustTypeItemElement) = set { o.type.resolvedType } override fun visitFnItem(o: RustFnItemElement) = set { deviseFunctionType(o) } override fun visitTraitItem(o: RustTraitItemElement) = set { RustTraitType(o) } } private class RustTypeTypificationVisitor : RustComputingVisitor<RustUnresolvedType>() { override fun visitType(o: RustTypeElement) = set { RustUnknownType } override fun visitTupleType(o: RustTupleTypeElement) = set { // Perhaps introduce tuple_type to PSI? if (o.typeList.size > 0) RustUnresolvedTupleType(o.typeList.map { it.type }) else RustUnitType } override fun visitPathType(o: RustPathTypeElement) = set { val path = o.path?.asRustPath ?: return@set RustUnknownType if (path is RustPath.Named && path.segments.isEmpty()) { val primitiveType = RustPrimitiveTypeBase.fromTypeName(path.head.name) if (primitiveType != null) return@set primitiveType } RustUnresolvedPathType(path) } override fun visitRefType(o: RustRefTypeElement) = set { o.type?.let { RustUnresolvedReferenceType(it.type, o.mut != null) } ?: RustUnknownType } } /** * NOTA BENE: That's far from complete */ private fun deviseBoundPatType(binding: RustPatBindingElement): RustType { //TODO: probably want something more precise than `getTopmostParentOfType` here val pattern = PsiTreeUtil.getTopmostParentOfType(binding, RustPatElement::class.java) ?: return RustUnknownType val parent = pattern.parent val type = when (parent) { is RustLetDeclElement -> // use type ascription, if present or fallback to the type of the initializer expression parent.type?.resolvedType ?: parent.expr?.resolvedType is RustParameterElement -> parent.type?.resolvedType is RustScopedLetDeclElement -> parent.expr.resolvedType else -> null } ?: return RustUnknownType return RustTypeInferenceEngine.inferPatBindingTypeFrom(binding, pattern, type) } /** * Devises type for the given (implicit) self-argument */ private fun deviseSelfType(self: RustSelfArgumentElement): RustType { var Self = self.parentOfType<RustImplItemElement>()?.type?.resolvedType ?: return RustUnknownType if (self.and != null) { Self = RustReferenceType(Self, mutable = self.mut != null) } return Self } private fun deviseEnumType(variant: RustEnumVariantElement): RustType = RustTypificationEngine.typifyItem((variant.parent as RustEnumBodyElement).parent as RustEnumItemElement) private fun deviseFunctionType(fn: RustFnElement): RustFunctionType { val paramTypes = mutableListOf<RustType>() val params = fn.parameters if (params != null) { val self = params.selfArgument if (self != null) { paramTypes += deviseSelfType(self) } paramTypes += params.parameterList.orEmpty().map { it.type?.resolvedType ?: RustUnknownType } } return RustFunctionType(paramTypes, fn.retType?.type?.resolvedType ?: RustUnitType) }
mit
73e07d91b6b300abe1957a06986edd76
33.575646
115
0.678655
4.453422
false
false
false
false
owntracks/android
project/app/src/gms/java/org/owntracks/android/ui/map/GoogleMapFragment.kt
1
13689
package org.owntracks.android.ui.map import android.annotation.SuppressLint import android.content.res.Configuration import android.graphics.Bitmap import android.location.Location import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.lifecycle.Observer import com.google.android.gms.maps.CameraUpdate import com.google.android.gms.maps.CameraUpdateFactory import com.google.android.gms.maps.GoogleMap import com.google.android.gms.maps.GoogleMap.MAP_TYPE_HYBRID import com.google.android.gms.maps.GoogleMap.MAP_TYPE_NORMAL import com.google.android.gms.maps.GoogleMap.MAP_TYPE_SATELLITE import com.google.android.gms.maps.GoogleMap.MAP_TYPE_TERRAIN import com.google.android.gms.maps.GoogleMap.OnCameraMoveStartedListener.REASON_GESTURE import com.google.android.gms.maps.LocationSource import com.google.android.gms.maps.MapsInitializer import com.google.android.gms.maps.OnMapReadyCallback import com.google.android.gms.maps.OnMapsSdkInitializedCallback import com.google.android.gms.maps.model.BitmapDescriptorFactory import com.google.android.gms.maps.model.CameraPosition import com.google.android.gms.maps.model.Circle import com.google.android.gms.maps.model.CircleOptions import com.google.android.gms.maps.model.MapStyleOptions import com.google.android.gms.maps.model.Marker import com.google.android.gms.maps.model.MarkerOptions import org.owntracks.android.R import org.owntracks.android.data.WaypointModel import org.owntracks.android.databinding.GoogleMapFragmentBinding import org.owntracks.android.gms.location.toGMSLatLng import org.owntracks.android.location.LatLng import org.owntracks.android.location.toLatLng import org.owntracks.android.support.ContactImageBindingAdapter import org.owntracks.android.support.Preferences import org.owntracks.android.ui.map.osm.OSMMapFragment import timber.log.Timber class GoogleMapFragment internal constructor( private val preferences: Preferences, contactImageBindingAdapter: ContactImageBindingAdapter ) : MapFragment<GoogleMapFragmentBinding>(contactImageBindingAdapter), OnMapReadyCallback, OnMapsSdkInitializedCallback { data class RegionOnMap(val marker: Marker, val circle: Circle) override val layout: Int get() = R.layout.google_map_fragment private var locationObserver: Observer<Location>? = null private val googleMapLocationSource: LocationSource by lazy { object : LocationSource { override fun activate( onLocationChangedListener: LocationSource.OnLocationChangedListener ) { locationObserver = object : Observer<Location> { override fun onChanged(location: Location) { onLocationChangedListener.onLocationChanged(location) viewModel.setCurrentBlueDotLocation(location.toLatLng()) if (viewModel.viewMode == MapViewModel.ViewMode.Device) { updateCamera(location.toLatLng()) } } } locationObserver?.run { viewModel.currentLocation.observe(viewLifecycleOwner, this) } } override fun deactivate() { locationObserver?.run(viewModel.currentLocation::removeObserver) } } } private var googleMap: GoogleMap? = null private val markersOnMap: MutableMap<String, Marker> = HashMap() private val regionsOnMap: MutableList<RegionOnMap> = mutableListOf() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { val root = super.onCreateView(inflater, container, savedInstanceState) binding.googleMapView.onCreate(savedInstanceState) binding.googleMapView.getMapAsync(this) return root } override fun onMapReady(googleMap: GoogleMap) { this.googleMap = googleMap initMap() viewModel.onMapReady() } private fun setMapStyle() { if (resources .configuration .uiMode .and(Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES ) { googleMap?.setMapStyle( MapStyleOptions.loadRawResourceStyle( requireContext(), R.raw.google_maps_night_theme ) ) } } private fun MapLocationZoomLevelAndRotation.toCameraUpdate(): CameraUpdate = CameraUpdateFactory.newCameraPosition( CameraPosition.builder() .target(this.latLng.toGMSLatLng()) .zoom(convertStandardZoomToGoogleZoom(this.zoom).toFloat()) .bearing( if (preferences.enableMapRotation) convertBetweenStandardRotationAndBearing( this.rotation ) else 0f ) .build() ) @SuppressLint("MissingPermission") override fun initMap() { MapsInitializer.initialize(requireContext(), MapsInitializer.Renderer.LATEST, this) this.googleMap?.run { val myLocationEnabled = (requireActivity() as MapActivity).checkAndRequestMyLocationCapability(false) Timber.d("GoogleMapFragment initMap hasLocationCapability=$myLocationEnabled") setMaxZoomPreference(MAX_ZOOM_LEVEL.toFloat()) setMinZoomPreference(MIN_ZOOM_LEVEL.toFloat()) isIndoorEnabled = false isMyLocationEnabled = myLocationEnabled uiSettings.isMyLocationButtonEnabled = false uiSettings.setAllGesturesEnabled(true) preferences.enableMapRotation.run { uiSettings.isCompassEnabled = this uiSettings.isRotateGesturesEnabled = this } setLocationSource(googleMapLocationSource) setMapStyle() viewModel.initMapStartingLocation().run { moveCamera(toCameraUpdate()) } setOnMarkerClickListener { it.tag?.run { onMarkerClicked(this as String) true } ?: false } setOnMapClickListener { onMapClick() } setOnCameraMoveStartedListener { reason -> if (reason == REASON_GESTURE) { onMapClick() } } setOnCameraIdleListener { viewModel.setMapLocationFromMapMoveEvent( this.cameraPosition.run { MapLocationZoomLevelAndRotation( LatLng( target.latitude, target.longitude ), convertGoogleZoomToStandardZoom(zoom.toDouble()), convertBetweenStandardRotationAndBearing(bearing) ) } ) } viewModel.mapLayerStyle.value?.run { setMapLayerType(this) } // We need to specifically re-draw any contact markers and regions now that we've re-init the map viewModel.allContacts.value?.values?.toSet()?.run(::updateAllMarkers) viewModel.regions.value?.toSet()?.run(::drawRegions) } } override fun updateCamera(latLng: org.owntracks.android.location.LatLng) { googleMap?.moveCamera(CameraUpdateFactory.newLatLng(latLng.toGMSLatLng())) } override fun updateMarkerOnMap( id: String, latLng: org.owntracks.android.location.LatLng, image: Bitmap ) { googleMap?.run { // If we don't have a google Map, we can't add markers to it // Remove null markers from the collection markersOnMap.values.removeAll { it.tag == null } markersOnMap.getOrPut(id) { addMarker( MarkerOptions() .position(latLng.toGMSLatLng()) .anchor(0.5f, 0.5f).visible(false) )!!.also { it.tag = id } }.run { position = latLng.toGMSLatLng() setIcon(BitmapDescriptorFactory.fromBitmap(image)) isVisible = true } } } override fun removeMarkerFromMap(id: String) { markersOnMap[id]?.remove() } override fun onResume() { super.onResume() binding.googleMapView.onResume() setMapStyle() } override fun onLowMemory() { binding.googleMapView.onLowMemory() super.onLowMemory() } override fun onPause() { binding.googleMapView.onPause() super.onPause() } override fun onDestroy() { binding.googleMapView.onDestroy() super.onDestroy() } override fun onSaveInstanceState(outState: Bundle) { binding.googleMapView.onSaveInstanceState(outState) super.onSaveInstanceState(outState) } override fun onStart() { super.onStart() binding.googleMapView.onStart() } override fun onStop() { binding.googleMapView.onStop() super.onStop() } override fun onMapsSdkInitialized(renderer: MapsInitializer.Renderer) { Timber.d("Maps SDK initialized with renderer: ${renderer.name}") } override fun drawRegions(regions: Set<WaypointModel>) { if (preferences.showRegionsOnMap) { googleMap?.run { Timber.d("Drawing regions on map") regionsOnMap.forEach { it.circle.remove() it.marker.remove() } regions.forEach { region -> RegionOnMap( MarkerOptions().apply { position(region.location.toLatLng().toGMSLatLng()) anchor(0.5f, 1.0f) title(region.description) }.let { addMarker(it)!! }, CircleOptions().apply { center(region.location.toLatLng().toGMSLatLng()) radius(region.geofenceRadius.toDouble()) fillColor(getRegionColor()) strokeWidth(0.0f) }.let { addCircle(it) } ).run(regionsOnMap::add) } } } } companion object { private const val MIN_ZOOM_LEVEL: Double = 4.0 private const val MAX_ZOOM_LEVEL: Double = 20.0 } /** * Convert standard rotation to google bearing. OSM uses a "map rotation" concept to represent * how the map is oriented, whereas google uses the "bearing". These are not the same thing, so * this converts from a rotation to a bearing and back again (because it's reversable) * * @param input * @return an equivalent bearing */ private fun convertBetweenStandardRotationAndBearing(input: Float): Float = -input % 360 /** * Converts standard (OSM) zoom to Google Maps zoom level. Simple linear conversion * * @param inputZoom Zoom level from standard (OSM) * @return Equivalent zoom level on Google Maps */ private fun convertStandardZoomToGoogleZoom(inputZoom: Double): Double = linearConversion( OSMMapFragment.MIN_ZOOM_LEVEL..OSMMapFragment.MAX_ZOOM_LEVEL, MIN_ZOOM_LEVEL..MAX_ZOOM_LEVEL, inputZoom ) /** * Converts Google Maps zoom to Standard (OSM) zoom level. Simple linear conversion * * @param inputZoom Zoom level from Google Maps * @return Equivalent zoom level on Standard (OSM) */ private fun convertGoogleZoomToStandardZoom(inputZoom: Double): Double = linearConversion( MIN_ZOOM_LEVEL..MAX_ZOOM_LEVEL, OSMMapFragment.MIN_ZOOM_LEVEL..OSMMapFragment.MAX_ZOOM_LEVEL, inputZoom ) /** * Linear conversion of a point in a range to the equivalent point in another range * * @param fromRange Starting range the given point is in * @param toRange Range to translate the point to * @param point point in the starting range * @return a value that's at the same location in [toRange] as [point] is in [fromRange] */ fun linearConversion( fromRange: ClosedRange<Double>, toRange: ClosedRange<Double>, point: Double ): Double { if (!fromRange.contains(point)) { throw Exception("Given point $point is not in fromRange $fromRange") } return ((point - fromRange.start) / (fromRange.endInclusive - fromRange.start)) * (toRange.endInclusive - toRange.start) + toRange.start } override fun setMapLayerType(mapLayerStyle: MapLayerStyle) { when (mapLayerStyle) { MapLayerStyle.GoogleMapDefault -> { googleMap?.mapType = MAP_TYPE_NORMAL } MapLayerStyle.GoogleMapHybrid -> { googleMap?.mapType = MAP_TYPE_HYBRID } MapLayerStyle.GoogleMapSatellite -> { googleMap?.mapType = MAP_TYPE_SATELLITE } MapLayerStyle.GoogleMapTerrain -> { googleMap?.mapType = MAP_TYPE_TERRAIN } else -> { Timber.w("Unsupported map layer type $mapLayerStyle") } } } }
epl-1.0
e286b0d7c26d1e5f0d741d7bfa8e620f
35.997297
144
0.613777
5.07
false
false
false
false
jimschubert/kopper
kopper-cli/src/main/kotlin/us/jimschubert/kopper/cli/TypedApp.kt
1
1636
package us.jimschubert.kopper.cli import us.jimschubert.kopper.typed.BooleanArgument import us.jimschubert.kopper.typed.StringArgument import us.jimschubert.kopper.typed.TypedArgumentParser fun main(args: Array<String>) { val arguments = TypedArgs( arrayOf( "-version", "-f", "asdf.txt", "--allowEmpty", "-q", "trailing", "arguments") ) if (arguments.help) return arguments.printHelp(System.out) println("quiet=${arguments.quiet}") println("file=${arguments.file}") println("allowEmpty=${arguments.allowEmpty}") println("remainingArgs=${arguments._etc_.joinToString()}") if (arguments.version) { println("version 1.0.0 or whatever.") } } class TypedArgs(args: Array<String>) : TypedArgumentParser(args, "TypedApp", "Example Typed Arguments Application") { val quiet by BooleanArgument(self, "q", default = true, longOption = listOf("quiet", "silent"), description = "Run quietly" ) val file by StringArgument(self, "f", longOption = listOf("file"), description = "The filename to process", parameterText = "filename") val allowEmpty by BooleanArgument(self, "a", longOption = listOf("allowEmpty")) val help by BooleanArgument(self, "h", longOption = listOf("help"), description = "Display the help message") val version by BooleanArgument(self, "version", description = "Get the current version") }
mit
fe5f73608f4f71094f54ae34655bd641
31.098039
117
0.595966
4.482192
false
false
false
false
jiangkang/KTools
tools/src/main/java/com/jiangkang/tools/service/WatchingTopActivityService.kt
1
2136
package com.jiangkang.tools.service import android.app.AlarmManager import android.app.PendingIntent import android.app.Service import android.content.Context import android.content.Intent import android.os.Handler import android.os.IBinder import android.os.Looper import android.os.SystemClock import com.jiangkang.tools.extend.activityManager import com.jiangkang.tools.widget.FloatingWindow import java.util.* class WatchingTopActivityService : Service() { private var info = "" var timer = Timer() override fun onCreate() { super.onCreate() } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { timer.scheduleAtFixedRate(WatchingTask(this), 0, 500) return super.onStartCommand(intent, flags, startId) } override fun onTaskRemoved(rootIntent: Intent) { val restartServiceIntent = Intent(applicationContext, this.javaClass) restartServiceIntent.`package` = packageName val restartServicePendingIntent = PendingIntent.getService( applicationContext, 1, restartServiceIntent, PendingIntent.FLAG_ONE_SHOT) val alarmService = applicationContext .getSystemService(Context.ALARM_SERVICE) as AlarmManager alarmService.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 500, restartServicePendingIntent) super.onTaskRemoved(rootIntent) } override fun onBind(intent: Intent): IBinder? { return null } inner class WatchingTask(context: Context) : TimerTask() { private val mContext = context override fun run() { val runningTasks = mContext.activityManager.getRunningTasks(1) val topActivity = "${runningTasks[0].topActivity?.packageName}\n${runningTasks[0].topActivity?.className}" if (info !== topActivity) { info = topActivity Handler(Looper.getMainLooper()).post { FloatingWindow.show(mContext, info) } } } } }
mit
ba3f8f3c8d9771a8c0ea64d08a1552ce
27.105263
118
0.664326
4.933025
false
false
false
false
mcxiaoke/kotlin-koi
core/src/main/kotlin/com/mcxiaoke/koi/adapter/QuickViewBinder.kt
1
3631
package com.mcxiaoke.koi.adapter import android.content.Context import android.graphics.Bitmap import android.graphics.drawable.Drawable import android.text.util.Linkify import android.view.View import android.widget.* /** * User: mcxiaoke * Date: 16/1/30 * Time: 18:57 */ open class QuickViewBinder constructor( val context: Context, val view: View, var position: Int) { init { view.tag = this } inline fun <reified T : View> findView(viewId: Int): T = view.findViewById(viewId) as T fun setText(viewId: Int, value: String): QuickViewBinder { findView<TextView>(viewId).text = value return this } fun setImageResource(viewId: Int, imageResId: Int): QuickViewBinder { findView<ImageView>(viewId).setImageResource(imageResId) return this } fun setBackgroundColor(viewId: Int, color: Int): QuickViewBinder { findView<View>(viewId).setBackgroundColor(color) return this } fun setBackgroundRes(viewId: Int, backgroundRes: Int): QuickViewBinder { findView<View>(viewId).setBackgroundResource(backgroundRes) return this } fun setTextColor(viewId: Int, textColor: Int): QuickViewBinder { findView<TextView>(viewId).setTextColor(textColor) return this } fun setTextColorRes(viewId: Int, textColorRes: Int): QuickViewBinder { findView<TextView>(viewId).setTextColor(context.resources.getColor(textColorRes)) return this } fun setImageDrawable(viewId: Int, drawable: Drawable): QuickViewBinder { findView<ImageView>(viewId).setImageDrawable(drawable) return this } fun setImageBitmap(viewId: Int, bitmap: Bitmap): QuickViewBinder { findView<ImageView>(viewId).setImageBitmap(bitmap) return this } fun setAlpha(viewId: Int, value: Float): QuickViewBinder { findView<View>(viewId).alpha = value return this } fun setVisible(viewId: Int, visible: Boolean): QuickViewBinder { findView<View>(viewId).visibility = if (visible) View.VISIBLE else View.GONE return this } fun linkify(viewId: Int): QuickViewBinder { Linkify.addLinks(findView<TextView>(viewId), Linkify.ALL) return this } fun setOnClickListener(viewId: Int, listener: View.OnClickListener): QuickViewBinder { findView<View>(viewId).setOnClickListener(listener) return this } fun setOnTouchListener(viewId: Int, listener: View.OnTouchListener): QuickViewBinder { findView<View>(viewId).setOnTouchListener(listener) return this } fun setOnLongClickListener(viewId: Int, listener: View.OnLongClickListener) : QuickViewBinder { findView<View>(viewId).setOnLongClickListener(listener) return this } fun setOnItemClickListener(viewId: Int, listener: AdapterView.OnItemClickListener) : QuickViewBinder { findView<AdapterView<Adapter>>(viewId).onItemClickListener = listener return this } fun setOnItemLongClickListener(viewId: Int, listener: AdapterView.OnItemLongClickListener) : QuickViewBinder { findView<AdapterView<Adapter>>(viewId).onItemLongClickListener = listener return this } fun setChecked(viewId: Int, checked: Boolean): QuickViewBinder { (findView<View>(viewId) as Checkable).isChecked = checked return this } }
apache-2.0
468e8d25d5fceb9f09f9147d050ab9ba
29.266667
91
0.654365
5.008276
false
false
false
false
Magneticraft-Team/Magneticraft
src/main/kotlin/com/cout970/magneticraft/systems/tilemodules/ModuleGrinderMb.kt
2
2316
package com.cout970.magneticraft.systems.tilemodules import com.cout970.magneticraft.Magneticraft import com.cout970.magneticraft.misc.vector.rotatePoint import com.cout970.magneticraft.misc.vector.xi import com.cout970.magneticraft.misc.vector.yi import com.cout970.magneticraft.misc.vector.zi import com.cout970.magneticraft.misc.world.isServer import com.cout970.magneticraft.registry.ELECTRIC_NODE_HANDLER import com.cout970.magneticraft.systems.blocks.IOnActivated import com.cout970.magneticraft.systems.blocks.OnActivatedArgs import com.cout970.magneticraft.systems.tileentities.IModule import com.cout970.magneticraft.systems.tileentities.IModuleContainer import net.minecraft.util.EnumFacing import net.minecraft.util.math.BlockPos import net.minecraftforge.common.capabilities.Capability class ModuleGrinderMb( val facingGetter: () -> EnumFacing, val energyModule: () -> ModuleElectricity, override val name: String = "module_grinder_mb" ) : IModule, IOnActivated { override lateinit var container: IModuleContainer inline val facing get() = facingGetter() fun getCapability(cap: Capability<*>, side: EnumFacing?, relPos: BlockPos): Any? { if (cap != ELECTRIC_NODE_HANDLER) return null if (side != facing.rotateY()) return null val connectorPos = facing.rotatePoint(BlockPos.ORIGIN, BlockPos(1, 1, -1)) if (relPos != connectorPos) return null return energyModule() } fun getConnectableDirections(): List<Pair<BlockPos, EnumFacing>> { return if (facing.rotateY().axisDirection == EnumFacing.AxisDirection.NEGATIVE) { val pos = facing.rotatePoint(BlockPos.ORIGIN, BlockPos(2, 1, -1)) listOf(pos to getConnectionSide()) } else emptyList() } private fun getConnectionSide() = facing.rotateY() fun canConnectAtSide(facing: EnumFacing?): Boolean { return facing == getConnectionSide() || facing == getConnectionSide().opposite } override fun onActivated(args: OnActivatedArgs): Boolean { if (!args.playerIn.isSneaking) { if (args.worldIn.isServer) { args.playerIn.openGui(Magneticraft, -1, args.worldIn, pos.xi, pos.yi, pos.zi) } return true } else { return false } } }
gpl-2.0
72fcd11a6d12c3ed06c0068a5c4269fb
36.983607
93
0.715889
4.203267
false
false
false
false
vhromada/Catalog-Spring
src/test/kotlin/cz/vhromada/catalog/web/mapper/MovieMapperTest.kt
1
1404
package cz.vhromada.catalog.web.mapper import cz.vhromada.catalog.entity.Movie import cz.vhromada.catalog.web.CatalogMapperTestConfiguration import cz.vhromada.catalog.web.common.MovieUtils import cz.vhromada.catalog.web.fo.MovieFO import cz.vhromada.catalog.web.mapper.impl.MovieMapperImpl import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.springframework.beans.factory.annotation.Autowired import org.springframework.test.context.ContextConfiguration import org.springframework.test.context.junit.jupiter.SpringExtension /** * A class represents test for mapper between [Movie] and [MovieFO]. * * @author Vladimir Hromada */ @ExtendWith(SpringExtension::class) @ContextConfiguration(classes = [CatalogMapperTestConfiguration::class]) class MovieMapperTest { /** * Mapper for movies */ @Autowired private lateinit var mapper: MovieMapper /** * Test method for [MovieMapperImpl.map]. */ @Test fun map() { val movie = MovieUtils.getMovie() val movieFO = mapper.map(movie) MovieUtils.assertMovieDeepEquals(movie, movieFO) } /** * Test method for [MovieMapperImpl.mapBack]. */ @Test fun mapBack() { val movieFO = MovieUtils.getMovieFO() val movie = mapper.mapBack(movieFO) MovieUtils.assertMovieDeepEquals(movieFO, movie) } }
mit
b08205561bd330a663737070b2ed4545
25.490566
72
0.727208
4.093294
false
true
false
false
f-droid/fdroidclient
libs/index/src/androidAndroidTest/kotlin/org/fdroid/index/v1/IndexV1CreatorTest.kt
1
1429
package org.fdroid.index.v1 import android.content.Context import android.content.pm.ApplicationInfo.FLAG_SYSTEM import androidx.test.core.app.ApplicationProvider import androidx.test.ext.junit.runners.AndroidJUnit4 import org.fdroid.index.IndexParser import org.fdroid.test.TestDataMinV1 import org.junit.Rule import org.junit.rules.TemporaryFolder import org.junit.runner.RunWith import java.io.File import kotlin.random.Random import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertTrue @RunWith(AndroidJUnit4::class) internal class IndexV1CreatorTest { @get:Rule var tmpFolder: TemporaryFolder = TemporaryFolder() private val context: Context = ApplicationProvider.getApplicationContext() @Test fun test() { val repoDir = tmpFolder.newFolder() val repo = TestDataMinV1.repo val packageNames = context.packageManager.getInstalledPackages(0).filter { (it.applicationInfo.flags and FLAG_SYSTEM == 0) and (Random.nextInt(0, 3) == 0) }.map { it.packageName }.toSet() val indexCreator = IndexV1Creator(context.packageManager, repoDir, packageNames, repo) val indexV1 = indexCreator.createRepo() val indexFile = File(repoDir, JSON_FILE_NAME) assertTrue(indexFile.exists()) val indexStr = indexFile.readBytes().decodeToString() assertEquals(indexV1, IndexParser.parseV1(indexStr)) } }
gpl-3.0
68d236884c7dc810b55e7814d7887990
33.853659
94
0.746676
4.106322
false
true
false
false
shaeberling/euler
kotlin/src/com/s13g/aoc/aoc2019/Day11.kt
1
2051
package com.s13g.aoc.aoc2019 import com.s13g.aoc.Result import com.s13g.aoc.Solver import java.lang.RuntimeException /** https://adventofcode.com/2019/day/11 */ class Day11 : Solver { override fun solve(lines: List<String>): Result { val program = lines[0].split(",").map { it.toLong() }.toMutableList() program.addAll(Array(1000) { 0L }) val robotA = Robot(VM19(program, mutableListOf())) robotA.run() val robotB = Robot(VM19(program, mutableListOf())) robotB.map[XY(0, 0)] = 1 robotB.run() return Result("${robotA.numPanelsPainted()}", robotB.printPanel()) } private class Robot(val vm: VM19) : VM19.VmIO { var dir = 0 var pos = XY(0, 0) val map = hashMapOf<XY, Long>() var outIsColor = true init { vm.vmIo = this } fun run() { while (true) { if (!vm.step()) { return } } } fun numPanelsPainted() = map.size override fun onInput() = map[pos] ?: 0L override fun onOutput(out: Long) { if (outIsColor) { map[pos] = out } else { changeDir(out) } outIsColor = !outIsColor } private fun changeDir(i: Long) { // 0 --> turn left, 1 --> turn right dir += if (i == 0L) -1 else 1 if (dir < 0) dir += 4 dir %= 4 pos = pos.add(when (dir) { 0 -> XY(0, -1) 1 -> XY(1, 0) 2 -> XY(0, 1) 3 -> XY(-1, 0) else -> throw RuntimeException("Unknown direction") }) } fun printPanel(): String { val minX = map.keys.map { it.x }.min()!! val maxX = map.keys.map { it.x }.max()!! val minY = map.keys.map { it.y }.min()!! val maxY = map.keys.map { it.y }.max()!! var result = "\n" for (y in minY..maxY) { for (x in minX..maxX) { result += if ((map[XY(x, y)] ?: 0L) == 1L) "#" else "." } result += "\n" } return result } } private data class XY(var x: Int, var y: Int) { fun add(b: XY) = XY(x + b.x, y + b.y) } }
apache-2.0
65640c488c2015d2b9f51d82fe6e80aa
22.586207
73
0.517796
3.21978
false
false
false
false
Ekito/koin
koin-projects/examples/androidx-compose-jetnews/src/main/java/com/example/jetnews/ui/home/HomeScreen.kt
1
15354
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.jetnews.ui.home import androidx.compose.foundation.Box import androidx.compose.foundation.Icon import androidx.compose.foundation.ScrollableColumn import androidx.compose.foundation.ScrollableRow import androidx.compose.foundation.Text import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.preferredSize import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.CircularProgressIndicator import androidx.compose.material.Divider import androidx.compose.material.DrawerValue import androidx.compose.material.EmphasisAmbient import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.material.IconButton import androidx.compose.material.MaterialTheme import androidx.compose.material.ProvideEmphasis import androidx.compose.material.Scaffold import androidx.compose.material.ScaffoldState import androidx.compose.material.SnackbarResult import androidx.compose.material.Surface import androidx.compose.material.TextButton import androidx.compose.material.TopAppBar import androidx.compose.material.rememberDrawerState import androidx.compose.material.rememberScaffoldState import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.launchInComposition import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.ContextAmbient import androidx.compose.ui.res.stringResource import androidx.compose.ui.res.vectorResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.ui.tooling.preview.Preview import com.example.jetnews.R import com.example.jetnews.data.Result import com.example.jetnews.data.posts.PostsRepository import com.example.jetnews.data.posts.impl.BlockingFakePostsRepository import com.example.jetnews.model.Post import com.example.jetnews.ui.AppDrawer import com.example.jetnews.ui.Screen import com.example.jetnews.ui.SwipeToRefreshLayout import com.example.jetnews.ui.ThemedPreview import com.example.jetnews.ui.state.UiState import com.example.jetnews.utils.launchUiStateProducer import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking /** * Stateful HomeScreen which manages state using [launchUiStateProducer] * * @param navigateTo (event) request navigation to [Screen] * @param postsRepository data source for this screen * @param scaffoldState (state) state for the [Scaffold] component on this screen */ @Composable fun HomeScreen( navigateTo: (Screen) -> Unit, postsRepository: PostsRepository, scaffoldState: ScaffoldState = rememberScaffoldState() ) { val (postUiState, refreshPost, clearError) = launchUiStateProducer(postsRepository) { getPosts() } // [collectAsState] will automatically collect a Flow<T> and return a State<T> object that // updates whenever the Flow emits a value. Collection is cancelled when [collectAsState] is // removed from the composition tree. val favorites by postsRepository.observeFavorites().collectAsState(setOf()) // Returns a [CoroutineScope] that is scoped to the lifecycle of [HomeScreen]. When this // screen is removed from composition, the scope will be cancelled. val coroutineScope = rememberCoroutineScope() HomeScreen( posts = postUiState.value, favorites = favorites, onToggleFavorite = { coroutineScope.launch { postsRepository.toggleFavorite(it) } }, onRefreshPosts = refreshPost, onErrorDismiss = clearError, navigateTo = navigateTo, scaffoldState = scaffoldState ) } /** * Responsible for displaying the Home Screen of this application. * * Stateless composable is not coupled to any specific state management. * * @param posts (state) the data to show on the screen * @param favorites (state) favorite posts * @param onToggleFavorite (event) toggles favorite for a post * @param onRefreshPosts (event) request a refresh of posts * @param onErrorDismiss (event) request the current error be dismissed * @param navigateTo (event) request navigation to [Screen] */ @OptIn(ExperimentalMaterialApi::class) @Composable fun HomeScreen( posts: UiState<List<Post>>, favorites: Set<String>, onToggleFavorite: (String) -> Unit, onRefreshPosts: () -> Unit, onErrorDismiss: () -> Unit, navigateTo: (Screen) -> Unit, scaffoldState: ScaffoldState ) { if (posts.hasError) { val errorMessage = stringResource(id = R.string.load_error) val retryMessage = stringResource(id = R.string.retry) // Show snackbar using a coroutine, when the coroutine is cancelled the snackbar will // automatically dismiss. This coroutine will cancel whenever posts.hasError changes, and // only start when posts.hasError is true (due to the above if-check). launchInComposition(posts.hasError) { val snackbarResult = scaffoldState.snackbarHostState.showSnackbar( message = errorMessage, actionLabel = retryMessage ) when (snackbarResult) { SnackbarResult.ActionPerformed -> onRefreshPosts() SnackbarResult.Dismissed -> onErrorDismiss() } } } Scaffold( scaffoldState = scaffoldState, drawerContent = { AppDrawer( currentScreen = Screen.Home, closeDrawer = { scaffoldState.drawerState.close() }, navigateTo = navigateTo ) }, topBar = { val title = stringResource(id = R.string.app_name) TopAppBar( title = { Text(text = title) }, navigationIcon = { IconButton(onClick = { scaffoldState.drawerState.open() }) { Icon(vectorResource(R.drawable.ic_jetnews_logo)) } } ) }, bodyContent = { innerPadding -> val modifier = Modifier.padding(innerPadding) LoadingContent( empty = posts.initialLoad, emptyContent = { FullScreenLoading() }, loading = posts.loading, onRefresh = onRefreshPosts, content = { HomeScreenErrorAndContent( posts = posts, onRefresh = { onRefreshPosts() }, navigateTo = navigateTo, favorites = favorites, onToggleFavorite = onToggleFavorite, modifier = modifier ) } ) } ) } /** * Display an initial empty state or swipe to refresh content. * * @param empty (state) when true, display [emptyContent] * @param emptyContent (slot) the content to display for the empty state * @param loading (state) when true, display a loading spinner over [content] * @param onRefresh (event) event to request refresh * @param content (slot) the main content to show */ @Composable private fun LoadingContent( empty: Boolean, emptyContent: @Composable () -> Unit, loading: Boolean, onRefresh: () -> Unit, content: @Composable () -> Unit ) { if (empty) { emptyContent() } else { SwipeToRefreshLayout( refreshingState = loading, onRefresh = onRefresh, refreshIndicator = { Surface(elevation = 10.dp, shape = CircleShape) { CircularProgressIndicator( modifier = Modifier .preferredSize(36.dp) .padding(4.dp) ) } }, content = content, ) } } /** * Responsible for displaying any error conditions around [PostList]. * * @param posts (state) list of posts and error state to display * @param onRefresh (event) request to refresh data * @param navigateTo (event) request navigation to [Screen] * @param favorites (state) all favorites * @param onToggleFavorite (event) request a single favorite be toggled * @param modifier modifier for root element */ @Composable private fun HomeScreenErrorAndContent( posts: UiState<List<Post>>, onRefresh: () -> Unit, navigateTo: (Screen) -> Unit, favorites: Set<String>, onToggleFavorite: (String) -> Unit, modifier: Modifier = Modifier ) { if (posts.data != null) { PostList(posts.data, navigateTo, favorites, onToggleFavorite, modifier) } else if (!posts.hasError) { // if there are no posts, and no error, let the user refresh manually TextButton(onClick = onRefresh, modifier.fillMaxSize()) { Text("Tap to load content", textAlign = TextAlign.Center) } } } /** * Display a list of posts. * * When a post is clicked on, [navigateTo] will be called to navigate to the detail screen for that * post. * * @param posts (state) the list to display * @param navigateTo (event) request navigation to [Screen] * @param modifier modifier for the root element */ @Composable private fun PostList( posts: List<Post>, navigateTo: (Screen) -> Unit, favorites: Set<String>, onToggleFavorite: (String) -> Unit, modifier: Modifier = Modifier ) { val postTop = posts[3] val postsSimple = posts.subList(0, 2) val postsPopular = posts.subList(2, 7) val postsHistory = posts.subList(7, 10) ScrollableColumn(modifier = modifier) { PostListTopSection(postTop, navigateTo) PostListSimpleSection(postsSimple, navigateTo, favorites, onToggleFavorite) PostListPopularSection(postsPopular, navigateTo) PostListHistorySection(postsHistory, navigateTo) } } /** * Full screen circular progress indicator */ @Composable private fun FullScreenLoading() { Box(modifier = Modifier.fillMaxSize().wrapContentSize(Alignment.Center)) { CircularProgressIndicator() } } /** * Top section of [PostList] * * @param post (state) highlighted post to display * @param navigateTo (event) request navigation to [Screen] */ @Composable private fun PostListTopSection(post: Post, navigateTo: (Screen) -> Unit) { ProvideEmphasis(EmphasisAmbient.current.high) { Text( modifier = Modifier.padding(start = 16.dp, top = 16.dp, end = 16.dp), text = "Top stories for you", style = MaterialTheme.typography.subtitle1 ) } PostCardTop( post = post, modifier = Modifier.clickable(onClick = { navigateTo(Screen.Article(post.id)) }) ) PostListDivider() } /** * Full-width list items for [PostList] * * @param posts (state) to display * @param navigateTo (event) request navigation to [Screen] */ @Composable private fun PostListSimpleSection( posts: List<Post>, navigateTo: (Screen) -> Unit, favorites: Set<String>, onToggleFavorite: (String) -> Unit ) { Column { posts.forEach { post -> PostCardSimple( post = post, navigateTo = navigateTo, isFavorite = favorites.contains(post.id), onToggleFavorite = { onToggleFavorite(post.id) } ) PostListDivider() } } } /** * Horizontal scrolling cards for [PostList] * * @param posts (state) to display * @param navigateTo (event) request navigation to [Screen] */ @Composable private fun PostListPopularSection( posts: List<Post>, navigateTo: (Screen) -> Unit ) { Column { ProvideEmphasis(EmphasisAmbient.current.high) { Text( modifier = Modifier.padding(16.dp), text = "Popular on Jetnews", style = MaterialTheme.typography.subtitle1 ) } ScrollableRow(modifier = Modifier.padding(end = 16.dp)) { posts.forEach { post -> PostCardPopular(post, navigateTo, Modifier.padding(start = 16.dp, bottom = 16.dp)) } } PostListDivider() } } /** * Full-width list items that display "based on your history" for [PostList] * * @param posts (state) to display * @param navigateTo (event) request navigation to [Screen] */ @Composable private fun PostListHistorySection( posts: List<Post>, navigateTo: (Screen) -> Unit ) { Column { posts.forEach { post -> PostCardHistory(post, navigateTo) PostListDivider() } } } /** * Full-width divider with padding for [PostList] */ @Composable private fun PostListDivider() { Divider( modifier = Modifier.padding(horizontal = 14.dp), color = MaterialTheme.colors.onSurface.copy(alpha = 0.08f) ) } @Preview("Home screen body") @Composable fun PreviewHomeScreenBody() { ThemedPreview { val posts = loadFakePosts() PostList(posts, { }, setOf(), {}) } } @Preview("Home screen, open drawer") @Composable private fun PreviewDrawerOpen() { ThemedPreview { val scaffoldState = rememberScaffoldState( drawerState = rememberDrawerState(DrawerValue.Open) ) HomeScreen( postsRepository = BlockingFakePostsRepository(ContextAmbient.current), scaffoldState = scaffoldState, navigateTo = { } ) } } @Preview("Home screen dark theme") @Composable fun PreviewHomeScreenBodyDark() { ThemedPreview(darkTheme = true) { val posts = loadFakePosts() PostList(posts, {}, setOf(), {}) } } @Composable private fun loadFakePosts(): List<Post> { val context = ContextAmbient.current val posts = runBlocking { BlockingFakePostsRepository(context).getPosts() } return (posts as Result.Success).data } @Preview("Home screen, open drawer dark theme") @Composable private fun PreviewDrawerOpenDark() { ThemedPreview(darkTheme = true) { val scaffoldState = rememberScaffoldState( drawerState = rememberDrawerState(DrawerValue.Open) ) HomeScreen( postsRepository = BlockingFakePostsRepository(ContextAmbient.current), scaffoldState = scaffoldState, navigateTo = { } ) } }
apache-2.0
199c1c215e5a43dee4193be048f5fcec
31.948498
99
0.666211
4.704044
false
false
false
false
beyama/winter
winter-compiler/src/main/java/io/jentz/winter/compiler/model/FactoryModel.kt
1
9552
package io.jentz.winter.compiler.model import com.squareup.kotlinpoet.ClassName import com.squareup.kotlinpoet.TypeName import com.squareup.kotlinpoet.asClassName import com.squareup.kotlinpoet.asTypeName import com.squareup.kotlinpoet.metadata.* import io.jentz.winter.compiler.* import io.jentz.winter.inject.EagerSingleton import io.jentz.winter.inject.FactoryType import io.jentz.winter.inject.InjectConstructor import io.jentz.winter.inject.Prototype import javax.inject.Inject import javax.inject.Scope import javax.lang.model.element.Element import javax.lang.model.element.ExecutableElement import javax.lang.model.element.TypeElement import javax.lang.model.element.VariableElement import javax.lang.model.util.ElementFilter import io.jentz.winter.Scope as WinterScope @KotlinPoetMetadataPreview class FactoryModel private constructor( val originatingElement: Element, val typeName: ClassName, val factoryTypeName: ClassName, val scopeAnnotationName: ClassName?, val scope: WinterScope, val isEagerSingleton: Boolean, val qualifier: String?, val parameters: List<Parameter>, val generatedClassName: ClassName, val injectorModel: InjectorModel? ) { data class Parameter(val typeName: TypeName, val isNullable: Boolean, val qualifier: String?) companion object { fun forInjectAnnotatedConstructor(constructorElement: ExecutableElement): FactoryModel { val typeElement = constructorElement.enclosingElement as TypeElement validateType(typeElement) validateConstructor(constructorElement) val scopeAnnotationName = getScopeAnnotationName(typeElement) val winterScopeAnnotation = getWinterScopeAnnotation(typeElement) return FactoryModel( originatingElement = constructorElement, typeName = typeElement.asClassName(), factoryTypeName = getFactoryTypeName(typeElement), scopeAnnotationName = scopeAnnotationName, scope = getWinterScope(winterScopeAnnotation, scopeAnnotationName), isEagerSingleton = winterScopeAnnotation is EagerSingleton, qualifier = typeElement.qualifier, parameters = buildParameters(constructorElement), generatedClassName = getGeneratedClassName(typeElement), injectorModel = getInjectorModel(typeElement) ) } fun forInjectConstructorAnnotatedClass(typeElement: TypeElement): FactoryModel { validateType(typeElement) val constructorElements = ElementFilter .constructorsIn(typeElement.enclosedElements) .filterNot { it.isPrivate || it.isProtected } require(constructorElements.size == 1) { "Class `${typeElement.qualifiedName}` is annotated with InjectConstructor " + "and therefore must have exactly one non-private constructor." } val constructorElement = constructorElements.first() require(constructorElement.getAnnotation(Inject::class.java) == null) { "Class `${typeElement.qualifiedName}` is annotated with InjectConstructor " + "and therefore must not have a constructor with Inject annotation." } val scopeAnnotationName = getScopeAnnotationName(typeElement) val winterScopeAnnotation = getWinterScopeAnnotation(typeElement) return FactoryModel( originatingElement = typeElement, typeName = typeElement.asClassName(), factoryTypeName = getFactoryTypeName(typeElement), scopeAnnotationName = scopeAnnotationName, scope = getWinterScope(winterScopeAnnotation, scopeAnnotationName), isEagerSingleton = winterScopeAnnotation is EagerSingleton, qualifier = typeElement.qualifier, parameters = buildParameters(constructorElement), generatedClassName = getGeneratedClassName(typeElement), injectorModel = getInjectorModel(typeElement) ) } private fun validateType(typeElement: TypeElement) { require(!(typeElement.isInnerClass && !typeElement.isStatic)) { "Cannot inject a non-static inner class." } require(!typeElement.isPrivate) { "Cannot inject a private class." } require(!typeElement.isAbstract) { "Cannot inject a abstract class." } } private fun validateConstructor(constructorElement: ExecutableElement) { require(!constructorElement.isPrivate) { "Cannot inject a private constructor." } } private fun getFactoryTypeName(typeElement: TypeElement): ClassName { val typeUtils: TypeUtils = DI.graph.instance() val typeName: ClassName = typeElement.asClassName() val injectAnnotationFactoryType = typeUtils .getFactoryTypeFromAnnotation(typeElement, InjectConstructor::class) val factoryTypeAnnotationFactoryType = typeUtils .getFactoryTypeFromAnnotation(typeElement, FactoryType::class) require(!(injectAnnotationFactoryType != null && factoryTypeAnnotationFactoryType != null)) { "Factory type can be declared via InjectConstructor or FactoryType annotation but not both." } return when { injectAnnotationFactoryType != null -> injectAnnotationFactoryType.asClassName() factoryTypeAnnotationFactoryType != null -> factoryTypeAnnotationFactoryType.asClassName() else -> typeName } } private fun getScopeAnnotationName(typeElement: TypeElement): ClassName? { val scopeAnnotations = typeElement.annotationMirrors.map { it.annotationType.asElement() as TypeElement }.filter { it.getAnnotation(Scope::class.java) != null } require(scopeAnnotations.size <= 1) { val scopesString = scopeAnnotations.joinToString(", ") { it.qualifiedName.toString() } "Multiple scope annotations found but only one is allowed. ($scopesString})" } return scopeAnnotations.firstOrNull() ?.asClassName() ?.let { if (it == SINGLETON_ANNOTATION_CLASS_NAME) APPLICATION_SCOPE_CLASS_NAME else it } } private fun getWinterScope( winterScopeAnnotation: Annotation?, scopeAnnotationName: ClassName? ): WinterScope = when { winterScopeAnnotation is Prototype -> WinterScope.Prototype winterScopeAnnotation is EagerSingleton -> WinterScope.Singleton scopeAnnotationName == null -> WinterScope.Prototype else -> WinterScope.Singleton } private fun getGeneratedClassName(typeElement: TypeElement): ClassName { val typeName = typeElement.asClassName() return ClassName( typeName.packageName, "${typeName.simpleNames.joinToString("_")}_WinterFactory" ) } private fun getInjectorModel(typeElement: TypeElement): InjectorModel? = typeElement .selfAndSuperclasses .firstOrNull { it.enclosedElements.any(Element::isInjectFieldOrMethod) } ?.let { InjectorModel(it, null, null) } private fun getWinterScopeAnnotation(typeElement: TypeElement): Annotation? { val eagerSingleton: EagerSingleton? = typeElement.getAnnotation(EagerSingleton::class.java) val prototype: Prototype? = typeElement.getAnnotation(Prototype::class.java) require(!(eagerSingleton != null && prototype != null)) { "Class can either be annotated with EagerSingleton or Prototype but not both." } return eagerSingleton ?: prototype } private fun buildParameters(constructorElement: ExecutableElement): List<Parameter> { return mergeJavaAndKotlinParameters(constructorElement) .map { (javaParam, kotlinParam) -> Parameter( typeName = kotlinParam?.type?.asTypeName() ?: javaParam.asType().asTypeName().kotlinTypeName, isNullable = kotlinParam?.type?.isNullable ?: javaParam.isNullable, qualifier = javaParam.qualifier ) } } private fun mergeJavaAndKotlinParameters( constructorElement: ExecutableElement ): List<Pair<VariableElement, ImmutableKmValueParameter?>> { val typeElement = constructorElement.enclosingElement as TypeElement val kmConstructors = runCatching { typeElement.toImmutableKmClass().constructors }.getOrElse { emptyList() } val jvmSignature = constructorElement.jvmSignature() val kmConstructor = kmConstructors.find { it.signature?.desc == jvmSignature } return if (kmConstructor != null) { constructorElement.parameters.zip(kmConstructor.valueParameters) } else { constructorElement.parameters.map { it to null } } } } }
apache-2.0
61abef2453091786ccb23bb65245e56e
41.079295
108
0.647299
5.85653
false
false
false
false
canou/Simple-Commons
commons/src/main/kotlin/com/simplemobiletools/commons/extensions/String.kt
1
27391
package com.simplemobiletools.commons.extensions import android.content.Context import java.util.* fun String.getFilenameFromPath() = substring(lastIndexOf("/") + 1) fun String.getFilenameExtension() = substring(lastIndexOf(".") + 1) fun String.getBasePath(context: Context): String { return if (startsWith(context.internalStoragePath)) context.internalStoragePath else if (!context.sdCardPath.isEmpty() && startsWith(context.sdCardPath)) context.sdCardPath else "/" } fun String.isAValidFilename(): Boolean { val ILLEGAL_CHARACTERS = charArrayOf('/', '\n', '\r', '\t', '\u0000', '`', '?', '*', '\\', '<', '>', '|', '\"', ':') ILLEGAL_CHARACTERS.forEach { if (contains(it)) return false } return true } val String.photoExtensions: Array<String> get() = arrayOf(".jpg", ".png", ".jpeg", ".bmp", ".webp") val String.videoExtensions: Array<String> get() = arrayOf(".mp4", ".mkv", ".webm", ".avi", ".3gp", ".mov", ".m4v") fun String.isImageVideoGif() = isImageFast() || isVideoFast() || isGif() fun String.isGif() = endsWith(".gif", true) fun String.isPng() = endsWith(".png", true) // fast extension check, not guaranteed to be accurate fun String.isVideoFast() = videoExtensions.any { endsWith(it, true) } // fast extension check, not guaranteed to be accurate fun String.isImageFast() = photoExtensions.any { endsWith(it, true) } fun String.areDigitsOnly() = matches(Regex("[0-9]+")) fun String.getMimeTypeFromPath(): String { val typesMap = HashMap<String, String>().apply { put("323", "text/h323") put("3g2", "video/3gpp2") put("3gp", "video/3gpp") put("3gp2", "video/3gpp2") put("3gpp", "video/3gpp") put("7z", "application/x-7z-compressed") put("aa", "audio/audible") put("AAC", "audio/aac") put("aaf", "application/octet-stream") put("aax", "audio/vnd.audible.aax") put("ac3", "audio/ac3") put("aca", "application/octet-stream") put("accda", "application/msaccess.addin") put("accdb", "application/msaccess") put("accdc", "application/msaccess.cab") put("accde", "application/msaccess") put("accdr", "application/msaccess.runtime") put("accdt", "application/msaccess") put("accdw", "application/msaccess.webapplication") put("accft", "application/msaccess.ftemplate") put("acx", "application/internet-property-stream") put("AddIn", "text/xml") put("ade", "application/msaccess") put("adobebridge", "application/x-bridge-url") put("adp", "application/msaccess") put("ADT", "audio/vnd.dlna.adts") put("ADTS", "audio/aac") put("afm", "application/octet-stream") put("ai", "application/postscript") put("aif", "audio/aiff") put("aifc", "audio/aiff") put("aiff", "audio/aiff") put("air", "application/vnd.adobe.air-application-installer-package+zip") put("amc", "application/mpeg") put("anx", "application/annodex") put("apk", "application/vnd.android.package-archive") put("application", "application/x-ms-application") put("art", "image/x-jg") put("asa", "application/xml") put("asax", "application/xml") put("ascx", "application/xml") put("asd", "application/octet-stream") put("asf", "video/x-ms-asf") put("ashx", "application/xml") put("asi", "application/octet-stream") put("asm", "text/plain") put("asmx", "application/xml") put("aspx", "application/xml") put("asr", "video/x-ms-asf") put("asx", "video/x-ms-asf") put("atom", "application/atom+xml") put("au", "audio/basic") put("avi", "video/x-msvideo") put("axa", "audio/annodex") put("axs", "application/olescript") put("axv", "video/annodex") put("bas", "text/plain") put("bcpio", "application/x-bcpio") put("bin", "application/octet-stream") put("bmp", "image/bmp") put("c", "text/plain") put("cab", "application/octet-stream") put("caf", "audio/x-caf") put("calx", "application/vnd.ms-office.calx") put("cat", "application/vnd.ms-pki.seccat") put("cc", "text/plain") put("cd", "text/plain") put("cdda", "audio/aiff") put("cdf", "application/x-cdf") put("cer", "application/x-x509-ca-cert") put("cfg", "text/plain") put("chm", "application/octet-stream") put("class", "application/x-java-applet") put("clp", "application/x-msclip") put("cmd", "text/plain") put("cmx", "image/x-cmx") put("cnf", "text/plain") put("cod", "image/cis-cod") put("config", "application/xml") put("contact", "text/x-ms-contact") put("coverage", "application/xml") put("cpio", "application/x-cpio") put("cpp", "text/plain") put("crd", "application/x-mscardfile") put("crl", "application/pkix-crl") put("crt", "application/x-x509-ca-cert") put("cs", "text/plain") put("csdproj", "text/plain") put("csh", "application/x-csh") put("csproj", "text/plain") put("css", "text/css") put("csv", "text/csv") put("cur", "application/octet-stream") put("cxx", "text/plain") put("dat", "application/octet-stream") put("datasource", "application/xml") put("dbproj", "text/plain") put("dcr", "application/x-director") put("def", "text/plain") put("deploy", "application/octet-stream") put("der", "application/x-x509-ca-cert") put("dgml", "application/xml") put("dib", "image/bmp") put("dif", "video/x-dv") put("dir", "application/x-director") put("disco", "text/xml") put("divx", "video/divx") put("dll", "application/x-msdownload") put("dll.config", "text/xml") put("dlm", "text/dlm") put("doc", "application/msword") put("docm", "application/vnd.ms-word.document.macroEnabled.12") put("docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document") put("dot", "application/msword") put("dotm", "application/vnd.ms-word.template.macroEnabled.12") put("dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template") put("dsp", "application/octet-stream") put("dsw", "text/plain") put("dtd", "text/xml") put("dtsConfig", "text/xml") put("dv", "video/x-dv") put("dvi", "application/x-dvi") put("dwf", "drawing/x-dwf") put("dwp", "application/octet-stream") put("dxr", "application/x-director") put("eml", "message/rfc822") put("emz", "application/octet-stream") put("eot", "application/vnd.ms-fontobject") put("eps", "application/postscript") put("etl", "application/etl") put("etx", "text/x-setext") put("evy", "application/envoy") put("exe", "application/octet-stream") put("exe.config", "text/xml") put("fdf", "application/vnd.fdf") put("fif", "application/fractals") put("filters", "application/xml") put("fla", "application/octet-stream") put("flac", "audio/flac") put("flr", "x-world/x-vrml") put("flv", "video/x-flv") put("fsscript", "application/fsharp-script") put("fsx", "application/fsharp-script") put("generictest", "application/xml") put("gif", "image/gif") put("group", "text/x-ms-group") put("gsm", "audio/x-gsm") put("gtar", "application/x-gtar") put("gz", "application/x-gzip") put("h", "text/plain") put("hdf", "application/x-hdf") put("hdml", "text/x-hdml") put("hhc", "application/x-oleobject") put("hhk", "application/octet-stream") put("hhp", "application/octet-stream") put("hlp", "application/winhlp") put("hpp", "text/plain") put("hqx", "application/mac-binhex40") put("hta", "application/hta") put("htc", "text/x-component") put("htm", "text/html") put("html", "text/html") put("htt", "text/webviewhtml") put("hxa", "application/xml") put("hxc", "application/xml") put("hxd", "application/octet-stream") put("hxe", "application/xml") put("hxf", "application/xml") put("hxh", "application/octet-stream") put("hxi", "application/octet-stream") put("hxk", "application/xml") put("hxq", "application/octet-stream") put("hxr", "application/octet-stream") put("hxs", "application/octet-stream") put("hxt", "text/html") put("hxv", "application/xml") put("hxw", "application/octet-stream") put("hxx", "text/plain") put("i", "text/plain") put("ico", "image/x-icon") put("ics", "application/octet-stream") put("idl", "text/plain") put("ief", "image/ief") put("iii", "application/x-iphone") put("inc", "text/plain") put("inf", "application/octet-stream") put("ini", "text/plain") put("inl", "text/plain") put("ins", "application/x-internet-signup") put("ipa", "application/x-itunes-ipa") put("ipg", "application/x-itunes-ipg") put("ipproj", "text/plain") put("ipsw", "application/x-itunes-ipsw") put("iqy", "text/x-ms-iqy") put("isp", "application/x-internet-signup") put("ite", "application/x-itunes-ite") put("itlp", "application/x-itunes-itlp") put("itms", "application/x-itunes-itms") put("itpc", "application/x-itunes-itpc") put("IVF", "video/x-ivf") put("jar", "application/java-archive") put("java", "application/octet-stream") put("jck", "application/liquidmotion") put("jcz", "application/liquidmotion") put("jfif", "image/pjpeg") put("jnlp", "application/x-java-jnlp-file") put("jpb", "application/octet-stream") put("jpe", "image/jpeg") put("jpeg", "image/jpeg") put("jpg", "image/jpeg") put("js", "application/javascript") put("json", "application/json") put("jsx", "text/jscript") put("jsxbin", "text/plain") put("latex", "application/x-latex") put("library-ms", "application/windows-library+xml") put("lit", "application/x-ms-reader") put("loadtest", "application/xml") put("lpk", "application/octet-stream") put("lsf", "video/x-la-asf") put("lst", "text/plain") put("lsx", "video/x-la-asf") put("lzh", "application/octet-stream") put("m13", "application/x-msmediaview") put("m14", "application/x-msmediaview") put("m1v", "video/mpeg") put("m2t", "video/vnd.dlna.mpeg-tts") put("m2ts", "video/vnd.dlna.mpeg-tts") put("m2v", "video/mpeg") put("m3u", "audio/x-mpegurl") put("m3u8", "audio/x-mpegurl") put("m4a", "audio/m4a") put("m4b", "audio/m4b") put("m4p", "audio/m4p") put("m4r", "audio/x-m4r") put("m4v", "video/x-m4v") put("mac", "image/x-macpaint") put("mak", "text/plain") put("man", "application/x-troff-man") put("manifest", "application/x-ms-manifest") put("map", "text/plain") put("master", "application/xml") put("mda", "application/msaccess") put("mdb", "application/x-msaccess") put("mde", "application/msaccess") put("mdp", "application/octet-stream") put("me", "application/x-troff-me") put("mfp", "application/x-shockwave-flash") put("mht", "message/rfc822") put("mhtml", "message/rfc822") put("mid", "audio/mid") put("midi", "audio/mid") put("mix", "application/octet-stream") put("mk", "text/plain") put("mmf", "application/x-smaf") put("mno", "text/xml") put("mny", "application/x-msmoney") put("mod", "video/mpeg") put("mov", "video/quicktime") put("movie", "video/x-sgi-movie") put("mp2", "video/mpeg") put("mp2v", "video/mpeg") put("mp3", "audio/mpeg") put("mp4", "video/mp4") put("mp4v", "video/mp4") put("mpa", "video/mpeg") put("mpe", "video/mpeg") put("mpeg", "video/mpeg") put("mpf", "application/vnd.ms-mediapackage") put("mpg", "video/mpeg") put("mpp", "application/vnd.ms-project") put("mpv2", "video/mpeg") put("mqv", "video/quicktime") put("ms", "application/x-troff-ms") put("msi", "application/octet-stream") put("mso", "application/octet-stream") put("mts", "video/vnd.dlna.mpeg-tts") put("mtx", "application/xml") put("mvb", "application/x-msmediaview") put("mvc", "application/x-miva-compiled") put("mxp", "application/x-mmxp") put("nc", "application/x-netcdf") put("nsc", "video/x-ms-asf") put("nws", "message/rfc822") put("ocx", "application/octet-stream") put("oda", "application/oda") put("odb", "application/vnd.oasis.opendocument.database") put("odc", "application/vnd.oasis.opendocument.chart") put("odf", "application/vnd.oasis.opendocument.formula") put("odg", "application/vnd.oasis.opendocument.graphics") put("odh", "text/plain") put("odi", "application/vnd.oasis.opendocument.image") put("odl", "text/plain") put("odm", "application/vnd.oasis.opendocument.text-master") put("odp", "application/vnd.oasis.opendocument.presentation") put("ods", "application/vnd.oasis.opendocument.spreadsheet") put("odt", "application/vnd.oasis.opendocument.text") put("oga", "audio/ogg") put("ogg", "audio/ogg") put("ogv", "video/ogg") put("ogx", "application/ogg") put("one", "application/onenote") put("onea", "application/onenote") put("onepkg", "application/onenote") put("onetmp", "application/onenote") put("onetoc", "application/onenote") put("onetoc2", "application/onenote") put("opus", "audio/ogg") put("orderedtest", "application/xml") put("osdx", "application/opensearchdescription+xml") put("otf", "application/font-sfnt") put("otg", "application/vnd.oasis.opendocument.graphics-template") put("oth", "application/vnd.oasis.opendocument.text-web") put("otp", "application/vnd.oasis.opendocument.presentation-template") put("ots", "application/vnd.oasis.opendocument.spreadsheet-template") put("ott", "application/vnd.oasis.opendocument.text-template") put("oxt", "application/vnd.openofficeorg.extension") put("p10", "application/pkcs10") put("p12", "application/x-pkcs12") put("p7b", "application/x-pkcs7-certificates") put("p7c", "application/pkcs7-mime") put("p7m", "application/pkcs7-mime") put("p7r", "application/x-pkcs7-certreqresp") put("p7s", "application/pkcs7-signature") put("pbm", "image/x-portable-bitmap") put("pcast", "application/x-podcast") put("pct", "image/pict") put("pcx", "application/octet-stream") put("pcz", "application/octet-stream") put("pdf", "application/pdf") put("pfb", "application/octet-stream") put("pfm", "application/octet-stream") put("pfx", "application/x-pkcs12") put("pgm", "image/x-portable-graymap") put("pic", "image/pict") put("pict", "image/pict") put("pkgdef", "text/plain") put("pkgundef", "text/plain") put("pko", "application/vnd.ms-pki.pko") put("pls", "audio/scpls") put("pma", "application/x-perfmon") put("pmc", "application/x-perfmon") put("pml", "application/x-perfmon") put("pmr", "application/x-perfmon") put("pmw", "application/x-perfmon") put("png", "image/png") put("pnm", "image/x-portable-anymap") put("pnt", "image/x-macpaint") put("pntg", "image/x-macpaint") put("pnz", "image/png") put("pot", "application/vnd.ms-powerpoint") put("potm", "application/vnd.ms-powerpoint.template.macroEnabled.12") put("potx", "application/vnd.openxmlformats-officedocument.presentationml.template") put("ppa", "application/vnd.ms-powerpoint") put("ppam", "application/vnd.ms-powerpoint.addin.macroEnabled.12") put("ppm", "image/x-portable-pixmap") put("pps", "application/vnd.ms-powerpoint") put("ppsm", "application/vnd.ms-powerpoint.slideshow.macroEnabled.12") put("ppsx", "application/vnd.openxmlformats-officedocument.presentationml.slideshow") put("ppt", "application/vnd.ms-powerpoint") put("pptm", "application/vnd.ms-powerpoint.presentation.macroEnabled.12") put("pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation") put("prf", "application/pics-rules") put("prm", "application/octet-stream") put("prx", "application/octet-stream") put("ps", "application/postscript") put("psc1", "application/PowerShell") put("psd", "application/octet-stream") put("psess", "application/xml") put("psm", "application/octet-stream") put("psp", "application/octet-stream") put("pub", "application/x-mspublisher") put("pwz", "application/vnd.ms-powerpoint") put("qht", "text/x-html-insertion") put("qhtm", "text/x-html-insertion") put("qt", "video/quicktime") put("qti", "image/x-quicktime") put("qtif", "image/x-quicktime") put("qtl", "application/x-quicktimeplayer") put("qxd", "application/octet-stream") put("ra", "audio/x-pn-realaudio") put("ram", "audio/x-pn-realaudio") put("rar", "application/x-rar-compressed") put("ras", "image/x-cmu-raster") put("rat", "application/rat-file") put("rc", "text/plain") put("rc2", "text/plain") put("rct", "text/plain") put("rdlc", "application/xml") put("reg", "text/plain") put("resx", "application/xml") put("rf", "image/vnd.rn-realflash") put("rgb", "image/x-rgb") put("rgs", "text/plain") put("rm", "application/vnd.rn-realmedia") put("rmi", "audio/mid") put("rmp", "application/vnd.rn-rn_music_package") put("roff", "application/x-troff") put("rpm", "audio/x-pn-realaudio-plugin") put("rqy", "text/x-ms-rqy") put("rtf", "application/rtf") put("rtx", "text/richtext") put("ruleset", "application/xml") put("s", "text/plain") put("safariextz", "application/x-safari-safariextz") put("scd", "application/x-msschedule") put("scr", "text/plain") put("sct", "text/scriptlet") put("sd2", "audio/x-sd2") put("sdp", "application/sdp") put("sea", "application/octet-stream") put("searchConnector-ms", "application/windows-search-connector+xml") put("setpay", "application/set-payment-initiation") put("setreg", "application/set-registration-initiation") put("settings", "application/xml") put("sgimb", "application/x-sgimb") put("sgml", "text/sgml") put("sh", "application/x-sh") put("shar", "application/x-shar") put("shtml", "text/html") put("sit", "application/x-stuffit") put("sitemap", "application/xml") put("skin", "application/xml") put("sldm", "application/vnd.ms-powerpoint.slide.macroEnabled.12") put("sldx", "application/vnd.openxmlformats-officedocument.presentationml.slide") put("slk", "application/vnd.ms-excel") put("sln", "text/plain") put("slupkg-ms", "application/x-ms-license") put("smd", "audio/x-smd") put("smi", "application/octet-stream") put("smx", "audio/x-smd") put("smz", "audio/x-smd") put("snd", "audio/basic") put("snippet", "application/xml") put("snp", "application/octet-stream") put("sol", "text/plain") put("sor", "text/plain") put("spc", "application/x-pkcs7-certificates") put("spl", "application/futuresplash") put("spx", "audio/ogg") put("src", "application/x-wais-source") put("srf", "text/plain") put("SSISDeploymentManifest", "text/xml") put("ssm", "application/streamingmedia") put("sst", "application/vnd.ms-pki.certstore") put("stl", "application/vnd.ms-pki.stl") put("sv4cpio", "application/x-sv4cpio") put("sv4crc", "application/x-sv4crc") put("svc", "application/xml") put("svg", "image/svg+xml") put("swf", "application/x-shockwave-flash") put("t", "application/x-troff") put("tar", "application/x-tar") put("tcl", "application/x-tcl") put("testrunconfig", "application/xml") put("testsettings", "application/xml") put("tex", "application/x-tex") put("texi", "application/x-texinfo") put("texinfo", "application/x-texinfo") put("tgz", "application/x-compressed") put("thmx", "application/vnd.ms-officetheme") put("thn", "application/octet-stream") put("tif", "image/tiff") put("tiff", "image/tiff") put("tlh", "text/plain") put("tli", "text/plain") put("toc", "application/octet-stream") put("tr", "application/x-troff") put("trm", "application/x-msterminal") put("trx", "application/xml") put("ts", "video/vnd.dlna.mpeg-tts") put("tsv", "text/tab-separated-values") put("ttf", "application/font-sfnt") put("tts", "video/vnd.dlna.mpeg-tts") put("txt", "text/plain") put("u32", "application/octet-stream") put("uls", "text/iuls") put("user", "text/plain") put("ustar", "application/x-ustar") put("vb", "text/plain") put("vbdproj", "text/plain") put("vbk", "video/mpeg") put("vbproj", "text/plain") put("vbs", "text/vbscript") put("vcf", "text/x-vcard") put("vcproj", "application/xml") put("vcs", "text/plain") put("vcxproj", "application/xml") put("vddproj", "text/plain") put("vdp", "text/plain") put("vdproj", "text/plain") put("vdx", "application/vnd.ms-visio.viewer") put("vml", "text/xml") put("vscontent", "application/xml") put("vsct", "text/xml") put("vsd", "application/vnd.visio") put("vsi", "application/ms-vsi") put("vsix", "application/vsix") put("vsixlangpack", "text/xml") put("vsixmanifest", "text/xml") put("vsmdi", "application/xml") put("vspscc", "text/plain") put("vss", "application/vnd.visio") put("vsscc", "text/plain") put("vssettings", "text/xml") put("vssscc", "text/plain") put("vst", "application/vnd.visio") put("vstemplate", "text/xml") put("vsto", "application/x-ms-vsto") put("vsw", "application/vnd.visio") put("vsx", "application/vnd.visio") put("vtx", "application/vnd.visio") put("wav", "audio/wav") put("wave", "audio/wav") put("wax", "audio/x-ms-wax") put("wbk", "application/msword") put("wbmp", "image/vnd.wap.wbmp") put("wcm", "application/vnd.ms-works") put("wdb", "application/vnd.ms-works") put("wdp", "image/vnd.ms-photo") put("webarchive", "application/x-safari-webarchive") put("webm", "video/webm") put("webp", "image/webp") put("webtest", "application/xml") put("wiq", "application/xml") put("wiz", "application/msword") put("wks", "application/vnd.ms-works") put("WLMP", "application/wlmoviemaker") put("wlpginstall", "application/x-wlpg-detect") put("wlpginstall3", "application/x-wlpg3-detect") put("wm", "video/x-ms-wm") put("wma", "audio/x-ms-wma") put("wmd", "application/x-ms-wmd") put("wmf", "application/x-msmetafile") put("wml", "text/vnd.wap.wml") put("wmlc", "application/vnd.wap.wmlc") put("wmls", "text/vnd.wap.wmlscript") put("wmlsc", "application/vnd.wap.wmlscriptc") put("wmp", "video/x-ms-wmp") put("wmv", "video/x-ms-wmv") put("wmx", "video/x-ms-wmx") put("wmz", "application/x-ms-wmz") put("woff", "application/font-woff") put("wpl", "application/vnd.ms-wpl") put("wps", "application/vnd.ms-works") put("wri", "application/x-mswrite") put("wrl", "x-world/x-vrml") put("wrz", "x-world/x-vrml") put("wsc", "text/scriptlet") put("wsdl", "text/xml") put("wvx", "video/x-ms-wvx") put("x", "application/directx") put("xaf", "x-world/x-vrml") put("xaml", "application/xaml+xml") put("xap", "application/x-silverlight-app") put("xbap", "application/x-ms-xbap") put("xbm", "image/x-xbitmap") put("xdr", "text/plain") put("xht", "application/xhtml+xml") put("xhtml", "application/xhtml+xml") put("xla", "application/vnd.ms-excel") put("xlam", "application/vnd.ms-excel.addin.macroEnabled.12") put("xlc", "application/vnd.ms-excel") put("xld", "application/vnd.ms-excel") put("xlk", "application/vnd.ms-excel") put("xll", "application/vnd.ms-excel") put("xlm", "application/vnd.ms-excel") put("xls", "application/vnd.ms-excel") put("xlsb", "application/vnd.ms-excel.sheet.binary.macroEnabled.12") put("xlsm", "application/vnd.ms-excel.sheet.macroEnabled.12") put("xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") put("xlt", "application/vnd.ms-excel") put("xltm", "application/vnd.ms-excel.template.macroEnabled.12") put("xltx", "application/vnd.openxmlformats-officedocument.spreadsheetml.template") put("xlw", "application/vnd.ms-excel") put("xml", "text/xml") put("xmta", "application/xml") put("xof", "x-world/x-vrml") put("XOML", "text/plain") put("xpm", "image/x-xpixmap") put("xps", "application/vnd.ms-xpsdocument") put("xrm-ms", "text/xml") put("xsc", "application/xml") put("xsd", "text/xml") put("xsf", "text/xml") put("xsl", "text/xml") put("xslt", "text/xml") put("xsn", "application/octet-stream") put("xss", "application/xml") put("xspf", "application/xspf+xml") put("xtp", "application/octet-stream") put("xwd", "image/x-xwindowdump") put("z", "application/x-compress") put("zip", "application/zip") } return typesMap[getFilenameExtension()] ?: "" }
apache-2.0
050d8d3e8db2edce9f14a55becafaed5
41.598756
120
0.567486
3.237324
false
false
false
false
JiangKlijna/blog
src/main/java/com/jiangKlijna/web/control/CommentControl.kt
1
2086
package com.jiangKlijna.web.control import com.jiangKlijna.web.bean.Result import com.jiangKlijna.web.service.CommentService import org.springframework.stereotype.Controller import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestMethod import org.springframework.web.bind.annotation.ResponseBody import javax.annotation.Resource /** * Created by jiangKlijna on 8/6/2017. */ @RequestMapping("/comment") @Controller class CommentControl : BaseControl() { @Resource(name = "commentService") val cs: CommentService? = null /** * 写评论 * @message type 1 推送给文章作者 */ @ResponseBody @RequestMapping("/write.json", method = arrayOf(RequestMethod.POST)) fun writeComment(articleid: Int?, content: String?): Result { val un = sess_username testParameter(un, articleid, content).let { if (!it) return errorParameterResult } return cs!!.write(un!!, articleid!!, content!!).apply { setMessage(if (isSucess()) Result.SUCCESS_PUBLISH else Result.FAILURE_PUBLISH) } } /** * 分页查询Article的评论 */ @ResponseBody @RequestMapping("/listByArticle.json", method = arrayOf(RequestMethod.POST)) fun listByArticle(articleid: Int?, pageNum: Int?, perPage: Int?): Result { testParameter(articleid, pageNum, perPage).let { if (!it) return errorParameterResult } return cs!!.listByArticle(articleid!!, pageNum!!, perPage!!).apply { setMessage(if (isSucess()) Result.SUCCESS_SEARCH else Result.FAILURE_SEARCH) } } /** * 删除自己的评论 */ @ResponseBody @RequestMapping("/delete.json", method = arrayOf(RequestMethod.POST)) fun delete(commentid: Int?): Result { val un = sess_username testParameter(un, commentid).let { if (!it) return errorParameterResult } return cs!!.delete(commentid!!, un!!).apply { setMessage(if (isSucess()) Result.SUCCESS_DELETE else Result.FAILURE_DELETE) } } }
gpl-2.0
567275490516fae21dd790f75198b259
32.42623
95
0.678116
4.184805
false
false
false
false
uber/RIBs
android/libraries/rib-router-navigator/src/test/kotlin/os/Bundle.kt
1
1050
/* * Copyright (C) 2017. Uber Technologies * * 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 os /** Stub class to have pure Java unit tests. */ class Bundle : Parcelable { private val testData: MutableMap<String, Any> = HashMap() fun getString(key: String) = testData[key] as String? fun <T : Parcelable?> getParcelable(key: String) = testData[key] as T? fun putParcelable(key: String, value: Parcelable) { testData[key] = value } fun putString(key: String, value: String) { testData[key] = value } }
apache-2.0
ebe9c557446eab4a3e26f465505a6d7b
30.818182
75
0.710476
3.962264
false
true
false
false
asymmetric-team/secure-messenger-android
repository/src/androidTest/java/com/safechat/repository/RepositoryImplTest.kt
1
2313
package com.safechat.repository import android.support.test.InstrumentationRegistry.getTargetContext import com.safechat.message.Message import com.safechat.register.KeyPairString import org.junit.After import org.junit.Assert.* import org.junit.Before import org.junit.Test class RepositoryImplTest { val repositoryImpl = RepositoryImpl(getTargetContext()) @Test fun shouldNotFindKeyBeforeKeySaved() { assertFalse(repositoryImpl.isKeySaved()) } @Test fun shouldFindKeyAfterKeySaved() { repositoryImpl.saveNewKey(newKeyPair()) assertTrue(repositoryImpl.isKeySaved()) } @Test fun shouldReadSavedKey() { val keyPair = newKeyPair() repositoryImpl.saveNewKey(keyPair) assertEquals(keyPair.privateKey, repositoryImpl.getPrivateKeyString()) assertEquals(keyPair.publicKey, repositoryImpl.getPublicKeyString()) } @Test fun shouldSaveDecryptedSymmetricKey() { repositoryImpl.saveDecryptedSymmetricKey(otherPublicKey, "decrypted_symmetric_key") assertTrue(repositoryImpl.containsSymmetricKey(otherPublicKey)) } @Test fun shouldSaveConversationMessage() { val message = Message("", false, false, 1L) repositoryImpl.saveConversationMessage(otherPublicKey, message) val messages = repositoryImpl.getConversationsMessages() assertEquals(message, messages.values.first()) } @Test fun shouldOverrideMessageFromTheSamePublicKey() { val secondMessage = Message("", false, false, 2L) repositoryImpl.saveConversationMessage(otherPublicKey, Message("", false, false, 1L)) repositoryImpl.saveConversationMessage(otherPublicKey, secondMessage) val messages = repositoryImpl.getConversationsMessages() assertEquals(secondMessage, messages.values.first()) } private fun newKeyPair() = KeyPairString("publicKey", "privateKey") private val otherPublicKey = "other_public_key" @After @Before fun clearKey() { repositoryImpl.sharedPreferences.edit() .remove(RepositoryImpl.PRIVATE_KEY) .remove(RepositoryImpl.PUBLIC_KEY) .remove(RepositoryImpl.CONVERSATIONS) .remove(otherPublicKey) .apply() } }
apache-2.0
68490fad1e8fe7770c1b44cf407a4496
31.125
93
0.705577
4.910828
false
true
false
false
dataloom/conductor-client
src/main/kotlin/com/openlattice/hazelcast/serializers/SynchronizeMaterializedEntitySetProcessorStreamSerializer.kt
1
3424
/* * Copyright (C) 2019. OpenLattice, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * You can contact the owner of the copyright at [email protected] * * */ package com.openlattice.hazelcast.serializers import com.hazelcast.nio.ObjectDataInput import com.hazelcast.nio.ObjectDataOutput import com.kryptnostic.rhizome.hazelcast.serializers.UUIDStreamSerializerUtils import com.kryptnostic.rhizome.pods.hazelcast.SelfRegisteringStreamSerializer import com.openlattice.assembler.AssemblerConnectionManager import com.openlattice.assembler.AssemblerConnectionManagerDependent import com.openlattice.assembler.processors.SynchronizeMaterializedEntitySetProcessor import com.openlattice.hazelcast.StreamSerializerTypeIds import org.springframework.stereotype.Component @Component class SynchronizeMaterializedEntitySetProcessorStreamSerializer : SelfRegisteringStreamSerializer<SynchronizeMaterializedEntitySetProcessor>, AssemblerConnectionManagerDependent<Void?> { private lateinit var acm: AssemblerConnectionManager override fun getTypeId(): Int { return StreamSerializerTypeIds.SYNCHRONIZE_MATERIALIZED_ENTITY_SET_PROCESSOR.ordinal } override fun getClazz(): Class<out SynchronizeMaterializedEntitySetProcessor> { return SynchronizeMaterializedEntitySetProcessor::class.java } override fun write(out: ObjectDataOutput, obj: SynchronizeMaterializedEntitySetProcessor) { EntitySetStreamSerializer.serialize(out, obj.entitySet) out.writeInt(obj.materializablePropertyTypes.size) obj.materializablePropertyTypes.forEach { (propertyTypeId, propertyType) -> UUIDStreamSerializerUtils.serialize(out, propertyTypeId) PropertyTypeStreamSerializer.serialize(out, propertyType) } MaterializeEntitySetProcessorStreamSerializer .serializeAuthorizedPropertyTypesOfPrincipals(out, obj.authorizedPropertyTypesOfPrincipals) } override fun read(input: ObjectDataInput): SynchronizeMaterializedEntitySetProcessor { val entitySet = EntitySetStreamSerializer.deserialize(input) val size = input.readInt() val materializablePropertyTypes = ((0 until size).map { UUIDStreamSerializerUtils.deserialize(input) to PropertyTypeStreamSerializer.deserialize(input) }.toMap()) val authorizedPropertyTypesOfPrincipals = MaterializeEntitySetProcessorStreamSerializer .deserializeAuthorizedPropertyTypesOfPrincipals(input) return SynchronizeMaterializedEntitySetProcessor( entitySet, materializablePropertyTypes, authorizedPropertyTypesOfPrincipals ).init(acm) } override fun init(acm: AssemblerConnectionManager): Void? { this.acm = acm return null } }
gpl-3.0
90f7d611c1662a8fdca2036bdda92864
40.26506
107
0.775409
5.883162
false
false
false
false
pyamsoft/zaptorch
service/src/main/java/com/pyamsoft/zaptorch/service/CameraInteractorImpl.kt
1
3363
/* * Copyright 2020 Peter Kenji Yamanaka * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.pyamsoft.zaptorch.service import android.view.KeyEvent import com.pyamsoft.pydroid.core.Enforcer import com.pyamsoft.zaptorch.core.* import com.pyamsoft.zaptorch.service.command.Command import javax.inject.Inject import javax.inject.Provider import javax.inject.Singleton import kotlinx.coroutines.* import timber.log.Timber @Singleton internal class CameraInteractorImpl @Inject internal constructor( private val cameraProvider: Provider<CameraInterface>, private val notificationHandler: NotificationHandler, // Need JvmSuppressWildcards for Dagger private val commands: Set<@JvmSuppressWildcards Command>, ) : CameraInteractor, TorchOffInteractor, Command.Handler { private var cameraInterface: CameraInterface? = null override suspend fun handleKeyPress(action: Int, keyCode: Int) { val self = this withContext(context = Dispatchers.Default) { Enforcer.assertOffMainThread() if (action != KeyEvent.ACTION_UP) { return@withContext } for (command in commands) { val name = command.id() val otherCommands = commands.filter { it.id() !== name } if (command.handle(keyCode, self)) { otherCommands.forEach { it.reset() } Timber.d("Torch handled by $name") } } } } override suspend fun onCommandStart(state: TorchState) { Timber.d("Start command: $state") notificationHandler.start() } override suspend fun onCommandStop() { Timber.d("Stop command") notificationHandler.stop() } override fun initialize() { Enforcer.assertOnMainThread() // Reset clearCommands() teardown() cameraInterface = cameraProvider.get().apply { setOnUnavailableCallback { state -> Timber.w("Torch unavailable: $state") clearCommands() notificationHandler.stop() } } } override suspend fun forceTorchOn(state: TorchState): Throwable? = withContext(context = Dispatchers.IO) { cameraInterface?.forceTorchOn(state) } override suspend fun forceTorchOff(): Throwable? = withContext(context = Dispatchers.IO) { cameraInterface?.forceTorchOff() } override suspend fun killTorch() { withContext(context = Dispatchers.Default) { Timber.d("Kill torch") clearCommands() notificationHandler.stop() cameraInterface?.forceTorchOff() } } private fun clearCommands() { commands.forEach { it.reset() } } private fun destroyCommands() { commands.forEach { it.destroy() } } private fun teardown() { notificationHandler.stop() cameraInterface?.destroy() cameraInterface = null } override fun destroy() { destroyCommands() teardown() } }
apache-2.0
5eda11f0e0204b6899f562aa172ea7b8
27.025
84
0.693726
4.436675
false
false
false
false
msebire/intellij-community
platform/lang-impl/src/com/intellij/execution/console/PrefixHistoryModel.kt
2
4850
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.execution.console import com.intellij.execution.console.ConsoleHistoryModel.Entry import com.intellij.ide.ui.UISettings import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.util.ModificationTracker import com.intellij.openapi.util.SimpleModificationTracker import com.intellij.openapi.util.TextRange import com.intellij.util.containers.ConcurrentFactoryMap import com.intellij.util.containers.ContainerUtil import gnu.trove.TIntStack /** * @author Yuli Fiterman */ private val MasterModels = ConcurrentFactoryMap.createMap<String, MasterModel>( { MasterModel() }, { ContainerUtil.createConcurrentWeakValueMap() }) private fun assertDispatchThread() = ApplicationManager.getApplication().assertIsDispatchThread() fun createModel(persistenceId: String, console: LanguageConsoleView): ConsoleHistoryModel { val masterModel: MasterModel = MasterModels[persistenceId]!! fun getPrefixFromConsole(): String { val caretOffset = console.consoleEditor.caretModel.offset return console.editorDocument.getText(TextRange.create(0, caretOffset)) } return PrefixHistoryModel(masterModel, ::getPrefixFromConsole) } private class PrefixHistoryModel constructor(private val masterModel: MasterModel, private val getPrefixFn: () -> String) : ConsoleHistoryBaseModel by masterModel, ConsoleHistoryModel { var userContent: String = "" override fun setContent(userContent: String) { this.userContent = userContent } private var currentIndex: Int? = null private var currentEntries: List<String>? = null private var prevEntries: TIntStack = TIntStack() private var historyPrefix: String = "" init { resetIndex() } override fun resetEntries(entries: MutableList<String>) { masterModel.resetEntries(entries) resetIndex() } override fun addToHistory(statement: String?) { assertDispatchThread() if (statement.isNullOrEmpty()) { return } masterModel.addToHistory(statement) resetIndex() } override fun removeFromHistory(statement: String?) { assertDispatchThread() if (statement.isNullOrEmpty()) { return } masterModel.removeFromHistory(statement) resetIndex() } private fun resetIndex() { currentIndex = null currentEntries = null prevEntries.clear() historyPrefix = "" } override fun getHistoryNext(): Entry? { val entries = currentEntries ?: masterModel.entries val offset = currentIndex ?: entries.size if (offset <= 0) { return null } if (currentIndex == null) { historyPrefix = getPrefixFn() } val res = entries.withIndex().findLast { it.index < offset && it.value.startsWith(historyPrefix) } ?: return null if (currentEntries == null) { currentEntries = entries } currentIndex?.let { prevEntries.push(it) } currentIndex = res.index return createEntry(res.value) } override fun getHistoryPrev(): Entry? { val entries = currentEntries ?: return null return if (prevEntries.size() > 0) { val index = prevEntries.pop() currentIndex = index createEntry(entries[index]) } else { resetIndex() createEntry(userContent) } } private fun createEntry(prevEntry: String): Entry = Entry(prevEntry, prevEntry.length) override fun getCurrentIndex(): Int = currentIndex ?: entries.size-1 override fun prevOnLastLine(): Boolean = true override fun hasHistory(): Boolean = currentEntries != null } private class MasterModel(private val modTracker: SimpleModificationTracker = SimpleModificationTracker()) : ConsoleHistoryBaseModel, ModificationTracker by modTracker { @Volatile private var entries: MutableList<String> = mutableListOf() @Suppress("UNCHECKED_CAST") override fun getEntries(): MutableList<String> = entries.toMutableList() override fun resetEntries(ent: List<String>) { entries = ent.toMutableList() } override fun addToHistory(statement: String?) { if (statement == null) return entries.remove(statement) entries.add(statement) if (entries.size >= maxHistorySize) { entries.removeAt(0) } modTracker.incModificationCount() } override fun removeFromHistory(statement: String?) { if (statement == null) return entries.remove(statement) modTracker.incModificationCount() } override fun getMaxHistorySize() = UISettings.instance.state.consoleCommandHistoryLimit override fun isEmpty(): Boolean = entries.isEmpty() override fun getHistorySize(): Int = entries.size }
apache-2.0
efc4297592c002f7ff6ae0af8d07fbb7
29.3125
169
0.711959
4.672447
false
false
false
false
msebire/intellij-community
xml/impl/src/com/intellij/ide/browsers/actions/OpenFileInDefaultBrowserAction.kt
4
2219
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.browsers.actions import com.intellij.ide.GeneralSettings import com.intellij.ide.browsers.BrowserLauncherAppless import com.intellij.ide.browsers.DefaultBrowserPolicy import com.intellij.ide.browsers.WebBrowser import com.intellij.ide.browsers.WebBrowserManager import com.intellij.openapi.actionSystem.ActionPlaces import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.DumbAwareAction import com.intellij.xml.util.HtmlUtil class OpenFileInDefaultBrowserAction : DumbAwareAction() { override fun update(e: AnActionEvent) { val result = BaseOpenInBrowserAction.doUpdate(e) ?: return var description = templatePresentation.description if (HtmlUtil.isHtmlFile(result.file)) { description += " (hold Shift to open URL of local file)" } val presentation = e.presentation presentation.text = templatePresentation.text presentation.description = description findUsingBrowser()?.let { presentation.icon = it.icon } if (ActionPlaces.isPopupPlace(e.place)) { presentation.isVisible = presentation.isEnabled } } override fun actionPerformed(e: AnActionEvent) { openInBrowser(e, findUsingBrowser()) } } fun findUsingBrowser(): WebBrowser? { val browserManager = WebBrowserManager.getInstance() val defaultBrowserPolicy = browserManager.defaultBrowserPolicy if (defaultBrowserPolicy == DefaultBrowserPolicy.FIRST || defaultBrowserPolicy == DefaultBrowserPolicy.SYSTEM && !BrowserLauncherAppless.canUseSystemDefaultBrowserPolicy()) { return browserManager.firstActiveBrowser } else if (defaultBrowserPolicy == DefaultBrowserPolicy.ALTERNATIVE) { val path = GeneralSettings.getInstance().browserPath if (!path.isNullOrBlank()) { val browser = browserManager.findBrowserById(path) if (browser == null) { for (item in browserManager.activeBrowsers) { if (path == item.path) { return item } } } else { return browser } } } return null }
apache-2.0
43ed42e533840034466051a1ce2050c9
33.6875
176
0.741325
4.622917
false
false
false
false
msebire/intellij-community
plugins/devkit/devkit-core/src/inspections/missingApi/MissingRecentApiVisitor.kt
1
8380
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.idea.devkit.inspections.missingApi import com.intellij.codeInsight.AnnotationUtil import com.intellij.codeInsight.ExternalAnnotationsManager import com.intellij.codeInsight.daemon.impl.analysis.HighlightMessageUtil import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import com.intellij.codeInspection.apiUsage.ApiUsageVisitorBase import com.intellij.openapi.util.BuildNumber import com.intellij.psi.* import com.intellij.psi.util.PsiUtil import org.jetbrains.annotations.ApiStatus import org.jetbrains.idea.devkit.DevKitBundle import org.jetbrains.uast.UImportStatement import org.jetbrains.uast.getUastParentOfType /** * PSI visitor containing implementation of [MissingRecentApiInspection], * which reports usages of APIs that are not available in old IDE builds matching the * "since" constraint of the plugin. */ class MissingRecentApiVisitor( private val holder: ProblemsHolder, private val highlightType: ProblemHighlightType, private val targetedSinceUntilRanges: List<SinceUntilRange> ) : ApiUsageVisitorBase() { companion object { val AVAILABLE_SINCE_ANNOTATION: String = ApiStatus.AvailableSince::class.qualifiedName!! } override fun shouldProcessReferences(element: PsiElement) = !element.isInsideImportStatement() private fun PsiElement.isInsideImportStatement() = getUastParentOfType<UImportStatement>() != null override fun processReference(reference: PsiReference) { if (reference is ResolvingHint && !(reference as ResolvingHint).canResolveTo(PsiModifierListOwner::class.java)) { return } val resolved = reference.resolve() if (resolved != null) { val elementToHighlight = getElementToHighlight(reference) checkMissingApi(resolved, elementToHighlight) } } private fun getElementToHighlight(reference: PsiReference): PsiElement { if (reference is PsiJavaCodeReferenceElement) { val referenceNameElement = reference.referenceNameElement if (referenceNameElement != null) { return referenceNameElement } } return reference.element } override fun processConstructorInvocation(instantiatedClass: PsiJavaCodeReferenceElement, constructor: PsiMethod) { checkMissingApi(constructor, instantiatedClass) } override fun processDefaultConstructorInvocation(instantiatedClass: PsiJavaCodeReferenceElement) { val createdClass = instantiatedClass.resolve() as? PsiClass ?: return checkClassDefaultConstructorApi(createdClass, instantiatedClass) } private fun checkClassDefaultConstructorApi(psiClass: PsiClass, elementToHighlight: PsiElement) { val availableSince = findEmptyConstructorAnnotations(psiClass)?.getAvailableSinceBuildNumber() ?: return val brokenRanges = targetedSinceUntilRanges.filter { it.someBuildsAreNotCovered(availableSince) } if (brokenRanges.isNotEmpty()) { registerDefaultConstructorProblem(psiClass, elementToHighlight, availableSince, brokenRanges) } } override fun processEmptyConstructorOfSuperClassImplicitInvocationAtSubclassDeclaration( subclass: PsiClass, superClass: PsiClass ) { val availableSince = findEmptyConstructorAnnotations(superClass)?.getAvailableSinceBuildNumber() ?: return val brokenRanges = targetedSinceUntilRanges.filter { it.someBuildsAreNotCovered(availableSince) } if (brokenRanges.isNotEmpty()) { val asAnonymous = subclass as? PsiAnonymousClass if (asAnonymous != null) { val argumentList = asAnonymous.argumentList if (argumentList != null && !argumentList.isEmpty) return } val elementToHighlight = asAnonymous?.baseClassReference ?: subclass.nameIdentifier if (elementToHighlight != null) { registerDefaultConstructorProblem(superClass, elementToHighlight, availableSince, brokenRanges) } } } override fun processEmptyConstructorOfSuperClassImplicitInvocationAtSubclassConstructor( superClass: PsiClass, subclassConstructor: PsiMethod ) { val nameIdentifier = subclassConstructor.nameIdentifier ?: return checkClassDefaultConstructorApi(superClass, nameIdentifier) } override fun processMethodOverriding(method: PsiMethod, overriddenMethod: PsiMethod) { val availableSince = overriddenMethod.getApiSinceBuildNumber() ?: return val brokenRanges = targetedSinceUntilRanges.filter { it.someBuildsAreNotCovered(availableSince) } if (brokenRanges.isNotEmpty()) { val aClass = overriddenMethod.containingClass ?: return val nameIdentifier = method.nameIdentifier ?: return val description = DevKitBundle.message( "inspections.api.overrides.method.available.only.since", aClass.getPresentableName(), availableSince.asString(), brokenRanges.joinToString { it.asString() } ) holder.registerProblem(nameIdentifier, description, highlightType) } } private fun registerDefaultConstructorProblem( constructorOwner: PsiClass, elementToHighlight: PsiElement, apiSinceBuildNumber: BuildNumber, brokenRanges: List<SinceUntilRange> ) { val description = DevKitBundle.message( "inspections.api.constructor.only.since", constructorOwner.qualifiedName, apiSinceBuildNumber.asString(), brokenRanges.joinToString { it.asString() } ) holder.registerProblem(elementToHighlight, description, highlightType) } private fun findEmptyConstructorAnnotations(psiClass: PsiClass): List<PsiAnnotation>? { val constructors = psiClass.constructors if (constructors.isEmpty()) { /* Default constructor of a class, which is not present in source code, can be externally annotated (IDEA-200832). */ return ExternalAnnotationsManager.getInstance(psiClass.project) .findDefaultConstructorExternalAnnotations(psiClass, AVAILABLE_SINCE_ANNOTATION) } else { val emptyConstructor = constructors.find { it.parameterList.isEmpty } if (emptyConstructor != null) { return AnnotationUtil.findAllAnnotations(emptyConstructor, listOf(AVAILABLE_SINCE_ANNOTATION), false) } return null } } /** * Checks if the API element [refElement] is annotated * with [org.jetbrains.annotations.ApiStatus.AvailableSince]. * If so, it checks plugin's [since, until] compatibility range * and registers a problem if the API was first introduced later * than plugin's `since` build. */ private fun checkMissingApi(refElement: PsiElement, elementToHighlight: PsiElement) { if (refElement !is PsiModifierListOwner) return val availableSince = refElement.getApiSinceBuildNumber() ?: return val brokenRanges = targetedSinceUntilRanges.filter { it.someBuildsAreNotCovered(availableSince) } if (brokenRanges.isNotEmpty()) { val description = DevKitBundle.message( "inspections.api.available.only.since", refElement.getPresentableName(), availableSince.asString(), brokenRanges.joinToString { it.asString() } ) holder.registerProblem(elementToHighlight, description, highlightType) } } /** * Returns the first build number when `this` API element was added. */ private fun PsiModifierListOwner.getApiSinceBuildNumber(): BuildNumber? { val externalAnnotations = AnnotationUtil.findAllAnnotations(this, listOf(AVAILABLE_SINCE_ANNOTATION), false) if (externalAnnotations.isEmpty()) return null return externalAnnotations.getAvailableSinceBuildNumber() } private fun List<PsiAnnotation>.getAvailableSinceBuildNumber(): BuildNumber? = asSequence() .mapNotNull { annotation -> AnnotationUtil.getDeclaredStringAttributeValue(annotation, "value")?.let { BuildNumber.fromStringOrNull(it) } } .min() private fun SinceUntilRange.someBuildsAreNotCovered(apiSinceBuildNumber: BuildNumber) = sinceBuild == null || sinceBuild < apiSinceBuildNumber private fun PsiElement.getPresentableName(): String? { //Annotation attribute methods don't have parameters. return if (this is PsiMethod && PsiUtil.isAnnotationMethod(this)) { name } else HighlightMessageUtil.getSymbolName(this) } }
apache-2.0
5450696a27fc2ab5f88eb20b006cc8af
40.490099
140
0.759427
5.160099
false
false
false
false
TangHao1987/intellij-community
platform/configuration-store-impl/src/StoreAwareProjectManager.kt
2
10277
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.configurationStore import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ApplicationNamesInfo import com.intellij.openapi.application.ModalityState import com.intellij.openapi.application.WriteAction import com.intellij.openapi.application.ex.ApplicationManagerEx import com.intellij.openapi.components.ComponentManager import com.intellij.openapi.components.StateStorage import com.intellij.openapi.components.impl.stores.* import com.intellij.openapi.components.stateStore import com.intellij.openapi.module.Module import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectBundle import com.intellij.openapi.project.impl.ProjectManagerImpl import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.Key import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.openapi.vfs.ex.VirtualFileManagerAdapter import com.intellij.openapi.vfs.newvfs.events.VFileEvent import com.intellij.openapi.vfs.newvfs.events.VFilePropertyChangeEvent import com.intellij.util.SingleAlarm import com.intellij.util.containers.MultiMap import gnu.trove.THashSet import org.jetbrains.annotations.TestOnly import java.util.LinkedHashSet import java.util.concurrent.atomic.AtomicInteger /** * Should be a separate service, not closely related to ProjectManager, but it requires some cleanup/investigation. */ class StoreAwareProjectManager(virtualFileManager: VirtualFileManager, progressManager: ProgressManager) : ProjectManagerImpl(progressManager) { companion object { private val CHANGED_FILES_KEY = Key.create<MultiMap<ComponentStoreImpl, StateStorage>>("CHANGED_FILES_KEY") } private val reloadBlockCount = AtomicInteger() private val changedApplicationFiles = LinkedHashSet<StateStorage>() private val restartApplicationOrReloadProjectTask = Runnable { if (isReloadUnblocked() && tryToReloadApplication()) { val projectsToReload = THashSet<Project>() for (project in getOpenProjects()) { if (project.isDisposed()) { continue } val changes = CHANGED_FILES_KEY.get(project) ?: continue CHANGED_FILES_KEY.set(project, null) if (!changes.isEmpty()) { for ((store, storages) in changes.entrySet()) { @suppress("UNCHECKED_CAST") if (reloadStore(storages as Set<StateStorage>, store, false) == ReloadComponentStoreStatus.RESTART_AGREED) { projectsToReload.add(project) } } } } for (project in projectsToReload) { ProjectManagerImpl.doReloadProject(project) } } } private val changedFilesAlarm = SingleAlarm(restartApplicationOrReloadProjectTask, 300, this) init { ApplicationManager.getApplication().getMessageBus().connect().subscribe(StateStorageManager.STORAGE_TOPIC, object : StorageManagerListener() { override fun storageFileChanged(event: VFileEvent, storage: StateStorage, componentManager: ComponentManager) { if (event is VFilePropertyChangeEvent) { // ignore because doesn't affect content return } if (event.getRequestor() is StateStorage.SaveSession || event.getRequestor() is StateStorage || event.getRequestor() is ProjectManagerImpl) { return } registerChangedStorage(storage, componentManager) } }) virtualFileManager.addVirtualFileManagerListener(object : VirtualFileManagerAdapter() { override fun beforeRefreshStart(asynchronous: Boolean) { blockReloadingProjectOnExternalChanges() } override fun afterRefreshFinish(asynchronous: Boolean) { unblockReloadingProjectOnExternalChanges() } }) } private fun isReloadUnblocked(): Boolean { val count = reloadBlockCount.get() if (LOG.isDebugEnabled()) { LOG.debug("[RELOAD] myReloadBlockCount = $count") } return count == 0 } override fun saveChangedProjectFile(file: VirtualFile, project: Project) { val storageManager = (project.stateStore as ComponentStoreImpl).storageManager as? StateStorageManagerImpl ?: return storageManager.getCachedFileStorages(listOf(storageManager.collapseMacros(file.getPath()))).firstOrNull()?.let { // if empty, so, storage is not yet loaded, so, we don't have to reload registerChangedStorage(it, project) } } override fun blockReloadingProjectOnExternalChanges() { reloadBlockCount.incrementAndGet() } override fun unblockReloadingProjectOnExternalChanges() { assert(reloadBlockCount.get() > 0) if (reloadBlockCount.decrementAndGet() == 0 && changedFilesAlarm.isEmpty()) { if (ApplicationManager.getApplication().isUnitTestMode()) { // todo fix test to handle invokeLater changedFilesAlarm.request(true) } else { ApplicationManager.getApplication().invokeLater(restartApplicationOrReloadProjectTask, ModalityState.NON_MODAL) } } } @TestOnly fun flushChangedAlarm() { changedFilesAlarm.flush() } override fun reloadProject(project: Project) { CHANGED_FILES_KEY.set(project, null) super.reloadProject(project) } private fun registerChangedStorage(storage: StateStorage, componentManager: ComponentManager) { if (LOG.isDebugEnabled()) { LOG.debug("[RELOAD] Registering project to reload: $storage", Exception()) } val project: Project? = when (componentManager) { is Project -> componentManager is Module -> componentManager.getProject() else -> null } if (project == null) { val changes = changedApplicationFiles synchronized (changes) { changes.add(storage) } } else { var changes = CHANGED_FILES_KEY.get(project) if (changes == null) { changes = MultiMap.createLinkedSet() CHANGED_FILES_KEY.set(project, changes) } synchronized (changes) { changes.putValue(componentManager.stateStore as ComponentStoreImpl, storage) } } if (storage is StateStorageBase<*>) { storage.disableSaving() } if (isReloadUnblocked()) { changedFilesAlarm.cancelAndRequest() } } private fun tryToReloadApplication(): Boolean { if (ApplicationManager.getApplication().isDisposed()) { return false } if (changedApplicationFiles.isEmpty()) { return true } val changes = LinkedHashSet<StateStorage>(changedApplicationFiles) changedApplicationFiles.clear() val status = reloadStore(changes, ApplicationManager.getApplication().stateStore as ComponentStoreImpl, true) if (status == ReloadComponentStoreStatus.RESTART_AGREED) { ApplicationManagerEx.getApplicationEx().restart(true) return false } else { return status == ReloadComponentStoreStatus.SUCCESS || status == ReloadComponentStoreStatus.RESTART_CANCELLED } } } private fun reloadStore(changedStorages: Set<StateStorage>, store: ComponentStoreImpl, isApp: Boolean): ReloadComponentStoreStatus { val notReloadableComponents: Collection<String>? var willBeReloaded = false try { val token = WriteAction.start() try { notReloadableComponents = store.reload(changedStorages) } catch (e: Throwable) { LOG.warn(e) Messages.showWarningDialog(ProjectBundle.message("project.reload.failed", e.getMessage()), ProjectBundle.message("project.reload.failed.title")) return ReloadComponentStoreStatus.ERROR } finally { token.finish() } if (notReloadableComponents == null || notReloadableComponents.isEmpty()) { return ReloadComponentStoreStatus.SUCCESS } willBeReloaded = askToRestart(store, notReloadableComponents, changedStorages, isApp) return if (willBeReloaded) ReloadComponentStoreStatus.RESTART_AGREED else ReloadComponentStoreStatus.RESTART_CANCELLED } finally { if (!willBeReloaded) { for (storage in changedStorages) { if (storage is StateStorageBase<*>) { storage.enableSaving() } } } } } // used in settings repository plugin fun askToRestart(store: IComponentStore, notReloadableComponents: Collection<String>, changedStorages: Set<StateStorage>?, isApp: Boolean): Boolean { val message = StringBuilder() val storeName = if (store is IProjectStore) "Project" else "Application" message.append(storeName).append(' ') message.append("components were changed externally and cannot be reloaded:\n\n") var count = 0 for (component in notReloadableComponents) { if (count == 10) { message.append('\n').append("and ").append(notReloadableComponents.size() - count).append(" more").append('\n') } else { message.append(component).append('\n') count++ } } message.append("\nWould you like to ") if (isApp) { message.append(if (ApplicationManager.getApplication().isRestartCapable()) "restart" else "shutdown").append(' ') message.append(ApplicationNamesInfo.getInstance().getProductName()).append('?') } else { message.append("reload project?") } if (Messages.showYesNoDialog(message.toString(), "$storeName Files Changed", Messages.getQuestionIcon()) == Messages.YES) { if (changedStorages != null) { for (storage in changedStorages) { if (storage is StateStorageBase<*>) { storage.disableSaving() } } } return true } return false } public enum class ReloadComponentStoreStatus { RESTART_AGREED, RESTART_CANCELLED, ERROR, SUCCESS }
apache-2.0
91069fb79ac920bc05dd65fde6c8229d
33.959184
150
0.71986
4.974347
false
true
false
false
rock3r/detekt
detekt-api/src/main/kotlin/io/gitlab/arturbosch/detekt/api/Location.kt
1
3154
package io.gitlab.arturbosch.detekt.api import io.gitlab.arturbosch.detekt.api.internal.getTextSafe import io.gitlab.arturbosch.detekt.api.internal.searchName import org.jetbrains.kotlin.com.intellij.openapi.util.TextRange import org.jetbrains.kotlin.com.intellij.psi.PsiElement import org.jetbrains.kotlin.com.intellij.testFramework.LightVirtualFile import org.jetbrains.kotlin.diagnostics.DiagnosticUtils import org.jetbrains.kotlin.diagnostics.PsiDiagnosticUtils import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.getTextWithLocation import org.jetbrains.kotlin.psi.psiUtil.startOffset /** * Specifies a position within a source code fragment. */ data class Location( val source: SourceLocation, val text: TextLocation, @Deprecated("Will be removed in the future. Use queries on 'ktElement' instead.") val locationString: String, val file: String ) : Compactable { override fun compact(): String = "$file:$source" companion object { /** * Creates a [Location] from a [PsiElement]. * If the element can't be determined, the [KtFile] with a character offset can be used. */ fun from(element: PsiElement, offset: Int = 0): Location { val start = startLineAndColumn(element, offset) val sourceLocation = SourceLocation(start.line, start.column) val textLocation = TextLocation(element.startOffset + offset, element.endOffset + offset) val fileName = element.originalFilePath() val locationText = element.getTextAtLocationSafe() return Location(sourceLocation, textLocation, locationText, fileName) } /** * Determines the line and column of a [PsiElement] in the source file. */ @Suppress("TooGenericExceptionCaught") fun startLineAndColumn(element: PsiElement, offset: Int = 0): PsiDiagnosticUtils.LineAndColumn { return try { val range = element.textRange DiagnosticUtils.getLineAndColumnInPsiFile(element.containingFile, TextRange(range.startOffset + offset, range.endOffset + offset)) } catch (e: IndexOutOfBoundsException) { // #18 - somehow the TextRange is out of bound on '}' leaf nodes, returning fail safe -1 PsiDiagnosticUtils.LineAndColumn(-1, -1, null) } } private fun PsiElement.originalFilePath() = (containingFile.viewProvider.virtualFile as? LightVirtualFile)?.originalFile?.name ?: containingFile.name private fun PsiElement.getTextAtLocationSafe() = getTextSafe({ searchName() }, { getTextWithLocation() }) } } /** * Stores line and column information of a location. */ data class SourceLocation(val line: Int, val column: Int) { override fun toString(): String = "$line:$column" } /** * Stores character start and end positions of an text file. */ data class TextLocation(val start: Int, val end: Int) { override fun toString(): String = "$start:$end" }
apache-2.0
94737837cfd57d6ca5bf67553a8289dd
39.435897
104
0.687698
4.679525
false
false
false
false
ankidroid/Anki-Android
AnkiDroid/src/main/java/com/ichi2/themes/HtmlColors.kt
1
9899
/* * Copyright (c) 2021 Akshay Jadhav <[email protected]> * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation; either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package com.ichi2.themes import com.ichi2.utils.HashUtil.HashMapInit import com.ichi2.utils.KotlinCleanup import timber.log.Timber import java.util.* import java.util.regex.Matcher import java.util.regex.Pattern @KotlinCleanup("for better possibly-null handling") object HtmlColors { private val fHtmlColorPattern = Pattern.compile( "((?:color|background)\\s*[=:]\\s*\"?)((?:[a-z]+|#[0-9a-f]+|rgb\\([0-9]+,\\s*[0-9],+\\s*[0-9]+\\)))([\";\\s])", Pattern.CASE_INSENSITIVE ) private val fShortHexColorPattern = Pattern.compile("^#([0-9a-f])([0-9a-f])([0-9a-f])$", Pattern.CASE_INSENSITIVE) private val fLongHexColorPattern = Pattern.compile("^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$", Pattern.CASE_INSENSITIVE) private val fRgbColorPattern = Pattern.compile("^rgb\\(([0-9]+)\\s*,\\s*([0-9]+)\\s*,\\s*([0-9]+)\\)$", Pattern.CASE_INSENSITIVE) @Suppress("RegExpRedundantEscape") // In Android, } should be escaped private val fClozeStylePattern = Pattern.compile("(.cloze\\s*\\{[^}]*color:\\s*#)[0-9a-f]{6}(;[^}]*\\})", Pattern.CASE_INSENSITIVE) private fun nameToHex(name: String): String? { if (sColorsMap == null) { sColorsMap = HashMapInit(fColorsRawList.size) var i = 0 while (i < fColorsRawList.size) { (sColorsMap as HashMap<String, String>)[fColorsRawList[i].lowercase(Locale.US)] = fColorsRawList[i + 1].lowercase(Locale.US) i += 2 } } val normalisedName = name.lowercase(Locale.US) return if (sColorsMap!!.containsKey(normalisedName)) { sColorsMap!![normalisedName] } else name } /** * Returns a string where all colors have been inverted. It applies to anything that is in a tag and looks like * #FFFFFF Example: Here only #000000 will be replaced (#777777 is content) <span style="color: #000000;">Code * #777777 is the grey color</span> This is done with a state machine with 2 states: - 0: within content - 1: within * a tag */ fun invertColors(text: String?): String { val sb = StringBuffer() val m1 = fHtmlColorPattern.matcher(text!!) while (m1.find()) { // Convert names to hex var color = nameToHex(m1.group(2)!!) var m2: Matcher try { if (color!!.length == 4 && color[0] == '#') { m2 = fShortHexColorPattern.matcher(color) if (m2.find()) { color = String.format( Locale.US, "#%x%x%x", 0xf - m2.group(1)!!.toInt(16), 0xf - m2.group(2)!!.toInt(16), 0xf - m2.group(3)!!.toInt(16) ) } } else if (color.length == 7 && color[0] == '#') { m2 = fLongHexColorPattern.matcher(color) if (m2.find()) { color = String.format( Locale.US, "#%02x%02x%02x", 0xff - m2.group(1)!!.toInt(16), 0xff - m2.group(2)!!.toInt(16), 0xff - m2.group(3)!!.toInt(16) ) } } else if (color.length > 9 && color.lowercase(Locale.US).startsWith("rgb")) { m2 = fRgbColorPattern.matcher(color) if (m2.find()) { color = String.format( Locale.US, "rgb(%d, %d, %d)", 0xff - m2.group(1)!!.toInt(), 0xff - m2.group(2)!!.toInt(), 0xff - m2.group(3)!!.toInt() ) } } } catch (e: NumberFormatException) { Timber.w(e) // shouldn't happen but ignore anyway } m1.appendReplacement(sb, m1.group(1)!! + color + m1.group(3)) } m1.appendTail(sb) var invertedText = sb.toString() // fix style for cloze to light blue instead of inverted blue which ends up as yellow val mc = fClozeStylePattern.matcher(invertedText) invertedText = mc.replaceAll("$10088ff$2") return invertedText } private var sColorsMap: MutableMap<String, String>? = null private val fColorsRawList = arrayOf( "AliceBlue", "#F0F8FF", "AntiqueWhite", "#FAEBD7", "Aqua", "#00FFFF", "Aquamarine", "#7FFFD4", "Azure", "#F0FFFF", "Beige", "#F5F5DC", "Bisque", "#FFE4C4", "Black", "#000000", "BlanchedAlmond", "#FFEBCD", "Blue", "#0000FF", "BlueViolet", "#8A2BE2", "Brown", "#A52A2A", "BurlyWood", "#DEB887", "CadetBlue", "#5F9EA0", "Chartreuse", "#7FFF00", "Chocolate", "#D2691E", "Coral", "#FF7F50", "CornflowerBlue", "#6495ED", "Cornsilk", "#FFF8DC", "Crimson", "#DC143C", "Cyan", "#00FFFF", "DarkBlue", "#00008B", "DarkCyan", "#008B8B", "DarkGoldenRod", "#B8860B", "DarkGray", "#A9A9A9", "DarkGrey", "#A9A9A9", "DarkGreen", "#006400", "DarkKhaki", "#BDB76B", "DarkMagenta", "#8B008B", "DarkOliveGreen", "#556B2F", "Darkorange", "#FF8C00", "DarkOrchid", "#9932CC", "DarkRed", "#8B0000", "DarkSalmon", "#E9967A", "DarkSeaGreen", "#8FBC8F", "DarkSlateBlue", "#483D8B", "DarkSlateGray", "#2F4F4F", "DarkSlateGrey", "#2F4F4F", "DarkTurquoise", "#00CED1", "DarkViolet", "#9400D3", "DeepPink", "#FF1493", "DeepSkyBlue", "#00BFFF", "DimGray", "#696969", "DimGrey", "#696969", "DodgerBlue", "#1E90FF", "FireBrick", "#B22222", "FloralWhite", "#FFFAF0", "ForestGreen", "#228B22", "Fuchsia", "#FF00FF", "Gainsboro", "#DCDCDC", "GhostWhite", "#F8F8FF", "Gold", "#FFD700", "GoldenRod", "#DAA520", "Gray", "#808080", "Grey", "#808080", "Green", "#008000", "GreenYellow", "#ADFF2F", "HoneyDew", "#F0FFF0", "HotPink", "#FF69B4", "IndianRed", "#CD5C5C", "Indigo", "#4B0082", "Ivory", "#FFFFF0", "Khaki", "#F0E68C", "Lavender", "#E6E6FA", "LavenderBlush", "#FFF0F5", "LawnGreen", "#7CFC00", "LemonChiffon", "#FFFACD", "LightBlue", "#ADD8E6", "LightCoral", "#F08080", "LightCyan", "#E0FFFF", "LightGoldenRodYellow", "#FAFAD2", "LightGray", "#D3D3D3", "LightGrey", "#D3D3D3", "LightGreen", "#90EE90", "LightPink", "#FFB6C1", "LightSalmon", "#FFA07A", "LightSeaGreen", "#20B2AA", "LightSkyBlue", "#87CEFA", "LightSlateGray", "#778899", "LightSlateGrey", "#778899", "LightSteelBlue", "#B0C4DE", "LightYellow", "#FFFFE0", "Lime", "#00FF00", "LimeGreen", "#32CD32", "Linen", "#FAF0E6", "Magenta", "#FF00FF", "Maroon", "#800000", "MediumAquaMarine", "#66CDAA", "MediumBlue", "#0000CD", "MediumOrchid", "#BA55D3", "MediumPurple", "#9370D8", "MediumSeaGreen", "#3CB371", "MediumSlateBlue", "#7B68EE", "MediumSpringGreen", "#00FA9A", "MediumTurquoise", "#48D1CC", "MediumVioletRed", "#C71585", "MidnightBlue", "#191970", "MintCream", "#F5FFFA", "MistyRose", "#FFE4E1", "Moccasin", "#FFE4B5", "NavajoWhite", "#FFDEAD", "Navy", "#000080", "OldLace", "#FDF5E6", "Olive", "#808000", "OliveDrab", "#6B8E23", "Orange", "#FFA500", "OrangeRed", "#FF4500", "Orchid", "#DA70D6", "PaleGoldenRod", "#EEE8AA", "PaleGreen", "#98FB98", "PaleTurquoise", "#AFEEEE", "PaleVioletRed", "#D87093", "PapayaWhip", "#FFEFD5", "PeachPuff", "#FFDAB9", "Peru", "#CD853F", "Pink", "#FFC0CB", "Plum", "#DDA0DD", "PowderBlue", "#B0E0E6", "Purple", "#800080", "Red", "#FF0000", "RosyBrown", "#BC8F8F", "RoyalBlue", "#4169E1", "SaddleBrown", "#8B4513", "Salmon", "#FA8072", "SandyBrown", "#F4A460", "SeaGreen", "#2E8B57", "SeaShell", "#FFF5EE", "Sienna", "#A0522D", "Silver", "#C0C0C0", "SkyBlue", "#87CEEB", "SlateBlue", "#6A5ACD", "SlateGray", "#708090", "SlateGrey", "#708090", "Snow", "#FFFAFA", "SpringGreen", "#00FF7F", "SteelBlue", "#4682B4", "Tan", "#D2B48C", "Teal", "#008080", "Thistle", "#D8BFD8", "Tomato", "#FF6347", "Turquoise", "#40E0D0", "Violet", "#EE82EE", "Wheat", "#F5DEB3", "White", "#FFFFFF", "WhiteSmoke", "#F5F5F5", "Yellow", "#FFFF00", "YellowGreen", "#9ACD32" ) }
gpl-3.0
f55b2a91c641bf730974aec758e2e1dd
36.927203
144
0.507021
3.320698
false
false
false
false
tokenbrowser/token-android-client
app/src/main/java/com/toshi/view/custom/ChatSearchView.kt
1
2092
/* * Copyright (c) 2017. Toshi Inc * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.toshi.view.custom import android.content.Context import android.support.v7.widget.LinearLayoutManager import android.util.AttributeSet import android.widget.FrameLayout import com.toshi.R import com.toshi.extensions.addHorizontalLineDivider import com.toshi.model.local.User import com.toshi.view.adapter.UserAdapter import kotlinx.android.synthetic.main.view_chat_search.view.searchList class ChatSearchView : FrameLayout { constructor(context: Context) : super(context) { init() } constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) { init() } constructor(context: Context, attrs: AttributeSet?, defStyle: Int) : super(context, attrs, defStyle) { init() } private lateinit var userAdapter: UserAdapter var onUserClickListener: ((User) -> Unit)? = null private fun init() { inflate(context, R.layout.view_chat_search, this) initRecyclerView() } private fun initRecyclerView() { userAdapter = UserAdapter( onItemClickListener = { onUserClickListener?.invoke(it) } ) searchList.apply { adapter = userAdapter layoutManager = LinearLayoutManager(context) addHorizontalLineDivider() } } fun setUsers(users: List<User>) = userAdapter.setUsers(users) }
gpl-3.0
9dbbea90bf7d62b7c8b7b6b70dd0549c
33.311475
106
0.693595
4.278119
false
false
false
false
pdvrieze/ProcessManager
PE-common/src/commonMain/kotlin/nl/adaptivity/process/processModel/XmlResultType.kt
1
5338
/* * Copyright (c) 2018. * * This file is part of ProcessManager. * * ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the * GNU Lesser General Public License as published by the Free Software Foundation. * * ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not, * see <http://www.gnu.org/licenses/>. */ @file:Suppress("EXPERIMENTAL_API_USAGE") package nl.adaptivity.process.processModel import kotlinx.serialization.Serializer import kotlinx.serialization.Serializable import kotlinx.serialization.descriptors.buildClassSerialDescriptor import kotlinx.serialization.descriptors.element import kotlinx.serialization.encoding.Decoder import kotlinx.serialization.encoding.Encoder import nl.adaptivity.process.ProcessConsts.Engine import nl.adaptivity.util.multiplatform.toCharArray import nl.adaptivity.xmlutil.* import nl.adaptivity.xmlutil.serialization.XML import nl.adaptivity.xmlutil.serialization.XmlSerialName @Serializable(XmlResultType.Companion::class) class XmlResultType : XPathHolder, IPlatformXmlResultType { override val bodyStreamReader: XmlReader get() = getXmlReader() constructor( name: String?, path: String? = null, content: CharArray? = null, originalNSContext: Iterable<Namespace> = emptyList() ) : super(name, path, content, originalNSContext) constructor( name: String?, path: String? = null, content: CharSequence?, nsContext: Iterable<Namespace> = emptyList() ) : this(name, path, content?.toCharArray(), nsContext) override fun serializeStartElement(out: XmlWriter) { out.smartStartTag(ELEMENTNAME) } override fun serializeEndElement(out: XmlWriter) { out.endTag(ELEMENTNAME) } override fun serialize(out: XmlWriter) { XML { autoPolymorphic = true }.encodeToWriter(out, Companion, this) } override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || this::class != other::class) return false if (!super.equals(other)) return false return true } override fun hashCode(): Int { return super.hashCode() } override fun toString(): String { return "XmlResultType(content=$contentString, namespaces=(${originalNSContext.joinToString()}), name=$name, path=${getPath()})" } @ProcessModelDSL class Builder constructor( var name: String? = null, var path: String? = null, var content: CharArray? = CharArray(0), nsContext: Iterable<Namespace> = emptyList(), ) { val nsContext = nsContext.toMutableList() constructor(orig: IXmlResultType) : this(orig.name, orig.path, orig.content?.copyOf(), orig.originalNSContext) fun build(): XmlResultType { return XmlResultType(name, path, content, nsContext) } } /** Dummy serializer that is just used to get the annotations on the type. */ @Serializable @XmlSerialName(value = XmlResultType.ELEMENTLOCALNAME, namespace = Engine.NAMESPACE, prefix = Engine.NSPREFIX) private class XmlResultTypeAnnotationHelper {} companion object : XPathHolderSerializer<XmlResultType>() { override val descriptor = buildClassSerialDescriptor("XmlResultType") { annotations = XmlResultTypeAnnotationHelper.serializer().descriptor.annotations element<String>("name") element<String>("xpath") element<String>("namespaces") element<String>("content") } @kotlin.jvm.JvmStatic fun deserialize(reader: XmlReader): XmlResultType { return XML {autoPolymorphic=true }.decodeFromReader(this, reader) } const val ELEMENTLOCALNAME = "result" private val ELEMENTNAME = QName( Engine.NAMESPACE, ELEMENTLOCALNAME, Engine.NSPREFIX ) @Deprecated( "Use normal factory method", ReplaceWith("XmlResultType(import)", "nl.adaptivity.process.processModel.XmlResultType") ) operator fun get(import: IXmlResultType) = XmlResultType(import) override fun deserialize(decoder: Decoder): XmlResultType { val data = PathHolderData(this) data.deserialize(descriptor, decoder, XmlResultType) return XmlResultType(data.name, data.path, data.content, data.namespaces) } override fun serialize(encoder: Encoder, value: XmlResultType) { serialize(descriptor, encoder, value) } } } fun XmlResultType(import: IXmlResultType): XmlResultType { if (import is XmlResultType) { return import } val originalNSContext: Iterable<Namespace> = import.originalNSContext return XmlResultType( import.getName(), import.getPath(), content = null, originalNSContext = originalNSContext ) }
lgpl-3.0
b16c810c1a839d75d9686e2da10e3ff7
34.586667
135
0.677969
4.93802
false
false
false
false
wleroux/fracturedskies
src/main/kotlin/com/fracturedskies/render/common/shaders/ShaderProgram.kt
1
1433
package com.fracturedskies.render.common.shaders import org.lwjgl.opengl.GL11.GL_TRUE import org.lwjgl.opengl.GL20.* abstract class ShaderProgram(vertexShaderSource: String, fragmentShaderSource: String) { val id = glCreateProgram() init { val vertexShaderId = compileShader(GL_VERTEX_SHADER, vertexShaderSource) val fragmentShaderId = compileShader(GL_FRAGMENT_SHADER, fragmentShaderSource) glAttachShader(id, vertexShaderId) glAttachShader(id, fragmentShaderId) glLinkProgram(id) val success = glGetProgrami(id, GL_LINK_STATUS) if (success != GL_TRUE) { val errorMessage = glGetProgramInfoLog(id) throw RuntimeException("Could not link program: $errorMessage") } glDeleteShader(vertexShaderId) glDeleteShader(fragmentShaderId) } private fun compileShader(type: Int, source: String): Int { val shaderId = glCreateShader(type) glShaderSource(shaderId, source) glCompileShader(shaderId) val success = glGetShaderi(shaderId, GL_COMPILE_STATUS) if (success != GL_TRUE) { val errorMessage = glGetShaderInfoLog(shaderId) throw RuntimeException("Could not compile shader: $errorMessage\n$source") } return shaderId } inline fun bind(block: ()->Unit) { glUseProgram(id) block.invoke() glUseProgram(0) } fun close() { glDeleteProgram(id) } override fun toString(): String = this.javaClass.simpleName }
unlicense
049e04eb26a841e89c01c8d1d7ef5003
27.098039
88
0.722959
4.355623
false
false
false
false
SchoolPower/SchoolPower-Android
app/src/main/java/com/carbonylgroup/schoolpower/fragments/CourseDetailFragment.kt
1
3831
/** * Copyright (C) 2019 SchoolPower Studio */ package com.carbonylgroup.schoolpower.fragments import android.os.Bundle import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.animation.Animation import android.view.animation.AnimationUtils import android.widget.TextView import com.carbonylgroup.schoolpower.R import com.carbonylgroup.schoolpower.activities.MainActivity import com.carbonylgroup.schoolpower.adapter.CourseDetailAdapter import com.carbonylgroup.schoolpower.data.AssignmentItem import com.carbonylgroup.schoolpower.data.Subject import com.carbonylgroup.schoolpower.transition.TransitionHelper import com.carbonylgroup.schoolpower.utils.Utils class CourseDetailFragment : TransitionHelper.BaseFragment() { private lateinit var utils: Utils private var offset_up_from_bottom: Animation? = null private var dataList: List<Subject>? = null override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater.inflate(R.layout.course_detail_view_content, container, false) initValue(view) initAnim() return view } private fun initValue(view: View) { utils = Utils(activity!!) MainActivity.of(activity).presentFragment = 1 MainActivity.of(activity).setToolBarTitle("") MainActivity.of(activity).expandToolBar(true, true) MainActivity.of(activity).hideToolBarItems(true) MainActivity.of(activity).hideCourseDetailBarItems(false) val transformedPosition = this.arguments!!.getInt("transformedPosition", -1) val itemToPresent = MainActivity.of(activity).subjectTransporter if (transformedPosition != -1 && itemToPresent != null) { val courseDetailRecycler = view.findViewById<RecyclerView>(R.id.course_detail_recycler) val period = utils.getLatestTermGrade(itemToPresent) dataList = utils.getFilteredSubjects(MainActivity.of(activity).subjects!!) MainActivity.of(activity).setToolBarColor(utils.getColorByLetterGrade(period?.letter ?: "--"), true) view.findViewById<View>(R.id.detail_view_header).setBackgroundColor(utils.getColorByLetterGrade(period?.letter ?: "--")) view.findViewById<View>(R.id.detail_view_header).setOnClickListener { MainActivity.of(activity).expandToolBar(true, true) courseDetailRecycler.smoothScrollToPosition(0) } view.findViewById<TextView>(R.id.detail_subject_title_tv).text = itemToPresent.name courseDetailRecycler.layoutManager = LinearLayoutManager( activity, LinearLayoutManager.VERTICAL, false ) // Init adapter val subject = dataList!![transformedPosition] val termsList = ArrayList<String>() val allTerm = getString(R.string.all_terms) termsList.addAll(Utils.sortTerm(subject.grades.keys.map { it })) termsList.add(0, allTerm) courseDetailRecycler.adapter = CourseDetailAdapter(context!!, subject, true, termsList, fun(assignments:List<AssignmentItem>, filter:String):List<AssignmentItem>{ return if (filter == allTerm) { assignments } else { assignments.filter { it.terms.contains(filter) } } } ) } } private fun initAnim() { offset_up_from_bottom = AnimationUtils.loadAnimation(activity, R.anim.offset_up_from_bottom) } }
gpl-3.0
5736d2a0a2d4443a1532ac10d680b406
40.641304
132
0.681284
4.837121
false
false
false
false
matkoniecz/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/edithistory/UndoDialog.kt
1
7288
package de.westnordost.streetcomplete.edithistory import android.content.Context import android.os.Bundle import android.text.Html import android.text.format.DateUtils import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.ViewGroup.LayoutParams.MATCH_PARENT import android.view.ViewGroup.LayoutParams.WRAP_CONTENT import android.widget.TextView import androidx.appcompat.app.AlertDialog import de.westnordost.osmfeatures.FeatureDictionary import de.westnordost.streetcomplete.Injector import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.data.edithistory.Edit import de.westnordost.streetcomplete.data.edithistory.EditHistoryController import de.westnordost.streetcomplete.data.edithistory.icon import de.westnordost.streetcomplete.data.edithistory.overlayIcon import de.westnordost.streetcomplete.data.osm.edits.ElementEdit import de.westnordost.streetcomplete.data.osm.edits.MapDataWithEditsSource import de.westnordost.streetcomplete.data.osm.edits.delete.DeletePoiNodeAction import de.westnordost.streetcomplete.data.osm.edits.split_way.SplitWayAction import de.westnordost.streetcomplete.data.osm.edits.update_tags.* import de.westnordost.streetcomplete.data.osm.mapdata.Element import de.westnordost.streetcomplete.data.osm.osmquests.OsmQuestHidden import de.westnordost.streetcomplete.data.osmnotes.edits.NoteEdit import de.westnordost.streetcomplete.data.osmnotes.edits.NoteEditAction.* import de.westnordost.streetcomplete.data.osmnotes.notequests.OsmNoteQuestHidden import de.westnordost.streetcomplete.data.quest.QuestType import de.westnordost.streetcomplete.databinding.DialogUndoBinding import de.westnordost.streetcomplete.quests.getHtmlQuestTitle import de.westnordost.streetcomplete.view.CharSequenceText import de.westnordost.streetcomplete.view.ResText import de.westnordost.streetcomplete.view.Text import de.westnordost.streetcomplete.view.setText import kotlinx.coroutines.* import org.sufficientlysecure.htmltextview.HtmlTextView import java.util.MissingFormatArgumentException import java.util.concurrent.FutureTask import javax.inject.Inject class UndoDialog( context: Context, private val edit: Edit ) : AlertDialog(context, R.style.Theme_Bubble_Dialog) { @Inject internal lateinit var mapDataSource: MapDataWithEditsSource @Inject internal lateinit var featureDictionaryFutureTask: FutureTask<FeatureDictionary> @Inject internal lateinit var editHistoryController: EditHistoryController private val binding = DialogUndoBinding.inflate(LayoutInflater.from(context)) private val scope = CoroutineScope(Dispatchers.Main) init { Injector.applicationComponent.inject(this) binding.icon.setImageResource(edit.icon) val overlayResId = edit.overlayIcon if (overlayResId != 0) binding.overlayIcon.setImageResource(overlayResId) binding.createdTimeText.text = DateUtils.getRelativeTimeSpanString(edit.createdTimestamp, System.currentTimeMillis(), DateUtils.MINUTE_IN_MILLIS) binding.descriptionContainer.addView(edit.descriptionView) setTitle(R.string.undo_confirm_title2) setView(binding.root) setButton(BUTTON_POSITIVE, context.getText(R.string.undo_confirm_positive), null) { _, _ -> scope.launch(Dispatchers.IO) { editHistoryController.undo(edit) } } setButton(BUTTON_NEGATIVE, context.getText(R.string.undo_confirm_negative), null, null) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) scope.launch { binding.titleText.text = edit.getTitle() } } override fun dismiss() { super.dismiss() scope.cancel() } suspend fun Edit.getTitle(): CharSequence = when(this) { is ElementEdit -> { getQuestTitle(questType, originalElement) } is NoteEdit -> { context.resources.getText(when(action) { CREATE -> R.string.created_note_action_title COMMENT -> R.string.commented_note_action_title }) } is OsmQuestHidden -> { val element = withContext(Dispatchers.IO) { mapDataSource.get(elementType, elementId) } getQuestTitle(questType, element) } is OsmNoteQuestHidden -> { context.resources.getText(R.string.quest_noteDiscussion_title) } else -> throw IllegalArgumentException() } private val Edit.descriptionView: View get() = when(this) { is ElementEdit -> { when(action) { is UpdateElementTagsAction -> createListOfTagUpdates(action.changes.changes) is DeletePoiNodeAction -> createTextView(ResText(R.string.deleted_poi_action_description)) is SplitWayAction -> createTextView(ResText(R.string.split_way_action_description)) else -> throw IllegalArgumentException() } } is NoteEdit -> createTextView(text?.let { CharSequenceText(it) }) is OsmQuestHidden -> createTextView(ResText(R.string.hid_action_description)) is OsmNoteQuestHidden -> createTextView(ResText(R.string.hid_action_description)) else -> throw IllegalArgumentException() } private fun getQuestTitle(questType: QuestType<*>, element: Element?): CharSequence = try { context.resources.getHtmlQuestTitle(questType, element, featureDictionaryFutureTask) } catch (e: MissingFormatArgumentException) { /* The exception happens when the number of format strings in the quest title * differs from what can be "filled" by getHtmlQuestTitle. When does this happen? * It happens the element is null or otherwise is not at all what is expected by * that quest type. * So, this is the fallback for that case */ context.resources.getString(questType.title, *Array(10){"…"}) } private fun createTextView(text: Text?): TextView { val txt = TextView(context) txt.layoutParams = ViewGroup.LayoutParams(MATCH_PARENT, WRAP_CONTENT) txt.setText(text) return txt } private fun createListOfTagUpdates(changes: Collection<StringMapEntryChange>): HtmlTextView { val txt = HtmlTextView(context) txt.layoutParams = ViewGroup.LayoutParams(MATCH_PARENT, WRAP_CONTENT) txt.setHtml(changes.joinToString(separator = "", prefix = "<ul>", postfix = "</ul>") { change -> "<li>" + context.resources.getString( change.titleResId, "<tt>"+Html.escapeHtml(change.tagString)+"</tt>" ) + "</li>" }) return txt } } private val StringMapEntryChange.tagString: String get() = when(this) { is StringMapEntryAdd -> "$key = $value" is StringMapEntryModify -> "$key = $value" is StringMapEntryDelete -> "$key = $valueBefore" } private val StringMapEntryChange.titleResId: Int get() = when(this) { is StringMapEntryAdd -> R.string.added_tag_action_title is StringMapEntryModify -> R.string.changed_tag_action_title is StringMapEntryDelete -> R.string.removed_tag_action_title }
gpl-3.0
ac5e10fdb15255f1c259558bd1c27c16
42.628743
126
0.721658
4.585274
false
false
false
false
ccomeaux/boardgamegeek4android
app/src/main/java/com/boardgamegeek/entities/GeekListItemEntity.kt
1
2570
package com.boardgamegeek.entities import android.content.Context import android.os.Parcelable import com.boardgamegeek.R import com.boardgamegeek.provider.BggContract import kotlinx.parcelize.IgnoredOnParcel import kotlinx.parcelize.Parcelize @Parcelize data class GeekListItemEntity( val id: Long = BggContract.INVALID_ID.toLong(), val objectId: Int = BggContract.INVALID_ID, val objectName: String = "", private val objectType: String = "", private val subtype: String = "", val imageId: Int = 0, val username: String = "", val body: String = "", val numberOfThumbs: Int = 0, val postDateTime: Long = 0L, val editDateTime: Long = 0L, val comments: List<GeekListCommentEntity> = emptyList() ) : Parcelable { @IgnoredOnParcel val isBoardGame: Boolean = "thing" == objectType @IgnoredOnParcel val objectUrl: String = when { subtype.isNotBlank() -> "https://www.boardgamegeek.com/$subtype/$objectId" objectType.isNotBlank() -> "https://www.boardgamegeek.com/$objectType/$objectId" else -> "" } fun objectTypeDescription(context: Context): String { val objectTypeResId = getObjectTypeResId() return if (objectTypeResId == INVALID_OBJECT_TYPE_RES_ID) "" else context.getString(objectTypeResId) } private fun getObjectTypeResId(): Int { return when (objectType) { "thing" -> { when (subtype) { "boardgame" -> R.string.title_board_game "boardgameaccessory" -> R.string.title_board_game_accessory else -> R.string.title_thing } } "company" -> { when (subtype) { "boardgamepublisher" -> R.string.title_board_game_publisher else -> R.string.title_company } } "person" -> { when (subtype) { "boardgamedesigner" -> R.string.title_board_game_designer else -> R.string.title_person } } "family" -> { when (subtype) { "boardgamefamily" -> R.string.title_board_game_family else -> R.string.title_family } } "filepage" -> R.string.title_file "geeklist" -> R.string.title_geeklist else -> INVALID_OBJECT_TYPE_RES_ID } } companion object { const val INVALID_OBJECT_TYPE_RES_ID = 0 } }
gpl-3.0
09496ef70da6918082ede84101f94689
32.815789
108
0.570039
4.477352
false
false
false
false
ageery/kwicket
kwicket-wicket-bootstrap-core/src/main/kotlin/org/kwicket/agilecoders/wicket/core/ajax/markup/html/bootstrap/navbar/KNavbar.kt
1
1536
package org.kwicket.agilecoders.wicket.core.ajax.markup.html.bootstrap.navbar import de.agilecoders.wicket.core.markup.html.bootstrap.navbar.INavbarComponent import de.agilecoders.wicket.core.markup.html.bootstrap.navbar.Navbar import org.apache.wicket.behavior.Behavior import org.apache.wicket.model.IModel import org.kwicket.component.init open class KNavbar( id: String, model: IModel<*>? = null, position: Navbar.Position? = null, inverted: Boolean? = null, brandName: IModel<String>? = null, outputMarkupId: Boolean? = null, outputMarkupPlaceholderTag: Boolean? = null, visible: Boolean? = null, enabled: Boolean? = null, escapeModelStrings: Boolean? = null, renderBodyOnly: Boolean? = null, fluid: Boolean? = null, components: ((String) -> List<List<INavbarComponent>>)? = null, behaviors: List<Behavior>? = null ) : Navbar(id, model) { init { init( outputMarkupId = outputMarkupId, outputMarkupPlaceholderTag = outputMarkupPlaceholderTag, visible = visible, enabled = enabled, escapeModelStrings = escapeModelStrings, renderBodyOnly = renderBodyOnly, behaviors = behaviors ) position?.let { this.position = it } inverted?.let { this.setInverted(it) } brandName?.let { this.setBrandName(brandName) } fluid?.let { if (it) this.fluid() } components?.let { it.invoke(Navbar.componentId()).forEach { addComponents(it) } } } }
apache-2.0
bd2aa10f1850698b361ca3842b1a8d64
34.744186
89
0.666016
4.278552
false
false
false
false
SimonVT/cathode
cathode-sync/src/main/java/net/simonvt/cathode/actions/movies/SyncTrendingMovies.kt
1
3143
/* * Copyright (C) 2013 Simon Vig Therkildsen * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.simonvt.cathode.actions.movies import android.content.ContentProviderOperation import android.content.ContentValues import android.content.Context import net.simonvt.cathode.actions.CallAction import net.simonvt.cathode.api.entity.TrendingItem import net.simonvt.cathode.api.enumeration.Extended import net.simonvt.cathode.api.service.MoviesService import net.simonvt.cathode.common.database.forEach import net.simonvt.cathode.common.database.getLong import net.simonvt.cathode.provider.DatabaseContract.MovieColumns import net.simonvt.cathode.provider.ProviderSchematic.Movies import net.simonvt.cathode.provider.batch import net.simonvt.cathode.provider.helper.MovieDatabaseHelper import net.simonvt.cathode.provider.query import net.simonvt.cathode.settings.SuggestionsTimestamps import retrofit2.Call import javax.inject.Inject class SyncTrendingMovies @Inject constructor( private val context: Context, private val movieHelper: MovieDatabaseHelper, private val moviesService: MoviesService ) : CallAction<Unit, List<TrendingItem>>() { override fun key(params: Unit): String = "SyncTrendingMovies" override fun getCall(params: Unit): Call<List<TrendingItem>> = moviesService.getTrendingMovies(LIMIT, Extended.FULL) override suspend fun handleResponse(params: Unit, response: List<TrendingItem>) { val ops = arrayListOf<ContentProviderOperation>() val trendingIds = mutableListOf<Long>() val localMovies = context.contentResolver.query(Movies.TRENDING, arrayOf(MovieColumns.ID)) localMovies.forEach { cursor -> trendingIds.add(cursor.getLong(MovieColumns.ID)) } localMovies.close() response.forEachIndexed { index, trendingItem -> val movie = trendingItem.movie!! val movieId = movieHelper.partialUpdate(movie) trendingIds.remove(movieId) val values = ContentValues() values.put(MovieColumns.TRENDING_INDEX, index) val op = ContentProviderOperation.newUpdate(Movies.withId(movieId)).withValues(values).build() ops.add(op) } for (movieId in trendingIds) { val values = ContentValues() values.put(MovieColumns.TRENDING_INDEX, -1) val op = ContentProviderOperation.newUpdate(Movies.withId(movieId)).withValues(values).build() ops.add(op) } context.contentResolver.batch(ops) SuggestionsTimestamps.get(context) .edit() .putLong(SuggestionsTimestamps.MOVIES_TRENDING, System.currentTimeMillis()) .apply() } companion object { private const val LIMIT = 50 } }
apache-2.0
34a35a7901e3fb4a485e397908b909d6
36.416667
100
0.766147
4.311385
false
false
false
false
ziggy42/Blum
app/src/main/java/com/andreapivetta/blu/common/utils/Extensions.kt
1
4181
package com.andreapivetta.blu.common.utils import android.app.Activity import android.app.DownloadManager import android.content.Context import android.content.Intent import android.net.Uri import android.support.annotation.DrawableRes import android.support.annotation.LayoutRes import android.support.customtabs.CustomTabsIntent import android.support.v4.app.Fragment import android.support.v7.app.AppCompatActivity import android.view.View import android.widget.ImageView import android.widget.Toast import com.andreapivetta.blu.R import com.andreapivetta.blu.ui.custom.Theme import com.andreapivetta.blu.ui.hashtag.HashtagActivity import com.andreapivetta.blu.ui.profile.UserActivity import com.bumptech.glide.Glide import com.luseen.autolinklibrary.AutoLinkMode import com.luseen.autolinklibrary.AutoLinkTextView /** * Created by andrea on 27/09/16. */ fun View.visible(show: Boolean = true) { this.visibility = if (show) View.VISIBLE else View.GONE } fun ImageView.loadUri(uri: Uri?, @DrawableRes placeholder: Int = R.drawable.placeholder) { Glide.with(context).load(uri).placeholder(placeholder).into(this) } fun ImageView.loadUrl(url: CharSequence?, @DrawableRes placeholder: Int = R.drawable.placeholder) { Glide.with(context).load(url).placeholder(placeholder).into(this) } fun ImageView.loadUrlWithoutPlaceholder(url: CharSequence?) { Glide.with(context).load(url).into(this) } fun ImageView.loadUrlCenterCrop(url: CharSequence?, @DrawableRes placeholder: Int = R.drawable.placeholder) { Glide.with(context).load(url).placeholder(placeholder).centerCrop().into(this) } fun ImageView.loadAvatar(url: CharSequence?) { // TODO placeholder Glide.with(context).load(url).dontAnimate().into(this) } fun AutoLinkTextView.setupText(text: String) { addAutoLinkMode(AutoLinkMode.MODE_HASHTAG, AutoLinkMode.MODE_URL, AutoLinkMode.MODE_MENTION) setHashtagModeColor(Theme.getColorPrimary(context)) setUrlModeColor(Theme.getColorPrimary(context)) setMentionModeColor(Theme.getColorPrimary(context)) setAutoLinkText(text) setAutoLinkOnClickListener { mode, text -> when (mode) { AutoLinkMode.MODE_HASHTAG -> HashtagActivity.launch(context, text) AutoLinkMode.MODE_MENTION -> UserActivity.launch(context, text) AutoLinkMode.MODE_URL -> openUrl(context as Activity, text) else -> throw UnsupportedOperationException("No handlers for mode $mode") } } } fun AppCompatActivity.pushFragment(@LayoutRes containerViewId: Int, fragment: Fragment) { supportFragmentManager.beginTransaction().replace(containerViewId, fragment).commit() } fun openUrl(activity: Activity, url: String) { try { CustomTabsIntent.Builder() .setToolbarColor(Theme.getColorPrimary(activity)) .setShowTitle(true) .addDefaultShareMenuItem() .build() .launchUrl(activity, Uri.parse(url.trim())) } catch (err: Exception) { Toast.makeText(activity, "You are running this app on an alien spaceship and we don't support them yet", Toast.LENGTH_SHORT).show() } } fun shareText(context: Context, text: String) { val intent = Intent(Intent.ACTION_SEND) intent.putExtra(Intent.EXTRA_TEXT, text) intent.type = "text/plain" context.startActivity(intent) } fun shareApp(context: Context) { try { context.startActivity(Intent(Intent.ACTION_VIEW, Uri .parse("market://details?id=${context.applicationContext.packageName}"))) } catch (err: Exception) { Toast.makeText(context, context.getString(R.string.missing_play_store), Toast.LENGTH_SHORT).show() } } fun download(context: Context, url: String) { val request = DownloadManager.Request(Uri.parse(url)) .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED) .setDestinationInExternalPublicDir("/Download", System.currentTimeMillis().toString()) request.allowScanningByMediaScanner() (context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager).enqueue(request) }
apache-2.0
a81cc54e408ae98f39f458c00067efc6
36.675676
109
0.734992
4.127345
false
false
false
false
nathanjent/adventofcode-rust
kotlin/src/main/kotlin/2018/Lib04.kt
1
3980
package aoc.kt.y2018; import java.time.LocalDateTime import java.util.Locale import java.time.format.DateTimeFormatter import java.time.temporal.ChronoUnit /** * Day 4. */ data class Message(val dateTime: LocalDateTime, val text: String) /** Part 1 */ fun processRepose1(input: String): String { val guardMap = makeGuardMap(input) val guardWithMostSleepTime = guardMap.map { val guardId = it.key val sleepTime = it.value.sumBy { sleepWakeTime -> ChronoUnit.MINUTES.between(sleepWakeTime.first, sleepWakeTime.second) .toInt() } Pair(guardId, sleepTime) } .maxBy { it.second }?.first val minuteGuardSleptMost = guardMap.get(guardWithMostSleepTime)?.flatMap { val sleepStart = it.first val sleepEnd = it.second val minutesSlept = mutableMapOf<Int, Long>() var timeCursor = sleepStart while (timeCursor.until(sleepEnd, ChronoUnit.MINUTES) > 0) { val minute = timeCursor.getMinute() val minuteCount = minutesSlept.getOrDefault(minute, 0) minutesSlept.put(minute, minuteCount + 1) timeCursor = timeCursor.plusMinutes(1) } minutesSlept.toList() }?.groupBy { it.first }?.map { Pair(it.key, it.value.sumBy { x -> x.second.toInt() }) }?.maxBy { it.second }?.first val output = guardWithMostSleepTime?.let { a -> minuteGuardSleptMost?.let { b -> a * b } } return output.toString() } /** Part 2 */ fun processRepose2(input: String): String { val guardMap = makeGuardMap(input) val m = guardMap.map { val minutesSlept = mutableMapOf<Int, Long>() it.value.forEach { val sleepStart = it.first val sleepEnd = it.second var timeCursor = sleepStart while (timeCursor.until(sleepEnd, ChronoUnit.MINUTES) > 0) { val minute = timeCursor.getMinute() val minuteCount = minutesSlept.getOrDefault(minute, 0) minutesSlept.put(minute, minuteCount + 1) timeCursor = timeCursor.plusMinutes(1) } } Pair(it.key, minutesSlept) } .map { val minuteSleptMost = it.second.maxBy { (_, sleptCount) -> sleptCount } Pair(it.first, minuteSleptMost) }.map { (g, m) -> Triple(g, m?.key, m?.value) }.maxBy { it.third?:-1 } val output = m?.first?.let { a -> m.second?.let { b -> a * b } } return output.toString() } private fun makeGuardMap(input: String): MutableMap<Int, MutableList<Pair<LocalDateTime, LocalDateTime>>> { val messageMatch = """(\[.*\])|([Gfw].*$)""".toRegex() val numMatch = """[0-9]+""".toRegex() val dateTimePattern = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm", Locale.ENGLISH) var messages = input.lines() .filter { !it.isEmpty() } .map { val (dateTimeStr, message) = messageMatch.findAll(it) .map { it.value } .toList() val dateTime = LocalDateTime.parse( dateTimeStr.trim { it == '[' || it == ']' }, dateTimePattern) Message(dateTime, message) } .sortedBy { it.dateTime } .toList() // Map of guards to datetime ranges val guardMap = mutableMapOf<Int, MutableList<Pair<LocalDateTime, LocalDateTime>>>() var currentGuardId = -1 var asleepStart: LocalDateTime? = null for (message in messages) { currentGuardId = numMatch.find(message.text)?.value?.toInt()?:currentGuardId if (message.text.contains("asleep")) { asleepStart = message.dateTime } if (message.text.contains("wake") && asleepStart != null) { val sleepWakeList = guardMap.getOrDefault(currentGuardId, mutableListOf()) sleepWakeList.add(Pair(asleepStart, message.dateTime)) guardMap.put(currentGuardId, sleepWakeList) } } return guardMap }
mit
1630e0ab776fdc8c641b457a043c35de
30.338583
107
0.605276
3.875365
false
false
false
false
Devexperts/usages
idea-plugin/src/main/kotlin/com/devexperts/usages/idea/UsagesViewer.kt
1
6187
/** * Copyright (C) 2017 Devexperts LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. */ package com.devexperts.usages.idea import com.devexperts.usages.api.Member import com.devexperts.usages.api.MemberUsage import com.intellij.icons.AllIcons import com.intellij.openapi.actionSystem.* import com.intellij.openapi.project.Project import com.intellij.openapi.ui.SimpleToolWindowPanel import com.intellij.openapi.wm.ToolWindow import com.intellij.openapi.wm.ToolWindowAnchor import com.intellij.openapi.wm.ToolWindowManager import com.intellij.ui.components.JBScrollPane import com.intellij.ui.content.Content import com.intellij.ui.content.ContentFactory import com.intellij.util.ui.tree.TreeUtil import javax.swing.Icon import javax.swing.JComponent import javax.swing.JPanel val USAGES_TOOL_WINDOW_TITLE = "Maven Usages" private val FIND_USAGES_ICON = AllIcons.Actions.Find // todo use custom icon: IconLoader.getIcon("/find_usages.png") /** * Shows usages in the project toolbar like standard "Find Usages" action */ class UsagesViewer(val project: Project, val member: Member, val newTab: Boolean) { private val usagesModel: UsagesTreeModel private val usagesTree: UsagesTree private val toolWindow: ToolWindow private val content: Content init { toolWindow = getOrInitToolWindow() val toolWindowPanel = SimpleToolWindowPanel(false) // Add usages tree val groupingStrategy = GroupingStrategy(arrayListOf(NodeType.ROOT, NodeType.SEARCHED_PACKAGE, NodeType.SEARCHED_CLASS, NodeType.SEARCHED_CLASS_MEMBER, NodeType.ARTIFACT, NodeType.USAGE_KIND, NodeType.TARGET_PACKAGE, NodeType.TARGET_CLASS, NodeType.TARGET_CLASS_MEMBER, NodeType.TARGET_LINE)) usagesModel = UsagesTreeModel(groupingStrategy) usagesTree = UsagesTree(usagesModel) toolWindowPanel.setContent(JBScrollPane(usagesTree)) // Add toolbar toolWindowPanel.setToolbar(createToolbar(toolWindowPanel)) // Create content and add it to the window val contentTitle = "of ${member.simpleName()}" // "Maven Usages " is presented as toolWindow title content = ContentFactory.SERVICE.getInstance().createContent(toolWindowPanel, contentTitle, true) toolWindow.contentManager.addContent(content) // Show the content // todo process newTab parameter toolWindow.contentManager.setSelectedContent(content) if (!toolWindow.isActive) toolWindow.activate {} toolWindow.show {} } fun addUsages(newUsages: List<MemberUsage>) { val firstAdd = usagesModel.rootNode.usageCount == 0 usagesModel.addUsages(newUsages) if (firstAdd) { println("FIRST!!!!") val firstUsagePath = usagesTree.expandFirstUsage() usagesTree.fireTreeWillExpand(firstUsagePath) } } private fun getOrInitToolWindow(): ToolWindow { var toolWindow = ToolWindowManager.getInstance(project).getToolWindow(USAGES_TOOL_WINDOW_TITLE) if (toolWindow == null) { toolWindow = ToolWindowManager.getInstance(project).registerToolWindow( USAGES_TOOL_WINDOW_TITLE, true, ToolWindowAnchor.BOTTOM) toolWindow.icon = FIND_USAGES_ICON } return toolWindow } private fun createToolbar(toolWindowPanel: JPanel): JComponent { val group = DefaultActionGroup() group.add(usagesToolbarAction(icon = AllIcons.General.Settings, title = "Settings", toolWindowPanel = toolWindowPanel, shortcut = "ctrl alt shift F9") { FindUsagesRequestConfigurationDialog(project, member).show() }) group.add(usagesToolbarAction(icon = AllIcons.Actions.Rerun, title = "Rerun", toolWindowPanel = toolWindowPanel, shortcut = null) { // todo }) group.add(usagesToolbarAction(icon = AllIcons.Actions.Cancel, title = "Close", toolWindowPanel = toolWindowPanel, shortcut = "ctrl shift F4") { toolWindow.contentManager.removeContent(content, false) }) group.add(usagesToolbarAction(icon = AllIcons.Actions.Suspend, title = "Stop", toolWindowPanel = toolWindowPanel, shortcut = null) { }) group.add(usagesToolbarAction(icon = AllIcons.Actions.Expandall, title = "Expand All", toolWindowPanel = toolWindowPanel, shortcut = "ctrl UP") { TreeUtil.expandAll(usagesTree) }) group.add(usagesToolbarAction(icon = AllIcons.Actions.Collapseall, title = "Collapse All", toolWindowPanel = toolWindowPanel, shortcut = "ctrl DOWN") { TreeUtil.collapseAll(usagesTree, 3) }) return ActionManager.getInstance().createActionToolbar(ActionPlaces.TOOLBAR, group, false).component } private inline fun usagesToolbarAction(icon: Icon, title: String, toolWindowPanel: JPanel, shortcut: String?, crossinline action: (AnActionEvent) -> Unit): AnAction { return object : AnAction(title, null, icon) { init { if (shortcut != null) registerCustomShortcutSet(CustomShortcutSet.fromString(shortcut), toolWindowPanel) } override fun actionPerformed(e: AnActionEvent) = action(e) } } } class GroupingStrategy(val groupingOrder: List<NodeType>) { fun getRank(nodeType: NodeType): Int = groupingOrder.indexOf(nodeType) }
gpl-3.0
f6dd51f67ee51f7943a3d3ad2c3d1953
43.84058
116
0.692096
4.75192
false
false
false
false